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.

UI updates

tilakpatel224a0281d6664f
diff --git a/fincept-terminal-desktop/bun.lock b/fincept-terminal-desktop/bun.lock
index 65d87482d..49a9b7329 100644
--- a/fincept-terminal-desktop/bun.lock
+++ b/fincept-terminal-desktop/bun.lock
@@ -45,7 +45,9 @@
"@tauri-apps/plugin-sql": "^2.3.0",
"@tauri-apps/plugin-updater": "~2.9.0",
"@types/react-grid-layout": "^1.3.5",
+ "anychart": "^8.14.0",
"axios": "^1.12.2",
+ "better-sqlite3": "^12.5.0",
"ccxt": "^4.5.24",
"cheerio": "^1.1.2",
"class-variance-authority": "^0.7.1",
@@ -69,6 +71,7 @@
"otpauth": "^9.4.1",
"otplib": "^12.0.1",
"playwright": "^1.55.1",
+ "process": "^0.11.10",
"react": "^19.1.0",
"react-confetti": "^6.4.0",
"react-day-picker": "^9.11.0",
@@ -78,6 +81,7 @@
"react-markdown": "^10.1.0",
"react-router-dom": "^7.9.6",
"reactflow": "^11.11.4",
+ "readable-stream": "^4.7.0",
"recharts": "^2.15.4",
"remark-gfm": "^4.0.1",
"sonner": "^2.0.7",
@@ -105,15 +109,20 @@
"socks-proxy-agent": "^8.0.5",
"stream-browserify": "^3.0.0",
"stream-http": "^3.2.0",
+ "string_decoder": "^1.3.0",
"ts-node": "^10.9.2",
"tw-animate-css": "^1.4.0",
"typescript": "~5.8.3",
"url": "^0.11.4",
"util": "^0.12.5",
"vite": "^7.0.4",
+ "vite-plugin-node-polyfills": "^0.24.0",
},
},
},
+ "overrides": {
+ "readable-stream": "4.7.0",
+ },
"packages": {
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", "abort-controller": "^3.0.0", "agentkeepalive": "^4.2.1", "form-data-encoder": "1.7.2", "formdata-node": "^4.3.2", "node-fetch": "^2.6.7" } }, "sha512-IjLt0gd3L4jlOfilxVXTifn42FnVffMgDC04RJK1KDZpmkBWLv0XC92MVVmkxrFZNS/7l3xWgP/I3nqtX1sQHw=="],
@@ -425,6 +434,10 @@
"@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA=="],
+ "@rollup/plugin-inject": ["@rollup/[email protected]", "", { "dependencies": { "@rollup/pluginutils": "^5.0.1", "estree-walker": "^2.0.2", "magic-string": "^0.30.3" }, "peerDependencies": { "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "optionalPeers": ["rollup"] }, "sha512-2+DEJbNBoPROPkgTDNe8/1YXWcqxbN5DTjASVIOx8HS+pITXushyNiBV56RB08zuptzz8gT3YfkqriTBVycepg=="],
+
+ "@rollup/pluginutils": ["@rollup/[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-walker": "^2.0.2", "picomatch": "^4.0.2" }, "peerDependencies": { "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "optionalPeers": ["rollup"] }, "sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q=="],
+
"@rollup/rollup-android-arm-eabi": ["@rollup/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-mRSi+4cBjrRLoaal2PnqH82Wqyb+d3HsPUN/W+WslCXsZsyHa9ZeQQX/pQsZaVIWDkPcpV6jJ+3KLbTbgnwv8w=="],
"@rollup/rollup-android-arm64": ["@rollup/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-CbDGaMpdE9sh7sCmTrTUyllhrg65t6SwhjlMJsLr+J8YjFuPmCEjbBSx4Z/e4SmDyH3aB5hGaJUP2ltV/vcs4w=="],
@@ -677,6 +690,8 @@
"ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
+ "anychart": ["[email protected]", "", {}, "sha512-jydxc1U74kjzatBdZpk6PoOf4yrJ87UfFCRanBGNARNMNLuzRY4aX+KPUTIBAQkyoJ4hS6oY9887HnhIP1DbLA=="],
+
"arg": ["[email protected]", "", {}, "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA=="],
"argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
@@ -685,6 +700,8 @@
"asn1.js": ["[email protected]", "", { "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0" } }, "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw=="],
+ "assert": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.2", "is-nan": "^1.3.2", "object-is": "^1.1.5", "object.assign": "^4.1.4", "util": "^0.12.5" } }, "sha512-eLHpSK/Y4nhMJ07gDaAzoX/XAKS8PSaojml3M0DM4JpV1LAi5JOJ/p6H/XWrl8L+DzVEvVCW1z3vWAaB9oTsQw=="],
+
"asynckit": ["[email protected]", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="],
"available-typed-arrays": ["[email protected]", "", { "dependencies": { "possible-typed-array-names": "^1.0.0" } }, "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ=="],
@@ -697,14 +714,22 @@
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.js" } }, "sha512-PxSsosKQjI38iXkmb3d0Y32efqyA0uW4s41u4IVBsLlWLhCiYNpH/AfNOVWRqCQBlD8TFJTz6OUWNd4DFJCnmw=="],
+ "better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-WwCZ/5Diz7rsF29o27o0Gcc1Du+l7Zsv7SYtVPG0X3G/uUI1LqdxrQI7c9Hs2FWpqXXERjW9hp6g3/tH7DlVKg=="],
+
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
+ "bindings": ["[email protected]", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="],
+
+ "bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
+
"bn.js": ["[email protected]", "", {}, "sha512-v2YAxEmKaBLahNwE1mjp4WON6huMNeuDvagFZW+ASCuA/ku0bXR9hSMw0XpiqMoA3+rmnyck/tPRSFQkoC9Cuw=="],
"boolbase": ["[email protected]", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="],
"brorand": ["[email protected]", "", {}, "sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w=="],
+ "browser-resolve": ["[email protected]", "", { "dependencies": { "resolve": "^1.17.0" } }, "sha512-7sWsQlYL2rGLy2IWm8WL8DCTJvYLc/qlOnsakDac87SOoCd16WLsaAMdCiAqsTNHIe+SXfaqyxyo6THoWqs8WQ=="],
+
"browserify-aes": ["[email protected]", "", { "dependencies": { "buffer-xor": "^1.0.3", "cipher-base": "^1.0.0", "create-hash": "^1.1.0", "evp_bytestokey": "^1.0.3", "inherits": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA=="],
"browserify-cipher": ["[email protected]", "", { "dependencies": { "browserify-aes": "^1.0.4", "browserify-des": "^1.0.0", "evp_bytestokey": "^1.0.0" } }, "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w=="],
@@ -755,6 +780,8 @@
"cheerio-select": ["[email protected]", "", { "dependencies": { "boolbase": "^1.0.0", "css-select": "^5.1.0", "css-what": "^6.1.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.0.1" } }, "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g=="],
+ "chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
+
"cipher-base": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.4", "safe-buffer": "^5.2.1", "to-buffer": "^1.2.2" } }, "sha512-Mz9QMT5fJe7bKI7MH31UilT5cEK5EHHRCccw/YRFsRY47AuNgaV6HY3rscp0/I4Q+tTW/5zoqpSeRRI54TkDWA=="],
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
@@ -775,14 +802,16 @@
"comma-separated-tokens": ["[email protected]", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],
+ "console-browserify": ["[email protected]", "", {}, "sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA=="],
+
"console-table-printer": ["[email protected]", "", { "dependencies": { "simple-wcswidth": "^1.1.2" } }, "sha512-SrhBq4hYVjLCkBVOWaTzceJalvn5K1Zq5aQA6wXC/cYjI3frKWNPEMK3sZsJfNNQApvCQmgBcc13ZKmFj8qExw=="],
+ "constants-browserify": ["[email protected]", "", {}, "sha512-xFxOwqIzR/e1k1gLiWEophSCMqXcwVHIH7akf7b/vxcUeGunlj3hvZaaqxwHsTgn+IndtkQJgSztIDWeumWJDQ=="],
+
"convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
"cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],
- "core-util-is": ["[email protected]", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="],
-
"create-ecdh": ["[email protected]", "", { "dependencies": { "bn.js": "^4.1.0", "elliptic": "^6.5.3" } }, "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A=="],
"create-hash": ["[email protected]", "", { "dependencies": { "cipher-base": "^1.0.1", "inherits": "^2.0.1", "md5.js": "^1.3.4", "ripemd160": "^2.0.1", "sha.js": "^2.4.0" } }, "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg=="],
@@ -845,12 +874,18 @@
"decode-named-character-reference": ["[email protected]", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q=="],
+ "decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
+
+ "deep-extend": ["[email protected]", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
+
"deep-is": ["[email protected]", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="],
"deepmerge": ["[email protected]", "", {}, "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="],
"define-data-property": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
+ "define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
+
"delayed-stream": ["[email protected]", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="],
"dequal": ["[email protected]", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="],
@@ -871,6 +906,8 @@
"dom-serializer": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],
+ "domain-browser": ["[email protected]", "", {}, "sha512-IGBwjF7tNk3cwypFNH/7bfzBcgSCbaMOD3GsaY1AU/JRrnHnYgEM0+9kQt52iZxjNsjBtJYtao146V+f8jFZNw=="],
+
"domelementtype": ["[email protected]", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="],
"domhandler": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0" } }, "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w=="],
@@ -897,6 +934,8 @@
"encoding-sniffer": ["[email protected]", "", { "dependencies": { "iconv-lite": "^0.6.3", "whatwg-encoding": "^3.1.1" } }, "sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw=="],
+ "end-of-stream": ["[email protected]", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
+
"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.2.0" } }, "sha512-d4lC8xfavMeBjzGr2vECC3fsGXziXZQyJxD868h2M/mBI3PwAuODxAkLkq5HYuvrPYcUtiLzsTo8U3PgX3Ocww=="],
"entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
@@ -923,6 +962,8 @@
"estree-util-is-identifier-name": ["[email protected]", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="],
+ "estree-walker": ["[email protected]", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
+
"esutils": ["[email protected]", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],
"event-target-shim": ["[email protected]", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="],
@@ -933,6 +974,8 @@
"evp_bytestokey": ["[email protected]", "", { "dependencies": { "md5.js": "^1.3.4", "safe-buffer": "^5.1.1" } }, "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA=="],
+ "expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
+
"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
"fancy-canvas": ["[email protected]", "", {}, "sha512-nifxXJ95JNLFR2NgRV4/MxVP45G9909wJTEKz5fg/TZS20JJZA6hfgRVh/bC9bwl2zBtBNcYPjiBE4njQHVBwQ=="],
@@ -945,6 +988,10 @@
"file-type": ["[email protected]", "", { "dependencies": { "readable-web-to-node-stream": "^3.0.0", "strtok3": "^6.2.4", "token-types": "^4.1.1" } }, "sha512-/yFHK0aGjFEgDJjEKP0pWCplsPFPhwyfwevf/pVxiN0tmE4L9LmwWxWukdJSHdoCli4VgQLehjJtwQBnqmsKcw=="],
+ "file-uri-to-path": ["[email protected]", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="],
+
+ "find-up": ["[email protected]", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="],
+
"flat": ["[email protected]", "", { "bin": { "flat": "cli.js" } }, "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ=="],
"follow-redirects": ["[email protected]", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="],
@@ -957,6 +1004,8 @@
"formdata-node": ["[email protected]", "", { "dependencies": { "node-domexception": "1.0.0", "web-streams-polyfill": "4.0.0-beta.3" } }, "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ=="],
+ "fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
+
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
@@ -975,6 +1024,8 @@
"get-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
+ "github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
+
"gopd": ["[email protected]", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
"graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
@@ -1031,6 +1082,8 @@
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
+ "ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
+
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
"internmap": ["[email protected]", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
@@ -1045,6 +1098,8 @@
"is-callable": ["[email protected]", "", {}, "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA=="],
+ "is-core-module": ["[email protected]", "", { "dependencies": { "hasown": "^2.0.2" } }, "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w=="],
+
"is-decimal": ["[email protected]", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="],
"is-fullwidth-code-point": ["[email protected]", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
@@ -1053,13 +1108,17 @@
"is-hexadecimal": ["[email protected]", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="],
+ "is-nan": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.0", "define-properties": "^1.1.3" } }, "sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w=="],
+
"is-plain-obj": ["[email protected]", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
"is-regex": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g=="],
"is-typed-array": ["[email protected]", "", { "dependencies": { "which-typed-array": "^1.1.16" } }, "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ=="],
- "isarray": ["[email protected]", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="],
+ "isarray": ["[email protected]", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="],
+
+ "isomorphic-timers-promises": ["[email protected]", "", {}, "sha512-u4sej9B1LPSxTGKB/HiuzvEQnXH0ECYkSVQU39koSwmFAxhlEAFl9RdTvLv4TOTQUgBS5O3O5fwUxk6byBZ+IQ=="],
"isstream": ["[email protected]", "", {}, "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g=="],
@@ -1125,6 +1184,8 @@
"lightweight-charts": ["[email protected]", "", { "dependencies": { "fancy-canvas": "2.1.0" } }, "sha512-8oQIis8jfZVfSwz8j9Z5x3O79dIRTkEYI9UY7DKtE4O3ZxlHjMK3L0+4nOVOOFq4FHI/oSIzz1RHeNImCk6/Jg=="],
+ "locate-path": ["[email protected]", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="],
+
"lodash": ["[email protected]", "", {}, "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="],
"lodash.camelcase": ["[email protected]", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="],
@@ -1257,16 +1318,24 @@
"mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="],
+ "mimic-response": ["[email protected]", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="],
+
"minimalistic-assert": ["[email protected]", "", {}, "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A=="],
"minimalistic-crypto-utils": ["[email protected]", "", {}, "sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg=="],
+ "minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
+
+ "mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
+
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"mustache": ["[email protected]", "", { "bin": { "mustache": "bin/mustache" } }, "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ=="],
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
+ "napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
+
"next-themes": ["[email protected]", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],
"nice-grpc": ["[email protected]", "", { "dependencies": { "@grpc/grpc-js": "^1.14.0", "abort-controller-x": "^0.4.0", "nice-grpc-common": "^2.0.2" } }, "sha512-GK9pKNxlvnU5FAdaw7i2FFuR9CqBspcE+if2tqnKXBcE0R8525wj4BZvfcwj7FjvqbssqKxRHt2nwedalbJlww=="],
@@ -1275,32 +1344,50 @@
"nice-grpc-common": ["[email protected]", "", { "dependencies": { "ts-error": "^1.0.6" } }, "sha512-7RNWbls5kAL1QVUOXvBsv1uO0wPQK3lHv+cY1gwkTzirnG1Nop4cBJZubpgziNbaVc/bl9QJcyvsf/NQxa3rjQ=="],
+ "node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-zsFhmbkAzwhTft6nd3VxcG0cvJsT70rL+BIGHWVq5fi6MwGrHwzqKaxXE+Hl2GmnGItnDKPPkO5/LQqjVkIdFg=="],
+
"node-domexception": ["[email protected]", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="],
"node-fetch": ["[email protected]", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
"node-releases": ["[email protected]", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
+ "node-stdlib-browser": ["[email protected]", "", { "dependencies": { "assert": "^2.0.0", "browser-resolve": "^2.0.0", "browserify-zlib": "^0.2.0", "buffer": "^5.7.1", "console-browserify": "^1.1.0", "constants-browserify": "^1.0.0", "create-require": "^1.1.1", "crypto-browserify": "^3.12.1", "domain-browser": "4.22.0", "events": "^3.0.0", "https-browserify": "^1.0.0", "isomorphic-timers-promises": "^1.0.1", "os-browserify": "^0.3.0", "path-browserify": "^1.0.1", "pkg-dir": "^5.0.0", "process": "^0.11.10", "punycode": "^1.4.1", "querystring-es3": "^0.2.1", "readable-stream": "^3.6.0", "stream-browserify": "^3.0.0", "stream-http": "^3.2.0", "string_decoder": "^1.0.0", "timers-browserify": "^2.0.4", "tty-browserify": "0.0.1", "url": "^0.11.4", "util": "^0.12.4", "vm-browserify": "^1.0.1" } }, "sha512-X75ZN8DCLftGM5iKwoYLA3rjnrAEs97MkzvSd4q2746Tgpg8b8XWiBGiBG4ZpgcAqBgtgPHTiAc8ZMCvZuikDw=="],
+
"nth-check": ["[email protected]", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="],
"object-assign": ["[email protected]", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["[email protected]", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
+ "object-is": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1" } }, "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q=="],
+
+ "object-keys": ["[email protected]", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="],
+
+ "object.assign": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0", "has-symbols": "^1.1.0", "object-keys": "^1.1.1" } }, "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw=="],
+
"ollama": ["[email protected]", "", { "dependencies": { "whatwg-fetch": "^3.6.20" } }, "sha512-KEWEhIqE5wtfzEIZbDCLH51VFZ6Z3ZSa6sIOg/E/tBV8S51flyqBOXi+bRxlOYKDf8i327zG9eSTb8IJxvm3Zg=="],
+ "once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
+
"openai": ["[email protected]", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.23.8" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-xqzHHQch5Tws5PcKR2xsZGX9xtch+JQFz5zb14dGqlshmmDAFBFEWmeIpf7wVqWV+w7Emj7jRgkNJakyKE0tYQ=="],
"openapi-types": ["[email protected]", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="],
"optionator": ["[email protected]", "", { "dependencies": { "deep-is": "~0.1.3", "fast-levenshtein": "~2.0.6", "levn": "~0.3.0", "prelude-ls": "~1.1.2", "type-check": "~0.3.2", "word-wrap": "~1.2.3" } }, "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA=="],
+ "os-browserify": ["[email protected]", "", {}, "sha512-gjcpUc3clBf9+210TRaDWbf+rZZZEshZ+DlXMRCeAjp0xhTrnQsKHypIy1J3d5hKdUzj69t708EHtU8P6bUn0A=="],
+
"otpauth": ["[email protected]", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-+iVvys36CFsyXEqfNftQm1II7SW23W1wx9RwNk0Cd97lbvorqAhBDksb/0bYry087QMxjiuBS0wokdoZ0iUeAw=="],
"otplib": ["[email protected]", "", { "dependencies": { "@otplib/core": "^12.0.1", "@otplib/preset-default": "^12.0.1", "@otplib/preset-v11": "^12.0.1" } }, "sha512-xDGvUOQjop7RDgxTQ+o4pOol0/3xSZzawTiPKRrHnQWAy0WjhNs/5HdIDJCrqC4MBynmjXgULc6YfioaxZeFgg=="],
"p-finally": ["[email protected]", "", {}, "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow=="],
+ "p-limit": ["[email protected]", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="],
+
+ "p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="],
+
"p-queue": ["[email protected]", "", { "dependencies": { "eventemitter3": "^4.0.4", "p-timeout": "^3.2.0" } }, "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ=="],
"p-retry": ["[email protected]", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="],
@@ -1319,6 +1406,12 @@
"parse5-parser-stream": ["[email protected]", "", { "dependencies": { "parse5": "^7.0.0" } }, "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow=="],
+ "path-browserify": ["[email protected]", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="],
+
+ "path-exists": ["[email protected]", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
+
+ "path-parse": ["[email protected]", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="],
+
"pbkdf2": ["[email protected]", "", { "dependencies": { "create-hash": "^1.2.0", "create-hmac": "^1.1.7", "ripemd160": "^2.0.3", "safe-buffer": "^5.2.1", "sha.js": "^2.4.12", "to-buffer": "^1.2.1" } }, "sha512-Q3CG/cYvCO1ye4QKkuH7EXxs3VC/rI1/trd+qX2+PolbaKG0H+bgcZzrTt96mMyRtejk+JMCiLUn3y29W8qmFQ=="],
"peek-readable": ["[email protected]", "", {}, "sha512-ZI3LnwUv5nOGbQzD9c2iDG6toheuXSZP5esSHBjopsXH4dg19soufvpUGA3uohi5anFtGb2lhAVdHzH6R/Evvg=="],
@@ -1327,6 +1420,8 @@
"picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
+ "pkg-dir": ["[email protected]", "", { "dependencies": { "find-up": "^5.0.0" } }, "sha512-NPE8TDbzl/3YQYY7CSS228s3g2ollTFnc+Qi3tqmqJp9Vg2ovUpixcJEo2HJScN2Ez+kEaal6y70c0ehqJBJeA=="],
+
"playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.57.0" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw=="],
"playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ=="],
@@ -1335,12 +1430,12 @@
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
+ "prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
+
"prelude-ls": ["[email protected]", "", {}, "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w=="],
"process": ["[email protected]", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
- "process-nextick-args": ["[email protected]", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
-
"prop-types": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", "react-is": "^16.13.1" } }, "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg=="],
"property-information": ["[email protected]", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="],
@@ -1353,16 +1448,22 @@
"public-encrypt": ["[email protected]", "", { "dependencies": { "bn.js": "^4.1.0", "browserify-rsa": "^4.0.0", "create-hash": "^1.1.0", "parse-asn1": "^5.0.0", "randombytes": "^2.0.1", "safe-buffer": "^5.1.2" } }, "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q=="],
+ "pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA=="],
+
"punycode": ["[email protected]", "", {}, "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ=="],
"qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w=="],
+ "querystring-es3": ["[email protected]", "", {}, "sha512-773xhDQnZBMFobEiztv8LIl70ch5MSF/jUQVlhwFyBILqq96anmoctVIYz+ZRp0qbCKATTn6ev02M3r7Ga5vqA=="],
+
"querystringify": ["[email protected]", "", {}, "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ=="],
"randombytes": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.1.0" } }, "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ=="],
"randomfill": ["[email protected]", "", { "dependencies": { "randombytes": "^2.0.5", "safe-buffer": "^5.1.0" } }, "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw=="],
+ "rc": ["[email protected]", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
+
"react": ["[email protected]", "", {}, "sha512-DGrYcCWK7tvYMnWh79yrPHt+vdx9tY+1gPZa7nJQtO/p8bLTDaHp4dzwEhQB7pZ4Xe3ok4XKuEPrVuc+wlpkmw=="],
"react-confetti": ["[email protected]", "", { "dependencies": { "tween-functions": "^1.2.0" }, "peerDependencies": { "react": "^16.3.0 || ^17.0.1 || ^18.0.0 || ^19.0.0" } }, "sha512-5MdGUcqxrTU26I2EU7ltkWPwxvucQTuqMm8dUz72z2YMqTD6s9vMcDUysk7n9jnC+lXuCPeJJ7Knf98VEYE9Rg=="],
@@ -1401,7 +1502,7 @@
"reactflow": ["[email protected]", "", { "dependencies": { "@reactflow/background": "11.3.14", "@reactflow/controls": "11.2.14", "@reactflow/core": "11.11.4", "@reactflow/minimap": "11.7.14", "@reactflow/node-resizer": "2.2.14", "@reactflow/node-toolbar": "1.3.14" }, "peerDependencies": { "react": ">=17", "react-dom": ">=17" } }, "sha512-70FOtJkUWH3BAOsN+LU9lCrKoKbtOPnz2uq0CV2PLdNSwxTXOhCbsZr50GmZ+Rtw3jx8Uv7/vBFtCGixLfd4Og=="],
- "readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
+ "readable-stream": ["[email protected]", "", { "dependencies": { "abort-controller": "^3.0.0", "buffer": "^6.0.3", "events": "^3.3.0", "process": "^0.11.10", "string_decoder": "^1.3.0" } }, "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg=="],
"readable-web-to-node-stream": ["[email protected]", "", { "dependencies": { "readable-stream": "^4.7.0" } }, "sha512-9nX56alTf5bwXQ3ZDipHJhusu9NTQJ/CVPtb/XHAJCXihZeitfJvIRS4GqQ/mfIoOE3IelHMrpayVrosdHBuLw=="],
@@ -1423,6 +1524,8 @@
"resize-observer-polyfill": ["[email protected]", "", {}, "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg=="],
+ "resolve": ["[email protected]", "", { "dependencies": { "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ=="],
+
"retry": ["[email protected]", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="],
"retry-axios": ["[email protected]", "", { "peerDependencies": { "axios": "*" } }, "sha512-pOLi+Gdll3JekwuFjXO3fTq+L9lzMQGcSq7M5gIjExcl3Gu1hd4XXuf5o3+LuSBsaULQH7DiNbsqPd1chVpQGQ=="],
@@ -1445,6 +1548,8 @@
"set-function-length": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="],
+ "setimmediate": ["[email protected]", "", {}, "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA=="],
+
"sha.js": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.4", "safe-buffer": "^5.2.1", "to-buffer": "^1.2.0" }, "bin": { "sha.js": "bin.js" } }, "sha512-8LzC5+bvI45BjpfXU8V5fdU2mfeKiQe1D1gIMn7XUlF3OTUrpdJpPPH4EMAnF0DsHHdSZqCdSss5qCmJKuiO3w=="],
"side-channel": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
@@ -1455,6 +1560,10 @@
"side-channel-weakmap": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
+ "simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
+
+ "simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
+
"simple-wcswidth": ["[email protected]", "", {}, "sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw=="],
"smart-buffer": ["[email protected]", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="],
@@ -1485,6 +1594,8 @@
"strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+ "strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
+
"strtok3": ["[email protected]", "", { "dependencies": { "@tokenizer/token": "^0.3.0", "peek-readable": "^4.1.0" } }, "sha512-fZtbhtvI9I48xDSywd/somNqgUHl2L2cstmXCCif0itOf96jeW18MBSyrLuNicYQVkvpOxkZtkzujiTJ9LW5Jw=="],
"style-to-js": ["[email protected]", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
@@ -1493,14 +1604,22 @@
"supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
+ "supports-preserve-symlinks-flag": ["[email protected]", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="],
+
"tailwind-merge": ["[email protected]", "", {}, "sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g=="],
"tailwindcss": ["[email protected]", "", {}, "sha512-j9Ee2YjuQqYT9bbRTfTZht9W/ytp5H+jJpZKiYdP/bpnXARAuELt9ofP0lPnmHjbga7SNQIxdTAXCmtKVYjN+Q=="],
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
+ "tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
+
+ "tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
+
"thirty-two": ["[email protected]", "", {}, "sha512-OEI0IWCe+Dw46019YLl6V10Us5bi574EvlJEOcAkB29IzQ/mYD1A6RyNHLjZPiHCmuodxvgF6U+vZO1L15lxVA=="],
+ "timers-browserify": ["[email protected]", "", { "dependencies": { "setimmediate": "^1.0.4" } }, "sha512-9phl76Cqm6FhSX9Xe1ZUAMLtm1BLkKj2Qd5ApyWkXzsMRaA7dgr81kf4wJmQf/hAvg8EEyJxDo3du/0KlhPiKQ=="],
+
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],
@@ -1523,6 +1642,10 @@
"tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+ "tty-browserify": ["[email protected]", "", {}, "sha512-C3TaO7K81YvjCgQH9Q1S3R3P3BtN3RIM8n+OvX4il1K1zgE8ZhI0op7kClgkxtutIE8hQrcrHBXvIheqKUUCxw=="],
+
+ "tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
+
"tw-animate-css": ["[email protected]", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
"tween-functions": ["[email protected]", "", {}, "sha512-PZBtLYcCLtEcjL14Fzb1gSxPBeL7nWvGhO5ZFPGqziCcr8uvHp0NDmdjBchp6KHL+tExcg0m3NISmKxhU394dA=="],
@@ -1567,8 +1690,6 @@
"util": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "is-arguments": "^1.0.4", "is-generator-function": "^1.0.7", "is-typed-array": "^1.1.3", "which-typed-array": "^1.1.2" } }, "sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA=="],
- "util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
-
"uuid": ["[email protected]", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="],
"v8-compile-cache-lib": ["[email protected]", "", {}, "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg=="],
@@ -1583,6 +1704,10 @@
"vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-tI2l/nFHC5rLh7+5+o7QjKjSR04ivXDF4jcgV0f/bTQ+OJiITy5S6gaynVsEM+7RqzufMnVbIon6Sr5x1SDYaQ=="],
+ "vite-plugin-node-polyfills": ["[email protected]", "", { "dependencies": { "@rollup/plugin-inject": "^5.0.5", "node-stdlib-browser": "^1.2.0" }, "peerDependencies": { "vite": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-GA9QKLH+vIM8NPaGA+o2t8PDfFUl32J8rUp1zQfMKVJQiNkOX4unE51tR6ppl6iKw5yOrDAdSH7r/UIFLCVhLw=="],
+
+ "vm-browserify": ["[email protected]", "", {}, "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ=="],
+
"void-elements": ["[email protected]", "", {}, "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w=="],
"weaviate-client": ["[email protected]", "", { "dependencies": { "abort-controller-x": "^0.5.0", "graphql": "^16.12.0", "graphql-request": "^6.1.0", "long": "^5.3.2", "nice-grpc": "^2.1.13", "nice-grpc-client-middleware-retry": "^3.1.12", "nice-grpc-common": "^2.0.2", "uuid": "^9.0.1" } }, "sha512-PB338DjIwUus1Mq1dxhCc6fEp+yA+aY4H4sSFDS0No/GguEufd6SDhHHVLOYMy2cPgX35dWgEx5jUbG5o3aPZA=="],
@@ -1605,6 +1730,8 @@
"wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
+ "wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
+
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg=="],
"xtend": ["[email protected]", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
@@ -1621,6 +1748,8 @@
"yn": ["[email protected]", "", {}, "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q=="],
+ "yocto-queue": ["[email protected]", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
+
"zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25 || ^4" } }, "sha512-HvWtU2UG41LALjajJrML6uQejQhNJx+JBO9IflpSja4R03iNWfKXrj6W2h7ljuLyc1nKS+9yDyL/9tD1U/yBnQ=="],
@@ -1687,7 +1816,7 @@
"asn1.js/bn.js": ["[email protected]", "", {}, "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw=="],
- "browserify-sign/readable-stream": ["[email protected]", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
+ "bl/buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
"chalk/ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
@@ -1719,6 +1848,10 @@
"nice-grpc-client-middleware-retry/abort-controller-x": ["[email protected]", "", {}, "sha512-VtUwTNU8fpMwvWGn4xE93ywbogTYsuT+AUxAXOeelbXuQVIwNmC5YLeho9sH4vZ4ITW8414TTAOG1nW6uIVHCA=="],
+ "node-abi/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="],
+
+ "node-stdlib-browser/buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
+
"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
"parse5/entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],
@@ -1733,12 +1866,8 @@
"react-smooth/fast-equals": ["[email protected]", "", {}, "sha512-/boTcHZeIAQ2r/tL11voclBHDeP9WPxLt+tyAbVSyyXuUFyh0Tne7gJZTqGbxnvj79TjLdCXLOY7UIPhyG5MTw=="],
- "readable-web-to-node-stream/readable-stream": ["[email protected]", "", { "dependencies": { "abort-controller": "^3.0.0", "buffer": "^6.0.3", "events": "^3.3.0", "process": "^0.11.10", "string_decoder": "^1.3.0" } }, "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg=="],
-
"ripemd160/hash-base": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.4", "readable-stream": "^2.3.8", "safe-buffer": "^5.2.1", "to-buffer": "^1.2.1" } }, "sha512-Bb33KbowVTIj5s7Ked1OsqHUeCpz//tPwR+E2zJgJKo9Z5XolZ9b6bdUgjmYlwnWhoOQKoTd1TYToZGn5mAYOg=="],
- "to-buffer/isarray": ["[email protected]", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="],
-
"tough-cookie/punycode": ["[email protected]", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
"weaviate-client/uuid": ["[email protected]", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="],
@@ -1751,22 +1880,6 @@
"@ibm-cloud/watsonx-ai/@types/node/undici-types": ["[email protected]", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],
- "browserify-sign/readable-stream/safe-buffer": ["[email protected]", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
-
- "browserify-sign/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
-
"ibm-cloud-sdk-core/@types/node/undici-types": ["[email protected]", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],
-
- "md5.js/hash-base/readable-stream": ["[email protected]", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
-
- "ripemd160/hash-base/readable-stream": ["[email protected]", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
-
- "md5.js/hash-base/readable-stream/safe-buffer": ["[email protected]", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
-
- "md5.js/hash-base/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
-
- "ripemd160/hash-base/readable-stream/safe-buffer": ["[email protected]", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
-
- "ripemd160/hash-base/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
}
}
diff --git a/fincept-terminal-desktop/kraken_output.txt b/fincept-terminal-desktop/kraken_output.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/fincept-terminal-desktop/kraken_sub.json b/fincept-terminal-desktop/kraken_sub.json
new file mode 100644
index 000000000..6718d92c9
--- /dev/null
+++ b/fincept-terminal-desktop/kraken_sub.json
@@ -0,0 +1 @@
+method:subscribe params:channel:book params:symbol:[BTC/USD] params:depth:10 params:snapshot:true req_id:1
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.json
index 2032a3b20..813c88a45 100644
--- a/fincept-terminal-desktop/package.json
+++ b/fincept-terminal-desktop/package.json
@@ -8,7 +8,9 @@
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri",
- "bump-version": "node scripts/bump-version.js"
+ "tauri:dev": "bun run tauri dev",
+ "tauri:build": "bun run tauri build",
+ "bump-version": "bun scripts/bump-version.js"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
@@ -51,7 +53,9 @@
"@tauri-apps/plugin-sql": "^2.3.0",
"@tauri-apps/plugin-updater": "~2.9.0",
"@types/react-grid-layout": "^1.3.5",
+ "anychart": "^8.14.0",
"axios": "^1.12.2",
+ "better-sqlite3": "^12.5.0",
"ccxt": "^4.5.24",
"cheerio": "^1.1.2",
"class-variance-authority": "^0.7.1",
@@ -75,6 +79,7 @@
"otpauth": "^9.4.1",
"otplib": "^12.0.1",
"playwright": "^1.55.1",
+ "process": "^0.11.10",
"react": "^19.1.0",
"react-confetti": "^6.4.0",
"react-day-picker": "^9.11.0",
@@ -84,6 +89,7 @@
"react-markdown": "^10.1.0",
"react-router-dom": "^7.9.6",
"reactflow": "^11.11.4",
+ "readable-stream": "^4.7.0",
"recharts": "^2.15.4",
"remark-gfm": "^4.0.1",
"sonner": "^2.0.7",
@@ -92,6 +98,9 @@
"vaul": "^1.1.2",
"ws": "^8.18.3"
},
+ "resolutions": {
+ "readable-stream": "4.7.0"
+ },
"devDependencies": {
"@tauri-apps/cli": "^2",
"@types/jmespath": "^0.15.2",
@@ -111,11 +120,13 @@
"socks-proxy-agent": "^8.0.5",
"stream-browserify": "^3.0.0",
"stream-http": "^3.2.0",
+ "string_decoder": "^1.3.0",
"ts-node": "^10.9.2",
"tw-animate-css": "^1.4.0",
"typescript": "~5.8.3",
"url": "^0.11.4",
"util": "^0.12.5",
- "vite": "^7.0.4"
+ "vite": "^7.0.4",
+ "vite-plugin-node-polyfills": "^0.24.0"
}
}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs b/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs
index 6f566c77b..c60094fe5 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs
@@ -63,9 +63,6 @@ pub async fn execute_lean_cli(
backtest_id: String,
state: State<'_, BacktestingState>,
) -> Result<ProcessInfo, String> {
- println!("[Lean CLI] Executing: {}", command);
- println!("[Lean CLI] Working directory: {}", working_dir);
-
// Parse command into parts
let parts: Vec<&str> = command.split_whitespace().collect();
if parts.is_empty() {
@@ -98,8 +95,6 @@ pub async fn execute_lean_cli(
// In production, would spawn a thread to monitor output
// For now, we'll wait for completion in the background
- println!("[Lean CLI] Started process with PID: {}", pid);
-
Ok(ProcessInfo { process_id: pid })
}
@@ -110,8 +105,6 @@ pub async fn execute_lean_cli(
*/
#[tauri::command]
pub async fn execute_command(command: String) -> Result<CommandResult, String> {
- println!("[Command] Executing: {}", command);
-
// Parse command
let parts: Vec<&str> = command.split_whitespace().collect();
if parts.is_empty() {
@@ -145,8 +138,6 @@ pub async fn kill_lean_process(
process_id: u32,
state: State<'_, BacktestingState>,
) -> Result<(), String> {
- println!("[Lean CLI] Killing process: {}", process_id);
-
#[cfg(unix)]
{
use nix::sys::signal::{kill, Signal};
@@ -171,8 +162,6 @@ pub async fn kill_lean_process(
processes.retain(|_, p| p.pid != process_id);
}
- println!("[Lean CLI] Process {} terminated", process_id);
-
Ok(())
}
@@ -187,9 +176,6 @@ pub async fn execute_python_backtest(
command: String,
args: String,
) -> Result<String, String> {
- println!("[Python Backtest] Provider: {}", provider);
- println!("[Python Backtest] Command: {}", command);
-
// Determine Python path (bundled or system)
let python_path = get_python_path();
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index be971c0cd..eb359c245 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -44,7 +44,6 @@ fn greet(name: &str) -> String {
// Cleanup workflow on app close (called from frontend)
#[tauri::command]
async fn cleanup_running_workflows() -> Result<(), String> {
- println!("[Tauri] Cleaning up running workflows...");
// This is just a marker command - the actual cleanup happens in the frontend
// via workflowService.cleanupRunningWorkflows()
Ok(())
@@ -60,21 +59,17 @@ fn spawn_mcp_server(
args: Vec<String>,
env: HashMap<String, String>,
) -> Result<SpawnResult, String> {
- println!("[Tauri] Spawning MCP server: {} with command: {} {:?}", server_id, command, args);
-
// 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) {
Ok(bun_path) => {
- println!("[Tauri] Using bundled Bun: {:?}", bun_path);
// Use 'bun x' which is equivalent to 'bunx' or 'npx'
let mut new_args = vec!["x".to_string()];
new_args.extend(args.clone());
(bun_path.to_string_lossy().to_string(), new_args)
}
- Err(e) => {
- println!("[Tauri] Bundled Bun not found, falling back to system npx: {}", e);
+ Err(_) => {
// Fall back to system npx
#[cfg(target_os = "windows")]
let cmd = "npx.cmd".to_string();
@@ -120,7 +115,6 @@ fn spawn_mcp_server(
match cmd.spawn() {
Ok(mut child) => {
let pid = child.id();
- println!("[Tauri] MCP server spawned successfully with PID: {}", pid);
// Extract stdin and stdout
let stdin = child.stdin.take().ok_or("Failed to get stdin")?;
@@ -134,37 +128,32 @@ fn spawn_mcp_server(
let server_id_clone = server_id.clone();
thread::spawn(move || {
let reader = BufReader::new(stdout);
- println!("[Tauri] Started stdout reader thread for {}", server_id_clone);
for line in reader.lines() {
match line {
Ok(content) => {
if !content.trim().is_empty() {
- println!("[Tauri] Received from {}: {}", server_id_clone, content);
if response_tx.send(content).is_err() {
- eprintln!("[Tauri] Response channel closed for {}", server_id_clone);
break;
}
}
}
- Err(e) => {
- eprintln!("[Tauri] Error reading stdout for {}: {}", server_id_clone, e);
+ Err(_) => {
break;
}
}
}
- println!("[Tauri] Stdout reader thread exiting for {}", server_id_clone);
});
// Spawn background thread to read stderr (for debugging)
if let Some(stderr) = stderr {
- let server_id_clone = server_id.clone();
+ let _server_id_clone = server_id.clone();
thread::spawn(move || {
let reader = BufReader::new(stderr);
for line in reader.lines() {
if let Ok(content) = line {
if !content.trim().is_empty() {
- eprintln!("[Tauri] STDERR from {}: {}", server_id_clone, content);
+ eprintln!("[MCP] {}", content);
}
}
}
@@ -219,20 +208,15 @@ fn send_mcp_request(
.map_err(|e| format!("Failed to flush stdin: {}", e))?;
}
- println!("[Tauri] Request sent, waiting for response...");
-
// Wait for response with timeout (30 seconds for initial package download)
match mcp_process.response_rx.recv_timeout(Duration::from_secs(30)) {
Ok(response) => {
- println!("[Tauri] Received response: {}", response);
Ok(response)
}
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
- eprintln!("[Tauri] Timeout waiting for response from {}", server_id);
Err("Timeout: No response from server within 30 seconds".to_string())
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
- eprintln!("[Tauri] Response channel disconnected for {}", server_id);
Err("Server process has terminated unexpectedly".to_string())
}
}
@@ -248,8 +232,6 @@ fn send_mcp_notification(
server_id: String,
notification: String,
) -> Result<(), String> {
- println!("[Tauri] Sending notification to server {}: {}", server_id, notification);
-
let mut processes = state.processes.lock().unwrap();
if let Some(mcp_process) = processes.get_mut(&server_id) {
@@ -290,14 +272,11 @@ fn kill_mcp_server(
state: tauri::State<MCPState>,
server_id: String,
) -> Result<(), String> {
- println!("[Tauri] Killing MCP server: {}", server_id);
-
let mut processes = state.processes.lock().unwrap();
if let Some(mut mcp_process) = processes.remove(&server_id) {
match mcp_process.child.kill() {
Ok(_) => {
- println!("[Tauri] Server {} killed successfully", server_id);
Ok(())
}
Err(e) => Err(format!("Failed to kill server: {}", e)),
diff --git a/fincept-terminal-desktop/src-tauri/src/utils/python.rs b/fincept-terminal-desktop/src-tauri/src/utils/python.rs
index 9596ad853..94b681048 100644
--- a/fincept-terminal-desktop/src-tauri/src/utils/python.rs
+++ b/fincept-terminal-desktop/src-tauri/src/utils/python.rs
@@ -62,7 +62,6 @@ pub fn get_python_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {
// Check if system Python is available
if let Ok(output) = Command::new(system_python).arg("--version").output() {
if output.status.success() {
- println!("[DEV MODE] Using system Python: {}", system_python);
return Ok(PathBuf::from(system_python));
}
}
@@ -118,7 +117,6 @@ pub fn get_bundled_bun_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {
// Check if system Bun is available
if let Ok(output) = Command::new(system_bun).arg("--version").output() {
if output.status.success() {
- println!("[DEV MODE] Using system Bun: {}", system_bun);
return Ok(PathBuf::from(system_bun));
}
}
diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.json
index 3fbfd6050..c99e29314 100644
--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json
+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json
@@ -4,9 +4,9 @@
"version": "3.0.12",
"identifier": "com.fincept.terminal",
"build": {
- "beforeDevCommand": "npm run dev",
+ "beforeDevCommand": "bun run dev",
"devUrl": "http://localhost:1420",
- "beforeBuildCommand": "npm run build",
+ "beforeBuildCommand": "bun run build",
"frontendDist": "../dist"
},
"app": {
diff --git a/fincept-terminal-desktop/src/brokers/crypto/types.ts b/fincept-terminal-desktop/src/brokers/crypto/types.ts
index 8f71c5c1a..b29768a11 100644
--- a/fincept-terminal-desktop/src/brokers/crypto/types.ts
+++ b/fincept-terminal-desktop/src/brokers/crypto/types.ts
@@ -59,6 +59,9 @@ export interface IExchangeAdapter {
on(event: ExchangeEvent, callback: (data: ExchangeEventData) => void): void;
off(event: ExchangeEvent, callback: (data: ExchangeEventData) => void): void;
emit(event: ExchangeEvent, data: ExchangeEventData): void;
+
+ // Capabilities
+ getCapabilities(): ExchangeCapabilities;
}
// ============================================================================
@@ -93,6 +96,7 @@ export type OrderType =
| 'market'
| 'limit'
| 'stop'
+ | 'stop_market'
| 'stop_limit'
| 'trailing_stop'
| 'iceberg'
@@ -296,7 +300,8 @@ export type ExchangeEvent =
| 'trade'
| 'order'
| 'balance'
- | 'position';
+ | 'position'
+ | 'reset';
export interface ExchangeEventData {
event: ExchangeEvent;
diff --git a/fincept-terminal-desktop/src/brokers/features.ts b/fincept-terminal-desktop/src/brokers/features.ts
new file mode 100644
index 000000000..48ee63145
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/features.ts
@@ -0,0 +1,315 @@
+/**
+ * Broker Feature Detection System
+ *
+ * Auto-detects which methods and features each broker adapter supports
+ * Enables dynamic UI rendering based on broker capabilities
+ */
+
+import type { IExchangeAdapter } from './crypto/types';
+import type { BrokerMetadata } from './registry';
+
+// ============================================================================
+// FEATURE CATEGORIES
+// ============================================================================
+
+export interface BrokerFeatures {
+ // Market Data
+ marketData: {
+ fetchMarkets: boolean;
+ fetchTicker: boolean;
+ fetchTickers: boolean;
+ fetchOrderBook: boolean;
+ fetchTrades: boolean;
+ fetchOHLCV: boolean;
+ fetchStatus: boolean;
+ fetchTime: boolean;
+ fetchCurrencies: boolean;
+ };
+
+ // Account & Balance
+ account: {
+ fetchBalance: boolean;
+ fetchPositions: boolean;
+ fetchLedger: boolean;
+ fetchTradingFee: boolean;
+ fetchDeposits: boolean;
+ fetchWithdrawals: boolean;
+ };
+
+ // Trading - Basic
+ trading: {
+ createOrder: boolean;
+ createOrders: boolean;
+ editOrder: boolean;
+ editOrders: boolean;
+ cancelOrder: boolean;
+ cancelOrders: boolean;
+ cancelAllOrders: boolean;
+ cancelAllOrdersAfter: boolean;
+ };
+
+ // Trading - Advanced
+ tradingAdvanced: {
+ fetchOrder: boolean;
+ fetchOrders: boolean;
+ fetchOpenOrders: boolean;
+ fetchClosedOrders: boolean;
+ fetchCanceledOrders: boolean;
+ fetchMyTrades: boolean;
+ fetchOrderTrades: boolean;
+ };
+
+ // Margin & Leverage
+ margin: {
+ setLeverage: boolean;
+ setMarginMode: boolean;
+ addMargin: boolean;
+ reduceMargin: boolean;
+ };
+
+ // Transfers & Withdrawals
+ transfers: {
+ transfer: boolean;
+ transferOut: boolean;
+ withdraw: boolean;
+ createDepositAddress: boolean;
+ fetchDepositAddress: boolean;
+ fetchDepositMethods: boolean;
+ };
+
+ // Futures & Derivatives
+ futures: {
+ fetchFundingRate: boolean;
+ fetchFundingRates: boolean;
+ fetchFundingRateHistory: boolean;
+ fetchFundingHistory: boolean;
+ fetchOpenInterest: boolean;
+ fetchOpenInterests: boolean;
+ };
+
+ // HyperLiquid-specific
+ hyperliquid: {
+ createVault: boolean;
+ setVaultAddress: boolean;
+ setSubAccountAddress: boolean;
+ fetchVaultBalance: boolean;
+ };
+
+ // WebSocket
+ websocket: {
+ watchTicker: boolean;
+ watchTickers: boolean;
+ watchOrderBook: boolean;
+ watchTrades: boolean;
+ watchOHLCV: boolean;
+ watchOrders: boolean;
+ watchMyTrades: boolean;
+ watchBalance: boolean;
+ watchPositions: boolean;
+ };
+}
+
+// ============================================================================
+// FEATURE DETECTION
+// ============================================================================
+
+/**
+ * Detect all features supported by a broker adapter
+ */
+export function detectBrokerFeatures(adapter: IExchangeAdapter | any): BrokerFeatures {
+ return {
+ marketData: {
+ fetchMarkets: hasMethod(adapter, 'fetchMarkets'),
+ fetchTicker: hasMethod(adapter, 'fetchTicker'),
+ fetchTickers: hasMethod(adapter, 'fetchTickers'),
+ fetchOrderBook: hasMethod(adapter, 'fetchOrderBook'),
+ fetchTrades: hasMethod(adapter, 'fetchTrades'),
+ fetchOHLCV: hasMethod(adapter, 'fetchOHLCV'),
+ fetchStatus: hasMethod(adapter, 'fetchStatus'),
+ fetchTime: hasMethod(adapter, 'fetchTime'),
+ fetchCurrencies: hasMethod(adapter, 'fetchCurrencies'),
+ },
+
+ account: {
+ fetchBalance: hasMethod(adapter, 'fetchBalance'),
+ fetchPositions: hasMethod(adapter, 'fetchPositions'),
+ fetchLedger: hasMethod(adapter, 'fetchLedger'),
+ fetchTradingFee: hasMethod(adapter, 'fetchTradingFee'),
+ fetchDeposits: hasMethod(adapter, 'fetchDeposits'),
+ fetchWithdrawals: hasMethod(adapter, 'fetchWithdrawals'),
+ },
+
+ trading: {
+ createOrder: hasMethod(adapter, 'createOrder'),
+ createOrders: hasMethod(adapter, 'createOrders'),
+ editOrder: hasMethod(adapter, 'editOrder'),
+ editOrders: hasMethod(adapter, 'editOrders'),
+ cancelOrder: hasMethod(adapter, 'cancelOrder'),
+ cancelOrders: hasMethod(adapter, 'cancelOrders'),
+ cancelAllOrders: hasMethod(adapter, 'cancelAllOrders'),
+ cancelAllOrdersAfter: hasMethod(adapter, 'cancelAllOrdersAfter'),
+ },
+
+ tradingAdvanced: {
+ fetchOrder: hasMethod(adapter, 'fetchOrder'),
+ fetchOrders: hasMethod(adapter, 'fetchOrders'),
+ fetchOpenOrders: hasMethod(adapter, 'fetchOpenOrders'),
+ fetchClosedOrders: hasMethod(adapter, 'fetchClosedOrders'),
+ fetchCanceledOrders: hasMethod(adapter, 'fetchCanceledOrders'),
+ fetchMyTrades: hasMethod(adapter, 'fetchMyTrades'),
+ fetchOrderTrades: hasMethod(adapter, 'fetchOrderTrades'),
+ },
+
+ margin: {
+ setLeverage: hasMethod(adapter, 'setLeverage'),
+ setMarginMode: hasMethod(adapter, 'setMarginMode'),
+ addMargin: hasMethod(adapter, 'addMargin'),
+ reduceMargin: hasMethod(adapter, 'reduceMargin'),
+ },
+
+ transfers: {
+ transfer: hasMethod(adapter, 'transfer'),
+ transferOut: hasMethod(adapter, 'transferOut'),
+ withdraw: hasMethod(adapter, 'withdraw'),
+ createDepositAddress: hasMethod(adapter, 'createDepositAddress'),
+ fetchDepositAddress: hasMethod(adapter, 'fetchDepositAddress'),
+ fetchDepositMethods: hasMethod(adapter, 'fetchDepositMethods'),
+ },
+
+ futures: {
+ fetchFundingRate: hasMethod(adapter, 'fetchFundingRate'),
+ fetchFundingRates: hasMethod(adapter, 'fetchFundingRates'),
+ fetchFundingRateHistory: hasMethod(adapter, 'fetchFundingRateHistory'),
+ fetchFundingHistory: hasMethod(adapter, 'fetchFundingHistory'),
+ fetchOpenInterest: hasMethod(adapter, 'fetchOpenInterest'),
+ fetchOpenInterests: hasMethod(adapter, 'fetchOpenInterests'),
+ },
+
+ hyperliquid: {
+ createVault: hasMethod(adapter, 'createVault'),
+ setVaultAddress: hasMethod(adapter, 'setVaultAddress'),
+ setSubAccountAddress: hasMethod(adapter, 'setSubAccountAddress'),
+ fetchVaultBalance: hasMethod(adapter, 'fetchVaultBalance'),
+ },
+
+ websocket: {
+ watchTicker: hasMethod(adapter, 'watchTicker'),
+ watchTickers: hasMethod(adapter, 'watchTickers'),
+ watchOrderBook: hasMethod(adapter, 'watchOrderBook'),
+ watchTrades: hasMethod(adapter, 'watchTrades'),
+ watchOHLCV: hasMethod(adapter, 'watchOHLCV'),
+ watchOrders: hasMethod(adapter, 'watchOrders'),
+ watchMyTrades: hasMethod(adapter, 'watchMyTrades'),
+ watchBalance: hasMethod(adapter, 'watchBalance'),
+ watchPositions: hasMethod(adapter, 'watchPositions'),
+ },
+ };
+}
+
+/**
+ * Check if adapter has a specific method
+ */
+function hasMethod(adapter: any, methodName: string): boolean {
+ return typeof adapter?.[methodName] === 'function';
+}
+
+/**
+ * Check if broker supports a specific feature
+ */
+export function supportsFeature(
+ features: BrokerFeatures,
+ category: keyof BrokerFeatures,
+ feature: string
+): boolean {
+ const categoryFeatures = features[category] as any;
+ return categoryFeatures?.[feature] === true;
+}
+
+/**
+ * Get all supported features in a category
+ */
+export function getSupportedFeatures(
+ features: BrokerFeatures,
+ category: keyof BrokerFeatures
+): string[] {
+ const categoryFeatures = features[category] as any;
+ return Object.keys(categoryFeatures).filter(key => categoryFeatures[key] === true);
+}
+
+/**
+ * Get feature count for a category
+ */
+export function getFeatureCount(
+ features: BrokerFeatures,
+ category: keyof BrokerFeatures
+): number {
+ return getSupportedFeatures(features, category).length;
+}
+
+/**
+ * Check if broker supports category (has at least one feature)
+ */
+export function supportsCategory(
+ features: BrokerFeatures,
+ category: keyof BrokerFeatures
+): boolean {
+ return getFeatureCount(features, category) > 0;
+}
+
+/**
+ * Combine metadata and detected features
+ */
+export interface CompleteBrokerInfo {
+ metadata: BrokerMetadata;
+ features: BrokerFeatures;
+ capabilities: ReturnType<IExchangeAdapter['getCapabilities']>;
+}
+
+/**
+ * Get complete broker information
+ */
+export function getCompleteBrokerInfo(
+ metadata: BrokerMetadata,
+ adapter: IExchangeAdapter
+): CompleteBrokerInfo {
+ return {
+ metadata,
+ features: detectBrokerFeatures(adapter),
+ capabilities: adapter.getCapabilities(),
+ };
+}
+
+/**
+ * Create feature check helper
+ */
+export function createFeatureChecker(features: BrokerFeatures) {
+ return {
+ // Market data checks
+ canFetchTicker: () => features.marketData.fetchTicker,
+ canFetchOrderBook: () => features.marketData.fetchOrderBook,
+ canFetchOHLCV: () => features.marketData.fetchOHLCV,
+
+ // Trading checks
+ canCreateOrder: () => features.trading.createOrder,
+ canEditOrder: () => features.trading.editOrder,
+ canBatchOrder: () => features.trading.createOrders,
+ canCancelAll: () => features.trading.cancelAllOrders,
+
+ // Advanced checks
+ canSetLeverage: () => features.margin.setLeverage,
+ canTransfer: () => features.transfers.transfer,
+ canWithdraw: () => features.transfers.withdraw,
+
+ // Futures checks
+ hasFundingRates: () => features.futures.fetchFundingRates,
+ hasOpenInterest: () => features.futures.fetchOpenInterest,
+
+ // HyperLiquid checks
+ hasVaults: () => features.hyperliquid.createVault,
+ hasSubaccounts: () => features.hyperliquid.setSubAccountAddress,
+
+ // WebSocket checks
+ hasWebSocket: () => features.websocket.watchTicker,
+ canStreamOrders: () => features.websocket.watchOrders,
+ };
+}
diff --git a/fincept-terminal-desktop/src/brokers/index.ts b/fincept-terminal-desktop/src/brokers/index.ts
index c05699fd0..8e7c5b5ec 100644
--- a/fincept-terminal-desktop/src/brokers/index.ts
+++ b/fincept-terminal-desktop/src/brokers/index.ts
@@ -31,7 +31,39 @@ export {
export { KiteConnectAdapter, createKiteAdapter } from './stocks';
// ============================================================================
-// UNIFIED BROKER REGISTRY
+// UNIFIED BROKER REGISTRY (NEW SYSTEM)
+// ============================================================================
+export {
+ BROKER_REGISTRY,
+ getAllBrokers,
+ getBrokersByType,
+ getBrokerMetadata,
+ isBrokerRegistered,
+ getBrokerDisplayName,
+ getDefaultSymbols,
+ supportsBrokerFeature,
+ supportsTradingFeature,
+ supportsAdvancedFeature,
+ getMaxLeverage,
+ createBrokerAdapter,
+ createBrokerAdapters,
+ type BrokerMetadata,
+} from './registry';
+
+export {
+ detectBrokerFeatures,
+ supportsFeature,
+ getSupportedFeatures,
+ getFeatureCount,
+ supportsCategory,
+ getCompleteBrokerInfo,
+ createFeatureChecker,
+ type BrokerFeatures,
+ type CompleteBrokerInfo,
+} from './features';
+
+// ============================================================================
+// LEGACY BROKER REGISTRY (Kept for backward compatibility)
// ============================================================================
import { SUPPORTED_EXCHANGES } from './crypto';
diff --git a/fincept-terminal-desktop/src/brokers/registry.ts b/fincept-terminal-desktop/src/brokers/registry.ts
new file mode 100644
index 000000000..315a2d367
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/registry.ts
@@ -0,0 +1,309 @@
+/**
+ * Unified Broker Registry
+ *
+ * Central registry for all broker adapters with metadata and capabilities
+ * Enables seamless broker switching and future extensibility
+ */
+
+import { KrakenAdapter } from './crypto/kraken/KrakenAdapter';
+import { HyperLiquidAdapter } from './crypto/hyperliquid/HyperLiquidAdapter';
+import type { IExchangeAdapter, ExchangeConfig } from './crypto/types';
+
+// ============================================================================
+// BROKER METADATA
+// ============================================================================
+
+export interface BrokerMetadata {
+ id: string;
+ name: string;
+ displayName: string;
+ type: 'crypto' | 'stocks' | 'forex' | 'commodities';
+ category: 'centralized' | 'decentralized';
+ region: 'global' | 'us' | 'india' | 'asia' | 'europe';
+
+ // Adapter class
+ adapterClass: any; // Using any to avoid complex type incompatibility with async generators
+
+ // Feature flags
+ features: {
+ spot?: boolean;
+ margin?: boolean;
+ futures?: boolean;
+ perpetuals?: boolean;
+ options?: boolean;
+ staking?: boolean;
+ vaults?: boolean;
+ subaccounts?: boolean;
+ };
+
+ // Trading features
+ tradingFeatures: {
+ marketOrders: boolean;
+ limitOrders: boolean;
+ stopOrders: boolean;
+ stopLimitOrders: boolean;
+ trailingStopOrders: boolean;
+ icebergOrders: boolean;
+ batchOrders: boolean;
+ editOrders: boolean;
+ };
+
+ // Advanced features
+ advancedFeatures: {
+ leverage: boolean;
+ maxLeverage?: number;
+ marginMode: boolean;
+ transfers: boolean;
+ withdrawals: boolean;
+ deposits: boolean;
+ };
+
+ // Default symbols (popular pairs)
+ defaultSymbols: string[];
+
+ // WebSocket support
+ websocket: {
+ enabled: boolean;
+ endpoint?: string;
+ };
+}
+
+// ============================================================================
+// BROKER REGISTRY
+// ============================================================================
+
+export const BROKER_REGISTRY: Record<string, BrokerMetadata> = {
+ kraken: {
+ id: 'kraken',
+ name: 'kraken',
+ displayName: 'Kraken',
+ type: 'crypto',
+ category: 'centralized',
+ region: 'global',
+ adapterClass: KrakenAdapter,
+
+ features: {
+ spot: true,
+ margin: true,
+ futures: true,
+ perpetuals: false,
+ options: false,
+ staking: true,
+ vaults: false,
+ subaccounts: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true,
+ stopLimitOrders: true,
+ trailingStopOrders: true,
+ icebergOrders: true,
+ batchOrders: true,
+ editOrders: true,
+ },
+
+ advancedFeatures: {
+ leverage: true,
+ maxLeverage: 5,
+ marginMode: true,
+ transfers: true,
+ withdrawals: true,
+ deposits: true,
+ },
+
+ defaultSymbols: [
+ 'BTC/USD',
+ 'ETH/USD',
+ 'SOL/USD',
+ 'XRP/USD',
+ 'ADA/USD',
+ 'DOGE/USD',
+ 'MATIC/USD',
+ 'DOT/USD',
+ 'AVAX/USD',
+ 'LINK/USD',
+ 'UNI/USD',
+ 'ATOM/USD',
+ 'LTC/USD',
+ 'BCH/USD',
+ 'ALGO/USD',
+ ],
+
+ websocket: {
+ enabled: true,
+ endpoint: 'wss://ws.kraken.com/v2',
+ },
+ },
+
+ hyperliquid: {
+ id: 'hyperliquid',
+ name: 'hyperliquid',
+ displayName: 'HyperLiquid',
+ type: 'crypto',
+ category: 'decentralized',
+ region: 'global',
+ adapterClass: HyperLiquidAdapter,
+
+ features: {
+ spot: true,
+ margin: false,
+ futures: true,
+ perpetuals: true,
+ options: false,
+ staking: false,
+ vaults: true,
+ subaccounts: true,
+ },
+
+ tradingFeatures: {
+ marketOrders: true, // Simulated with limit orders
+ limitOrders: true,
+ stopOrders: true,
+ stopLimitOrders: true,
+ trailingStopOrders: false,
+ icebergOrders: false,
+ batchOrders: true,
+ editOrders: true,
+ },
+
+ advancedFeatures: {
+ leverage: true,
+ maxLeverage: 50,
+ marginMode: true,
+ transfers: true,
+ withdrawals: true,
+ deposits: false,
+ },
+
+ defaultSymbols: ['BTC/USDC:USDC', 'ETH/USDC:USDC', 'SOL/USDC:USDC', 'AVAX/USDC:USDC', 'MATIC/USDC:USDC'],
+
+ websocket: {
+ enabled: true, // HyperLiquidAdapter now available
+ endpoint: 'wss://api.hyperliquid.xyz/ws',
+ },
+ },
+};
+
+// ============================================================================
+// HELPER FUNCTIONS
+// ============================================================================
+
+/**
+ * Get all registered brokers
+ */
+export function getAllBrokers(): BrokerMetadata[] {
+ return Object.values(BROKER_REGISTRY);
+}
+
+/**
+ * Get brokers by type
+ */
+export function getBrokersByType(type: 'crypto' | 'stocks' | 'forex' | 'commodities'): BrokerMetadata[] {
+ return getAllBrokers().filter(broker => broker.type === type);
+}
+
+/**
+ * Get broker metadata by ID
+ */
+export function getBrokerMetadata(brokerId: string): BrokerMetadata | undefined {
+ return BROKER_REGISTRY[brokerId];
+}
+
+/**
+ * Check if broker is registered
+ */
+export function isBrokerRegistered(brokerId: string): boolean {
+ return brokerId in BROKER_REGISTRY;
+}
+
+/**
+ * Get broker display name
+ */
+export function getBrokerDisplayName(brokerId: string): string {
+ return BROKER_REGISTRY[brokerId]?.displayName || brokerId.toUpperCase();
+}
+
+/**
+ * Get default symbols for broker
+ */
+export function getDefaultSymbols(brokerId: string): string[] {
+ return BROKER_REGISTRY[brokerId]?.defaultSymbols || [];
+}
+
+/**
+ * Check if broker supports feature
+ */
+export function supportsBrokerFeature(
+ brokerId: string,
+ feature: keyof BrokerMetadata['features']
+): boolean {
+ const metadata = BROKER_REGISTRY[brokerId];
+ return metadata?.features[feature] === true;
+}
+
+/**
+ * Check if broker supports trading feature
+ */
+export function supportsTradingFeature(
+ brokerId: string,
+ feature: keyof BrokerMetadata['tradingFeatures']
+): boolean {
+ const metadata = BROKER_REGISTRY[brokerId];
+ return metadata?.tradingFeatures[feature] === true;
+}
+
+/**
+ * Check if broker supports advanced feature
+ */
+export function supportsAdvancedFeature(
+ brokerId: string,
+ feature: keyof BrokerMetadata['advancedFeatures']
+): boolean {
+ const metadata = BROKER_REGISTRY[brokerId];
+ return metadata?.advancedFeatures[feature] === true;
+}
+
+/**
+ * Get max leverage for broker
+ */
+export function getMaxLeverage(brokerId: string): number {
+ return BROKER_REGISTRY[brokerId]?.advancedFeatures.maxLeverage || 1;
+}
+
+// ============================================================================
+// ADAPTER FACTORY
+// ============================================================================
+
+/**
+ * Create broker adapter instance
+ */
+export function createBrokerAdapter(
+ brokerId: string,
+ config?: Partial<ExchangeConfig>
+): IExchangeAdapter {
+ const metadata = BROKER_REGISTRY[brokerId];
+
+ if (!metadata) {
+ throw new Error(`Broker "${brokerId}" is not registered`);
+ }
+
+ return new metadata.adapterClass(config);
+}
+
+/**
+ * Create multiple broker adapters
+ */
+export function createBrokerAdapters(
+ brokerIds: string[],
+ config?: Partial<ExchangeConfig>
+): Map<string, IExchangeAdapter> {
+ const adapters = new Map<string, IExchangeAdapter>();
+
+ for (const brokerId of brokerIds) {
+ adapters.set(brokerId, createBrokerAdapter(brokerId, config));
+ }
+
+ return adapters;
+}
diff --git a/fincept-terminal-desktop/src/components/charts/SimpleLineChart.tsx b/fincept-terminal-desktop/src/components/charts/SimpleLineChart.tsx
deleted file mode 100644
index 3779007f3..000000000
--- a/fincept-terminal-desktop/src/components/charts/SimpleLineChart.tsx
+++ /dev/null
@@ -1,207 +0,0 @@
-import React, { useEffect, useRef } from 'react';
-
-export interface ChartDataPoint {
- timestamp: number;
- value: number;
- label?: string;
-}
-
-interface SimpleLineChartProps {
- data: ChartDataPoint[];
- width?: number;
- height?: number;
- color?: string;
- backgroundColor?: string;
- gridColor?: string;
- textColor?: string;
- lineWidth?: number;
- showGrid?: boolean;
- showLabels?: boolean;
-}
-
-const SimpleLineChart: React.FC<SimpleLineChartProps> = ({
- data,
- width = 400,
- height = 200,
- color = '#00ff88',
- backgroundColor = '#0a0a0a',
- gridColor = '#222222',
- textColor = '#888888',
- lineWidth = 2,
- showGrid = true,
- showLabels = true,
-}) => {
- const canvasRef = useRef<HTMLCanvasElement>(null);
-
- useEffect(() => {
- if (!canvasRef.current || data.length === 0) return;
-
- const canvas = canvasRef.current;
- const ctx = canvas.getContext('2d');
- if (!ctx) return;
-
- // Set canvas size
- canvas.width = width;
- canvas.height = height;
-
- // Clear canvas
- ctx.fillStyle = backgroundColor;
- ctx.fillRect(0, 0, width, height);
-
- // Calculate data range
- const values = data.map(d => d.value);
- const maxValue = Math.max(...values);
- const minValue = Math.min(...values);
- const valueRange = maxValue - minValue || 1;
-
- // Padding
- const padding = { top: 20, right: 40, bottom: 30, left: 10 };
- const chartWidth = width - padding.left - padding.right;
- const chartHeight = height - padding.top - padding.bottom;
-
- // Draw grid
- if (showGrid) {
- ctx.strokeStyle = gridColor;
- ctx.lineWidth = 1;
-
- // Horizontal grid lines
- const gridLines = 5;
- for (let i = 0; i <= gridLines; i++) {
- const y = padding.top + (chartHeight / gridLines) * i;
- ctx.beginPath();
- ctx.moveTo(padding.left, y);
- ctx.lineTo(width - padding.right, y);
- ctx.stroke();
- }
-
- // Vertical grid lines
- const verticalLines = 4;
- for (let i = 0; i <= verticalLines; i++) {
- const x = padding.left + (chartWidth / verticalLines) * i;
- ctx.beginPath();
- ctx.moveTo(x, padding.top);
- ctx.lineTo(x, height - padding.bottom);
- ctx.stroke();
- }
- }
-
- // Draw price labels
- if (showLabels) {
- ctx.fillStyle = textColor;
- ctx.font = '9px Consolas, monospace';
- ctx.textAlign = 'left';
-
- const labelCount = 5;
- for (let i = 0; i <= labelCount; i++) {
- const value = minValue + (valueRange / labelCount) * (labelCount - i);
- const y = padding.top + (chartHeight / labelCount) * i;
- ctx.fillText(value.toFixed(2), width - padding.right + 5, y + 3);
- }
-
- // Draw date labels
- ctx.textAlign = 'center';
- const dateLabels = [0, Math.floor(data.length / 2), data.length - 1];
- dateLabels.forEach(idx => {
- if (idx < data.length) {
- const x = padding.left + (chartWidth / (data.length - 1)) * idx;
- const date = new Date(data[idx].timestamp * 1000);
- const dateStr = `${date.getMonth() + 1}/${date.getDate()}`;
- ctx.fillText(dateStr, x, height - padding.bottom + 15);
- }
- });
- }
-
- // Draw line
- ctx.strokeStyle = color;
- ctx.lineWidth = lineWidth;
- ctx.beginPath();
-
- data.forEach((point, index) => {
- const x = padding.left + (chartWidth / (data.length - 1)) * index;
- const normalizedValue = (point.value - minValue) / valueRange;
- const y = height - padding.bottom - (normalizedValue * chartHeight);
-
- if (index === 0) {
- ctx.moveTo(x, y);
- } else {
- ctx.lineTo(x, y);
- }
- });
-
- ctx.stroke();
-
- // Draw glow effect
- ctx.shadowColor = color;
- ctx.shadowBlur = 8;
- ctx.stroke();
- ctx.shadowBlur = 0;
-
- // Draw points
- data.forEach((point, index) => {
- const x = padding.left + (chartWidth / (data.length - 1)) * index;
- const normalizedValue = (point.value - minValue) / valueRange;
- const y = height - padding.bottom - (normalizedValue * chartHeight);
-
- // Only draw points at start, end, and every 10th point for clarity
- if (index === 0 || index === data.length - 1 || index % 10 === 0) {
- ctx.fillStyle = color;
- ctx.beginPath();
- ctx.arc(x, y, 2, 0, Math.PI * 2);
- ctx.fill();
- }
- });
-
- // Draw current price indicator
- if (data.length > 0) {
- const lastPoint = data[data.length - 1];
- const lastX = padding.left + chartWidth;
- const normalizedValue = (lastPoint.value - minValue) / valueRange;
- const lastY = height - padding.bottom - (normalizedValue * chartHeight);
-
- // Draw horizontal line
- ctx.strokeStyle = color;
- ctx.lineWidth = 1;
- ctx.setLineDash([5, 5]);
- ctx.beginPath();
- ctx.moveTo(padding.left, lastY);
- ctx.lineTo(width - padding.right, lastY);
- ctx.stroke();
- ctx.setLineDash([]);
-
- // Draw price box
- ctx.fillStyle = color;
- const priceText = lastPoint.value.toFixed(2);
- const textWidth = ctx.measureText(priceText).width;
- ctx.fillRect(width - padding.right + 2, lastY - 8, textWidth + 6, 16);
- ctx.fillStyle = backgroundColor;
- ctx.font = 'bold 10px Consolas, monospace';
- ctx.textAlign = 'left';
- ctx.fillText(priceText, width - padding.right + 5, lastY + 3);
- }
-
- }, [data, width, height, color, backgroundColor, gridColor, textColor, lineWidth, showGrid, showLabels]);
-
- if (data.length === 0) {
- return (
- <div
- style={{
- width: `${width}px`,
- height: `${height}px`,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- backgroundColor,
- color: textColor,
- fontSize: '11px',
- fontFamily: 'Consolas, monospace',
- }}
- >
- No chart data available
- </div>
- );
- }
-
- return <canvas ref={canvasRef} style={{ display: 'block' }} />;
-};
-
-export default SimpleLineChart;
diff --git a/fincept-terminal-desktop/src/components/common/WebSocketErrorBoundary.tsx b/fincept-terminal-desktop/src/components/common/WebSocketErrorBoundary.tsx
new file mode 100644
index 000000000..9c3f7b51a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/common/WebSocketErrorBoundary.tsx
@@ -0,0 +1,54 @@
+// WebSocket Error Boundary for graceful error handling
+import React, { Component, ErrorInfo, ReactNode } from 'react';
+
+interface Props {
+ children: ReactNode;
+ fallback?: ReactNode;
+}
+
+interface State {
+ hasError: boolean;
+ error: Error | null;
+}
+
+export class WebSocketErrorBoundary extends Component<Props, State> {
+ constructor(props: Props) {
+ super(props);
+ this.state = { hasError: false, error: null };
+ }
+
+ static getDerivedStateFromError(error: Error): State {
+ return { hasError: true, error };
+ }
+
+ componentDidCatch(error: Error, errorInfo: ErrorInfo) {
+ console.error('[WebSocketErrorBoundary] Caught error:', error, errorInfo);
+ }
+
+ render() {
+ if (this.state.hasError) {
+ if (this.props.fallback) {
+ return this.props.fallback;
+ }
+
+ return (
+ <div className="flex items-center justify-center h-full bg-[#0d0d0d] text-white">
+ <div className="text-center p-6">
+ <div className="text-red-500 text-lg mb-2">⚠ Connection Error</div>
+ <div className="text-gray-400 text-sm mb-4">
+ {this.state.error?.message || 'WebSocket connection failed'}
+ </div>
+ <button
+ onClick={() => window.location.reload()}
+ className="px-4 py-2 bg-orange-600 hover:bg-orange-700 rounded text-sm"
+ >
+ Reload Page
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ return this.props.children;
+ }
+}
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 2f3c52964..46119b84f 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -37,7 +37,6 @@ import MCPTab from '@/components/tabs/mcp';
import FyersTab from '@/components/tabs/fyers';
import SupportTicketTab from '@/components/tabs/SupportTicketTab';
import PolygonEqTab from '@/components/tabs/PolygonEqTab';
-import KrakenTab from '@/components/tabs/KrakenTab';
import { TradingTab } from '@/components/tabs/TradingTab';
import ReportBuilderTab from '@/components/tabs/ReportBuilderTab';
import BacktestingTab from '@/components/tabs/BacktestingTab';
@@ -473,7 +472,6 @@ function FinxeptTerminalContent() {
{ label: 'Live Markets', shortcut: 'F2', action: () => setActiveTab('markets') },
{ label: 'Stock Screener', shortcut: 'F8', action: () => setActiveTab('screener') },
{ label: 'Polygon Data', action: () => setActiveTab('polygon'), separator: true },
- { label: 'Kraken Crypto', action: () => setActiveTab('kraken') },
{ label: 'Economics', action: () => setActiveTab('economics') },
{ label: 'DBnomics', action: () => setActiveTab('dbnomics') }
];
@@ -984,9 +982,6 @@ function FinxeptTerminalContent() {
<TabsContent value="maritime" className="h-full m-0 p-0">
<MaritimeTab />
</TabsContent>
- <TabsContent value="kraken" className="h-full m-0 p-0">
- <KrakenTab />
- </TabsContent>
<TabsContent value="trading" className="h-full m-0 p-0">
<TradingTab />
</TabsContent>
diff --git a/fincept-terminal-desktop/src/components/tabs/KrakenTab.tsx b/fincept-terminal-desktop/src/components/tabs/KrakenTab.tsx
deleted file mode 100644
index f5ecb8f0e..000000000
--- a/fincept-terminal-desktop/src/components/tabs/KrakenTab.tsx
+++ /dev/null
@@ -1,836 +0,0 @@
-// Kraken Trading Terminal - Bloomberg-style interface
-import React, { useState, useEffect, useMemo, useRef } from 'react';
-import { useWebSocket } from '@/hooks/useWebSocket';
-import { getWebSocketManager } from '@/services/websocket';
-import { TrendingUp, TrendingDown, Activity, BookOpen, BarChart3, Zap } from 'lucide-react';
-import { createChart, ColorType, IChartApi, ISeriesApi, CandlestickData, CandlestickSeries } from 'lightweight-charts';
-
-// Popular Kraken trading pairs
-const POPULAR_PAIRS = [
- 'BTC/USD', 'ETH/USD', 'XRP/USD', 'SOL/USD', 'ADA/USD',
- 'MATIC/USD', 'AVAX/USD', 'DOT/USD', 'LINK/USD', 'UNI/USD'
-];
-
-const OHLC_INTERVALS = [
- { label: '1m', value: 1 },
- { label: '5m', value: 5 },
- { label: '15m', value: 15 },
- { label: '30m', value: 30 },
- { label: '1h', value: 60 },
- { label: '4h', value: 240 },
- { label: '1D', value: 1440 }
-];
-
-const ORDERBOOK_DEPTHS = [10, 25, 100, 500, 1000];
-
-interface TickerData {
- symbol: string;
- bid: number;
- ask: number;
- last: number;
- volume: number;
- vwap: number;
- high: number;
- low: number;
- change: number;
- change_pct: number;
-}
-
-interface TradeData {
- symbol: string;
- price: number;
- qty: number;
- side: 'buy' | 'sell';
- timestamp: number;
-}
-
-interface OrderBookLevel {
- price: number;
- qty: number;
-}
-
-interface OrderBookData {
- symbol: string;
- bids: OrderBookLevel[];
- asks: OrderBookLevel[];
- checksum?: number;
-}
-
-interface OHLCData {
- timestamp: number | string;
- open: number;
- high: number;
- low: number;
- close: number;
- volume: number;
-}
-
-export default function KrakenTab() {
- const [selectedPair, setSelectedPair] = useState('BTC/USD');
- const [ohlcInterval, setOhlcInterval] = useState(60);
- const [bookDepth, setBookDepth] = useState(25);
- const [tickerData, setTickerData] = useState<TickerData | null>(null);
- const [trades, setTrades] = useState<TradeData[]>([]);
- const [orderBook, setOrderBook] = useState<OrderBookData>({ symbol: '', bids: [], asks: [] });
- const [isConnected, setIsConnected] = useState(false);
- const [chartData, setChartData] = useState<OHLCData[]>([]);
- const [searchQuery, setSearchQuery] = useState('');
- const [customPair, setCustomPair] = useState('');
-
- const chartContainerRef = useRef<HTMLDivElement>(null);
- const chartRef = useRef<IChartApi | null>(null);
- const candlestickSeriesRef = useRef<any>(null);
- const isMountedRef = useRef(true);
- const lastCandleTimeRef = useRef<number>(0);
-
- // Initialize WebSocket manager
- useEffect(() => {
- const manager = getWebSocketManager();
- manager.setProviderConfig('kraken', {
- provider_name: 'kraken',
- enabled: true,
- endpoint: 'wss://ws.kraken.com/v2'
- });
-
- // Connect to Kraken
- const connectToKraken = async () => {
- try {
- await manager.connect('kraken');
- setIsConnected(true);
- } catch (error) {
- console.error('Failed to connect to Kraken:', error);
- setIsConnected(false);
- }
- };
-
- connectToKraken();
-
- return () => {
- // Don't disconnect on unmount as other components might be using it
- setIsConnected(false);
- };
- }, []);
-
- // Fetch historical OHLC data from Kraken REST API
- const fetchHistoricalData = async (pair: string, interval: number) => {
- try {
- // Convert pair format for Kraken API
- // BTC/USD -> XBTUSD, ETH/USD -> ETHUSD, etc.
- let krakenPair = pair.replace('/', '');
-
- // Special case: BTC is XBT on Kraken
- if (krakenPair.startsWith('BTC')) {
- krakenPair = krakenPair.replace('BTC', 'XBT');
- }
-
- console.log(`Fetching historical data for ${pair} (Kraken: ${krakenPair}), interval: ${interval}`);
-
- // Fetch last 100 candles
- const response = await fetch(
- `https://api.kraken.com/0/public/OHLC?pair=${krakenPair}&interval=${interval}`
- );
-
- const data = await response.json();
-
- if (data.error && data.error.length > 0) {
- console.error('Kraken API error:', data.error);
- return [];
- }
-
- const result = data.result;
- const pairKey = Object.keys(result).find(key => key !== 'last');
-
- if (!pairKey) {
- console.warn('No data found for pair:', krakenPair);
- return [];
- }
-
- const ohlcData: OHLCData[] = result[pairKey].map((candle: any[]) => ({
- timestamp: candle[0],
- open: parseFloat(candle[1]),
- high: parseFloat(candle[2]),
- low: parseFloat(candle[3]),
- close: parseFloat(candle[4]),
- volume: parseFloat(candle[6])
- }));
-
- console.log(`Fetched ${ohlcData.length} candles for ${pair}`);
- return ohlcData;
- } catch (error) {
- console.error('Failed to fetch historical data:', error);
- return [];
- }
- };
-
- // Initialize chart
- useEffect(() => {
- if (!chartContainerRef.current) return;
-
- const chart = createChart(chartContainerRef.current, {
- layout: {
- background: { type: ColorType.Solid, color: '#0a0a0a' },
- textColor: '#d1d5db',
- },
- grid: {
- vertLines: { color: '#1f2937' },
- horzLines: { color: '#1f2937' },
- },
- width: chartContainerRef.current.clientWidth,
- height: chartContainerRef.current.clientHeight,
- timeScale: {
- timeVisible: true,
- secondsVisible: false,
- },
- });
-
- const candlestickSeries = chart.addSeries(CandlestickSeries, {
- upColor: '#10b981',
- downColor: '#ef4444',
- borderUpColor: '#10b981',
- borderDownColor: '#ef4444',
- wickUpColor: '#10b981',
- wickDownColor: '#ef4444',
- });
-
- chartRef.current = chart;
- candlestickSeriesRef.current = candlestickSeries;
-
- // Handle resize
- const handleResize = () => {
- if (isMountedRef.current && chartContainerRef.current && chartRef.current) {
- try {
- chartRef.current.applyOptions({
- width: chartContainerRef.current.clientWidth,
- height: chartContainerRef.current.clientHeight,
- });
- } catch (error) {
- // Ignore errors if chart is being disposed
- }
- }
- };
-
- window.addEventListener('resize', handleResize);
-
- return () => {
- isMountedRef.current = false;
- window.removeEventListener('resize', handleResize);
- candlestickSeriesRef.current = null;
- chartRef.current = null;
- setTimeout(() => {
- try {
- chart.remove();
- } catch (error) {
- // Ignore errors during cleanup
- }
- }, 0);
- };
- }, []);
-
- // Load historical data when pair or interval changes
- useEffect(() => {
- const loadData = async () => {
- // Reset the last candle time when loading new data
- lastCandleTimeRef.current = 0;
-
- const historical = await fetchHistoricalData(selectedPair, ohlcInterval);
- setChartData(historical);
-
- if (candlestickSeriesRef.current && historical.length > 0) {
- const chartCandles = historical.map((candle, idx) => {
- // Ensure timestamp is a number (Unix timestamp in seconds)
- let time: number;
-
- if (typeof candle.timestamp === 'number') {
- time = candle.timestamp;
- } else if (typeof candle.timestamp === 'string') {
- time = Math.floor(new Date(candle.timestamp).getTime() / 1000);
- } else {
- console.error('Invalid timestamp type in historical data:', candle.timestamp, 'at index:', idx);
- time = 0;
- }
-
- // If it's in milliseconds, convert to seconds
- if (time > 10000000000) {
- time = Math.floor(time / 1000);
- }
-
- return {
- time,
- open: candle.open,
- high: candle.high,
- low: candle.low,
- close: candle.close,
- };
- }).filter(candle => candle.time > 0) // Filter out invalid candles
- .sort((a, b) => a.time - b.time); // Sort by time ascending
-
- console.log('Setting chart data with', chartCandles.length, 'candles, first:', chartCandles[0], 'last:', chartCandles[chartCandles.length - 1]);
-
- // Use setData to replace all chart data
- candlestickSeriesRef.current.setData(chartCandles);
-
- // Track the last candle time so we can update it with live data
- const lastCandle = chartCandles[chartCandles.length - 1];
- if (lastCandle) {
- lastCandleTimeRef.current = lastCandle.time;
- console.log('Last candle time set to:', lastCandleTimeRef.current);
- }
- }
- };
-
- loadData();
- }, [selectedPair, ohlcInterval]);
-
- // Ticker subscription
- const { message: tickerMessage } = useWebSocket(
- isConnected ? `kraken.ticker.${selectedPair}` : null,
- null,
- { autoSubscribe: true }
- );
-
- // Trade subscription
- const { message: tradeMessage } = useWebSocket(
- isConnected ? `kraken.trade.${selectedPair}` : null,
- null,
- { autoSubscribe: true }
- );
-
- // Order book subscription
- const { message: bookMessage } = useWebSocket(
- isConnected ? `kraken.book.${selectedPair}` : null,
- null,
- { autoSubscribe: true, params: { depth: bookDepth } }
- );
-
- // OHLC subscription
- const { message: ohlcMessage } = useWebSocket(
- isConnected ? `kraken.ohlc.${selectedPair}` : null,
- null,
- { autoSubscribe: true, params: { interval: ohlcInterval } }
- );
-
- // Update ticker data
- useEffect(() => {
- if (tickerMessage?.data) {
- console.log('Ticker message received:', tickerMessage.data);
- setTickerData(tickerMessage.data as TickerData);
- }
- }, [tickerMessage]);
-
- // Update trades
- useEffect(() => {
- if (tradeMessage?.data) {
- const trade = tradeMessage.data as TradeData;
- setTrades(prev => [trade, ...prev].slice(0, 100));
- }
- }, [tradeMessage]);
-
- // Update order book - merge instead of replace
- useEffect(() => {
- if (bookMessage?.data) {
- const newBook = bookMessage.data as OrderBookData;
- const messageType = (bookMessage.data as any).messageType;
-
- if (messageType === 'snapshot') {
- // Snapshot: replace entire book
- setOrderBook(newBook);
- } else {
- // Update: merge with existing book
- setOrderBook(prev => {
- const updatedBids = [...prev.bids];
- const updatedAsks = [...prev.asks];
-
- // Update bids
- newBook.bids?.forEach(newBid => {
- const index = updatedBids.findIndex(b => b.price === newBid.price);
- if (newBid.qty === 0) {
- // Remove if quantity is 0
- if (index !== -1) updatedBids.splice(index, 1);
- } else {
- if (index !== -1) {
- // Update existing
- updatedBids[index] = newBid;
- } else {
- // Add new
- updatedBids.push(newBid);
- }
- }
- });
-
- // Update asks
- newBook.asks?.forEach(newAsk => {
- const index = updatedAsks.findIndex(a => a.price === newAsk.price);
- if (newAsk.qty === 0) {
- // Remove if quantity is 0
- if (index !== -1) updatedAsks.splice(index, 1);
- } else {
- if (index !== -1) {
- // Update existing
- updatedAsks[index] = newAsk;
- } else {
- // Add new
- updatedAsks.push(newAsk);
- }
- }
- });
-
- // Sort bids descending, asks ascending, and limit to depth
- updatedBids.sort((a, b) => b.price - a.price);
- updatedAsks.sort((a, b) => a.price - b.price);
-
- return {
- symbol: newBook.symbol || prev.symbol,
- bids: updatedBids.slice(0, bookDepth),
- asks: updatedAsks.slice(0, bookDepth),
- checksum: newBook.checksum
- };
- });
- }
- }
- }, [bookMessage, bookDepth]);
-
- // Update chart with live OHLC data
- useEffect(() => {
- if (ohlcMessage?.data && candlestickSeriesRef.current) {
- try {
- const ohlc = ohlcMessage.data as any;
-
- // Parse the interval_begin timestamp to determine the candle's time
- // This represents when the candle period started
- let candleTime: number;
-
- if (ohlc.interval_begin) {
- // Parse ISO string from interval_begin
- candleTime = Math.floor(new Date(ohlc.interval_begin).getTime() / 1000);
- } else {
- // Fallback to the message timestamp
- let timestamp = ohlcMessage.timestamp;
- candleTime = typeof timestamp === 'number' ? Math.floor(timestamp / 1000) : 0;
- }
-
- // Validate that candleTime is actually a number
- if (typeof candleTime !== 'number' || isNaN(candleTime)) {
- console.error('Invalid candleTime:', candleTime, 'type:', typeof candleTime);
- return;
- }
-
- // Skip old candles (this can happen when historical data is still loading)
- // Only update if the candle is >= the last tracked candle
- if (lastCandleTimeRef.current > 0 && candleTime < lastCandleTimeRef.current) {
- console.log('Skipping old candle:', candleTime, 'last:', lastCandleTimeRef.current);
- return;
- }
-
- console.log('Updating candle:', candleTime, 'last:', lastCandleTimeRef.current);
-
- // Check if this is the same candle we're already tracking (update)
- // or a new candle (which means the previous interval completed)
- if (lastCandleTimeRef.current === candleTime) {
- // Same candle - update it (this makes it "animate" like TradingView)
- candlestickSeriesRef.current.update({
- time: candleTime as any,
- open: parseFloat(ohlc.open),
- high: parseFloat(ohlc.high),
- low: parseFloat(ohlc.low),
- close: parseFloat(ohlc.close),
- });
- } else {
- // New candle - the interval completed
- lastCandleTimeRef.current = candleTime;
- candlestickSeriesRef.current.update({
- time: candleTime as any,
- open: parseFloat(ohlc.open),
- high: parseFloat(ohlc.high),
- low: parseFloat(ohlc.low),
- close: parseFloat(ohlc.close),
- });
- }
- } catch (error) {
- console.error('Failed to update chart with OHLC data:', error, ohlcMessage);
- }
- }
- }, [ohlcMessage]);
-
- const priceChangeColor = useMemo(() => {
- if (!tickerData) return 'text-gray-400';
- return tickerData.change >= 0 ? 'text-green-400' : 'text-red-400';
- }, [tickerData]);
-
- const spread = useMemo(() => {
- if (!tickerData) return 0;
- return ((tickerData.ask - tickerData.bid) / tickerData.bid * 100).toFixed(4);
- }, [tickerData]);
-
- // Filter popular pairs based on search query
- const filteredPairs = useMemo(() => {
- if (!searchQuery) return POPULAR_PAIRS;
- const query = searchQuery.toLowerCase();
- return POPULAR_PAIRS.filter(pair => pair.toLowerCase().includes(query));
- }, [searchQuery]);
-
- // Handle custom pair submission
- const handleCustomPairSubmit = (e: React.FormEvent) => {
- e.preventDefault();
- if (customPair.trim()) {
- // Format the pair (add / if not present)
- const formattedPair = customPair.includes('/')
- ? customPair.toUpperCase()
- : customPair.toUpperCase().replace(/([A-Z]{3,})([A-Z]{3,})/, '$1/$2');
- setSelectedPair(formattedPair);
- setCustomPair('');
- setSearchQuery('');
- }
- };
-
- return (
- <div className="h-full bg-[#0a0a0a] text-gray-100 flex flex-col overflow-hidden font-mono">
- {/* Header */}
- <div className="bg-[#111111] border-b border-gray-800 px-4 py-2 flex items-center justify-between">
- <div className="flex items-center gap-4">
- <div className="flex items-center gap-2">
- <Zap className="w-5 h-5 text-yellow-400" />
- <span className="text-lg font-bold text-yellow-400">KRAKEN</span>
- <span className="text-xs text-gray-500">TERMINAL</span>
- </div>
- <div className="h-6 w-px bg-gray-700" />
- <div className={`flex items-center gap-2 ${priceChangeColor}`}>
- <span className="text-2xl font-bold">
- {selectedPair}
- </span>
- {tickerData && (
- <>
- {tickerData.change >= 0 ? <TrendingUp className="w-5 h-5" /> : <TrendingDown className="w-5 h-5" />}
- <span className="text-sm">
- {tickerData.change >= 0 ? '+' : ''}{tickerData.change_pct?.toFixed(2)}%
- </span>
- </>
- )}
- </div>
- </div>
- <div className="flex items-center gap-2">
- <div className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-400 animate-pulse' : 'bg-red-400'}`} />
- <span className="text-xs text-gray-400">
- {isConnected ? 'LIVE' : 'DISCONNECTED'}
- </span>
- </div>
- </div>
-
- {/* Symbol Selector */}
- <div className="bg-[#0d0d0d] border-b border-gray-800 px-4 py-2">
- <div className="flex items-center gap-3">
- {/* Search Input */}
- <div className="flex items-center gap-2 flex-shrink-0">
- <input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Search pairs..."
- className="bg-[#1a1a1a] text-gray-200 text-xs px-3 py-1 border border-gray-700 focus:outline-none focus:border-orange-500 w-32"
- />
- {/* Custom Pair Form */}
- <form onSubmit={handleCustomPairSubmit} className="flex items-center gap-1">
- <input
- type="text"
- value={customPair}
- onChange={(e) => setCustomPair(e.target.value)}
- placeholder="BTC/USD"
- className="bg-[#1a1a1a] text-gray-200 text-xs px-3 py-1 border border-gray-700 focus:outline-none focus:border-orange-500 w-24"
- />
- <button
- type="submit"
- className="bg-orange-600 text-black text-xs px-2 py-1 font-semibold hover:bg-orange-500 transition-colors"
- >
- Go
- </button>
- </form>
- </div>
-
- {/* Pair Buttons */}
- <div className="flex items-center gap-2 overflow-x-auto flex-1">
- {filteredPairs.map(pair => (
- <button
- key={pair}
- onClick={() => setSelectedPair(pair)}
- className={`px-3 py-1 rounded text-xs font-semibold whitespace-nowrap transition-colors ${
- selectedPair === pair
- ? 'bg-orange-600 text-black'
- : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
- }`}
- >
- {pair}
- </button>
- ))}
- {filteredPairs.length === 0 && (
- <span className="text-xs text-gray-500">No pairs found</span>
- )}
- </div>
- </div>
- </div>
-
- {/* Main Content */}
- <div className="flex-1 flex overflow-hidden">
- {/* Left Panel - Ticker & Stats */}
- <div className="w-80 border-r border-gray-800 flex flex-col">
- {/* Price Display */}
- <div className="bg-[#0d0d0d] border-b border-gray-800 p-4">
- <div className="mb-2">
- <div className="text-xs text-gray-500 mb-1">LAST PRICE</div>
- <div className={`text-3xl font-bold ${priceChangeColor}`}>
- ${tickerData?.last?.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '---'}
- </div>
- </div>
- <div className="grid grid-cols-2 gap-3 text-xs">
- <div>
- <div className="text-gray-500">24H CHANGE</div>
- <div className={priceChangeColor}>
- {tickerData && tickerData.change !== undefined
- ? `${tickerData.change >= 0 ? '+' : ''}${tickerData.change.toFixed(2)}`
- : '---'}
- <span className="ml-1">
- ({tickerData?.change_pct?.toFixed(2) || '---'}%)
- </span>
- </div>
- </div>
- <div>
- <div className="text-gray-500">SPREAD</div>
- <div className="text-gray-300">{spread}%</div>
- </div>
- <div>
- <div className="text-gray-500">24H HIGH</div>
- <div className="text-green-400">${tickerData?.high?.toLocaleString() || '---'}</div>
- </div>
- <div>
- <div className="text-gray-500">24H LOW</div>
- <div className="text-red-400">${tickerData?.low?.toLocaleString() || '---'}</div>
- </div>
- <div>
- <div className="text-gray-500">24H VOLUME</div>
- <div className="text-gray-300">{tickerData?.volume?.toFixed(2) || '---'}</div>
- </div>
- <div>
- <div className="text-gray-500">VWAP</div>
- <div className="text-gray-300">${tickerData?.vwap?.toFixed(2) || '---'}</div>
- </div>
- </div>
- </div>
-
- {/* BID/ASK */}
- <div className="bg-[#0d0d0d] border-b border-gray-800 p-4">
- <div className="grid grid-cols-2 gap-3">
- <div>
- <div className="text-xs text-gray-500 mb-1">BID</div>
- <div className="text-lg font-bold text-green-400">
- ${tickerData?.bid?.toLocaleString('en-US', { minimumFractionDigits: 2 }) || '---'}
- </div>
- </div>
- <div>
- <div className="text-xs text-gray-500 mb-1">ASK</div>
- <div className="text-lg font-bold text-red-400">
- ${tickerData?.ask?.toLocaleString('en-US', { minimumFractionDigits: 2 }) || '---'}
- </div>
- </div>
- </div>
- </div>
-
- {/* Trades Feed */}
- <div className="flex-1 flex flex-col bg-[#0a0a0a]">
- <div className="bg-[#0d0d0d] border-b border-gray-800 px-4 py-2 flex items-center gap-2">
- <Activity className="w-4 h-4 text-orange-500" />
- <span className="text-xs font-semibold text-gray-400">RECENT TRADES</span>
- </div>
- <div className="flex-1 overflow-y-auto">
- <div className="text-[10px] px-2 py-1 bg-[#0d0d0d] grid grid-cols-3 gap-2 text-gray-500 sticky top-0">
- <div>TIME</div>
- <div className="text-right">PRICE</div>
- <div className="text-right">SIZE</div>
- </div>
- {trades.map((trade, idx) => (
- <div
- key={`${trade.timestamp}-${idx}`}
- className={`text-xs px-2 py-1 grid grid-cols-3 gap-2 border-b border-gray-900 hover:bg-gray-900 ${
- trade.side === 'buy' ? 'bg-green-950/10' : 'bg-red-950/10'
- }`}
- >
- <div className="text-gray-500">
- {new Date(trade.timestamp).toLocaleTimeString('en-US', {
- hour12: false,
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit'
- })}
- </div>
- <div className={`text-right font-semibold ${trade.side === 'buy' ? 'text-green-400' : 'text-red-400'}`}>
- ${trade.price.toFixed(2)}
- </div>
- <div className="text-right text-gray-300">
- {trade.qty.toFixed(6)}
- </div>
- </div>
- ))}
- {trades.length === 0 && (
- <div className="p-4 text-center text-gray-600 text-xs">
- Waiting for trades...
- </div>
- )}
- </div>
- </div>
- </div>
-
- {/* Center Panel - Chart */}
- <div className="flex-1 flex flex-col bg-[#0a0a0a]">
- {/* Chart Controls */}
- <div className="bg-[#0d0d0d] border-b border-gray-800 px-4 py-2 flex items-center justify-between">
- <div className="flex items-center gap-2">
- <BarChart3 className="w-4 h-4 text-orange-500" />
- <span className="text-xs font-semibold text-gray-400">CANDLESTICK CHART</span>
- </div>
- <div className="flex items-center gap-2">
- {OHLC_INTERVALS.map(interval => (
- <button
- key={interval.value}
- onClick={() => setOhlcInterval(interval.value)}
- className={`px-2 py-1 rounded text-[10px] font-semibold transition-colors ${
- ohlcInterval === interval.value
- ? 'bg-orange-600 text-black'
- : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
- }`}
- >
- {interval.label}
- </button>
- ))}
- </div>
- </div>
-
- {/* Chart */}
- <div ref={chartContainerRef} className="flex-1 bg-[#0a0a0a]" />
- </div>
-
- {/* Right Panel - Order Book */}
- <div className="w-96 border-l border-gray-800 flex flex-col bg-[#0a0a0a]">
- {/* Order Book Header */}
- <div className="bg-[#0d0d0d] border-b border-gray-800 px-4 py-2 flex items-center justify-between">
- <div className="flex items-center gap-2">
- <BookOpen className="w-4 h-4 text-orange-500" />
- <span className="text-xs font-semibold text-gray-400">ORDER BOOK</span>
- </div>
- <select
- value={bookDepth}
- onChange={(e) => setBookDepth(Number(e.target.value))}
- className="bg-gray-800 text-gray-300 text-[10px] px-2 py-1 rounded border border-gray-700 focus:outline-none focus:border-orange-500"
- >
- {ORDERBOOK_DEPTHS.map(depth => (
- <option key={depth} value={depth}>
- DEPTH: {depth}
- </option>
- ))}
- </select>
- </div>
-
- {/* Order Book Content */}
- <div className="flex-1 flex flex-col overflow-hidden">
- {/* Asks (Sell Orders) */}
- <div className="flex-1 flex flex-col-reverse overflow-y-auto">
- <div className="text-[10px] px-3 py-1 bg-[#0d0d0d] grid grid-cols-3 gap-2 text-gray-500 sticky bottom-0">
- <div className="text-right">PRICE</div>
- <div className="text-right">SIZE</div>
- <div className="text-right">TOTAL</div>
- </div>
- {orderBook.asks.slice(0, 15).reverse().map((level, idx) => {
- const total = orderBook.asks.slice(0, idx + 1).reduce((sum, l) => sum + l.qty, 0);
- const maxTotal = Math.max(...orderBook.asks.slice(0, 15).map((_, i) =>
- orderBook.asks.slice(0, i + 1).reduce((sum, l) => sum + l.qty, 0)
- ));
- const percentage = maxTotal > 0 ? (total / maxTotal) * 100 : 0;
-
- return (
- <div
- key={`ask-${level.price}-${idx}`}
- className="text-xs px-3 py-0.5 grid grid-cols-3 gap-2 relative hover:bg-red-950/20"
- >
- <div
- className="absolute inset-0 bg-red-950/20"
- style={{ width: `${percentage}%`, right: 0, left: 'auto' }}
- />
- <div className="text-right text-red-400 font-semibold relative z-10">
- {level.price.toFixed(2)}
- </div>
- <div className="text-right text-gray-300 relative z-10">
- {level.qty.toFixed(6)}
- </div>
- <div className="text-right text-gray-500 relative z-10">
- {total.toFixed(6)}
- </div>
- </div>
- );
- })}
- </div>
-
- {/* Spread */}
- <div className="bg-[#0d0d0d] border-y border-gray-800 px-3 py-2 text-center">
- <div className="text-[10px] text-gray-500">SPREAD</div>
- <div className="text-sm font-bold text-yellow-400">{spread}%</div>
- </div>
-
- {/* Bids (Buy Orders) */}
- <div className="flex-1 overflow-y-auto">
- <div className="text-[10px] px-3 py-1 bg-[#0d0d0d] grid grid-cols-3 gap-2 text-gray-500 sticky top-0">
- <div className="text-right">PRICE</div>
- <div className="text-right">SIZE</div>
- <div className="text-right">TOTAL</div>
- </div>
- {orderBook.bids.slice(0, 15).map((level, idx) => {
- const total = orderBook.bids.slice(0, idx + 1).reduce((sum, l) => sum + l.qty, 0);
- const maxTotal = Math.max(...orderBook.bids.slice(0, 15).map((_, i) =>
- orderBook.bids.slice(0, i + 1).reduce((sum, l) => sum + l.qty, 0)
- ));
- const percentage = maxTotal > 0 ? (total / maxTotal) * 100 : 0;
-
- return (
- <div
- key={`bid-${level.price}-${idx}`}
- className="text-xs px-3 py-0.5 grid grid-cols-3 gap-2 relative hover:bg-green-950/20"
- >
- <div
- className="absolute inset-0 bg-green-950/20"
- style={{ width: `${percentage}%`, right: 0, left: 'auto' }}
- />
- <div className="text-right text-green-400 font-semibold relative z-10">
- {level.price.toFixed(2)}
- </div>
- <div className="text-right text-gray-300 relative z-10">
- {level.qty.toFixed(6)}
- </div>
- <div className="text-right text-gray-500 relative z-10">
- {total.toFixed(6)}
- </div>
- </div>
- );
- })}
- {orderBook.bids.length === 0 && orderBook.asks.length === 0 && (
- <div className="p-4 text-center text-gray-600 text-xs">
- Loading order book...
- </div>
- )}
- </div>
- </div>
- </div>
- </div>
-
- {/* Status Bar */}
- <div className="bg-[#0d0d0d] border-t border-gray-800 px-4 py-1 flex items-center justify-between text-[10px] text-gray-500">
- <div className="flex items-center gap-4">
- <span>KRAKEN WEBSOCKET v2</span>
- <span>•</span>
- <span>PAIR: {selectedPair}</span>
- <span>•</span>
- <span>INTERVAL: {OHLC_INTERVALS.find(i => i.value === ohlcInterval)?.label}</span>
- <span>•</span>
- <span>DEPTH: {bookDepth}</span>
- </div>
- <div className="flex items-center gap-2">
- <span>{new Date().toLocaleTimeString('en-US', { hour12: false })}</span>
- </div>
- </div>
- </div>
- );
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
index 965ade6af..7fb8aae8c 100644
--- a/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
@@ -38,7 +38,6 @@ const NewsTab: React.FC = () => {
timestamp: new Date().toISOString(),
filter: activeFilter
};
- console.log('[NewsTab] Recording current data:', recordData);
await contextRecorderService.recordApiResponse(
'News',
'news-feed',
@@ -46,9 +45,8 @@ const NewsTab: React.FC = () => {
`News Feed (Snapshot) - ${new Date().toLocaleString()}`,
['news', 'rss', 'snapshot', activeFilter.toLowerCase()]
);
- console.log('[NewsTab] Current data recorded successfully');
} catch (error) {
- console.error('[NewsTab] Failed to record current data:', error);
+ // Silently handle recording errors
}
}
};
@@ -75,7 +73,6 @@ const NewsTab: React.FC = () => {
timestamp: new Date().toISOString(),
filter: activeFilter
};
- console.log('[NewsTab] Recording data:', recordData);
await contextRecorderService.recordApiResponse(
'News',
'news-feed',
@@ -83,13 +80,12 @@ const NewsTab: React.FC = () => {
`News Feed - ${new Date().toLocaleString()}`,
['news', 'rss', 'live-feed', activeFilter.toLowerCase()]
);
- console.log('[NewsTab] Data recorded successfully');
} catch (error) {
- console.error('[NewsTab] Failed to record data:', error);
+ // Silently handle recording errors
}
}
} catch (error) {
- console.error('Error fetching news:', error);
+ // Silently handle fetch errors
} finally {
setLoading(false);
}
@@ -125,11 +121,11 @@ const NewsTab: React.FC = () => {
['news', 'rss', 'live-feed', activeFilter.toLowerCase()]
);
} catch (error) {
- console.error('[NewsTab] Failed to record data:', error);
+ // Silently handle recording errors
}
}
} catch (error) {
- console.error('Error fetching news:', error);
+ // Silently handle fetch errors
} finally {
setLoading(false);
}
@@ -1015,10 +1011,8 @@ const NewsTab: React.FC = () => {
onClick={async (e) => {
e.stopPropagation();
const link = selectedArticle.link;
- console.log('📰 Opening link in external browser:', link);
if (!link) {
- console.error('❌ No link available');
return;
}
@@ -1026,7 +1020,6 @@ const NewsTab: React.FC = () => {
if (window.__TAURI__) {
const { openUrl } = await import('@tauri-apps/plugin-opener');
await openUrl(link);
- console.log('✅ Link opened via Tauri opener');
} else {
const a = document.createElement('a');
a.href = link;
@@ -1035,12 +1028,9 @@ const NewsTab: React.FC = () => {
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
- console.log('✅ Link opened via anchor element');
}
} catch (error) {
- console.error('❌ Failed to open link:', error);
await navigator.clipboard.writeText(link);
- console.log('📋 Link copied to clipboard');
}
}}
style={{
@@ -1063,7 +1053,6 @@ const NewsTab: React.FC = () => {
const link = selectedArticle.link;
if (link) {
navigator.clipboard.writeText(link);
- console.log('Link copied to clipboard:', link);
e.currentTarget.textContent = '✓ COPIED!';
setTimeout(() => {
e.currentTarget.textContent = '📋 COPY';
diff --git a/fincept-terminal-desktop/src/components/tabs/TestChart.tsx b/fincept-terminal-desktop/src/components/tabs/TestChart.tsx
new file mode 100644
index 000000000..c9288c6c1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/TestChart.tsx
@@ -0,0 +1,55 @@
+import React, { useEffect, useRef } from 'react';
+import { createChart, ColorType } from 'lightweight-charts';
+
+export function TestChart() {
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!chartContainerRef.current) return;
+
+ // Create chart
+ const chart = createChart(chartContainerRef.current, {
+ width: chartContainerRef.current.clientWidth,
+ height: 400,
+ layout: {
+ background: { type: ColorType.Solid, color: '#0d0d0d' },
+ textColor: '#999',
+ },
+ grid: {
+ vertLines: { color: '#1a1a1a' },
+ horzLines: { color: '#1a1a1a' },
+ },
+ });
+
+ // Add candlestick series
+ const candleSeries = (chart as any).addCandlestickSeries({
+ upColor: '#10b981',
+ downColor: '#dc2626',
+ borderUpColor: '#10b981',
+ borderDownColor: '#dc2626',
+ wickUpColor: '#10b981',
+ wickDownColor: '#dc2626',
+ });
+
+ // Dummy data
+ const dummyData = [
+ { time: '2024-01-01', open: 100, high: 110, low: 95, close: 105 },
+ { time: '2024-01-02', open: 105, high: 115, low: 100, close: 112 },
+ { time: '2024-01-03', open: 112, high: 120, low: 108, close: 109 },
+ { time: '2024-01-04', open: 109, high: 118, low: 105, close: 116 },
+ { time: '2024-01-05', open: 116, high: 125, low: 115, close: 122 },
+ ];
+
+ candleSeries.setData(dummyData);
+ chart.timeScale().fitContent();
+
+ return () => chart.remove();
+ }, []);
+
+ return (
+ <div style={{ padding: '20px', backgroundColor: '#0d0d0d', color: 'white' }}>
+ <h1>Test Lightweight Charts</h1>
+ <div ref={chartContainerRef} style={{ width: '100%', height: '400px' }} />
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
index f7bd1dacb..328b7d339 100644
--- a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
@@ -1,707 +1,1400 @@
// File: src/components/tabs/TradingTab.tsx
-// Unified trading tab with multi-provider support and paper trading
-// Uses new broker adapter architecture
-
-import React, { useState, useEffect, useRef, useCallback } from 'react';
-import { Activity, TrendingUp } from 'lucide-react';
-import { ProviderSwitcher } from './trading/ProviderSwitcher';
-import { PaperTradingPanel } from './trading/PaperTradingPanel';
-import { TickerDisplay } from './trading/TickerDisplay';
-import { OrderBook } from './trading/OrderBook';
-import { TradesFeed } from './trading/TradesFeed';
-import { OrderForm } from './trading/OrderForm';
-import { PositionsTable } from './trading/PositionsTable';
-import { OrdersTable } from './trading/OrdersTable';
-import { TradeHistory } from './trading/TradeHistory';
-import { PaperTradingStats } from './trading/PaperTradingStats';
-import { useProviderContext } from '../../contexts/ProviderContext';
-import { paperTradingDatabase } from '../../paper-trading';
+// Complete Trading Tab with Paper Trading Integration
+
+import React, { useState, useEffect, useCallback } from 'react';
+import { useBrokerContext } from '../../contexts/BrokerContext';
import { useWebSocket } from '../../hooks/useWebSocket';
-import { getWebSocketManager } from '../../services/websocket';
-import { createExchangeAdapter } from '../../brokers/crypto';
-import { createPaperTradingAdapter } from '../../paper-trading';
-import type { IExchangeAdapter } from '../../brokers/crypto/types';
-import type { Position as CCXTPosition } from 'ccxt';
-
-// Symbol configurations per provider
-const KRAKEN_PAIRS = ['BTC/USD', 'ETH/USD', 'SOL/USD', 'AVAX/USD', 'MATIC/USD'];
-const HYPERLIQUID_SYMBOLS = ['BTC/USDC:USDC', 'ETH/USDC:USDC', 'SOL/USDC:USDC', 'AVAX/USDC:USDC', 'MATIC/USDC:USDC'];
-
-// Bloomberg color scheme
-const BLOOMBERG_COLORS = {
- ORANGE: '#ea580c',
- WHITE: '#ffffff',
- RED: '#dc2626',
- GREEN: '#10b981',
- GRAY: '#525252',
- DARK_BG: '#0d0d0d',
- PANEL_BG: '#1a1a1a',
- CYAN: '#22d3ee',
- YELLOW: '#fbbf24'
-};
+import { OrderForm } from './trading/OrderForm';
+import type { OrderRequest } from '../../types/trading';
+
+interface OrderBookLevel {
+ price: number;
+ size: number;
+}
+
+interface OrderBook {
+ bids: OrderBookLevel[];
+ asks: OrderBookLevel[];
+ symbol: string;
+ checksum?: number;
+}
+
+interface Position {
+ symbol: string;
+ side: 'long' | 'short';
+ quantity: number;
+ entryPrice: number;
+ positionValue: number;
+ currentPrice: number;
+ unrealizedPnl: number;
+ pnlPercent: number;
+}
+
+interface Order {
+ id: string;
+ symbol: string;
+ side: 'buy' | 'sell';
+ type: string;
+ quantity: number;
+ price?: number;
+ status: string;
+ createdAt: string;
+}
export function TradingTab() {
- const { activeProvider } = useProviderContext();
- const [portfolioId, setPortfolioId] = useState<string | null>(null);
- const [isResetting, setIsResetting] = useState(false);
- const [currentTime, setCurrentTime] = useState(new Date());
- const [isConnected, setIsConnected] = useState(false);
- const [positions, setPositions] = useState<CCXTPosition[]>([]);
- const [balance, setBalance] = useState<number>(0);
- const [totalPnL, setTotalPnL] = useState<number>(0);
- const [isLoading, setIsLoading] = useState(false);
- const [orders, setOrders] = useState<any[]>([]);
+ const {
+ activeBroker,
+ tradingMode,
+ activeAdapter,
+ paperAdapter,
+ defaultSymbols,
+ isConnecting,
+ } = useBrokerContext();
+
+ // Debug logging
+ useEffect(() => {
+ console.log('[TradingTab] Context updated:');
+ console.log(' - activeBroker:', activeBroker);
+ console.log(' - tradingMode:', tradingMode);
+ console.log(' - paperAdapter:', paperAdapter ? 'EXISTS' : 'NULL');
+ console.log(' - paperAdapter.isConnected():', paperAdapter?.isConnected());
+ console.log(' - isConnecting:', isConnecting);
+ }, [activeBroker, tradingMode, paperAdapter, isConnecting]);
+
+ const [selectedSymbol, setSelectedSymbol] = useState(defaultSymbols[0] || 'BTC/USD');
+ const [tickerData, setTickerData] = useState<any>(null);
+ const [orderBook, setOrderBook] = useState<OrderBook>({ bids: [], asks: [], symbol: '' });
+ const [tradesData, setTradesData] = useState<any[]>([]);
+ const [isPlacingOrder, setIsPlacingOrder] = useState(false);
+ const [lastOrderBookUpdate, setLastOrderBookUpdate] = useState<number>(0);
+
+ // Symbol search state
+ const [searchQuery, setSearchQuery] = useState('');
+ const [availableSymbols, setAvailableSymbols] = useState<string[]>([]);
+ const [isLoadingSymbols, setIsLoadingSymbols] = useState(false);
+ const [showSymbolDropdown, setShowSymbolDropdown] = useState(false);
+
+ // Paper trading state
+ const [positions, setPositions] = useState<Position[]>([]);
+ const [orders, setOrders] = useState<Order[]>([]);
const [trades, setTrades] = useState<any[]>([]);
+ const [balance, setBalance] = useState(0);
+ const [equity, setEquity] = useState(0);
const [stats, setStats] = useState<any>(null);
+ const [activeTab, setActiveTab] = useState<'positions' | 'orders' | 'trades' | 'stats'>('positions');
- // Get symbols based on active provider
- const popularSymbols = activeProvider === 'kraken' ? KRAKEN_PAIRS : HYPERLIQUID_SYMBOLS;
- const [selectedSymbol, setSelectedSymbol] = useState(popularSymbols[0]);
-
- // Adapter refs
- const realAdapterRef = useRef<any>(null);
- const paperAdapterRef = useRef<any>(null);
+ // Trading settings
+ const [slippage, setSlippage] = useState(0);
+ const [makerFee, setMakerFee] = useState(0.0002); // 0.02% default
+ const [takerFee, setTakerFee] = useState(0.0005); // 0.05% default
+ const [showSettings, setShowSettings] = useState(false);
- // Initialize WebSocket connection for active provider
+ // Clear data when symbol changes
useEffect(() => {
- const manager = getWebSocketManager();
+ console.log('[TradingTab] Symbol changed to:', selectedSymbol);
+ // Clear existing data for new symbol
+ setTickerData(null);
+ setOrderBook({ bids: [], asks: [], symbol: selectedSymbol });
+ setTradesData([]);
+ setLastOrderBookUpdate(0);
+ }, [selectedSymbol]);
+
+ // Subscribe to ticker WebSocket
+ const { message: tickerMessage } = useWebSocket(
+ activeBroker ? `${activeBroker}.ticker.${selectedSymbol}` : null
+ );
- const initProvider = async () => {
- try {
- console.log(`[TradingTab] Initializing ${activeProvider} provider...`);
+ // Subscribe to orderbook WebSocket
+ const { message: orderbookMessage } = useWebSocket(
+ activeBroker ? `${activeBroker}.book.${selectedSymbol}` : null
+ );
- if (activeProvider === 'kraken') {
- manager.setProviderConfig('kraken', {
- provider_name: 'kraken',
- enabled: true,
- endpoint: 'wss://ws.kraken.com/v2'
- });
- await manager.connect('kraken');
- console.log('[TradingTab] Kraken connected successfully');
- } else if (activeProvider === 'hyperliquid') {
- manager.setProviderConfig('hyperliquid', {
- provider_name: 'hyperliquid',
- enabled: true,
- endpoint: 'wss://api.hyperliquid.xyz/ws'
- });
- await manager.connect('hyperliquid');
- console.log('[TradingTab] HyperLiquid connected successfully');
- }
- setIsConnected(true);
- } catch (error) {
- console.error(`[TradingTab] Failed to connect to ${activeProvider}:`, error);
- setIsConnected(false);
- }
- };
+ // Subscribe to trades WebSocket
+ const { message: tradesMessage } = useWebSocket(
+ activeBroker ? `${activeBroker}.trade.${selectedSymbol}` : null
+ );
- initProvider();
- }, [activeProvider]);
- // Update selected symbol when provider changes
+ // Update ticker data
useEffect(() => {
- const symbols = activeProvider === 'kraken' ? KRAKEN_PAIRS : HYPERLIQUID_SYMBOLS;
- setSelectedSymbol(symbols[0]);
- }, [activeProvider]);
+ if (tickerMessage && tickerMessage.data) {
+ const data = tickerMessage.data;
+
+ // Verify the ticker data is for the current selected symbol
+ if (data.symbol === selectedSymbol) {
+ console.log('[TradingTab] WebSocket ticker update for', selectedSymbol, ':', data);
+ setTickerData(data);
+
+ // Update matching engine with WebSocket price for order monitoring
+ if (tradingMode === 'paper' && paperAdapter) {
+ const matchingEngine = (paperAdapter as any).matchingEngine;
+ if (matchingEngine && typeof matchingEngine.updatePriceFromWebSocket === 'function') {
+ matchingEngine.updatePriceFromWebSocket(selectedSymbol, {
+ bid: data.bid,
+ ask: data.ask,
+ last: data.last,
+ });
+ console.log('[TradingTab] Price fed to matching engine:', data.last);
+ }
+ }
+ } else {
+ console.log('[TradingTab] Ignoring ticker for', data.symbol, '- current symbol is', selectedSymbol);
+ }
+ }
+ }, [tickerMessage, tradingMode, paperAdapter, selectedSymbol]);
- // Update clock
+ // Update orderbook data
useEffect(() => {
- const timer = setInterval(() => {
- setCurrentTime(new Date());
- }, 1000);
- return () => clearInterval(timer);
- }, []);
+ if (!orderbookMessage || !orderbookMessage.data) return;
- // Initialize real adapter when provider changes
- useEffect(() => {
- const initAdapter = async () => {
- try {
- // Cleanup old adapter
- if (realAdapterRef.current) {
- await realAdapterRef.current.disconnect();
+ const data = orderbookMessage.data;
+ const messageType = data.messageType;
+ const dataSymbol = data.symbol || selectedSymbol;
+
+ // Only process if it's for the current selected symbol
+ if (dataSymbol !== selectedSymbol) {
+ console.log('[TradingTab] Ignoring orderbook for', dataSymbol, '- current symbol is', selectedSymbol);
+ return;
+ }
+
+ if (messageType === 'snapshot') {
+ setOrderBook({
+ bids: data.bids || [],
+ asks: data.asks || [],
+ symbol: dataSymbol,
+ checksum: data.checksum
+ });
+ setLastOrderBookUpdate(Date.now());
+ } else if (messageType === 'update') {
+ setOrderBook(prevBook => {
+ const newBook = { ...prevBook };
+
+ if (data.bids && data.bids.length > 0) {
+ const bidsMap = new Map(prevBook.bids.map(b => [b.price, b.size]));
+ data.bids.forEach((bid: OrderBookLevel) => {
+ if (bid.size === 0) {
+ bidsMap.delete(bid.price);
+ } else {
+ bidsMap.set(bid.price, bid.size);
+ }
+ });
+ newBook.bids = Array.from(bidsMap.entries())
+ .map(([price, size]) => ({ price, size }))
+ .sort((a, b) => b.price - a.price)
+ .slice(0, 25);
}
- // Create new adapter
- realAdapterRef.current = createExchangeAdapter(activeProvider as 'kraken' | 'hyperliquid');
- await realAdapterRef.current?.connect();
- console.log(`[TradingTab] ${activeProvider} adapter connected`);
- } catch (error) {
- console.error(`[TradingTab] Failed to initialize ${activeProvider} adapter:`, error);
- }
- };
+ if (data.asks && data.asks.length > 0) {
+ const asksMap = new Map(prevBook.asks.map(a => [a.price, a.size]));
+ data.asks.forEach((ask: OrderBookLevel) => {
+ if (ask.size === 0) {
+ asksMap.delete(ask.price);
+ } else {
+ asksMap.set(ask.price, ask.size);
+ }
+ });
+ newBook.asks = Array.from(asksMap.entries())
+ .map(([price, size]) => ({ price, size }))
+ .sort((a, b) => a.price - b.price)
+ .slice(0, 25);
+ }
- initAdapter();
+ newBook.checksum = data.checksum;
+ setLastOrderBookUpdate(Date.now());
+ return newBook;
+ });
+ }
+ }, [orderbookMessage, selectedSymbol]);
- return () => {
- if (realAdapterRef.current) {
- realAdapterRef.current.disconnect();
+ // Update trades data
+ useEffect(() => {
+ if (tradesMessage && tradesMessage.data) {
+ const data = tradesMessage.data;
+ const dataSymbol = data.symbol || selectedSymbol;
+
+ // Only add trades for current selected symbol
+ if (dataSymbol === selectedSymbol) {
+ setTradesData(prev => [data, ...prev].slice(0, 50));
+ } else {
+ console.log('[TradingTab] Ignoring trade for', dataSymbol, '- current symbol is', selectedSymbol);
}
- };
- }, [activeProvider]);
+ }
+ }, [tradesMessage, selectedSymbol]);
+
- // Initialize paper trading adapter when portfolio is created
+ // Load paper trading data
useEffect(() => {
- const initPaperTrading = async () => {
- if (!portfolioId || !realAdapterRef.current) {
- if (paperAdapterRef.current) {
- // Remove event listeners
- paperAdapterRef.current.off('order', () => {});
- paperAdapterRef.current.off('position', () => {});
- paperAdapterRef.current.off('balance', () => {});
- await paperAdapterRef.current.disconnect();
- paperAdapterRef.current = null;
- }
- setPositions([]);
- setBalance(0);
- setTotalPnL(0);
- setOrders([]);
- setTrades([]);
- setStats(null);
- return;
- }
+ const loadPaperTradingData = async () => {
+ if (tradingMode !== 'paper' || !paperAdapter) return;
try {
- setIsLoading(true);
-
- // Create paper trading adapter
- paperAdapterRef.current = createPaperTradingAdapter(
- {
- portfolioId,
- portfolioName: `${activeProvider.toUpperCase()} Paper Trading`,
- provider: activeProvider,
- assetClass: 'crypto',
- initialBalance: 100000,
- currency: 'USD',
- fees: {
- maker: activeProvider === 'kraken' ? 0.0002 : 0.0002,
- taker: activeProvider === 'kraken' ? 0.0005 : 0.0005,
- },
- slippage: {
- market: 0.001,
- limit: 0,
- },
- enableMarginTrading: true,
- defaultLeverage: 1,
- maxLeverage: activeProvider === 'hyperliquid' ? 50 : 5,
- },
- realAdapterRef.current
- );
-
- await paperAdapterRef.current.connect();
-
- // Set up event listeners for real-time updates
- const orderHandler = (event: any) => {
- console.log('[TradingTab] Order event:', event.data);
- refreshPaperTradingData();
- };
-
- const positionHandler = (event: any) => {
- console.log('[TradingTab] Position event:', event.data);
- refreshPaperTradingData();
- };
-
- const balanceHandler = (event: any) => {
- console.log('[TradingTab] Balance event:', event.data);
- refreshPaperTradingData();
- };
-
- paperAdapterRef.current.on('order', orderHandler);
- paperAdapterRef.current.on('position', positionHandler);
- paperAdapterRef.current.on('balance', balanceHandler);
- console.log('[TradingTab] Paper trading adapter connected');
-
- // Load initial data
- await refreshPaperTradingData();
- } catch (error) {
- console.error('[TradingTab] Failed to initialize paper trading:', error);
- } finally {
- setIsLoading(false);
- }
- };
+ console.log('[TradingTab] ==========================================');
+ console.log('[TradingTab] Loading paper trading data...');
+ console.log('[TradingTab] Portfolio ID:', (paperAdapter as any).paperConfig?.portfolioId);
+ console.log('[TradingTab] ==========================================');
+
+ // Fetch balance
+ const balanceData = await paperAdapter.fetchBalance();
+ console.log('[TradingTab] Balance:', balanceData);
+ const usdBalance = (balanceData.free as any)?.USD || 0;
+ const totalEquity = (balanceData.total as any)?.USD || 0;
+ setBalance(usdBalance);
+ setEquity(totalEquity);
+
+ // Fetch positions
+ const positionsData = await paperAdapter.fetchPositions();
+ console.log('[TradingTab] Positions RAW from adapter:', positionsData);
+ console.log('[TradingTab] Number of positions:', positionsData.length);
+
+ const mappedPositions: Position[] = positionsData.map((p: any) => {
+ console.log('[TradingTab] Mapping position:', {
+ symbol: p.symbol,
+ side: p.side,
+ contracts: p.contracts,
+ entryPrice: p.entryPrice,
+ markPrice: p.markPrice,
+ unrealizedPnl: p.unrealizedPnl,
+ percentage: p.percentage,
+ positionValue: p.info?.positionValue
+ });
- initPaperTrading();
+ return {
+ symbol: p.symbol,
+ side: p.side,
+ quantity: p.contracts,
+ entryPrice: p.entryPrice,
+ positionValue: p.info?.positionValue || (p.entryPrice * p.contracts),
+ currentPrice: p.markPrice,
+ unrealizedPnl: p.unrealizedPnl,
+ pnlPercent: p.percentage || 0,
+ };
+ });
+
+ console.log('[TradingTab] Mapped positions:', mappedPositions);
+ console.log('[TradingTab] Setting positions state with', mappedPositions.length, 'positions');
+ setPositions(mappedPositions);
+
+ // Fetch open orders
+ const ordersData = await paperAdapter.fetchOpenOrders();
+ console.log('[TradingTab] Orders RAW from adapter:', ordersData);
+ console.log('[TradingTab] Number of orders:', ordersData.length);
+
+ const mappedOrders: Order[] = ordersData.map((o: any) => {
+ console.log('[TradingTab] Mapping order:', {
+ id: o.id,
+ symbol: o.symbol,
+ side: o.side,
+ type: o.type,
+ amount: o.amount,
+ price: o.price,
+ status: o.status
+ });
- return () => {
- if (paperAdapterRef.current) {
- paperAdapterRef.current.off('order', () => {});
- paperAdapterRef.current.off('position', () => {});
- paperAdapterRef.current.off('balance', () => {});
- paperAdapterRef.current.disconnect();
+ return {
+ id: o.id,
+ symbol: o.symbol,
+ side: o.side,
+ type: o.type,
+ quantity: o.amount,
+ price: o.price,
+ status: o.status,
+ createdAt: o.datetime,
+ };
+ });
+
+ console.log('[TradingTab] Mapped orders:', mappedOrders);
+ console.log('[TradingTab] Setting orders state with', mappedOrders.length, 'orders');
+ setOrders(mappedOrders);
+
+ // Fetch trades
+ const tradesData = await paperAdapter.fetchMyTrades(undefined, undefined, 50);
+ console.log('[TradingTab] Trades:', tradesData);
+ console.log('[TradingTab] Trades details:');
+ tradesData.forEach((trade: any, idx: number) => {
+ console.log(` Trade ${idx + 1}:`, {
+ side: trade.side,
+ amount: trade.amount,
+ price: trade.price,
+ cost: trade.cost,
+ fee: trade.fee?.cost,
+ timestamp: trade.datetime
+ });
+ });
+ setTrades(tradesData);
+
+ // Fetch statistics
+ if (typeof (paperAdapter as any).getStatistics === 'function') {
+ const statsData = await (paperAdapter as any).getStatistics();
+ console.log('[TradingTab] Stats:', statsData);
+ setStats(statsData);
+ }
+ } catch (error) {
+ console.error('[TradingTab] Failed to load paper trading data:', error);
}
};
- }, [portfolioId, activeProvider]);
- // Refresh paper trading data
- const refreshPaperTradingData = useCallback(async () => {
- if (!paperAdapterRef.current || !portfolioId) return;
+ loadPaperTradingData();
- try {
- const [balanceData, positionsData, ordersData, tradesData] = await Promise.all([
- paperAdapterRef.current.fetchBalance(),
- paperAdapterRef.current.fetchPositions(),
- paperTradingDatabase.getPortfolioOrders(portfolioId),
- paperTradingDatabase.getPortfolioTrades(portfolioId, 100),
- ]);
-
- // Calculate balance and P&L
- const usdBalance = (balanceData.free as any)?.['USD'] || (balanceData.free as any)?.['USDC'] || 100000;
- const unrealizedPnL = positionsData.reduce((sum: number, p: any) => sum + (p.unrealizedPnl || 0), 0);
-
- // Calculate stats
- const closedTrades = tradesData.filter((t: any) => t.side === 'sell');
- const totalPnL = unrealizedPnL + closedTrades.reduce((sum: number, t: any) => sum + (t.price * t.quantity), 0);
- const winningTrades = closedTrades.filter((t: any) => t.price * t.quantity > 0).length;
- const losingTrades = closedTrades.filter((t: any) => t.price * t.quantity < 0).length;
- const winRate = closedTrades.length > 0 ? (winningTrades / closedTrades.length) * 100 : 0;
- const totalFees = tradesData.reduce((sum: number, t: any) => sum + t.fee, 0);
- const wins = closedTrades.filter((t: any) => t.price * t.quantity > 0).map((t: any) => t.price * t.quantity);
- const losses = closedTrades.filter((t: any) => t.price * t.quantity < 0).map((t: any) => Math.abs(t.price * t.quantity));
- const averageWin = wins.length > 0 ? wins.reduce((a: number, b: number) => a + b, 0) / wins.length : 0;
- const averageLoss = losses.length > 0 ? losses.reduce((a: number, b: number) => a + b, 0) / losses.length : 0;
- const largestWin = wins.length > 0 ? Math.max(...wins) : 0;
- const largestLoss = losses.length > 0 ? Math.max(...losses) : 0;
- const totalWins = wins.reduce((a: number, b: number) => a + b, 0);
- const totalLosses = losses.reduce((a: number, b: number) => a + b, 0);
- const profitFactor = totalLosses > 0 ? totalWins / totalLosses : 0;
+ // Refresh every 2 seconds (not too spammy)
+ const interval = setInterval(loadPaperTradingData, 2000);
+ return () => clearInterval(interval);
+ }, [tradingMode, paperAdapter]);
- setBalance(usdBalance);
- setPositions(positionsData);
- setTotalPnL(unrealizedPnL);
- setOrders(ordersData);
- setTrades(tradesData);
- setStats({
- totalTrades: closedTrades.length,
- winningTrades,
- losingTrades,
- winRate,
- totalPnL,
- realizedPnL: totalPnL - unrealizedPnL,
- unrealizedPnL,
- totalFees,
- averageWin,
- averageLoss,
- largestWin,
- largestLoss,
- profitFactor,
- });
- } catch (error) {
- console.error('[TradingTab] Failed to refresh paper trading data:', error);
+ // Update slippage when it changes
+ useEffect(() => {
+ if (paperAdapter) {
+ (paperAdapter as any).paperConfig.slippage.market = slippage;
+ console.log('[TradingTab] Slippage updated to:', slippage);
}
- }, [portfolioId]);
+ }, [slippage, paperAdapter]);
- // Auto-refresh positions every 5 seconds
+ // Update fees when they change
useEffect(() => {
- if (!portfolioId) return;
+ if (paperAdapter) {
+ (paperAdapter as any).paperConfig.fees.maker = makerFee;
+ (paperAdapter as any).paperConfig.fees.taker = takerFee;
+ console.log('[TradingTab] Fees updated - Maker:', makerFee, 'Taker:', takerFee);
+ }
+ }, [makerFee, takerFee, paperAdapter]);
- const interval = setInterval(() => {
- refreshPaperTradingData();
- }, 5000);
+ // Fetch available markets from broker
+ useEffect(() => {
+ const fetchMarkets = async () => {
+ if (!activeAdapter) return;
- return () => clearInterval(interval);
- }, [portfolioId, refreshPaperTradingData]);
+ setIsLoadingSymbols(true);
+ try {
+ console.log('[TradingTab] Fetching markets from adapter...');
+ const markets = await activeAdapter.fetchMarkets();
+ console.log('[TradingTab] Markets fetched:', markets.length);
+
+ // Extract symbols and filter for spot/USD pairs
+ const symbols = markets
+ .filter((m: any) => {
+ // Filter for active, spot markets
+ return m.active && m.spot && (m.quote === 'USD' || m.quote === 'USDT' || m.quote === 'USDC');
+ })
+ .map((m: any) => m.symbol)
+ .sort();
+
+ console.log('[TradingTab] Available symbols:', symbols.length);
+ setAvailableSymbols(symbols);
+ } catch (error) {
+ console.error('[TradingTab] Failed to fetch markets:', error);
+ // Fallback to default symbols
+ setAvailableSymbols(defaultSymbols);
+ } finally {
+ setIsLoadingSymbols(false);
+ }
+ };
- // Get current price from ticker
- const { message: tickerMessage } = useWebSocket(
- isConnected ? `${activeProvider}.ticker.${selectedSymbol}` : null,
- null,
- { autoSubscribe: true }
- );
+ fetchMarkets();
+ }, [activeAdapter, defaultSymbols]);
- const currentPrice = tickerMessage?.data?.last || tickerMessage?.data?.close || tickerMessage?.data?.mid;
+ // Close dropdown when clicking outside
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ const target = event.target as HTMLElement;
+ if (showSymbolDropdown && !target.closest('[data-symbol-selector]')) {
+ setShowSymbolDropdown(false);
+ setSearchQuery('');
+ }
+ };
- // Handle portfolio creation
- const handlePortfolioChange = useCallback((newPortfolioId: string | null) => {
- setPortfolioId(newPortfolioId);
- }, []);
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }, [showSymbolDropdown]);
// Handle order placement
- const handlePlaceOrder = async (order: {
- symbol: string;
- side: 'buy' | 'sell';
- type: string;
- quantity: number;
- price?: number;
- stopPrice?: number;
- }) => {
- if (!portfolioId || !paperAdapterRef.current) {
- throw new Error('Paper trading not enabled');
+ const handlePlaceOrder = useCallback(async (orderRequest: OrderRequest) => {
+ console.log('[TradingTab] ========== ORDER PLACEMENT START ==========');
+ console.log('[TradingTab] Order request:', orderRequest);
+ console.log('[TradingTab] Slippage:', slippage);
+ console.log('[TradingTab] Trading mode:', tradingMode);
+ console.log('[TradingTab] paperAdapter:', paperAdapter ? 'EXISTS' : 'NULL');
+ console.log('[TradingTab] paperAdapter connected:', paperAdapter?.isConnected());
+
+ if (!paperAdapter) {
+ const errorMsg = 'Paper trading adapter not available. Please wait for initialization.';
+ console.error('[TradingTab]', errorMsg);
+ alert(errorMsg);
+ throw new Error(errorMsg);
}
- try {
- setIsLoading(true);
-
- await paperAdapterRef.current.createOrder(
- order.symbol,
- order.type as any,
- order.side,
- order.quantity,
- order.price,
- order.stopPrice ? { stopPrice: order.stopPrice } : undefined
- );
-
- // Refresh data
- await refreshPaperTradingData();
- } catch (error) {
- console.error('[TradingTab] Failed to place order:', error);
- throw error;
- } finally {
- setIsLoading(false);
+ if (!paperAdapter.isConnected()) {
+ const errorMsg = 'Paper trading adapter not connected. Please wait.';
+ console.error('[TradingTab]', errorMsg);
+ alert(errorMsg);
+ throw new Error(errorMsg);
}
- };
- // Handle position close
- const handleClosePosition = async (positionId: string) => {
- if (!portfolioId || !paperAdapterRef.current) return;
+ setIsPlacingOrder(true);
try {
- setIsLoading(true);
-
- // Find position to close
- const position = positions.find((p) => p.id === positionId);
- if (!position) {
- throw new Error('Position not found');
- }
-
- // Close position by placing opposite order
- const closeSide = position.side === 'long' ? 'sell' : 'buy';
- await paperAdapterRef.current.createOrder(
- position.symbol,
- 'market',
- closeSide,
- Math.abs(position.contracts || 0),
- undefined,
- { reduceOnly: true }
+ console.log('[TradingTab] Calling paperAdapter.createOrder...');
+
+ const order = await paperAdapter.createOrder(
+ orderRequest.symbol,
+ orderRequest.type,
+ orderRequest.side,
+ orderRequest.quantity,
+ orderRequest.price,
+ { stopPrice: orderRequest.stopPrice }
);
- // Refresh data
- await refreshPaperTradingData();
+ console.log('[TradingTab] ✓ Order created successfully:', order);
+ console.log('[TradingTab] Order ID:', order.id);
+ console.log('[TradingTab] Order status:', order.status);
+
+ // Immediate refresh
+ console.log('[TradingTab] Refreshing orders and balance...');
+
+ const ordersData = await paperAdapter.fetchOpenOrders();
+ console.log('[TradingTab] fetchOpenOrders returned:', ordersData);
+ console.log('[TradingTab] Number of orders:', ordersData.length);
+
+ const mappedOrders: Order[] = ordersData.map((o: any) => ({
+ id: o.id,
+ symbol: o.symbol,
+ side: o.side,
+ type: o.type,
+ quantity: o.amount,
+ price: o.price,
+ status: o.status,
+ createdAt: o.datetime,
+ }));
+
+ console.log('[TradingTab] Setting orders state:', mappedOrders);
+ setOrders(mappedOrders);
+
+ const balanceData = await paperAdapter.fetchBalance();
+ console.log('[TradingTab] New balance:', balanceData);
+ const usdBalance = (balanceData.free as any)?.USD || 0;
+ setBalance(usdBalance);
+
+ alert(`Order placed successfully! ID: ${order.id}`);
+ console.log('[TradingTab] ========== ORDER PLACEMENT END ==========');
} catch (error) {
- console.error('[TradingTab] Failed to close position:', error);
+ console.error('[TradingTab] ✗ Order placement failed:', error);
+ console.error('[TradingTab] Error details:', error);
+ alert(`Order failed: ${(error as Error).message}`);
+ throw error;
} finally {
- setIsLoading(false);
+ setIsPlacingOrder(false);
}
- };
+ }, [paperAdapter, tradingMode]);
// Handle order cancellation
- const handleCancelOrder = async (orderId: string) => {
- if (!portfolioId || !paperAdapterRef.current) return;
+ const handleCancelOrder = useCallback(async (orderId: string, symbol: string) => {
+ if (!paperAdapter) return;
try {
- setIsLoading(true);
- // Find the order's symbol first
- const order = orders.find((o) => o.id === orderId);
- if (!order) {
- throw new Error('Order not found');
- }
- await paperAdapterRef.current.cancelOrder(orderId, order.symbol);
- await refreshPaperTradingData();
+ console.log('[TradingTab] Cancelling order:', orderId);
+ await paperAdapter.cancelOrder(orderId, symbol);
+ console.log('[TradingTab] ✓ Order cancelled');
+
+ // Refresh orders immediately
+ const ordersData = await paperAdapter.fetchOpenOrders();
+ const mappedOrders: Order[] = ordersData.map((o: any) => ({
+ id: o.id,
+ symbol: o.symbol,
+ side: o.side,
+ type: o.type,
+ quantity: o.amount,
+ price: o.price,
+ status: o.status,
+ createdAt: o.datetime,
+ }));
+ setOrders(mappedOrders);
} catch (error) {
- console.error('[TradingTab] Failed to cancel order:', error);
- } finally {
- setIsLoading(false);
+ console.error('[TradingTab] ✗ Cancel failed:', error);
}
- };
+ }, [paperAdapter]);
+
+ // Handle balance reset
+ const handleResetBalance = useCallback(async () => {
+ if (!paperAdapter) return;
+
+ const confirmed = window.confirm(
+ '⚠️ Reset Paper Trading Account?\n\n' +
+ 'This will:\n' +
+ '• Close all open positions\n' +
+ '• Cancel all pending orders\n' +
+ '• Reset balance to initial capital\n' +
+ '• Clear trade history\n\n' +
+ 'This action cannot be undone!'
+ );
- // Handle portfolio reset
- const handleReset = async () => {
- if (!portfolioId) return;
+ if (!confirmed) return;
- setIsResetting(true);
try {
- // For now, just recreate the adapter
- // TODO: Implement proper reset in PaperTradingDatabase
- if (paperAdapterRef.current) {
- await paperAdapterRef.current.disconnect();
+ console.log('[TradingTab] Resetting paper trading account...');
+
+ // Call reset method on paper adapter
+ if (typeof (paperAdapter as any).resetAccount === 'function') {
+ await (paperAdapter as any).resetAccount();
+ console.log('[TradingTab] ✓ Account reset successfully');
+ alert('✓ Paper trading account has been reset!');
+ } else {
+ console.error('[TradingTab] resetAccount method not found on paperAdapter');
+ alert('❌ Reset method not available');
}
-
- // Trigger re-initialization
- const currentId = portfolioId;
- setPortfolioId(null);
- setTimeout(() => setPortfolioId(currentId), 100);
- } finally {
- setIsResetting(false);
+ } catch (error) {
+ console.error('[TradingTab] ✗ Reset failed:', error);
+ alert(`❌ Reset failed: ${(error as Error).message}`);
}
- };
+ }, [paperAdapter]);
- const { ORANGE, WHITE, RED, GREEN, GRAY, DARK_BG, PANEL_BG, CYAN } = BLOOMBERG_COLORS;
+ const currentPrice = tickerData?.last || orderBook.asks[0]?.price || 0;
return (
<div style={{
+ padding: '20px',
+ color: 'white',
+ backgroundColor: '#0d0d0d',
height: '100%',
- backgroundColor: DARK_BG,
- color: WHITE,
- fontFamily: 'Consolas, monospace',
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column'
+ overflow: 'auto'
}}>
- <style>{`
- *::-webkit-scrollbar { width: 8px; height: 8px; }
- *::-webkit-scrollbar-track { background: #1a1a1a; }
- *::-webkit-scrollbar-thumb { background: #404040; border-radius: 4px; }
- *::-webkit-scrollbar-thumb:hover { background: #525252; }
- `}</style>
-
- {/* Header Bar */}
- <div style={{
- backgroundColor: PANEL_BG,
- borderBottom: `1px solid ${GRAY}`,
- padding: '8px 12px',
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <TrendingUp size={16} style={{ color: ORANGE }} />
- <span style={{ color: ORANGE, fontWeight: 'bold', fontSize: '14px' }}>
- FINCEPT TRADING TERMINAL
- </span>
- <span style={{ color: WHITE }}>|</span>
- <span style={{ color: portfolioId ? GREEN : GRAY, fontSize: '10px' }}>
- ● {portfolioId ? 'PAPER TRADING' : 'VIEW ONLY'}
- </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', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px', gap: '16px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flex: 1 }}>
+ <h1 style={{ fontSize: '24px', margin: 0 }}>
+ Trading
+ </h1>
+
+ {/* Symbol Selector with Search */}
+ <div style={{ position: 'relative', minWidth: '200px' }} data-symbol-selector>
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '8px 12px',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #333',
+ borderRadius: '6px',
+ cursor: 'pointer'
+ }}
+ onClick={() => setShowSymbolDropdown(!showSymbolDropdown)}
+ >
+ <span style={{ fontSize: '14px', fontWeight: 'bold', flex: 1 }}>
+ {selectedSymbol}
+ </span>
+ <span style={{ fontSize: '12px', color: '#666' }}>▼</span>
+ </div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Activity size={14} style={{ color: GREEN }} />
- <span style={{ color: GREEN, fontSize: '10px', fontWeight: 'bold' }}>
- LIVE MARKET DATA
- </span>
+ {/* Dropdown */}
+ {showSymbolDropdown && (
+ <div style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ right: 0,
+ marginTop: '4px',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #333',
+ borderRadius: '6px',
+ maxHeight: '400px',
+ overflow: 'hidden',
+ zIndex: 1000,
+ boxShadow: '0 4px 12px rgba(0,0,0,0.5)'
+ }}>
+ {/* Search Input */}
+ <div style={{ padding: '12px', borderBottom: '1px solid #333' }}>
+ <input
+ type="text"
+ placeholder="Search pairs... (e.g., BTC, ETH)"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ autoFocus
+ style={{
+ width: '100%',
+ padding: '8px 12px',
+ backgroundColor: '#0d0d0d',
+ color: 'white',
+ border: '1px solid #333',
+ borderRadius: '4px',
+ fontSize: '13px',
+ outline: 'none'
+ }}
+ />
+ </div>
+
+ {/* Loading State */}
+ {isLoadingSymbols ? (
+ <div style={{ padding: '20px', textAlign: 'center', color: '#666', fontSize: '13px' }}>
+ Loading markets...
+ </div>
+ ) : (
+ /* Symbol List */
+ <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
+ {availableSymbols
+ .filter(symbol =>
+ symbol.toLowerCase().includes(searchQuery.toLowerCase())
+ )
+ .map(symbol => (
+ <div
+ key={symbol}
+ onClick={() => {
+ setSelectedSymbol(symbol);
+ setShowSymbolDropdown(false);
+ setSearchQuery('');
+ }}
+ style={{
+ padding: '10px 16px',
+ cursor: 'pointer',
+ fontSize: '13px',
+ backgroundColor: symbol === selectedSymbol ? '#f59e0b20' : 'transparent',
+ color: symbol === selectedSymbol ? '#f59e0b' : 'white',
+ borderBottom: '1px solid #222',
+ transition: 'background-color 0.15s'
+ }}
+ onMouseEnter={(e) => {
+ if (symbol !== selectedSymbol) {
+ e.currentTarget.style.backgroundColor = '#ffffff10';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (symbol !== selectedSymbol) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ {symbol}
+ </div>
+ ))
+ }
+ {/* No Results */}
+ {availableSymbols.filter(s => s.toLowerCase().includes(searchQuery.toLowerCase())).length === 0 && (
+ <div style={{ padding: '20px', textAlign: 'center', color: '#666', fontSize: '13px' }}>
+ No pairs found matching "{searchQuery}"
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
</div>
+
+ {/* Mode Badge */}
+ <span style={{
+ padding: '4px 12px',
+ backgroundColor: tradingMode === 'paper' ? '#10b98120' : '#dc262620',
+ color: tradingMode === 'paper' ? '#10b981' : '#dc2626',
+ border: `1px solid ${tradingMode === 'paper' ? '#10b981' : '#dc2626'}`,
+ borderRadius: '4px',
+ fontSize: '12px',
+ fontWeight: 'bold'
+ }}>
+ {tradingMode === 'paper' ? '📝 PAPER' : '🔴 LIVE'}
+ </span>
</div>
+
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ padding: '8px 16px',
+ backgroundColor: '#1a1a1a',
+ color: 'white',
+ border: '1px solid #333',
+ borderRadius: '6px',
+ cursor: 'pointer',
+ fontSize: '13px'
+ }}
+ >
+ ⚙️ Settings
+ </button>
</div>
- {/* Provider Switcher */}
- <ProviderSwitcher />
+ {/* Settings Panel */}
+ {showSettings && (
+ <div style={{
+ marginBottom: '20px',
+ padding: '16px',
+ backgroundColor: '#1a1a1a',
+ borderRadius: '6px',
+ border: '1px solid #333'
+ }}>
+ <h3 style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '16px' }}>Trading Settings</h3>
+
+ {/* Slippage Control */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px' }}>
+ <label style={{ fontSize: '13px', color: '#999', minWidth: '100px' }}>
+ Slippage (%):
+ </label>
+ <input
+ type="number"
+ value={slippage * 100}
+ onChange={(e) => setSlippage(parseFloat(e.target.value) / 100)}
+ step="0.01"
+ min="0"
+ max="5"
+ style={{
+ padding: '6px 12px',
+ backgroundColor: '#0d0d0d',
+ color: 'white',
+ border: '1px solid #333',
+ borderRadius: '4px',
+ width: '100px',
+ fontSize: '13px'
+ }}
+ />
+ <span style={{ fontSize: '12px', color: '#666' }}>
+ (0% = exact price, 0.1% = realistic)
+ </span>
+ </div>
+
+ {/* Maker Fee Control */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px' }}>
+ <label style={{ fontSize: '13px', color: '#999', minWidth: '100px' }}>
+ Maker Fee (%):
+ </label>
+ <input
+ type="number"
+ value={makerFee * 100}
+ onChange={(e) => setMakerFee(parseFloat(e.target.value) / 100)}
+ step="0.001"
+ min="0"
+ max="1"
+ style={{
+ padding: '6px 12px',
+ backgroundColor: '#0d0d0d',
+ color: 'white',
+ border: '1px solid #333',
+ borderRadius: '4px',
+ width: '100px',
+ fontSize: '13px'
+ }}
+ />
+ <span style={{ fontSize: '12px', color: '#666' }}>
+ (0.02% Kraken default)
+ </span>
+ </div>
- {/* Paper Trading Panel */}
- <PaperTradingPanel
- portfolioId={portfolioId}
- balance={balance}
- totalPnL={totalPnL}
- onPortfolioChange={handlePortfolioChange}
- onReset={handleReset}
- isResetting={isResetting}
- />
+ {/* Taker Fee Control */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '16px' }}>
+ <label style={{ fontSize: '13px', color: '#999', minWidth: '100px' }}>
+ Taker Fee (%):
+ </label>
+ <input
+ type="number"
+ value={takerFee * 100}
+ onChange={(e) => setTakerFee(parseFloat(e.target.value) / 100)}
+ step="0.001"
+ min="0"
+ max="1"
+ style={{
+ padding: '6px 12px',
+ backgroundColor: '#0d0d0d',
+ color: 'white',
+ border: '1px solid #333',
+ borderRadius: '4px',
+ width: '100px',
+ fontSize: '13px'
+ }}
+ />
+ <span style={{ fontSize: '12px', color: '#666' }}>
+ (0.05% Kraken default)
+ </span>
+ </div>
- {/* Symbol Selector */}
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- backgroundColor: PANEL_BG,
- padding: '8px 12px',
- borderBottom: `1px solid ${GRAY}`,
- flexShrink: 0
- }}>
- <span style={{ fontSize: '10px', color: GRAY, fontWeight: 'bold', textTransform: 'uppercase' }}>
- {activeProvider === 'kraken' ? 'Pair:' : 'Symbol:'}
- </span>
- <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
- {popularSymbols.map(symbol => (
+ {/* Reset Balance Button */}
+ <div style={{
+ borderTop: '1px solid #333',
+ paddingTop: '16px',
+ marginTop: '4px'
+ }}>
<button
- key={symbol}
- onClick={() => setSelectedSymbol(symbol)}
+ onClick={handleResetBalance}
style={{
- padding: '4px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
- textTransform: 'uppercase',
- backgroundColor: selectedSymbol === symbol ? ORANGE : '#2d2d2d',
- color: selectedSymbol === symbol ? WHITE : GRAY,
- border: selectedSymbol === symbol ? `1px solid ${ORANGE}` : '1px solid #404040',
+ padding: '8px 16px',
+ backgroundColor: '#dc262620',
+ color: '#dc2626',
+ border: '1px solid #dc2626',
+ borderRadius: '6px',
cursor: 'pointer',
+ fontSize: '13px',
+ fontWeight: 'bold',
+ width: '100%',
transition: 'all 0.2s'
}}
- onMouseEnter={(e) => {
- if (selectedSymbol !== symbol) {
- e.currentTarget.style.backgroundColor = '#404040';
- e.currentTarget.style.borderColor = GRAY;
- }
+ onMouseOver={(e) => {
+ e.currentTarget.style.backgroundColor = '#dc2626';
+ e.currentTarget.style.color = 'white';
}}
- onMouseLeave={(e) => {
- if (selectedSymbol !== symbol) {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
- e.currentTarget.style.borderColor = '#404040';
- }
+ onMouseOut={(e) => {
+ e.currentTarget.style.backgroundColor = '#dc262620';
+ e.currentTarget.style.color = '#dc2626';
}}
>
- {symbol}
+ 🔄 Reset Paper Trading Account
</button>
- ))}
- </div>
- <input
- type="text"
- placeholder={activeProvider === 'kraken' ? 'BTC/USD' : 'BTC/USDC:USDC'}
- value={selectedSymbol}
- onChange={(e) => setSelectedSymbol(e.target.value.toUpperCase())}
- style={{
- marginLeft: '12px',
- padding: '4px 8px',
- backgroundColor: '#2d2d2d',
- color: WHITE,
- border: '1px solid #404040',
- fontSize: '11px',
- outline: 'none',
- width: '150px'
- }}
- onFocus={(e) => e.currentTarget.style.borderColor = ORANGE}
- onBlur={(e) => e.currentTarget.style.borderColor = '#404040'}
- />
- <span style={{ fontSize: '10px', color: isConnected ? GREEN : GRAY, marginLeft: '12px' }}>
- {isConnected ? '● CONNECTED' : '● CONNECTING...'}
- </span>
- </div>
-
- {/* Main Trading Layout */}
- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* Left Panel - Ticker & Trades */}
- <div style={{
- width: '280px',
- display: 'flex',
- flexDirection: 'column',
- borderRight: `1px solid ${GRAY}`,
- backgroundColor: PANEL_BG
- }}>
- <TickerDisplay symbol={selectedSymbol} provider={activeProvider} />
- <TradesFeed symbol={selectedSymbol} provider={activeProvider} />
+ <div style={{ fontSize: '11px', color: '#666', marginTop: '8px', textAlign: 'center' }}>
+ Resets balance, closes all positions, and clears history
+ </div>
+ </div>
</div>
-
- {/* Center Panel - Chart Placeholder */}
- <div style={{
- flex: 1,
- display: 'flex',
- flexDirection: 'column',
- backgroundColor: DARK_BG
- }}>
- <div style={{
- flex: 1,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- borderBottom: `1px solid ${GRAY}`
- }}>
- <div style={{ textAlign: 'center', color: GRAY }}>
- <div style={{ fontSize: '48px', marginBottom: '12px' }}>📊</div>
- <div style={{ fontSize: '14px', fontWeight: 'bold', color: WHITE, marginBottom: '8px' }}>
- ADVANCED CHARTING
- </div>
- <div style={{ fontSize: '11px', color: GRAY }}>
- TradingView Integration Coming Soon
+ )}
+
+ {/* Status Bar */}
+ <div style={{ marginBottom: '20px', padding: '12px', backgroundColor: '#1a1a1a', borderRadius: '6px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '16px', fontSize: '13px' }}>
+ <div>
+ <div style={{ color: '#666', marginBottom: '4px' }}>Symbol</div>
+ <div style={{ fontWeight: 'bold', fontSize: '16px' }}>{selectedSymbol}</div>
+ </div>
+ <div>
+ <div style={{ color: '#666', marginBottom: '4px' }}>Last Price</div>
+ <div style={{ fontWeight: 'bold', fontSize: '16px', color: tickerData ? '#10b981' : '#666' }}>
+ {tickerData ? `$${tickerData.last?.toFixed(2) || '0.00'}` : 'Loading...'}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: '#666', marginBottom: '4px' }}>Bid / Ask</div>
+ <div style={{ fontWeight: 'bold', fontSize: '13px' }}>
+ {tickerData ? (
+ <>
+ <span style={{ color: '#10b981' }}>${tickerData.bid?.toFixed(2) || '0.00'}</span>
+ {' / '}
+ <span style={{ color: '#dc2626' }}>${tickerData.ask?.toFixed(2) || '0.00'}</span>
+ </>
+ ) : (
+ <span style={{ color: '#666' }}>--</span>
+ )}
+ </div>
+ </div>
+ {tradingMode === 'paper' && (
+ <>
+ <div>
+ <div style={{ color: '#666', marginBottom: '4px' }}>Balance</div>
+ <div style={{ fontWeight: 'bold' }}>${balance.toFixed(2)}</div>
</div>
- <div style={{ fontSize: '10px', marginTop: '8px', color: GRAY }}>
- Showing {selectedSymbol} on {activeProvider.toUpperCase()}
+ <div>
+ <div style={{ color: '#666', marginBottom: '4px' }}>Equity</div>
+ <div style={{ fontWeight: 'bold' }}>${equity.toFixed(2)}</div>
</div>
+ </>
+ )}
+ <div>
+ <div style={{ color: '#666', marginBottom: '4px' }}>Status</div>
+ <div style={{ fontWeight: 'bold', color: activeAdapter?.isConnected() ? '#10b981' : '#dc2626' }}>
+ {isConnecting ? 'Connecting...' : activeAdapter?.isConnected() ? 'Connected' : 'Disconnected'}
</div>
</div>
+ </div>
+ </div>
+
+ {/* Main Grid */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 350px', gap: '20px', marginBottom: '20px' }}>
+ {/* Left Column: Positions */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
+ {/* Trading Activity Tabs (Paper Trading) */}
+ {tradingMode === 'paper' && (
+ <div style={{ padding: '16px', backgroundColor: '#1a1a1a', borderRadius: '6px' }}>
+ {/* Tab Headers */}
+ <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', borderBottom: '1px solid #333' }}>
+ {(['positions', 'orders', 'trades', 'stats'] as const).map((tab) => (
+ <button
+ key={tab}
+ onClick={() => setActiveTab(tab)}
+ style={{
+ padding: '10px 16px',
+ backgroundColor: activeTab === tab ? '#f59e0b20' : 'transparent',
+ color: activeTab === tab ? '#f59e0b' : '#999',
+ border: 'none',
+ borderBottom: activeTab === tab ? '2px solid #f59e0b' : '2px solid transparent',
+ cursor: 'pointer',
+ fontSize: '13px',
+ fontWeight: activeTab === tab ? 'bold' : 'normal',
+ textTransform: 'capitalize',
+ transition: 'all 0.2s'
+ }}
+ >
+ {tab}
+ {tab === 'positions' && ` (${positions.length})`}
+ {tab === 'orders' && ` (${orders.length})`}
+ {tab === 'trades' && ` (${trades.length})`}
+ </button>
+ ))}
+ </div>
- {/* Bottom Panel - Positions/Orders/Trades */}
- {portfolioId && (
- <div style={{ display: 'flex', flexDirection: 'column', maxHeight: '400px' }}>
- <PositionsTable
- positions={positions}
- onClosePosition={handleClosePosition}
- isLoading={isLoading}
- />
- <OrdersTable
- orders={orders}
- onCancelOrder={handleCancelOrder}
- isLoading={isLoading}
- />
- <TradeHistory trades={trades} />
+ {/* Positions Tab */}
+ {activeTab === 'positions' && (
+ <div>
+ {positions.length === 0 ? (
+ <div style={{ padding: '40px', textAlign: 'center', color: '#666', fontSize: '13px' }}>
+ No open positions
+ </div>
+ ) : (
+ <table style={{ width: '100%', fontSize: '12px', fontFamily: 'monospace', borderCollapse: 'collapse' }}>
+ <thead>
+ <tr style={{ borderBottom: '1px solid #333' }}>
+ <th style={{ textAlign: 'left', padding: '8px', color: '#666' }}>Symbol</th>
+ <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Side</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Qty</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Value</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Entry</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Current</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>PnL ($)</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>PnL (%)</th>
+ </tr>
+ </thead>
+ <tbody>
+ {positions.map((pos, idx) => {
+ // Calculate price difference
+ const priceDiff = pos.entryPrice - pos.currentPrice;
+
+ // For SHORT: profit when price goes DOWN (priceDiff > 0)
+ // For LONG: profit when price goes UP (priceDiff < 0)
+ const totalPnlDollar = pos.side === 'short'
+ ? priceDiff * pos.quantity
+ : -priceDiff * pos.quantity;
+
+ // Calculate P&L percentage based on position value
+ const pnlPercent = pos.positionValue > 0 ? (totalPnlDollar / pos.positionValue) * 100 : 0;
+
+ return (
+ <tr key={idx} style={{ borderBottom: '1px solid #222' }}>
+ <td style={{ padding: '8px' }}>{pos.symbol}</td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <span style={{
+ padding: '4px 8px',
+ borderRadius: '4px',
+ backgroundColor: pos.side === 'long' ? '#10b98120' : '#dc262620',
+ color: pos.side === 'long' ? '#10b981' : '#dc2626',
+ fontSize: '11px',
+ fontWeight: 'bold'
+ }}>
+ {pos.side.toUpperCase()}
+ </span>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>{pos.quantity.toFixed(4)}</td>
+ <td style={{ padding: '8px', textAlign: 'right', color: '#999' }}>
+ ${pos.positionValue.toFixed(2)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>${pos.entryPrice.toFixed(2)}</td>
+ <td style={{ padding: '8px', textAlign: 'right', fontWeight: 'bold' }}>
+ ${pos.currentPrice.toFixed(2)}
+ </td>
+ <td style={{
+ padding: '8px',
+ textAlign: 'right',
+ color: totalPnlDollar >= 0 ? '#10b981' : '#dc2626',
+ fontWeight: 'bold'
+ }}>
+ {totalPnlDollar >= 0 ? '+' : '-'}${Math.abs(totalPnlDollar).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </td>
+ <td style={{
+ padding: '8px',
+ textAlign: 'right',
+ color: pnlPercent >= 0 ? '#10b981' : '#dc2626',
+ fontWeight: 'bold'
+ }}>
+ {pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(2)}%
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ )}
+ </div>
+ )}
+
+ {/* Orders Tab */}
+ {activeTab === 'orders' && (
+ <div>
+ {orders.length === 0 ? (
+ <div style={{ padding: '40px', textAlign: 'center', color: '#666', fontSize: '13px' }}>
+ No open orders
+ </div>
+ ) : (
+ <table style={{ width: '100%', fontSize: '12px', fontFamily: 'monospace', borderCollapse: 'collapse' }}>
+ <thead>
+ <tr style={{ borderBottom: '1px solid #333' }}>
+ <th style={{ textAlign: 'left', padding: '8px', color: '#666' }}>Symbol</th>
+ <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Type</th>
+ <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Side</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Qty</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Price</th>
+ <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Status</th>
+ <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Action</th>
+ </tr>
+ </thead>
+ <tbody>
+ {orders.map((order) => (
+ <tr key={order.id} style={{ borderBottom: '1px solid #222' }}>
+ <td style={{ padding: '8px' }}>{order.symbol}</td>
+ <td style={{ padding: '8px', textAlign: 'center', textTransform: 'uppercase', fontSize: '11px' }}>
+ {order.type}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <span style={{
+ padding: '4px 8px',
+ borderRadius: '4px',
+ backgroundColor: order.side === 'buy' ? '#10b98120' : '#dc262620',
+ color: order.side === 'buy' ? '#10b981' : '#dc2626',
+ fontSize: '11px',
+ fontWeight: 'bold'
+ }}>
+ {order.side.toUpperCase()}
+ </span>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>{order.quantity.toFixed(4)}</td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>
+ {order.price ? `$${order.price.toFixed(2)}` : 'Market'}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center', textTransform: 'uppercase', fontSize: '11px', color: '#f59e0b' }}>
+ {order.status}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <button
+ onClick={() => handleCancelOrder(order.id, order.symbol)}
+ style={{
+ padding: '4px 12px',
+ backgroundColor: '#dc262620',
+ color: '#dc2626',
+ border: '1px solid #dc2626',
+ borderRadius: '4px',
+ cursor: 'pointer',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ transition: 'all 0.2s'
+ }}
+ onMouseOver={(e) => {
+ e.currentTarget.style.backgroundColor = '#dc2626';
+ e.currentTarget.style.color = 'white';
+ }}
+ onMouseOut={(e) => {
+ e.currentTarget.style.backgroundColor = '#dc262620';
+ e.currentTarget.style.color = '#dc2626';
+ }}
+ >
+ Cancel
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ )}
+
+ {/* Trades Tab */}
+ {activeTab === 'trades' && (
+ <div>
+ {trades.length === 0 ? (
+ <div style={{ padding: '40px', textAlign: 'center', color: '#666', fontSize: '13px' }}>
+ No trade history
+ </div>
+ ) : (
+ <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
+ <table style={{ width: '100%', fontSize: '12px', fontFamily: 'monospace', borderCollapse: 'collapse' }}>
+ <thead style={{ position: 'sticky', top: 0, backgroundColor: '#1a1a1a' }}>
+ <tr style={{ borderBottom: '1px solid #333' }}>
+ <th style={{ textAlign: 'left', padding: '8px', color: '#666' }}>Time</th>
+ <th style={{ textAlign: 'left', padding: '8px', color: '#666' }}>Symbol</th>
+ <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Side</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Qty</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Price</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Value</th>
+ <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Fee</th>
+ </tr>
+ </thead>
+ <tbody>
+ {trades.map((trade, idx) => (
+ <tr key={idx} style={{ borderBottom: '1px solid #222' }}>
+ <td style={{ padding: '8px', fontSize: '11px', color: '#999' }}>
+ {new Date(trade.timestamp).toLocaleTimeString()}
+ </td>
+ <td style={{ padding: '8px' }}>{trade.symbol}</td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <span style={{
+ padding: '4px 8px',
+ borderRadius: '4px',
+ backgroundColor: trade.side === 'buy' ? '#10b98120' : '#dc262620',
+ color: trade.side === 'buy' ? '#10b981' : '#dc2626',
+ fontSize: '11px',
+ fontWeight: 'bold'
+ }}>
+ {trade.side.toUpperCase()}
+ </span>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>{trade.amount?.toFixed(4) || '0.0000'}</td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>${trade.price?.toFixed(2) || '0.00'}</td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>${trade.cost?.toFixed(2) || '0.00'}</td>
+ <td style={{ padding: '8px', textAlign: 'right', color: '#dc2626' }}>
+ ${trade.fee?.cost?.toFixed(2) || '0.00'}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Stats Tab */}
+ {activeTab === 'stats' && (
+ <div>
+ {!stats ? (
+ <div style={{ padding: '40px', textAlign: 'center', color: '#666', fontSize: '13px' }}>
+ Loading statistics...
+ </div>
+ ) : (
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px' }}>
+ {/* Initial Balance */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Initial Balance</div>
+ <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>
+ ${stats.initialBalance?.toFixed(2) || '0.00'}
+ </div>
+ </div>
+
+ {/* Current Balance */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Current Balance</div>
+ <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>
+ ${stats.currentBalance?.toFixed(2) || '0.00'}
+ </div>
+ </div>
+
+ {/* Total Value */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Total Value</div>
+ <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>
+ ${stats.totalValue?.toFixed(2) || '0.00'}
+ </div>
+ </div>
+
+ {/* Total PnL */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Total PnL</div>
+ <div style={{
+ fontSize: '20px',
+ fontWeight: 'bold',
+ fontFamily: 'monospace',
+ color: stats.totalPnL >= 0 ? '#10b981' : '#dc2626'
+ }}>
+ {stats.totalPnL >= 0 ? '+' : ''}${stats.totalPnL?.toFixed(2) || '0.00'}
+ </div>
+ </div>
+
+ {/* Realized PnL */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Realized PnL</div>
+ <div style={{
+ fontSize: '20px',
+ fontWeight: 'bold',
+ fontFamily: 'monospace',
+ color: stats.realizedPnL >= 0 ? '#10b981' : '#dc2626'
+ }}>
+ {stats.realizedPnL >= 0 ? '+' : ''}${stats.realizedPnL?.toFixed(2) || '0.00'}
+ </div>
+ </div>
+
+ {/* Unrealized PnL */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Unrealized PnL</div>
+ <div style={{
+ fontSize: '20px',
+ fontWeight: 'bold',
+ fontFamily: 'monospace',
+ color: stats.unrealizedPnL >= 0 ? '#10b981' : '#dc2626'
+ }}>
+ {stats.unrealizedPnL >= 0 ? '+' : ''}${stats.unrealizedPnL?.toFixed(2) || '0.00'}
+ </div>
+ </div>
+
+ {/* Return % */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Return</div>
+ <div style={{
+ fontSize: '20px',
+ fontWeight: 'bold',
+ fontFamily: 'monospace',
+ color: parseFloat(stats.returnPercent || '0') >= 0 ? '#10b981' : '#dc2626'
+ }}>
+ {parseFloat(stats.returnPercent || '0') >= 0 ? '+' : ''}{stats.returnPercent || '0.00'}%
+ </div>
+ </div>
+
+ {/* Total Trades */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Total Trades</div>
+ <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>
+ {stats.totalTrades || 0}
+ </div>
+ </div>
+
+ {/* Open Positions */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Open Positions</div>
+ <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace', color: '#f59e0b' }}>
+ {stats.openPositions || 0}
+ </div>
+ </div>
+
+ {/* Closed Positions */}
+ <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>
+ <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Closed Positions</div>
+ <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>
+ {stats.closedPositions || 0}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
</div>
)}
</div>
- {/* Right Panel - Order Book & Order Form & Stats */}
- <div style={{
- width: '320px',
- display: 'flex',
- flexDirection: 'column',
- borderLeft: `1px solid ${GRAY}`,
- backgroundColor: PANEL_BG,
- overflow: 'hidden'
- }}>
- <OrderBook symbol={selectedSymbol} provider={activeProvider} depth={25} />
-
- {/* Order Form (only if paper trading enabled) */}
- {portfolioId && (
- <OrderForm
- symbol={selectedSymbol}
- currentPrice={currentPrice}
- onPlaceOrder={handlePlaceOrder}
- isLoading={isLoading}
- />
- )}
-
- {/* Paper Trading Stats (only if paper trading enabled) */}
- {portfolioId && stats && (
- <div style={{ overflowY: 'auto' }}>
- <PaperTradingStats
- stats={stats}
- balance={balance}
- initialBalance={100000}
- />
+ {/* Right Column: Order Form + Order Book */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
+ {/* Order Form */}
+ {tradingMode === 'paper' && (
+ <div>
+ {!paperAdapter || !paperAdapter.isConnected() ? (
+ <div style={{
+ padding: '20px',
+ backgroundColor: '#1a1a1a',
+ borderRadius: '6px',
+ textAlign: 'center',
+ border: '1px solid #f59e0b'
+ }}>
+ <div style={{ fontSize: '14px', color: '#f59e0b', marginBottom: '8px', fontWeight: 'bold' }}>
+ ⚠️ Paper Trading Initializing...
+ </div>
+ <div style={{ fontSize: '12px', color: '#999' }}>
+ {isConnecting ? 'Connecting to broker...' : 'Waiting for adapter...'}
+ </div>
+ <div style={{
+ marginTop: '12px',
+ width: '100%',
+ height: '4px',
+ backgroundColor: '#333',
+ borderRadius: '2px',
+ overflow: 'hidden'
+ }}>
+ <div style={{
+ width: '50%',
+ height: '100%',
+ backgroundColor: '#f59e0b',
+ animation: 'loading 1.5s ease-in-out infinite'
+ }} />
+ </div>
+ </div>
+ ) : (
+ <OrderForm
+ symbol={selectedSymbol}
+ currentPrice={currentPrice}
+ onPlaceOrder={handlePlaceOrder}
+ isLoading={isPlacingOrder}
+ />
+ )}
</div>
)}
- {/* Paper Trading Disabled Message */}
- {!portfolioId && (
- <div style={{
- backgroundColor: DARK_BG,
- borderTop: `1px solid ${GRAY}`,
- padding: '16px',
- textAlign: 'center'
- }}>
- <div style={{ fontSize: '12px', color: GRAY, marginBottom: '8px', fontWeight: 'bold' }}>
- PAPER TRADING DISABLED
+ {/* Order Book */}
+ <div style={{ padding: '16px', backgroundColor: '#1a1a1a', borderRadius: '6px' }}>
+ <h3 style={{ marginBottom: '12px', fontSize: '14px', fontWeight: 'bold' }}>
+ Order Book - {orderBook.bids.length} bids, {orderBook.asks.length} asks
+ </h3>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ {/* Asks */}
+ <div>
+ <h4 style={{ color: '#dc2626', fontSize: '12px', marginBottom: '8px', fontWeight: 'bold' }}>ASKS</h4>
+ <table style={{ width: '100%', fontSize: '11px', fontFamily: 'monospace' }}>
+ <tbody>
+ {orderBook.asks.slice(0, 10).map((ask, idx) => (
+ <tr key={idx}>
+ <td style={{ padding: '2px 4px', color: '#dc2626' }}>
+ ${ask.price.toFixed(1)}
+ </td>
+ <td style={{ padding: '2px 4px', textAlign: 'right', color: '#999' }}>
+ {ask.size.toFixed(4)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
</div>
- <div style={{ fontSize: '10px', color: GRAY, lineHeight: '1.4' }}>
- Enable paper trading to place orders and manage positions with $100,000 virtual balance
+
+ {/* Bids */}
+ <div>
+ <h4 style={{ color: '#10b981', fontSize: '12px', marginBottom: '8px', fontWeight: 'bold' }}>BIDS</h4>
+ <table style={{ width: '100%', fontSize: '11px', fontFamily: 'monospace' }}>
+ <tbody>
+ {orderBook.bids.slice(0, 10).map((bid, idx) => (
+ <tr key={idx}>
+ <td style={{ padding: '2px 4px', color: '#10b981' }}>
+ ${bid.price.toFixed(1)}
+ </td>
+ <td style={{ padding: '2px 4px', textAlign: 'right', color: '#999' }}>
+ {bid.size.toFixed(4)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
</div>
</div>
- )}
+ <div style={{ marginTop: '12px', fontSize: '10px', color: '#555' }}>
+ Last update: {lastOrderBookUpdate > 0 ? new Date(lastOrderBookUpdate).toLocaleTimeString() : 'Never'}
+ </div>
+ </div>
</div>
</div>
- {/* Status Bar / Footer */}
+ {/* Footer */}
<div style={{
- borderTop: `1px solid ${GRAY}`,
- backgroundColor: PANEL_BG,
- padding: '6px 12px',
- fontSize: '9px',
- color: GRAY,
- flexShrink: 0
+ marginTop: '20px',
+ padding: '16px',
+ backgroundColor: '#1a1a1a',
+ borderRadius: '6px',
+ borderTop: '1px solid #333',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ fontSize: '12px',
+ color: '#666'
}}>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- flexWrap: 'wrap',
- gap: '8px'
- }}>
- <span>
- Fincept Trading Terminal v1.0.0 | WebSocket real-time data via {activeProvider.toUpperCase()}
- </span>
- <span style={{ whiteSpace: 'nowrap' }}>
- {portfolioId ? (
- <>
- <span style={{ color: GREEN }}>● PAPER TRADING ACTIVE</span>
- <span style={{ marginLeft: '8px' }}>|</span>
- <span style={{ marginLeft: '8px' }}>
- {positions.length} Open Position{positions.length !== 1 ? 's' : ''}
- </span>
- </>
- ) : (
- <>
- <span style={{ color: GRAY }}>● VIEW ONLY MODE</span>
- <span style={{ marginLeft: '8px' }}>|</span>
- <span style={{ marginLeft: '8px' }}>Enable paper trading to trade</span>
- </>
- )}
- </span>
+ <div style={{ display: 'flex', gap: '24px', alignItems: 'center' }}>
+ <div>
+ <span style={{ color: '#999', marginRight: '8px' }}>Broker:</span>
+ <span style={{ color: '#f59e0b', fontWeight: 'bold' }}>
+ {activeBroker || 'None'}
+ </span>
+ </div>
+ <div>
+ <span style={{ color: '#999', marginRight: '8px' }}>Mode:</span>
+ <span style={{
+ color: tradingMode === 'paper' ? '#10b981' : '#dc2626',
+ fontWeight: 'bold'
+ }}>
+ {tradingMode === 'paper' ? 'Paper Trading' : 'Live Trading'}
+ </span>
+ </div>
+ <div>
+ <span style={{ color: '#999', marginRight: '8px' }}>Connection:</span>
+ <span style={{
+ color: activeAdapter?.isConnected() ? '#10b981' : '#dc2626',
+ fontWeight: 'bold'
+ }}>
+ {activeAdapter?.isConnected() ? '● Connected' : '○ Disconnected'}
+ </span>
+ </div>
+ </div>
+
+ <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
+ <div style={{ fontSize: '11px', color: '#555' }}>
+ Fincept Terminal v3.0.12
+ </div>
+ <div style={{ fontSize: '11px', color: '#555' }}>
+ © {new Date().getFullYear()} Fincept Corporation
+ </div>
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/data-sources/adapters/KrakenAdapter.ts b/fincept-terminal-desktop/src/components/tabs/data-sources/adapters/KrakenAdapter.ts
deleted file mode 100644
index 6ca44e5cb..000000000
--- a/fincept-terminal-desktop/src/components/tabs/data-sources/adapters/KrakenAdapter.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-// Kraken Crypto Exchange API Adapter
-import { BaseAdapter } from './BaseAdapter';
-import { TestConnectionResult } from '../types';
-
-export class KrakenAdapter extends BaseAdapter {
- async testConnection(): Promise<TestConnectionResult> {
- try {
- const validation = this.validateConfig();
- if (!validation.valid) {
- return this.createErrorResult(validation.errors.join(', '));
- }
-
- const apiKey = this.getConfig<string>('apiKey');
- const apiSecret = this.getConfig<string>('apiSecret');
-
- console.log('Testing Kraken API connection...');
-
- try {
- // Test with public server time endpoint
- const response = await fetch('https://api.kraken.com/0/public/Time');
-
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
- }
-
- const data = await response.json();
-
- if (data.error && data.error.length > 0) {
- throw new Error(data.error.join(', '));
- }
-
- return this.createSuccessResult('Successfully connected to Kraken API', {
- serverTime: new Date(data.result.unixtime * 1000).toISOString(),
- rfc1123: data.result.rfc1123,
- authenticated: !!(apiKey && apiSecret),
- timestamp: new Date().toISOString(),
- });
- } catch (fetchError) {
- if (fetchError instanceof Error) {
- return this.createErrorResult(fetchError.message);
- }
- throw fetchError;
- }
- } catch (error) {
- return this.createErrorResult(error);
- }
- }
-
- async query(endpoint: string, params?: Record<string, any>): Promise<any> {
- try {
- const isPublic = endpoint.includes('/public/');
- const url = `https://api.kraken.com/0${endpoint}`;
-
- const queryParams = params ? `?${new URLSearchParams(params).toString()}` : '';
-
- const response = await fetch(`${url}${queryParams}`, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json',
- },
- });
-
- if (!response.ok) {
- throw new Error(`Query failed: ${response.status} ${response.statusText}`);
- }
-
- const data = await response.json();
-
- if (data.error && data.error.length > 0) {
- throw new Error(data.error.join(', '));
- }
-
- return data.result;
- } catch (error) {
- throw new Error(`Kraken query error: ${error instanceof Error ? error.message : String(error)}`);
- }
- }
-
- async getMetadata(): Promise<Record<string, any>> {
- const base = await super.getMetadata();
- return {
- ...base,
- hasApiKey: !!this.getConfig('apiKey'),
- hasApiSecret: !!this.getConfig('apiSecret'),
- provider: 'Kraken',
- };
- }
-
- /**
- * Get ticker information
- */
- async getTicker(pair: string): Promise<any> {
- return await this.query('/public/Ticker', { pair });
- }
-
- /**
- * Get OHLC data
- */
- async getOHLC(pair: string, interval: number = 1): Promise<any> {
- return await this.query('/public/OHLC', { pair, interval: interval.toString() });
- }
-
- /**
- * Get order book
- */
- async getOrderBook(pair: string, count: number = 100): Promise<any> {
- return await this.query('/public/Depth', { pair, count: count.toString() });
- }
-
- /**
- * Get recent trades
- */
- async getTrades(pair: string): Promise<any> {
- return await this.query('/public/Trades', { pair });
- }
-
- /**
- * Get tradable asset pairs
- */
- async getAssetPairs(): Promise<any> {
- return await this.query('/public/AssetPairs');
- }
-
- /**
- * Get asset info
- */
- async getAssets(): Promise<any> {
- return await this.query('/public/Assets');
- }
-
- /**
- * Get server time
- */
- async getServerTime(): Promise<any> {
- return await this.query('/public/Time');
- }
-
- /**
- * Get system status
- */
- async getSystemStatus(): Promise<any> {
- return await this.query('/public/SystemStatus');
- }
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/data-sources/adapters/index.ts b/fincept-terminal-desktop/src/components/tabs/data-sources/adapters/index.ts
index b414810aa..96b499eae 100644
--- a/fincept-terminal-desktop/src/components/tabs/data-sources/adapters/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/data-sources/adapters/index.ts
@@ -42,7 +42,6 @@ import { DatabricksAdapter } from './DatabricksAdapter';
import { GCPStorageAdapter } from './GCPStorageAdapter';
import { AzureBlobAdapter } from './AzureBlobAdapter';
import { IEXCloudAdapter } from './IEXCloudAdapter';
-import { KrakenAdapter } from './KrakenAdapter';
import { CoinMarketCapAdapter } from './CoinMarketCapAdapter';
import { TwelveDataAdapter } from './TwelveDataAdapter';
import { QuandlAdapter } from './QuandlAdapter';
@@ -194,7 +193,6 @@ const ADAPTER_MAP: Record<string, new (connection: any) => BaseAdapter> = {
binance: BinanceAdapter,
coinbase: CoinbaseAdapter,
'iex-cloud': IEXCloudAdapter,
- kraken: KrakenAdapter,
coinmarketcap: CoinMarketCapAdapter,
'twelve-data': TwelveDataAdapter,
quandl: QuandlAdapter,
@@ -316,7 +314,6 @@ export {
GCPStorageAdapter,
AzureBlobAdapter,
IEXCloudAdapter,
- KrakenAdapter,
CoinMarketCapAdapter,
TwelveDataAdapter,
QuandlAdapter,
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx
new file mode 100644
index 000000000..516ef9a06
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx
@@ -0,0 +1,229 @@
+// File: src/components/tabs/trading/AdvancedFeaturesPanel.tsx
+// Advanced trading features panel with leverage, margin mode, and broker-specific controls
+
+import React, { useState } from 'react';
+import { useBrokerContext } from '../../../contexts/BrokerContext';
+import { Sliders, ArrowUpDown, Settings, Zap } from 'lucide-react';
+
+const COLORS = {
+ ORANGE: '#ea580c',
+ WHITE: '#ffffff',
+ GREEN: '#10b981',
+ RED: '#dc2626',
+ GRAY: '#525252',
+ DARK_BG: '#0d0d0d',
+ PANEL_BG: '#1a1a1a',
+};
+
+export function AdvancedFeaturesPanel() {
+ const {
+ activeBroker,
+ activeBrokerMetadata,
+ activeAdapter,
+ supports,
+ tradingMode,
+ } = useBrokerContext();
+
+ const [leverage, setLeverage] = useState(1);
+ const [marginMode, setMarginMode] = useState<'cross' | 'isolated'>('cross');
+ const [isLoading, setIsLoading] = useState(false);
+
+ const { ORANGE, WHITE, GREEN, RED, GRAY, PANEL_BG, DARK_BG } = COLORS;
+
+ const canSetLeverage = supports?.canSetLeverage() || false;
+ const canTransfer = supports?.canTransfer() || false;
+ const hasVaults = supports?.hasVaults() || false;
+ const hasSubaccounts = supports?.hasSubaccounts() || false;
+ const maxLeverage = activeBrokerMetadata?.advancedFeatures.maxLeverage || 1;
+
+ // Handle leverage change
+ const handleLeverageChange = async (newLeverage: number) => {
+ if (!activeAdapter || !canSetLeverage) return;
+
+ setLeverage(newLeverage);
+
+ if (tradingMode === 'live') {
+ try {
+ setIsLoading(true);
+ if ('setLeverage' in activeAdapter) {
+ await (activeAdapter as any).setLeverage('', newLeverage);
+ }
+ } catch (error) {
+ console.error('Failed to set leverage:', error);
+ } finally {
+ setIsLoading(false);
+ }
+ }
+ };
+
+ // Handle margin mode change
+ const handleMarginModeChange = async (mode: 'cross' | 'isolated') => {
+ if (!activeAdapter) return;
+
+ setMarginMode(mode);
+
+ if (tradingMode === 'live') {
+ try {
+ setIsLoading(true);
+ if ('setMarginMode' in activeAdapter) {
+ await (activeAdapter as any).setMarginMode('', mode);
+ }
+ } catch (error) {
+ console.error('Failed to set margin mode:', error);
+ } finally {
+ setIsLoading(false);
+ }
+ }
+ };
+
+ // Don't render if no advanced features
+ if (!canSetLeverage && !canTransfer && !hasVaults && !hasSubaccounts) {
+ return null;
+ }
+
+ return (
+ <div style={{
+ backgroundColor: PANEL_BG,
+ borderBottom: `1px solid ${GRAY}`,
+ padding: '8px 12px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flexWrap: 'wrap' }}>
+ {/* Header */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Settings size={12} style={{ color: ORANGE }} />
+ <span style={{ fontSize: '10px', color: GRAY, fontWeight: 'bold', textTransform: 'uppercase' }}>
+ Advanced:
+ </span>
+ </div>
+
+ {/* Leverage Control */}
+ {canSetLeverage && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Sliders size={12} style={{ color: GRAY }} />
+ <span style={{ fontSize: '10px', color: GRAY }}>Leverage:</span>
+ <input
+ type="range"
+ min="1"
+ max={maxLeverage}
+ value={leverage}
+ onChange={(e) => handleLeverageChange(Number(e.target.value))}
+ disabled={isLoading}
+ style={{
+ width: '100px',
+ height: '4px',
+ accentColor: ORANGE,
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ }}
+ />
+ <span style={{
+ fontSize: '11px',
+ fontWeight: 'bold',
+ color: leverage > 1 ? ORANGE : WHITE,
+ minWidth: '35px',
+ textAlign: 'right',
+ }}>
+ {leverage}x
+ </span>
+ </div>
+ )}
+
+ {/* Margin Mode */}
+ {canSetLeverage && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <ArrowUpDown size={12} style={{ color: GRAY }} />
+ <span style={{ fontSize: '10px', color: GRAY }}>Margin:</span>
+ <div style={{ display: 'flex', gap: '4px', backgroundColor: DARK_BG, padding: '2px', borderRadius: '2px' }}>
+ <button
+ onClick={() => handleMarginModeChange('cross')}
+ disabled={isLoading}
+ style={{
+ padding: '3px 8px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ backgroundColor: marginMode === 'cross' ? ORANGE : 'transparent',
+ color: marginMode === 'cross' ? '#000' : GRAY,
+ border: 'none',
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ borderRadius: '2px',
+ textTransform: 'uppercase',
+ }}
+ >
+ Cross
+ </button>
+ <button
+ onClick={() => handleMarginModeChange('isolated')}
+ disabled={isLoading}
+ style={{
+ padding: '3px 8px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ backgroundColor: marginMode === 'isolated' ? ORANGE : 'transparent',
+ color: marginMode === 'isolated' ? '#000' : GRAY,
+ border: 'none',
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ borderRadius: '2px',
+ textTransform: 'uppercase',
+ }}
+ >
+ Isolated
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* HyperLiquid Specific Features */}
+ {activeBroker === 'hyperliquid' && (
+ <>
+ {hasVaults && (
+ <div style={{
+ padding: '3px 8px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ backgroundColor: '#1a1a1a',
+ color: ORANGE,
+ border: `1px solid ${ORANGE}40`,
+ borderRadius: '2px',
+ textTransform: 'uppercase',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}>
+ <Zap size={10} />
+ Vaults Available
+ </div>
+ )}
+ {hasSubaccounts && (
+ <div style={{
+ padding: '3px 8px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ backgroundColor: '#1a1a1a',
+ color: GREEN,
+ border: `1px solid ${GREEN}40`,
+ borderRadius: '2px',
+ textTransform: 'uppercase',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}>
+ Subaccounts
+ </div>
+ )}
+ </>
+ )}
+
+ {/* Trading Mode Warning */}
+ {tradingMode === 'paper' && canSetLeverage && (
+ <span style={{
+ fontSize: '9px',
+ color: '#666',
+ fontStyle: 'italic',
+ marginLeft: 'auto',
+ }}>
+ Paper mode - changes apply to virtual trading only
+ </span>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/BrokerSwitcher.tsx b/fincept-terminal-desktop/src/components/tabs/trading/BrokerSwitcher.tsx
new file mode 100644
index 000000000..309428856
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/BrokerSwitcher.tsx
@@ -0,0 +1,216 @@
+// File: src/components/tabs/trading/BrokerSwitcher.tsx
+// Enhanced broker selection with metadata and capabilities display
+
+import React from 'react';
+import { useBrokerContext } from '../../../contexts/BrokerContext';
+import { Activity, Zap, Shield, TrendingUp } from 'lucide-react';
+
+const BLOOMBERG_COLORS = {
+ ORANGE: '#ea580c',
+ WHITE: '#ffffff',
+ GREEN: '#10b981',
+ GRAY: '#525252',
+ DARK_BG: '#0d0d0d',
+ PANEL_BG: '#1a1a1a',
+};
+
+export function BrokerSwitcher() {
+ const {
+ activeBroker,
+ activeBrokerMetadata,
+ availableBrokers,
+ setActiveBroker,
+ tradingMode,
+ setTradingMode,
+ isLoading,
+ isConnecting,
+ } = useBrokerContext();
+
+ const { ORANGE, WHITE, GREEN, GRAY, DARK_BG, PANEL_BG } = BLOOMBERG_COLORS;
+
+ if (isLoading) {
+ return (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ backgroundColor: DARK_BG,
+ padding: '8px 12px',
+ borderBottom: `1px solid ${GRAY}`,
+ }}>
+ <span style={{ fontSize: '10px', color: GRAY, fontWeight: 'bold' }}>BROKER:</span>
+ <div style={{ fontSize: '10px', color: GRAY }}>Loading...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ backgroundColor: PANEL_BG,
+ padding: '8px 12px',
+ borderBottom: `1px solid ${GRAY}`,
+ }}>
+ {/* Left: Broker Selection */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <span style={{ fontSize: '10px', color: GRAY, fontWeight: 'bold', textTransform: 'uppercase' }}>
+ Broker:
+ </span>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ {availableBrokers.map(broker => {
+ const isActive = activeBroker === broker.id;
+ return (
+ <button
+ key={broker.id}
+ onClick={() => !isLoading && setActiveBroker(broker.id)}
+ disabled={isLoading || isConnecting}
+ style={{
+ padding: '4px 12px',
+ borderRadius: '2px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ textTransform: 'uppercase',
+ backgroundColor: isActive ? ORANGE : '#2d2d2d',
+ color: isActive ? '#000' : GRAY,
+ border: isActive ? `1px solid ${ORANGE}` : '1px solid #404040',
+ cursor: (isLoading || isConnecting) ? 'not-allowed' : 'pointer',
+ opacity: (isLoading || isConnecting) ? 0.5 : 1,
+ transition: 'all 0.2s',
+ }}
+ onMouseEnter={(e) => {
+ if (!isActive && !isLoading && !isConnecting) {
+ e.currentTarget.style.backgroundColor = '#404040';
+ e.currentTarget.style.borderColor = GRAY;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!isActive) {
+ e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.borderColor = '#404040';
+ }
+ }}
+ >
+ {broker.displayName}
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Broker Type Badge */}
+ {activeBrokerMetadata && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <span style={{
+ fontSize: '9px',
+ color: '#666',
+ padding: '2px 6px',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #333',
+ borderRadius: '2px',
+ textTransform: 'uppercase',
+ }}>
+ {activeBrokerMetadata.category === 'centralized' ? (
+ <>
+ <Shield size={10} style={{ display: 'inline', marginRight: '4px' }} />
+ CEX
+ </>
+ ) : (
+ <>
+ <Zap size={10} style={{ display: 'inline', marginRight: '4px' }} />
+ DEX
+ </>
+ )}
+ </span>
+
+ {/* Max Leverage Badge */}
+ {activeBrokerMetadata.advancedFeatures.leverage && (
+ <span style={{
+ fontSize: '9px',
+ color: ORANGE,
+ padding: '2px 6px',
+ backgroundColor: '#1a1a1a',
+ border: `1px solid ${ORANGE}40`,
+ borderRadius: '2px',
+ fontWeight: 'bold',
+ }}>
+ <TrendingUp size={10} style={{ display: 'inline', marginRight: '4px' }} />
+ {activeBrokerMetadata.advancedFeatures.maxLeverage}x
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Right: Trading Mode & Status */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ {/* Trading Mode Toggle */}
+ <div style={{ display: 'flex', gap: '4px', backgroundColor: DARK_BG, padding: '2px', borderRadius: '2px' }}>
+ <button
+ onClick={() => setTradingMode('paper')}
+ disabled={isLoading}
+ style={{
+ padding: '4px 10px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ backgroundColor: tradingMode === 'paper' ? ORANGE : 'transparent',
+ color: tradingMode === 'paper' ? '#000' : GRAY,
+ border: 'none',
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ borderRadius: '2px',
+ transition: 'all 0.2s',
+ }}
+ >
+ PAPER
+ </button>
+ <button
+ onClick={() => setTradingMode('live')}
+ disabled={isLoading}
+ style={{
+ padding: '4px 10px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ backgroundColor: tradingMode === 'live' ? '#dc2626' : 'transparent',
+ color: tradingMode === 'live' ? WHITE : GRAY,
+ border: 'none',
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ borderRadius: '2px',
+ transition: 'all 0.2s',
+ }}
+ >
+ LIVE
+ </button>
+ </div>
+
+ {/* Connection Status */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Activity
+ size={12}
+ style={{
+ color: isConnecting ? ORANGE : GREEN,
+ animation: isConnecting ? 'pulse 1.5s ease-in-out infinite' : 'none',
+ }}
+ />
+ <span style={{
+ fontSize: '10px',
+ color: isConnecting ? ORANGE : GREEN,
+ fontWeight: 'bold',
+ textTransform: 'uppercase',
+ }}>
+ {isConnecting ? 'Connecting...' : 'Connected'}
+ </span>
+ </div>
+ </div>
+
+ <style>{`
+ @keyframes pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.5; }
+ }
+ `}</style>
+ </div>
+ );
+}
+
+// Re-export as ProviderSwitcher for backward compatibility
+export { BrokerSwitcher as ProviderSwitcher };
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/MarketDepthChart.tsx b/fincept-terminal-desktop/src/components/tabs/trading/MarketDepthChart.tsx
new file mode 100644
index 000000000..5cc74efe5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/MarketDepthChart.tsx
@@ -0,0 +1,211 @@
+// MarketDepthChart.tsx - Market depth table with visual depth bars
+import React, { useState, useEffect } from 'react';
+import { useWebSocket } from '../../../hooks/useWebSocket';
+import { isProviderAvailable } from '../../../services/websocket';
+
+interface MarketDepthChartProps {
+ symbol: string;
+ provider: string;
+}
+
+interface DepthLevel {
+ price: number;
+ size: number;
+ cumulative: number;
+}
+
+export function MarketDepthChart({ symbol, provider }: MarketDepthChartProps) {
+ const [bids, setBids] = useState<DepthLevel[]>([]);
+ const [asks, setAsks] = useState<DepthLevel[]>([]);
+ const [maxCumulative, setMaxCumulative] = useState(0);
+
+ // Only subscribe if WebSocket adapter exists for this provider
+ const hasWebSocket = isProviderAvailable(provider);
+
+ const { message, isLoading } = useWebSocket(
+ hasWebSocket ? `${provider}.book.${symbol}` : null,
+ null,
+ { autoSubscribe: hasWebSocket, params: { depth: 50 } }
+ );
+
+ useEffect(() => {
+ if (!message || message.type !== 'orderbook') return;
+
+ const data = message.data;
+ if (!data || !Array.isArray(data.bids) || !Array.isArray(data.asks)) return;
+
+ try {
+ // Process bids (buy orders) - highest to lowest
+ const rawBids = data.bids
+ .filter((level: any) => level && typeof level.price === 'number' && typeof level.size === 'number')
+ .sort((a: any, b: any) => b.price - a.price)
+ .slice(0, 25);
+
+ let bidCumulative = 0;
+ const processedBids: DepthLevel[] = rawBids.map((level: any) => {
+ bidCumulative += level.size;
+ return {
+ price: level.price,
+ size: level.size,
+ cumulative: bidCumulative,
+ };
+ });
+
+ // Process asks (sell orders) - lowest to highest
+ const rawAsks = data.asks
+ .filter((level: any) => level && typeof level.price === 'number' && typeof level.size === 'number')
+ .sort((a: any, b: any) => a.price - b.price)
+ .slice(0, 25);
+
+ let askCumulative = 0;
+ const processedAsks: DepthLevel[] = rawAsks.map((level: any) => {
+ askCumulative += level.size;
+ return {
+ price: level.price,
+ size: level.size,
+ cumulative: askCumulative,
+ };
+ });
+
+ setBids(processedBids);
+ setAsks(processedAsks);
+
+ // Calculate max cumulative for bar sizing
+ const maxBid = processedBids.length > 0 ? processedBids[processedBids.length - 1].cumulative : 0;
+ const maxAsk = processedAsks.length > 0 ? processedAsks[processedAsks.length - 1].cumulative : 0;
+ setMaxCumulative(Math.max(maxBid, maxAsk));
+ } catch (error) {
+ console.error('[MarketDepthChart] Failed to process data:', error);
+ }
+ }, [message]);
+
+ if (isLoading) {
+ return (
+ <div className="bg-[#0d0d0d] border-t border-gray-800 p-3">
+ <h3 className="text-[10px] font-bold text-gray-400 tracking-wider mb-2">MARKET DEPTH</h3>
+ <div className="flex items-center justify-center h-40 text-gray-500">
+ <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-orange-500 mr-2"></div>
+ <span className="text-[10px]">Loading market depth...</span>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="bg-[#0d0d0d] border-t border-gray-800 p-3">
+ <h3 className="text-[10px] font-bold text-gray-400 tracking-wider mb-2">MARKET DEPTH</h3>
+
+ <div className="grid grid-cols-2 gap-2">
+ {/* BIDS (Buy Orders) */}
+ <div className="bg-[#1a1a1a] rounded">
+ <div className="px-2 py-1 border-b border-gray-800">
+ <h4 className="text-[9px] font-bold text-green-400 uppercase tracking-wide">Bids (Buy)</h4>
+ </div>
+ <div className="px-2 py-0.5 bg-[#0d0d0d] text-gray-500 text-[8px] font-bold uppercase tracking-wide flex justify-between">
+ <span className="w-1/3">Price</span>
+ <span className="w-1/3 text-right">Size</span>
+ <span className="w-1/3 text-right">Total</span>
+ </div>
+ <div className="max-h-48 overflow-y-auto">
+ {bids.length === 0 ? (
+ <div className="p-2 text-center text-gray-600 text-[10px]">No bid data</div>
+ ) : (
+ bids.map((level, idx) => (
+ <DepthRow
+ key={`bid-${idx}`}
+ level={level}
+ maxCumulative={maxCumulative}
+ side="bid"
+ />
+ ))
+ )}
+ </div>
+ </div>
+
+ {/* ASKS (Sell Orders) */}
+ <div className="bg-[#1a1a1a] rounded">
+ <div className="px-2 py-1 border-b border-gray-800">
+ <h4 className="text-[9px] font-bold text-red-400 uppercase tracking-wide">Asks (Sell)</h4>
+ </div>
+ <div className="px-2 py-0.5 bg-[#0d0d0d] text-gray-500 text-[8px] font-bold uppercase tracking-wide flex justify-between">
+ <span className="w-1/3">Price</span>
+ <span className="w-1/3 text-right">Size</span>
+ <span className="w-1/3 text-right">Total</span>
+ </div>
+ <div className="max-h-48 overflow-y-auto">
+ {asks.length === 0 ? (
+ <div className="p-2 text-center text-gray-600 text-[10px]">No ask data</div>
+ ) : (
+ asks.map((level, idx) => (
+ <DepthRow
+ key={`ask-${idx}`}
+ level={level}
+ maxCumulative={maxCumulative}
+ side="ask"
+ />
+ ))
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Summary Stats */}
+ {bids.length > 0 && asks.length > 0 && (
+ <div className="mt-2 grid grid-cols-3 gap-2 pt-2 border-t border-gray-800">
+ <div className="text-center">
+ <div className="text-[8px] text-gray-500 uppercase">Best Bid</div>
+ <div className="text-[11px] font-bold text-green-400 tabular-nums">
+ ${bids[0].price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div className="text-center">
+ <div className="text-[8px] text-gray-500 uppercase">Spread</div>
+ <div className="text-[11px] font-bold text-orange-400 tabular-nums">
+ ${(asks[0].price - bids[0].price).toFixed(2)}
+ </div>
+ </div>
+ <div className="text-center">
+ <div className="text-[8px] text-gray-500 uppercase">Best Ask</div>
+ <div className="text-[11px] font-bold text-red-400 tabular-nums">
+ ${asks[0].price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+interface DepthRowProps {
+ level: DepthLevel;
+ maxCumulative: number;
+ side: 'bid' | 'ask';
+}
+
+function DepthRow({ level, maxCumulative, side }: DepthRowProps) {
+ const percentage = maxCumulative > 0 ? (level.cumulative / maxCumulative) * 100 : 0;
+ const bgColor = side === 'bid' ? 'bg-green-900/30' : 'bg-red-900/30';
+
+ return (
+ <div className="relative px-2 py-[1px] hover:bg-gray-800/70 cursor-pointer transition-colors">
+ {/* Background depth bar */}
+ <div
+ className={`absolute right-0 top-0 bottom-0 ${bgColor} transition-all`}
+ style={{ width: `${percentage}%` }}
+ />
+
+ {/* Content */}
+ <div className="relative flex justify-between items-center text-[10px]">
+ <div className={`w-1/3 font-bold tabular-nums ${side === 'bid' ? 'text-green-400' : 'text-red-400'}`}>
+ {level.price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </div>
+ <div className="w-1/3 text-right text-gray-200 tabular-nums">
+ {level.size.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 })}
+ </div>
+ <div className="w-1/3 text-right text-gray-500 tabular-nums">
+ {level.cumulative.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx b/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx
index 0a2839f11..4dca67d88 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx
@@ -3,6 +3,7 @@
import React, { useState, useEffect } from 'react';
import { useWebSocket } from '../../../hooks/useWebSocket';
+import { isProviderAvailable } from '../../../services/websocket';
interface OrderBookLevel {
price: number;
@@ -21,10 +22,13 @@ export function OrderBook({ symbol, provider, depth = 25 }: OrderBookProps) {
const [asks, setAsks] = useState<OrderBookLevel[]>([]);
const [spread, setSpread] = useState<number>(0);
+ // Only subscribe if WebSocket adapter exists for this provider
+ const hasWebSocket = isProviderAvailable(provider);
+
const { message } = useWebSocket(
- `${provider}.book.${symbol}`,
+ hasWebSocket ? `${provider}.book.${symbol}` : null,
null,
- { autoSubscribe: true, params: { depth } }
+ { autoSubscribe: hasWebSocket, params: { depth } }
);
useEffect(() => {
@@ -32,27 +36,55 @@ export function OrderBook({ symbol, provider, depth = 25 }: OrderBookProps) {
const data = message.data;
+ // Validate data structure
+ if (!data || typeof data !== 'object') {
+ console.warn('[OrderBook] Invalid data structure:', data);
+ return;
+ }
+
// Process bids (buy orders) - highest first
- const processedBids = (data.bids || [])
+ const rawBids = Array.isArray(data.bids) ? data.bids : [];
+ const processedBids = rawBids
+ .filter((level: any) =>
+ level &&
+ typeof level === 'object' &&
+ typeof level.price === 'number' &&
+ typeof level.size === 'number'
+ )
.slice(0, depth)
.sort((a: any, b: any) => b.price - a.price);
// Process asks (sell orders) - lowest first
- const processedAsks = (data.asks || [])
+ const rawAsks = Array.isArray(data.asks) ? data.asks : [];
+ const processedAsks = rawAsks
+ .filter((level: any) =>
+ level &&
+ typeof level === 'object' &&
+ typeof level.price === 'number' &&
+ typeof level.size === 'number'
+ )
.slice(0, depth)
.sort((a: any, b: any) => a.price - b.price);
// Calculate running totals
let bidTotal = 0;
const bidsWithTotal = processedBids.map((level: any) => {
- bidTotal += level.size;
- return { price: level.price, size: level.size, total: bidTotal };
+ bidTotal += level.size || 0;
+ return {
+ price: level.price || 0,
+ size: level.size || 0,
+ total: bidTotal
+ };
});
let askTotal = 0;
const asksWithTotal = processedAsks.map((level: any) => {
- askTotal += level.size;
- return { price: level.price, size: level.size, total: askTotal };
+ askTotal += level.size || 0;
+ return {
+ price: level.price || 0,
+ size: level.size || 0,
+ total: askTotal
+ };
});
setBids(bidsWithTotal);
@@ -60,8 +92,8 @@ export function OrderBook({ symbol, provider, depth = 25 }: OrderBookProps) {
// Calculate spread
if (processedBids.length > 0 && processedAsks.length > 0) {
- const bestBid = processedBids[0].price;
- const bestAsk = processedAsks[0].price;
+ const bestBid = processedBids[0].price || 0;
+ const bestAsk = processedAsks[0].price || 0;
setSpread(bestAsk - bestBid);
}
}, [message, depth]);
@@ -72,49 +104,61 @@ export function OrderBook({ symbol, provider, depth = 25 }: OrderBookProps) {
);
return (
- <div className="flex flex-col h-full bg-[#0d0d0d] text-white font-mono text-xs">
+ <div className="flex flex-col h-full bg-[#0d0d0d] text-white font-mono text-[11px]">
{/* Header */}
- <div className="flex items-center justify-between px-3 py-2 border-b border-gray-800">
- <h3 className="text-sm font-bold text-gray-400">ORDER BOOK</h3>
- <div className="text-xs text-gray-500">
- Spread: <span className="text-orange-500">{spread.toFixed(2)}</span>
+ <div className="flex items-center justify-between px-2 py-1.5 border-b border-gray-800">
+ <h3 className="text-[10px] font-bold text-gray-400 tracking-wider">ORDER BOOK</h3>
+ <div className="text-[10px] text-gray-500">
+ Spread: <span className="text-orange-500 font-bold">{(spread ?? 0).toFixed(2)}</span>
</div>
</div>
{/* Column Headers */}
- <div className="flex justify-between px-3 py-1 bg-[#1a1a1a] text-gray-500 text-[10px] font-semibold">
- <div className="w-1/3">PRICE</div>
- <div className="w-1/3 text-right">SIZE</div>
- <div className="w-1/3 text-right">TOTAL</div>
+ <div className="flex justify-between px-2 py-0.5 bg-[#1a1a1a] text-gray-500 text-[9px] font-bold uppercase tracking-wide">
+ <div className="w-1/3">Price</div>
+ <div className="w-1/3 text-right">Size</div>
+ <div className="w-1/3 text-right">Total</div>
</div>
<div className="flex-1 overflow-hidden">
{/* Asks (Sell Orders) - Reversed to show lowest at bottom */}
<div className="h-1/2 overflow-y-auto flex flex-col-reverse border-b border-gray-800">
- {asks.slice().reverse().map((level, idx) => (
- <OrderBookRow
- key={`ask-${idx}`}
- price={level.price}
- size={level.size}
- total={level.total || 0}
- maxTotal={maxTotal}
- side="ask"
- />
- ))}
+ {asks.length === 0 ? (
+ <div className="flex items-center justify-center h-full text-gray-500 text-xs">
+ Waiting for data...
+ </div>
+ ) : (
+ asks.slice().reverse().map((level, idx) => (
+ <OrderBookRow
+ key={`ask-${idx}`}
+ price={level.price}
+ size={level.size}
+ total={level.total || 0}
+ maxTotal={maxTotal}
+ side="ask"
+ />
+ ))
+ )}
</div>
{/* Bids (Buy Orders) */}
<div className="h-1/2 overflow-y-auto">
- {bids.map((level, idx) => (
- <OrderBookRow
- key={`bid-${idx}`}
- price={level.price}
- size={level.size}
- total={level.total || 0}
- maxTotal={maxTotal}
- side="bid"
- />
- ))}
+ {bids.length === 0 ? (
+ <div className="flex items-center justify-center h-full text-gray-500 text-xs">
+ Waiting for data...
+ </div>
+ ) : (
+ bids.map((level, idx) => (
+ <OrderBookRow
+ key={`bid-${idx}`}
+ price={level.price}
+ size={level.size}
+ total={level.total || 0}
+ maxTotal={maxTotal}
+ side="bid"
+ />
+ ))
+ )}
</div>
</div>
</div>
@@ -130,24 +174,34 @@ interface OrderBookRowProps {
}
function OrderBookRow({ price, size, total, maxTotal, side }: OrderBookRowProps) {
- const percentage = (total / maxTotal) * 100;
- const bgColor = side === 'bid' ? 'bg-green-900/20' : 'bg-red-900/20';
+ // Safely handle undefined or null values
+ const safePrice = price ?? 0;
+ const safeSize = size ?? 0;
+ const safeTotal = total ?? 0;
+ const safeMaxTotal = maxTotal > 0 ? maxTotal : 1; // Prevent division by zero
+
+ const percentage = (safeTotal / safeMaxTotal) * 100;
+ const bgColor = side === 'bid' ? 'bg-green-900/30' : 'bg-red-900/30';
return (
- <div className="relative px-3 py-0.5 hover:bg-gray-800/50 cursor-pointer">
+ <div className="relative px-2 py-[2px] hover:bg-gray-800/70 cursor-pointer transition-colors">
{/* Background bar */}
<div
- className={`absolute right-0 top-0 bottom-0 ${bgColor}`}
+ className={`absolute right-0 top-0 bottom-0 ${bgColor} transition-all`}
style={{ width: `${percentage}%` }}
/>
{/* Content */}
- <div className="relative flex justify-between">
- <div className={`w-1/3 ${side === 'bid' ? 'text-green-400' : 'text-red-400'}`}>
- {price.toFixed(2)}
+ <div className="relative flex justify-between items-center">
+ <div className={`w-1/3 font-bold ${side === 'bid' ? 'text-green-400' : 'text-red-400'}`}>
+ {safePrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </div>
+ <div className="w-1/3 text-right text-gray-200 tabular-nums">
+ {safeSize.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 })}
+ </div>
+ <div className="w-1/3 text-right text-gray-500 tabular-nums">
+ {safeTotal.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
</div>
- <div className="w-1/3 text-right text-gray-300">{size.toFixed(4)}</div>
- <div className="w-1/3 text-right text-gray-500">{total.toFixed(4)}</div>
</div>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsx b/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsx
index b45d51ab5..828b273ca 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsx
@@ -1,7 +1,8 @@
// File: src/components/tabs/trading/OrderForm.tsx
-// Order placement form with all order types
+// Feature-aware order placement form - adapts to broker capabilities
import React, { useState } from 'react';
+import { useBrokerContext } from '../../../contexts/BrokerContext';
import type { OrderRequest, OrderType, OrderSide } from '../../../types/trading';
interface OrderFormProps {
@@ -12,13 +13,24 @@ interface OrderFormProps {
}
export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: OrderFormProps) {
+ const { activeBrokerMetadata, tradingMode } = useBrokerContext();
+
const [side, setSide] = useState<OrderSide>('buy');
const [orderType, setOrderType] = useState<OrderType>('market');
const [quantity, setQuantity] = useState<string>('');
const [price, setPrice] = useState<string>('');
const [stopPrice, setStopPrice] = useState<string>('');
+ const [takeProfitPrice, setTakeProfitPrice] = useState<string>('');
+ const [stopLossPrice, setStopLossPrice] = useState<string>('');
+ const [enableAdvanced, setEnableAdvanced] = useState(false);
const [error, setError] = useState<string>('');
+ // Get supported order types from broker
+ const supportsMarket = activeBrokerMetadata?.tradingFeatures.marketOrders ?? true;
+ const supportsLimit = activeBrokerMetadata?.tradingFeatures.limitOrders ?? true;
+ const supportsStop = activeBrokerMetadata?.tradingFeatures.stopOrders ?? false;
+ const supportsStopLimit = activeBrokerMetadata?.tradingFeatures.stopLimitOrders ?? false;
+
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
@@ -95,7 +107,7 @@ export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: Ord
</button>
</div>
- {/* Order Type */}
+ {/* Order Type - Only show supported types */}
<div>
<label className="block text-xs text-gray-500 mb-1">Order Type</label>
<select
@@ -103,10 +115,10 @@ export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: Ord
onChange={(e) => setOrderType(e.target.value as OrderType)}
className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"
>
- <option value="market">Market</option>
- <option value="limit">Limit</option>
- <option value="stop_market">Stop Market</option>
- <option value="stop_limit">Stop Limit</option>
+ {supportsMarket && <option value="market">Market</option>}
+ {supportsLimit && <option value="limit">Limit</option>}
+ {supportsStop && <option value="stop_market">Stop Market</option>}
+ {supportsStopLimit && <option value="stop_limit">Stop Limit</option>}
</select>
</div>
@@ -153,6 +165,65 @@ export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: Ord
</div>
)}
+ {/* Advanced Settings Toggle */}
+ <button
+ type="button"
+ onClick={() => setEnableAdvanced(!enableAdvanced)}
+ className="text-xs text-orange-500 hover:text-orange-400 transition-colors"
+ >
+ {enableAdvanced ? '− ' : '+ '}Advanced (SL/TP)
+ </button>
+
+ {/* Advanced Settings: Stop Loss & Take Profit */}
+ {enableAdvanced && (
+ <div className="space-y-3 border border-gray-700 rounded p-3 bg-gray-900/50">
+ <div>
+ <label className="block text-xs text-gray-500 mb-1">Take Profit Price</label>
+ <input
+ type="number"
+ step="0.01"
+ value={takeProfitPrice}
+ onChange={(e) => setTakeProfitPrice(e.target.value)}
+ placeholder="Optional"
+ className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500"
+ />
+ </div>
+
+ <div>
+ <label className="block text-xs text-gray-500 mb-1">Stop Loss Price</label>
+ <input
+ type="number"
+ step="0.01"
+ value={stopLossPrice}
+ onChange={(e) => setStopLossPrice(e.target.value)}
+ placeholder="Optional"
+ className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-red-500"
+ />
+ </div>
+
+ {currentPrice && (takeProfitPrice || stopLossPrice) && (
+ <div className="text-xs space-y-1">
+ {takeProfitPrice && (
+ <div className="flex justify-between text-green-400">
+ <span>TP R/R:</span>
+ <span>
+ {((Math.abs(parseFloat(takeProfitPrice) - currentPrice) / currentPrice) * 100).toFixed(2)}%
+ </span>
+ </div>
+ )}
+ {stopLossPrice && (
+ <div className="flex justify-between text-red-400">
+ <span>SL Risk:</span>
+ <span>
+ {((Math.abs(currentPrice - parseFloat(stopLossPrice)) / currentPrice) * 100).toFixed(2)}%
+ </span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
{/* Estimated Cost */}
{currentPrice && (
<div className="flex justify-between text-xs">
@@ -168,18 +239,38 @@ export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: Ord
</div>
)}
+ {/* Trading Mode Warning */}
+ {tradingMode === 'live' && (
+ <div className="bg-red-900/20 border border-red-600 rounded p-2 text-xs text-red-400 font-bold">
+ ⚠️ LIVE TRADING MODE - Real money will be used!
+ </div>
+ )}
+
{/* Submit Button */}
<button
type="submit"
disabled={isLoading}
className={`w-full py-2 rounded font-semibold text-sm transition-colors ${
- side === 'buy'
+ tradingMode === 'live'
+ ? 'bg-red-600 hover:bg-red-700 text-white border-2 border-red-400'
+ : side === 'buy'
? 'bg-green-600 hover:bg-green-700 text-white'
: 'bg-red-600 hover:bg-red-700 text-white'
} ${isLoading ? 'opacity-50 cursor-not-allowed' : ''}`}
>
- {isLoading ? 'Placing Order...' : `${side.toUpperCase()} ${symbol}`}
+ {isLoading
+ ? 'Placing Order...'
+ : tradingMode === 'live'
+ ? `🔴 LIVE ${side.toUpperCase()} ${symbol}`
+ : `${side.toUpperCase()} ${symbol}`}
</button>
+
+ {/* Paper Trading Info */}
+ {tradingMode === 'paper' && (
+ <div className="text-xs text-gray-500 text-center italic">
+ Paper trading - No real money used
+ </div>
+ )}
</form>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx
index c41bfa754..b5b146213 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx
@@ -94,13 +94,19 @@ function PositionRow({ position, onClose, isLoading }: PositionRowProps) {
const pnl = position.unrealizedPnl || 0;
const pnlColor = pnl >= 0 ? 'text-green-400' : 'text-red-400';
- // Calculate P&L percentage
+ // Calculate P&L percentage based on initial margin
const entryPrice = position.entryPrice || 0;
const currentPrice = position.markPrice || position.entryPrice || 0;
- const pnlPercent = entryPrice > 0
- ? ((currentPrice - entryPrice) / entryPrice) * 100 * (position.side === 'long' ? 1 : -1)
+ const quantity = position.contracts || 0;
+ const initialValue = entryPrice * quantity;
+ const pnlPercent = initialValue > 0
+ ? (pnl / initialValue) * 100
: 0;
+ // Calculate price movement
+ const priceChange = currentPrice - entryPrice;
+ const priceChangePercent = entryPrice > 0 ? (priceChange / entryPrice) * 100 : 0;
+
return (
<tr className="border-b border-gray-800 hover:bg-gray-800/50">
<td className="px-3 py-2 text-white font-semibold">{position.symbol}</td>
@@ -111,14 +117,19 @@ function PositionRow({ position, onClose, isLoading }: PositionRowProps) {
{(position.side || 'unknown').toUpperCase()}
</span>
</td>
- <td className="px-3 py-2 text-right text-gray-300">{(position.contracts || 0).toFixed(4)}</td>
- <td className="px-3 py-2 text-right text-gray-300">${(position.entryPrice || 0).toFixed(2)}</td>
- <td className="px-3 py-2 text-right text-white">
- ${(position.markPrice || position.entryPrice || 0).toFixed(2)}
+ <td className="px-3 py-2 text-right text-gray-300">{quantity.toFixed(4)}</td>
+ <td className="px-3 py-2 text-right text-gray-300">${entryPrice.toFixed(2)}</td>
+ <td className="px-3 py-2 text-right">
+ <div className="flex flex-col items-end">
+ <span className="text-white">${currentPrice.toFixed(2)}</span>
+ <span className={`text-[9px] ${priceChange >= 0 ? 'text-green-400' : 'text-red-400'}`}>
+ {priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)} ({priceChangePercent >= 0 ? '+' : ''}{priceChangePercent.toFixed(2)}%)
+ </span>
+ </div>
</td>
<td className={`px-3 py-2 text-right font-semibold ${pnlColor}`}>
<div className="flex flex-col items-end">
- <span>{pnl >= 0 ? '+' : ''}${pnl.toFixed(2)}</span>
+ <span className="text-sm">{pnl >= 0 ? '+' : ''}${Math.abs(pnl).toFixed(2)}</span>
<span className="text-[9px] opacity-75">
{pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(2)}%
</span>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ProviderSwitcher.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ProviderSwitcher.tsx
deleted file mode 100644
index afcd71d1f..000000000
--- a/fincept-terminal-desktop/src/components/tabs/trading/ProviderSwitcher.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-// File: src/components/tabs/trading/ProviderSwitcher.tsx
-// Provider selection component for multi-provider trading
-
-import React from 'react';
-import { useProviderContext } from '../../../contexts/ProviderContext';
-
-export function ProviderSwitcher() {
- const { activeProvider, availableProviders, setActiveProvider, isLoading } = useProviderContext();
-
- if (isLoading) {
- return (
- <div className="flex items-center gap-2 bg-[#0d0d0d] px-4 py-2 border-b border-gray-800">
- <span className="text-xs text-gray-500">PROVIDER:</span>
- <div className="text-xs text-gray-400">Loading...</div>
- </div>
- );
- }
-
- return (
- <div className="flex items-center gap-2 bg-[#0d0d0d] px-4 py-2 border-b border-gray-800">
- <span className="text-xs text-gray-500 uppercase font-semibold">Provider:</span>
- <div className="flex gap-2">
- {availableProviders.map(provider => (
- <button
- key={provider}
- onClick={() => setActiveProvider(provider)}
- disabled={isLoading}
- className={`
- px-3 py-1 rounded text-xs font-bold uppercase transition-colors
- ${activeProvider === provider
- ? 'bg-orange-600 text-black'
- : 'bg-gray-800 text-gray-400 hover:bg-gray-700 hover:text-gray-300'
- }
- ${isLoading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
- `}
- >
- {provider}
- </button>
- ))}
- </div>
-
- {activeProvider && (
- <div className="ml-4 flex items-center gap-2">
- <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>
- <span className="text-xs text-gray-500">Connected to {activeProvider}</span>
- </div>
- )}
- </div>
- );
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/QuickOrderButtons.tsx b/fincept-terminal-desktop/src/components/tabs/trading/QuickOrderButtons.tsx
new file mode 100644
index 000000000..d74c7bc05
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/QuickOrderButtons.tsx
@@ -0,0 +1,108 @@
+// QuickOrderButtons.tsx - One-click trading with preset amounts
+import React, { useState } from 'react';
+
+interface QuickOrderButtonsProps {
+ symbol: string;
+ currentPrice?: number;
+ onPlaceOrder: (order: {
+ symbol: string;
+ side: 'buy' | 'sell';
+ type: string;
+ quantity: number;
+ price?: number;
+ }) => Promise<void>;
+}
+
+const PRESET_AMOUNTS = [0.01, 0.05, 0.1, 0.25, 0.5, 1.0];
+
+export function QuickOrderButtons({ symbol, currentPrice, onPlaceOrder }: QuickOrderButtonsProps) {
+ const [isProcessing, setIsProcessing] = useState<string>('');
+
+ const handleQuickOrder = async (side: 'buy' | 'sell', quantity: number) => {
+ const key = `${side}-${quantity}`;
+ setIsProcessing(key);
+
+ try {
+ await onPlaceOrder({
+ symbol,
+ side,
+ type: 'market',
+ quantity,
+ });
+ } catch (error) {
+ console.error('[QuickOrderButtons] Failed:', error);
+ } finally {
+ setIsProcessing('');
+ }
+ };
+
+ return (
+ <div className="bg-[#0d0d0d] border-t border-gray-800 p-4">
+ <h3 className="text-sm font-bold text-gray-400 mb-3">QUICK ORDERS</h3>
+
+ {/* Buy Buttons */}
+ <div className="mb-3">
+ <div className="text-xs text-gray-500 mb-1">Quick Buy</div>
+ <div className="grid grid-cols-3 gap-1">
+ {PRESET_AMOUNTS.map((amount) => {
+ const key = `buy-${amount}`;
+ const isLoading = isProcessing === key;
+ const cost = currentPrice ? (amount * currentPrice).toFixed(2) : '0.00';
+
+ return (
+ <button
+ key={key}
+ onClick={() => handleQuickOrder('buy', amount)}
+ disabled={isLoading || !currentPrice}
+ className="bg-green-900/30 hover:bg-green-700/50 border border-green-600 text-green-400 rounded px-2 py-1.5 text-xs font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {isLoading ? (
+ <span className="animate-pulse">...</span>
+ ) : (
+ <>
+ {amount}
+ <div className="text-[9px] text-green-500/70">${cost}</div>
+ </>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Sell Buttons */}
+ <div>
+ <div className="text-xs text-gray-500 mb-1">Quick Sell</div>
+ <div className="grid grid-cols-3 gap-1">
+ {PRESET_AMOUNTS.map((amount) => {
+ const key = `sell-${amount}`;
+ const isLoading = isProcessing === key;
+ const proceeds = currentPrice ? (amount * currentPrice).toFixed(2) : '0.00';
+
+ return (
+ <button
+ key={key}
+ onClick={() => handleQuickOrder('sell', amount)}
+ disabled={isLoading || !currentPrice}
+ className="bg-red-900/30 hover:bg-red-700/50 border border-red-600 text-red-400 rounded px-2 py-1.5 text-xs font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {isLoading ? (
+ <span className="animate-pulse">...</span>
+ ) : (
+ <>
+ {amount}
+ <div className="text-[9px] text-red-500/70">${proceeds}</div>
+ </>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ <div className="mt-3 text-[10px] text-gray-600">
+ ⚠️ Market orders execute instantly
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/SymbolSelector.tsx b/fincept-terminal-desktop/src/components/tabs/trading/SymbolSelector.tsx
new file mode 100644
index 000000000..8e7a35003
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/SymbolSelector.tsx
@@ -0,0 +1,213 @@
+// File: src/components/tabs/trading/SymbolSelector.tsx
+// Dynamic symbol selector that adapts to active broker
+
+import React, { useState, useEffect, useMemo } from 'react';
+import { useBrokerContext } from '../../../contexts/BrokerContext';
+import { Search } from 'lucide-react';
+
+const BLOOMBERG_COLORS = {
+ ORANGE: '#ea580c',
+ WHITE: '#ffffff',
+ GRAY: '#525252',
+ DARK_BG: '#0d0d0d',
+ PANEL_BG: '#1a1a1a',
+};
+
+interface SymbolSelectorProps {
+ selectedSymbol: string;
+ onSymbolChange: (symbol: string) => void;
+}
+
+export function SymbolSelector({ selectedSymbol, onSymbolChange }: SymbolSelectorProps) {
+ const { activeBroker, activeBrokerMetadata, defaultSymbols } = useBrokerContext();
+ const [searchValue, setSearchValue] = useState('');
+ const [isFocused, setIsFocused] = useState(false);
+
+ const { ORANGE, WHITE, GRAY, PANEL_BG } = BLOOMBERG_COLORS;
+
+ // Update search value when selected symbol changes
+ useEffect(() => {
+ setSearchValue(selectedSymbol);
+ }, [selectedSymbol]);
+
+ // Filter symbols based on search
+ const filteredSymbols = useMemo(() => {
+ if (!searchValue || searchValue === selectedSymbol) {
+ return defaultSymbols;
+ }
+ return defaultSymbols.filter(symbol =>
+ symbol.toLowerCase().includes(searchValue.toLowerCase())
+ );
+ }, [defaultSymbols, searchValue, selectedSymbol]);
+
+ // Get placeholder based on broker
+ const placeholder = useMemo(() => {
+ if (!activeBrokerMetadata) return 'Search symbol...';
+
+ if (activeBroker === 'kraken') {
+ return 'e.g. BTC/USD';
+ } else if (activeBroker === 'hyperliquid') {
+ return 'e.g. BTC/USDC:USDC';
+ }
+ return 'Search symbol...';
+ }, [activeBroker, activeBrokerMetadata]);
+
+ const handleSymbolClick = (symbol: string) => {
+ setSearchValue(symbol);
+ onSymbolChange(symbol);
+ setIsFocused(false);
+ };
+
+ const handleInputChange = (value: string) => {
+ setSearchValue(value.toUpperCase());
+ };
+
+ const handleInputKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter') {
+ if (filteredSymbols.length > 0) {
+ handleSymbolClick(filteredSymbols[0]);
+ } else if (searchValue) {
+ onSymbolChange(searchValue);
+ setIsFocused(false);
+ }
+ }
+ };
+
+ return (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ backgroundColor: PANEL_BG,
+ padding: '8px 12px',
+ borderBottom: `1px solid ${GRAY}`,
+ position: 'relative',
+ }}>
+ <span style={{
+ fontSize: '10px',
+ color: GRAY,
+ fontWeight: 'bold',
+ textTransform: 'uppercase',
+ }}>
+ {activeBroker === 'kraken' ? 'Pair:' : 'Symbol:'}
+ </span>
+
+ {/* Popular Symbols */}
+ <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
+ {defaultSymbols.map(symbol => (
+ <button
+ key={symbol}
+ onClick={() => handleSymbolClick(symbol)}
+ style={{
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ textTransform: 'uppercase',
+ backgroundColor: selectedSymbol === symbol ? ORANGE : '#2d2d2d',
+ color: selectedSymbol === symbol ? '#000' : GRAY,
+ border: selectedSymbol === symbol ? `1px solid ${ORANGE}` : '1px solid #404040',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ borderRadius: '2px',
+ }}
+ onMouseEnter={(e) => {
+ if (selectedSymbol !== symbol) {
+ e.currentTarget.style.backgroundColor = '#404040';
+ e.currentTarget.style.borderColor = GRAY;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (selectedSymbol !== symbol) {
+ e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.borderColor = '#404040';
+ }
+ }}
+ >
+ {symbol}
+ </button>
+ ))}
+ </div>
+
+ {/* Search Input */}
+ <div style={{ position: 'relative', marginLeft: '12px' }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ backgroundColor: '#2d2d2d',
+ border: `1px solid ${isFocused ? ORANGE : '#404040'}`,
+ borderRadius: '2px',
+ padding: '4px 8px',
+ transition: 'border-color 0.2s',
+ }}>
+ <Search size={12} style={{ color: GRAY, marginRight: '6px' }} />
+ <input
+ type="text"
+ placeholder={placeholder}
+ value={searchValue}
+ onChange={(e) => handleInputChange(e.target.value)}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setTimeout(() => setIsFocused(false), 200)}
+ onKeyPress={handleInputKeyPress}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ outline: 'none',
+ color: WHITE,
+ fontSize: '11px',
+ width: '150px',
+ fontFamily: 'Consolas, monospace',
+ }}
+ />
+ </div>
+
+ {/* Dropdown Suggestions */}
+ {isFocused && filteredSymbols.length > 0 && searchValue !== selectedSymbol && (
+ <div style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ right: 0,
+ marginTop: '4px',
+ backgroundColor: '#1a1a1a',
+ border: `1px solid ${GRAY}`,
+ borderRadius: '2px',
+ maxHeight: '200px',
+ overflowY: 'auto',
+ zIndex: 1000,
+ boxShadow: '0 4px 6px rgba(0, 0, 0, 0.3)',
+ }}>
+ {filteredSymbols.map(symbol => (
+ <button
+ key={symbol}
+ onClick={() => handleSymbolClick(symbol)}
+ style={{
+ display: 'block',
+ width: '100%',
+ padding: '8px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ textAlign: 'left',
+ backgroundColor: 'transparent',
+ color: GRAY,
+ border: 'none',
+ cursor: 'pointer',
+ transition: 'background-color 0.2s',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.color = WHITE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = GRAY;
+ }}
+ >
+ {symbol}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx b/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx
index 1e8916bc0..c0a642a41 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx
@@ -3,6 +3,7 @@
import React, { useState, useEffect } from 'react';
import { useWebSocket } from '../../../hooks/useWebSocket';
+import { isProviderAvailable } from '../../../services/websocket';
interface TickerDisplayProps {
symbol: string;
@@ -23,10 +24,13 @@ interface TickerData {
export function TickerDisplay({ symbol, provider }: TickerDisplayProps) {
const [ticker, setTicker] = useState<TickerData | null>(null);
+ // Only subscribe if WebSocket adapter exists for this provider
+ const hasWebSocket = isProviderAvailable(provider);
+
const { message } = useWebSocket(
- `${provider}.ticker.${symbol}`,
+ hasWebSocket ? `${provider}.ticker.${symbol}` : null,
null,
- { autoSubscribe: true }
+ { autoSubscribe: hasWebSocket }
);
useEffect(() => {
@@ -34,22 +38,43 @@ export function TickerDisplay({ symbol, provider }: TickerDisplayProps) {
const data = message.data;
+ // Parse nested data if needed
+ const tickerData = data.ticker || data;
+
+ // Extract values with multiple fallbacks for different provider formats
+ const last = parseFloat(tickerData.last || tickerData.close || tickerData.price || tickerData.mid || 0);
+ const bid = parseFloat(tickerData.bid || tickerData.bid_price || tickerData.b || 0);
+ const ask = parseFloat(tickerData.ask || tickerData.ask_price || tickerData.a || 0);
+ const volume = parseFloat(tickerData.volume || tickerData.vol || tickerData.v || 0);
+ const high = parseFloat(tickerData.high || tickerData.h || 0);
+ const low = parseFloat(tickerData.low || tickerData.l || 0);
+
+ // Calculate change if not provided
+ let change = parseFloat(tickerData.change || 0);
+ let changePct = parseFloat(tickerData.change_pct || tickerData.changePct || 0);
+
+ if (change === 0 && tickerData.open) {
+ change = last - parseFloat(tickerData.open);
+ changePct = (change / parseFloat(tickerData.open)) * 100;
+ }
+
setTicker({
- last: data.last || data.close || data.mid || 0,
- bid: data.bid || 0,
- ask: data.ask || 0,
- volume: data.volume || data.v || 0,
- high: data.high || data.h || 0,
- low: data.low || data.l || 0,
- change: data.change || 0,
- changePct: data.change_pct || data.changePct || 0
+ last,
+ bid,
+ ask,
+ volume,
+ high,
+ low,
+ change,
+ changePct
});
}, [message]);
if (!ticker) {
return (
- <div className="bg-[#0d0d0d] p-4 text-center text-gray-500">
- Loading ticker data...
+ <div className="bg-[#0d0d0d] p-3 text-center text-gray-500">
+ <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-orange-500 mx-auto mb-1.5"></div>
+ <div className="text-[10px]">Loading ticker...</div>
</div>
);
}
@@ -59,27 +84,27 @@ export function TickerDisplay({ symbol, provider }: TickerDisplayProps) {
return (
<div className="bg-[#0d0d0d] border-b border-gray-800">
{/* Main Price */}
- <div className="px-4 py-3 border-b border-gray-800">
- <div className="text-2xl font-bold font-mono text-white mb-1">
+ <div className="px-3 py-2 border-b border-gray-800">
+ <div className="text-xl font-bold font-mono text-white mb-0.5 tabular-nums tracking-tight">
${ticker.last.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
</div>
- <div className={`text-sm font-semibold ${isPositive ? 'text-green-400' : 'text-red-400'}`}>
- {isPositive ? '+' : ''}{ticker.change.toFixed(2)} ({isPositive ? '+' : ''}{ticker.changePct.toFixed(2)}%)
+ <div className={`text-xs font-bold tabular-nums ${isPositive ? 'text-green-400' : 'text-red-400'}`}>
+ {isPositive ? '▲' : '▼'} {isPositive ? '+' : ''}{ticker.change.toFixed(2)} ({isPositive ? '+' : ''}{ticker.changePct.toFixed(2)}%)
</div>
</div>
{/* Stats Grid */}
- <div className="grid grid-cols-2 gap-2 px-4 py-3 text-xs font-mono">
+ <div className="grid grid-cols-3 gap-x-2 gap-y-1.5 px-3 py-2 text-[10px] font-mono">
<StatItem label="BID" value={ticker.bid.toFixed(2)} valueColor="text-green-400" />
<StatItem label="ASK" value={ticker.ask.toFixed(2)} valueColor="text-red-400" />
- <StatItem label="HIGH" value={ticker.high.toFixed(2)} valueColor="text-gray-300" />
- <StatItem label="LOW" value={ticker.low.toFixed(2)} valueColor="text-gray-300" />
- <StatItem label="VOLUME" value={ticker.volume.toFixed(2)} valueColor="text-blue-400" />
<StatItem
label="SPREAD"
value={(ticker.ask - ticker.bid).toFixed(2)}
valueColor="text-orange-400"
/>
+ <StatItem label="HIGH" value={ticker.high.toFixed(2)} valueColor="text-gray-300" />
+ <StatItem label="LOW" value={ticker.low.toFixed(2)} valueColor="text-gray-300" />
+ <StatItem label="VOLUME" value={ticker.volume.toLocaleString(undefined, { maximumFractionDigits: 0 })} valueColor="text-cyan-400" />
</div>
</div>
);
@@ -93,9 +118,9 @@ interface StatItemProps {
function StatItem({ label, value, valueColor }: StatItemProps) {
return (
- <div>
- <div className="text-gray-500 text-[10px] mb-0.5">{label}</div>
- <div className={`${valueColor} font-semibold`}>{value}</div>
+ <div className="flex flex-col">
+ <div className="text-gray-600 text-[9px] font-bold uppercase tracking-wide mb-0.5">{label}</div>
+ <div className={`${valueColor} font-bold text-[11px] tabular-nums`}>{value}</div>
</div>
);
}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx b/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx
index faec27c55..087b9ae4e 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx
@@ -3,6 +3,7 @@
import React, { useState, useEffect } from 'react';
import { useWebSocket } from '../../../hooks/useWebSocket';
+import { isProviderAvailable } from '../../../services/websocket';
interface Trade {
price: number;
@@ -20,10 +21,13 @@ interface TradesFeedProps {
export function TradesFeed({ symbol, provider, maxTrades = 50 }: TradesFeedProps) {
const [trades, setTrades] = useState<Trade[]>([]);
- const { message } = useWebSocket(
- `${provider}.trades.${symbol}`,
+ // Only subscribe if WebSocket adapter exists for this provider
+ const hasWebSocket = isProviderAvailable(provider);
+
+ const { message, isLoading, error } = useWebSocket(
+ hasWebSocket ? `${provider}.trades.${symbol}` : null,
null,
- { autoSubscribe: true }
+ { autoSubscribe: hasWebSocket }
);
useEffect(() => {
@@ -59,23 +63,36 @@ export function TradesFeed({ symbol, provider, maxTrades = 50 }: TradesFeedProps
}, [message, maxTrades]);
return (
- <div className="flex flex-col h-full bg-[#0d0d0d] text-white font-mono text-xs">
+ <div className="flex flex-col h-full bg-[#0d0d0d] text-white font-mono text-[11px]">
{/* Header */}
- <div className="px-3 py-2 border-b border-gray-800">
- <h3 className="text-sm font-bold text-gray-400">RECENT TRADES</h3>
+ <div className="flex items-center justify-between px-2 py-1.5 border-b border-gray-800">
+ <h3 className="text-[10px] font-bold text-gray-400 tracking-wider">RECENT TRADES</h3>
+ <div className="flex items-center gap-1.5">
+ <div className="w-1.5 h-1.5 bg-green-500 rounded-full animate-pulse"></div>
+ <span className="text-[10px] text-gray-500">Live</span>
+ </div>
</div>
{/* Column Headers */}
- <div className="flex justify-between px-3 py-1 bg-[#1a1a1a] text-gray-500 text-[10px] font-semibold">
- <div className="w-1/3">TIME</div>
- <div className="w-1/3 text-right">PRICE</div>
- <div className="w-1/3 text-right">SIZE</div>
+ <div className="flex justify-between px-2 py-0.5 bg-[#1a1a1a] text-gray-500 text-[9px] font-bold uppercase tracking-wide">
+ <div className="w-1/3">Time</div>
+ <div className="w-1/3 text-right">Price</div>
+ <div className="w-1/3 text-right">Size</div>
</div>
{/* Trades List */}
<div className="flex-1 overflow-y-auto">
- {trades.length === 0 ? (
- <div className="p-4 text-center text-gray-500">No trades yet...</div>
+ {isLoading && trades.length === 0 ? (
+ <div className="p-4 text-center text-gray-500">
+ <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-orange-500 mx-auto mb-2"></div>
+ Connecting...
+ </div>
+ ) : error && trades.length === 0 ? (
+ <div className="p-4 text-center text-red-500 text-xs">
+ Connection error
+ </div>
+ ) : trades.length === 0 ? (
+ <div className="p-4 text-center text-gray-500">Waiting for trades...</div>
) : (
trades.map((trade, idx) => (
<TradeRow key={`${trade.time}-${idx}`} trade={trade} />
@@ -99,12 +116,14 @@ function TradeRow({ trade }: TradeRowProps) {
});
return (
- <div className="flex justify-between px-3 py-1 hover:bg-gray-800/50">
- <div className="w-1/3 text-gray-400">{timeStr}</div>
- <div className={`w-1/3 text-right font-semibold ${trade.side === 'buy' ? 'text-green-400' : 'text-red-400'}`}>
- {trade.price.toFixed(2)}
+ <div className="flex justify-between px-2 py-[2px] hover:bg-gray-800/70 cursor-pointer transition-colors">
+ <div className="w-1/3 text-gray-500 tabular-nums">{timeStr}</div>
+ <div className={`w-1/3 text-right font-bold tabular-nums ${trade.side === 'buy' ? 'text-green-400' : 'text-red-400'}`}>
+ {trade.price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </div>
+ <div className="w-1/3 text-right text-gray-200 tabular-nums">
+ {trade.size.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 })}
</div>
- <div className="w-1/3 text-right text-gray-300">{trade.size.toFixed(4)}</div>
</div>
);
}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx
new file mode 100644
index 000000000..73efc9378
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx
@@ -0,0 +1,307 @@
+// TradingChart.tsx - TradingView Lightweight Charts with historical + live data
+import React, { useEffect, useRef, useState } from 'react';
+import { createChart, IChartApi, ISeriesApi, CandlestickData, Time } from 'lightweight-charts';
+import { useWebSocket } from '../../../hooks/useWebSocket';
+import { isProviderAvailable } from '../../../services/websocket';
+import { useBrokerContext } from '../../../contexts/BrokerContext';
+
+interface TradingChartProps {
+ symbol: string;
+ provider: string;
+ interval?: '1m' | '5m' | '15m' | '30m' | '1h' | '4h' | '1d';
+}
+
+export function TradingChart({ symbol, provider, interval = '1m' }: TradingChartProps) {
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+ const chartRef = useRef<IChartApi | null>(null);
+ const candlestickSeriesRef = useRef<ISeriesApi<any> | null>(null);
+ const volumeSeriesRef = useRef<ISeriesApi<any> | null>(null);
+
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [candleData, setCandleData] = useState<CandlestickData[]>([]);
+
+ const { realAdapter } = useBrokerContext();
+
+ // Only subscribe if WebSocket adapter exists for this provider
+ const hasWebSocket = isProviderAvailable(provider);
+
+ // Subscribe to candle data
+ const { message, error: wsError } = useWebSocket(
+ hasWebSocket ? `${provider}.ohlc.${symbol}` : null,
+ null,
+ { autoSubscribe: hasWebSocket, params: { interval: parseInterval(interval) } }
+ );
+
+ // Initialize chart
+ useEffect(() => {
+ if (!chartContainerRef.current) return;
+
+ console.log('[TradingChart] Initializing Lightweight Charts...');
+
+ // Create chart
+ const chart = createChart(chartContainerRef.current, {
+ width: chartContainerRef.current.clientWidth,
+ height: chartContainerRef.current.clientHeight,
+ layout: {
+ background: { color: '#0d0d0d' },
+ textColor: '#d1d5db',
+ },
+ grid: {
+ vertLines: { color: '#1a1a1a' },
+ horzLines: { color: '#1a1a1a' },
+ },
+ crosshair: {
+ mode: 1, // Normal crosshair
+ },
+ rightPriceScale: {
+ borderColor: '#2a2a2a',
+ },
+ timeScale: {
+ borderColor: '#2a2a2a',
+ timeVisible: true,
+ secondsVisible: false,
+ },
+ });
+
+ // Create candlestick series
+ const candlestickSeries = (chart as any).addCandlestickSeries({
+ upColor: '#10b981',
+ downColor: '#dc2626',
+ borderUpColor: '#10b981',
+ borderDownColor: '#dc2626',
+ wickUpColor: '#10b981',
+ wickDownColor: '#dc2626',
+ });
+
+ // Create volume series
+ const volumeSeries = (chart as any).addHistogramSeries({
+ color: '#26a69a',
+ priceFormat: {
+ type: 'volume',
+ },
+ priceScaleId: '', // Use separate price scale for volume
+ });
+
+ volumeSeries.priceScale().applyOptions({
+ scaleMargins: {
+ top: 0.8, // Volume takes up bottom 20%
+ bottom: 0,
+ },
+ });
+
+ chartRef.current = chart;
+ candlestickSeriesRef.current = candlestickSeries;
+ volumeSeriesRef.current = volumeSeries;
+
+ // Handle resize
+ const handleResize = () => {
+ if (chartContainerRef.current && chartRef.current) {
+ chartRef.current.applyOptions({
+ width: chartContainerRef.current.clientWidth,
+ height: chartContainerRef.current.clientHeight,
+ });
+ }
+ };
+
+ window.addEventListener('resize', handleResize);
+
+ console.log('[TradingChart] Chart initialized');
+
+ return () => {
+ window.removeEventListener('resize', handleResize);
+ if (chartRef.current) {
+ chartRef.current.remove();
+ chartRef.current = null;
+ }
+ };
+ }, []);
+
+ // Fetch historical data on mount or when symbol/interval changes
+ useEffect(() => {
+ const fetchHistoricalData = async () => {
+ if (!realAdapter) {
+ console.log('[TradingChart] No adapter available, skipping historical fetch');
+ return;
+ }
+
+ try {
+ setIsLoading(true);
+ setError(null);
+
+ console.log(`[TradingChart] Fetching historical data for ${symbol} ${interval}...`);
+
+ // Fetch OHLCV data from exchange
+ const timeframe = interval; // CCXT uses same format
+ const limit = 100; // Last 100 candles
+
+ const ohlcv = await realAdapter.fetchOHLCV(symbol, timeframe, undefined);
+
+ console.log(`[TradingChart] Fetched ${ohlcv.length} historical candles`);
+
+ // Convert to Lightweight Charts format
+ const candles: CandlestickData<Time>[] = ohlcv.map((candle) => ({
+ time: Math.floor((candle[0] ?? 0) / 1000) as Time, // Convert ms to seconds
+ open: candle[1] ?? 0,
+ high: candle[2] ?? 0,
+ low: candle[3] ?? 0,
+ close: candle[4] ?? 0,
+ }));
+
+ const volumes = ohlcv.map((candle) => ({
+ time: Math.floor((candle[0] ?? 0) / 1000) as Time,
+ value: candle[5] ?? 0,
+ color: (candle[4] ?? 0) >= (candle[1] ?? 0) ? '#10b98180' : '#dc262680', // Green if close >= open
+ }));
+
+ // Update chart
+ if (candlestickSeriesRef.current && volumeSeriesRef.current) {
+ candlestickSeriesRef.current.setData(candles as any);
+ volumeSeriesRef.current.setData(volumes as any);
+ setCandleData(candles);
+
+ // Fit content
+ if (chartRef.current) {
+ chartRef.current.timeScale().fitContent();
+ }
+
+ console.log('[TradingChart] Historical data loaded successfully');
+ }
+
+ setIsLoading(false);
+ } catch (err) {
+ console.error('[TradingChart] Failed to fetch historical data:', err);
+ setError(err instanceof Error ? err.message : 'Failed to load chart data');
+ setIsLoading(false);
+ }
+ };
+
+ fetchHistoricalData();
+ }, [symbol, interval, realAdapter]);
+
+ // Handle live candle updates from WebSocket
+ useEffect(() => {
+ if (!message || message.type !== 'candle') return;
+ if (!candlestickSeriesRef.current || !volumeSeriesRef.current) return;
+
+ const data = message.data;
+
+ // Parse candle data
+ const candle = parseCandleData(data);
+ if (!candle) return;
+
+ console.log('[TradingChart] Live candle update:', candle);
+
+ try {
+ // Update candlestick
+ candlestickSeriesRef.current.update(candle);
+
+ // Update volume
+ volumeSeriesRef.current.update({
+ time: candle.time,
+ value: (data.volume || data.v || 0) as number,
+ color: candle.close >= candle.open ? '#10b98180' : '#dc262680',
+ });
+
+ // Update local state
+ setCandleData(prev => {
+ const lastCandle = prev[prev.length - 1];
+ if (lastCandle && lastCandle.time === candle.time) {
+ // Update existing candle
+ return [...prev.slice(0, -1), candle];
+ } else {
+ // Append new candle
+ return [...prev, candle];
+ }
+ });
+ } catch (error) {
+ console.error('[TradingChart] Failed to update candle:', error);
+ }
+ }, [message]);
+
+ return (
+ <div className="relative w-full h-full bg-[#0d0d0d]">
+ {/* Loading State */}
+ {isLoading && (
+ <div className="absolute inset-0 flex items-center justify-center bg-[#0d0d0d] z-10">
+ <div className="text-center">
+ <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-500 mx-auto mb-3"></div>
+ <div className="text-gray-400 text-sm">Loading chart data...</div>
+ <div className="text-gray-600 text-xs mt-2">{symbol} • {interval}</div>
+ </div>
+ </div>
+ )}
+
+ {/* Error State */}
+ {error && !isLoading && (
+ <div className="absolute inset-0 flex items-center justify-center bg-[#0d0d0d] z-10">
+ <div className="text-center">
+ <div className="text-red-500 text-sm mb-2">Failed to Load Chart</div>
+ <div className="text-gray-500 text-xs">{error}</div>
+ <div className="text-gray-600 text-xs mt-1">{symbol} • {interval}</div>
+ </div>
+ </div>
+ )}
+
+ {/* WebSocket Error */}
+ {wsError && !isLoading && !error && (
+ <div className="absolute top-2 right-2 bg-yellow-900/50 border border-yellow-600 px-3 py-2 rounded text-xs text-yellow-400 z-10">
+ ⚠️ Live updates unavailable
+ </div>
+ )}
+
+ {/* Chart Container */}
+ <div ref={chartContainerRef} className="w-full h-full" />
+
+ {/* Info Overlay */}
+ <div className="absolute top-2 left-2 text-xs text-gray-500 bg-black/70 px-3 py-2 rounded backdrop-blur-sm">
+ <div className="font-bold text-white mb-1">{symbol}</div>
+ <div className="flex items-center gap-2">
+ <span>{interval}</span>
+ <span>•</span>
+ <span>{candleData.length} candles</span>
+ {hasWebSocket && (
+ <>
+ <span>•</span>
+ <span className="text-green-400">● Live</span>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// Helper: Parse interval for WebSocket
+function parseInterval(interval: string): number {
+ const map: Record<string, number> = {
+ '1m': 1,
+ '5m': 5,
+ '15m': 15,
+ '30m': 30,
+ '1h': 60,
+ '4h': 240,
+ '1d': 1440,
+ };
+ return map[interval] || 1;
+}
+
+// Helper: Parse candle data from WebSocket message
+function parseCandleData(data: any): CandlestickData | null {
+ try {
+ const time = Math.floor((data.time || data.timestamp || Date.now()) / 1000) as Time;
+ const open = parseFloat(data.open || data.o || 0);
+ const high = parseFloat(data.high || data.h || 0);
+ const low = parseFloat(data.low || data.l || 0);
+ const close = parseFloat(data.close || data.c || 0);
+
+ if (open === 0 || high === 0 || low === 0 || close === 0) {
+ return null;
+ }
+
+ return { time, open, high, low, close };
+ } catch (error) {
+ console.error('[TradingChart] Failed to parse candle data:', error);
+ return null;
+ }
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/widgets/FundingRateWidget.tsx b/fincept-terminal-desktop/src/components/tabs/trading/widgets/FundingRateWidget.tsx
new file mode 100644
index 000000000..dcd42a503
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/widgets/FundingRateWidget.tsx
@@ -0,0 +1,99 @@
+// File: src/components/tabs/trading/widgets/FundingRateWidget.tsx
+// Display funding rates for perpetual futures
+
+import React, { useState, useEffect } from 'react';
+import { TrendingUp, TrendingDown } from 'lucide-react';
+
+const COLORS = {
+ ORANGE: '#ea580c',
+ WHITE: '#ffffff',
+ GREEN: '#10b981',
+ RED: '#dc2626',
+ GRAY: '#525252',
+ PANEL_BG: '#1a1a1a',
+};
+
+interface FundingRateWidgetProps {
+ adapter: any;
+ symbol: string;
+}
+
+export function FundingRateWidget({ adapter, symbol }: FundingRateWidgetProps) {
+ const [fundingRate, setFundingRate] = useState<number | null>(null);
+ const [nextFundingTime, setNextFundingTime] = useState<number | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+
+ const { ORANGE, WHITE, GREEN, RED, GRAY, PANEL_BG } = COLORS;
+
+ useEffect(() => {
+ const fetchFundingRate = async () => {
+ if (!adapter || !symbol) return;
+
+ try {
+ setIsLoading(true);
+
+ if ('fetchFundingRate' in adapter) {
+ const data = await adapter.fetchFundingRate(symbol);
+ setFundingRate(data.fundingRate || null);
+ setNextFundingTime(data.fundingTimestamp || null);
+ }
+ } catch (error) {
+ console.error('Failed to fetch funding rate:', error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchFundingRate();
+ const interval = setInterval(fetchFundingRate, 60000); // Update every minute
+
+ return () => clearInterval(interval);
+ }, [adapter, symbol]);
+
+ if (isLoading && fundingRate === null) {
+ return (
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: PANEL_BG,
+ borderBottom: `1px solid ${GRAY}`,
+ }}>
+ <span style={{ fontSize: '10px', color: GRAY }}>Loading funding rate...</span>
+ </div>
+ );
+ }
+
+ if (fundingRate === null) return null;
+
+ const fundingRatePercent = (fundingRate * 100).toFixed(4);
+ const isPositive = fundingRate > 0;
+ const color = isPositive ? RED : GREEN;
+
+ return (
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: PANEL_BG,
+ borderBottom: `1px solid ${GRAY}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ fontSize: '10px', color: GRAY, fontWeight: 'bold', textTransform: 'uppercase' }}>
+ Funding Rate:
+ </span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ {isPositive ? <TrendingUp size={12} style={{ color }} /> : <TrendingDown size={12} style={{ color }} />}
+ <span style={{ fontSize: '11px', fontWeight: 'bold', color }}>
+ {isPositive ? '+' : ''}{fundingRatePercent}%
+ </span>
+ </div>
+ </div>
+
+ {nextFundingTime && (
+ <span style={{ fontSize: '9px', color: '#666' }}>
+ Next: {new Date(nextFundingTime).toLocaleTimeString()}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/widgets/OpenInterestWidget.tsx b/fincept-terminal-desktop/src/components/tabs/trading/widgets/OpenInterestWidget.tsx
new file mode 100644
index 000000000..9f9a1551a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/widgets/OpenInterestWidget.tsx
@@ -0,0 +1,76 @@
+// File: src/components/tabs/trading/widgets/OpenInterestWidget.tsx
+// Display open interest for derivatives
+
+import React, { useState, useEffect } from 'react';
+import { BarChart3 } from 'lucide-react';
+
+const COLORS = {
+ ORANGE: '#ea580c',
+ WHITE: '#ffffff',
+ GRAY: '#525252',
+ PANEL_BG: '#1a1a1a',
+};
+
+interface OpenInterestWidgetProps {
+ adapter: any;
+ symbol: string;
+}
+
+export function OpenInterestWidget({ adapter, symbol }: OpenInterestWidgetProps) {
+ const [openInterest, setOpenInterest] = useState<number | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+
+ const { ORANGE, WHITE, GRAY, PANEL_BG } = COLORS;
+
+ useEffect(() => {
+ const fetchOpenInterest = async () => {
+ if (!adapter || !symbol) return;
+
+ try {
+ setIsLoading(true);
+
+ if ('fetchOpenInterest' in adapter) {
+ const data = await adapter.fetchOpenInterest(symbol);
+ setOpenInterest(data.openInterestValue || data.openInterestAmount || null);
+ }
+ } catch (error) {
+ console.error('Failed to fetch open interest:', error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchOpenInterest();
+ const interval = setInterval(fetchOpenInterest, 30000); // Update every 30s
+
+ return () => clearInterval(interval);
+ }, [adapter, symbol]);
+
+ if (isLoading && openInterest === null) return null;
+ if (openInterest === null) return null;
+
+ const formattedOI = openInterest >= 1000000
+ ? `$${(openInterest / 1000000).toFixed(2)}M`
+ : openInterest >= 1000
+ ? `$${(openInterest / 1000).toFixed(2)}K`
+ : `$${openInterest.toFixed(2)}`;
+
+ return (
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: PANEL_BG,
+ borderBottom: `1px solid ${GRAY}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ }}>
+ <BarChart3 size={12} style={{ color: ORANGE }} />
+ <span style={{ fontSize: '10px', color: GRAY, fontWeight: 'bold', textTransform: 'uppercase' }}>
+ Open Interest:
+ </span>
+ <span style={{ fontSize: '11px', fontWeight: 'bold', color: WHITE }}>
+ {formattedOI}
+ </span>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
new file mode 100644
index 000000000..66bf7d099
--- /dev/null
+++ b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
@@ -0,0 +1,439 @@
+// File: src/contexts/BrokerContext.tsx
+// Unified broker management context for multi-broker trading
+// Replaces ProviderContext with enhanced broker registry support
+
+import React, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef, ReactNode } from 'react';
+import { getWebSocketManager } from '../services/websocket';
+import type { ProviderConfig } from '../services/websocket/types';
+import { ConnectionStatus } from '../services/websocket/types';
+import {
+ BROKER_REGISTRY,
+ getAllBrokers,
+ getBrokerMetadata,
+ createBrokerAdapter,
+ getDefaultSymbols,
+ type BrokerMetadata,
+ type BrokerFeatures,
+ detectBrokerFeatures,
+ createFeatureChecker,
+} from '../brokers';
+import { createPaperTradingAdapter } from '../paper-trading';
+import type { IExchangeAdapter } from '../brokers/crypto/types';
+import type { PaperTradingAdapter } from '../paper-trading/PaperTradingAdapter';
+
+interface BrokerContextType {
+ // Active broker
+ activeBroker: string;
+ activeBrokerMetadata: BrokerMetadata | null;
+ setActiveBroker: (brokerId: string) => Promise<void>;
+
+ // Available brokers
+ availableBrokers: BrokerMetadata[];
+
+ // Trading mode
+ tradingMode: 'live' | 'paper';
+ setTradingMode: (mode: 'live' | 'paper') => void;
+
+ // Broker adapters
+ realAdapter: IExchangeAdapter | null;
+ paperAdapter: PaperTradingAdapter | null;
+ activeAdapter: IExchangeAdapter | PaperTradingAdapter | null;
+
+ // Broker capabilities
+ features: BrokerFeatures | null;
+ supports: ReturnType<typeof createFeatureChecker> | null;
+
+ // Symbol management
+ defaultSymbols: string[];
+
+ // WebSocket
+ providerConfigs: Map<string, ProviderConfig>;
+ updateProviderConfig: (provider: string, config: Partial<ProviderConfig>) => Promise<void>;
+
+ // Loading state
+ isLoading: boolean;
+ isConnecting: boolean;
+}
+
+const BrokerContext = createContext<BrokerContextType | null>(null);
+
+interface BrokerProviderProps {
+ children: ReactNode;
+}
+
+export function BrokerProvider({ children }: BrokerProviderProps) {
+ const [activeBroker, setActiveBrokerState] = useState<string>('kraken');
+ const [tradingMode, setTradingModeState] = useState<'live' | 'paper'>('paper');
+ const [providerConfigs, setProviderConfigs] = useState<Map<string, ProviderConfig>>(new Map());
+ const [isLoading, setIsLoading] = useState(true);
+ const [isConnecting, setIsConnecting] = useState(false);
+
+ // Adapter instances
+ const [realAdapter, setRealAdapter] = useState<IExchangeAdapter | null>(null);
+ const [paperAdapter, setPaperAdapter] = useState<PaperTradingAdapter | null>(null);
+
+ // Get broker metadata
+ const activeBrokerMetadata = useMemo(() => {
+ return getBrokerMetadata(activeBroker) || null;
+ }, [activeBroker]);
+
+ // Get available brokers (only crypto for now)
+ const availableBrokers = useMemo(() => {
+ return getAllBrokers().filter(b => b.type === 'crypto');
+ }, []);
+
+ // Get default symbols
+ const defaultSymbols = useMemo(() => {
+ return getDefaultSymbols(activeBroker);
+ }, [activeBroker]);
+
+ // Detect features
+ const features = useMemo(() => {
+ const adapter = tradingMode === 'paper' ? paperAdapter : realAdapter;
+ return adapter ? detectBrokerFeatures(adapter) : null;
+ }, [realAdapter, paperAdapter, tradingMode]);
+
+ // Create feature checker
+ const supports = useMemo(() => {
+ return features ? createFeatureChecker(features) : null;
+ }, [features]);
+
+ // Get active adapter
+ const activeAdapter = useMemo(() => {
+ return tradingMode === 'paper' ? paperAdapter : realAdapter;
+ }, [tradingMode, realAdapter, paperAdapter]);
+
+ // Load configurations on mount
+ useEffect(() => {
+ const loadConfigurations = async () => {
+ setIsLoading(true);
+
+ try {
+ const manager = getWebSocketManager();
+ const configs = new Map<string, ProviderConfig>();
+
+ // Initialize configs for all available brokers
+ for (const broker of availableBrokers) {
+ if (broker.websocket.enabled && broker.websocket.endpoint) {
+ configs.set(broker.id, {
+ provider_name: broker.id,
+ enabled: true,
+ endpoint: broker.websocket.endpoint,
+ });
+ }
+ }
+
+ setProviderConfigs(configs);
+
+ // Load saved preferences
+ const savedBroker = localStorage.getItem('active_trading_broker');
+ const savedMode = localStorage.getItem('trading_mode') as 'live' | 'paper' | null;
+
+ if (savedBroker && BROKER_REGISTRY[savedBroker]) {
+ setActiveBrokerState(savedBroker);
+ }
+
+ if (savedMode) {
+ setTradingModeState(savedMode);
+ }
+
+ // Apply configurations to WebSocket manager
+ configs.forEach((config, provider) => {
+ manager.setProviderConfig(provider, config);
+ });
+ } catch (error) {
+ console.error('[BrokerContext] Failed to load configurations:', error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ loadConfigurations();
+ }, [availableBrokers]);
+
+ // Initialize adapters when broker changes
+ const isInitializedRef = useRef(false);
+
+ useEffect(() => {
+ console.log(`[BrokerContext] useEffect triggered - activeBroker: ${activeBroker}, isLoading: ${isLoading}, isInitialized: ${isInitializedRef.current}`);
+
+ // Don't initialize while loading configs
+ if (isLoading) {
+ console.log(`[BrokerContext] Skipping initialization - still loading configs`);
+ return;
+ }
+
+ // Don't re-initialize if already initialized (keeps connection alive across tab changes)
+ if (isInitializedRef.current) {
+ console.log(`[BrokerContext] Skipping initialization - already initialized`);
+ return;
+ }
+
+ const initializeAdapters = async () => {
+ setIsConnecting(true);
+
+ try {
+ console.log(`[BrokerContext] ========================================`);
+ console.log(`[BrokerContext] Initializing ${activeBroker} adapters...`);
+ console.log(`[BrokerContext] ========================================`);
+
+ // Clean up old adapters
+ if (realAdapter) {
+ console.log(`[BrokerContext] Disconnecting old real adapter...`);
+ await realAdapter.disconnect();
+ }
+ if (paperAdapter) {
+ console.log(`[BrokerContext] Disconnecting old paper adapter...`);
+ await paperAdapter.disconnect();
+ }
+
+ // Create real adapter
+ console.log(`[BrokerContext] Creating ${activeBroker} real adapter...`);
+ const newRealAdapter = createBrokerAdapter(activeBroker);
+
+ console.log(`[BrokerContext] Connecting ${activeBroker} real adapter...`);
+ await newRealAdapter.connect();
+ console.log(`[BrokerContext] ✓ ${activeBroker} real adapter connected (status: ${newRealAdapter.isConnected() ? 'CONNECTED' : 'NOT CONNECTED'})`);
+
+ setRealAdapter(newRealAdapter);
+
+ // Create paper adapter (wrapping real adapter)
+ // Use a stable portfolio ID based on broker name (reuse existing portfolio instead of creating new ones)
+ console.log(`[BrokerContext] Creating ${activeBroker} paper adapter...`);
+ const portfolioId = `paper_${activeBroker}`; // Stable ID - no timestamp
+ console.log(`[BrokerContext] Portfolio ID: ${portfolioId}`);
+
+ let newPaperAdapter: PaperTradingAdapter;
+
+ try {
+ newPaperAdapter = createPaperTradingAdapter(
+ {
+ portfolioId,
+ portfolioName: `${activeBroker.toUpperCase()} Paper Trading`,
+ provider: activeBroker,
+ assetClass: 'crypto',
+ initialBalance: 100000,
+ currency: 'USD',
+ fees: {
+ maker: activeBroker === 'kraken' ? 0.0002 : 0.0002,
+ taker: activeBroker === 'kraken' ? 0.0005 : 0.0005,
+ },
+ slippage: {
+ market: 0,
+ limit: 0,
+ },
+ enableMarginTrading: true,
+ defaultLeverage: 1,
+ maxLeverage: activeBrokerMetadata?.advancedFeatures.maxLeverage || 1,
+ },
+ newRealAdapter
+ );
+ console.log(`[BrokerContext] ✓ Paper adapter instance created`);
+ } catch (error) {
+ console.error(`[BrokerContext] ✗ Failed to create paper adapter:`, error);
+ throw error;
+ }
+
+ console.log(`[BrokerContext] Connecting ${activeBroker} paper adapter...`);
+ await newPaperAdapter.connect();
+ console.log(`[BrokerContext] ✓ ${activeBroker} paper adapter connected (status: ${newPaperAdapter.isConnected() ? 'CONNECTED' : 'NOT CONNECTED'})`);
+
+ setPaperAdapter(newPaperAdapter);
+ console.log(`[BrokerContext] ✓ setPaperAdapter() called`);
+
+ // Connect WebSocket AFTER adapters are ready
+ const manager = getWebSocketManager();
+ const config = providerConfigs.get(activeBroker);
+
+ console.log(`[BrokerContext] WebSocket config for ${activeBroker}:`, config ? 'EXISTS' : 'MISSING');
+
+ if (config) {
+ console.log(`[BrokerContext] Setting WebSocket config for ${activeBroker}...`);
+ manager.setProviderConfig(activeBroker, config);
+
+ console.log(`[BrokerContext] Connecting WebSocket for ${activeBroker}...`);
+ await manager.connect(activeBroker);
+
+ // Wait for WebSocket to actually OPEN (not just connect call to finish)
+ let wsStatus = manager.getStatus(activeBroker);
+ let waitCount = 0;
+ const maxWait = 20; // 10 seconds max
+
+ while (wsStatus !== ConnectionStatus.CONNECTED && waitCount < maxWait) {
+ console.log(`[BrokerContext] Waiting for WebSocket... (${waitCount + 1}/${maxWait}) - Status: ${wsStatus}`);
+ await new Promise(resolve => setTimeout(resolve, 500));
+ wsStatus = manager.getStatus(activeBroker);
+ waitCount++;
+ }
+
+ console.log(`[BrokerContext] ✓ ${activeBroker} WebSocket status: ${wsStatus}`);
+
+ console.log(`[BrokerContext] ========================================`);
+ console.log(`[BrokerContext] ${activeBroker} initialization complete!`);
+ console.log(`[BrokerContext] Real Adapter: ${newRealAdapter.isConnected() ? '✓ CONNECTED' : '✗ NOT CONNECTED'}`);
+ console.log(`[BrokerContext] Paper Adapter: ${newPaperAdapter.isConnected() ? '✓ CONNECTED' : '✗ NOT CONNECTED'}`);
+ console.log(`[BrokerContext] WebSocket: ${wsStatus}`);
+ console.log(`[BrokerContext] ========================================`);
+ } else {
+ console.warn(`[BrokerContext] No WebSocket config found for ${activeBroker}!`);
+ }
+
+ // Mark as initialized
+ isInitializedRef.current = true;
+ } catch (error) {
+ console.error(`[BrokerContext] ✗ Failed to initialize ${activeBroker}:`, error);
+ console.error(`[BrokerContext] Error details:`, error);
+ console.error(`[BrokerContext] Stack trace:`, (error as Error)?.stack);
+
+ // Set adapters to null on failure
+ setRealAdapter(null);
+ setPaperAdapter(null);
+ } finally {
+ setIsConnecting(false);
+ }
+ };
+
+ initializeAdapters();
+
+ // Cleanup only when broker actually changes (not on tab change)
+ return () => {
+ // Only cleanup if we're switching brokers (flag was reset)
+ if (!isInitializedRef.current && realAdapter) {
+ console.log(`[BrokerContext] Cleanup: Disconnecting adapters for broker switch`);
+ realAdapter.disconnect();
+ if (paperAdapter) {
+ paperAdapter.disconnect();
+ }
+ }
+ };
+ }, [isLoading, activeBroker]); // Depend on activeBroker to handle broker switching
+
+ // Set active broker
+ const setActiveBroker = useCallback(async (brokerId: string) => {
+ if (!BROKER_REGISTRY[brokerId]) {
+ throw new Error(`Broker ${brokerId} is not available`);
+ }
+
+ console.log(`[BrokerContext] Switching to broker: ${brokerId}`);
+
+ // Reset initialization flag to allow switching brokers
+ isInitializedRef.current = false;
+
+ setActiveBrokerState(brokerId);
+
+ // Save preference
+ localStorage.setItem('active_trading_broker', brokerId);
+ }, []);
+
+ // Set trading mode
+ const setTradingMode = useCallback((mode: 'live' | 'paper') => {
+ console.log(`[BrokerContext] Switching to ${mode} mode`);
+ setTradingModeState(mode);
+ localStorage.setItem('trading_mode', mode);
+ }, []);
+
+ // Update provider config
+ const updateProviderConfig = useCallback(async (
+ provider: string,
+ config: Partial<ProviderConfig>
+ ) => {
+ setProviderConfigs(prev => {
+ const newConfigs = new Map(prev);
+ const existingConfig = newConfigs.get(provider);
+
+ const updatedConfig: ProviderConfig = {
+ ...existingConfig,
+ ...config,
+ provider_name: provider,
+ } as ProviderConfig;
+
+ newConfigs.set(provider, updatedConfig);
+
+ // Update WebSocket manager
+ const manager = getWebSocketManager();
+ manager.setProviderConfig(provider, updatedConfig);
+
+ return newConfigs;
+ });
+ }, []);
+
+ return (
+ <BrokerContext.Provider
+ value={{
+ activeBroker,
+ activeBrokerMetadata,
+ setActiveBroker,
+ availableBrokers,
+ tradingMode,
+ setTradingMode,
+ realAdapter,
+ paperAdapter,
+ activeAdapter,
+ features,
+ supports,
+ defaultSymbols,
+ providerConfigs,
+ updateProviderConfig,
+ isLoading,
+ isConnecting,
+ }}
+ >
+ {children}
+ </BrokerContext.Provider>
+ );
+}
+
+export function useBrokerContext(): BrokerContextType {
+ const context = useContext(BrokerContext);
+
+ if (!context) {
+ throw new Error('useBrokerContext must be used within a BrokerProvider');
+ }
+
+ return context;
+}
+
+/**
+ * Hook for quick broker selection
+ */
+export function useBrokerSelection() {
+ const { activeBroker, availableBrokers, setActiveBroker, isLoading } = useBrokerContext();
+
+ return {
+ broker: activeBroker,
+ brokers: availableBrokers,
+ setBroker: setActiveBroker,
+ isLoading,
+ };
+}
+
+/**
+ * Hook for feature checks
+ */
+export function useBrokerFeatures() {
+ const { features, supports } = useBrokerContext();
+
+ return {
+ features,
+ supports,
+ hasFeature: (category: keyof BrokerFeatures, feature: string) => {
+ if (!features) return false;
+ const categoryFeatures = features[category] as any;
+ return categoryFeatures?.[feature] === true;
+ },
+ };
+}
+
+/**
+ * Hook for adapter access
+ */
+export function useBrokerAdapter() {
+ const { activeAdapter, realAdapter, paperAdapter, tradingMode } = useBrokerContext();
+
+ return {
+ adapter: activeAdapter,
+ realAdapter,
+ paperAdapter,
+ tradingMode,
+ };
+}
diff --git a/fincept-terminal-desktop/src/contexts/ProviderContext.tsx b/fincept-terminal-desktop/src/contexts/ProviderContext.tsx
index adf0ee241..427cc8d83 100644
--- a/fincept-terminal-desktop/src/contexts/ProviderContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/ProviderContext.tsx
@@ -1,163 +1,70 @@
// File: src/contexts/ProviderContext.tsx
-// Global provider selection context for multi-provider trading
+// DEPRECATED: This file is kept for backward compatibility only
+// Use BrokerContext instead for new code
-import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
-import { getWebSocketManager } from '../services/websocket';
-import type { ProviderConfig } from '../services/websocket/types';
-import { getAvailableProviders } from '../services/websocket/adapters';
+import React, { ReactNode } from 'react';
+import { BrokerProvider, useBrokerContext } from './BrokerContext';
-interface ProviderContextType {
+// Re-export for backward compatibility
+export interface ProviderContextType {
activeProvider: string;
availableProviders: string[];
setActiveProvider: (provider: string) => Promise<void>;
- providerConfigs: Map<string, ProviderConfig>;
- updateProviderConfig: (provider: string, config: Partial<ProviderConfig>) => Promise<void>;
+ providerConfigs: Map<string, any>;
+ updateProviderConfig: (provider: string, config: Partial<any>) => Promise<void>;
isLoading: boolean;
}
-const ProviderContext = createContext<ProviderContextType | null>(null);
-
interface ProviderProviderProps {
children: ReactNode;
}
+// Wrapper that maps BrokerContext to old ProviderContext interface
export function ProviderProvider({ children }: ProviderProviderProps) {
- const [activeProvider, setActiveProviderState] = useState<string>('kraken');
- const [providerConfigs, setProviderConfigs] = useState<Map<string, ProviderConfig>>(new Map());
- const [isLoading, setIsLoading] = useState(true);
-
- // Get available providers from adapter registry
- const availableProviders = getAvailableProviders();
-
- // Load provider configurations and preferences on mount
- useEffect(() => {
- const loadConfigurations = async () => {
- setIsLoading(true);
-
- try {
- const manager = getWebSocketManager();
-
- // Initialize default configurations for available providers
- const configs = new Map<string, ProviderConfig>();
-
- // Kraken config
- configs.set('kraken', {
- provider_name: 'kraken',
- enabled: true,
- endpoint: 'wss://ws.kraken.com/v2'
- });
-
- // HyperLiquid config
- configs.set('hyperliquid', {
- provider_name: 'hyperliquid',
- enabled: true,
- endpoint: 'wss://api.hyperliquid.xyz/ws',
- config_data: JSON.stringify({ testnet: false })
- });
-
- setProviderConfigs(configs);
-
- // Load saved provider preference from localStorage
- const savedProvider = localStorage.getItem('active_trading_provider');
- if (savedProvider && configs.has(savedProvider)) {
- setActiveProviderState(savedProvider);
- }
-
- // Apply configurations to WebSocket manager
- configs.forEach((config, provider) => {
- manager.setProviderConfig(provider, config);
- });
- } catch (error) {
- console.error('Failed to load provider configurations:', error);
- } finally {
- setIsLoading(false);
- }
- };
-
- loadConfigurations();
- }, []);
-
- const setActiveProvider = useCallback(async (provider: string) => {
- if (!availableProviders.includes(provider)) {
- throw new Error(`Provider ${provider} is not available`);
- }
-
- setActiveProviderState(provider);
-
- // Save preference to localStorage
- localStorage.setItem('active_trading_provider', provider);
-
- // Ensure the provider is connected
- const manager = getWebSocketManager();
- const status = manager.getStatus(provider);
-
- if (status !== 'connected') {
- try {
- await manager.connect(provider);
- } catch (error) {
- console.error(`Failed to connect to ${provider}:`, error);
- }
- }
- }, [availableProviders]);
-
- const updateProviderConfig = useCallback(async (
- provider: string,
- config: Partial<ProviderConfig>
- ) => {
- setProviderConfigs(prev => {
- const newConfigs = new Map(prev);
- const existingConfig = newConfigs.get(provider);
-
- const updatedConfig: ProviderConfig = {
- ...existingConfig,
- ...config,
- provider_name: provider
- } as ProviderConfig;
-
- newConfigs.set(provider, updatedConfig);
-
- // Update WebSocket manager
- const manager = getWebSocketManager();
- manager.setProviderConfig(provider, updatedConfig);
-
- return newConfigs;
- });
- }, []);
-
- return (
- <ProviderContext.Provider value={{
- activeProvider,
- availableProviders,
- setActiveProvider,
- providerConfigs,
- updateProviderConfig,
- isLoading
- }}>
- {children}
- </ProviderContext.Provider>
- );
+ return <BrokerProvider>{children}</BrokerProvider>;
}
export function useProviderContext(): ProviderContextType {
- const context = useContext(ProviderContext);
+ const {
+ activeBroker,
+ availableBrokers,
+ setActiveBroker,
+ providerConfigs,
+ updateProviderConfig,
+ isLoading,
+ } = useBrokerContext();
- if (!context) {
- throw new Error('useProviderContext must be used within a ProviderProvider');
- }
+ return {
+ activeProvider: activeBroker,
+ availableProviders: availableBrokers.map(b => b.id),
+ setActiveProvider: setActiveBroker,
+ providerConfigs,
+ updateProviderConfig,
+ isLoading,
+ };
+}
- return context;
+// Legacy implementation below - kept for reference but not used
+/*
+import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
+import { getWebSocketManager } from '../services/websocket';
+import type { ProviderConfig } from '../services/websocket/types';
+import { getAvailableProviders } from '../services/websocket/adapters';
+
+interface ProviderContextType {
+ activeProvider: string;
+ availableProviders: string[];
+ setActiveProvider: (provider: string) => Promise<void>;
+ providerConfigs: Map<string, ProviderConfig>;
+ updateProviderConfig: (provider: string, config: Partial<ProviderConfig>) => Promise<void>;
+ isLoading: boolean;
}
-/**
- * Hook for quick provider selection
- */
-export function useProviderSelection() {
- const { activeProvider, availableProviders, setActiveProvider, isLoading } = useProviderContext();
+const ProviderContext = createContext<ProviderContextType | null>(null);
- return {
- provider: activeProvider,
- providers: availableProviders,
- setProvider: setActiveProvider,
- isLoading
- };
+interface ProviderProviderProps {
+ children: ReactNode;
}
+
+export function ProviderProvider({ children }: ProviderProviderProps) {
+*/
diff --git a/fincept-terminal-desktop/src/hooks/useWebSocket.ts b/fincept-terminal-desktop/src/hooks/useWebSocket.ts
index d688b1a86..52cdacecb 100644
--- a/fincept-terminal-desktop/src/hooks/useWebSocket.ts
+++ b/fincept-terminal-desktop/src/hooks/useWebSocket.ts
@@ -154,6 +154,17 @@ export function useWebSocket(
* Internal message handler
*/
const handleMessage = useCallback((msg: NormalizedMessage) => {
+ // Only log chart/candle messages
+ if (msg.channel === 'ohlc' || msg.type === 'candle') {
+ console.log(`[useWebSocket] 📊 Chart message:`, {
+ provider: msg.provider,
+ channel: msg.channel,
+ type: msg.type,
+ symbol: msg.symbol,
+ dataKeys: Object.keys(msg.data || {})
+ });
+ }
+
setMessage(msg);
setMessages(prev => {
const updated = [...prev, msg];
@@ -173,6 +184,9 @@ export function useWebSocket(
subscribeTopic: string,
subscribeParams?: Record<string, any>
) => {
+ console.log(`[useWebSocket] 📡 Attempting to subscribe to: ${subscribeTopic}`);
+ console.log(`[useWebSocket] Params:`, subscribeParams || params);
+
try {
setIsLoading(true);
setError(null);
@@ -181,12 +195,18 @@ export function useWebSocket(
// Parse provider from topic
const provider = subscribeTopic.split('.')[0];
+ console.log(`[useWebSocket] Provider: ${provider}`);
+
+ // Check WebSocket status BEFORE subscribing
+ const wsStatus = manager.getStatus(provider);
+ console.log(`[useWebSocket] WebSocket status for ${provider}: ${wsStatus}`);
// Get or create provider config if needed
// Note: Config should be set via setProviderConfig before subscribing
// This is handled in SettingsTab
// Subscribe
+ console.log(`[useWebSocket] Calling manager.subscribe()...`);
const sub = await manager.subscribe(
subscribeTopic,
handleMessage,
@@ -194,10 +214,12 @@ export function useWebSocket(
);
subscriptionRef.current = sub;
+ console.log(`[useWebSocket] ✓ Subscription created: ${sub.id}`);
// Update status
const providerStatus = manager.getStatus(provider);
setStatus(providerStatus);
+ console.log(`[useWebSocket] Final status: ${providerStatus}`);
if (onStatusChange && providerStatus) {
onStatusChange(providerStatus);
@@ -206,11 +228,16 @@ export function useWebSocket(
const error = err instanceof Error ? err : new Error(String(err));
setError(error);
+ console.error(`[useWebSocket] ✗ Subscribe FAILED for ${subscribeTopic}:`, error.message);
+
if (onError) {
onError(error);
}
- console.error('[useWebSocket] Subscribe error:', error);
+ // Only log errors that aren't connection-related (those are logged elsewhere)
+ if (!error.message.includes('not connected') && !error.message.includes('not open')) {
+ console.error('[useWebSocket] Subscribe error:', error);
+ }
} finally {
setIsLoading(false);
}
@@ -292,12 +319,15 @@ export function useWebSocket(
* Auto-subscribe on mount if enabled
*/
useEffect(() => {
- if (topic && autoSubscribe && autoConnect) {
+ let isMounted = true;
+
+ if (topic && autoSubscribe && autoConnect && isMounted) {
subscribe(topic, params);
}
// Cleanup on unmount
return () => {
+ isMounted = false;
unsubscribe();
};
}, [topic, autoSubscribe, autoConnect]); // Intentionally limited dependencies
@@ -311,18 +341,42 @@ export function useWebSocket(
const manager = getWebSocketManager();
const provider = topic.split('.')[0];
let isMounted = true;
+ let isResubscribing = false;
+ let consecutiveFailures = 0;
- const checkInterval = setInterval(() => {
- if (!isMounted) return; // Guard against unmounted component
+ const checkInterval = setInterval(async () => {
+ if (!isMounted || isResubscribing) return; // Guard against unmounted component or concurrent resubscribes
const providerStatus = manager.getStatus(provider);
// If connected but no active subscription, resubscribe
if (providerStatus === ConnectionStatus.CONNECTED && !subscriptionRef.current) {
- console.log(`[useWebSocket] Auto-resubscribing to ${topic} after reconnection`);
- subscribe(topic, params);
+ // Exponential backoff if we're having repeated failures
+ if (consecutiveFailures > 3) {
+ console.debug(`[useWebSocket] Too many consecutive failures for ${topic}, pausing auto-resubscribe`);
+ return;
+ }
+
+ isResubscribing = true;
+ try {
+ console.log(`[useWebSocket] Auto-resubscribing to ${topic} after reconnection`);
+ await subscribe(topic, params);
+ consecutiveFailures = 0; // Reset on success
+ } catch (error) {
+ consecutiveFailures++;
+ // Silently fail - subscription will retry on next interval
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ if (!errorMsg.includes('not connected') && !errorMsg.includes('not open')) {
+ console.debug(`[useWebSocket] Auto-resubscribe failed (attempt ${consecutiveFailures}):`, error);
+ }
+ } finally {
+ isResubscribing = false;
+ }
+ } else if (subscriptionRef.current) {
+ // Reset failure counter when subscription is active
+ consecutiveFailures = 0;
}
- }, 2000);
+ }, 5000); // Increased to 5 seconds to reduce noise
return () => {
isMounted = false;
diff --git a/fincept-terminal-desktop/src/main.tsx b/fincept-terminal-desktop/src/main.tsx
index c83678886..410d48e1f 100644
--- a/fincept-terminal-desktop/src/main.tsx
+++ b/fincept-terminal-desktop/src/main.tsx
@@ -1,18 +1,61 @@
+// CRITICAL: Must be first import to set up Buffer/process globals
+import './polyfills/init'
+
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { AuthProvider } from './contexts/AuthContext'
import { LanguageProvider } from './contexts/LanguageContext'
+import { BrokerProvider } from './contexts/BrokerContext'
import './i18n/config' // Initialize i18n
import './App.css' // Make sure this line exists
import './tauri-cors-config' // Initialize Tauri CORS plugin
+// Error Boundary Component
+class ErrorBoundary extends React.Component<
+ { children: React.ReactNode },
+ { hasError: boolean; error: Error | null }
+> {
+ constructor(props: { children: React.ReactNode }) {
+ super(props);
+ this.state = { hasError: false, error: null };
+ }
+
+ static getDerivedStateFromError(error: Error) {
+ return { hasError: true, error };
+ }
+
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
+ console.error('Error caught by boundary:', error, errorInfo);
+ }
+
+ render() {
+ if (this.state.hasError) {
+ return (
+ <div style={{ padding: '20px', color: 'white', backgroundColor: '#1a1a1a' }}>
+ <h1>Something went wrong</h1>
+ <pre style={{ color: '#ff6b6b' }}>{this.state.error?.toString()}</pre>
+ <pre style={{ fontSize: '12px', marginTop: '10px' }}>
+ {this.state.error?.stack}
+ </pre>
+ </div>
+ );
+ }
+
+ return this.props.children;
+ }
+}
+
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
- <AuthProvider>
- <LanguageProvider>
- <App />
- </LanguageProvider>
- </AuthProvider>
+ <ErrorBoundary>
+ <AuthProvider>
+ <LanguageProvider>
+ <BrokerProvider>
+ <App />
+ </BrokerProvider>
+ </LanguageProvider>
+ </AuthProvider>
+ </ErrorBoundary>
</React.StrictMode>,
)
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
index a903ae622..6fbac2c9d 100644
--- a/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
+++ b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
@@ -22,6 +22,7 @@ export class OrderMatchingEngine {
private balanceManager: PaperTradingBalance;
private monitoringInterval: NodeJS.Timeout | null = null;
private priceCache: Map<string, PriceSnapshot> = new Map();
+ private websocketPriceUpdates: Map<string, PriceSnapshot> = new Map();
constructor(
private config: PaperTradingConfig,
@@ -30,6 +31,20 @@ export class OrderMatchingEngine {
this.balanceManager = new PaperTradingBalance(config);
}
+ /**
+ * Update price from WebSocket feed (for monitoring orders)
+ */
+ updatePriceFromWebSocket(symbol: string, ticker: { bid?: number; ask?: number; last?: number }): void {
+ const snapshot: PriceSnapshot = {
+ symbol,
+ bid: ticker.bid || ticker.last || 0,
+ ask: ticker.ask || ticker.last || 0,
+ last: ticker.last || 0,
+ timestamp: Date.now(),
+ };
+ this.websocketPriceUpdates.set(symbol, snapshot);
+ }
+
// ============================================================================
// ORDER PLACEMENT
// ============================================================================
@@ -649,6 +664,12 @@ export class OrderMatchingEngine {
* Fetch price snapshot from real exchange
*/
private async fetchPriceSnapshot(symbol: string): Promise<PriceSnapshot> {
+ // Prioritize WebSocket price updates for monitoring
+ const wsPrice = this.websocketPriceUpdates.get(symbol);
+ if (wsPrice && Date.now() - wsPrice.timestamp < 2000) {
+ return wsPrice;
+ }
+
const cached = this.priceCache.get(symbol);
const now = Date.now();
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
index a8c1a3497..6b3338d97 100644
--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
@@ -27,8 +27,8 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
private initialized: boolean = false;
constructor(config: ExchangeConfig & { paperTradingConfig: PaperTradingConfig; realAdapter: IExchangeAdapter }) {
- // Initialize base with paper trading exchange ID
- super({ ...config, exchange: `${config.paperTradingConfig.provider}_paper` });
+ // Initialize base with real exchange name (CCXT doesn't support "_paper" suffix)
+ super({ ...config, exchange: config.paperTradingConfig.provider });
this.paperConfig = config.paperTradingConfig;
this.realAdapter = config.realAdapter;
@@ -49,16 +49,26 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
async connect(): Promise<void> {
try {
+ console.log('[PaperTradingAdapter] Starting connection...');
+ console.log('[PaperTradingAdapter] Real adapter connected:', this.realAdapter.isConnected());
+
// Connect to real exchange for market data
if (!this.realAdapter.isConnected()) {
+ console.log('[PaperTradingAdapter] Connecting real adapter...');
await this.realAdapter.connect();
+ console.log('[PaperTradingAdapter] Real adapter connected successfully');
+ } else {
+ console.log('[PaperTradingAdapter] Real adapter already connected, skipping');
}
// Initialize or load portfolio
+ console.log('[PaperTradingAdapter] Initializing portfolio...');
await this.initializePortfolio();
+ console.log('[PaperTradingAdapter] Portfolio initialized');
// Start order monitoring
if (this.paperConfig.enableRealtimeUpdates !== false) {
+ console.log('[PaperTradingAdapter] Starting order monitoring...');
this.matchingEngine.startMonitoring(this.paperConfig.priceUpdateInterval || 1000);
}
@@ -66,10 +76,12 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
this._isAuthenticated = true; // Paper trading doesn't require real auth
this.initialized = true;
+ console.log('[PaperTradingAdapter] ✓ Connection complete!');
this.emit('connected', { exchange: this.id });
this.emit('authenticated', { exchange: this.id });
} catch (error) {
this._isConnected = false;
+ console.error('[PaperTradingAdapter] ✗ Connection failed:', error);
throw this.handleError(error);
}
}
@@ -81,6 +93,72 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
this.emit('disconnected', { exchange: this.id });
}
+ /**
+ * Reset paper trading account to initial state
+ * - Closes all positions
+ * - Cancels all orders
+ * - Resets balance to initial capital
+ * - Clears trade history
+ */
+ async resetAccount(): Promise<void> {
+ console.log('[PaperTradingAdapter] Resetting account...');
+ const portfolioId = this.paperConfig.portfolioId;
+
+ try {
+ // 1. Close all open positions
+ const openPositions = await paperTradingDatabase.getPortfolioPositions(portfolioId, 'open');
+ console.log(`[PaperTradingAdapter] Closing ${openPositions.length} open positions...`);
+ for (const position of openPositions) {
+ await paperTradingDatabase.updatePosition(position.id, {
+ status: 'closed',
+ closedAt: new Date().toISOString(),
+ });
+ }
+
+ // 2. Cancel all pending orders
+ const pendingOrders = await paperTradingDatabase.getPendingOrders(portfolioId);
+ console.log(`[PaperTradingAdapter] Cancelling ${pendingOrders.length} pending orders...`);
+ for (const order of pendingOrders) {
+ await paperTradingDatabase.updateOrder(order.id, { status: 'canceled' });
+ }
+
+ // 3. Delete all positions (to clean up)
+ console.log('[PaperTradingAdapter] Deleting all positions...');
+ const allPositions = await paperTradingDatabase.getPortfolioPositions(portfolioId);
+ for (const position of allPositions) {
+ await paperTradingDatabase.deletePosition(position.id);
+ }
+
+ // 4. Delete all orders (to clean up)
+ console.log('[PaperTradingAdapter] Deleting all orders...');
+ const allOrders = await paperTradingDatabase.getPortfolioOrders(portfolioId);
+ for (const order of allOrders) {
+ await paperTradingDatabase.deleteOrder(order.id);
+ }
+
+ // 5. Delete all trades (to clean up)
+ console.log('[PaperTradingAdapter] Deleting all trades...');
+ const allTrades = await paperTradingDatabase.getPortfolioTrades(portfolioId);
+ for (const trade of allTrades) {
+ await paperTradingDatabase.deleteTrade(trade.id);
+ }
+
+ // 6. Reset balance to initial capital
+ const initialBalance = this.paperConfig.initialBalance;
+ console.log(`[PaperTradingAdapter] Resetting balance to ${initialBalance}...`);
+ await paperTradingDatabase.updatePortfolioBalance(portfolioId, initialBalance);
+
+ // 7. Reinitialize balance manager
+ this.balanceManager = new PaperTradingBalance(this.paperConfig);
+
+ console.log('[PaperTradingAdapter] ✓ Account reset complete!');
+ this.emit('reset', { exchange: this.id, portfolioId });
+ } catch (error) {
+ console.error('[PaperTradingAdapter] ✗ Reset failed:', error);
+ throw error;
+ }
+ }
+
async authenticate(credentials: ExchangeCredentials): Promise<void> {
// Paper trading doesn't require authentication
// but we'll mark as authenticated for consistency
@@ -177,7 +255,40 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
throw new Error('Paper trading adapter not initialized. Call connect() first.');
}
+ console.log('[PaperTradingAdapter] fetchPositions called');
+ console.log('[PaperTradingAdapter] Portfolio ID:', this.paperConfig.portfolioId);
+
const positions = await paperTradingDatabase.getPortfolioPositions(this.paperConfig.portfolioId, 'open');
+ console.log('[PaperTradingAdapter] Raw open positions from DB:', positions.length);
+
+ // Also check ALL positions to see if there are closed ones
+ const allPositions = await paperTradingDatabase.getPortfolioPositions(this.paperConfig.portfolioId);
+ console.log('[PaperTradingAdapter] Total positions (open + closed):', allPositions.length);
+ allPositions.forEach(p => {
+ console.log(` Position: ${p.symbol} ${p.side} ${p.quantity} @ ${p.entryPrice} - Status: ${p.status}`);
+ });
+
+ // Update positions with current prices
+ for (const p of positions) {
+ try {
+ const ticker = await this.realAdapter.fetchTicker(p.symbol);
+ const currentPrice = ticker.last || ticker.close || p.currentPrice || p.entryPrice;
+
+ const unrealizedPnl = p.side === 'long'
+ ? (currentPrice - p.entryPrice) * p.quantity
+ : (p.entryPrice - currentPrice) * p.quantity;
+
+ await paperTradingDatabase.updatePosition(p.id, {
+ currentPrice,
+ unrealizedPnl,
+ });
+
+ p.currentPrice = currentPrice;
+ p.unrealizedPnl = unrealizedPnl;
+ } catch (err) {
+ console.warn(`[PaperTradingAdapter] Failed to update price for ${p.symbol}`);
+ }
+ }
// Convert to CCXT Position format
const ccxtPositions: Position[] = positions
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
index bb2722daa..418cac815 100644
--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
@@ -124,11 +124,15 @@ export class PaperTradingBalance {
leverage: number,
marginMode: 'cross' | 'isolated'
): Promise<PaperTradingPosition> {
- const existingPosition = await paperTradingDatabase.getPositionBySymbol(portfolioId, symbol, 'open');
+ // Determine position side from order side
+ const positionSide = side === 'buy' ? 'long' : 'short';
+
+ // Check for existing position WITH THE SAME SIDE (hedging mode)
+ const existingPosition = await paperTradingDatabase.getPositionBySymbolAndSide(portfolioId, symbol, positionSide, 'open');
if (!existingPosition) {
// Create new position
- const positionSide = side === 'buy' ? 'long' : 'short';
+ console.log(`[PaperTradingBalance] Creating new ${positionSide} position for ${symbol}`);
const positionId = `pos_${Date.now()}_${Math.random().toString(36).substring(7)}`;
const liquidationPrice = this.calculateLiquidationPrice(
@@ -157,101 +161,35 @@ export class PaperTradingBalance {
return position;
} else {
- // Update existing position
- const positionSide = existingPosition.side;
- const orderDirection = side === 'buy' ? 'long' : 'short';
-
- if (positionSide === orderDirection) {
- // Adding to position - calculate new average entry price (VWAP)
- const totalValue = existingPosition.entryPrice * existingPosition.quantity + fillPrice * fillQuantity;
- const totalQuantity = existingPosition.quantity + fillQuantity;
- const newEntryPrice = totalValue / totalQuantity;
-
- const liquidationPrice = this.calculateLiquidationPrice(
- positionSide,
- newEntryPrice,
- leverage,
- totalQuantity
- );
-
- await paperTradingDatabase.updatePosition(existingPosition.id, {
- quantity: totalQuantity,
- entryPrice: newEntryPrice,
- liquidationPrice,
- });
- } else {
- // Reducing or closing position
- const remainingQuantity = existingPosition.quantity - fillQuantity;
-
- if (remainingQuantity <= 0) {
- // Position fully closed - calculate realized P&L
- const realizedPnl = this.calculateRealizedPnL(
- existingPosition.side,
- existingPosition.entryPrice,
- fillPrice,
- existingPosition.quantity
- );
-
- await paperTradingDatabase.updatePosition(existingPosition.id, {
- quantity: 0,
- realizedPnl: existingPosition.realizedPnl + realizedPnl,
- status: 'closed',
- closedAt: new Date().toISOString(),
- });
-
- // If overfilled, create new position in opposite direction
- if (remainingQuantity < 0) {
- const reversalQuantity = Math.abs(remainingQuantity);
- const newPositionSide = positionSide === 'long' ? 'short' : 'long';
- const newPositionId = `pos_${Date.now()}_${Math.random().toString(36).substring(7)}`;
-
- const liquidationPrice = this.calculateLiquidationPrice(
- newPositionSide,
- fillPrice,
- leverage,
- reversalQuantity
- );
-
- await paperTradingDatabase.createPosition({
- id: newPositionId,
- portfolioId,
- symbol,
- side: newPositionSide,
- entryPrice: fillPrice,
- quantity: reversalQuantity,
- leverage,
- marginMode,
- });
-
- await paperTradingDatabase.updatePosition(newPositionId, { liquidationPrice });
- }
- } else {
- // Position partially closed
- const closedQuantity = fillQuantity;
- const realizedPnl = this.calculateRealizedPnL(
- existingPosition.side,
- existingPosition.entryPrice,
- fillPrice,
- closedQuantity
- );
-
- const liquidationPrice = this.calculateLiquidationPrice(
- existingPosition.side,
- existingPosition.entryPrice,
- leverage,
- remainingQuantity
- );
-
- await paperTradingDatabase.updatePosition(existingPosition.id, {
- quantity: remainingQuantity,
- realizedPnl: existingPosition.realizedPnl + realizedPnl,
- liquidationPrice,
- });
- }
- }
+ // Position exists with same side - ADD to position (VWAP averaging)
+ console.log(`[PaperTradingBalance] Adding to existing ${positionSide} position for ${symbol}`);
+ console.log(` Existing: ${existingPosition.quantity} @ ${existingPosition.entryPrice}`);
+ console.log(` Adding: ${fillQuantity} @ ${fillPrice}`);
+
+ // Calculate new average entry price (VWAP - Volume Weighted Average Price)
+ const totalValue = existingPosition.entryPrice * existingPosition.quantity + fillPrice * fillQuantity;
+ const totalQuantity = existingPosition.quantity + fillQuantity;
+ const newEntryPrice = totalValue / totalQuantity;
+
+ console.log(` New position: ${totalQuantity} @ ${newEntryPrice}`);
+
+ const liquidationPrice = this.calculateLiquidationPrice(
+ positionSide,
+ newEntryPrice,
+ leverage,
+ totalQuantity
+ );
+
+ await paperTradingDatabase.updatePosition(existingPosition.id, {
+ quantity: totalQuantity,
+ entryPrice: newEntryPrice,
+ liquidationPrice,
+ });
+
+ const updatedPosition = await paperTradingDatabase.getPosition(existingPosition.id);
+ if (!updatedPosition) throw new Error('Failed to retrieve updated position');
- const updatedPosition = await paperTradingDatabase.getPositionBySymbol(portfolioId, symbol, 'open');
- return updatedPosition!;
+ return updatedPosition;
}
}
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts
index f33e874b4..05793b54e 100644
--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts
@@ -110,10 +110,12 @@ export class PaperTradingDatabase {
leverage?: number;
marginMode?: 'cross' | 'isolated';
}): Promise<void> {
+ const positionValue = position.entryPrice * position.quantity;
+
const sql = `
INSERT INTO paper_trading_positions
- (id, portfolio_id, symbol, side, entry_price, quantity, leverage, margin_mode, status)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'open')
+ (id, portfolio_id, symbol, side, entry_price, quantity, position_value, leverage, margin_mode, status)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'open')
`;
await sqliteService.execute(sql, [
@@ -123,6 +125,7 @@ export class PaperTradingDatabase {
position.side,
position.entryPrice,
position.quantity,
+ positionValue,
position.leverage || 1,
position.marginMode || 'cross',
]);
@@ -130,7 +133,7 @@ export class PaperTradingDatabase {
async getPosition(positionId: string): Promise<PaperTradingPosition | null> {
const sql = `
- SELECT id, portfolio_id, symbol, side, entry_price, quantity,
+ SELECT id, portfolio_id, symbol, side, entry_price, quantity, position_value,
current_price, unrealized_pnl, realized_pnl, leverage, margin_mode,
liquidation_price, opened_at, closed_at, status
FROM paper_trading_positions
@@ -148,7 +151,7 @@ export class PaperTradingDatabase {
async getPositionBySymbol(portfolioId: string, symbol: string, status: 'open' | 'closed' = 'open'): Promise<PaperTradingPosition | null> {
const sql = `
- SELECT id, portfolio_id, symbol, side, entry_price, quantity,
+ SELECT id, portfolio_id, symbol, side, entry_price, quantity, position_value,
current_price, unrealized_pnl, realized_pnl, leverage, margin_mode,
liquidation_price, opened_at, closed_at, status
FROM paper_trading_positions
@@ -166,9 +169,34 @@ export class PaperTradingDatabase {
return this.mapDBPosition(result[0]);
}
+ async getPositionBySymbolAndSide(
+ portfolioId: string,
+ symbol: string,
+ side: 'long' | 'short',
+ status: 'open' | 'closed' = 'open'
+ ): Promise<PaperTradingPosition | null> {
+ const sql = `
+ SELECT id, portfolio_id, symbol, side, entry_price, quantity, position_value,
+ current_price, unrealized_pnl, realized_pnl, leverage, margin_mode,
+ liquidation_price, opened_at, closed_at, status
+ FROM paper_trading_positions
+ WHERE portfolio_id = $1 AND symbol = $2 AND side = $3 AND status = $4
+ ORDER BY opened_at DESC
+ LIMIT 1
+ `;
+
+ const result = await sqliteService.select<DBPosition[]>(sql, [portfolioId, symbol, side, status]);
+
+ if (!result || result.length === 0) {
+ return null;
+ }
+
+ return this.mapDBPosition(result[0]);
+ }
+
async getPortfolioPositions(portfolioId: string, status?: 'open' | 'closed'): Promise<PaperTradingPosition[]> {
let sql = `
- SELECT id, portfolio_id, symbol, side, entry_price, quantity,
+ SELECT id, portfolio_id, symbol, side, entry_price, quantity, position_value,
current_price, unrealized_pnl, realized_pnl, leverage, margin_mode,
liquidation_price, opened_at, closed_at, status
FROM paper_trading_positions
@@ -487,6 +515,11 @@ export class PaperTradingDatabase {
return result.map(row => this.mapDBTrade(row));
}
+ async deleteTrade(tradeId: string): Promise<void> {
+ const sql = `DELETE FROM paper_trading_trades WHERE id = $1`;
+ await sqliteService.execute(sql, [tradeId]);
+ }
+
// ============================================================================
// MAPPING FUNCTIONS
// ============================================================================
@@ -514,6 +547,7 @@ export class PaperTradingDatabase {
side: row.side,
entryPrice: row.entry_price,
quantity: row.quantity,
+ positionValue: row.position_value,
currentPrice: row.current_price,
unrealizedPnl: row.unrealized_pnl,
realizedPnl: row.realized_pnl,
diff --git a/fincept-terminal-desktop/src/paper-trading/types.ts b/fincept-terminal-desktop/src/paper-trading/types.ts
index 554bf2d59..bcae93676 100644
--- a/fincept-terminal-desktop/src/paper-trading/types.ts
+++ b/fincept-terminal-desktop/src/paper-trading/types.ts
@@ -12,6 +12,7 @@ export type OrderType =
| 'market'
| 'limit'
| 'stop'
+ | 'stop_market'
| 'stop_limit'
| 'trailing_stop'
| 'iceberg'
@@ -107,6 +108,7 @@ export interface PaperTradingPosition {
side: 'long' | 'short';
entryPrice: number;
quantity: number;
+ positionValue: number;
currentPrice: number | null;
unrealizedPnl: number | null;
realizedPnl: number;
@@ -260,6 +262,7 @@ export interface DBPosition {
side: 'long' | 'short';
entry_price: number;
quantity: number;
+ position_value: number;
current_price: number | null;
unrealized_pnl: number | null;
realized_pnl: number;
diff --git a/fincept-terminal-desktop/src/polyfills/assert-shim.ts b/fincept-terminal-desktop/src/polyfills/assert-shim.ts
new file mode 100644
index 000000000..0ec3fa98f
--- /dev/null
+++ b/fincept-terminal-desktop/src/polyfills/assert-shim.ts
@@ -0,0 +1,20 @@
+// Browser polyfill for node assert module
+export default function assert(value: any, message?: string): asserts value {
+ if (!value) {
+ throw new Error(message || 'Assertion failed');
+ }
+}
+
+export const ok = assert;
+
+export function strictEqual(actual: any, expected: any, message?: string): void {
+ if (actual !== expected) {
+ throw new Error(message || `Expected ${actual} to strictly equal ${expected}`);
+ }
+}
+
+export function deepStrictEqual(actual: any, expected: any, message?: string): void {
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {
+ throw new Error(message || `Expected ${JSON.stringify(actual)} to deep equal ${JSON.stringify(expected)}`);
+ }
+}
diff --git a/fincept-terminal-desktop/src/polyfills/init.ts b/fincept-terminal-desktop/src/polyfills/init.ts
new file mode 100644
index 000000000..5828a759a
--- /dev/null
+++ b/fincept-terminal-desktop/src/polyfills/init.ts
@@ -0,0 +1,26 @@
+// This file MUST be imported first before any other modules
+import { Buffer } from 'buffer';
+
+// Create a minimal process shim with all required properties
+const processShim: any = {
+ version: 'v18.0.0',
+ browser: true,
+ env: { NODE_ENV: 'development' },
+ nextTick: (fn: Function, ...args: any[]) => {
+ setTimeout(() => fn(...args), 0);
+ },
+ cwd: () => '/',
+ platform: 'browser',
+ argv: [],
+ pid: 1
+};
+
+// Inject globals immediately BEFORE any imports that might need them
+(globalThis as any).Buffer = Buffer;
+(globalThis as any).global = globalThis;
+(globalThis as any).process = processShim;
+(window as any).Buffer = Buffer;
+(window as any).process = processShim;
+
+// Export to ensure this module runs
+export {};
diff --git a/fincept-terminal-desktop/src/polyfills/net-shim.ts b/fincept-terminal-desktop/src/polyfills/net-shim.ts
new file mode 100644
index 000000000..d7d61d0fb
--- /dev/null
+++ b/fincept-terminal-desktop/src/polyfills/net-shim.ts
@@ -0,0 +1,28 @@
+// Browser polyfill for node:net module
+export const isIP = (input: string): number => {
+ // Simple IP validation for browser environment
+ const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
+ const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
+
+ if (ipv4Regex.test(input)) return 4;
+ if (ipv6Regex.test(input)) return 6;
+ return 0;
+};
+
+export const isIPv4 = (input: string): boolean => isIP(input) === 4;
+export const isIPv6 = (input: string): boolean => isIP(input) === 6;
+
+// Stub for net.connect - not functional in browser
+export const connect = (...args: any[]): any => {
+ console.warn('net.connect is not supported in browser environment');
+ return null;
+};
+
+// Stub for Socket class - not functional in browser
+export class Socket {
+ constructor(...args: any[]) {
+ console.warn('net.Socket is not supported in browser environment');
+ }
+}
+
+export default { isIP, isIPv4, isIPv6, connect, Socket };
diff --git a/fincept-terminal-desktop/src/polyfills/vm-shim.ts b/fincept-terminal-desktop/src/polyfills/vm-shim.ts
new file mode 100644
index 000000000..fe444d592
--- /dev/null
+++ b/fincept-terminal-desktop/src/polyfills/vm-shim.ts
@@ -0,0 +1,24 @@
+// Browser polyfill for node vm module
+export function runInNewContext(code: string, sandbox?: any): any {
+ // In browser, we can't truly create a VM context
+ // This is a minimal polyfill that may not work for all cases
+ console.warn('vm.runInNewContext is not fully supported in browser');
+ try {
+ const func = new Function(...Object.keys(sandbox || {}), code);
+ return func(...Object.values(sandbox || {}));
+ } catch (error) {
+ console.error('Error running code in new context:', error);
+ return undefined;
+ }
+}
+
+export function runInThisContext(code: string): any {
+ try {
+ return eval(code);
+ } catch (error) {
+ console.error('Error running code in this context:', error);
+ return undefined;
+ }
+}
+
+export default { runInNewContext, runInThisContext };
diff --git a/fincept-terminal-desktop/src/services/fyers-auth.js b/fincept-terminal-desktop/src/services/fyers-auth.js
deleted file mode 100644
index dbb2508e3..000000000
--- a/fincept-terminal-desktop/src/services/fyers-auth.js
+++ /dev/null
@@ -1,163 +0,0 @@
-const axios = require("axios");
-const { authenticator } = require("otplib");
-const crypto = require("crypto");
-const { JSDOM } = require("jsdom");
-
-// Mock browser environment
-const dom = new JSDOM("", { url: "http://localhost", pretendToBeVisual: true });
-global.window = dom.window;
-global.document = window.document;
-global.navigator = window.navigator;
-global.WebSocket = require("ws");
-
-const { fyersDataSocket, fyersOrderSocket } = require("fyers-web-sdk-v3");
-
-// Configuration
-const CONFIG = {
- CLIENT_ID: "XB02507",
- PIN: "1590",
- APP_ID: "NDM5TDN9DB",
- APP_TYPE: "100",
- APP_SECRET: "UR9IJU1U0E",
- TOTP_KEY: "XOYMD3QRDV6QPNSWK3WSKMD642KGODJQ",
-};
-
-async function authenticate() {
- let res = await axios.post("https://api-t2.fyers.in/vagator/v2/send_login_otp", {
- fy_id: CONFIG.CLIENT_ID,
- app_id: "2",
- });
- let key = res.data.request_key;
-
- const totp = authenticator.generate(CONFIG.TOTP_KEY);
- res = await axios.post("https://api-t2.fyers.in/vagator/v2/verify_otp", {
- request_key: key,
- otp: totp,
- });
- key = res.data.request_key;
-
- res = await axios.post("https://api-t2.fyers.in/vagator/v2/verify_pin", {
- request_key: key,
- identity_type: "pin",
- identifier: CONFIG.PIN,
- });
- const token1 = res.data.data.access_token;
-
- try {
- res = await axios.post(
- "https://api-t1.fyers.in/api/v3/token",
- {
- fyers_id: CONFIG.CLIENT_ID,
- app_id: CONFIG.APP_ID,
- redirect_uri: "https://trade.fyers.in/api-login/redirect-uri/index.html",
- appType: CONFIG.APP_TYPE,
- code_challenge: "",
- state: "sample_state",
- scope: "",
- nonce: "",
- response_type: "code",
- create_cookie: true,
- },
- { headers: { Authorization: `Bearer ${token1}` }, validateStatus: () => true }
- );
- } catch (error) {
- res = error.response;
- }
-
- const authCode = new URL(res.data.Url).searchParams.get("auth_code");
- const hash = crypto.createHash("sha256").update(`${CONFIG.APP_ID}-${CONFIG.APP_TYPE}:${CONFIG.APP_SECRET}`).digest("hex");
-
- res = await axios.post("https://api-t1.fyers.in/api/v3/validate-authcode", {
- grant_type: "authorization_code",
- appIdHash: hash,
- code: authCode,
- });
-
- return `${CONFIG.APP_ID}-${CONFIG.APP_TYPE}:${res.data.access_token}`;
-}
-
-async function main() {
- const accessToken = await authenticate();
- console.log("Authenticated successfully\n");
-
- // === MARKET DATA WebSocket ===
- const fyersData = new fyersDataSocket(accessToken);
-
- fyersData.on("connect", () => {
- console.log("Market Data WebSocket CONNECTED\n");
- fyersData.subscribe(["NSE:PCJEWELLER-EQ"]);
- });
-
- fyersData.on("message", (msg) => {
- console.log("\n=== MARKET DATA ===");
- console.log(JSON.stringify(msg, null, 2));
- console.log("===================\n");
- });
-
- fyersData.on("error", (err) => {
- console.log("\n=== MARKET DATA ERROR ===");
- console.log(JSON.stringify(err, null, 2));
- console.log("=========================\n");
- });
-
- fyersData.autoreconnect();
- fyersData.connect();
-
- // === ORDER WebSocket ===
- const fyersOrderdata = new fyersOrderSocket(accessToken);
-
- fyersOrderdata.on("error", (errmsg) => {
- console.log("\n=== ORDER ERROR ===");
- console.log(JSON.stringify(errmsg, null, 2));
- console.log("===================\n");
- });
-
- fyersOrderdata.on("general", (msg) => {
- console.log("\n=== ORDER GENERAL ===");
- console.log(JSON.stringify(msg, null, 2));
- console.log("=====================\n");
- });
-
- fyersOrderdata.on("connect", () => {
- console.log("Order WebSocket CONNECTED\n");
- fyersOrderdata.subscribe([
- fyersOrderdata.orderUpdates,
- fyersOrderdata.tradeUpdates,
- fyersOrderdata.positionUpdates,
- fyersOrderdata.edis,
- fyersOrderdata.pricealerts
- ]);
- });
-
- fyersOrderdata.on("close", () => {
- console.log("\n=== ORDER WEBSOCKET CLOSED ===\n");
- });
-
- fyersOrderdata.on("orders", (msg) => {
- console.log("\n=== ORDER UPDATE ===");
- console.log(JSON.stringify(msg, null, 2));
- console.log("====================\n");
- });
-
- fyersOrderdata.on("trades", (msg) => {
- console.log("\n=== TRADE UPDATE ===");
- console.log(JSON.stringify(msg, null, 2));
- console.log("====================\n");
- });
-
- fyersOrderdata.on("positions", (msg) => {
- console.log("\n=== POSITION UPDATE ===");
- console.log(JSON.stringify(msg, null, 2));
- console.log("=======================\n");
- });
-
- fyersOrderdata.autoreconnect();
- fyersOrderdata.connect();
-
- process.on("SIGINT", () => {
- console.log("\nDisconnecting...");
- process.exit(0);
- });
-}
-
-main().catch(console.error);
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/services/newsService.ts b/fincept-terminal-desktop/src/services/newsService.ts
index 7fcea59fc..ecbf738ce 100644
--- a/fincept-terminal-desktop/src/services/newsService.ts
+++ b/fincept-terminal-desktop/src/services/newsService.ts
@@ -203,11 +203,11 @@ function parseRSSFeed(xmlText: string, feedConfig: typeof RSS_FEEDS[0]): NewsArt
pubDate
});
} catch (err) {
- console.error('Error parsing item:', err);
+ // Silently skip problematic items
}
});
} catch (error) {
- console.error('Error parsing RSS feed:', error);
+ // Silently skip feed parsing errors
}
return articles;
@@ -235,7 +235,6 @@ async function fetchRSSFeed(feedConfig: typeof RSS_FEEDS[0]): Promise<NewsArticl
clearTimeout(timeoutId);
if (!response.ok) {
- console.log(`✗ ${feedConfig.name} via proxy ${i+1}: HTTP ${response.status}`);
continue; // Try next proxy
}
@@ -253,25 +252,19 @@ async function fetchRSSFeed(feedConfig: typeof RSS_FEEDS[0]): Promise<NewsArticl
// Validate response is XML before parsing
if (!xmlText || !xmlText.trim().startsWith('<')) {
- console.log(`✗ ${feedConfig.name} via proxy ${i+1}: Not XML`);
continue; // Try next proxy
}
const articles = parseRSSFeed(xmlText, feedConfig);
if (articles.length > 0) {
- console.log(`✓ Fetched ${articles.length} articles from ${feedConfig.name} via proxy ${i+1}`);
return articles;
- } else {
- console.log(`✗ ${feedConfig.name} via proxy ${i+1}: Parsed 0 articles`);
}
} catch (error: any) {
- console.log(`✗ ${feedConfig.name} via proxy ${i+1}: ${error.message}`);
continue;
}
}
- console.log(`✗ ${feedConfig.name}: All ${CORS_PROXIES.length} proxies failed`);
return [];
}
@@ -302,7 +295,6 @@ export async function fetchAllNews(): Promise<NewsArticle[]> {
return dateB.getTime() - dateA.getTime();
});
- console.log(`✓ Loaded ${allArticles.length} articles from ${successfulFeeds}/${RSS_FEEDS.length} feeds`);
return allArticles;
}
@@ -317,12 +309,9 @@ export async function fetchNewsWithCache(forceRefresh: boolean = false): Promise
// Return cached news if still valid and not forcing refresh
if (!forceRefresh && cachedNews.length > 0 && (now - lastFetchTime) < CACHE_DURATION) {
- console.log(`📋 Using cached news (${cachedNews.length} articles)`);
return cachedNews;
}
- console.log(`🔄 Fetching fresh news from ${RSS_FEEDS.length} feeds...`);
-
// On first load or force refresh, fetch real news immediately
try {
const fetchedNews = await fetchAllNews();
@@ -331,25 +320,19 @@ export async function fetchNewsWithCache(forceRefresh: boolean = false): Promise
cachedNews = fetchedNews;
useMockData = false;
lastFetchTime = Date.now();
- console.log(`✅ Cache updated with ${cachedNews.length} articles`);
return cachedNews;
} else {
// Only use mock data if real fetch completely fails and we have no cache
if (cachedNews.length === 0) {
- console.log('⚠ Using demo data - no live feeds available');
cachedNews = generateMockNews();
useMockData = true;
lastFetchTime = Date.now();
- } else {
- console.log('⚠ Fetch returned 0 articles, keeping cache');
}
return cachedNews;
}
} catch (err) {
- console.error('❌ Fetch error:', err);
// Only use mock data if real fetch completely fails and we have no cache
if (cachedNews.length === 0) {
- console.log('⚠ Using demo data - fetch failed');
cachedNews = generateMockNews();
useMockData = true;
lastFetchTime = Date.now();
diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.ts
index df408a5e3..197f36282 100644
--- a/fincept-terminal-desktop/src/services/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/sqliteService.ts
@@ -347,6 +347,9 @@ class SQLiteService {
provider TEXT NOT NULL,
initial_balance REAL NOT NULL DEFAULT 100000,
current_balance REAL NOT NULL,
+ currency TEXT DEFAULT 'USD',
+ margin_mode TEXT DEFAULT 'cross',
+ leverage REAL DEFAULT 1,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)`,
@@ -359,9 +362,13 @@ class SQLiteService {
side TEXT NOT NULL CHECK (side IN ('long', 'short')),
entry_price REAL NOT NULL,
quantity REAL NOT NULL,
+ position_value REAL,
current_price REAL,
unrealized_pnl REAL,
realized_pnl REAL DEFAULT 0,
+ leverage REAL DEFAULT 1,
+ margin_mode TEXT DEFAULT 'cross',
+ liquidation_price REAL,
opened_at TEXT DEFAULT CURRENT_TIMESTAMP,
closed_at TEXT,
status TEXT NOT NULL CHECK (status IN ('open', 'closed')),
@@ -381,8 +388,17 @@ class SQLiteService {
filled_quantity REAL DEFAULT 0,
avg_fill_price REAL,
status TEXT NOT NULL CHECK (status IN ('pending', 'filled', 'partial', 'cancelled', 'rejected', 'triggered')),
+ time_in_force TEXT DEFAULT 'GTC',
+ post_only INTEGER DEFAULT 0,
+ reduce_only INTEGER DEFAULT 0,
+ trailing_percent REAL,
+ trailing_amount REAL,
+ iceberg_qty REAL,
+ leverage REAL,
+ margin_mode TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
filled_at TEXT,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE
)`,
@@ -396,6 +412,8 @@ class SQLiteService {
price REAL NOT NULL,
quantity REAL NOT NULL,
fee REAL DEFAULT 0,
+ fee_rate REAL DEFAULT 0,
+ is_maker INTEGER DEFAULT 0,
timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE,
FOREIGN KEY (order_id) REFERENCES paper_trading_orders(id) ON DELETE CASCADE
@@ -458,6 +476,9 @@ class SQLiteService {
PRIMARY KEY (symbol, category)
)`,
+ // Migration: Add position_value column if it doesn't exist
+ `ALTER TABLE paper_trading_positions ADD COLUMN position_value REAL`,
+
// Data source connections table
`CREATE TABLE IF NOT EXISTS data_source_connections (
id TEXT PRIMARY KEY,
@@ -626,7 +647,25 @@ class SQLiteService {
];
for (const sql of statements) {
- await this.db.execute(sql);
+ try {
+ await this.db.execute(sql);
+ } catch (error: any) {
+ // Ignore "duplicate column" errors from ALTER TABLE
+ if (!error.message?.includes('duplicate column')) {
+ throw error;
+ }
+ }
+ }
+
+ // Update existing positions to populate position_value
+ try {
+ await this.db.execute(`
+ UPDATE paper_trading_positions
+ SET position_value = entry_price * quantity
+ WHERE position_value IS NULL
+ `);
+ } catch (error) {
+ console.error('[SQLite] Failed to populate position_value:', error);
}
}
diff --git a/fincept-terminal-desktop/src/services/websocket/EventBus.ts b/fincept-terminal-desktop/src/services/websocket/EventBus.ts
index 8e09d0564..154e65ca7 100644
--- a/fincept-terminal-desktop/src/services/websocket/EventBus.ts
+++ b/fincept-terminal-desktop/src/services/websocket/EventBus.ts
@@ -134,8 +134,9 @@ export class EventBus {
// Find all matching subscriptions
const matchingSubscriptions = this.findMatchingSubscriptions(topic);
- if (this.enableLogging && matchingSubscriptions.length > 0) {
- console.log(`[EventBus] Publishing to ${matchingSubscriptions.length} subscribers: ${topic}`);
+ // Only log chart/candle related messages
+ if (this.enableLogging && matchingSubscriptions.length > 0 && (topic.includes('ohlc') || topic.includes('candle'))) {
+ console.log(`[EventBus] 📊 Publishing chart data to ${matchingSubscriptions.length} subscribers: ${topic}`);
}
// Deliver message to all matching subscribers
diff --git a/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts b/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
index 54d41b62c..3d2ff1c15 100644
--- a/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
+++ b/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
@@ -49,6 +49,9 @@ export class WebSocketManager {
// Track subscriptions for cleanup
private activeSubscriptions: Map<string, Subscription> = new Map();
+ // Track ongoing connections to prevent duplicates
+ private connectingProviders: Set<string> = new Set();
+
constructor(config?: Partial<WebSocketManagerConfig>) {
this.config = { ...DEFAULT_MANAGER_CONFIG, ...config };
this.eventBus = globalEventBus;
@@ -116,7 +119,13 @@ export class WebSocketManager {
return subscription;
} catch (error) {
- console.error(`[WebSocketManager] Subscribe failed for ${topic}:`, error);
+ // Only log non-connection errors (connection errors are expected during reconnects)
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ if (!errorMsg.includes('not connected') && !errorMsg.includes('not open')) {
+ console.error(`[WebSocketManager] Subscribe failed for ${topic}:`, error);
+ } else {
+ console.debug(`[WebSocketManager] Subscribe pending connection for ${topic}`);
+ }
throw error;
}
}
@@ -178,41 +187,59 @@ export class WebSocketManager {
return;
}
- // Get provider config
- const config = this.providerConfigs.get(provider);
- if (!config) {
- throw new Error(`No configuration found for provider: ${provider}. Use setProviderConfig() first.`);
+ // Check if already connecting - PREVENT DUPLICATE CONNECTIONS
+ if (this.connectingProviders.has(provider)) {
+ this.log(`Already connecting to ${provider}, waiting...`);
+ // Wait for existing connection to complete
+ while (this.connectingProviders.has(provider)) {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ return;
}
- // Create adapter if doesn't exist
- if (!this.registry.has(provider)) {
- const adapter = createAdapter(provider);
-
- // Setup message handler
- adapter.onMessage((message: NormalizedMessage) => {
- // Publish to event bus with full topic path
- const fullTopic = this.buildFullTopic(message);
- this.eventBus.publish(fullTopic, message);
- });
-
- // Setup error handler
- adapter.onError((error) => {
- this.log(`Error from ${provider}:`, error);
- });
-
- // Setup status change handler
- adapter.onStatusChange((status) => {
- this.log(`${provider} status changed to: ${status}`);
- });
-
- // Register adapter
- this.registry.register(provider, adapter, config);
- }
+ // Mark as connecting
+ this.connectingProviders.add(provider);
- // Connect
- const adapter = this.registry.get(provider);
- if (adapter && adapter.status !== ConnectionStatus.CONNECTED) {
- await adapter.connect(config);
+ try {
+ // Get provider config
+ const config = this.providerConfigs.get(provider);
+ if (!config) {
+ throw new Error(`No configuration found for provider: ${provider}. Use setProviderConfig() first.`);
+ }
+
+ // Create adapter if doesn't exist
+ if (!this.registry.has(provider)) {
+ const adapter = createAdapter(provider);
+
+ // Setup message handler
+ adapter.onMessage((message: NormalizedMessage) => {
+ // Publish to event bus with full topic path
+ const fullTopic = this.buildFullTopic(message);
+ this.eventBus.publish(fullTopic, message);
+ });
+
+ // Setup error handler
+ adapter.onError((error) => {
+ this.log(`Error from ${provider}:`, error);
+ });
+
+ // Setup status change handler
+ adapter.onStatusChange((status) => {
+ this.log(`${provider} status changed to: ${status}`);
+ });
+
+ // Register adapter
+ this.registry.register(provider, adapter, config);
+ }
+
+ // Connect
+ const adapter = this.registry.get(provider);
+ if (adapter && adapter.status !== ConnectionStatus.CONNECTED) {
+ await adapter.connect(config);
+ }
+ } finally {
+ // Always remove from connecting set
+ this.connectingProviders.delete(provider);
}
}
@@ -463,7 +490,7 @@ let globalManagerInstance: WebSocketManager | null = null;
export function getWebSocketManager(): WebSocketManager {
if (!globalManagerInstance) {
globalManagerInstance = new WebSocketManager({
- enableLogging: false,
+ enableLogging: true, // ENABLED FOR DEBUGGING
enableMetrics: true
});
}
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts b/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts
index 8931ca9ce..86f0e198a 100644
--- a/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts
+++ b/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts
@@ -105,6 +105,8 @@ export abstract class BaseAdapter implements IWebSocketAdapter {
* Connect to WebSocket
*/
async connect(config: ProviderConfig): Promise<void> {
+ console.log(`[${this.provider}] 🔌 Connecting to WebSocket...`);
+
if (!this.circuitBreaker.isAllowed()) {
throw new Error(`Circuit breaker is open for ${this.provider}`);
}
@@ -114,12 +116,17 @@ export abstract class BaseAdapter implements IWebSocketAdapter {
try {
const url = this.getWebSocketUrl(config);
+ console.log(`[${this.provider}] WebSocket URL: ${url}`);
+
this.ws = new WebSocket(url);
+ console.log(`[${this.provider}] WebSocket object created, readyState: ${this.ws.readyState}`);
this.setupWebSocketHandlers();
// Wait for connection
+ console.log(`[${this.provider}] Waiting for WebSocket to open...`);
await this.waitForConnection();
+ console.log(`[${this.provider}] ✓ WebSocket opened! readyState: ${this.ws?.readyState}`);
this.reconnectionManager.recordSuccess();
this.circuitBreaker.recordSuccess();
@@ -128,12 +135,16 @@ export abstract class BaseAdapter implements IWebSocketAdapter {
// Start heartbeat monitoring
this.heartbeatMonitor.start(() => this.handleStaleConnection());
+ console.log(`[${this.provider}] Heartbeat monitoring started`);
// Perform provider-specific initialization
await this.onConnected();
+ console.log(`[${this.provider}] ✓ Connection complete!`);
this.log('Connected successfully');
} catch (error) {
+ console.error(`[${this.provider}] ✗ Connection failed:`, error);
+
this.circuitBreaker.recordFailure();
this.reconnectionManager.recordAttempt();
@@ -148,6 +159,7 @@ export abstract class BaseAdapter implements IWebSocketAdapter {
// Attempt reconnection if policy allows
if (this.reconnectionManager.shouldAttempt()) {
+ console.log(`[${this.provider}] Will retry connection...`);
await this.scheduleReconnection();
} else {
throw error;
@@ -185,6 +197,17 @@ export abstract class BaseAdapter implements IWebSocketAdapter {
* Subscribe to a topic
*/
async subscribe(topic: string, params?: Record<string, any>): Promise<void> {
+ console.log(`[${this.provider}] Subscribe requested: ${topic}`);
+ console.log(`[${this.provider}] - WebSocket exists: ${!!this.ws}`);
+ console.log(`[${this.provider}] - readyState: ${this.ws?.readyState} (OPEN=${WebSocket.OPEN})`);
+ console.log(`[${this.provider}] - Status: ${this._status}`);
+
+ // Check WebSocket is actually open FIRST (most accurate check)
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
+ throw new Error(`Cannot subscribe: WebSocket is not open (readyState: ${this.ws?.readyState || 'null'})`);
+ }
+
+ // Then check connection status
if (this._status !== ConnectionStatus.CONNECTED) {
throw new Error(`Cannot subscribe: connection status is ${this._status}`);
}
@@ -458,12 +481,18 @@ export abstract class BaseAdapter implements IWebSocketAdapter {
* Handle stale connection (heartbeat timeout)
*/
protected async handleStaleConnection(): Promise<void> {
+ // Prevent simultaneous reconnection attempts
+ if (this._status === ConnectionStatus.RECONNECTING || this._status === ConnectionStatus.CONNECTING) {
+ this.log('Already reconnecting, skipping stale connection handler');
+ return;
+ }
+
this.log('Connection appears stale, forcing reconnect');
await this.disconnect();
if (this.config && this.reconnectionManager.shouldAttempt()) {
- await this.connect(this.config);
+ await this.scheduleReconnection();
}
}
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.ts b/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.ts
new file mode 100644
index 000000000..ef3953f47
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.ts
@@ -0,0 +1,381 @@
+// File: src/services/websocket/adapters/HyperLiquidAdapter.ts
+// HyperLiquid WebSocket API adapter
+// Documentation: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket
+
+import { BaseAdapter } from './BaseAdapter';
+import { ProviderConfig, NormalizedMessage } from '../types';
+
+/**
+ * HyperLiquid WebSocket message types
+ */
+interface HyperLiquidMessage {
+ channel?: string;
+ data?: any;
+}
+
+interface HyperLiquidSubscription {
+ method: 'subscribe' | 'unsubscribe';
+ subscription: {
+ type: string;
+ coin?: string;
+ user?: string;
+ interval?: string;
+ };
+}
+
+/**
+ * HyperLiquidAdapter - WebSocket adapter for HyperLiquid DEX
+ *
+ * Supported channels:
+ * - allMids: All mid prices for all coins
+ * - l2Book: Level 2 order book for specific coin
+ * - trades: Recent trades for specific coin
+ * - candle: OHLC candlestick data (intervals: 1m, 5m, 15m, 1h, 4h, 1d)
+ * - user: User-specific data (fills, orders - requires authentication)
+ *
+ * Topic format: "channel.symbol" e.g., "book.BTC", "trades.ETH"
+ */
+export class HyperLiquidAdapter extends BaseAdapter {
+ readonly provider = 'hyperliquid';
+
+ private readonly WS_URL = 'wss://api.hyperliquid.xyz/ws';
+
+ /**
+ * Get WebSocket URL
+ */
+ protected getWebSocketUrl(config: ProviderConfig): string {
+ return this.WS_URL;
+ }
+
+ /**
+ * Handle incoming messages from HyperLiquid
+ */
+ protected handleMessage(event: MessageEvent): void {
+ try {
+ const message: HyperLiquidMessage = JSON.parse(event.data);
+
+ this.log('Received message:', message);
+
+ // Handle channel messages
+ if (message.channel && message.data) {
+ this.handleChannelMessage(message);
+ }
+ } catch (error) {
+ console.error('[HyperLiquidAdapter] Failed to parse message:', error);
+ }
+ }
+
+ /**
+ * Subscribe to a channel
+ * @param topic - Format: "channel.symbol" e.g., "book.BTC", "trades.ETH"
+ * @param params - Optional parameters (interval for candles)
+ */
+ protected async performSubscribe(topic: string, params?: Record<string, any>): Promise<void> {
+ const { channel, symbol } = this.parseTopic(topic);
+
+ const subscribeMessage: HyperLiquidSubscription = {
+ method: 'subscribe',
+ subscription: {
+ type: this.mapChannelToType(channel)
+ }
+ };
+
+ // Add coin for specific subscriptions
+ if (symbol && channel !== 'allMids') {
+ subscribeMessage.subscription.coin = symbol;
+ }
+
+ // Add interval for candles
+ if (channel === 'ohlc' && params?.interval) {
+ subscribeMessage.subscription.interval = this.normalizeInterval(params.interval);
+ }
+
+ await this.send(subscribeMessage);
+ this.log(`Subscribed to ${channel}${symbol ? ` for ${symbol}` : ''}`);
+ }
+
+ /**
+ * Unsubscribe from a channel
+ */
+ protected async performUnsubscribe(topic: string): Promise<void> {
+ const { channel, symbol } = this.parseTopic(topic);
+
+ const unsubscribeMessage: HyperLiquidSubscription = {
+ method: 'unsubscribe',
+ subscription: {
+ type: this.mapChannelToType(channel)
+ }
+ };
+
+ if (symbol && channel !== 'allMids') {
+ unsubscribeMessage.subscription.coin = symbol;
+ }
+
+ await this.send(unsubscribeMessage);
+ this.log(`Sent unsubscription request for ${topic}`);
+ }
+
+ /**
+ * Perform ping (HyperLiquid doesn't require explicit ping)
+ */
+ protected async performPing(): Promise<void> {
+ // HyperLiquid WebSocket maintains connection automatically
+ // No explicit ping needed
+ this.log('Ping not required for HyperLiquid');
+ }
+
+ /**
+ * Called after successful connection
+ */
+ protected async onConnected(): Promise<void> {
+ this.log('WebSocket connected successfully');
+ }
+
+ /**
+ * Handle channel data messages
+ */
+ private handleChannelMessage(message: HyperLiquidMessage): void {
+ if (!message.channel || !message.data) {
+ return;
+ }
+
+ // Normalize message based on channel type
+ const normalizedMessages = this.normalizeMessage(message);
+
+ // Emit each normalized message
+ normalizedMessages.forEach(msg => {
+ this.notifyMessage(msg);
+ });
+ }
+
+ /**
+ * Normalize HyperLiquid message to standard format
+ */
+ private normalizeMessage(message: HyperLiquidMessage): NormalizedMessage[] {
+ const normalized: NormalizedMessage[] = [];
+ const channel = message.channel || 'unknown';
+ const data = message.data;
+
+ let type: NormalizedMessage['type'] = 'custom';
+ let symbol: string | undefined;
+
+ // Map channel to normalized type and extract data
+ switch (channel) {
+ case 'allMids':
+ // All mid prices - emit as ticker for each coin
+ type = 'ticker';
+ if (data.mids && typeof data.mids === 'object') {
+ Object.entries(data.mids).forEach(([coin, price]) => {
+ normalized.push({
+ provider: this.provider,
+ channel: 'ticker',
+ type: 'ticker',
+ symbol: coin,
+ timestamp: Date.now(),
+ data: {
+ last: parseFloat(price as string),
+ mid: parseFloat(price as string)
+ },
+ raw: message
+ });
+ });
+ }
+ return normalized;
+
+ case 'l2Book':
+ // Order book
+ type = 'orderbook';
+ symbol = data.coin;
+ const orderBookData = this.normalizeOrderBookData(data);
+ normalized.push({
+ provider: this.provider,
+ channel: 'book',
+ type,
+ symbol,
+ timestamp: data.time || Date.now(),
+ data: orderBookData,
+ raw: message
+ });
+ return normalized;
+
+ case 'trades':
+ // Trades
+ type = 'trade';
+ symbol = data.coin;
+ if (Array.isArray(data.trades)) {
+ data.trades.forEach((trade: any) => {
+ normalized.push({
+ provider: this.provider,
+ channel: 'trades',
+ type: 'trade',
+ symbol,
+ timestamp: trade.time || Date.now(),
+ data: {
+ price: parseFloat(trade.px),
+ size: parseFloat(trade.sz),
+ side: trade.side === 'A' ? 'sell' : 'buy', // A = ask (sell), B = bid (buy)
+ time: trade.time
+ },
+ raw: message
+ });
+ });
+ }
+ return normalized;
+
+ case 'candle':
+ // OHLC candles
+ type = 'candle';
+ symbol = data.coin;
+ if (data.candle) {
+ const candle = data.candle;
+ normalized.push({
+ provider: this.provider,
+ channel: 'ohlc',
+ type: 'candle',
+ symbol,
+ timestamp: candle.t || Date.now(),
+ data: {
+ time: candle.t,
+ open: parseFloat(candle.o),
+ high: parseFloat(candle.h),
+ low: parseFloat(candle.l),
+ close: parseFloat(candle.c),
+ volume: parseFloat(candle.v || 0)
+ },
+ raw: message
+ });
+ }
+ return normalized;
+
+ default:
+ type = 'custom';
+ }
+
+ // Default push for unhandled channels
+ normalized.push({
+ provider: this.provider,
+ channel,
+ type,
+ symbol,
+ timestamp: Date.now(),
+ data,
+ raw: message
+ });
+
+ return normalized;
+ }
+
+ /**
+ * Normalize HyperLiquid order book data to standardized format
+ */
+ private normalizeOrderBookData(data: any): any {
+ const normalized: any = {};
+
+ // HyperLiquid format: levels: [[bids], [asks]]
+ // Each level: { px: price, sz: size, n: number of orders }
+ if (data.levels && Array.isArray(data.levels) && data.levels.length === 2) {
+ const [bids, asks] = data.levels;
+
+ // Transform bids
+ if (Array.isArray(bids)) {
+ normalized.bids = bids.map((level: any) => ({
+ price: parseFloat(level.px),
+ size: parseFloat(level.sz),
+ numOrders: level.n
+ }));
+ }
+
+ // Transform asks
+ if (Array.isArray(asks)) {
+ normalized.asks = asks.map((level: any) => ({
+ price: parseFloat(level.px),
+ size: parseFloat(level.sz),
+ numOrders: level.n
+ }));
+ }
+ }
+
+ // Add metadata
+ if (data.coin) normalized.symbol = data.coin;
+ if (data.time) normalized.time = data.time;
+
+ return normalized;
+ }
+
+ /**
+ * Map internal channel name to HyperLiquid subscription type
+ */
+ private mapChannelToType(channel: string): string {
+ const channelMap: Record<string, string> = {
+ 'ticker': 'allMids',
+ 'book': 'l2Book',
+ 'trades': 'trades',
+ 'ohlc': 'candle',
+ 'candle': 'candle',
+ 'allMids': 'allMids',
+ 'l2Book': 'l2Book'
+ };
+
+ return channelMap[channel] || channel;
+ }
+
+ /**
+ * Normalize interval to HyperLiquid format
+ */
+ private normalizeInterval(interval: string | number): string {
+ // Convert number (minutes) to HyperLiquid format
+ if (typeof interval === 'number') {
+ const intervalMap: Record<number, string> = {
+ 1: '1m',
+ 5: '5m',
+ 15: '15m',
+ 60: '1h',
+ 240: '4h',
+ 1440: '1d'
+ };
+ return intervalMap[interval] || '1m';
+ }
+
+ // Already in correct format
+ return interval;
+ }
+
+ /**
+ * Parse topic into channel and symbol
+ */
+ private parseTopic(topic: string): { channel: string; symbol?: string } {
+ const parts = topic.split('.');
+
+ if (parts.length === 1) {
+ // Just channel, no symbol
+ return { channel: parts[0] };
+ } else {
+ // channel.symbol format
+ return {
+ channel: parts[0],
+ symbol: parts.slice(1).join('.')
+ };
+ }
+ }
+}
+
+/**
+ * HyperLiquid WebSocket Usage Examples:
+ *
+ * All Mid Prices:
+ * subscribe('allMids')
+ * subscribe('ticker') // Alias for allMids
+ *
+ * Order Book Level 2:
+ * subscribe('book.BTC')
+ * subscribe('book.ETH')
+ *
+ * Trades:
+ * subscribe('trades.BTC')
+ *
+ * OHLC Candles (intervals: 1m, 5m, 15m, 1h, 4h, 1d):
+ * subscribe('ohlc.BTC', { interval: '1m' })
+ * subscribe('candle.ETH', { interval: '1h' })
+ *
+ * Note: HyperLiquid uses coin symbols without pairs (e.g., 'BTC' not 'BTC/USD')
+ */
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts b/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts
index c770c37f0..e0f35e3c9 100644
--- a/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts
+++ b/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts
@@ -91,13 +91,26 @@ export class KrakenAdapter extends BaseAdapter {
// Add symbol array if provided
if (symbol) {
- subscribeMessage.params.symbol = [symbol];
+ // Normalize symbol for Kraken (BTC/USD -> XBT/USD, ensure uppercase)
+ const normalizedSymbol = this.normalizeSymbolForKraken(symbol);
+ subscribeMessage.params.symbol = [normalizedSymbol];
}
// Channel-specific parameters
if (channel === 'book' || channel === 'level3') {
// Depth: 10, 25, 100, 500, 1000 (default: 10)
- subscribeMessage.params.depth = params?.depth ?? 10;
+ // Validate and round to nearest valid depth
+ let depth = params?.depth ?? 10;
+ const validDepths = [10, 25, 100, 500, 1000];
+
+ // Find the closest valid depth
+ if (!validDepths.includes(depth)) {
+ depth = validDepths.reduce((prev, curr) =>
+ Math.abs(curr - depth) < Math.abs(prev - depth) ? curr : prev
+ );
+ }
+
+ subscribeMessage.params.depth = depth;
}
if (channel === 'ohlc') {
@@ -212,7 +225,18 @@ export class KrakenAdapter extends BaseAdapter {
case 'book':
case 'level3':
type = 'orderbook';
- break;
+ // Transform Kraken order book format to standardized format
+ const normalizedData = this.normalizeOrderBookData(dataItem);
+ normalized.push({
+ provider: this.provider,
+ channel,
+ type,
+ symbol,
+ timestamp: message.timestamp ? new Date(message.timestamp).getTime() : Date.now(),
+ data: normalizedData,
+ raw: message
+ });
+ return; // Skip the default push below
case 'instrument':
type = 'status';
break;
@@ -237,6 +261,37 @@ export class KrakenAdapter extends BaseAdapter {
return normalized;
}
+ /**
+ * Normalize Kraken order book data to standardized format
+ */
+ private normalizeOrderBookData(data: any): any {
+ const normalized: any = {
+ messageType: data.type || 'update'
+ };
+
+ // Transform bids array to standardized format
+ if (data.bids && Array.isArray(data.bids)) {
+ normalized.bids = data.bids.map((bid: any) => ({
+ price: parseFloat(bid.price || bid[0] || 0),
+ size: parseFloat(bid.qty || bid[1] || 0)
+ }));
+ }
+
+ // Transform asks array to standardized format
+ if (data.asks && Array.isArray(data.asks)) {
+ normalized.asks = data.asks.map((ask: any) => ({
+ price: parseFloat(ask.price || ask[0] || 0),
+ size: parseFloat(ask.qty || ask[1] || 0)
+ }));
+ }
+
+ // Copy over other fields
+ if (data.symbol) normalized.symbol = data.symbol;
+ if (data.checksum) normalized.checksum = data.checksum;
+
+ return normalized;
+ }
+
/**
* Handle subscription response
*/
@@ -244,11 +299,25 @@ export class KrakenAdapter extends BaseAdapter {
if (message.success) {
this.log('Subscription successful:', message);
} else if (message.error) {
- console.error('[KrakenAdapter] Subscription error:', message.error);
- this.addError({
- timestamp: Date.now(),
- error: message.error
- });
+ // Log error but don't add to error queue for common subscription issues
+ const errorStr = String(message.error);
+
+ // Categorize errors
+ const isCommonError =
+ errorStr.includes('not Found') ||
+ errorStr.includes('invalid') ||
+ errorStr.includes('not supported');
+
+ // Only log verbose errors in development
+ if (isCommonError) {
+ console.debug('[KrakenAdapter] Subscription info:', message.error);
+ } else {
+ console.error('[KrakenAdapter] Subscription error:', message.error);
+ this.addError({
+ timestamp: Date.now(),
+ error: message.error
+ });
+ }
}
}
@@ -297,6 +366,22 @@ export class KrakenAdapter extends BaseAdapter {
private getNextReqId(): number {
return this.reqIdCounter++;
}
+
+ /**
+ * Normalize symbol for Kraken WebSocket API
+ * Kraken WebSocket v2 uses different formats than v1
+ * Examples: BTC/USD, ETH/USD (not XBT/USD)
+ */
+ private normalizeSymbolForKraken(symbol: string): string {
+ // Ensure uppercase
+ let normalized = symbol.toUpperCase();
+
+ // Kraken WebSocket v2 actually uses BTC/USD format, not XBT/USD
+ // The v1 API used XBT, but v2 standardized on BTC
+ // No conversion needed for v2 API
+
+ return normalized;
+ }
}
/**
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/index.ts b/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
index 249faa8b5..0c5ac000f 100644
--- a/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
+++ b/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
@@ -4,15 +4,15 @@
import { AdapterRegistry, IWebSocketAdapter } from '../types';
import { BaseAdapter } from './BaseAdapter';
import { KrakenAdapter } from './KrakenAdapter';
+import { HyperLiquidAdapter } from './HyperLiquidAdapter';
/**
* Global registry of available WebSocket adapters
* Add new adapters here as they are implemented
- *
- * Note: HyperLiquid now uses CCXT adapter in src/brokers/exchanges/HyperLiquidAdapter.ts
*/
export const adapters: AdapterRegistry = {
kraken: KrakenAdapter,
+ hyperliquid: HyperLiquidAdapter,
// Add more adapters here:
// fyers: FyersAdapter,
// polygon: PolygonAdapter,
@@ -50,3 +50,4 @@ export function createAdapter(provider: string): IWebSocketAdapter {
// Export adapter classes
export { BaseAdapter } from './BaseAdapter';
export { KrakenAdapter } from './KrakenAdapter';
+export { HyperLiquidAdapter } from './HyperLiquidAdapter';
diff --git a/fincept-terminal-desktop/vite.config.ts b/fincept-terminal-desktop/vite.config.ts
index 588180749..de392da65 100644
--- a/fincept-terminal-desktop/vite.config.ts
+++ b/fincept-terminal-desktop/vite.config.ts
@@ -1,55 +1,100 @@
-import { defineConfig } from 'vite'
+import { defineConfig, Plugin } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
+import { nodePolyfills } from 'vite-plugin-node-polyfills'
import path from 'path'
+// Plugin to handle CCXT's .cjs files
+const ccxtFixPlugin = (): Plugin => ({
+ name: 'ccxt-cjs-fix',
+ enforce: 'pre',
+ resolveId(id) {
+ if (id.includes('dydx-v4-client/long/index.cjs')) {
+ return id.replace('.cjs', '.js');
+ }
+ return null;
+ },
+ transform(code, id) {
+ if (id.includes('ccxt') && id.endsWith('.cjs')) {
+ if (code.includes('typeof exports === "object"')) {
+ return {
+ code: code + '\nexport default module.exports;',
+ map: null
+ };
+ }
+ }
+ return null;
+ }
+});
+
export default defineConfig({
- plugins: [react(), tailwindcss()],
+ plugins: [
+ react(),
+ tailwindcss(),
+ nodePolyfills({
+ globals: {
+ Buffer: 'build', // Changed from true to 'build' to inject in build output
+ global: true,
+ process: true,
+ },
+ protocolImports: true,
+ exclude: ['net', 'assert', 'vm'],
+ overrides: {
+ // Force readable-stream to use proper Buffer
+ 'readable-stream': 'readable-stream',
+ },
+ }),
+ ccxtFixPlugin()
+ ],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
- // Polyfills for Node.js modules used by CCXT
- 'http': 'stream-http',
- 'https': 'https-browserify',
- 'stream': 'stream-browserify',
- 'crypto': 'crypto-browserify',
- 'buffer': 'buffer',
- 'util': 'util',
- 'url': 'url',
- 'zlib': 'browserify-zlib',
- // Replace ws with empty module (browser has native WebSocket)
+ // Custom polyfills
+ 'net': path.resolve(__dirname, './src/polyfills/net-shim.ts'),
+ 'node:net': path.resolve(__dirname, './src/polyfills/net-shim.ts'),
+ 'assert': path.resolve(__dirname, './src/polyfills/assert-shim.ts'),
+ 'node:assert': path.resolve(__dirname, './src/polyfills/assert-shim.ts'),
+ 'vm': path.resolve(__dirname, './src/polyfills/vm-shim.ts'),
+ 'node:vm': path.resolve(__dirname, './src/polyfills/vm-shim.ts'),
'ws': path.resolve(__dirname, './src/polyfills/ws-shim.ts'),
},
+ extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json', '.cjs']
},
optimizeDeps: {
- exclude: ['@mapbox/node-pre-gyp', 'mock-aws-s3', 'aws-sdk', 'nock', 'ccxt', 'ws'],
+ exclude: ['@mapbox/node-pre-gyp', 'mock-aws-s3', 'aws-sdk', 'nock'],
+ include: ['buffer', 'process', 'ccxt', 'readable-stream', 'crypto-browserify', 'stream-browserify'],
esbuildOptions: {
define: {
- global: 'globalThis'
+ global: 'globalThis',
}
}
},
define: {
- 'process.env': {},
+ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
'global': 'globalThis',
},
build: {
+ commonjsOptions: {
+ transformMixedEsModules: true,
+ include: [/node_modules/],
+ extensions: ['.js', '.cjs'],
+ },
rollupOptions: {
external: [
- 'ccxt',
- 'ws',
'http-proxy-agent',
'https-proxy-agent',
'socks-proxy-agent',
- 'net',
'tls',
+ 'node:tls',
'fs',
+ 'node:fs',
'path',
- 'os'
+ 'node:path',
+ 'os',
+ 'node:os'
],
output: {
manualChunks: {
- // Split vendor chunks
'react-vendor': ['react', 'react-dom', 'react-router-dom'],
'chart-vendor': ['recharts', 'lightweight-charts'],
'ui-vendor': ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu', '@radix-ui/react-popover', '@radix-ui/react-tabs'],
@@ -58,7 +103,7 @@ export default defineConfig({
}
}
},
- chunkSizeWarningLimit: 1000, // Increase limit to 1000kb to reduce warnings
+ chunkSizeWarningLimit: 1000,
},
clearScreen: false,
server: {
@@ -71,7 +116,6 @@ export default defineConfig({
rewrite: (path) => path.replace(/^\/api/, ''),
configure: (proxy, options) => {
proxy.on('proxyReq', (proxyReq, req, res) => {
- // Add the skip_zrok_interstitial header
proxyReq.setHeader('skip_zrok_interstitial', '1');
console.log('Proxying request:', req.method, req.url, '-> https://finceptbackend.share.zrok.io' + req.url.replace('/api', ''));
});
@@ -80,4 +124,4 @@ export default defineConfig({
}
},
envPrefix: ['VITE_', 'TAURI_'],
-})
\ No newline at end of file
+})