FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
db migrations
tilakpatel2241cc36ec276f
diff --git a/fincept-terminal-desktop/bun.lock b/fincept-terminal-desktop/bun.lockindex 340f7d2ef..b0086fb43 100644--- a/fincept-terminal-desktop/bun.lock+++ b/fincept-terminal-desktop/bun.lock@@ -38,6 +38,7 @@"@tailwindcss/vite": "^4.1.13","@tauri-apps/api": "~2.9.0","@tauri-apps/plugin-dialog": "^2.4.2",+ "@tauri-apps/plugin-fs": "^2.4.4","@tauri-apps/plugin-http": "^2.5.2","@tauri-apps/plugin-opener": "^2","@tauri-apps/plugin-process": "^2.3.1",@@ -56,6 +57,8 @@"date-fns": "^4.1.0","embla-carousel-react": "^8.6.0","fyers-web-sdk-v3": "^1.3.1",+ "handsontable": "^16.2.0",+ "hyperformula": "^3.1.1","i18next": "^25.7.1","i18next-browser-languagedetector": "^8.2.0","i18next-http-backend": "^3.0.2",@@ -89,6 +92,7 @@"tailwindcss": "^4.1.13","vaul": "^1.1.2","ws": "^8.18.3",+ "xlsx": "^0.18.5",},"devDependencies": {"@tauri-apps/cli": "^2",@@ -249,6 +253,8 @@"@grpc/proto-loader": ["@grpc/[email protected]", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.3", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ=="],+ "@handsontable/pikaday": ["@handsontable/[email protected]", "", {}, "sha512-1VN6N38t5/DcjJ7y7XUYrDx1LuzvvzlrFdBdMG90Qo1xc8+LXHqbWbsTEm5Ec5gXTEbDEO53vUT35R+2COmOyg=="],+"@ibm-cloud/watsonx-ai": ["@ibm-cloud/[email protected]", "", { "dependencies": { "@types/node": "^18.0.0", "extend": "3.0.2", "form-data": "^4.0.4", "ibm-cloud-sdk-core": "^5.4.3" } }, "sha512-5cVSUToeZBDEG6q3OfjuYO3yTOjI8dMsi3jgp1PGZ83hBbMeNrTA+hjT6gXPlxpTIgQeov3rSie5w7B3qzFOgg=="],"@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],@@ -539,6 +545,8 @@"@tauri-apps/plugin-dialog": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-lNIn5CZuw8WZOn8zHzmFmDSzg5zfohWoa3mdULP0YFh/VogVdMVWZPcWSHlydsiJhRQYaTNSYKN7RmZKE2lCYQ=="],+ "@tauri-apps/plugin-fs": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-MTorXxIRmOnOPT1jZ3w96vjSuScER38ryXY88vl5F0uiKdnvTKKTtaEjTEo8uPbl4e3gnUtfsDVwC7h77GQLvQ=="],+"@tauri-apps/plugin-http": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-/i4U/9za3mrytTgfRn5RHneKubZE/dwRmshYwyMvNRlkWjvu1m4Ma72kcbVJMZFGXpkbl+qLyWMGrihtWB76Zg=="],"@tauri-apps/plugin-opener": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-ei/yRRoCklWHImwpCcDK3VhNXx+QXM9793aQ64YxpqVF0BDuuIlXhZgiAkc15wnPVav+IbkYhmDJIv5R326Mew=="],@@ -663,6 +671,8 @@"@types/tough-cookie": ["@types/[email protected]", "", {}, "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA=="],+ "@types/trusted-types": ["@types/[email protected]", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],+"@types/unist": ["@types/[email protected]", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],"@types/uuid": ["@types/[email protected]", "", {}, "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ=="],@@ -681,6 +691,8 @@"acorn-walk": ["[email protected]", "", { "dependencies": { "acorn": "^8.11.0" } }, "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g=="],+ "adler-32": ["[email protected]", "", {}, "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A=="],+"agent-base": ["[email protected]", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],"agentkeepalive": ["[email protected]", "", { "dependencies": { "humanize-ms": "^1.2.1" } }, "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ=="],@@ -715,6 +727,8 @@"better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-WwCZ/5Diz7rsF29o27o0Gcc1Du+l7Zsv7SYtVPG0X3G/uUI1LqdxrQI7c9Hs2FWpqXXERjW9hp6g3/tH7DlVKg=="],+ "bignumber.js": ["[email protected]", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],+"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=="],@@ -765,6 +779,8 @@"ccxt": ["[email protected]", "", { "dependencies": { "ws": "^8.8.1" } }, "sha512-0ym0t8A4EFpxKpge12yowIkSnimtLF5PYOaANycAT8i+FqSO3KoD5qLfSK0rP69g3nnx7Q38X+9c0Rs0r74a4Q=="],+ "cfb": ["[email protected]", "", { "dependencies": { "adler-32": "~1.3.0", "crc-32": "~1.2.0" } }, "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA=="],+"chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],"character-entities": ["[email protected]", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="],@@ -779,6 +795,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=="],+ "chevrotain": ["[email protected]", "", { "dependencies": { "regexp-to-ast": "0.4.0" } }, "sha512-BwqQ/AgmKJ8jcMEjaSnfMybnKMgGTrtDKowfTP3pX4jwVy0kNjRsT/AP6h+wC3+3NC+X8X15VWBnTCQlX+wQFg=="],+"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=="],@@ -793,6 +811,8 @@"cmdk": ["[email protected]", "", { "dependencies": { "@radix-ui/react-compose-refs": "^1.1.1", "@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-id": "^1.1.0", "@radix-ui/react-primitive": "^2.0.2" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg=="],+ "codepage": ["[email protected]", "", {}, "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA=="],+"color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],"color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],@@ -811,6 +831,10 @@"cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],+ "core-js": ["[email protected]", "", {}, "sha512-c3Q2VVkGAUyupsjRnaNX6u8Dq2vAdzm9iuPj5FW0fRxzlxgq9Q39MDq10IvmQSpLgHQNyQzQmOo6bgGHmH3NNg=="],++ "crc-32": ["[email protected]", "", { "bin": { "crc32": "bin/crc32.njs" } }, "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ=="],+"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=="],@@ -911,6 +935,8 @@"domhandler": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.3.0" } }, "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w=="],+ "dompurify": ["[email protected]", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q=="],+"domutils": ["[email protected]", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="],"dotenv": ["[email protected]", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],@@ -1003,6 +1029,8 @@"formdata-node": ["[email protected]", "", { "dependencies": { "node-domexception": "1.0.0", "web-streams-polyfill": "4.0.0-beta.3" } }, "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ=="],+ "frac": ["[email protected]", "", {}, "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA=="],+"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],@@ -1033,6 +1061,8 @@"graphql-request": ["[email protected]", "", { "dependencies": { "@graphql-typed-document-node/core": "^3.2.0", "cross-fetch": "^3.1.5" }, "peerDependencies": { "graphql": "14 - 16" } }, "sha512-p+XPfS4q7aIpKVcgmnZKhMNqhltk20hfXtkaIkTfjjmiKMJ5xrt5c743cL03y/K7y1rg3WrIC49xGiEQ4mxdNw=="],+ "handsontable": ["[email protected]", "", { "dependencies": { "@handsontable/pikaday": "^1.0.0", "core-js": "^3.37.0", "dompurify": "^3.1.7", "moment": "2.30.1", "numbro": "2.5.0" }, "optionalDependencies": { "hyperformula": "^3.0.0" } }, "sha512-4zhMQON9DPyip/6YIPH2G7jN+QEJ0uabCZruhrhOqTqr3Qf/FDjsTInUaEzMCmhhdii5MbA6PGyLfUad6t1sXA=="],+"has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],"has-property-descriptors": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="],@@ -1067,6 +1097,8 @@"humanize-ms": ["[email protected]", "", { "dependencies": { "ms": "^2.0.0" } }, "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ=="],+ "hyperformula": ["[email protected]", "", { "dependencies": { "chevrotain": "^6.5.0", "tiny-emitter": "^2.1.0" } }, "sha512-v+yvRPZGL73KinH2lvS4/1QMe2xNviTfgIcVgKjzKGi66xEuvuoDRgQ48ODc4XhD+c+JLNfs9Ln1GnHQ5TDNGA=="],+"i18next": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.4" }, "peerDependencies": { "typescript": "^5" }, "optionalPeers": ["typescript"] }, "sha512-XbTnkh1yCZWSAZGnA9xcQfHcYNgZs2cNxm+c6v1Ma9UAUGCeJPplRe1ILia6xnDvXBjk0uXU+Z8FYWhA19SKFw=="],"i18next-browser-languagedetector": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.23.2" } }, "sha512-P+3zEKLnOF0qmiesW383vsLdtQVyKtCNA9cjSoKCppTKPQVfKd2W8hbVo5ZhNJKDqeM7BOcvNoKJOjpHh4Js9g=="],@@ -1327,6 +1359,8 @@"mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],+ "moment": ["[email protected]", "", {}, "sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how=="],+"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],"mustache": ["[email protected]", "", { "bin": { "mustache": "bin/mustache" } }, "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ=="],@@ -1355,6 +1389,8 @@"nth-check": ["[email protected]", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="],+ "numbro": ["[email protected]", "", { "dependencies": { "bignumber.js": "^8 || ^9" } }, "sha512-xDcctDimhzko/e+y+Q2/8i3qNC9Svw1QgOkSkQoO0kIPI473tR9QRbo2KP88Ty9p8WbPy+3OpTaAIzehtuHq+A=="],+"object-assign": ["[email protected]", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],"object-inspect": ["[email protected]", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],@@ -1509,6 +1545,8 @@"recharts-scale": ["[email protected]", "", { "dependencies": { "decimal.js-light": "^2.4.1" } }, "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w=="],+ "regexp-to-ast": ["[email protected]", "", {}, "sha512-4qf/7IsIKfSNHQXSwial1IFmfM1Cc/whNBQqRwe0V2stPe7KmN1U0tWQiIx6JiirgSrisjE0eECdNf7Tav1Ntw=="],+"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],"remark-parse": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="],@@ -1579,6 +1617,8 @@"space-separated-tokens": ["[email protected]", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="],+ "ssf": ["[email protected]", "", { "dependencies": { "frac": "~1.1.2" } }, "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g=="],+"static-eval": ["[email protected]", "", { "dependencies": { "escodegen": "^1.8.1" } }, "sha512-N/D219Hcr2bPjLxPiV+TQE++Tsmrady7TqAJugLy7Xk1EumfDWS/f5dtBbkRCGE7wKKXuYockQoj8Rm2/pVKyg=="],"stream-browserify": ["[email protected]", "", { "dependencies": { "inherits": "~2.0.4", "readable-stream": "^3.5.0" } }, "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA=="],@@ -1619,6 +1659,8 @@"timers-browserify": ["[email protected]", "", { "dependencies": { "setimmediate": "^1.0.4" } }, "sha512-9phl76Cqm6FhSX9Xe1ZUAMLtm1BLkKj2Qd5ApyWkXzsMRaA7dgr81kf4wJmQf/hAvg8EEyJxDo3du/0KlhPiKQ=="],+ "tiny-emitter": ["[email protected]", "", {}, "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q=="],+"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=="],@@ -1725,6 +1767,10 @@"which-typed-array": ["[email protected]", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "for-each": "^0.3.5", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2" } }, "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw=="],+ "wmf": ["[email protected]", "", {}, "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw=="],++ "word": ["[email protected]", "", {}, "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA=="],+"word-wrap": ["[email protected]", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],"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=="],@@ -1733,6 +1779,8 @@"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg=="],+ "xlsx": ["[email protected]", "", { "dependencies": { "adler-32": "~1.3.0", "cfb": "~1.2.1", "codepage": "~1.15.0", "crc-32": "~1.2.1", "ssf": "~0.11.2", "wmf": "~1.0.1", "word": "~0.3.0" }, "bin": { "xlsx": "bin/xlsx.njs" } }, "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ=="],+"xtend": ["[email protected]", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],diff --git a/fincept-terminal-desktop/dummy.txt b/fincept-terminal-desktop/dummy.txtdeleted file mode 100644index 9daeafb98..000000000--- a/fincept-terminal-desktop/dummy.txt+++ /dev/null@@ -1 +0,0 @@-testdiff --git a/fincept-terminal-desktop/kraken_output.txt b/fincept-terminal-desktop/kraken_output.txtdeleted file mode 100644index e69de29bb..000000000diff --git a/fincept-terminal-desktop/kraken_sub.json b/fincept-terminal-desktop/kraken_sub.jsondeleted file mode 100644index 6718d92c9..000000000--- a/fincept-terminal-desktop/kraken_sub.json+++ /dev/null@@ -1 +0,0 @@-method:subscribe params:channel:book params:symbol:[BTC/USD] params:depth:10 params:snapshot:true req_id:1diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.jsonindex df9392a9c..57a344b9f 100644--- a/fincept-terminal-desktop/package.json+++ b/fincept-terminal-desktop/package.json@@ -46,6 +46,7 @@"@tailwindcss/vite": "^4.1.13","@tauri-apps/api": "~2.9.0","@tauri-apps/plugin-dialog": "^2.4.2",+ "@tauri-apps/plugin-fs": "^2.4.4","@tauri-apps/plugin-http": "^2.5.2","@tauri-apps/plugin-opener": "^2","@tauri-apps/plugin-process": "^2.3.1",@@ -64,6 +65,8 @@"date-fns": "^4.1.0","embla-carousel-react": "^8.6.0","fyers-web-sdk-v3": "^1.3.1",+ "handsontable": "^16.2.0",+ "hyperformula": "^3.1.1","i18next": "^25.7.1","i18next-browser-languagedetector": "^8.2.0","i18next-http-backend": "^3.0.2",@@ -96,7 +99,8 @@"tailwind-merge": "^3.3.1","tailwindcss": "^4.1.13","vaul": "^1.1.2",- "ws": "^8.18.3"+ "ws": "^8.18.3",+ "xlsx": "^0.18.5"},"resolutions": {"readable-stream": "4.7.0"diff --git a/fincept-terminal-desktop/scripts/check-database.js b/fincept-terminal-desktop/scripts/check-database.jsnew file mode 100644index 000000000..84254410c--- /dev/null+++ b/fincept-terminal-desktop/scripts/check-database.js@@ -0,0 +1,59 @@+// Database Verification Script+// Run with: bun run check-database++import { invoke } from '@tauri-apps/api/core';++console.log('🔍 Checking Paper Trading Database...\n');++async function checkDatabase() {+ try {+ // Check portfolios+ console.log('📊 Checking portfolios...');+ const portfolios = await invoke('db_list_portfolios');+ console.log(`Found ${portfolios.length} portfolio(s):`);+ console.log(JSON.stringify(portfolios, null, 2));++ if (portfolios.length > 0) {+ const portfolio = portfolios[0];+ console.log(`\n💼 Checking portfolio: ${portfolio.name} (${portfolio.id})`);++ // Check positions+ const positions = await invoke('db_get_portfolio_positions', {+ portfolioId: portfolio.id,+ status: null+ });+ console.log(`\n📈 Positions: ${positions.length}`);+ if (positions.length > 0) {+ console.log(JSON.stringify(positions, null, 2));+ }++ // Check orders+ const orders = await invoke('db_get_portfolio_orders', {+ portfolioId: portfolio.id,+ status: null+ });+ console.log(`\n📋 Orders: ${orders.length}`);+ if (orders.length > 0) {+ console.log(JSON.stringify(orders, null, 2));+ }++ // Check trades+ const trades = await invoke('db_get_portfolio_trades', {+ portfolioId: portfolio.id,+ limit: 10+ });+ console.log(`\n💱 Trades: ${trades.length}`);+ if (trades.length > 0) {+ console.log(JSON.stringify(trades, null, 2));+ }+ }++ console.log('\n✅ Database check complete!');+ } catch (error) {+ console.error('❌ Error checking database:', error);+ console.log('\n💡 This is expected if running outside Tauri app.');+ console.log(' Run this from the app console instead.');+ }+}++checkDatabase();diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lockindex 9c9d93a0c..611fe468f 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.lock+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock@@ -19,6 +19,18 @@ dependencies = ["cpufeatures",]+[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "once_cell",+ "version_check",+ "zerocopy",+]+[[package]]name = "aho-corasick"version = "1.1.4"@@ -43,12 +55,6 @@ dependencies = ["alloc-no-stdlib",]-[[package]]-name = "allocator-api2"-version = "0.2.21"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"-[[package]]name = "android_system_properties"version = "0.1.5"@@ -248,15 +254,6 @@ dependencies = ["system-deps",]-[[package]]-name = "atoi"-version = "2.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528"-dependencies = [- "num-traits",-]-[[package]]name = "atomic-waker"version = "1.1.2"@@ -281,12 +278,6 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"-[[package]]-name = "base64ct"-version = "1.8.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba"-[[package]]name = "bitflags"version = "1.3.2"@@ -581,12 +572,6 @@ dependencies = ["crossbeam-utils",]-[[package]]-name = "const-oid"-version = "0.9.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"-[[package]]name = "constant_time_eq"version = "0.3.1"@@ -720,15 +705,6 @@ dependencies = ["crossbeam-utils",]-[[package]]-name = "crossbeam-queue"-version = "0.3.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115"-dependencies = [- "crossbeam-utils",-]-[[package]]name = "crossbeam-utils"version = "0.8.21"@@ -829,17 +805,6 @@ version = "0.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "26bf8fc351c5ed29b5c2f0cbbac1b209b74f60ecd62e675a998df72c49af5204"-[[package]]-name = "der"-version = "0.7.10"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"-dependencies = [- "const-oid",- "pem-rfc7468",- "zeroize",-]-[[package]]name = "deranged"version = "0.5.5"@@ -881,7 +846,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = ["block-buffer",- "const-oid","crypto-common","subtle",]@@ -977,12 +941,6 @@ dependencies = ["litrs",]-[[package]]-name = "dotenvy"-version = "0.15.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"-[[package]]name = "downcast-rs"version = "1.2.1"@@ -1030,9 +988,6 @@ name = "either"version = "1.15.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"-dependencies = [- "serde",-][[package]]name = "embed-resource"@@ -1123,17 +1078,6 @@ dependencies = ["windows-sys 0.61.2",]-[[package]]-name = "etcetera"-version = "0.8.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943"-dependencies = [- "cfg-if",- "home",- "windows-sys 0.48.0",-]-[[package]]name = "event-listener"version = "5.4.1"@@ -1155,6 +1099,18 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "fallible-iterator"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"++[[package]]+name = "fallible-streaming-iterator"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"+[[package]]name = "fastrand"version = "2.3.0"@@ -1200,8 +1156,13 @@ dependencies = ["chrono","futures-util","nix 0.29.0",+ "once_cell",+ "parking_lot","printpdf",+ "r2d2",+ "r2d2_sqlite","reqwest 0.11.27",+ "rusqlite","serde","serde_json","sha2",@@ -1209,11 +1170,11 @@ dependencies = ["tauri-build","tauri-plugin-cors-fetch","tauri-plugin-dialog",+ "tauri-plugin-fs","tauri-plugin-http","tauri-plugin-opener","tauri-plugin-process","tauri-plugin-shell",- "tauri-plugin-sql","tauri-plugin-updater","tokio","uuid",@@ -1237,29 +1198,12 @@ dependencies = ["miniz_oxide",]-[[package]]-name = "flume"-version = "0.11.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095"-dependencies = [- "futures-core",- "futures-sink",- "spin",-]-[[package]]name = "fnv"version = "1.0.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"-[[package]]-name = "foldhash"-version = "0.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"-[[package]]name = "foreign-types"version = "0.3.2"@@ -1328,7 +1272,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"dependencies = ["futures-core",- "futures-sink",][[package]]@@ -1348,17 +1291,6 @@ dependencies = ["futures-util",]-[[package]]-name = "futures-intrusive"-version = "0.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"-dependencies = [- "futures-core",- "lock_api",- "parking_lot",-]-[[package]]name = "futures-io"version = "0.3.31"@@ -1768,13 +1700,11 @@ checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"[[package]]name = "hashbrown"-version = "0.15.5"+version = "0.14.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"dependencies = [- "allocator-api2",- "equivalent",- "foldhash",+ "ahash",][[package]]@@ -1785,11 +1715,11 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"[[package]]name = "hashlink"-version = "0.10.0"+version = "0.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"+checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"dependencies = [- "hashbrown 0.15.5",+ "hashbrown 0.14.5",][[package]]@@ -1816,15 +1746,6 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"-[[package]]-name = "hkdf"-version = "0.12.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"-dependencies = [- "hmac",-]-[[package]]name = "hmac"version = "0.12.1"@@ -1834,15 +1755,6 @@ dependencies = ["digest",]-[[package]]-name = "home"-version = "0.5.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"-dependencies = [- "windows-sys 0.61.2",-]-[[package]]name = "html5ever"version = "0.29.1"@@ -2363,9 +2275,6 @@ name = "lazy_static"version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"-dependencies = [- "spin",-][[package]]name = "libappindicator"@@ -2417,12 +2326,6 @@ dependencies = ["windows-link 0.2.1",]-[[package]]-name = "libm"-version = "0.2.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de"-[[package]]name = "libredox"version = "0.1.10"@@ -2565,16 +2468,6 @@ version = "0.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5"-[[package]]-name = "md-5"-version = "0.10.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"-dependencies = [- "cfg-if",- "digest",-]-[[package]]name = "md5"version = "0.7.0"@@ -2734,48 +2627,12 @@ version = "0.1.14"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"-[[package]]-name = "num-bigint-dig"-version = "0.8.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"-dependencies = [- "lazy_static",- "libm",- "num-integer",- "num-iter",- "num-traits",- "rand 0.8.5",- "smallvec",- "zeroize",-]-[[package]]name = "num-conv"version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"-[[package]]-name = "num-integer"-version = "0.1.46"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"-dependencies = [- "num-traits",-]--[[package]]-name = "num-iter"-version = "0.1.45"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"-dependencies = [- "autocfg",- "num-integer",- "num-traits",-]-[[package]]name = "num-traits"version = "0.2.19"@@ -2783,7 +2640,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"dependencies = ["autocfg",- "libm",][[package]]@@ -3265,15 +3121,6 @@ dependencies = ["hmac",]-[[package]]-name = "pem-rfc7468"-version = "0.7.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"-dependencies = [- "base64ct",-]-[[package]]name = "percent-encoding"version = "2.3.2"@@ -3437,27 +3284,6 @@ dependencies = ["futures-io",]-[[package]]-name = "pkcs1"-version = "0.7.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"-dependencies = [- "der",- "pkcs8",- "spki",-]--[[package]]-name = "pkcs8"-version = "0.10.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"-dependencies = [- "der",- "spki",-]-[[package]]name = "pkg-config"version = "0.3.32"@@ -3727,6 +3553,28 @@ version = "5.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"+[[package]]+name = "r2d2"+version = "0.8.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51de85fb3fb6524929c8a2eb85e6b6d363de4e8c48f9e2c2eac4944abc181c93"+dependencies = [+ "log",+ "parking_lot",+ "scheduled-thread-pool",+]++[[package]]+name = "r2d2_sqlite"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb14dba8247a6a15b7fdbc7d389e2e6f03ee9f184f87117706d509c092dfe846"+dependencies = [+ "r2d2",+ "rusqlite",+ "uuid",+]+[[package]]name = "rand"version = "0.7.3"@@ -4040,23 +3888,19 @@ dependencies = [][[package]]-name = "rsa"-version = "0.9.9"+name = "rusqlite"+version = "0.32.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "40a0376c50d0358279d9d643e4bf7b7be212f1f4ff1da9070a7b54d22ef75c88"+checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"dependencies = [- "const-oid",- "digest",- "num-bigint-dig",- "num-integer",- "num-traits",- "pkcs1",- "pkcs8",- "rand_core 0.6.4",- "signature",- "spki",- "subtle",- "zeroize",+ "bitflags 2.10.0",+ "chrono",+ "fallible-iterator",+ "fallible-streaming-iterator",+ "hashlink",+ "libsqlite3-sys",+ "smallvec",+ "uuid",][[package]]@@ -4161,6 +4005,15 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "scheduled-thread-pool"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3cbc66816425a074528352f5789333ecff06ca41b36b0b0efdfbb29edc391a19"+dependencies = [+ "parking_lot",+]+[[package]]name = "schemars"version = "0.8.22"@@ -4514,16 +4367,6 @@ dependencies = ["libc",]-[[package]]-name = "signature"-version = "2.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"-dependencies = [- "digest",- "rand_core 0.6.4",-]-[[package]]name = "simd-adler32"version = "0.3.7"@@ -4553,9 +4396,6 @@ name = "smallvec"version = "1.15.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"-dependencies = [- "serde",-][[package]]name = "socket2"@@ -4625,217 +4465,6 @@ dependencies = ["system-deps",]-[[package]]-name = "spin"-version = "0.9.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"-dependencies = [- "lock_api",-]--[[package]]-name = "spki"-version = "0.7.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"-dependencies = [- "base64ct",- "der",-]--[[package]]-name = "sqlx"-version = "0.8.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc"-dependencies = [- "sqlx-core",- "sqlx-macros",- "sqlx-mysql",- "sqlx-postgres",- "sqlx-sqlite",-]--[[package]]-name = "sqlx-core"-version = "0.8.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6"-dependencies = [- "base64 0.22.1",- "bytes",- "crc",- "crossbeam-queue",- "either",- "event-listener",- "futures-core",- "futures-intrusive",- "futures-io",- "futures-util",- "hashbrown 0.15.5",- "hashlink",- "indexmap 2.12.1",- "log",- "memchr",- "once_cell",- "percent-encoding",- "serde",- "serde_json",- "sha2",- "smallvec",- "thiserror 2.0.17",- "time",- "tokio",- "tokio-stream",- "tracing",- "url",-]--[[package]]-name = "sqlx-macros"-version = "0.8.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d"-dependencies = [- "proc-macro2",- "quote",- "sqlx-core",- "sqlx-macros-core",- "syn 2.0.111",-]--[[package]]-name = "sqlx-macros-core"-version = "0.8.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b"-dependencies = [- "dotenvy",- "either",- "heck 0.5.0",- "hex",- "once_cell",- "proc-macro2",- "quote",- "serde",- "serde_json",- "sha2",- "sqlx-core",- "sqlx-mysql",- "sqlx-postgres",- "sqlx-sqlite",- "syn 2.0.111",- "tokio",- "url",-]--[[package]]-name = "sqlx-mysql"-version = "0.8.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526"-dependencies = [- "atoi",- "base64 0.22.1",- "bitflags 2.10.0",- "byteorder",- "bytes",- "crc",- "digest",- "dotenvy",- "either",- "futures-channel",- "futures-core",- "futures-io",- "futures-util",- "generic-array",- "hex",- "hkdf",- "hmac",- "itoa",- "log",- "md-5",- "memchr",- "once_cell",- "percent-encoding",- "rand 0.8.5",- "rsa",- "serde",- "sha1",- "sha2",- "smallvec",- "sqlx-core",- "stringprep",- "thiserror 2.0.17",- "time",- "tracing",- "whoami",-]--[[package]]-name = "sqlx-postgres"-version = "0.8.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46"-dependencies = [- "atoi",- "base64 0.22.1",- "bitflags 2.10.0",- "byteorder",- "crc",- "dotenvy",- "etcetera",- "futures-channel",- "futures-core",- "futures-util",- "hex",- "hkdf",- "hmac",- "home",- "itoa",- "log",- "md-5",- "memchr",- "once_cell",- "rand 0.8.5",- "serde",- "serde_json",- "sha2",- "smallvec",- "sqlx-core",- "stringprep",- "thiserror 2.0.17",- "time",- "tracing",- "whoami",-]--[[package]]-name = "sqlx-sqlite"-version = "0.8.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea"-dependencies = [- "atoi",- "flume",- "futures-channel",- "futures-core",- "futures-executor",- "futures-intrusive",- "futures-util",- "libsqlite3-sys",- "log",- "percent-encoding",- "serde",- "serde_urlencoded",- "sqlx-core",- "thiserror 2.0.17",- "time",- "tracing",- "url",-]-[[package]]name = "stable_deref_trait"version = "1.2.1"@@ -4873,17 +4502,6 @@ dependencies = ["quote",]-[[package]]-name = "stringprep"-version = "0.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"-dependencies = [- "unicode-bidi",- "unicode-normalization",- "unicode-properties",-]-[[package]]name = "strsim"version = "0.11.1"@@ -5344,25 +4962,6 @@ dependencies = ["tokio",]-[[package]]-name = "tauri-plugin-sql"-version = "2.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8a593f08c357091ba802a388d1161e99f05751278fb7204faeb08520da579a7c"-dependencies = [- "futures-core",- "indexmap 2.12.1",- "log",- "serde",- "serde_json",- "sqlx",- "tauri",- "tauri-plugin",- "thiserror 2.0.17",- "time",- "tokio",-]-[[package]]name = "tauri-plugin-updater"version = "2.9.0"@@ -5665,17 +5264,6 @@ dependencies = ["tokio",]-[[package]]-name = "tokio-stream"-version = "0.1.17"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047"-dependencies = [- "futures-core",- "pin-project-lite",- "tokio",-]-[[package]]name = "tokio-util"version = "0.7.17"@@ -5836,7 +5424,6 @@ version = "0.1.43"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2d15d90a0b5c19378952d479dc858407149d7bb45a14de0142f6c534b16fc647"dependencies = [- "log","pin-project-lite","tracing-attributes","tracing-core",@@ -5960,33 +5547,12 @@ dependencies = ["unic-common",]-[[package]]-name = "unicode-bidi"-version = "0.3.18"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"-[[package]]name = "unicode-ident"version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"-[[package]]-name = "unicode-normalization"-version = "0.1.25"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"-dependencies = [- "tinyvec",-]--[[package]]-name = "unicode-properties"-version = "0.1.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"-[[package]]name = "unicode-segmentation"version = "1.12.0"@@ -6043,6 +5609,7 @@ checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a"dependencies = ["getrandom 0.3.4","js-sys",+ "rand 0.9.2","serde_core","wasm-bindgen",]@@ -6125,12 +5692,6 @@ dependencies = ["wit-bindgen",]-[[package]]-name = "wasite"-version = "0.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"-[[package]]name = "wasm-bindgen"version = "0.2.106"@@ -6389,16 +5950,6 @@ dependencies = ["winsafe",]-[[package]]-name = "whoami"-version = "1.6.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d"-dependencies = [- "libredox",- "wasite",-]-[[package]]name = "winapi"version = "0.3.9"diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.tomlindex d382d4323..371ba4a63 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.toml+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml@@ -25,11 +25,11 @@ tauri = { version = "2", features = ["devtools"] }tauri-plugin-opener = "2"tauri-plugin-http = "2"tauri-plugin-cors-fetch = "4"-tauri-plugin-sql = { version = "2", features = ["sqlite"] }tauri-plugin-dialog = "2"tauri-plugin-updater = "2.8"tauri-plugin-process = "2"tauri-plugin-shell = "2"+tauri-plugin-fs = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"sha2 = "0.10"@@ -37,6 +37,11 @@ tokio = { version = "1", features = ["full"] }anyhow = "1.0"chrono = "0.4"uuid = { version = "1.11", features = ["v4", "serde"] }+rusqlite = { version = "0.32", features = ["bundled", "chrono", "uuid"] }+r2d2 = "0.8"+r2d2_sqlite = "0.25"+once_cell = "1.20"+parking_lot = "0.12"reqwest = { version = "0.11", features = ["json", "stream"] }futures-util = "0.3"zip = "2.2"diff --git a/fincept-terminal-desktop/src-tauri/capabilities/default.json b/fincept-terminal-desktop/src-tauri/capabilities/default.jsonindex 5751e7d71..c1b78d9da 100644--- a/fincept-terminal-desktop/src-tauri/capabilities/default.json+++ b/fincept-terminal-desktop/src-tauri/capabilities/default.json@@ -16,14 +16,19 @@]},"cors-fetch:default",- "sql:default",- "sql:allow-load",- "sql:allow-execute",- "sql:allow-select",- "sql:allow-close","dialog:default","dialog:allow-ask","dialog:allow-message",+ "dialog:allow-open",+ "dialog:allow-save",+ "fs:allow-read-file",+ "fs:allow-write-file",+ {+ "identifier": "fs:scope",+ "allow": [+ { "path": "**" }+ ]+ },"updater:default","updater:allow-check","updater:allow-download-and-install",diff --git a/fincept-terminal-desktop/src-tauri/src/commands/database.rs b/fincept-terminal-desktop/src-tauri/src/commands/database.rsnew file mode 100644index 000000000..a81ff0c23--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/database.rs@@ -0,0 +1,543 @@+// Database Tauri Commands - Expose all database operations to frontend++use crate::database::*;++// ============================================================================+// Settings Commands+// ============================================================================++#[tauri::command]+pub async fn db_save_setting(key: String, value: String, category: Option<String>) -> Result<String, String> {+ operations::save_setting(&key, &value, category.as_deref())+ .map_err(|e| e.to_string())?;+ Ok("Setting saved successfully".to_string())+}++#[tauri::command]+pub async fn db_get_setting(key: String) -> Result<Option<String>, String> {+ operations::get_setting(&key).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_all_settings() -> Result<Vec<Setting>, String> {+ operations::get_all_settings().map_err(|e| e.to_string())+}++// ============================================================================+// Credentials Commands+// ============================================================================++#[tauri::command]+pub async fn db_save_credential(credential: Credential) -> Result<OperationResult, String> {+ operations::save_credential(&credential).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_credentials() -> Result<Vec<Credential>, String> {+ operations::get_credentials().map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_credential_by_service(service_name: String) -> Result<Option<Credential>, String> {+ operations::get_credential_by_service(&service_name).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_delete_credential(id: i64) -> Result<OperationResult, String> {+ operations::delete_credential(id).map_err(|e| e.to_string())+}++// ============================================================================+// LLM Commands+// ============================================================================++#[tauri::command]+pub async fn db_get_llm_configs() -> Result<Vec<LLMConfig>, String> {+ operations::get_llm_configs().map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_save_llm_config(config: LLMConfig) -> Result<String, String> {+ operations::save_llm_config(&config).map_err(|e| e.to_string())?;+ Ok("LLM config saved successfully".to_string())+}++#[tauri::command]+pub async fn db_get_llm_global_settings() -> Result<LLMGlobalSettings, String> {+ operations::get_llm_global_settings().map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_save_llm_global_settings(settings: LLMGlobalSettings) -> Result<String, String> {+ operations::save_llm_global_settings(&settings).map_err(|e| e.to_string())?;+ Ok("LLM global settings saved successfully".to_string())+}++// ============================================================================+// Chat Commands+// ============================================================================++#[tauri::command]+pub async fn db_create_chat_session(title: String) -> Result<ChatSession, String> {+ operations::create_chat_session(&title).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_chat_sessions(limit: Option<i64>) -> Result<Vec<ChatSession>, String> {+ operations::get_chat_sessions(limit).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_add_chat_message(message: ChatMessage) -> Result<ChatMessage, String> {+ operations::add_chat_message(&message).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_chat_messages(session_uuid: String) -> Result<Vec<ChatMessage>, String> {+ operations::get_chat_messages(&session_uuid).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_delete_chat_session(session_uuid: String) -> Result<String, String> {+ operations::delete_chat_session(&session_uuid).map_err(|e| e.to_string())?;+ Ok("Chat session deleted successfully".to_string())+}++// ============================================================================+// Data Sources Commands+// ============================================================================++#[tauri::command]+pub async fn db_save_data_source(source: DataSource) -> Result<OperationResultWithId, String> {+ operations::save_data_source(&source).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_all_data_sources() -> Result<Vec<DataSource>, String> {+ operations::get_all_data_sources().map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_delete_data_source(id: String) -> Result<OperationResult, String> {+ operations::delete_data_source(&id).map_err(|e| e.to_string())+}++// ============================================================================+// MCP Server Commands+// ============================================================================++#[tauri::command]+pub async fn db_add_mcp_server(server: MCPServer) -> Result<String, String> {+ queries::add_mcp_server(&server).map_err(|e| e.to_string())?;+ Ok("MCP server added successfully".to_string())+}++#[tauri::command]+pub async fn db_get_mcp_servers() -> Result<Vec<MCPServer>, String> {+ queries::get_mcp_servers().map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_delete_mcp_server(id: String) -> Result<String, String> {+ queries::delete_mcp_server(&id).map_err(|e| e.to_string())?;+ Ok("MCP server deleted successfully".to_string())+}++// ============================================================================+// Backtesting Commands+// ============================================================================++#[tauri::command]+pub async fn db_save_backtesting_provider(provider: BacktestingProvider) -> Result<OperationResult, String> {+ queries::save_backtesting_provider(&provider).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_backtesting_providers() -> Result<Vec<BacktestingProvider>, String> {+ queries::get_backtesting_providers().map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_save_backtesting_strategy(strategy: BacktestingStrategy) -> Result<OperationResult, String> {+ queries::save_backtesting_strategy(&strategy).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_backtesting_strategies() -> Result<Vec<BacktestingStrategy>, String> {+ queries::get_backtesting_strategies().map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_save_backtest_run(run: BacktestRun) -> Result<OperationResult, String> {+ queries::save_backtest_run(&run).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_backtest_runs(limit: Option<i64>) -> Result<Vec<BacktestRun>, String> {+ queries::get_backtest_runs(limit).map_err(|e| e.to_string())+}++// ============================================================================+// Context Recording Commands+// ============================================================================++#[tauri::command]+pub async fn db_save_recorded_context(context: RecordedContext) -> Result<String, String> {+ queries::save_recorded_context(&context).map_err(|e| e.to_string())?;+ Ok("Context recorded successfully".to_string())+}++#[tauri::command]+pub async fn db_get_recorded_contexts(tab_name: Option<String>, limit: Option<i64>) -> Result<Vec<RecordedContext>, String> {+ queries::get_recorded_contexts(tab_name.as_deref(), limit).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_delete_recorded_context(id: String) -> Result<String, String> {+ queries::delete_recorded_context(&id).map_err(|e| e.to_string())?;+ Ok("Context deleted successfully".to_string())+}++// ============================================================================+// Watchlist Commands+// ============================================================================++#[tauri::command]+pub async fn db_create_watchlist(name: String, description: Option<String>, color: String) -> Result<Watchlist, String> {+ queries::create_watchlist(&name, description.as_deref(), &color).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_watchlists() -> Result<Vec<Watchlist>, String> {+ queries::get_watchlists().map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_add_watchlist_stock(watchlist_id: String, symbol: String, notes: Option<String>) -> Result<WatchlistStock, String> {+ queries::add_watchlist_stock(&watchlist_id, &symbol, notes.as_deref()).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_watchlist_stocks(watchlist_id: String) -> Result<Vec<WatchlistStock>, String> {+ queries::get_watchlist_stocks(&watchlist_id).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_remove_watchlist_stock(watchlist_id: String, symbol: String) -> Result<String, String> {+ queries::remove_watchlist_stock(&watchlist_id, &symbol).map_err(|e| e.to_string())?;+ Ok("Stock removed from watchlist successfully".to_string())+}++#[tauri::command]+pub async fn db_delete_watchlist(id: String) -> Result<String, String> {+ queries::delete_watchlist(&id).map_err(|e| e.to_string())?;+ Ok("Watchlist deleted successfully".to_string())+}++// ============================================================================+// Cache Commands+// ============================================================================++#[tauri::command]+pub async fn db_save_market_data_cache(symbol: String, category: String, quote_data: String) -> Result<String, String> {+ cache::save_market_data_cache(&symbol, &category, "e_data).map_err(|e| e.to_string())?;+ Ok("Market data cached successfully".to_string())+}++#[tauri::command]+pub async fn db_get_cached_market_data(symbol: String, category: String, max_age_minutes: i64) -> Result<Option<String>, String> {+ cache::get_cached_market_data(&symbol, &category, max_age_minutes).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_clear_market_data_cache() -> Result<String, String> {+ cache::clear_market_data_cache().map_err(|e| e.to_string())?;+ Ok("Market data cache cleared successfully".to_string())+}++// ============================================================================+// Paper Trading Commands+// ============================================================================++#[tauri::command]+pub async fn db_create_portfolio(+ id: String,+ name: String,+ provider: String,+ initial_balance: f64,+ currency: String,+ margin_mode: String,+ leverage: f64,+) -> Result<paper_trading::PaperTradingPortfolio, String> {+ paper_trading::create_portfolio(&id, &name, &provider, initial_balance, ¤cy, &margin_mode, leverage)+ .map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_portfolio(id: String) -> Result<paper_trading::PaperTradingPortfolio, String> {+ paper_trading::get_portfolio(&id).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_list_portfolios() -> Result<Vec<paper_trading::PaperTradingPortfolio>, String> {+ paper_trading::list_portfolios().map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_update_portfolio_balance(id: String, new_balance: f64) -> Result<String, String> {+ paper_trading::update_portfolio_balance(&id, new_balance).map_err(|e| e.to_string())?;+ Ok("Portfolio balance updated successfully".to_string())+}++#[tauri::command]+pub async fn db_create_position(+ id: String,+ portfolio_id: String,+ symbol: String,+ side: String,+ entry_price: f64,+ quantity: f64,+ leverage: f64,+ margin_mode: String,+) -> Result<String, String> {+ paper_trading::create_position(&id, &portfolio_id, &symbol, &side, entry_price, quantity, leverage, &margin_mode)+ .map_err(|e| e.to_string())?;+ Ok("Position created successfully".to_string())+}++#[tauri::command]+pub async fn db_get_portfolio_positions(portfolio_id: String, status: Option<String>) -> Result<Vec<paper_trading::PaperTradingPosition>, String> {+ paper_trading::get_portfolio_positions(&portfolio_id, status.as_deref()).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_create_order(+ id: String,+ portfolio_id: String,+ symbol: String,+ side: String,+ order_type: String,+ quantity: f64,+ price: Option<f64>,+ time_in_force: String,+) -> Result<String, String> {+ paper_trading::create_order(&id, &portfolio_id, &symbol, &side, &order_type, quantity, price, &time_in_force)+ .map_err(|e| e.to_string())?;+ Ok("Order created successfully".to_string())+}++#[tauri::command]+pub async fn db_get_portfolio_orders(portfolio_id: String, status: Option<String>) -> Result<Vec<paper_trading::PaperTradingOrder>, String> {+ paper_trading::get_portfolio_orders(&portfolio_id, status.as_deref()).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_portfolio_trades(portfolio_id: String, limit: Option<i64>) -> Result<Vec<paper_trading::PaperTradingTrade>, String> {+ paper_trading::get_portfolio_trades(&portfolio_id, limit).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_delete_portfolio(id: String) -> Result<String, String> {+ paper_trading::delete_portfolio(&id).map_err(|e| e.to_string())?;+ Ok("Portfolio deleted successfully".to_string())+}++#[tauri::command]+pub async fn db_get_position(id: String) -> Result<paper_trading::PaperTradingPosition, String> {+ paper_trading::get_position(&id).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_position_by_symbol(+ portfolio_id: String,+ symbol: String,+ status: String,+) -> Result<Option<paper_trading::PaperTradingPosition>, String> {+ paper_trading::get_position_by_symbol(&portfolio_id, &symbol, &status).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_position_by_symbol_and_side(+ portfolio_id: String,+ symbol: String,+ side: String,+ status: String,+) -> Result<Option<paper_trading::PaperTradingPosition>, String> {+ paper_trading::get_position_by_symbol_and_side(&portfolio_id, &symbol, &side, &status).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_update_position(+ id: String,+ quantity: Option<f64>,+ entry_price: Option<f64>,+ current_price: Option<f64>,+ unrealized_pnl: Option<f64>,+ realized_pnl: Option<f64>,+ liquidation_price: Option<f64>,+ status: Option<String>,+ closed_at: Option<String>,+) -> Result<String, String> {+ paper_trading::update_position(+ &id,+ quantity,+ entry_price,+ current_price,+ unrealized_pnl,+ realized_pnl,+ liquidation_price,+ status.as_deref(),+ closed_at.as_deref(),+ ).map_err(|e| e.to_string())?;+ Ok("Position updated successfully".to_string())+}++#[tauri::command]+pub async fn db_delete_position(id: String) -> Result<String, String> {+ paper_trading::delete_position(&id).map_err(|e| e.to_string())?;+ Ok("Position deleted successfully".to_string())+}++#[tauri::command]+pub async fn db_get_order(id: String) -> Result<paper_trading::PaperTradingOrder, String> {+ paper_trading::get_order(&id).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_pending_orders(portfolio_id: Option<String>) -> Result<Vec<paper_trading::PaperTradingOrder>, String> {+ paper_trading::get_pending_orders(portfolio_id.as_deref()).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_update_order(+ id: String,+ filled_quantity: Option<f64>,+ avg_fill_price: Option<f64>,+ status: Option<String>,+ filled_at: Option<String>,+) -> Result<String, String> {+ paper_trading::update_order(+ &id,+ filled_quantity,+ avg_fill_price,+ status.as_deref(),+ filled_at.as_deref(),+ ).map_err(|e| e.to_string())?;+ Ok("Order updated successfully".to_string())+}++#[tauri::command]+pub async fn db_delete_order(id: String) -> Result<String, String> {+ paper_trading::delete_order(&id).map_err(|e| e.to_string())?;+ Ok("Order deleted successfully".to_string())+}++#[tauri::command]+pub async fn db_create_trade(+ id: String,+ portfolio_id: String,+ order_id: String,+ symbol: String,+ side: String,+ price: f64,+ quantity: f64,+ fee: f64,+ fee_rate: f64,+ is_maker: bool,+) -> Result<String, String> {+ paper_trading::create_trade(+ &id,+ &portfolio_id,+ &order_id,+ &symbol,+ &side,+ price,+ quantity,+ fee,+ fee_rate,+ is_maker,+ ).map_err(|e| e.to_string())?;+ Ok("Trade created successfully".to_string())+}++#[tauri::command]+pub async fn db_get_trade(id: String) -> Result<paper_trading::PaperTradingTrade, String> {+ paper_trading::get_trade(&id).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_order_trades(order_id: String) -> Result<Vec<paper_trading::PaperTradingTrade>, String> {+ paper_trading::get_order_trades(&order_id).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_delete_trade(id: String) -> Result<String, String> {+ paper_trading::delete_trade(&id).map_err(|e| e.to_string())?;+ Ok("Trade deleted successfully".to_string())+}++// ============================================================================+// Notes Commands+// ============================================================================++#[tauri::command]+pub async fn db_create_note(note: Note) -> Result<i64, String> {+ notes_excel::create_note(¬e).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_all_notes(include_archived: bool) -> Result<Vec<Note>, String> {+ notes_excel::get_all_notes(include_archived).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_update_note(id: i64, note: Note) -> Result<String, String> {+ notes_excel::update_note(id, ¬e).map_err(|e| e.to_string())?;+ Ok("Note updated successfully".to_string())+}++#[tauri::command]+pub async fn db_delete_note(id: i64) -> Result<String, String> {+ notes_excel::delete_note(id).map_err(|e| e.to_string())?;+ Ok("Note deleted successfully".to_string())+}++#[tauri::command]+pub async fn db_search_notes(query: String) -> Result<Vec<Note>, String> {+ notes_excel::search_notes(&query).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_note_templates() -> Result<Vec<NoteTemplate>, String> {+ notes_excel::get_note_templates().map_err(|e| e.to_string())+}++// ============================================================================+// Excel Commands+// ============================================================================++#[tauri::command]+pub async fn db_add_or_update_excel_file(file: ExcelFile) -> Result<i64, String> {+ notes_excel::add_or_update_excel_file(&file).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_recent_excel_files(limit: i64) -> Result<Vec<ExcelFile>, String> {+ notes_excel::get_recent_excel_files(limit).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_create_excel_snapshot(file_id: i64, snapshot_name: String, sheet_data: String, created_at: String) -> Result<i64, String> {+ notes_excel::create_excel_snapshot(file_id, &snapshot_name, &sheet_data, &created_at).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_get_excel_snapshots(file_id: i64) -> Result<Vec<ExcelSnapshot>, String> {+ notes_excel::get_excel_snapshots(file_id).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_delete_excel_snapshot(id: i64) -> Result<String, String> {+ notes_excel::delete_excel_snapshot(id).map_err(|e| e.to_string())?;+ Ok("Excel snapshot deleted successfully".to_string())+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rsindex c0e754324..b96fa80ba 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs@@ -88,3 +88,6 @@ pub mod company_news;// Agno Trading Agentspub mod agno_trading;pub mod alpha_arena;++// High-performance Rust SQLite Database+pub mod database;diff --git a/fincept-terminal-desktop/src-tauri/src/database/cache.rs b/fincept-terminal-desktop/src-tauri/src/database/cache.rsnew file mode 100644index 000000000..95626d7ec--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/database/cache.rs@@ -0,0 +1,145 @@+// Cache Operations - Market data and forum caching with expiration++use crate::database::pool::get_pool;+use anyhow::Result;+use rusqlite::{params, OptionalExtension};++// ============================================================================+// Market Data Cache+// ============================================================================++pub fn save_market_data_cache(symbol: &str, category: &str, quote_data: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT OR REPLACE INTO market_data_cache (symbol, category, quote_data, cached_at)+ VALUES (?1, ?2, ?3, CURRENT_TIMESTAMP)",+ params![symbol, category, quote_data],+ )?;++ Ok(())+}++pub fn get_cached_market_data(symbol: &str, category: &str, max_age_minutes: i64) -> Result<Option<String>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let result = conn+ .query_row(+ "SELECT quote_data FROM market_data_cache+ WHERE symbol = ?1 AND category = ?2+ AND datetime(cached_at) > datetime('now', ?3)",+ params![symbol, category, format!("-{} minutes", max_age_minutes)],+ |row| row.get(0),+ )+ .optional()?;++ Ok(result)+}++pub fn clear_market_data_cache() -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute("DELETE FROM market_data_cache", [])?;++ Ok(())+}++#[allow(dead_code)]+pub fn clear_expired_market_cache(max_age_minutes: i64) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "DELETE FROM market_data_cache+ WHERE datetime(cached_at) <= datetime('now', ?1)",+ params![format!("-{} minutes", max_age_minutes)],+ )?;++ Ok(())+}++// ============================================================================+// Forum Cache+// ============================================================================++#[allow(dead_code)]+pub fn cache_forum_categories(categories: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT OR REPLACE INTO forum_categories_cache (id, data, cached_at)+ VALUES (1, ?1, CURRENT_TIMESTAMP)",+ params![categories],+ )?;++ Ok(())+}++#[allow(dead_code)]+pub fn get_cached_forum_categories(max_age_minutes: i64) -> Result<Option<String>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let result = conn+ .query_row(+ "SELECT data FROM forum_categories_cache+ WHERE id = 1 AND datetime(cached_at) > datetime('now', ?1)",+ params![format!("-{} minutes", max_age_minutes)],+ |row| row.get(0),+ )+ .optional()?;++ Ok(result)+}++#[allow(dead_code)]+pub fn cache_forum_posts(category_id: Option<i64>, sort_by: &str, posts: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let cache_key = format!("{}_{}", category_id.map_or("all".to_string(), |id| id.to_string()), sort_by);++ conn.execute(+ "INSERT OR REPLACE INTO forum_posts_cache (cache_key, category_id, sort_by, data, cached_at)+ VALUES (?1, ?2, ?3, ?4, CURRENT_TIMESTAMP)",+ params![cache_key, category_id, sort_by, posts],+ )?;++ Ok(())+}++#[allow(dead_code)]+pub fn get_cached_forum_posts(category_id: Option<i64>, sort_by: &str, max_age_minutes: i64) -> Result<Option<String>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let cache_key = format!("{}_{}", category_id.map_or("all".to_string(), |id| id.to_string()), sort_by);++ let result = conn+ .query_row(+ "SELECT data FROM forum_posts_cache+ WHERE cache_key = ?1 AND datetime(cached_at) > datetime('now', ?2)",+ params![cache_key, format!("-{} minutes", max_age_minutes)],+ |row| row.get(0),+ )+ .optional()?;++ Ok(result)+}++#[allow(dead_code)]+pub fn clear_forum_cache() -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute("DELETE FROM forum_categories_cache", [])?;+ conn.execute("DELETE FROM forum_posts_cache", [])?;+ conn.execute("DELETE FROM forum_stats_cache", [])?;+ conn.execute("DELETE FROM forum_post_details_cache", [])?;++ Ok(())+}diff --git a/fincept-terminal-desktop/src-tauri/src/database/mod.rs b/fincept-terminal-desktop/src-tauri/src/database/mod.rsnew file mode 100644index 000000000..4443e6186--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/database/mod.rs@@ -0,0 +1,22 @@+// Database Module - High-performance SQLite with connection pooling+// Structure: 8 files for optimal organization and performance++pub mod pool;+pub mod schema;+pub mod types;+pub mod operations;+pub mod queries;+pub mod cache;+pub mod paper_trading;+pub mod notes_excel;++pub use pool::init_database;+pub use types::*;++use anyhow::Result;++/// Initialize all databases and connection pools+pub async fn initialize() -> Result<()> {+ init_database().await?;+ Ok(())+}diff --git a/fincept-terminal-desktop/src-tauri/src/database/notes_excel.rs b/fincept-terminal-desktop/src-tauri/src/database/notes_excel.rsnew file mode 100644index 000000000..5321220d1--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/database/notes_excel.rs@@ -0,0 +1,392 @@+// Notes and Excel Operations - Separate databases for notes and excel files++use crate::database::{pool::{get_notes_db_path, get_excel_db_path}, types::{Note, NoteTemplate, ExcelFile, ExcelSnapshot}};+use anyhow::{Context, Result};+use rusqlite::{Connection, params, OptionalExtension};+use parking_lot::Mutex;+use once_cell::sync::Lazy;++// Separate connections for notes and excel (lighter databases)+static NOTES_CONN: Lazy<Mutex<Option<Connection>>> = Lazy::new(|| Mutex::new(None));+static EXCEL_CONN: Lazy<Mutex<Option<Connection>>> = Lazy::new(|| Mutex::new(None));++// ============================================================================+// Notes Database Initialization+// ============================================================================++fn get_notes_conn() -> Result<()> {+ let mut conn_lock = NOTES_CONN.lock();+ if conn_lock.is_none() {+ let path = get_notes_db_path()?;+ let conn = Connection::open(&path).context("Failed to open notes database")?;++ // Create schema+ conn.execute_batch(+ "CREATE TABLE IF NOT EXISTS financial_notes (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ title TEXT NOT NULL,+ content TEXT NOT NULL,+ category TEXT NOT NULL,+ priority TEXT DEFAULT 'MEDIUM',+ tags TEXT,+ tickers TEXT,+ sentiment TEXT DEFAULT 'NEUTRAL',+ is_favorite INTEGER DEFAULT 0,+ is_archived INTEGER DEFAULT 0,+ color_code TEXT DEFAULT '#FF8800',+ attachments TEXT,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ reminder_date TEXT,+ word_count INTEGER DEFAULT 0+ );++ CREATE TABLE IF NOT EXISTS note_templates (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name TEXT NOT NULL,+ description TEXT,+ content TEXT NOT NULL,+ category TEXT NOT NULL,+ created_at TEXT NOT NULL+ );++ CREATE INDEX IF NOT EXISTS idx_notes_category ON financial_notes(category);+ CREATE INDEX IF NOT EXISTS idx_notes_updated ON financial_notes(updated_at DESC);+ CREATE INDEX IF NOT EXISTS idx_notes_favorite ON financial_notes(is_favorite);+ CREATE INDEX IF NOT EXISTS idx_notes_archived ON financial_notes(is_archived);"+ )?;++ *conn_lock = Some(conn);+ }+ Ok(())+}++// ============================================================================+// Notes Operations+// ============================================================================++pub fn create_note(note: &Note) -> Result<i64> {+ get_notes_conn()?;+ let conn_lock = NOTES_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ conn.execute(+ "INSERT INTO financial_notes+ (title, content, category, priority, tags, tickers, sentiment, is_favorite, is_archived,+ color_code, attachments, created_at, updated_at, reminder_date, word_count)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",+ params![+ note.title,+ note.content,+ note.category,+ note.priority,+ note.tags,+ note.tickers,+ note.sentiment,+ if note.is_favorite { 1 } else { 0 },+ if note.is_archived { 1 } else { 0 },+ note.color_code,+ note.attachments,+ note.created_at,+ note.updated_at,+ note.reminder_date,+ note.word_count,+ ],+ )?;++ Ok(conn.last_insert_rowid())+}++pub fn get_all_notes(include_archived: bool) -> Result<Vec<Note>> {+ get_notes_conn()?;+ let conn_lock = NOTES_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ let query = if include_archived {+ "SELECT * FROM financial_notes ORDER BY updated_at DESC"+ } else {+ "SELECT * FROM financial_notes WHERE is_archived = 0 ORDER BY updated_at DESC"+ };++ let mut stmt = conn.prepare(query)?;+ let notes = stmt+ .query_map([], |row| {+ Ok(Note {+ id: row.get(0)?,+ title: row.get(1)?,+ content: row.get(2)?,+ category: row.get(3)?,+ priority: row.get(4)?,+ tags: row.get(5)?,+ tickers: row.get(6)?,+ sentiment: row.get(7)?,+ is_favorite: row.get::<_, i32>(8)? != 0,+ is_archived: row.get::<_, i32>(9)? != 0,+ color_code: row.get(10)?,+ attachments: row.get(11)?,+ created_at: row.get(12)?,+ updated_at: row.get(13)?,+ reminder_date: row.get(14)?,+ word_count: row.get(15)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(notes)+}++pub fn update_note(id: i64, updates: &Note) -> Result<()> {+ get_notes_conn()?;+ let conn_lock = NOTES_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ conn.execute(+ "UPDATE financial_notes SET+ title = ?1, content = ?2, category = ?3, priority = ?4, tags = ?5, tickers = ?6,+ sentiment = ?7, is_favorite = ?8, is_archived = ?9, color_code = ?10,+ attachments = ?11, updated_at = ?12, reminder_date = ?13, word_count = ?14+ WHERE id = ?15",+ params![+ updates.title,+ updates.content,+ updates.category,+ updates.priority,+ updates.tags,+ updates.tickers,+ updates.sentiment,+ if updates.is_favorite { 1 } else { 0 },+ if updates.is_archived { 1 } else { 0 },+ updates.color_code,+ updates.attachments,+ updates.updated_at,+ updates.reminder_date,+ updates.word_count,+ id,+ ],+ )?;++ Ok(())+}++pub fn delete_note(id: i64) -> Result<()> {+ get_notes_conn()?;+ let conn_lock = NOTES_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ conn.execute("DELETE FROM financial_notes WHERE id = ?1", params![id])?;++ Ok(())+}++pub fn search_notes(query: &str) -> Result<Vec<Note>> {+ get_notes_conn()?;+ let conn_lock = NOTES_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ let search_pattern = format!("%{}%", query);++ let mut stmt = conn.prepare(+ "SELECT * FROM financial_notes+ WHERE (title LIKE ?1 OR content LIKE ?1 OR tags LIKE ?1 OR tickers LIKE ?1)+ AND is_archived = 0+ ORDER BY updated_at DESC"+ )?;++ let notes = stmt+ .query_map(params![search_pattern], |row| {+ Ok(Note {+ id: row.get(0)?,+ title: row.get(1)?,+ content: row.get(2)?,+ category: row.get(3)?,+ priority: row.get(4)?,+ tags: row.get(5)?,+ tickers: row.get(6)?,+ sentiment: row.get(7)?,+ is_favorite: row.get::<_, i32>(8)? != 0,+ is_archived: row.get::<_, i32>(9)? != 0,+ color_code: row.get(10)?,+ attachments: row.get(11)?,+ created_at: row.get(12)?,+ updated_at: row.get(13)?,+ reminder_date: row.get(14)?,+ word_count: row.get(15)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(notes)+}++pub fn get_note_templates() -> Result<Vec<NoteTemplate>> {+ get_notes_conn()?;+ let conn_lock = NOTES_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ let mut stmt = conn.prepare("SELECT * FROM note_templates ORDER BY name ASC")?;+ let templates = stmt+ .query_map([], |row| {+ Ok(NoteTemplate {+ id: row.get(0)?,+ name: row.get(1)?,+ description: row.get(2)?,+ content: row.get(3)?,+ category: row.get(4)?,+ created_at: row.get(5)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(templates)+}++// ============================================================================+// Excel Database Initialization+// ============================================================================++fn get_excel_conn() -> Result<()> {+ let mut conn_lock = EXCEL_CONN.lock();+ if conn_lock.is_none() {+ let path = get_excel_db_path()?;+ let conn = Connection::open(&path).context("Failed to open excel database")?;++ // Create schema+ conn.execute_batch(+ "CREATE TABLE IF NOT EXISTS excel_files (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ file_name TEXT NOT NULL,+ file_path TEXT NOT NULL,+ sheet_count INTEGER DEFAULT 1,+ last_opened TEXT NOT NULL,+ last_modified TEXT NOT NULL,+ created_at TEXT NOT NULL+ );++ CREATE TABLE IF NOT EXISTS excel_snapshots (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ file_id INTEGER NOT NULL,+ snapshot_name TEXT NOT NULL,+ sheet_data TEXT NOT NULL,+ created_at TEXT NOT NULL,+ FOREIGN KEY (file_id) REFERENCES excel_files(id) ON DELETE CASCADE+ );++ CREATE INDEX IF NOT EXISTS idx_excel_last_opened ON excel_files(last_opened DESC);+ CREATE INDEX IF NOT EXISTS idx_snapshot_file ON excel_snapshots(file_id, created_at DESC);"+ )?;++ *conn_lock = Some(conn);+ }+ Ok(())+}++// ============================================================================+// Excel Operations+// ============================================================================++pub fn add_or_update_excel_file(file: &ExcelFile) -> Result<i64> {+ get_excel_conn()?;+ let conn_lock = EXCEL_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ // Check if exists+ let existing: Option<i64> = conn+ .query_row(+ "SELECT id FROM excel_files WHERE file_path = ?1",+ params![file.file_path],+ |row| row.get(0),+ )+ .optional()?;++ if let Some(id) = existing {+ // Update+ conn.execute(+ "UPDATE excel_files SET file_name = ?1, sheet_count = ?2, last_opened = ?3, last_modified = ?4+ WHERE file_path = ?5",+ params![file.file_name, file.sheet_count, file.last_opened, file.last_modified, file.file_path],+ )?;+ Ok(id)+ } else {+ // Insert+ conn.execute(+ "INSERT INTO excel_files (file_name, file_path, sheet_count, last_opened, last_modified, created_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",+ params![file.file_name, file.file_path, file.sheet_count, file.last_opened, file.last_modified, file.created_at],+ )?;+ Ok(conn.last_insert_rowid())+ }+}++pub fn get_recent_excel_files(limit: i64) -> Result<Vec<ExcelFile>> {+ get_excel_conn()?;+ let conn_lock = EXCEL_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ let mut stmt = conn.prepare(+ "SELECT * FROM excel_files ORDER BY last_opened DESC LIMIT ?1"+ )?;++ let files = stmt+ .query_map(params![limit], |row| {+ Ok(ExcelFile {+ id: row.get(0)?,+ file_name: row.get(1)?,+ file_path: row.get(2)?,+ sheet_count: row.get(3)?,+ last_opened: row.get(4)?,+ last_modified: row.get(5)?,+ created_at: row.get(6)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(files)+}++pub fn create_excel_snapshot(file_id: i64, snapshot_name: &str, sheet_data: &str, created_at: &str) -> Result<i64> {+ get_excel_conn()?;+ let conn_lock = EXCEL_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ conn.execute(+ "INSERT INTO excel_snapshots (file_id, snapshot_name, sheet_data, created_at)+ VALUES (?1, ?2, ?3, ?4)",+ params![file_id, snapshot_name, sheet_data, created_at],+ )?;++ Ok(conn.last_insert_rowid())+}++pub fn get_excel_snapshots(file_id: i64) -> Result<Vec<ExcelSnapshot>> {+ get_excel_conn()?;+ let conn_lock = EXCEL_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ let mut stmt = conn.prepare(+ "SELECT * FROM excel_snapshots WHERE file_id = ?1 ORDER BY created_at DESC"+ )?;++ let snapshots = stmt+ .query_map(params![file_id], |row| {+ Ok(ExcelSnapshot {+ id: row.get(0)?,+ file_id: row.get(1)?,+ snapshot_name: row.get(2)?,+ sheet_data: row.get(3)?,+ created_at: row.get(4)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(snapshots)+}++pub fn delete_excel_snapshot(id: i64) -> Result<()> {+ get_excel_conn()?;+ let conn_lock = EXCEL_CONN.lock();+ let conn = conn_lock.as_ref().unwrap();++ conn.execute("DELETE FROM excel_snapshots WHERE id = ?1", params![id])?;++ Ok(())+}diff --git a/fincept-terminal-desktop/src-tauri/src/database/operations.rs b/fincept-terminal-desktop/src-tauri/src/database/operations.rsnew file mode 100644index 000000000..f3a6cfb48--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/database/operations.rs@@ -0,0 +1,459 @@+// Database Operations - All CRUD operations with optimized queries+// Part 1: Core operations (Settings, Credentials, LLM, Chat, DataSources)++use crate::database::{pool::get_pool, types::*};+use anyhow::Result;+use rusqlite::{params, OptionalExtension};++// ============================================================================+// Settings Operations+// ============================================================================++pub fn save_setting(key: &str, value: &str, category: Option<&str>) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT OR REPLACE INTO settings (setting_key, setting_value, category, updated_at)+ VALUES (?1, ?2, ?3, CURRENT_TIMESTAMP)",+ params![key, value, category],+ )?;++ Ok(())+}++pub fn get_setting(key: &str) -> Result<Option<String>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let result = conn+ .query_row(+ "SELECT setting_value FROM settings WHERE setting_key = ?1",+ params![key],+ |row| row.get(0),+ )+ .optional()?;++ Ok(result)+}++pub fn get_all_settings() -> Result<Vec<Setting>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare("SELECT setting_key, setting_value, category, updated_at FROM settings")?;+ let settings = stmt+ .query_map([], |row| {+ Ok(Setting {+ setting_key: row.get(0)?,+ setting_value: row.get(1)?,+ category: row.get(2)?,+ updated_at: row.get(3)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(settings)+}++// ============================================================================+// Credentials Operations+// ============================================================================++pub fn save_credential(cred: &Credential) -> Result<OperationResult> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT OR REPLACE INTO credentials+ (service_name, username, password, api_key, api_secret, additional_data, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, CURRENT_TIMESTAMP)",+ params![+ cred.service_name,+ cred.username,+ cred.password,+ cred.api_key,+ cred.api_secret,+ cred.additional_data,+ ],+ )?;++ Ok(OperationResult {+ success: true,+ message: "Credential saved successfully".to_string(),+ })+}++pub fn get_credentials() -> Result<Vec<Credential>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, service_name, username, password, api_key, api_secret, additional_data, created_at, updated_at+ FROM credentials ORDER BY service_name"+ )?;++ let credentials = stmt+ .query_map([], |row| {+ Ok(Credential {+ id: row.get(0)?,+ service_name: row.get(1)?,+ username: row.get(2)?,+ password: row.get(3)?,+ api_key: row.get(4)?,+ api_secret: row.get(5)?,+ additional_data: row.get(6)?,+ created_at: row.get(7)?,+ updated_at: row.get(8)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(credentials)+}++pub fn get_credential_by_service(service_name: &str) -> Result<Option<Credential>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let result = conn+ .query_row(+ "SELECT id, service_name, username, password, api_key, api_secret, additional_data, created_at, updated_at+ FROM credentials WHERE service_name = ?1",+ params![service_name],+ |row| {+ Ok(Credential {+ id: row.get(0)?,+ service_name: row.get(1)?,+ username: row.get(2)?,+ password: row.get(3)?,+ api_key: row.get(4)?,+ api_secret: row.get(5)?,+ additional_data: row.get(6)?,+ created_at: row.get(7)?,+ updated_at: row.get(8)?,+ })+ },+ )+ .optional()?;++ Ok(result)+}++pub fn delete_credential(id: i64) -> Result<OperationResult> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute("DELETE FROM credentials WHERE id = ?1", params![id])?;++ Ok(OperationResult {+ success: true,+ message: "Credential deleted successfully".to_string(),+ })+}++// ============================================================================+// LLM Config Operations+// ============================================================================++pub fn get_llm_configs() -> Result<Vec<LLMConfig>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT provider, api_key, base_url, model, is_active, created_at, updated_at+ FROM llm_configs"+ )?;++ let configs = stmt+ .query_map([], |row| {+ Ok(LLMConfig {+ provider: row.get(0)?,+ api_key: row.get(1)?,+ base_url: row.get(2)?,+ model: row.get(3)?,+ is_active: row.get::<_, i32>(4)? != 0,+ created_at: row.get(5)?,+ updated_at: row.get(6)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(configs)+}++pub fn save_llm_config(config: &LLMConfig) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT OR REPLACE INTO llm_configs (provider, api_key, base_url, model, is_active, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, CURRENT_TIMESTAMP)",+ params![+ config.provider,+ config.api_key,+ config.base_url,+ config.model,+ if config.is_active { 1 } else { 0 },+ ],+ )?;++ Ok(())+}++pub fn get_llm_global_settings() -> Result<LLMGlobalSettings> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let result = conn.query_row(+ "SELECT temperature, max_tokens, system_prompt FROM llm_global_settings WHERE id = 1",+ [],+ |row| {+ Ok(LLMGlobalSettings {+ temperature: row.get(0)?,+ max_tokens: row.get(1)?,+ system_prompt: row.get(2)?,+ })+ },+ )?;++ Ok(result)+}++pub fn save_llm_global_settings(settings: &LLMGlobalSettings) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "UPDATE llm_global_settings SET temperature = ?1, max_tokens = ?2, system_prompt = ?3 WHERE id = 1",+ params![settings.temperature, settings.max_tokens, settings.system_prompt],+ )?;++ Ok(())+}++// ============================================================================+// Chat Operations+// ============================================================================++pub fn create_chat_session(title: &str) -> Result<ChatSession> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let session_uuid = uuid::Uuid::new_v4().to_string();++ conn.execute(+ "INSERT INTO chat_sessions (session_uuid, title) VALUES (?1, ?2)",+ params![session_uuid, title],+ )?;++ let session = conn.query_row(+ "SELECT session_uuid, title, message_count, created_at, updated_at+ FROM chat_sessions WHERE session_uuid = ?1",+ params![session_uuid],+ |row| {+ Ok(ChatSession {+ session_uuid: row.get(0)?,+ title: row.get(1)?,+ message_count: row.get(2)?,+ created_at: row.get(3)?,+ updated_at: row.get(4)?,+ })+ },+ )?;++ Ok(session)+}++pub fn get_chat_sessions(limit: Option<i64>) -> Result<Vec<ChatSession>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let query = if let Some(lim) = limit {+ format!(+ "SELECT session_uuid, title, message_count, created_at, updated_at+ FROM chat_sessions ORDER BY updated_at DESC LIMIT {}",+ lim+ )+ } else {+ "SELECT session_uuid, title, message_count, created_at, updated_at+ FROM chat_sessions ORDER BY updated_at DESC"+ .to_string()+ };++ let mut stmt = conn.prepare(&query)?;+ let sessions = stmt+ .query_map([], |row| {+ Ok(ChatSession {+ session_uuid: row.get(0)?,+ title: row.get(1)?,+ message_count: row.get(2)?,+ created_at: row.get(3)?,+ updated_at: row.get(4)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(sessions)+}++pub fn add_chat_message(msg: &ChatMessage) -> Result<ChatMessage> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT INTO chat_messages (id, session_uuid, role, content, provider, model, tokens_used)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",+ params![+ msg.id,+ msg.session_uuid,+ msg.role,+ msg.content,+ msg.provider,+ msg.model,+ msg.tokens_used,+ ],+ )?;++ // Update message count+ conn.execute(+ "UPDATE chat_sessions SET message_count = message_count + 1, updated_at = CURRENT_TIMESTAMP+ WHERE session_uuid = ?1",+ params![msg.session_uuid],+ )?;++ let result = conn.query_row(+ "SELECT id, session_uuid, role, content, timestamp, provider, model, tokens_used+ FROM chat_messages WHERE id = ?1",+ params![msg.id],+ |row| {+ Ok(ChatMessage {+ id: row.get(0)?,+ session_uuid: row.get(1)?,+ role: row.get(2)?,+ content: row.get(3)?,+ timestamp: row.get(4)?,+ provider: row.get(5)?,+ model: row.get(6)?,+ tokens_used: row.get(7)?,+ })+ },+ )?;++ Ok(result)+}++pub fn get_chat_messages(session_uuid: &str) -> Result<Vec<ChatMessage>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, session_uuid, role, content, timestamp, provider, model, tokens_used+ FROM chat_messages WHERE session_uuid = ?1 ORDER BY timestamp ASC"+ )?;++ let messages = stmt+ .query_map(params![session_uuid], |row| {+ Ok(ChatMessage {+ id: row.get(0)?,+ session_uuid: row.get(1)?,+ role: row.get(2)?,+ content: row.get(3)?,+ timestamp: row.get(4)?,+ provider: row.get(5)?,+ model: row.get(6)?,+ tokens_used: row.get(7)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(messages)+}++pub fn delete_chat_session(session_uuid: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "DELETE FROM chat_sessions WHERE session_uuid = ?1",+ params![session_uuid],+ )?;++ Ok(())+}++// ============================================================================+// Data Sources Operations+// ============================================================================++pub fn save_data_source(source: &DataSource) -> Result<OperationResultWithId> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT OR REPLACE INTO data_sources+ (id, alias, display_name, description, type, provider, category, config, enabled, tags, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, CURRENT_TIMESTAMP)",+ params![+ source.id,+ source.alias,+ source.display_name,+ source.description,+ source.ds_type,+ source.provider,+ source.category,+ source.config,+ if source.enabled { 1 } else { 0 },+ source.tags,+ ],+ )?;++ Ok(OperationResultWithId {+ success: true,+ message: "Data source saved successfully".to_string(),+ id: Some(source.id.clone()),+ })+}++pub fn get_all_data_sources() -> Result<Vec<DataSource>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, alias, display_name, description, type, provider, category, config, enabled, tags, created_at, updated_at+ FROM data_sources ORDER BY display_name"+ )?;++ let sources = stmt+ .query_map([], |row| {+ Ok(DataSource {+ id: row.get(0)?,+ alias: row.get(1)?,+ display_name: row.get(2)?,+ description: row.get(3)?,+ ds_type: row.get(4)?,+ provider: row.get(5)?,+ category: row.get(6)?,+ config: row.get(7)?,+ enabled: row.get::<_, i32>(8)? != 0,+ tags: row.get(9)?,+ created_at: row.get(10)?,+ updated_at: row.get(11)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(sources)+}++pub fn delete_data_source(id: &str) -> Result<OperationResult> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute("DELETE FROM data_sources WHERE id = ?1", params![id])?;++ Ok(OperationResult {+ success: true,+ message: "Data source deleted successfully".to_string(),+ })+}diff --git a/fincept-terminal-desktop/src-tauri/src/database/paper_trading.rs b/fincept-terminal-desktop/src-tauri/src/database/paper_trading.rsnew file mode 100644index 000000000..86e9c3b2e--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/database/paper_trading.rs@@ -0,0 +1,834 @@+// Paper Trading Operations - Portfolio, positions, orders, trades++use crate::database::pool::get_pool;+use anyhow::Result;+use rusqlite::params;+use serde::{Deserialize, Serialize};++// ============================================================================+// Types+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PaperTradingPortfolio {+ pub id: String,+ pub name: String,+ pub provider: String,+ pub initial_balance: f64,+ pub current_balance: f64,+ pub currency: String,+ pub margin_mode: String,+ pub leverage: f64,+ pub created_at: String,+ pub updated_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PaperTradingPosition {+ pub id: String,+ pub portfolio_id: String,+ pub symbol: String,+ pub side: String,+ pub entry_price: f64,+ pub quantity: f64,+ pub position_value: Option<f64>,+ pub current_price: Option<f64>,+ pub unrealized_pnl: Option<f64>,+ pub realized_pnl: f64,+ pub leverage: f64,+ pub margin_mode: String,+ pub liquidation_price: Option<f64>,+ pub opened_at: String,+ pub closed_at: Option<String>,+ pub status: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PaperTradingOrder {+ pub id: String,+ pub portfolio_id: String,+ pub symbol: String,+ pub side: String,+ pub order_type: String,+ pub quantity: f64,+ pub price: Option<f64>,+ pub stop_price: Option<f64>,+ pub filled_quantity: f64,+ pub avg_fill_price: Option<f64>,+ pub status: String,+ pub time_in_force: String,+ pub post_only: bool,+ pub reduce_only: bool,+ pub created_at: String,+ pub filled_at: Option<String>,+ pub updated_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PaperTradingTrade {+ pub id: String,+ pub portfolio_id: String,+ pub order_id: String,+ pub symbol: String,+ pub side: String,+ pub price: f64,+ pub quantity: f64,+ pub fee: f64,+ pub fee_rate: f64,+ pub is_maker: bool,+ pub timestamp: String,+}++// ============================================================================+// Portfolio Operations+// ============================================================================++pub fn create_portfolio(+ id: &str,+ name: &str,+ provider: &str,+ initial_balance: f64,+ currency: &str,+ margin_mode: &str,+ leverage: f64,+) -> Result<PaperTradingPortfolio> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT INTO paper_trading_portfolios+ (id, name, provider, initial_balance, current_balance, currency, margin_mode, leverage)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",+ params![id, name, provider, initial_balance, initial_balance, currency, margin_mode, leverage],+ )?;++ get_portfolio(id)+}++pub fn get_portfolio(id: &str) -> Result<PaperTradingPortfolio> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let portfolio = conn.query_row(+ "SELECT id, name, provider, initial_balance, current_balance, currency, margin_mode, leverage, created_at, updated_at+ FROM paper_trading_portfolios WHERE id = ?1",+ params![id],+ |row| {+ Ok(PaperTradingPortfolio {+ id: row.get(0)?,+ name: row.get(1)?,+ provider: row.get(2)?,+ initial_balance: row.get(3)?,+ current_balance: row.get(4)?,+ currency: row.get(5)?,+ margin_mode: row.get(6)?,+ leverage: row.get(7)?,+ created_at: row.get(8)?,+ updated_at: row.get(9)?,+ })+ },+ )?;++ Ok(portfolio)+}++pub fn update_portfolio_balance(id: &str, new_balance: f64) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "UPDATE paper_trading_portfolios SET current_balance = ?1, updated_at = CURRENT_TIMESTAMP WHERE id = ?2",+ params![new_balance, id],+ )?;++ Ok(())+}++pub fn list_portfolios() -> Result<Vec<PaperTradingPortfolio>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, name, provider, initial_balance, current_balance, currency, margin_mode, leverage, created_at, updated_at+ FROM paper_trading_portfolios ORDER BY created_at DESC"+ )?;++ let portfolios = stmt+ .query_map([], |row| {+ Ok(PaperTradingPortfolio {+ id: row.get(0)?,+ name: row.get(1)?,+ provider: row.get(2)?,+ initial_balance: row.get(3)?,+ current_balance: row.get(4)?,+ currency: row.get(5)?,+ margin_mode: row.get(6)?,+ leverage: row.get(7)?,+ created_at: row.get(8)?,+ updated_at: row.get(9)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(portfolios)+}++pub fn delete_portfolio(id: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "DELETE FROM paper_trading_portfolios WHERE id = ?1",+ params![id],+ )?;++ Ok(())+}++// ============================================================================+// Position Operations+// ============================================================================++pub fn create_position(+ id: &str,+ portfolio_id: &str,+ symbol: &str,+ side: &str,+ entry_price: f64,+ quantity: f64,+ leverage: f64,+ margin_mode: &str,+) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let position_value = entry_price * quantity;++ conn.execute(+ "INSERT INTO paper_trading_positions+ (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')",+ params![id, portfolio_id, symbol, side, entry_price, quantity, position_value, leverage, margin_mode],+ )?;++ Ok(())+}++pub fn get_portfolio_positions(portfolio_id: &str, status: Option<&str>) -> Result<Vec<PaperTradingPosition>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let query = if let Some(st) = status {+ format!(+ "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 status = '{}' ORDER BY opened_at DESC",+ st+ )+ } else {+ "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 ORDER BY opened_at DESC"+ .to_string()+ };++ let mut stmt = conn.prepare(&query)?;+ let positions = stmt+ .query_map(params![portfolio_id], |row| {+ Ok(PaperTradingPosition {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ symbol: row.get(2)?,+ side: row.get(3)?,+ entry_price: row.get(4)?,+ quantity: row.get(5)?,+ position_value: row.get(6)?,+ current_price: row.get(7)?,+ unrealized_pnl: row.get(8)?,+ realized_pnl: row.get(9)?,+ leverage: row.get(10)?,+ margin_mode: row.get(11)?,+ liquidation_price: row.get(12)?,+ opened_at: row.get(13)?,+ closed_at: row.get(14)?,+ status: row.get(15)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(positions)+}++pub fn get_position(id: &str) -> Result<PaperTradingPosition> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let position = conn.query_row(+ "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 id = ?1",+ params![id],+ |row| {+ Ok(PaperTradingPosition {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ symbol: row.get(2)?,+ side: row.get(3)?,+ entry_price: row.get(4)?,+ quantity: row.get(5)?,+ position_value: row.get(6)?,+ current_price: row.get(7)?,+ unrealized_pnl: row.get(8)?,+ realized_pnl: row.get(9)?,+ leverage: row.get(10)?,+ margin_mode: row.get(11)?,+ liquidation_price: row.get(12)?,+ opened_at: row.get(13)?,+ closed_at: row.get(14)?,+ status: row.get(15)?,+ })+ },+ )?;++ Ok(position)+}++pub fn get_position_by_symbol(portfolio_id: &str, symbol: &str, status: &str) -> Result<Option<PaperTradingPosition>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let position = conn.query_row(+ "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 status = ?3+ ORDER BY opened_at DESC LIMIT 1",+ params![portfolio_id, symbol, status],+ |row| {+ Ok(PaperTradingPosition {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ symbol: row.get(2)?,+ side: row.get(3)?,+ entry_price: row.get(4)?,+ quantity: row.get(5)?,+ position_value: row.get(6)?,+ current_price: row.get(7)?,+ unrealized_pnl: row.get(8)?,+ realized_pnl: row.get(9)?,+ leverage: row.get(10)?,+ margin_mode: row.get(11)?,+ liquidation_price: row.get(12)?,+ opened_at: row.get(13)?,+ closed_at: row.get(14)?,+ status: row.get(15)?,+ })+ },+ );++ match position {+ Ok(p) => Ok(Some(p)),+ Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),+ Err(e) => Err(e.into()),+ }+}++pub fn get_position_by_symbol_and_side(+ portfolio_id: &str,+ symbol: &str,+ side: &str,+ status: &str,+) -> Result<Option<PaperTradingPosition>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let position = conn.query_row(+ "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",+ params![portfolio_id, symbol, side, status],+ |row| {+ Ok(PaperTradingPosition {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ symbol: row.get(2)?,+ side: row.get(3)?,+ entry_price: row.get(4)?,+ quantity: row.get(5)?,+ position_value: row.get(6)?,+ current_price: row.get(7)?,+ unrealized_pnl: row.get(8)?,+ realized_pnl: row.get(9)?,+ leverage: row.get(10)?,+ margin_mode: row.get(11)?,+ liquidation_price: row.get(12)?,+ opened_at: row.get(13)?,+ closed_at: row.get(14)?,+ status: row.get(15)?,+ })+ },+ );++ match position {+ Ok(p) => Ok(Some(p)),+ Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),+ Err(e) => Err(e.into()),+ }+}++pub fn update_position(+ id: &str,+ quantity: Option<f64>,+ entry_price: Option<f64>,+ current_price: Option<f64>,+ unrealized_pnl: Option<f64>,+ realized_pnl: Option<f64>,+ liquidation_price: Option<f64>,+ status: Option<&str>,+ closed_at: Option<&str>,+) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut updates = Vec::new();+ let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();++ if let Some(q) = quantity {+ updates.push("quantity = ?".to_string());+ params_vec.push(Box::new(q));+ }+ if let Some(ep) = entry_price {+ updates.push("entry_price = ?".to_string());+ params_vec.push(Box::new(ep));+ }+ if let Some(cp) = current_price {+ updates.push("current_price = ?".to_string());+ params_vec.push(Box::new(cp));+ }+ if let Some(upnl) = unrealized_pnl {+ updates.push("unrealized_pnl = ?".to_string());+ params_vec.push(Box::new(upnl));+ }+ if let Some(rpnl) = realized_pnl {+ updates.push("realized_pnl = ?".to_string());+ params_vec.push(Box::new(rpnl));+ }+ if let Some(lp) = liquidation_price {+ updates.push("liquidation_price = ?".to_string());+ params_vec.push(Box::new(lp));+ }+ if let Some(st) = status {+ updates.push("status = ?".to_string());+ params_vec.push(Box::new(st.to_string()));+ }+ if let Some(ca) = closed_at {+ updates.push("closed_at = ?".to_string());+ params_vec.push(Box::new(ca.to_string()));+ }++ if updates.is_empty() {+ return Ok(());+ }++ params_vec.push(Box::new(id.to_string()));+ let sql = format!("UPDATE paper_trading_positions SET {} WHERE id = ?", updates.join(", "));++ let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();+ conn.execute(&sql, params_refs.as_slice())?;++ Ok(())+}++pub fn delete_position(id: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "DELETE FROM paper_trading_positions WHERE id = ?1",+ params![id],+ )?;++ Ok(())+}++// ============================================================================+// Order Operations+// ============================================================================++pub fn create_order(+ id: &str,+ portfolio_id: &str,+ symbol: &str,+ side: &str,+ order_type: &str,+ quantity: f64,+ price: Option<f64>,+ time_in_force: &str,+) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT INTO paper_trading_orders+ (id, portfolio_id, symbol, side, type, quantity, price, status, time_in_force, filled_quantity)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 'pending', ?8, 0)",+ params![id, portfolio_id, symbol, side, order_type, quantity, price, time_in_force],+ )?;++ Ok(())+}++pub fn get_portfolio_orders(portfolio_id: &str, status: Option<&str>) -> Result<Vec<PaperTradingOrder>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let query = if let Some(st) = status {+ format!(+ "SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price, filled_quantity,+ avg_fill_price, status, time_in_force, post_only, reduce_only, created_at, filled_at, updated_at+ FROM paper_trading_orders WHERE portfolio_id = ?1 AND status = '{}' ORDER BY created_at DESC",+ st+ )+ } else {+ "SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price, filled_quantity,+ avg_fill_price, status, time_in_force, post_only, reduce_only, created_at, filled_at, updated_at+ FROM paper_trading_orders WHERE portfolio_id = ?1 ORDER BY created_at DESC"+ .to_string()+ };++ let mut stmt = conn.prepare(&query)?;+ let orders = stmt+ .query_map(params![portfolio_id], |row| {+ Ok(PaperTradingOrder {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ symbol: row.get(2)?,+ side: row.get(3)?,+ order_type: row.get(4)?,+ quantity: row.get(5)?,+ price: row.get(6)?,+ stop_price: row.get(7)?,+ filled_quantity: row.get(8)?,+ avg_fill_price: row.get(9)?,+ status: row.get(10)?,+ time_in_force: row.get(11)?,+ post_only: row.get::<_, i32>(12)? != 0,+ reduce_only: row.get::<_, i32>(13)? != 0,+ created_at: row.get(14)?,+ filled_at: row.get(15)?,+ updated_at: row.get(16)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(orders)+}++#[allow(dead_code)]+pub fn update_order_status(id: &str, status: &str, filled_quantity: f64, avg_fill_price: Option<f64>) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "UPDATE paper_trading_orders+ SET status = ?1, filled_quantity = ?2, avg_fill_price = ?3, updated_at = CURRENT_TIMESTAMP+ WHERE id = ?4",+ params![status, filled_quantity, avg_fill_price, id],+ )?;++ Ok(())+}++pub fn get_order(id: &str) -> Result<PaperTradingOrder> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let order = conn.query_row(+ "SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price, filled_quantity,+ avg_fill_price, status, time_in_force, post_only, reduce_only, created_at, filled_at, updated_at+ FROM paper_trading_orders WHERE id = ?1",+ params![id],+ |row| {+ Ok(PaperTradingOrder {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ symbol: row.get(2)?,+ side: row.get(3)?,+ order_type: row.get(4)?,+ quantity: row.get(5)?,+ price: row.get(6)?,+ stop_price: row.get(7)?,+ filled_quantity: row.get(8)?,+ avg_fill_price: row.get(9)?,+ status: row.get(10)?,+ time_in_force: row.get(11)?,+ post_only: row.get::<_, i32>(12)? != 0,+ reduce_only: row.get::<_, i32>(13)? != 0,+ created_at: row.get(14)?,+ filled_at: row.get(15)?,+ updated_at: row.get(16)?,+ })+ },+ )?;++ Ok(order)+}++pub fn get_pending_orders(portfolio_id: Option<&str>) -> Result<Vec<PaperTradingOrder>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ if let Some(pid) = portfolio_id {+ let mut stmt = conn.prepare(+ "SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price, filled_quantity,+ avg_fill_price, status, time_in_force, post_only, reduce_only, created_at, filled_at, updated_at+ FROM paper_trading_orders WHERE status IN ('pending', 'triggered', 'partial') AND portfolio_id = ?1+ ORDER BY created_at ASC"+ )?;++ let orders = stmt.query_map(params![pid], |row| {+ Ok(PaperTradingOrder {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ symbol: row.get(2)?,+ side: row.get(3)?,+ order_type: row.get(4)?,+ quantity: row.get(5)?,+ price: row.get(6)?,+ stop_price: row.get(7)?,+ filled_quantity: row.get(8)?,+ avg_fill_price: row.get(9)?,+ status: row.get(10)?,+ time_in_force: row.get(11)?,+ post_only: row.get::<_, i32>(12)? != 0,+ reduce_only: row.get::<_, i32>(13)? != 0,+ created_at: row.get(14)?,+ filled_at: row.get(15)?,+ updated_at: row.get(16)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(orders)+ } else {+ let mut stmt = conn.prepare(+ "SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price, filled_quantity,+ avg_fill_price, status, time_in_force, post_only, reduce_only, created_at, filled_at, updated_at+ FROM paper_trading_orders WHERE status IN ('pending', 'triggered', 'partial')+ ORDER BY created_at ASC"+ )?;++ let orders = stmt.query_map([], |row| {+ Ok(PaperTradingOrder {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ symbol: row.get(2)?,+ side: row.get(3)?,+ order_type: row.get(4)?,+ quantity: row.get(5)?,+ price: row.get(6)?,+ stop_price: row.get(7)?,+ filled_quantity: row.get(8)?,+ avg_fill_price: row.get(9)?,+ status: row.get(10)?,+ time_in_force: row.get(11)?,+ post_only: row.get::<_, i32>(12)? != 0,+ reduce_only: row.get::<_, i32>(13)? != 0,+ created_at: row.get(14)?,+ filled_at: row.get(15)?,+ updated_at: row.get(16)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(orders)+ }+}++pub fn update_order(+ id: &str,+ filled_quantity: Option<f64>,+ avg_fill_price: Option<f64>,+ status: Option<&str>,+ filled_at: Option<&str>,+) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut updates = vec!["updated_at = CURRENT_TIMESTAMP".to_string()];+ let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();++ if let Some(fq) = filled_quantity {+ updates.push("filled_quantity = ?".to_string());+ params_vec.push(Box::new(fq));+ }+ if let Some(afp) = avg_fill_price {+ updates.push("avg_fill_price = ?".to_string());+ params_vec.push(Box::new(afp));+ }+ if let Some(st) = status {+ updates.push("status = ?".to_string());+ params_vec.push(Box::new(st.to_string()));+ }+ if let Some(fa) = filled_at {+ updates.push("filled_at = ?".to_string());+ params_vec.push(Box::new(fa.to_string()));+ }++ params_vec.push(Box::new(id.to_string()));+ let sql = format!("UPDATE paper_trading_orders SET {} WHERE id = ?", updates.join(", "));++ let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();+ conn.execute(&sql, params_refs.as_slice())?;++ Ok(())+}++pub fn delete_order(id: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "DELETE FROM paper_trading_orders WHERE id = ?1",+ params![id],+ )?;++ Ok(())+}++// ============================================================================+// Trade Operations+// ============================================================================++pub fn create_trade(+ id: &str,+ portfolio_id: &str,+ order_id: &str,+ symbol: &str,+ side: &str,+ price: f64,+ quantity: f64,+ fee: f64,+ fee_rate: f64,+ is_maker: bool,+) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT INTO paper_trading_trades+ (id, portfolio_id, order_id, symbol, side, price, quantity, fee, fee_rate, is_maker)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",+ params![id, portfolio_id, order_id, symbol, side, price, quantity, fee, fee_rate, if is_maker { 1 } else { 0 }],+ )?;++ Ok(())+}++pub fn get_portfolio_trades(portfolio_id: &str, limit: Option<i64>) -> Result<Vec<PaperTradingTrade>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let query = if let Some(lim) = limit {+ format!(+ "SELECT id, portfolio_id, order_id, symbol, side, price, quantity, fee, fee_rate, is_maker, timestamp+ FROM paper_trading_trades WHERE portfolio_id = ?1 ORDER BY timestamp DESC LIMIT {}",+ lim+ )+ } else {+ "SELECT id, portfolio_id, order_id, symbol, side, price, quantity, fee, fee_rate, is_maker, timestamp+ FROM paper_trading_trades WHERE portfolio_id = ?1 ORDER BY timestamp DESC"+ .to_string()+ };++ let mut stmt = conn.prepare(&query)?;+ let trades = stmt+ .query_map(params![portfolio_id], |row| {+ Ok(PaperTradingTrade {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ order_id: row.get(2)?,+ symbol: row.get(3)?,+ side: row.get(4)?,+ price: row.get(5)?,+ quantity: row.get(6)?,+ fee: row.get(7)?,+ fee_rate: row.get(8)?,+ is_maker: row.get::<_, i32>(9)? != 0,+ timestamp: row.get(10)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(trades)+}++pub fn get_trade(id: &str) -> Result<PaperTradingTrade> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let trade = conn.query_row(+ "SELECT id, portfolio_id, order_id, symbol, side, price, quantity, fee, fee_rate, is_maker, timestamp+ FROM paper_trading_trades WHERE id = ?1",+ params![id],+ |row| {+ Ok(PaperTradingTrade {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ order_id: row.get(2)?,+ symbol: row.get(3)?,+ side: row.get(4)?,+ price: row.get(5)?,+ quantity: row.get(6)?,+ fee: row.get(7)?,+ fee_rate: row.get(8)?,+ is_maker: row.get::<_, i32>(9)? != 0,+ timestamp: row.get(10)?,+ })+ },+ )?;++ Ok(trade)+}++pub fn get_order_trades(order_id: &str) -> Result<Vec<PaperTradingTrade>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, portfolio_id, order_id, symbol, side, price, quantity, fee, fee_rate, is_maker, timestamp+ FROM paper_trading_trades WHERE order_id = ?1 ORDER BY timestamp ASC"+ )?;++ let trades = stmt+ .query_map(params![order_id], |row| {+ Ok(PaperTradingTrade {+ id: row.get(0)?,+ portfolio_id: row.get(1)?,+ order_id: row.get(2)?,+ symbol: row.get(3)?,+ side: row.get(4)?,+ price: row.get(5)?,+ quantity: row.get(6)?,+ fee: row.get(7)?,+ fee_rate: row.get(8)?,+ is_maker: row.get::<_, i32>(9)? != 0,+ timestamp: row.get(10)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(trades)+}++pub fn delete_trade(id: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "DELETE FROM paper_trading_trades WHERE id = ?1",+ params![id],+ )?;++ Ok(())+}diff --git a/fincept-terminal-desktop/src-tauri/src/database/pool.rs b/fincept-terminal-desktop/src-tauri/src/database/pool.rsnew file mode 100644index 000000000..0da842263--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/database/pool.rs@@ -0,0 +1,163 @@+// Connection Pool Management - Singleton with r2d2 for concurrent access++use anyhow::{Context, Result};+use once_cell::sync::OnceCell;+use parking_lot::RwLock;+use r2d2::Pool;+use r2d2_sqlite::SqliteConnectionManager;+use rusqlite::OpenFlags;+use std::sync::Arc;++pub type DbPool = Arc<Pool<SqliteConnectionManager>>;++static POOL: OnceCell<RwLock<Option<DbPool>>> = OnceCell::new();++/// Get database connection pool (lazy initialized)+pub fn get_pool() -> Result<DbPool> {+ let pool_lock = POOL.get_or_init(|| RwLock::new(None));+ let pool_read = pool_lock.read();++ if let Some(pool) = pool_read.as_ref() {+ return Ok(Arc::clone(pool));+ }++ drop(pool_read);+ Err(anyhow::anyhow!("Database not initialized. Call init_database first."))+}++/// Initialize database connection pool with optimal settings+pub async fn init_database() -> Result<DbPool> {+ let pool_lock = POOL.get_or_init(|| RwLock::new(None));++ // Check if already initialized+ {+ let pool_read = pool_lock.read();+ if let Some(pool) = pool_read.as_ref() {+ return Ok(Arc::clone(pool));+ }+ }++ // Initialize pool+ let mut pool_write = pool_lock.write();++ // Get database path+ let db_path = get_db_path()?;++ // Create connection manager with optimizations+ let manager = SqliteConnectionManager::file(&db_path)+ .with_flags(+ OpenFlags::SQLITE_OPEN_READ_WRITE+ | OpenFlags::SQLITE_OPEN_CREATE+ | OpenFlags::SQLITE_OPEN_NO_MUTEX, // Faster with connection pool+ )+ .with_init(|conn| {+ // Performance optimizations+ conn.execute_batch(+ "PRAGMA journal_mode = WAL;+ PRAGMA synchronous = NORMAL;+ PRAGMA cache_size = -64000;+ PRAGMA temp_store = MEMORY;+ PRAGMA mmap_size = 30000000000;+ PRAGMA page_size = 4096;+ PRAGMA foreign_keys = ON;",+ )?;+ Ok(())+ });++ // Create pool with optimal settings+ let pool = Pool::builder()+ .max_size(16) // Support 16 concurrent connections+ .min_idle(Some(2)) // Keep 2 connections warm+ .connection_timeout(std::time::Duration::from_secs(5))+ .build(manager)+ .context("Failed to create connection pool")?;++ let pool_arc = Arc::new(pool);++ // Initialize schema+ {+ let conn = pool_arc.get().context("Failed to get connection")?;+ crate::database::schema::create_schema(&conn)?;+ }++ *pool_write = Some(Arc::clone(&pool_arc));++ Ok(pool_arc)+}++/// Get database file path - platform-specific app data directories+fn get_db_path() -> Result<std::path::PathBuf> {+ let db_dir = if cfg!(target_os = "windows") {+ // Windows: %APPDATA%\fincept-terminal+ let appdata = std::env::var("APPDATA")+ .context("APPDATA environment variable not set")?;+ std::path::PathBuf::from(appdata).join("fincept-terminal")+ } else if cfg!(target_os = "macos") {+ // macOS: ~/Library/Application Support/fincept-terminal+ let home = std::env::var("HOME")+ .context("HOME environment variable not set")?;+ std::path::PathBuf::from(home)+ .join("Library")+ .join("Application Support")+ .join("fincept-terminal")+ } else {+ // Linux: ~/.local/share/fincept-terminal (XDG Base Directory)+ let home = std::env::var("HOME")+ .context("HOME environment variable not set")?;+ let xdg_data = std::env::var("XDG_DATA_HOME")+ .unwrap_or_else(|_| format!("{}/.local/share", home));+ std::path::PathBuf::from(xdg_data).join("fincept-terminal")+ };++ std::fs::create_dir_all(&db_dir).context("Failed to create database directory")?;+ Ok(db_dir.join("fincept_terminal.db"))+}++/// Get separate database paths for notes and excel+pub fn get_notes_db_path() -> Result<std::path::PathBuf> {+ let db_dir = if cfg!(target_os = "windows") {+ let appdata = std::env::var("APPDATA")+ .context("APPDATA environment variable not set")?;+ std::path::PathBuf::from(appdata).join("fincept-terminal")+ } else if cfg!(target_os = "macos") {+ let home = std::env::var("HOME")+ .context("HOME environment variable not set")?;+ std::path::PathBuf::from(home)+ .join("Library")+ .join("Application Support")+ .join("fincept-terminal")+ } else {+ let home = std::env::var("HOME")+ .context("HOME environment variable not set")?;+ let xdg_data = std::env::var("XDG_DATA_HOME")+ .unwrap_or_else(|_| format!("{}/.local/share", home));+ std::path::PathBuf::from(xdg_data).join("fincept-terminal")+ };++ std::fs::create_dir_all(&db_dir).context("Failed to create database directory")?;+ Ok(db_dir.join("financial_notes.db"))+}++pub fn get_excel_db_path() -> Result<std::path::PathBuf> {+ let db_dir = if cfg!(target_os = "windows") {+ let appdata = std::env::var("APPDATA")+ .context("APPDATA environment variable not set")?;+ std::path::PathBuf::from(appdata).join("fincept-terminal")+ } else if cfg!(target_os = "macos") {+ let home = std::env::var("HOME")+ .context("HOME environment variable not set")?;+ std::path::PathBuf::from(home)+ .join("Library")+ .join("Application Support")+ .join("fincept-terminal")+ } else {+ let home = std::env::var("HOME")+ .context("HOME environment variable not set")?;+ let xdg_data = std::env::var("XDG_DATA_HOME")+ .unwrap_or_else(|_| format!("{}/.local/share", home));+ std::path::PathBuf::from(xdg_data).join("fincept-terminal")+ };++ std::fs::create_dir_all(&db_dir).context("Failed to create database directory")?;+ Ok(db_dir.join("excel_files.db"))+}diff --git a/fincept-terminal-desktop/src-tauri/src/database/queries.rs b/fincept-terminal-desktop/src-tauri/src/database/queries.rsnew file mode 100644index 000000000..0268e1b48--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/database/queries.rs@@ -0,0 +1,483 @@+// Specialized Query Operations - Complex queries, MCP, Backtesting, Context Recording++use crate::database::{pool::get_pool, types::*};+use anyhow::Result;+use rusqlite::params;++// ============================================================================+// MCP Server Operations+// ============================================================================++pub fn add_mcp_server(server: &MCPServer) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT OR REPLACE INTO mcp_servers+ (id, name, description, command, args, env, category, icon, enabled, auto_start, status, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, CURRENT_TIMESTAMP)",+ params![+ server.id,+ server.name,+ server.description,+ server.command,+ server.args,+ server.env,+ server.category,+ server.icon,+ if server.enabled { 1 } else { 0 },+ if server.auto_start { 1 } else { 0 },+ server.status,+ ],+ )?;++ Ok(())+}++pub fn get_mcp_servers() -> Result<Vec<MCPServer>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, name, description, command, args, env, category, icon, enabled, auto_start, status, created_at, updated_at+ FROM mcp_servers ORDER BY name"+ )?;++ let servers = stmt+ .query_map([], |row| {+ Ok(MCPServer {+ id: row.get(0)?,+ name: row.get(1)?,+ description: row.get(2)?,+ command: row.get(3)?,+ args: row.get(4)?,+ env: row.get(5)?,+ category: row.get(6)?,+ icon: row.get(7)?,+ enabled: row.get::<_, i32>(8)? != 0,+ auto_start: row.get::<_, i32>(9)? != 0,+ status: row.get(10)?,+ created_at: row.get(11)?,+ updated_at: row.get(12)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(servers)+}++pub fn delete_mcp_server(id: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute("DELETE FROM mcp_servers WHERE id = ?1", params![id])?;++ Ok(())+}++// ============================================================================+// Backtesting Operations+// ============================================================================++pub fn save_backtesting_provider(provider: &BacktestingProvider) -> Result<OperationResult> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT OR REPLACE INTO backtesting_providers+ (id, name, adapter_type, config, enabled, is_active, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, CURRENT_TIMESTAMP)",+ params![+ provider.id,+ provider.name,+ provider.adapter_type,+ provider.config,+ if provider.enabled { 1 } else { 0 },+ if provider.is_active { 1 } else { 0 },+ ],+ )?;++ Ok(OperationResult {+ success: true,+ message: "Backtesting provider saved successfully".to_string(),+ })+}++pub fn get_backtesting_providers() -> Result<Vec<BacktestingProvider>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, name, adapter_type, config, enabled, is_active, created_at, updated_at+ FROM backtesting_providers ORDER BY name"+ )?;++ let providers = stmt+ .query_map([], |row| {+ Ok(BacktestingProvider {+ id: row.get(0)?,+ name: row.get(1)?,+ adapter_type: row.get(2)?,+ config: row.get(3)?,+ enabled: row.get::<_, i32>(4)? != 0,+ is_active: row.get::<_, i32>(5)? != 0,+ created_at: row.get(6)?,+ updated_at: row.get(7)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(providers)+}++pub fn save_backtesting_strategy(strategy: &BacktestingStrategy) -> Result<OperationResult> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT OR REPLACE INTO backtesting_strategies+ (id, name, description, version, author, provider_type, strategy_type, strategy_definition, tags, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, CURRENT_TIMESTAMP)",+ params![+ strategy.id,+ strategy.name,+ strategy.description,+ strategy.version,+ strategy.author,+ strategy.provider_type,+ strategy.strategy_type,+ strategy.strategy_definition,+ strategy.tags,+ ],+ )?;++ Ok(OperationResult {+ success: true,+ message: "Backtesting strategy saved successfully".to_string(),+ })+}++pub fn get_backtesting_strategies() -> Result<Vec<BacktestingStrategy>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, name, description, version, author, provider_type, strategy_type, strategy_definition, tags, created_at, updated_at+ FROM backtesting_strategies ORDER BY name"+ )?;++ let strategies = stmt+ .query_map([], |row| {+ Ok(BacktestingStrategy {+ id: row.get(0)?,+ name: row.get(1)?,+ description: row.get(2)?,+ version: row.get(3)?,+ author: row.get(4)?,+ provider_type: row.get(5)?,+ strategy_type: row.get(6)?,+ strategy_definition: row.get(7)?,+ tags: row.get(8)?,+ created_at: row.get(9)?,+ updated_at: row.get(10)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(strategies)+}++pub fn save_backtest_run(run: &BacktestRun) -> Result<OperationResult> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT INTO backtest_runs+ (id, strategy_id, provider_name, config, results, status, performance_metrics, error_message)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",+ params![+ run.id,+ run.strategy_id,+ run.provider_name,+ run.config,+ run.results,+ run.status,+ run.performance_metrics,+ run.error_message,+ ],+ )?;++ Ok(OperationResult {+ success: true,+ message: "Backtest run saved successfully".to_string(),+ })+}++pub fn get_backtest_runs(limit: Option<i64>) -> Result<Vec<BacktestRun>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let query = if let Some(lim) = limit {+ format!(+ "SELECT id, strategy_id, provider_name, config, results, status, performance_metrics, error_message, created_at, completed_at, duration_seconds+ FROM backtest_runs ORDER BY created_at DESC LIMIT {}",+ lim+ )+ } else {+ "SELECT id, strategy_id, provider_name, config, results, status, performance_metrics, error_message, created_at, completed_at, duration_seconds+ FROM backtest_runs ORDER BY created_at DESC"+ .to_string()+ };++ let mut stmt = conn.prepare(&query)?;+ let runs = stmt+ .query_map([], |row| {+ Ok(BacktestRun {+ id: row.get(0)?,+ strategy_id: row.get(1)?,+ provider_name: row.get(2)?,+ config: row.get(3)?,+ results: row.get(4)?,+ status: row.get(5)?,+ performance_metrics: row.get(6)?,+ error_message: row.get(7)?,+ created_at: row.get(8)?,+ completed_at: row.get(9)?,+ duration_seconds: row.get(10)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(runs)+}++// ============================================================================+// Context Recording Operations+// ============================================================================++pub fn save_recorded_context(context: &RecordedContext) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "INSERT INTO recorded_contexts+ (id, tab_name, data_type, label, raw_data, metadata, data_size, tags)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",+ params![+ context.id,+ context.tab_name,+ context.data_type,+ context.label,+ context.raw_data,+ context.metadata,+ context.data_size,+ context.tags,+ ],+ )?;++ Ok(())+}++pub fn get_recorded_contexts(tab_name: Option<&str>, limit: Option<i64>) -> Result<Vec<RecordedContext>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let query = match (tab_name, limit) {+ (Some(_), Some(lim)) => format!(+ "SELECT id, tab_name, data_type, label, raw_data, metadata, data_size, created_at, tags+ FROM recorded_contexts WHERE tab_name = ?1 ORDER BY created_at DESC LIMIT {}",+ lim+ ),+ (Some(_), None) => {+ "SELECT id, tab_name, data_type, label, raw_data, metadata, data_size, created_at, tags+ FROM recorded_contexts WHERE tab_name = ?1 ORDER BY created_at DESC"+ .to_string()+ }+ (None, Some(lim)) => format!(+ "SELECT id, tab_name, data_type, label, raw_data, metadata, data_size, created_at, tags+ FROM recorded_contexts ORDER BY created_at DESC LIMIT {}",+ lim+ ),+ (None, None) => {+ "SELECT id, tab_name, data_type, label, raw_data, metadata, data_size, created_at, tags+ FROM recorded_contexts ORDER BY created_at DESC"+ .to_string()+ }+ };++ let mut stmt = conn.prepare(&query)?;++ let contexts = if let Some(tab) = tab_name {+ stmt.query_map(params![tab], |row| {+ Ok(RecordedContext {+ id: row.get(0)?,+ tab_name: row.get(1)?,+ data_type: row.get(2)?,+ label: row.get(3)?,+ raw_data: row.get(4)?,+ metadata: row.get(5)?,+ data_size: row.get(6)?,+ created_at: row.get(7)?,+ tags: row.get(8)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?+ } else {+ stmt.query_map([], |row| {+ Ok(RecordedContext {+ id: row.get(0)?,+ tab_name: row.get(1)?,+ data_type: row.get(2)?,+ label: row.get(3)?,+ raw_data: row.get(4)?,+ metadata: row.get(5)?,+ data_size: row.get(6)?,+ created_at: row.get(7)?,+ tags: row.get(8)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?+ };++ Ok(contexts)+}++pub fn delete_recorded_context(id: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute("DELETE FROM recorded_contexts WHERE id = ?1", params![id])?;++ Ok(())+}++// ============================================================================+// Watchlist Operations+// ============================================================================++pub fn create_watchlist(name: &str, description: Option<&str>, color: &str) -> Result<Watchlist> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let id = uuid::Uuid::new_v4().to_string();++ conn.execute(+ "INSERT INTO watchlists (id, name, description, color) VALUES (?1, ?2, ?3, ?4)",+ params![id, name, description, color],+ )?;++ let watchlist = conn.query_row(+ "SELECT id, name, description, color, created_at, updated_at FROM watchlists WHERE id = ?1",+ params![id],+ |row| {+ Ok(Watchlist {+ id: row.get(0)?,+ name: row.get(1)?,+ description: row.get(2)?,+ color: row.get(3)?,+ created_at: row.get(4)?,+ updated_at: row.get(5)?,+ })+ },+ )?;++ Ok(watchlist)+}++pub fn get_watchlists() -> Result<Vec<Watchlist>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, name, description, color, created_at, updated_at+ FROM watchlists ORDER BY created_at DESC"+ )?;++ let watchlists = stmt+ .query_map([], |row| {+ Ok(Watchlist {+ id: row.get(0)?,+ name: row.get(1)?,+ description: row.get(2)?,+ color: row.get(3)?,+ created_at: row.get(4)?,+ updated_at: row.get(5)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(watchlists)+}++pub fn add_watchlist_stock(watchlist_id: &str, symbol: &str, notes: Option<&str>) -> Result<WatchlistStock> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let id = uuid::Uuid::new_v4().to_string();++ conn.execute(+ "INSERT INTO watchlist_stocks (id, watchlist_id, symbol, notes) VALUES (?1, ?2, ?3, ?4)",+ params![id, watchlist_id, symbol.to_uppercase(), notes],+ )?;++ let stock = conn.query_row(+ "SELECT id, watchlist_id, symbol, added_at, notes FROM watchlist_stocks WHERE id = ?1",+ params![id],+ |row| {+ Ok(WatchlistStock {+ id: row.get(0)?,+ watchlist_id: row.get(1)?,+ symbol: row.get(2)?,+ added_at: row.get(3)?,+ notes: row.get(4)?,+ })+ },+ )?;++ Ok(stock)+}++pub fn get_watchlist_stocks(watchlist_id: &str) -> Result<Vec<WatchlistStock>> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let mut stmt = conn.prepare(+ "SELECT id, watchlist_id, symbol, added_at, notes+ FROM watchlist_stocks WHERE watchlist_id = ?1 ORDER BY added_at DESC"+ )?;++ let stocks = stmt+ .query_map(params![watchlist_id], |row| {+ Ok(WatchlistStock {+ id: row.get(0)?,+ watchlist_id: row.get(1)?,+ symbol: row.get(2)?,+ added_at: row.get(3)?,+ notes: row.get(4)?,+ })+ })?+ .collect::<std::result::Result<Vec<_>, _>>()?;++ Ok(stocks)+}++pub fn remove_watchlist_stock(watchlist_id: &str, symbol: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute(+ "DELETE FROM watchlist_stocks WHERE watchlist_id = ?1 AND symbol = ?2",+ params![watchlist_id, symbol.to_uppercase()],+ )?;++ Ok(())+}++pub fn delete_watchlist(watchlist_id: &str) -> Result<()> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ conn.execute("DELETE FROM watchlists WHERE id = ?1", params![watchlist_id])?;++ Ok(())+}diff --git a/fincept-terminal-desktop/src-tauri/src/database/schema.rs b/fincept-terminal-desktop/src-tauri/src/database/schema.rsnew file mode 100644index 000000000..790034f33--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/database/schema.rs@@ -0,0 +1,427 @@+// Database Schema - All table definitions and migrations++use anyhow::Result;+use rusqlite::Connection;++pub fn create_schema(conn: &Connection) -> Result<()> {+ // Execute all schema statements+ conn.execute_batch(+ "+ -- Credentials table+ CREATE TABLE IF NOT EXISTS credentials (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ service_name TEXT NOT NULL UNIQUE,+ username TEXT,+ password TEXT,+ api_key TEXT,+ api_secret TEXT,+ additional_data TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- Settings table+ CREATE TABLE IF NOT EXISTS settings (+ setting_key TEXT PRIMARY KEY,+ setting_value TEXT NOT NULL,+ category TEXT,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- LLM configurations table+ CREATE TABLE IF NOT EXISTS llm_configs (+ provider TEXT PRIMARY KEY,+ api_key TEXT,+ base_url TEXT,+ model TEXT NOT NULL,+ is_active INTEGER DEFAULT 0,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- LLM global settings table+ CREATE TABLE IF NOT EXISTS llm_global_settings (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ temperature REAL DEFAULT 0.7,+ max_tokens INTEGER DEFAULT 2000,+ system_prompt TEXT DEFAULT ''+ );++ INSERT OR IGNORE INTO llm_global_settings (id, temperature, max_tokens, system_prompt)+ VALUES (1, 0.7, 2000, 'You are a helpful AI assistant specialized in financial analysis and market data.');++ -- Chat sessions table+ CREATE TABLE IF NOT EXISTS chat_sessions (+ session_uuid TEXT PRIMARY KEY,+ title TEXT NOT NULL,+ message_count INTEGER DEFAULT 0,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- Chat messages table+ CREATE TABLE IF NOT EXISTS chat_messages (+ id TEXT PRIMARY KEY,+ session_uuid TEXT NOT NULL,+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),+ content TEXT NOT NULL,+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,+ provider TEXT,+ model TEXT,+ tokens_used INTEGER,+ FOREIGN KEY (session_uuid) REFERENCES chat_sessions(session_uuid) ON DELETE CASCADE+ );++ -- Data sources table+ CREATE TABLE IF NOT EXISTS data_sources (+ id TEXT PRIMARY KEY,+ alias TEXT NOT NULL UNIQUE,+ display_name TEXT NOT NULL,+ description TEXT,+ type TEXT NOT NULL CHECK (type IN ('websocket', 'rest_api')),+ provider TEXT NOT NULL,+ category TEXT,+ config TEXT NOT NULL,+ enabled INTEGER DEFAULT 1,+ tags TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- WebSocket provider configs table+ CREATE TABLE IF NOT EXISTS ws_provider_configs (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ provider_name TEXT NOT NULL UNIQUE,+ enabled INTEGER DEFAULT 1,+ api_key TEXT,+ api_secret TEXT,+ endpoint TEXT,+ config_data TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- Watchlists table+ CREATE TABLE IF NOT EXISTS watchlists (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ color TEXT DEFAULT '#FFA500',+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- Watchlist stocks table+ CREATE TABLE IF NOT EXISTS watchlist_stocks (+ id TEXT PRIMARY KEY,+ watchlist_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ added_at TEXT DEFAULT CURRENT_TIMESTAMP,+ notes TEXT,+ FOREIGN KEY (watchlist_id) REFERENCES watchlists(id) ON DELETE CASCADE+ );++ CREATE INDEX IF NOT EXISTS idx_watchlist_stocks ON watchlist_stocks(watchlist_id);++ -- Paper trading portfolios table+ CREATE TABLE IF NOT EXISTS paper_trading_portfolios (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ 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+ );++ -- Paper trading positions table+ CREATE TABLE IF NOT EXISTS paper_trading_positions (+ id TEXT PRIMARY KEY,+ portfolio_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ 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')),+ FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE+ );++ -- Paper trading orders table+ CREATE TABLE IF NOT EXISTS paper_trading_orders (+ id TEXT PRIMARY KEY,+ portfolio_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ side TEXT NOT NULL CHECK (side IN ('buy', 'sell')),+ type TEXT NOT NULL CHECK (type IN ('market', 'limit', 'stop_market', 'stop_limit')),+ quantity REAL NOT NULL,+ price REAL,+ stop_price REAL,+ 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+ );++ -- Paper trading trades table+ CREATE TABLE IF NOT EXISTS paper_trading_trades (+ id TEXT PRIMARY KEY,+ portfolio_id TEXT NOT NULL,+ order_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ side TEXT NOT NULL,+ 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+ );++ -- Indexes for paper trading tables+ CREATE INDEX IF NOT EXISTS idx_paper_positions_portfolio ON paper_trading_positions(portfolio_id);+ CREATE INDEX IF NOT EXISTS idx_paper_positions_status ON paper_trading_positions(status);+ CREATE INDEX IF NOT EXISTS idx_paper_orders_portfolio ON paper_trading_orders(portfolio_id);+ CREATE INDEX IF NOT EXISTS idx_paper_orders_status ON paper_trading_orders(status);+ CREATE INDEX IF NOT EXISTS idx_paper_trades_portfolio ON paper_trading_trades(portfolio_id);++ -- MCP servers table+ CREATE TABLE IF NOT EXISTS mcp_servers (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ command TEXT NOT NULL,+ args TEXT,+ env TEXT,+ category TEXT,+ icon TEXT,+ enabled INTEGER DEFAULT 1,+ auto_start INTEGER DEFAULT 0,+ status TEXT DEFAULT 'stopped',+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- MCP tools table+ CREATE TABLE IF NOT EXISTS mcp_tools (+ id TEXT PRIMARY KEY,+ server_id TEXT NOT NULL,+ name TEXT NOT NULL,+ description TEXT,+ input_schema TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE+ );++ -- MCP tool usage logs table+ CREATE TABLE IF NOT EXISTS mcp_tool_usage_logs (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ server_id TEXT NOT NULL,+ tool_name TEXT NOT NULL,+ args TEXT,+ result TEXT,+ success INTEGER,+ execution_time INTEGER,+ error TEXT,+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- Market data cache table+ CREATE TABLE IF NOT EXISTS market_data_cache (+ symbol TEXT NOT NULL,+ category TEXT NOT NULL,+ quote_data TEXT NOT NULL,+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (symbol, category)+ );++ -- Data source connections table+ CREATE TABLE IF NOT EXISTS data_source_connections (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ type TEXT NOT NULL,+ category TEXT NOT NULL,+ config TEXT NOT NULL,+ status TEXT NOT NULL,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,+ last_tested TEXT,+ error_message TEXT+ );++ -- Forum cache tables+ CREATE TABLE IF NOT EXISTS forum_categories_cache (+ id INTEGER PRIMARY KEY,+ data TEXT NOT NULL,+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ CREATE TABLE IF NOT EXISTS forum_posts_cache (+ cache_key TEXT PRIMARY KEY,+ category_id INTEGER,+ sort_by TEXT,+ data TEXT NOT NULL,+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ CREATE TABLE IF NOT EXISTS forum_stats_cache (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ data TEXT NOT NULL,+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ CREATE TABLE IF NOT EXISTS forum_post_details_cache (+ post_uuid TEXT PRIMARY KEY,+ data TEXT NOT NULL,+ comments_data TEXT NOT NULL,+ cached_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- Context Recording tables+ CREATE TABLE IF NOT EXISTS recorded_contexts (+ id TEXT PRIMARY KEY,+ tab_name TEXT NOT NULL,+ data_type TEXT NOT NULL,+ label TEXT,+ raw_data TEXT NOT NULL,+ metadata TEXT,+ data_size INTEGER,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ tags TEXT+ );++ CREATE INDEX IF NOT EXISTS idx_recorded_contexts_tab ON recorded_contexts(tab_name);+ CREATE INDEX IF NOT EXISTS idx_recorded_contexts_type ON recorded_contexts(data_type);+ CREATE INDEX IF NOT EXISTS idx_recorded_contexts_created ON recorded_contexts(created_at DESC);++ CREATE TABLE IF NOT EXISTS recording_sessions (+ id TEXT PRIMARY KEY,+ tab_name TEXT NOT NULL,+ is_active INTEGER DEFAULT 1,+ auto_record INTEGER DEFAULT 0,+ filters TEXT,+ started_at TEXT DEFAULT CURRENT_TIMESTAMP,+ ended_at TEXT+ );++ CREATE TABLE IF NOT EXISTS chat_context_links (+ chat_session_uuid TEXT NOT NULL,+ context_id TEXT NOT NULL,+ added_at TEXT DEFAULT CURRENT_TIMESTAMP,+ is_active INTEGER DEFAULT 1,+ PRIMARY KEY (chat_session_uuid, context_id),+ FOREIGN KEY(chat_session_uuid) REFERENCES chat_sessions(session_uuid) ON DELETE CASCADE,+ FOREIGN KEY(context_id) REFERENCES recorded_contexts(id) ON DELETE CASCADE+ );++ CREATE TABLE IF NOT EXISTS report_templates (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ template_data TEXT NOT NULL,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- Backtesting providers table+ CREATE TABLE IF NOT EXISTS backtesting_providers (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL UNIQUE,+ adapter_type TEXT NOT NULL,+ config TEXT NOT NULL,+ enabled INTEGER DEFAULT 1,+ is_active INTEGER DEFAULT 0,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ -- Backtesting strategies table+ CREATE TABLE IF NOT EXISTS backtesting_strategies (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ version TEXT DEFAULT '1.0.0',+ author TEXT,+ provider_type TEXT NOT NULL,+ strategy_type TEXT NOT NULL CHECK (strategy_type IN ('code', 'visual', 'template')),+ strategy_definition TEXT NOT NULL,+ tags TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ );++ CREATE INDEX IF NOT EXISTS idx_strategies_provider ON backtesting_strategies(provider_type);+ CREATE INDEX IF NOT EXISTS idx_strategies_type ON backtesting_strategies(strategy_type);++ -- Backtest runs table+ CREATE TABLE IF NOT EXISTS backtest_runs (+ id TEXT PRIMARY KEY,+ strategy_id TEXT,+ provider_name TEXT NOT NULL,+ config TEXT NOT NULL,+ results TEXT,+ status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'running', 'cancelled')),+ performance_metrics TEXT,+ error_message TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ completed_at TEXT,+ duration_seconds INTEGER,+ FOREIGN KEY(strategy_id) REFERENCES backtesting_strategies(id) ON DELETE SET NULL+ );++ CREATE INDEX IF NOT EXISTS idx_backtest_runs_strategy ON backtest_runs(strategy_id);+ CREATE INDEX IF NOT EXISTS idx_backtest_runs_provider ON backtest_runs(provider_name);+ CREATE INDEX IF NOT EXISTS idx_backtest_runs_status ON backtest_runs(status);+ CREATE INDEX IF NOT EXISTS idx_backtest_runs_created ON backtest_runs(created_at DESC);++ -- Optimization runs table+ CREATE TABLE IF NOT EXISTS optimization_runs (+ id TEXT PRIMARY KEY,+ strategy_id TEXT,+ provider_name TEXT NOT NULL,+ parameter_grid TEXT NOT NULL,+ objective TEXT NOT NULL,+ best_parameters TEXT,+ best_result TEXT,+ all_results TEXT,+ iterations INTEGER,+ status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'running', 'cancelled')),+ error_message TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ completed_at TEXT,+ duration_seconds INTEGER,+ FOREIGN KEY(strategy_id) REFERENCES backtesting_strategies(id) ON DELETE SET NULL+ );++ CREATE INDEX IF NOT EXISTS idx_optimization_runs_strategy ON optimization_runs(strategy_id);+ CREATE INDEX IF NOT EXISTS idx_optimization_runs_provider ON optimization_runs(provider_name);+ CREATE INDEX IF NOT EXISTS idx_optimization_runs_status ON optimization_runs(status);+ ",+ )?;++ Ok(())+}diff --git a/fincept-terminal-desktop/src-tauri/src/database/types.rs b/fincept-terminal-desktop/src-tauri/src/database/types.rsnew file mode 100644index 000000000..2403302d0--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/database/types.rs@@ -0,0 +1,341 @@+// Type definitions for all database entities++use serde::{Deserialize, Serialize};++// ============================================================================+// Common Result Types+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct OperationResult {+ pub success: bool,+ pub message: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct OperationResultWithId {+ pub success: bool,+ pub message: String,+ pub id: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ToggleResult {+ pub success: bool,+ pub message: String,+ pub enabled: bool,+}++// ============================================================================+// Credentials & API Keys+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Credential {+ pub id: Option<i64>,+ pub service_name: String,+ pub username: Option<String>,+ pub password: Option<String>,+ pub api_key: Option<String>,+ pub api_secret: Option<String>,+ pub additional_data: Option<String>,+ pub created_at: Option<String>,+ pub updated_at: Option<String>,+}++// ============================================================================+// Settings+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Setting {+ pub setting_key: String,+ pub setting_value: String,+ pub category: Option<String>,+ pub updated_at: Option<String>,+}++// ============================================================================+// LLM Configuration+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct LLMConfig {+ pub provider: String,+ pub api_key: Option<String>,+ pub base_url: Option<String>,+ pub model: String,+ pub is_active: bool,+ pub created_at: Option<String>,+ pub updated_at: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct LLMGlobalSettings {+ pub temperature: f64,+ pub max_tokens: i64,+ pub system_prompt: String,+}++// ============================================================================+// Chat+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ChatSession {+ pub session_uuid: String,+ pub title: String,+ pub message_count: i64,+ pub created_at: String,+ pub updated_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ChatMessage {+ pub id: String,+ pub session_uuid: String,+ pub role: String,+ pub content: String,+ pub timestamp: String,+ pub provider: Option<String>,+ pub model: Option<String>,+ pub tokens_used: Option<i64>,+}++// ============================================================================+// Data Sources+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DataSource {+ pub id: String,+ pub alias: String,+ pub display_name: String,+ pub description: Option<String>,+ #[serde(rename = "type")]+ pub ds_type: String,+ pub provider: String,+ pub category: Option<String>,+ pub config: String,+ pub enabled: bool,+ pub tags: Option<String>,+ pub created_at: String,+ pub updated_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct WSProviderConfig {+ pub id: i64,+ pub provider_name: String,+ pub enabled: bool,+ pub api_key: Option<String>,+ pub api_secret: Option<String>,+ pub endpoint: Option<String>,+ pub config_data: Option<String>,+ pub created_at: String,+ pub updated_at: String,+}++// ============================================================================+// MCP Servers+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MCPServer {+ pub id: String,+ pub name: String,+ pub description: String,+ pub command: String,+ pub args: String,+ pub env: Option<String>,+ pub category: String,+ pub icon: String,+ pub enabled: bool,+ pub auto_start: bool,+ pub status: String,+ pub created_at: String,+ pub updated_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MCPTool {+ pub id: String,+ pub server_id: String,+ pub name: String,+ pub description: Option<String>,+ pub input_schema: Option<String>,+ pub created_at: String,+}++// ============================================================================+// Context Recorder+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RecordedContext {+ pub id: String,+ pub tab_name: String,+ pub data_type: String,+ pub label: Option<String>,+ pub raw_data: String,+ pub metadata: Option<String>,+ pub data_size: i64,+ pub created_at: String,+ pub tags: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RecordingSession {+ pub id: String,+ pub tab_name: String,+ pub is_active: bool,+ pub auto_record: bool,+ pub filters: Option<String>,+ pub started_at: String,+ pub ended_at: Option<String>,+}++// ============================================================================+// Backtesting+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BacktestingProvider {+ pub id: String,+ pub name: String,+ pub adapter_type: String,+ pub config: String,+ pub enabled: bool,+ pub is_active: bool,+ pub created_at: String,+ pub updated_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BacktestingStrategy {+ pub id: String,+ pub name: String,+ pub description: Option<String>,+ pub version: String,+ pub author: Option<String>,+ pub provider_type: String,+ pub strategy_type: String,+ pub strategy_definition: String,+ pub tags: Option<String>,+ pub created_at: String,+ pub updated_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BacktestRun {+ pub id: String,+ pub strategy_id: Option<String>,+ pub provider_name: String,+ pub config: String,+ pub results: Option<String>,+ pub status: String,+ pub performance_metrics: Option<String>,+ pub error_message: Option<String>,+ pub created_at: String,+ pub completed_at: Option<String>,+ pub duration_seconds: Option<i64>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct OptimizationRun {+ pub id: String,+ pub strategy_id: Option<String>,+ pub provider_name: String,+ pub parameter_grid: String,+ pub objective: String,+ pub best_parameters: Option<String>,+ pub best_result: Option<String>,+ pub all_results: Option<String>,+ pub iterations: Option<i64>,+ pub status: String,+ pub error_message: Option<String>,+ pub created_at: String,+ pub completed_at: Option<String>,+ pub duration_seconds: Option<i64>,+}++// ============================================================================+// Watchlist+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Watchlist {+ pub id: String,+ pub name: String,+ pub description: Option<String>,+ pub color: String,+ pub created_at: String,+ pub updated_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct WatchlistStock {+ pub id: String,+ pub watchlist_id: String,+ pub symbol: String,+ pub added_at: String,+ pub notes: Option<String>,+}++// ============================================================================+// Notes+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Note {+ pub id: Option<i64>,+ pub title: String,+ pub content: String,+ pub category: String,+ pub priority: String,+ pub tags: Option<String>,+ pub tickers: Option<String>,+ pub sentiment: String,+ pub is_favorite: bool,+ pub is_archived: bool,+ pub color_code: String,+ pub attachments: String,+ pub created_at: String,+ pub updated_at: String,+ pub reminder_date: Option<String>,+ pub word_count: i64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct NoteTemplate {+ pub id: Option<i64>,+ pub name: String,+ pub description: String,+ pub content: String,+ pub category: String,+ pub created_at: String,+}++// ============================================================================+// Excel+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ExcelFile {+ pub id: Option<i64>,+ pub file_name: String,+ pub file_path: String,+ pub sheet_count: i64,+ pub last_opened: String,+ pub last_modified: String,+ pub created_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ExcelSnapshot {+ pub id: Option<i64>,+ pub file_id: i64,+ pub snapshot_name: String,+ pub sheet_data: String,+ pub created_at: String,+}diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex 9df11a66a..0dc5bdc45 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -15,6 +15,7 @@ mod data_sources;mod commands;mod utils;mod setup;+mod database;// mod finscript; // TODO: Implement FinScript module// MCP Server Process with communication channels@@ -355,12 +356,17 @@ fn execute_python_script(#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {+ // Initialize high-performance Rust SQLite database+ if let Err(e) = tokio::runtime::Runtime::new().unwrap().block_on(database::initialize()) {+ eprintln!("Failed to initialize database: {}", e);+ }+tauri::Builder::default().plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_http::init()).plugin(tauri_plugin_cors_fetch::init())- .plugin(tauri_plugin_sql::Builder::default().build()).plugin(tauri_plugin_dialog::init())+ .plugin(tauri_plugin_fs::init()).plugin(tauri_plugin_updater::Builder::new().build()).plugin(tauri_plugin_process::init()).manage(MCPState {@@ -1097,7 +1103,82 @@ pub fn run() {commands::alpha_arena::get_alpha_leaderboard,commands::alpha_arena::get_alpha_model_decisions,commands::alpha_arena::stop_alpha_competition,- commands::alpha_arena::run_alpha_cycle+ commands::alpha_arena::run_alpha_cycle,+ // High-Performance Rust SQLite Database Commands+ commands::database::db_save_setting,+ commands::database::db_get_setting,+ commands::database::db_get_all_settings,+ commands::database::db_save_credential,+ commands::database::db_get_credentials,+ commands::database::db_get_credential_by_service,+ commands::database::db_delete_credential,+ commands::database::db_get_llm_configs,+ commands::database::db_save_llm_config,+ commands::database::db_get_llm_global_settings,+ commands::database::db_save_llm_global_settings,+ commands::database::db_create_chat_session,+ commands::database::db_get_chat_sessions,+ commands::database::db_add_chat_message,+ commands::database::db_get_chat_messages,+ commands::database::db_delete_chat_session,+ commands::database::db_save_data_source,+ commands::database::db_get_all_data_sources,+ commands::database::db_delete_data_source,+ commands::database::db_add_mcp_server,+ commands::database::db_get_mcp_servers,+ commands::database::db_delete_mcp_server,+ commands::database::db_save_backtesting_provider,+ commands::database::db_get_backtesting_providers,+ commands::database::db_save_backtesting_strategy,+ commands::database::db_get_backtesting_strategies,+ commands::database::db_save_backtest_run,+ commands::database::db_get_backtest_runs,+ commands::database::db_save_recorded_context,+ commands::database::db_get_recorded_contexts,+ commands::database::db_delete_recorded_context,+ commands::database::db_create_watchlist,+ commands::database::db_get_watchlists,+ commands::database::db_add_watchlist_stock,+ commands::database::db_get_watchlist_stocks,+ commands::database::db_remove_watchlist_stock,+ commands::database::db_delete_watchlist,+ commands::database::db_save_market_data_cache,+ commands::database::db_get_cached_market_data,+ commands::database::db_clear_market_data_cache,+ commands::database::db_create_portfolio,+ commands::database::db_get_portfolio,+ commands::database::db_list_portfolios,+ commands::database::db_update_portfolio_balance,+ commands::database::db_delete_portfolio,+ commands::database::db_create_position,+ commands::database::db_get_position,+ commands::database::db_get_position_by_symbol,+ commands::database::db_get_position_by_symbol_and_side,+ commands::database::db_get_portfolio_positions,+ commands::database::db_update_position,+ commands::database::db_delete_position,+ commands::database::db_create_order,+ commands::database::db_get_order,+ commands::database::db_get_pending_orders,+ commands::database::db_get_portfolio_orders,+ commands::database::db_update_order,+ commands::database::db_delete_order,+ commands::database::db_create_trade,+ commands::database::db_get_trade,+ commands::database::db_get_order_trades,+ commands::database::db_get_portfolio_trades,+ commands::database::db_delete_trade,+ commands::database::db_create_note,+ commands::database::db_get_all_notes,+ commands::database::db_update_note,+ commands::database::db_delete_note,+ commands::database::db_search_notes,+ commands::database::db_get_note_templates,+ commands::database::db_add_or_update_excel_file,+ commands::database::db_get_recent_excel_files,+ commands::database::db_create_excel_snapshot,+ commands::database::db_get_excel_snapshots,+ commands::database::db_delete_excel_snapshot]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/fincept-terminal-desktop/src-tauri/src/setup.rs b/fincept-terminal-desktop/src-tauri/src/setup.rsindex 4c9a29f20..df8561860 100644--- a/fincept-terminal-desktop/src-tauri/src/setup.rs+++ b/fincept-terminal-desktop/src-tauri/src/setup.rs@@ -1,7 +1,7 @@// setup.rs - First-time setup for Python and Bun installationuse serde::{Deserialize, Serialize};use std::path::PathBuf;-use std::process::{Command, Stdio};+use std::process::Command;use tauri::{AppHandle, Emitter, Manager};// Windows-specific imports to hide console windows@@ -35,16 +35,22 @@ const BUN_VERSION: &str = "1.1.0";// Optimized builds (require AVX2 - modern CPUs from ~2013+)const BUN_WINDOWS_X64_URL: &str = "https://github.com/oven-sh/bun/releases/download/bun-v1.1.0/bun-windows-x64.zip";+#[cfg(target_os = "macos")]const BUN_MACOS_X64_URL: &str = "https://github.com/oven-sh/bun/releases/download/bun-v1.1.0/bun-darwin-x64.zip";+#[cfg(target_os = "linux")]const BUN_LINUX_X64_URL: &str = "https://github.com/oven-sh/bun/releases/download/bun-v1.1.0/bun-linux-x64.zip";// Baseline builds (work on all CPUs, slightly slower)const BUN_WINDOWS_X64_BASELINE_URL: &str = "https://github.com/oven-sh/bun/releases/download/bun-v1.1.0/bun-windows-x64-baseline.zip";+#[cfg(target_os = "macos")]const BUN_MACOS_X64_BASELINE_URL: &str = "https://github.com/oven-sh/bun/releases/download/bun-v1.1.0/bun-darwin-x64-baseline.zip";+#[cfg(target_os = "linux")]const BUN_LINUX_X64_BASELINE_URL: &str = "https://github.com/oven-sh/bun/releases/download/bun-v1.1.0/bun-linux-x64-baseline.zip";// ARM builds (always optimized for their architecture)+#[cfg(target_os = "macos")]const BUN_MACOS_ARM_URL: &str = "https://github.com/oven-sh/bun/releases/download/bun-v1.1.0/bun-darwin-aarch64.zip";+#[cfg(target_os = "linux")]const BUN_LINUX_ARM_URL: &str = "https://github.com/oven-sh/bun/releases/download/bun-v1.1.0/bun-linux-aarch64.zip";/// Detect if CPU supports AVX2 (required for optimized Bun builds)diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 49165e928..34b147648 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -44,6 +44,7 @@ import ReportBuilderTab from '@/components/tabs/ReportBuilderTab';import BacktestingTab from '@/components/tabs/BacktestingTabNew';import RecordedContextsManager from '@/components/common/RecordedContextsManager';import AgentConfigTab from '@/components/tabs/AgentConfigTab';+import ExcelTab from '@/components/tabs/ExcelTab';// Dropdown Menu Componentconst DropdownMenu = ({ label, items, onItemClick }: { label: string; items: any[]; onItemClick: (item: any) => void }) => {@@ -537,6 +538,7 @@ function FinxeptTerminalContent() {{ label: 'AI Assistant', shortcut: 'F10', action: () => setActiveTab('chat') },{ label: 'Agent Config', action: () => setActiveTab('agents') },{ label: 'MCP Servers', action: () => setActiveTab('mcp'), separator: true },+ { label: 'Excel Workbook', action: () => setActiveTab('excel') },{ label: 'Node Editor', action: () => setActiveTab('nodes') },{ label: 'Code Editor', action: () => setActiveTab('code') },{ label: 'Data Sources', action: () => setActiveTab('datasources'), separator: true },@@ -979,6 +981,9 @@ function FinxeptTerminalContent() {<TabsContent value="agents" className="h-full m-0 p-0"><AgentConfigTab /></TabsContent>+ <TabsContent value="excel" className="h-full m-0 p-0">+ <ExcelTab />+ </TabsContent></Tabs>)}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx b/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsxindex 9abaedd13..ff24090ea 100644--- a/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx@@ -331,12 +331,13 @@ export default function BacktestingTab() {// Save to databaseawait sqliteService.saveBacktestRun({id: result.id,- strategy_id: undefined,+ strategy_id: '',provider_name: activeProvider,config: JSON.stringify(config),results: JSON.stringify(result),status: result.status,performance_metrics: JSON.stringify(result.performance),+ created_at: new Date().toISOString(),error_message: result.error,});diff --git a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsxindex a3ea2352a..8a3e9cb93 100644--- a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx@@ -351,7 +351,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab// Convert conversation historyconst conversationHistory: APIMessage[] = messages.map(msg => ({- role: msg.role,+ role: (msg.role as 'system' | 'user' | 'assistant'),content: msg.content}));diff --git a/fincept-terminal-desktop/src/components/tabs/ExcelTab.tsx b/fincept-terminal-desktop/src/components/tabs/ExcelTab.tsxnew file mode 100644index 000000000..32c6f59e8--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ExcelTab.tsx@@ -0,0 +1,857 @@+import React, { useState, useEffect, useRef } from 'react';+import Handsontable from 'handsontable';+import 'handsontable/dist/handsontable.full.min.css';+import * as XLSX from 'xlsx';+import { HyperFormula } from 'hyperformula';+import { Upload, Download, Plus, Trash2, Save, FileSpreadsheet, History, Camera, RotateCcw, Clock, FolderOpen, X } from 'lucide-react';+import { open, save } from '@tauri-apps/plugin-dialog';+import { readFile as tauriReadFile, writeFile as tauriWriteFile } from '@tauri-apps/plugin-fs';+import { excelService, ExcelFile, ExcelSnapshot } from '@/services/excelService';++interface SheetData {+ name: string;+ data: any[][];+}++const ExcelTab: React.FC = () => {+ const containerRef = useRef<HTMLDivElement>(null);+ const hotInstanceRef = useRef<Handsontable | null>(null);+ const [sheets, setSheets] = useState<SheetData[]>([+ { name: 'Sheet1', data: Array(100).fill(null).map(() => Array(26).fill('')) }+ ]);+ const [activeSheetIndex, setActiveSheetIndex] = useState(0);+ const [fileName, setFileName] = useState<string>('Untitled.xlsx');+ const [currentFileId, setCurrentFileId] = useState<number | null>(null);+ const [filePath, setFilePath] = useState<string>('');+ const [showHistory, setShowHistory] = useState(false);+ const [showSnapshots, setShowSnapshots] = useState(false);+ const [recentFiles, setRecentFiles] = useState<ExcelFile[]>([]);+ const [snapshots, setSnapshots] = useState<ExcelSnapshot[]>([]);++ // Initialize Handsontable+ useEffect(() => {+ if (containerRef.current && !hotInstanceRef.current) {+ const hyperformulaInstance = HyperFormula.buildEmpty({+ licenseKey: 'internal-use-in-handsontable',+ });++ hotInstanceRef.current = new Handsontable(containerRef.current, {+ data: sheets[activeSheetIndex].data,+ colHeaders: true,+ rowHeaders: true,+ width: '100%',+ height: '100%',+ licenseKey: 'non-commercial-and-evaluation',+ formulas: {+ engine: hyperformulaInstance,+ },+ contextMenu: true,+ manualColumnResize: true,+ manualRowResize: true,+ filters: true,+ dropdownMenu: true,+ autoWrapRow: true,+ autoWrapCol: true,+ stretchH: 'all',+ className: 'htDark',+ cell: [],+ cells: function () {+ return {+ className: 'excel-cell'+ };+ }+ });+ }++ return () => {+ if (hotInstanceRef.current) {+ hotInstanceRef.current.destroy();+ hotInstanceRef.current = null;+ }+ };+ }, []);++ // Update table when active sheet changes+ useEffect(() => {+ if (hotInstanceRef.current) {+ hotInstanceRef.current.loadData(sheets[activeSheetIndex].data);+ }+ }, [activeSheetIndex, sheets]);++ // Save current sheet data before switching+ const saveCurrentSheetData = () => {+ if (hotInstanceRef.current) {+ const data = hotInstanceRef.current.getData();+ setSheets(prev => {+ const updated = [...prev];+ updated[activeSheetIndex] = { ...updated[activeSheetIndex], data };+ return updated;+ });+ }+ };++ // Import Excel file+ const handleImport = async () => {+ try {+ const selected = await open({+ multiple: false,+ filters: [{+ name: 'Spreadsheet Files',+ extensions: ['xlsx', 'xls', 'xlsm', 'xlsb', 'csv', 'tsv', 'ods']+ }]+ });++ if (selected) {+ const filePath = typeof selected === 'string' ? selected : selected;+ const fileData = await tauriReadFile(filePath);+ const workbook = XLSX.read(fileData, { type: 'array' });++ const newSheets: SheetData[] = workbook.SheetNames.map(sheetName => {+ const worksheet = workbook.Sheets[sheetName];+ const data = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' }) as any[][];++ // Ensure minimum size+ const minRows = 100;+ const minCols = 26;+ while (data.length < minRows) {+ data.push(Array(minCols).fill(''));+ }+ data.forEach(row => {+ while (row.length < minCols) {+ row.push('');+ }+ });++ return { name: sheetName, data };+ });++ setSheets(newSheets);+ setActiveSheetIndex(0);+ const fName = filePath.split(/[\\/]/).pop() || 'Untitled.xlsx';+ setFileName(fName);+ setFilePath(filePath);++ // Save to history+ const fileId = await excelService.addOrUpdateFile({+ file_name: fName,+ file_path: filePath,+ sheet_count: newSheets.length,+ last_opened: new Date().toISOString(),+ last_modified: new Date().toISOString(),+ created_at: new Date().toISOString()+ });+ setCurrentFileId(fileId);+ }+ } catch (error) {+ console.error('Error importing Excel file:', error);+ alert('Failed to import Excel file');+ }+ };++ // Export Excel file+ const handleExport = async () => {+ try {+ saveCurrentSheetData();++ const filePath = await save({+ filters: [{+ name: 'Excel Files',+ extensions: ['xlsx']+ }],+ defaultPath: fileName+ });++ if (filePath) {+ const workbook = XLSX.utils.book_new();++ sheets.forEach(sheet => {+ const worksheet = XLSX.utils.aoa_to_sheet(sheet.data);+ XLSX.utils.book_append_sheet(workbook, worksheet, sheet.name);+ });++ const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });+ await tauriWriteFile(filePath, new Uint8Array(excelBuffer));++ setFileName(filePath.split(/[\\/]/).pop() || 'Untitled.xlsx');+ alert('Excel file exported successfully!');+ }+ } catch (error) {+ console.error('Error exporting Excel file:', error);+ alert('Failed to export Excel file');+ }+ };++ // Add new sheet+ const handleAddSheet = () => {+ const newSheetName = `Sheet${sheets.length + 1}`;+ setSheets(prev => [+ ...prev,+ { name: newSheetName, data: Array(100).fill(null).map(() => Array(26).fill('')) }+ ]);+ setActiveSheetIndex(sheets.length);+ };++ // Delete sheet+ const handleDeleteSheet = () => {+ if (sheets.length === 1) {+ alert('Cannot delete the last sheet');+ return;+ }++ if (confirm(`Delete "${sheets[activeSheetIndex].name}"?`)) {+ setSheets(prev => prev.filter((_, idx) => idx !== activeSheetIndex));+ setActiveSheetIndex(Math.max(0, activeSheetIndex - 1));+ }+ };++ // Rename sheet+ const handleRenameSheet = (index: number) => {+ const newName = prompt('Enter new sheet name:', sheets[index].name);+ if (newName && newName.trim()) {+ setSheets(prev => {+ const updated = [...prev];+ updated[index] = { ...updated[index], name: newName.trim() };+ return updated;+ });+ }+ };++ // Load recent files+ const loadRecentFiles = async () => {+ const files = await excelService.getRecentFiles(20);+ setRecentFiles(files);+ };++ // Load snapshots for current file+ const loadSnapshots = async () => {+ if (currentFileId) {+ const snaps = await excelService.getSnapshots(currentFileId);+ setSnapshots(snaps);+ }+ };++ // Create snapshot+ const handleCreateSnapshot = async () => {+ if (!currentFileId) {+ alert('Please save the file first before creating a snapshot');+ return;+ }++ const snapshotName = prompt('Enter snapshot name:', `Restore Point ${new Date().toLocaleString()}`);+ if (!snapshotName) return;++ try {+ saveCurrentSheetData();+ await excelService.createSnapshot(currentFileId, snapshotName, JSON.stringify({ sheets }));+ await loadSnapshots();+ alert('Snapshot created successfully!');+ } catch (error) {+ console.error('Failed to create snapshot:', error);+ alert('Failed to create snapshot');+ }+ };++ // Restore from snapshot+ const handleRestoreSnapshot = async (snapshot: ExcelSnapshot) => {+ if (!confirm(`Restore to: ${snapshot.snapshot_name}?\n\nCurrent changes will be lost.`)) return;++ try {+ const data = JSON.parse(snapshot.sheet_data);+ setSheets(data.sheets);+ setActiveSheetIndex(0);+ alert('Snapshot restored successfully!');+ } catch (error) {+ console.error('Failed to restore snapshot:', error);+ alert('Failed to restore snapshot');+ }+ };++ // Open file from history+ const handleOpenFromHistory = async (file: ExcelFile) => {+ try {+ const fileData = await tauriReadFile(file.file_path);+ const workbook = XLSX.read(fileData, { type: 'array' });++ const newSheets: SheetData[] = workbook.SheetNames.map(sheetName => {+ const worksheet = workbook.Sheets[sheetName];+ const data = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' }) as any[][];++ const minRows = 100;+ const minCols = 26;+ while (data.length < minRows) {+ data.push(Array(minCols).fill(''));+ }+ data.forEach(row => {+ while (row.length < minCols) {+ row.push('');+ }+ });++ return { name: sheetName, data };+ });++ setSheets(newSheets);+ setActiveSheetIndex(0);+ setFileName(file.file_name);+ setFilePath(file.file_path);+ setCurrentFileId(file.id!);+ setShowHistory(false);++ // Update last opened+ await excelService.addOrUpdateFile({+ file_name: file.file_name,+ file_path: file.file_path,+ sheet_count: newSheets.length,+ last_opened: new Date().toISOString(),+ last_modified: file.last_modified,+ created_at: file.created_at+ });+ } catch (error) {+ console.error('Error opening file from history:', error);+ alert('Failed to open file');+ }+ };++ // Update import to save to history+ useEffect(() => {+ if (showHistory) {+ loadRecentFiles();+ }+ }, [showHistory]);++ useEffect(() => {+ if (showSnapshots) {+ loadSnapshots();+ }+ }, [showSnapshots, currentFileId]);++ return (+ <div style={{+ width: '100%',+ height: '100%',+ backgroundColor: '#000000',+ display: 'flex',+ flexDirection: 'column',+ fontFamily: 'Consolas, "Courier New", monospace',+ overflow: 'hidden'+ }}>+ {/* Toolbar */}+ <div style={{+ backgroundColor: '#2d2d2d',+ borderBottom: '1px solid #404040',+ padding: '8px 12px',+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ flexShrink: 0+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ color: '#ea580c',+ fontSize: '11px',+ fontWeight: 'bold',+ marginRight: '12px'+ }}>+ <FileSpreadsheet size={16} />+ <span>EXCEL WORKBOOK</span>+ </div>++ <button+ onClick={handleImport}+ style={{+ backgroundColor: '#404040',+ color: '#fff',+ border: 'none',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#525252'}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = '#404040'}+ >+ <Upload size={14} />+ Import+ </button>++ <button+ onClick={handleExport}+ style={{+ backgroundColor: '#404040',+ color: '#fff',+ border: 'none',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#525252'}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = '#404040'}+ >+ <Download size={14} />+ Export+ </button>++ <div style={{ width: '1px', height: '20px', backgroundColor: '#525252' }}></div>++ <button+ onClick={() => saveCurrentSheetData()}+ style={{+ backgroundColor: '#404040',+ color: '#fff',+ border: 'none',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#525252'}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = '#404040'}+ >+ <Save size={14} />+ Save Sheet+ </button>++ <div style={{ width: '1px', height: '20px', backgroundColor: '#525252' }}></div>++ <button+ onClick={() => setShowHistory(!showHistory)}+ style={{+ backgroundColor: showHistory ? '#ea580c' : '#404040',+ color: '#fff',+ border: 'none',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ onMouseEnter={(e) => { if (!showHistory) e.currentTarget.style.backgroundColor = '#525252' }}+ onMouseLeave={(e) => { if (!showHistory) e.currentTarget.style.backgroundColor = '#404040' }}+ >+ <FolderOpen size={14} />+ History+ </button>++ <button+ onClick={handleCreateSnapshot}+ style={{+ backgroundColor: '#404040',+ color: '#fff',+ border: 'none',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#525252'}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = '#404040'}+ title="Create Restore Point"+ >+ <Camera size={14} />+ Snapshot+ </button>++ <button+ onClick={() => setShowSnapshots(!showSnapshots)}+ style={{+ backgroundColor: showSnapshots ? '#ea580c' : '#404040',+ color: '#fff',+ border: 'none',+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ onMouseEnter={(e) => { if (!showSnapshots) e.currentTarget.style.backgroundColor = '#525252' }}+ onMouseLeave={(e) => { if (!showSnapshots) e.currentTarget.style.backgroundColor = '#404040' }}+ title="View and restore from saved snapshots - rollback to any previous state"+ >+ <RotateCcw size={14} />+ Restore+ </button>++ <div style={{ flex: 1 }}></div>++ <span style={{ color: '#a3a3a3', fontSize: '10px' }}>+ {fileName}+ </span>+ </div>++ {/* History Panel */}+ {showHistory && (+ <div style={{+ position: 'absolute',+ top: '60px',+ right: '12px',+ width: '400px',+ maxHeight: '500px',+ backgroundColor: '#1a1a1a',+ border: '1px solid #404040',+ borderRadius: '4px',+ zIndex: 1000,+ overflow: 'auto'+ }}>+ <div style={{+ padding: '12px',+ borderBottom: '1px solid #404040',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', color: '#ea580c', fontWeight: 'bold' }}>+ <History size={16} />+ <span>RECENT FILES</span>+ </div>+ <button onClick={() => setShowHistory(false)} style={{ background: 'none', border: 'none', color: '#a3a3a3', cursor: 'pointer' }}>+ <X size={16} />+ </button>+ </div>+ <div style={{ maxHeight: '400px', overflow: 'auto' }}>+ {recentFiles.length === 0 ? (+ <div style={{ padding: '20px', textAlign: 'center', color: '#666', fontSize: '11px' }}>+ No recent files+ </div>+ ) : (+ recentFiles.map(file => (+ <div+ key={file.id}+ onClick={() => handleOpenFromHistory(file)}+ style={{+ padding: '12px',+ borderBottom: '1px solid #2d2d2d',+ cursor: 'pointer',+ fontSize: '11px'+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#2d2d2d'}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}+ >+ <div style={{ color: '#fff', fontWeight: 600, marginBottom: '4px' }}>{file.file_name}</div>+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>{file.file_path}</div>+ <div style={{ display: 'flex', gap: '12px', color: '#999', fontSize: '9px' }}>+ <span>{file.sheet_count} sheet(s)</span>+ <span>•</span>+ <span>Last opened: {new Date(file.last_opened).toLocaleString()}</span>+ </div>+ </div>+ ))+ )}+ </div>+ </div>+ )}++ {/* Snapshots Panel */}+ {showSnapshots && (+ <div style={{+ position: 'absolute',+ top: '60px',+ right: '12px',+ width: '400px',+ maxHeight: '500px',+ backgroundColor: '#1a1a1a',+ border: '1px solid #404040',+ borderRadius: '4px',+ zIndex: 1000,+ overflow: 'auto'+ }}>+ <div style={{+ padding: '12px',+ borderBottom: '1px solid #404040',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', color: '#ea580c', fontWeight: 'bold' }}>+ <Clock size={16} />+ <span>RESTORE POINTS</span>+ </div>+ <button onClick={() => setShowSnapshots(false)} style={{ background: 'none', border: 'none', color: '#a3a3a3', cursor: 'pointer' }}>+ <X size={16} />+ </button>+ </div>+ <div style={{ maxHeight: '400px', overflow: 'auto' }}>+ {!currentFileId ? (+ <div style={{ padding: '20px', textAlign: 'center', color: '#666', fontSize: '11px' }}>+ Please save the file first+ </div>+ ) : snapshots.length === 0 ? (+ <div style={{ padding: '20px', textAlign: 'center', color: '#666', fontSize: '11px' }}>+ No snapshots created yet+ </div>+ ) : (+ snapshots.map(snapshot => (+ <div+ key={snapshot.id}+ style={{+ padding: '12px',+ borderBottom: '1px solid #2d2d2d',+ fontSize: '11px'+ }}+ >+ <div style={{ color: '#fff', fontWeight: 600, marginBottom: '4px' }}>{snapshot.snapshot_name}</div>+ <div style={{ color: '#999', fontSize: '10px', marginBottom: '8px' }}>+ Created: {new Date(snapshot.created_at).toLocaleString()}+ </div>+ <div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={() => handleRestoreSnapshot(snapshot)}+ style={{+ backgroundColor: '#10b981',+ color: '#fff',+ border: 'none',+ padding: '4px 8px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <RotateCcw size={12} />+ Restore+ </button>+ <button+ onClick={async () => {+ if (confirm('Delete this snapshot?')) {+ await excelService.deleteSnapshot(snapshot.id!);+ await loadSnapshots();+ }+ }}+ style={{+ backgroundColor: '#ef4444',+ color: '#fff',+ border: 'none',+ padding: '4px 8px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Trash2 size={12} />+ Delete+ </button>+ </div>+ </div>+ ))+ )}+ </div>+ </div>+ )}++ {/* Spreadsheet Container */}+ <div style={{+ flex: 1,+ backgroundColor: '#1a1a1a',+ padding: '0',+ overflow: 'hidden',+ position: 'relative'+ }}>+ <div+ ref={containerRef}+ style={{+ width: '100%',+ height: 'calc(100% - 32px)',+ backgroundColor: '#1a1a1a'+ }}+ />++ {/* Sheet Tabs */}+ <div style={{+ position: 'absolute',+ bottom: 0,+ left: 0,+ right: 0,+ height: '32px',+ backgroundColor: '#2d2d2d',+ borderTop: '1px solid #404040',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ padding: '0 8px',+ overflowX: 'auto',+ overflowY: 'hidden'+ }}>+ <button+ onClick={handleAddSheet}+ style={{+ backgroundColor: 'transparent',+ color: '#a3a3a3',+ border: '1px solid #404040',+ padding: '4px 8px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '2px',+ marginRight: '8px'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = '#404040';+ e.currentTarget.style.color = '#fff';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = '#a3a3a3';+ }}+ title="Add Sheet"+ >+ <Plus size={12} />+ </button>++ {sheets.map((sheet, index) => (+ <div+ key={index}+ onClick={() => {+ saveCurrentSheetData();+ setActiveSheetIndex(index);+ }}+ onDoubleClick={() => handleRenameSheet(index)}+ style={{+ backgroundColor: activeSheetIndex === index ? '#ea580c' : '#404040',+ color: activeSheetIndex === index ? '#fff' : '#a3a3a3',+ padding: '4px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '2px',+ whiteSpace: 'nowrap',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ border: activeSheetIndex === index ? '1px solid #ea580c' : '1px solid #525252'+ }}+ onMouseEnter={(e) => {+ if (activeSheetIndex !== index) {+ e.currentTarget.style.backgroundColor = '#525252';+ }+ }}+ onMouseLeave={(e) => {+ if (activeSheetIndex !== index) {+ e.currentTarget.style.backgroundColor = '#404040';+ }+ }}+ >+ <span>{sheet.name}</span>+ {activeSheetIndex === index && sheets.length > 1 && (+ <Trash2+ size={12}+ onClick={(e) => {+ e.stopPropagation();+ handleDeleteSheet();+ }}+ style={{ cursor: 'pointer' }}+ onMouseEnter={(e) => {+ (e.target as SVGElement).style.color = '#ff6b6b';+ }}+ onMouseLeave={(e) => {+ (e.target as SVGElement).style.color = '#fff';+ }}+ />+ )}+ </div>+ ))}+ </div>+ </div>++ {/* Custom CSS for Handsontable dark theme */}+ <style>{`+ .handsontable {+ color: #d4d4d4 !important;+ background: #1a1a1a !important;+ font-family: Consolas, "Courier New", monospace !important;+ font-size: 11px !important;+ }++ .handsontable td {+ background: #1a1a1a !important;+ color: #d4d4d4 !important;+ border-color: #404040 !important;+ }++ .handsontable th {+ background: #2d2d2d !important;+ color: #a3a3a3 !important;+ border-color: #404040 !important;+ }++ .handsontable td.current {+ background: #2d2d2d !important;+ }++ .handsontable td.area {+ background: #3f3f3f !important;+ }++ .handsontable .wtBorder {+ background: #ea580c !important;+ }++ .handsontable .currentRow {+ background: #262626 !important;+ }++ .handsontable .currentCol {+ background: #262626 !important;+ }++ .htContextMenu {+ background: #2d2d2d !important;+ border: 1px solid #404040 !important;+ }++ .htContextMenu .ht_clone_top {+ background: #2d2d2d !important;+ }++ .htContextMenu tbody td {+ background: #2d2d2d !important;+ color: #d4d4d4 !important;+ border-color: #404040 !important;+ }++ .htContextMenu tbody td:hover {+ background: #404040 !important;+ }++ .htDropdownMenu {+ background: #2d2d2d !important;+ border: 1px solid #404040 !important;+ }++ .htDropdownMenu tbody td {+ background: #2d2d2d !important;+ color: #d4d4d4 !important;+ }++ .htDropdownMenu tbody td:hover {+ background: #404040 !important;+ }+ `}</style>+ </div>+ );+};++export default ExcelTab;diff --git a/fincept-terminal-desktop/src/components/tabs/NotesTab.tsx b/fincept-terminal-desktop/src/components/tabs/NotesTab.tsxindex 4fa4fc379..a07735dcf 100644--- a/fincept-terminal-desktop/src/components/tabs/NotesTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/NotesTab.tsx@@ -9,7 +9,7 @@ import {ChevronRight, Copy, Download, Upload, RefreshCw, Maximize2, Minimize2, Bell} from 'lucide-react';import { notesService, Note, NoteTemplate } from '../../services/notesService';-import { noteReminderService } from '../../services/noteReminderService';+import { noteReminderService } from '../../services/noteReminderService.tsx';import { toast } from 'sonner';// Bloomberg Professional Color Palette@@ -105,10 +105,10 @@ export function NotesTab() {}};- window.addEventListener('openNote', handleOpenNote as EventListener);+ window.addEventListener('openNote', handleOpenNote as unknown as EventListener);return () => {- window.removeEventListener('openNote', handleOpenNote as EventListener);+ window.removeEventListener('openNote', handleOpenNote as unknown as EventListener);};}, []);@@ -211,8 +211,8 @@ export function NotesTab() {tags: editTags,tickers: editTickers,sentiment: editSentiment,- is_favorite: 0,- is_archived: 0,+ is_favorite: false,+ is_archived: false,color_code: editColorCode,attachments: '[]',created_at: new Date().toISOString(),@@ -293,7 +293,7 @@ export function NotesTab() {const handleToggleFavorite = async (note: Note) => {try {await notesService.updateNote(note.id!, {- is_favorite: note.is_favorite === 1 ? 0 : 1+ is_favorite: !note.is_favorite});await loadNotes();} catch (error) {@@ -305,7 +305,7 @@ export function NotesTab() {const handleToggleArchive = async (note: Note) => {try {await notesService.updateNote(note.id!, {- is_archived: note.is_archived === 1 ? 0 : 1+ is_archived: !note.is_archived});await loadNotes();await loadStatistics();@@ -1017,7 +1017,7 @@ export function NotesTab() {<span style={{ color: BLOOMBERG.WHITE, fontSize: '11px', fontWeight: 700 }}>{note.title}</span>- {note.is_favorite === 1 && <Star size={12} fill={BLOOMBERG.YELLOW} color={BLOOMBERG.YELLOW} />}+ {note.is_favorite && <Star size={12} fill={BLOOMBERG.YELLOW} color={BLOOMBERG.YELLOW} />}</div><div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}><span style={{@@ -1367,7 +1367,7 @@ export function NotesTab() {padding: '4px 8px',backgroundColor: 'transparent',border: `1px solid ${BLOOMBERG.BORDER}`,- color: selectedNote.is_favorite === 1 ? BLOOMBERG.YELLOW : BLOOMBERG.GRAY,+ color: selectedNote.is_favorite ? BLOOMBERG.YELLOW : BLOOMBERG.GRAY,cursor: 'pointer',fontSize: '10px',display: 'flex',@@ -1375,7 +1375,7 @@ export function NotesTab() {gap: '4px'}}>- <Star size={12} fill={selectedNote.is_favorite === 1 ? BLOOMBERG.YELLOW : 'none'} />+ <Star size={12} fill={selectedNote.is_favorite ? BLOOMBERG.YELLOW : 'none'} /></button><buttononClick={() => startEditing(selectedNote)}@@ -1411,7 +1411,7 @@ export function NotesTab() {}}><Archive size={12} />- {selectedNote.is_archived === 1 ? 'UNARCHIVE' : 'ARCHIVE'}+ {selectedNote.is_archived ? 'UNARCHIVE' : 'ARCHIVE'}</button><buttononClick={() => handleDeleteNote(selectedNote.id!)}diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsxindex 6797d03ef..3979d99af 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsx@@ -48,14 +48,15 @@ export const AlphaArenaChart: React.FC<AlphaArenaChartProps> = ({const cycleMap = new Map<number, any>();snapshots.forEach(snap => {- if (!cycleMap.has(snap.cycle_number)) {- cycleMap.set(snap.cycle_number, {- cycle: snap.cycle_number,+ const cycleNum = snap.cycle_number ?? 0;+ if (!cycleMap.has(cycleNum)) {+ cycleMap.set(cycleNum, {+ cycle: cycleNum,timestamp: snap.timestamp,});}- const cycleData = cycleMap.get(snap.cycle_number)!;+ const cycleData = cycleMap.get(cycleNum)!;cycleData[snap.model_name] = snap.portfolio_value;});diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsxindex fb46a8dff..0848ab00d 100644--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsx+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsx@@ -331,7 +331,7 @@ export const CompetitionDashboard: React.FC<CompetitionDashboardProps> = ({}}><div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px' }}><Calendar size={10} />- Created: {formatDate(comp.created_at)}+ Created: {formatDate(comp.created_at || new Date().toISOString())}</div>{comp.started_at && (<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>diff --git a/fincept-terminal-desktop/src/components/tabs/data-mapping/services/MappingDatabase.ts b/fincept-terminal-desktop/src/components/tabs/data-mapping/services/MappingDatabase.tsindex edf16541b..786993e52 100644--- a/fincept-terminal-desktop/src/components/tabs/data-mapping/services/MappingDatabase.ts+++ b/fincept-terminal-desktop/src/components/tabs/data-mapping/services/MappingDatabase.ts@@ -159,7 +159,7 @@ export class MappingDatabase {await this.ensureInitialized();try {- const result = await sqliteService.select<{ config_json: string }[]>(+ const result = await sqliteService.select<{ config_json: string }>('SELECT config_json FROM data_mappings WHERE id = ?',[id]);@@ -230,7 +230,7 @@ export class MappingDatabase {await this.ensureInitialized();try {- const results = await sqliteService.select<{ config_json: string }[]>(+ const results = await sqliteService.select<{ config_json: string }>('SELECT config_json FROM data_mappings ORDER BY updated_at DESC');@@ -279,7 +279,7 @@ export class MappingDatabase {const paramsHash = this.hashParams(params);const cacheKey = `${mappingId}_${paramsHash}`;- const result = await sqliteService.select<{ response_json: string; expires_at: string }[]>(+ const result = await sqliteService.select<{ response_json: string; expires_at: string }>(`SELECT response_json, expires_at FROM mapping_cacheWHERE cache_key = ? AND expires_at > datetime('now')`,[cacheKey]@@ -369,7 +369,7 @@ export class MappingDatabase {await this.ensureInitialized();try {- const result = await sqliteService.select<{ value: string }[]>(+ const result = await sqliteService.select<{ value: string }>('SELECT value FROM mapping_preferences WHERE key = ?',[key]);diff --git a/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/ArbitrageDetector.tsx b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/ArbitrageDetector.tsxindex 812f9c923..95d22f991 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/ArbitrageDetector.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/ArbitrageDetector.tsx@@ -1,11 +1,31 @@/*** ArbitrageDetector - Real-time arbitrage opportunity detection across exchanges+ * Bloomberg Terminal Style*/import React from 'react';import { Zap, RefreshCw, Loader, TrendingUp, Clock, AlertTriangle, ExternalLink } from 'lucide-react';import { useArbitrageDetection } from '../hooks/useCrossExchange';+// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};+export function ArbitrageDetector() {const { opportunities, isScanning, lastScanTime, scan } = useArbitrageDetection();@@ -26,36 +46,86 @@ export function ArbitrageDetector() {};return (- <div className="bg-gray-900 border border-gray-800 rounded p-6">+ <div style={{+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ height: '100%',+ overflow: 'auto'+ }}>{/* Header */}- <div className="flex items-center justify-between mb-6">- <div className="flex items-center gap-2">- <Zap className="w-5 h-5 text-yellow-500" />- <span className="text-lg font-semibold text-white">Arbitrage Opportunities</span>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '16px',+ paddingBottom: '12px',+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Zap style={{ width: 18, height: 18, color: BLOOMBERG.YELLOW }} />+ <span style={{ fontSize: '13px', fontWeight: 600, color: BLOOMBERG.WHITE, letterSpacing: '0.5px' }}>+ ARBITRAGE OPPORTUNITIES+ </span></div>- <div className="flex items-center gap-3">+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>{lastScanTime && (- <div className="flex items-center gap-1 text-xs text-gray-500">- <Clock className="w-3 h-3" />+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '10px', color: BLOOMBERG.MUTED }}>+ <Clock style={{ width: 12, height: 12 }} />{formatTime(lastScanTime)}</div>)}<buttononClick={scan}disabled={isScanning}- className="px-3 py-1 text-xs text-yellow-400 hover:text-yellow-300 border border-yellow-500/30 hover:border-yellow-400/50 rounded transition flex items-center gap-1 disabled:opacity-50 disabled:cursor-not-allowed"+ style={{+ padding: '6px 12px',+ fontSize: '10px',+ color: isScanning ? BLOOMBERG.MUTED : BLOOMBERG.YELLOW,+ backgroundColor: 'transparent',+ border: `1px solid ${isScanning ? BLOOMBERG.BORDER : BLOOMBERG.BORDER}`,+ borderRadius: '2px',+ cursor: isScanning ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: isScanning ? 0.5 : 1,+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ if (!isScanning) {+ e.currentTarget.style.borderColor = BLOOMBERG.YELLOW;+ e.currentTarget.style.backgroundColor = `${BLOOMBERG.YELLOW}15`;+ }+ }}+ onMouseLeave={(e) => {+ if (!isScanning) {+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ e.currentTarget.style.backgroundColor = 'transparent';+ }+ }}>- <RefreshCw className={`w-3 h-3 ${isScanning ? 'animate-spin' : ''}`} />- {isScanning ? 'Scanning...' : 'Scan'}+ <RefreshCw style={{ width: 12, height: 12, animation: isScanning ? 'spin 1s linear infinite' : 'none' }} />+ {isScanning ? 'SCANNING...' : 'SCAN'}</button></div></div>{/* Risk Warning */}- <div className="mb-6 p-3 bg-yellow-500/10 border border-yellow-500/20 rounded flex items-start gap-2">- <AlertTriangle className="w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5" />- <div className="text-xs text-yellow-400">- <strong>Risk Warning:</strong> Arbitrage opportunities include trading fees, withdrawal+ <div style={{+ marginBottom: '16px',+ padding: '10px',+ backgroundColor: `${BLOOMBERG.YELLOW}08`,+ border: `1px solid ${BLOOMBERG.YELLOW}25`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'flex-start',+ gap: '8px'+ }}>+ <AlertTriangle style={{ width: 14, height: 14, color: BLOOMBERG.YELLOW, flexShrink: 0, marginTop: '2px' }} />+ <div style={{ fontSize: '10px', color: BLOOMBERG.YELLOW, lineHeight: '1.5' }}>+ <strong>RISK WARNING:</strong> Arbitrage opportunities include trading fees, withdrawalfees, and execution risk. Always calculate net profit after all costs. Prices can changerapidly.</div>@@ -63,133 +133,266 @@ export function ArbitrageDetector() {{/* Scanning Status */}{isScanning && (- <div className="mb-4 p-3 bg-blue-500/10 border border-blue-500/20 rounded flex items-center gap-2">- <Loader className="w-4 h-4 text-blue-500 animate-spin" />- <span className="text-sm text-blue-400">Scanning for arbitrage opportunities...</span>+ <div style={{+ marginBottom: '12px',+ padding: '10px',+ backgroundColor: `${BLOOMBERG.CYAN}08`,+ border: `1px solid ${BLOOMBERG.CYAN}25`,+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}>+ <Loader style={{ width: 14, height: 14, color: BLOOMBERG.CYAN, animation: 'spin 1s linear infinite' }} />+ <span style={{ fontSize: '11px', color: BLOOMBERG.CYAN }}>SCANNING FOR ARBITRAGE OPPORTUNITIES...</span></div>)}{/* Opportunities List */}- <div className="space-y-3">+ <div style={{ marginBottom: '16px' }}>{opportunities.length === 0 ? (- <div className="text-center py-8 text-gray-500">- <Zap className="w-12 h-12 mx-auto mb-3 text-gray-600" />- <div className="text-sm">No arbitrage opportunities found</div>- <div className="text-xs mt-1">Spread must be > 0.2% to be considered viable</div>+ <div style={{+ textAlign: 'center',+ padding: '40px 0',+ color: BLOOMBERG.MUTED+ }}>+ <Zap style={{ width: 48, height: 48, margin: '0 auto 12px', color: BLOOMBERG.MUTED }} />+ <div style={{ fontSize: '11px', marginBottom: '6px' }}>NO ARBITRAGE OPPORTUNITIES FOUND</div>+ <div style={{ fontSize: '10px' }}>Spread must be > 0.2% to be considered viable</div></div>) : (- opportunities.map((opp, idx) => (- <div- key={idx}- className="p-4 bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-2 border-yellow-500/30 rounded hover:border-yellow-400/50 transition"- >- {/* Opportunity Header */}- <div className="flex items-center justify-between mb-3">- <div className="flex items-center gap-3">- <div className="flex items-center gap-1 text-yellow-500">- <Zap className="w-5 h-5 fill-current" />- <span className="text-lg font-bold text-white">{opp.symbol}</span>- </div>- <div className="px-2 py-0.5 bg-yellow-500/20 border border-yellow-500/30 rounded text-xs text-yellow-400 font-semibold">- {opp.spreadPercent.toFixed(2)}% Spread+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ {opportunities.map((opp, idx) => (+ <div+ key={idx}+ style={{+ padding: '14px',+ background: `linear-gradient(135deg, ${BLOOMBERG.YELLOW}05, ${BLOOMBERG.ORANGE}05)`,+ border: `2px solid ${BLOOMBERG.YELLOW}40`,+ borderRadius: '2px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = `${BLOOMBERG.YELLOW}80`;+ e.currentTarget.style.backgroundColor = BLOOMBERG.HEADER_BG;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = `${BLOOMBERG.YELLOW}40`;+ e.currentTarget.style.background = `linear-gradient(135deg, ${BLOOMBERG.YELLOW}05, ${BLOOMBERG.ORANGE}05)`;+ }}+ >+ {/* Opportunity Header */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '12px'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', color: BLOOMBERG.YELLOW }}>+ <Zap style={{ width: 18, height: 18 }} fill="currentColor" />+ <span style={{ fontSize: '16px', fontWeight: 700, color: BLOOMBERG.WHITE, fontFamily: 'monospace' }}>+ {opp.symbol}+ </span>+ </div>+ <div style={{+ padding: '4px 10px',+ backgroundColor: `${BLOOMBERG.YELLOW}20`,+ border: `1px solid ${BLOOMBERG.YELLOW}40`,+ borderRadius: '2px',+ fontSize: '10px',+ color: BLOOMBERG.YELLOW,+ fontWeight: 700,+ letterSpacing: '0.5px'+ }}>+ {opp.spreadPercent.toFixed(2)}% SPREAD+ </div></div>- </div>- <div className="text-right">- <div className="text-sm text-gray-400">Potential Profit</div>- <div className="text-xl font-bold text-green-500">- ${opp.potentialProfit.toFixed(2)}+ <div style={{ textAlign: 'right' }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '2px' }}>POTENTIAL PROFIT</div>+ <div style={{ fontSize: '18px', fontWeight: 700, color: BLOOMBERG.GREEN, fontFamily: 'monospace' }}>+ ${opp.potentialProfit.toFixed(2)}+ </div></div></div>- </div>- {/* Trade Details */}- <div className="grid grid-cols-2 gap-4 mb-3">- {/* Buy Side */}- <div className="p-3 bg-green-500/10 border border-green-500/20 rounded">- <div className="text-xs text-gray-400 mb-1">BUY ON</div>- <div className="text-sm font-semibold text-white capitalize mb-2">- {opp.buyExchange}+ {/* Trade Details */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '10px' }}>+ {/* Buy Side */}+ <div style={{+ padding: '12px',+ backgroundColor: `${BLOOMBERG.GREEN}10`,+ border: `1px solid ${BLOOMBERG.GREEN}30`,+ borderRadius: '2px'+ }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>+ BUY ON+ </div>+ <div style={{ fontSize: '11px', fontWeight: 600, color: BLOOMBERG.WHITE, marginBottom: '8px', textTransform: 'uppercase' }}>+ {opp.buyExchange}+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <TrendingUp style={{ width: 16, height: 16, color: BLOOMBERG.GREEN }} />+ <span style={{ fontSize: '16px', fontWeight: 700, color: BLOOMBERG.GREEN, fontFamily: 'monospace' }}>+ ${formatPrice(opp.buyPrice)}+ </span>+ </div></div>- <div className="flex items-center gap-2">- <TrendingUp className="w-4 h-4 text-green-500" />- <span className="text-lg font-bold text-green-500">- ${formatPrice(opp.buyPrice)}- </span>++ {/* Sell Side */}+ <div style={{+ padding: '12px',+ backgroundColor: `${BLOOMBERG.RED}10`,+ border: `1px solid ${BLOOMBERG.RED}30`,+ borderRadius: '2px'+ }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>+ SELL ON+ </div>+ <div style={{ fontSize: '11px', fontWeight: 600, color: BLOOMBERG.WHITE, marginBottom: '8px', textTransform: 'uppercase' }}>+ {opp.sellExchange}+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <TrendingUp style={{ width: 16, height: 16, color: BLOOMBERG.RED, transform: 'rotate(180deg)' }} />+ <span style={{ fontSize: '16px', fontWeight: 700, color: BLOOMBERG.RED, fontFamily: 'monospace' }}>+ ${formatPrice(opp.sellPrice)}+ </span>+ </div></div></div>- {/* Sell Side */}- <div className="p-3 bg-red-500/10 border border-red-500/20 rounded">- <div className="text-xs text-gray-400 mb-1">SELL ON</div>- <div className="text-sm font-semibold text-white capitalize mb-2">- {opp.sellExchange}- </div>- <div className="flex items-center gap-2">- <TrendingUp className="w-4 h-4 text-red-500 rotate-180" />- <span className="text-lg font-bold text-red-500">- ${formatPrice(opp.sellPrice)}+ {/* Spread Info */}+ <div style={{+ padding: '8px',+ backgroundColor: `${BLOOMBERG.DARK_BG}80`,+ borderRadius: '2px',+ marginBottom: '10px'+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ fontSize: '10px'+ }}>+ <span style={{ color: BLOOMBERG.GRAY }}>PRICE DIFFERENCE:</span>+ <span style={{ color: BLOOMBERG.WHITE, fontWeight: 600, fontFamily: 'monospace' }}>+ ${opp.spread.toFixed(2)}</span></div></div>- </div>- {/* Spread Info */}- <div className="p-2 bg-black/30 rounded mb-3">- <div className="flex items-center justify-between text-xs">- <span className="text-gray-400">Price Difference:</span>- <span className="text-white font-semibold">${opp.spread.toFixed(2)}</span>+ {/* Action Buttons */}+ <div style={{ display: 'flex', gap: '8px' }}>+ <button style={{+ flex: 1,+ padding: '10px 14px',+ backgroundColor: BLOOMBERG.GREEN,+ color: BLOOMBERG.WHITE,+ fontSize: '11px',+ fontWeight: 700,+ border: 'none',+ borderRadius: '2px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ transition: 'all 0.2s',+ letterSpacing: '0.5px'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = '#00FF7F';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = BLOOMBERG.GREEN;+ }}>+ <TrendingUp style={{ width: 14, height: 14 }} />+ EXECUTE ARBITRAGE+ </button>+ <button style={{+ padding: '10px 14px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ color: BLOOMBERG.WHITE,+ fontSize: '11px',+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '2px',+ cursor: 'pointer',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = BLOOMBERG.CYAN;+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ e.currentTarget.style.backgroundColor = BLOOMBERG.HEADER_BG;+ }}>+ <ExternalLink style={{ width: 14, height: 14 }} />+ </button></div>- </div>-- {/* Action Buttons */}- <div className="flex gap-2">- <button className="flex-1 px-3 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold rounded transition flex items-center justify-center gap-1">- <TrendingUp className="w-4 h-4" />- Execute Arbitrage- </button>- <button className="px-3 py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm rounded transition">- <ExternalLink className="w-4 h-4" />- </button>- </div>- {/* Timestamp */}- <div className="mt-2 text-xs text-gray-500 text-center">- Detected {formatTime(opp.timestamp)}+ {/* Timestamp */}+ <div style={{+ marginTop: '8px',+ fontSize: '9px',+ color: BLOOMBERG.MUTED,+ textAlign: 'center',+ letterSpacing: '0.5px'+ }}>+ DETECTED {formatTime(opp.timestamp)}+ </div></div>- </div>- ))+ ))}+ </div>)}</div>{/* Info Section */}- <div className="mt-6 space-y-2">- <div className="p-3 bg-gray-800/50 border border-gray-700 rounded">- <div className="text-xs font-semibold text-gray-300 mb-2">How It Works</div>- <div className="text-xs text-gray-400 space-y-1">+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ <div style={{+ padding: '10px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '2px'+ }}>+ <div style={{ fontSize: '10px', fontWeight: 600, color: BLOOMBERG.WHITE, marginBottom: '8px', letterSpacing: '0.5px' }}>+ HOW IT WORKS+ </div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, display: 'flex', flexDirection: 'column', gap: '4px' }}><div>- 1. <strong>Buy</strong> the asset on the exchange with the lower price+ 1. <strong style={{ color: BLOOMBERG.WHITE }}>BUY</strong> the asset on the exchange with the lower price</div><div>- 2. <strong>Transfer</strong> the asset to the exchange with the higher price+ 2. <strong style={{ color: BLOOMBERG.WHITE }}>TRANSFER</strong> the asset to the exchange with the higher price</div><div>- 3. <strong>Sell</strong> the asset for profit+ 3. <strong style={{ color: BLOOMBERG.WHITE }}>SELL</strong> the asset for profit</div></div></div>- <div className="p-3 bg-blue-500/10 border border-blue-500/20 rounded">- <div className="text-xs text-blue-400">- <strong>Cost Considerations:</strong> Factor in trading fees (maker/taker), withdrawal+ <div style={{+ padding: '10px',+ backgroundColor: `${BLOOMBERG.CYAN}08`,+ border: `1px solid ${BLOOMBERG.CYAN}25`,+ borderRadius: '2px'+ }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.CYAN, lineHeight: '1.5' }}>+ <strong>COST CONSIDERATIONS:</strong> Factor in trading fees (maker/taker), withdrawalfees, network fees, and execution time. The spread must exceed total costs forprofitable arbitrage.</div></div>- <div className="p-3 bg-purple-500/10 border border-purple-500/20 rounded">- <div className="text-xs text-purple-400">- <strong>Auto-Scan:</strong> Opportunities are automatically scanned every 10 seconds.- Click "Scan" to manually refresh.+ <div style={{+ padding: '10px',+ backgroundColor: `${BLOOMBERG.PURPLE}08`,+ border: `1px solid ${BLOOMBERG.PURPLE}25`,+ borderRadius: '2px'+ }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.PURPLE, lineHeight: '1.5' }}>+ <strong>AUTO-SCAN:</strong> Opportunities are automatically scanned every 10 seconds.+ Click "SCAN" to manually refresh.</div></div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsx b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsxindex 70ebac531..61bf83987 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsx@@ -1,11 +1,31 @@/*** PortfolioAggregator - Unified view of balances across all exchanges+ * Bloomberg Terminal Style*/import React from 'react';import { Wallet, TrendingUp, RefreshCw, Loader, PieChart } from 'lucide-react';import { useCrossExchangePortfolio } from '../hooks/useCrossExchange';+// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};+export function PortfolioAggregator() {const { aggregatedBalances, totalPortfolioValue, isLoading, error, refresh } =useCrossExchangePortfolio();@@ -26,9 +46,19 @@ export function PortfolioAggregator() {if (isLoading) {return (- <div className="bg-gray-900 border border-gray-800 rounded p-6">- <div className="flex items-center justify-center py-8">- <Loader className="w-6 h-6 text-blue-500 animate-spin" />+ <div style={{+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '4px',+ padding: '24px'+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '32px 0'+ }}>+ <Loader style={{ width: 24, height: 24, color: BLOOMBERG.BLUE, animation: 'spin 1s linear infinite' }} /></div></div>);@@ -36,122 +66,254 @@ export function PortfolioAggregator() {if (error) {return (- <div className="bg-gray-900 border border-gray-800 rounded p-6">- <div className="text-center py-8 text-red-500">{error}</div>+ <div style={{+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '4px',+ padding: '24px'+ }}>+ <div style={{+ textAlign: 'center',+ padding: '32px 0',+ color: BLOOMBERG.RED,+ fontSize: '12px'+ }}>+ {error}+ </div></div>);}return (- <div className="bg-gray-900 border border-gray-800 rounded p-6">+ <div style={{+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ height: '100%',+ overflow: 'auto'+ }}>{/* Header */}- <div className="flex items-center justify-between mb-6">- <div className="flex items-center gap-2">- <PieChart className="w-5 h-5 text-blue-500" />- <span className="text-lg font-semibold text-white">Cross-Exchange Portfolio</span>- </div>- <div className="flex items-center gap-3">- <button- onClick={refresh}- className="px-3 py-1 text-xs text-blue-400 hover:text-blue-300 border border-blue-500/30 hover:border-blue-400/50 rounded transition flex items-center gap-1"- >- <RefreshCw className="w-3 h-3" />- Refresh- </button>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '16px',+ paddingBottom: '12px',+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <PieChart style={{ width: 18, height: 18, color: BLOOMBERG.CYAN }} />+ <span style={{ fontSize: '13px', fontWeight: 600, color: BLOOMBERG.WHITE, letterSpacing: '0.5px' }}>+ CROSS-EXCHANGE PORTFOLIO+ </span></div>+ <button+ onClick={refresh}+ style={{+ padding: '6px 12px',+ fontSize: '10px',+ color: BLOOMBERG.CYAN,+ backgroundColor: 'transparent',+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '2px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = BLOOMBERG.CYAN;+ e.currentTarget.style.backgroundColor = `${BLOOMBERG.CYAN}15`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ e.currentTarget.style.backgroundColor = 'transparent';+ }}+ >+ <RefreshCw style={{ width: 12, height: 12 }} />+ REFRESH+ </button></div>{/* Total Portfolio Value */}- <div className="mb-6 p-4 bg-gradient-to-r from-blue-500/10 to-purple-500/10 border border-blue-500/20 rounded">- <div className="text-xs text-gray-400 mb-1">Total Portfolio Value</div>- <div className="flex items-center gap-3">- <div className="text-3xl font-bold text-white">${formatCurrency(totalPortfolioValue)}</div>- <div className="flex items-center gap-1 text-green-500 text-sm">- <TrendingUp className="w-4 h-4" />+ <div style={{+ marginBottom: '20px',+ padding: '16px',+ backgroundColor: `${BLOOMBERG.CYAN}08`,+ border: `1px solid ${BLOOMBERG.CYAN}25`,+ borderRadius: '2px'+ }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>+ TOTAL PORTFOLIO VALUE+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <div style={{ fontSize: '24px', fontWeight: 700, color: BLOOMBERG.WHITE, fontFamily: 'monospace' }}>+ ${formatCurrency(totalPortfolioValue)}+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', color: BLOOMBERG.GREEN, fontSize: '11px' }}>+ <TrendingUp style={{ width: 14, height: 14 }} /><span>+2.45%</span></div></div>- <div className="text-xs text-gray-500 mt-1">Across {aggregatedBalances.length} assets</div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.MUTED, marginTop: '6px' }}>+ ACROSS {aggregatedBalances.length} ASSETS+ </div></div>{/* Aggregated Balances */}- <div className="space-y-3">- <div className="text-sm font-semibold text-gray-400 mb-3">Asset Breakdown</div>+ <div>+ <div style={{+ fontSize: '11px',+ fontWeight: 600,+ color: BLOOMBERG.GRAY,+ marginBottom: '12px',+ letterSpacing: '0.5px'+ }}>+ ASSET BREAKDOWN+ </div>{aggregatedBalances.length === 0 ? (- <div className="text-center py-8 text-gray-500">- <Wallet className="w-12 h-12 mx-auto mb-3 text-gray-600" />- <div className="text-sm">No balances found</div>+ <div style={{+ textAlign: 'center',+ padding: '40px 0',+ color: BLOOMBERG.MUTED+ }}>+ <Wallet style={{ width: 48, height: 48, margin: '0 auto 12px', color: BLOOMBERG.MUTED }} />+ <div style={{ fontSize: '11px' }}>NO BALANCES FOUND</div></div>) : (- aggregatedBalances- .sort((a, b) => b.totalUsdValue - a.totalUsdValue)- .map((balance) => (- <div- key={balance.currency}- className="p-4 bg-gray-800/50 border border-gray-700 rounded hover:border-gray-600 transition"- >- {/* Currency Header */}- <div className="flex items-center justify-between mb-3">- <div className="flex items-center gap-3">- <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-500 rounded-full flex items-center justify-center text-white font-bold text-sm">- {balance.currency.substring(0, 2)}- </div>- <div>- <div className="text-white font-semibold">{balance.currency}</div>- <div className="text-xs text-gray-500">- {formatCrypto(balance.totalAmount)} {balance.currency}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>+ {aggregatedBalances+ .sort((a, b) => b.totalUsdValue - a.totalUsdValue)+ .map((balance) => (+ <div+ key={balance.currency}+ style={{+ padding: '12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '2px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = BLOOMBERG.CYAN;+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ e.currentTarget.style.backgroundColor = BLOOMBERG.HEADER_BG;+ }}+ >+ {/* Currency Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '10px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>+ <div style={{+ width: 32,+ height: 32,+ background: `linear-gradient(135deg, ${BLOOMBERG.CYAN}, ${BLOOMBERG.PURPLE})`,+ borderRadius: '50%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: BLOOMBERG.WHITE,+ fontWeight: 700,+ fontSize: '11px',+ fontFamily: 'monospace'+ }}>+ {balance.currency.substring(0, 2)}+ </div>+ <div>+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600, fontSize: '12px', fontFamily: 'monospace' }}>+ {balance.currency}+ </div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, fontFamily: 'monospace' }}>+ {formatCrypto(balance.totalAmount)} {balance.currency}+ </div></div></div>- </div>- <div className="text-right">- <div className="text-white font-semibold">- ${formatCurrency(balance.totalUsdValue)}- </div>- <div className="text-xs text-gray-500">- {((balance.totalUsdValue / totalPortfolioValue) * 100).toFixed(2)}%+ <div style={{ textAlign: 'right' }}>+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600, fontSize: '12px', fontFamily: 'monospace' }}>+ ${formatCurrency(balance.totalUsdValue)}+ </div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY }}>+ {((balance.totalUsdValue / totalPortfolioValue) * 100).toFixed(2)}%+ </div></div></div>- </div>- {/* Exchange Breakdown */}- <div className="space-y-2 pl-13">- {balance.exchanges.map((exch, idx) => (- <div- key={idx}- className="flex items-center justify-between text-xs p-2 bg-black/20 rounded"- >- <div className="flex items-center gap-2">- <span className="px-2 py-0.5 bg-gray-700 rounded text-gray-300 capitalize">- {exch.exchange}- </span>- <span className="text-gray-400">- {formatCrypto(exch.amount)} {balance.currency}+ {/* Exchange Breakdown */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', paddingLeft: '42px' }}>+ {balance.exchanges.map((exch, idx) => (+ <div+ key={idx}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ fontSize: '10px',+ padding: '6px 8px',+ backgroundColor: `${BLOOMBERG.DARK_BG}80`,+ borderRadius: '2px'+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{+ padding: '2px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderRadius: '2px',+ color: BLOOMBERG.GRAY,+ textTransform: 'uppercase',+ fontSize: '9px',+ letterSpacing: '0.5px'+ }}>+ {exch.exchange}+ </span>+ <span style={{ color: BLOOMBERG.GRAY, fontFamily: 'monospace' }}>+ {formatCrypto(exch.amount)} {balance.currency}+ </span>+ </div>+ <span style={{ color: BLOOMBERG.WHITE, fontFamily: 'monospace' }}>+ ${formatCurrency(exch.usdValue)}</span></div>- <span className="text-gray-300">${formatCurrency(exch.usdValue)}</span>- </div>- ))}- </div>+ ))}+ </div>- {/* Progress Bar */}- <div className="mt-3 h-2 bg-gray-700 rounded-full overflow-hidden">- <div- className="h-full bg-gradient-to-r from-blue-500 to-purple-500 transition-all"- style={{- width: `${(balance.totalUsdValue / totalPortfolioValue) * 100}%`,- }}- ></div>+ {/* Progress Bar */}+ <div style={{+ marginTop: '10px',+ height: '4px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderRadius: '2px',+ overflow: 'hidden'+ }}>+ <div+ style={{+ height: '100%',+ background: `linear-gradient(90deg, ${BLOOMBERG.CYAN}, ${BLOOMBERG.PURPLE})`,+ width: `${(balance.totalUsdValue / totalPortfolioValue) * 100}%`,+ transition: 'width 0.3s'+ }}+ />+ </div></div>- </div>- ))+ ))}+ </div>)}</div>{/* Info Note */}- <div className="mt-6 p-3 bg-blue-500/10 border border-blue-500/20 rounded">- <div className="text-xs text-blue-400">- <strong>Note:</strong> This view aggregates balances from all connected exchanges. Values+ <div style={{+ marginTop: '16px',+ padding: '10px',+ backgroundColor: `${BLOOMBERG.CYAN}08`,+ border: `1px solid ${BLOOMBERG.CYAN}25`,+ borderRadius: '2px'+ }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.CYAN, lineHeight: '1.5' }}>+ <strong>NOTE:</strong> This view aggregates balances from all connected exchanges. Valuesare updated every 30 seconds. Exchange-specific details are shown for each asset.</div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/FuturesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/FuturesPanel.tsxindex 1955482e8..c2b4ab8e6 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/FuturesPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/FuturesPanel.tsx@@ -1,11 +1,31 @@/*** FuturesPanel - Kraken futures trading interface+ * Bloomberg Terminal Style*/import React, { useState, useCallback, useEffect } from 'react';import { TrendingUp, Activity, AlertTriangle, ExternalLink, Loader } from 'lucide-react';import { useBrokerContext } from '../../../../../contexts/BrokerContext';+// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};+interface FuturesMarket {symbol: string;baseAsset: string;@@ -26,7 +46,6 @@ export function FuturesPanel() {const [isLoading, setIsLoading] = useState(true);const [error, setError] = useState<string | null>(null);- // Fetch futures markets on mountuseEffect(() => {if (activeBroker === 'kraken') {fetchFuturesMarkets();@@ -37,56 +56,11 @@ export function FuturesPanel() {setIsLoading(true);setError(null);try {- // Mock futures data (in production, fetch from Kraken Futures API)const mockMarkets: FuturesMarket[] = [- {- symbol: 'PF_BTCUSD',- baseAsset: 'BTC',- quoteAsset: 'USD',- price: 43250.5,- change24h: 2.35,- volume24h: 1234567890,- openInterest: 567890000,- fundingRate: 0.0001,- nextFunding: '4h 23m',- maxLeverage: 50,- },- {- symbol: 'PF_ETHUSD',- baseAsset: 'ETH',- quoteAsset: 'USD',- price: 2345.67,- change24h: -1.23,- volume24h: 456789012,- openInterest: 234567000,- fundingRate: 0.00005,- nextFunding: '4h 23m',- maxLeverage: 50,- },- {- symbol: 'PF_SOLUSD',- baseAsset: 'SOL',- quoteAsset: 'USD',- price: 98.45,- change24h: 5.67,- volume24h: 123456789,- openInterest: 45678900,- fundingRate: 0.00015,- nextFunding: '4h 23m',- maxLeverage: 25,- },- {- symbol: 'PF_XRPUSD',- baseAsset: 'XRP',- quoteAsset: 'USD',- price: 0.5234,- change24h: 3.45,- volume24h: 89012345,- openInterest: 23456789,- fundingRate: -0.00002,- nextFunding: '4h 23m',- maxLeverage: 20,- },+ { symbol: 'PF_BTCUSD', baseAsset: 'BTC', quoteAsset: 'USD', price: 43250.5, change24h: 2.35, volume24h: 1234567890, openInterest: 567890000, fundingRate: 0.0001, nextFunding: '4h 23m', maxLeverage: 50 },+ { symbol: 'PF_ETHUSD', baseAsset: 'ETH', quoteAsset: 'USD', price: 2345.67, change24h: -1.23, volume24h: 456789012, openInterest: 234567000, fundingRate: 0.00005, nextFunding: '4h 23m', maxLeverage: 50 },+ { symbol: 'PF_SOLUSD', baseAsset: 'SOL', quoteAsset: 'USD', price: 98.45, change24h: 5.67, volume24h: 123456789, openInterest: 45678900, fundingRate: 0.00015, nextFunding: '4h 23m', maxLeverage: 25 },+ { symbol: 'PF_XRPUSD', baseAsset: 'XRP', quoteAsset: 'USD', price: 0.5234, change24h: 3.45, volume24h: 89012345, openInterest: 23456789, fundingRate: -0.00002, nextFunding: '4h 23m', maxLeverage: 20 },];setFuturesMarkets(mockMarkets);@@ -102,10 +76,7 @@ export function FuturesPanel() {}, [activeAdapter, selectedMarket]);const formatNumber = (num: number, decimals: number = 2): string => {- return num.toLocaleString('en-US', {- minimumFractionDigits: decimals,- maximumFractionDigits: decimals,- });+ return num.toLocaleString('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });};const formatLargeNumber = (num: number): string => {@@ -121,218 +92,182 @@ export function FuturesPanel() {if (isLoading) {return (- <div className="bg-gray-900 border border-gray-800 rounded p-6">- <div className="flex items-center justify-center py-8">- <Loader className="w-6 h-6 text-blue-500 animate-spin" />+ <div style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '4px', padding: '24px' }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px 0' }}>+ <Loader style={{ width: 24, height: 24, color: BLOOMBERG.BLUE, animation: 'spin 1s linear infinite' }} /></div></div>);}return (- <div className="bg-gray-900 border border-gray-800 rounded p-6">+ <div style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '4px', padding: '16px', height: '100%', overflow: 'auto' }}>{/* Header */}- <div className="flex items-center justify-between mb-6">- <div className="flex items-center gap-2">- <Activity className="w-5 h-5 text-purple-500" />- <span className="text-lg font-semibold text-white">Kraken Futures</span>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', paddingBottom: '12px', borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Activity style={{ width: 18, height: 18, color: BLOOMBERG.PURPLE }} />+ <span style={{ fontSize: '13px', fontWeight: 600, color: BLOOMBERG.WHITE, letterSpacing: '0.5px' }}>KRAKEN FUTURES</span></div>- <div className="flex items-center gap-3">- <button- onClick={fetchFuturesMarkets}- className="px-3 py-1 text-xs text-blue-400 hover:text-blue-300 border border-blue-500/30 hover:border-blue-400/50 rounded transition"- >- Refresh+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>+ <button onClick={fetchFuturesMarkets}+ style={{ padding: '6px 12px', fontSize: '10px', color: BLOOMBERG.CYAN, backgroundColor: 'transparent', border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px', cursor: 'pointer', transition: 'all 0.2s' }}+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.CYAN; e.currentTarget.style.backgroundColor = `${BLOOMBERG.CYAN}15`; }}+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.BORDER; e.currentTarget.style.backgroundColor = 'transparent'; }}>+ REFRESH</button>- <a- href="https://futures.kraken.com"- target="_blank"- rel="noopener noreferrer"- className="px-3 py-1 text-xs text-gray-400 hover:text-gray-300 border border-gray-700 hover:border-gray-600 rounded transition flex items-center gap-1"- >- <ExternalLink className="w-3 h-3" />- Kraken Futures+ <a href="https://futures.kraken.com" target="_blank" rel="noopener noreferrer"+ style={{ padding: '6px 12px', fontSize: '10px', color: BLOOMBERG.GRAY, backgroundColor: 'transparent', border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px', textDecoration: 'none', display: 'flex', alignItems: 'center', gap: '6px', transition: 'all 0.2s' }}+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.MUTED; e.currentTarget.style.color = BLOOMBERG.WHITE; }}+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.BORDER; e.currentTarget.style.color = BLOOMBERG.GRAY; }}>+ <ExternalLink style={{ width: 12, height: 12 }} />+ KRAKEN FUTURES</a></div></div>{/* Warning Banner */}- <div className="mb-6 p-3 bg-yellow-500/10 border border-yellow-500/20 rounded flex items-start gap-2">- <AlertTriangle className="w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5" />- <div className="text-xs text-yellow-400">- <strong>Futures Trading Risk Warning:</strong> Futures trading involves high risk and- leverage. Only trade with funds you can afford to lose. Requires separate Kraken Futures- account.+ <div style={{ marginBottom: '16px', padding: '10px', backgroundColor: `${BLOOMBERG.YELLOW}08`, border: `1px solid ${BLOOMBERG.YELLOW}25`, borderRadius: '2px', display: 'flex', alignItems: 'flex-start', gap: '8px' }}>+ <AlertTriangle style={{ width: 14, height: 14, color: BLOOMBERG.YELLOW, flexShrink: 0, marginTop: '2px' }} />+ <div style={{ fontSize: '10px', color: BLOOMBERG.YELLOW, lineHeight: '1.5' }}>+ <strong>FUTURES TRADING RISK WARNING:</strong> Futures trading involves high risk and leverage. Only trade with funds you can afford to lose. Requires separate Kraken Futures account.</div></div>{/* Markets Grid */}{futuresMarkets.length === 0 ? (- <div className="text-center py-8 text-gray-500">- <Activity className="w-12 h-12 mx-auto mb-3 text-gray-600" />- <div className="text-sm">No futures markets available</div>+ <div style={{ textAlign: 'center', padding: '40px 0', color: BLOOMBERG.MUTED }}>+ <Activity style={{ width: 48, height: 48, margin: '0 auto 12px', color: BLOOMBERG.MUTED }} />+ <div style={{ fontSize: '11px' }}>NO FUTURES MARKETS AVAILABLE</div></div>) : (- <div className="space-y-4">+ <>{/* Market Selector */}- <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '8px', marginBottom: '16px' }}>{futuresMarkets.map((market) => (- <button- key={market.symbol}- onClick={() => setSelectedMarket(market)}- className={`p-3 rounded border-2 transition ${- selectedMarket?.symbol === market.symbol- ? 'border-purple-500 bg-purple-500/10'- : 'border-gray-700 bg-gray-800/50 hover:border-gray-600'- }`}- >- <div className="text-left">- <div className="text-white font-semibold mb-1">{market.baseAsset}/USD</div>- <div className="text-sm text-gray-400">${formatNumber(market.price)}</div>- <div- className={`text-xs font-semibold ${- market.change24h >= 0 ? 'text-green-500' : 'text-red-500'- }`}- >- {market.change24h >= 0 ? '+' : ''}- {market.change24h.toFixed(2)}%- </div>+ <div key={market.symbol} onClick={() => setSelectedMarket(market)}+ style={{ padding: '10px', borderRadius: '2px', border: `2px solid ${selectedMarket?.symbol === market.symbol ? BLOOMBERG.PURPLE : BLOOMBERG.BORDER}`, backgroundColor: selectedMarket?.symbol === market.symbol ? `${BLOOMBERG.PURPLE}10` : BLOOMBERG.HEADER_BG, cursor: 'pointer', transition: 'all 0.2s' }}+ onMouseEnter={(e) => { if (selectedMarket?.symbol !== market.symbol) e.currentTarget.style.borderColor = BLOOMBERG.MUTED; }}+ onMouseLeave={(e) => { if (selectedMarket?.symbol !== market.symbol) e.currentTarget.style.borderColor = BLOOMBERG.BORDER; }}>+ <div style={{ marginBottom: '4px', color: BLOOMBERG.WHITE, fontWeight: 700, fontSize: '11px', fontFamily: 'monospace' }}>{market.baseAsset}/USD</div>+ <div style={{ fontSize: '11px', color: BLOOMBERG.GRAY, marginBottom: '2px', fontFamily: 'monospace' }}>${formatNumber(market.price)}</div>+ <div style={{ fontSize: '10px', fontWeight: 700, color: market.change24h >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED }}>+ {market.change24h >= 0 ? '+' : ''}{market.change24h.toFixed(2)}%</div>- </button>+ </div>))}</div>{/* Selected Market Details */}{selectedMarket && (- <div className="border-t border-gray-800 pt-6 space-y-4">+ <div style={{ borderTop: `1px solid ${BLOOMBERG.BORDER}`, paddingTop: '16px' }}>{/* Market Stats */}- <div className="grid grid-cols-2 md:grid-cols-3 gap-4">+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px', marginBottom: '16px' }}>{/* Price */}- <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">- <div className="text-xs text-gray-400 mb-1">Mark Price</div>- <div className="text-2xl font-bold text-white">+ <div style={{ padding: '12px', backgroundColor: BLOOMBERG.HEADER_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>MARK PRICE</div>+ <div style={{ fontSize: '18px', fontWeight: 700, color: BLOOMBERG.WHITE, fontFamily: 'monospace', marginBottom: '4px' }}>${formatNumber(selectedMarket.price)}</div>- <div- className={`text-sm font-semibold ${- selectedMarket.change24h >= 0 ? 'text-green-500' : 'text-red-500'- }`}- >- {selectedMarket.change24h >= 0 ? '+' : ''}- {selectedMarket.change24h.toFixed(2)}% 24h+ <div style={{ fontSize: '11px', fontWeight: 700, color: selectedMarket.change24h >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED }}>+ {selectedMarket.change24h >= 0 ? '+' : ''}{selectedMarket.change24h.toFixed(2)}% 24h</div></div>{/* Volume */}- <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">- <div className="text-xs text-gray-400 mb-1">24h Volume</div>- <div className="text-lg font-bold text-white">+ <div style={{ padding: '12px', backgroundColor: BLOOMBERG.HEADER_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>24H VOLUME</div>+ <div style={{ fontSize: '16px', fontWeight: 700, color: BLOOMBERG.WHITE, fontFamily: 'monospace', marginBottom: '2px' }}>{formatLargeNumber(selectedMarket.volume24h)}</div>- <div className="text-xs text-gray-500">Trading Volume</div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.MUTED }}>TRADING VOLUME</div></div>{/* Open Interest */}- <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">- <div className="text-xs text-gray-400 mb-1">Open Interest</div>- <div className="text-lg font-bold text-white">+ <div style={{ padding: '12px', backgroundColor: BLOOMBERG.HEADER_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>OPEN INTEREST</div>+ <div style={{ fontSize: '16px', fontWeight: 700, color: BLOOMBERG.WHITE, fontFamily: 'monospace', marginBottom: '2px' }}>{formatLargeNumber(selectedMarket.openInterest)}</div>- <div className="text-xs text-gray-500">Total Positions</div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.MUTED }}>TOTAL POSITIONS</div></div>{/* Funding Rate */}- <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">- <div className="text-xs text-gray-400 mb-1">Funding Rate</div>- <div- className={`text-lg font-bold ${- selectedMarket.fundingRate >= 0 ? 'text-green-500' : 'text-red-500'- }`}- >+ <div style={{ padding: '12px', backgroundColor: BLOOMBERG.HEADER_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>FUNDING RATE</div>+ <div style={{ fontSize: '16px', fontWeight: 700, color: selectedMarket.fundingRate >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED, fontFamily: 'monospace', marginBottom: '2px' }}>{(selectedMarket.fundingRate * 100).toFixed(4)}%</div>- <div className="text-xs text-gray-500">Every 8 hours</div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.MUTED }}>EVERY 8 HOURS</div></div>{/* Next Funding */}- <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">- <div className="text-xs text-gray-400 mb-1">Next Funding</div>- <div className="text-lg font-bold text-white">{selectedMarket.nextFunding}</div>- <div className="text-xs text-gray-500">Countdown</div>+ <div style={{ padding: '12px', backgroundColor: BLOOMBERG.HEADER_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>NEXT FUNDING</div>+ <div style={{ fontSize: '16px', fontWeight: 700, color: BLOOMBERG.WHITE, fontFamily: 'monospace', marginBottom: '2px' }}>+ {selectedMarket.nextFunding}+ </div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.MUTED }}>COUNTDOWN</div></div>{/* Max Leverage */}- <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">- <div className="text-xs text-gray-400 mb-1">Max Leverage</div>- <div className="text-lg font-bold text-orange-500">+ <div style={{ padding: '12px', backgroundColor: BLOOMBERG.HEADER_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>MAX LEVERAGE</div>+ <div style={{ fontSize: '16px', fontWeight: 700, color: BLOOMBERG.ORANGE, fontFamily: 'monospace', marginBottom: '2px' }}>{selectedMarket.maxLeverage}x</div>- <div className="text-xs text-gray-500">Available</div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.MUTED }}>AVAILABLE</div></div></div>{/* Contract Details */}- <div className="p-4 bg-blue-500/10 border border-blue-500/20 rounded">- <div className="text-sm font-semibold text-blue-400 mb-2">Contract Details</div>- <div className="grid grid-cols-2 gap-3 text-xs">+ <div style={{ padding: '12px', backgroundColor: `${BLOOMBERG.CYAN}08`, border: `1px solid ${BLOOMBERG.CYAN}25`, borderRadius: '2px', marginBottom: '12px' }}>+ <div style={{ fontSize: '11px', fontWeight: 700, color: BLOOMBERG.CYAN, marginBottom: '8px', letterSpacing: '0.5px' }}>CONTRACT DETAILS</div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', fontSize: '10px' }}><div>- <span className="text-gray-400">Contract Type:</span>- <span className="text-white ml-2">Perpetual</span>+ <span style={{ color: BLOOMBERG.GRAY }}>CONTRACT TYPE:</span>+ <span style={{ color: BLOOMBERG.WHITE, marginLeft: '8px', fontWeight: 600 }}>Perpetual</span></div><div>- <span className="text-gray-400">Settlement:</span>- <span className="text-white ml-2">USD</span>+ <span style={{ color: BLOOMBERG.GRAY }}>SETTLEMENT:</span>+ <span style={{ color: BLOOMBERG.WHITE, marginLeft: '8px', fontWeight: 600 }}>USD</span></div><div>- <span className="text-gray-400">Contract Size:</span>- <span className="text-white ml-2">1 {selectedMarket.baseAsset}</span>+ <span style={{ color: BLOOMBERG.GRAY }}>CONTRACT SIZE:</span>+ <span style={{ color: BLOOMBERG.WHITE, marginLeft: '8px', fontWeight: 600 }}>1 {selectedMarket.baseAsset}</span></div><div>- <span className="text-gray-400">Min Order:</span>- <span className="text-white ml-2">0.0001 {selectedMarket.baseAsset}</span>+ <span style={{ color: BLOOMBERG.GRAY }}>MIN ORDER:</span>+ <span style={{ color: BLOOMBERG.WHITE, marginLeft: '8px', fontWeight: 600 }}>0.0001 {selectedMarket.baseAsset}</span></div></div></div>{/* Trading Info */}- <div className="p-4 bg-gray-800/30 border border-gray-700 rounded">- <div className="text-xs text-gray-400 space-y-2">- <div>- <strong className="text-gray-300">How to trade:</strong> Futures trading on- Kraken requires a separate Kraken Futures account. Visit{' '}- <a- href="https://futures.kraken.com"- target="_blank"- rel="noopener noreferrer"- className="text-blue-400 hover:text-blue-300 underline"- >- futures.kraken.com- </a>{' '}+ <div style={{ padding: '12px', backgroundColor: BLOOMBERG.HEADER_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px', marginBottom: '12px' }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, lineHeight: '1.6' }}>+ <div style={{ marginBottom: '8px' }}>+ <strong style={{ color: BLOOMBERG.WHITE }}>HOW TO TRADE:</strong> Futures trading on Kraken requires a separate Kraken Futures account. Visit{' '}+ <a href="https://futures.kraken.com" target="_blank" rel="noopener noreferrer"+ style={{ color: BLOOMBERG.CYAN, textDecoration: 'underline' }}>futures.kraken.com</a>{' '}to create an account and start trading.</div><div>- <strong className="text-gray-300">API Integration:</strong> To trade futures- directly from this terminal, configure Kraken Futures API credentials in- Settings.+ <strong style={{ color: BLOOMBERG.WHITE }}>API INTEGRATION:</strong> To trade futures directly from this terminal, configure Kraken Futures API credentials in Settings.</div></div></div>{/* Action Button */}- <div className="flex gap-3">- <a- href={`https://futures.kraken.com/trade/${selectedMarket.symbol}`}- target="_blank"- rel="noopener noreferrer"- className="flex-1 px-4 py-3 bg-purple-600 hover:bg-purple-700 text-white font-semibold rounded transition flex items-center justify-center gap-2"- >- <ExternalLink className="w-4 h-4" />- Trade on Kraken Futures- </a>- </div>+ <a href={`https://futures.kraken.com/trade/${selectedMarket.symbol}`} target="_blank" rel="noopener noreferrer"+ style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', padding: '12px 16px', backgroundColor: BLOOMBERG.PURPLE, color: BLOOMBERG.WHITE, fontSize: '11px', fontWeight: 700, border: 'none', borderRadius: '2px', textDecoration: 'none', transition: 'all 0.2s', letterSpacing: '0.5px' }}+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = '#B565FF'; }}+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = BLOOMBERG.PURPLE; }}>+ <ExternalLink style={{ width: 14, height: 14 }} />+ TRADE ON KRAKEN FUTURES+ </a></div>)}- </div>+ </>)}</div>);diff --git a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/StakingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/StakingPanel.tsxindex f8bc3d232..e26f5adbd 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/StakingPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/StakingPanel.tsx@@ -1,11 +1,31 @@/*** StakingPanel - Kraken staking management interface+ * Bloomberg Terminal Style*/import React, { useState, useCallback, useEffect } from 'react';import { DollarSign, TrendingUp, Clock, AlertCircle, CheckCircle, Loader } from 'lucide-react';import { useBrokerContext } from '../../../../../contexts/BrokerContext';+// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};+interface StakingAsset {asset: string;balance: number;@@ -36,7 +56,6 @@ export function StakingPanel() {const [error, setError] = useState<string | null>(null);const [success, setSuccess] = useState<string | null>(null);- // Fetch staking assets on mountuseEffect(() => {if (activeBroker === 'kraken') {fetchStakingAssets();@@ -52,57 +71,15 @@ export function StakingPanel() {setIsLoading(true);setError(null);try {- // Fetch balanceconst balance = await activeAdapter.fetchBalance();- const balances = balance as any; // Type assertion for dynamic currency access+ const balances = balance as any;- // Mock staking data (in production, fetch from Kraken API)const stakableAssets: StakingAsset[] = [- {- asset: 'ETH',- balance: balances['ETH']?.total || 0,- stakedBalance: 0,- availableBalance: balances['ETH']?.free || 0,- apy: 4.5,- lockPeriod: 'Flexible',- method: 'ETH2.S',- },- {- asset: 'DOT',- balance: balances['DOT']?.total || 0,- stakedBalance: 0,- availableBalance: balances['DOT']?.free || 0,- apy: 12.0,- lockPeriod: '28 days',- method: 'DOT.S',- },- {- asset: 'SOL',- balance: balances['SOL']?.total || 0,- stakedBalance: 0,- availableBalance: balances['SOL']?.free || 0,- apy: 6.5,- lockPeriod: '2 days',- method: 'SOL.S',- },- {- asset: 'ADA',- balance: balances['ADA']?.total || 0,- stakedBalance: 0,- availableBalance: balances['ADA']?.free || 0,- apy: 5.0,- lockPeriod: 'Flexible',- method: 'ADA.S',- },- {- asset: 'MATIC',- balance: balances['MATIC']?.total || 0,- stakedBalance: 0,- availableBalance: balances['MATIC']?.free || 0,- apy: 8.0,- lockPeriod: '3 days',- method: 'MATIC.S',- },+ { asset: 'ETH', balance: balances['ETH']?.total || 0, stakedBalance: 0, availableBalance: balances['ETH']?.free || 0, apy: 4.5, lockPeriod: 'Flexible', method: 'ETH2.S' },+ { asset: 'DOT', balance: balances['DOT']?.total || 0, stakedBalance: 0, availableBalance: balances['DOT']?.free || 0, apy: 12.0, lockPeriod: '28 days', method: 'DOT.S' },+ { asset: 'SOL', balance: balances['SOL']?.total || 0, stakedBalance: 0, availableBalance: balances['SOL']?.free || 0, apy: 6.5, lockPeriod: '2 days', method: 'SOL.S' },+ { asset: 'ADA', balance: balances['ADA']?.total || 0, stakedBalance: 0, availableBalance: balances['ADA']?.free || 0, apy: 5.0, lockPeriod: 'Flexible', method: 'ADA.S' },+ { asset: 'MATIC', balance: balances['MATIC']?.total || 0, stakedBalance: 0, availableBalance: balances['MATIC']?.free || 0, apy: 8.0, lockPeriod: '3 days', method: 'MATIC.S' },];setStakingAssets(stakableAssets.filter(a => a.balance > 0 || a.stakedBalance > 0));@@ -120,17 +97,9 @@ export function StakingPanel() {setError(null);setSuccess(null);- // Set available staking methods for selected assetconst assetData = stakingAssets.find(a => a.asset === asset);if (assetData) {- setStakingMethods([- {- method: assetData.method,- apy: assetData.apy,- lockPeriod: assetData.lockPeriod,- minAmount: 0.01,- },- ]);+ setStakingMethods([{ method: assetData.method, apy: assetData.apy, lockPeriod: assetData.lockPeriod, minAmount: 0.01 }]);setSelectedMethod(assetData.method);}};@@ -152,16 +121,11 @@ export function StakingPanel() {setSuccess(null);try {- // Call Kraken adapter's stakeAsset methodif (typeof (activeAdapter as any).stakeAsset === 'function') {await (activeAdapter as any).stakeAsset(selectedAsset, parseFloat(amount), selectedMethod);setSuccess(`Successfully staked ${amount} ${selectedAsset}`);setAmount('');-- // Refresh staking assets after 2 seconds- setTimeout(() => {- fetchStakingAssets();- }, 2000);+ setTimeout(() => fetchStakingAssets(), 2000);} else {setError('Staking not supported by current adapter');}@@ -190,16 +154,11 @@ export function StakingPanel() {setSuccess(null);try {- // Call Kraken adapter's unstakeAsset methodif (typeof (activeAdapter as any).unstakeAsset === 'function') {await (activeAdapter as any).unstakeAsset(selectedAsset, parseFloat(amount));setSuccess(`Successfully unstaked ${amount} ${selectedAsset}`);setAmount('');-- // Refresh staking assets after 2 seconds- setTimeout(() => {- fetchStakingAssets();- }, 2000);+ setTimeout(() => fetchStakingAssets(), 2000);} else {setError('Unstaking not supported by current adapter');}@@ -226,188 +185,127 @@ export function StakingPanel() {if (isLoading) {return (- <div className="bg-gray-900 border border-gray-800 rounded p-6">- <div className="flex items-center justify-center py-8">- <Loader className="w-6 h-6 text-blue-500 animate-spin" />+ <div style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '4px', padding: '24px' }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px 0' }}>+ <Loader style={{ width: 24, height: 24, color: BLOOMBERG.BLUE, animation: 'spin 1s linear infinite' }} /></div></div>);}return (- <div className="bg-gray-900 border border-gray-800 rounded p-6">+ <div style={{ backgroundColor: BLOOMBERG.PANEL_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '4px', padding: '16px', height: '100%', overflow: 'auto' }}>{/* Header */}- <div className="flex items-center justify-between mb-6">- <div className="flex items-center gap-2">- <DollarSign className="w-5 h-5 text-green-500" />- <span className="text-lg font-semibold text-white">Kraken Staking</span>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', paddingBottom: '12px', borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <DollarSign style={{ width: 18, height: 18, color: BLOOMBERG.GREEN }} />+ <span style={{ fontSize: '13px', fontWeight: 600, color: BLOOMBERG.WHITE, letterSpacing: '0.5px' }}>KRAKEN STAKING</span></div>- <button- onClick={fetchStakingAssets}- className="px-3 py-1 text-xs text-blue-400 hover:text-blue-300 border border-blue-500/30 hover:border-blue-400/50 rounded transition"- >- Refresh+ <button onClick={fetchStakingAssets} style={{ padding: '6px 12px', fontSize: '10px', color: BLOOMBERG.CYAN, backgroundColor: 'transparent', border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px', cursor: 'pointer', transition: 'all 0.2s' }}+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.CYAN; e.currentTarget.style.backgroundColor = `${BLOOMBERG.CYAN}15`; }}+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.BORDER; e.currentTarget.style.backgroundColor = 'transparent'; }}>+ REFRESH</button></div>- {/* Staking Assets List */}{stakingAssets.length === 0 ? (- <div className="text-center py-8 text-gray-500">- <AlertCircle className="w-12 h-12 mx-auto mb-3 text-gray-600" />- <div className="text-sm">No stakable assets found</div>- <div className="text-xs mt-1">Add funds to your Kraken account to start staking</div>+ <div style={{ textAlign: 'center', padding: '40px 0', color: BLOOMBERG.MUTED }}>+ <AlertCircle style={{ width: 48, height: 48, margin: '0 auto 12px', color: BLOOMBERG.MUTED }} />+ <div style={{ fontSize: '11px', marginBottom: '6px' }}>NO STAKABLE ASSETS FOUND</div>+ <div style={{ fontSize: '10px' }}>Add funds to your Kraken account to start staking</div></div>) : (<>{/* Asset Selection Grid */}- <div className="grid grid-cols-2 gap-3 mb-6">+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '16px' }}>{stakingAssets.map((asset) => (- <button- key={asset.asset}- onClick={() => handleAssetSelect(asset.asset)}- className={`p-4 rounded border-2 transition ${- selectedAsset === asset.asset- ? 'border-blue-500 bg-blue-500/10'- : 'border-gray-700 bg-gray-800/50 hover:border-gray-600'- }`}- >- <div className="flex items-center justify-between mb-2">- <span className="text-white font-semibold">{asset.asset}</span>- <div className="flex items-center gap-1 text-green-500 text-xs">- <TrendingUp className="w-3 h-3" />+ <div key={asset.asset} onClick={() => handleAssetSelect(asset.asset)}+ style={{ padding: '12px', borderRadius: '2px', border: `2px solid ${selectedAsset === asset.asset ? BLOOMBERG.CYAN : BLOOMBERG.BORDER}`, backgroundColor: selectedAsset === asset.asset ? `${BLOOMBERG.CYAN}10` : BLOOMBERG.HEADER_BG, cursor: 'pointer', transition: 'all 0.2s' }}+ onMouseEnter={(e) => { if (selectedAsset !== asset.asset) e.currentTarget.style.borderColor = BLOOMBERG.MUTED; }}+ onMouseLeave={(e) => { if (selectedAsset !== asset.asset) e.currentTarget.style.borderColor = BLOOMBERG.BORDER; }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>+ <span style={{ color: BLOOMBERG.WHITE, fontWeight: 700, fontSize: '12px', fontFamily: 'monospace' }}>{asset.asset}</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', color: BLOOMBERG.GREEN, fontSize: '10px' }}>+ <TrendingUp style={{ width: 12, height: 12 }} />{asset.apy.toFixed(2)}% APY</div></div>- <div className="text-xs text-gray-400">- <div>Balance: {asset.balance.toFixed(8)}</div>- {asset.stakedBalance > 0 && (- <div className="text-green-500">Staked: {asset.stakedBalance.toFixed(8)}</div>- )}+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY }}>+ <div>BALANCE: {asset.balance.toFixed(8)}</div>+ {asset.stakedBalance > 0 && <div style={{ color: BLOOMBERG.GREEN }}>STAKED: {asset.stakedBalance.toFixed(8)}</div>}</div>- <div className="flex items-center gap-1 text-xs text-gray-500 mt-2">- <Clock className="w-3 h-3" />+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '10px', color: BLOOMBERG.MUTED, marginTop: '6px' }}>+ <Clock style={{ width: 10, height: 10 }} />{asset.lockPeriod}</div>- </button>+ </div>))}</div>{/* Staking Form */}{selectedAsset && (- <div className="border-t border-gray-800 pt-6 space-y-4">- {/* Amount Input */}- <div>- <label className="block text-xs text-gray-400 mb-2">Amount to Stake</label>- <input- type="number"- value={amount}- onChange={(e) => setAmount(e.target.value)}- placeholder="0.00"- className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded text-white focus:outline-none focus:border-blue-500"- step="0.00000001"- min="0"- />- {/* Quick Percentage Buttons */}- <div className="flex gap-2 mt-2">+ <div style={{ borderTop: `1px solid ${BLOOMBERG.BORDER}`, paddingTop: '16px' }}>+ <div style={{ marginBottom: '12px' }}>+ <label style={{ display: 'block', fontSize: '10px', color: BLOOMBERG.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>AMOUNT TO STAKE</label>+ <input type="number" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="0.00"+ style={{ width: '100%', padding: '10px 12px', backgroundColor: BLOOMBERG.HEADER_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px', color: BLOOMBERG.WHITE, fontSize: '12px', fontFamily: 'monospace' }} step="0.00000001" min="0" />+ <div style={{ display: 'flex', gap: '6px', marginTop: '8px' }}>{[25, 50, 75, 100].map((pct) => (- <button- key={pct}- onClick={() => setPercentage(pct)}- className="flex-1 px-2 py-1 text-xs bg-gray-800 hover:bg-gray-700 border border-gray-700 rounded transition"- >+ <button key={pct} onClick={() => setPercentage(pct)}+ style={{ flex: 1, padding: '6px', fontSize: '10px', backgroundColor: BLOOMBERG.HEADER_BG, color: BLOOMBERG.GRAY, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px', cursor: 'pointer', transition: 'all 0.2s' }}+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER; e.currentTarget.style.color = BLOOMBERG.WHITE; }}+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = BLOOMBERG.HEADER_BG; e.currentTarget.style.color = BLOOMBERG.GRAY; }}>{pct}%</button>))}</div></div>- {/* Info Display */}{selectedAsset && amount && parseFloat(amount) > 0 && (- <div className="p-3 bg-blue-500/10 border border-blue-500/20 rounded">- <div className="text-xs space-y-1">- <div className="flex justify-between">- <span className="text-gray-400">Estimated yearly earnings:</span>- <span className="text-green-500 font-semibold">- {(- parseFloat(amount) *- (stakingAssets.find((a) => a.asset === selectedAsset)?.apy || 0) /- 100- ).toFixed(8)}{' '}- {selectedAsset}+ <div style={{ padding: '10px', backgroundColor: `${BLOOMBERG.CYAN}08`, border: `1px solid ${BLOOMBERG.CYAN}25`, borderRadius: '2px', marginBottom: '12px' }}>+ <div style={{ fontSize: '10px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>+ <span style={{ color: BLOOMBERG.GRAY }}>ESTIMATED YEARLY EARNINGS:</span>+ <span style={{ color: BLOOMBERG.GREEN, fontWeight: 700, fontFamily: 'monospace' }}>+ {(parseFloat(amount) * (stakingAssets.find((a) => a.asset === selectedAsset)?.apy || 0) / 100).toFixed(8)} {selectedAsset}</span></div>- <div className="flex justify-between">- <span className="text-gray-400">Lock period:</span>- <span className="text-white">- {stakingAssets.find((a) => a.asset === selectedAsset)?.lockPeriod}- </span>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: BLOOMBERG.GRAY }}>LOCK PERIOD:</span>+ <span style={{ color: BLOOMBERG.WHITE, fontWeight: 600 }}>{stakingAssets.find((a) => a.asset === selectedAsset)?.lockPeriod}</span></div></div></div>)}- {/* Error/Success Messages */}{error && (- <div className="p-3 bg-red-500/10 border border-red-500/20 rounded flex items-start gap-2">- <AlertCircle className="w-4 h-4 text-red-500 flex-shrink-0 mt-0.5" />- <span className="text-xs text-red-400">{error}</span>+ <div style={{ padding: '10px', backgroundColor: `${BLOOMBERG.RED}10`, border: `1px solid ${BLOOMBERG.RED}30`, borderRadius: '2px', display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '12px' }}>+ <AlertCircle style={{ width: 14, height: 14, color: BLOOMBERG.RED, flexShrink: 0, marginTop: '2px' }} />+ <span style={{ fontSize: '10px', color: BLOOMBERG.RED }}>{error}</span></div>)}{success && (- <div className="p-3 bg-green-500/10 border border-green-500/20 rounded flex items-start gap-2">- <CheckCircle className="w-4 h-4 text-green-500 flex-shrink-0 mt-0.5" />- <span className="text-xs text-green-400">{success}</span>+ <div style={{ padding: '10px', backgroundColor: `${BLOOMBERG.GREEN}10`, border: `1px solid ${BLOOMBERG.GREEN}30`, borderRadius: '2px', display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '12px' }}>+ <CheckCircle style={{ width: 14, height: 14, color: BLOOMBERG.GREEN, flexShrink: 0, marginTop: '2px' }} />+ <span style={{ fontSize: '10px', color: BLOOMBERG.GREEN }}>{success}</span></div>)}- {/* Action Buttons */}- <div className="flex gap-3">- <button- onClick={handleStake}- disabled={isStaking || !amount || parseFloat(amount) <= 0}- className="flex-1 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-700 disabled:cursor-not-allowed text-white font-semibold rounded transition flex items-center justify-center gap-2"- >- {isStaking ? (- <>- <Loader className="w-4 h-4 animate-spin" />- Staking...- </>- ) : (- <>- <TrendingUp className="w-4 h-4" />- Stake- </>- )}+ <div style={{ display: 'flex', gap: '10px', marginBottom: '12px' }}>+ <button onClick={handleStake} disabled={isStaking || !amount || parseFloat(amount) <= 0}+ style={{ flex: 1, padding: '10px 14px', backgroundColor: isStaking || !amount || parseFloat(amount) <= 0 ? BLOOMBERG.MUTED : BLOOMBERG.GREEN, color: BLOOMBERG.WHITE, fontSize: '11px', fontWeight: 700, border: 'none', borderRadius: '2px', cursor: isStaking || !amount || parseFloat(amount) <= 0 ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', opacity: isStaking || !amount || parseFloat(amount) <= 0 ? 0.5 : 1, transition: 'all 0.2s', letterSpacing: '0.5px' }}>+ {isStaking ? <><Loader style={{ width: 14, height: 14, animation: 'spin 1s linear infinite' }} />STAKING...</> : <><TrendingUp style={{ width: 14, height: 14 }} />STAKE</>}</button>-- <button- onClick={handleUnstake}- disabled={- isUnstaking ||- !amount ||- parseFloat(amount) <= 0 ||- (stakingAssets.find((a) => a.asset === selectedAsset)?.stakedBalance || 0) === 0- }- className="flex-1 px-4 py-3 bg-orange-600 hover:bg-orange-700 disabled:bg-gray-700 disabled:cursor-not-allowed text-white font-semibold rounded transition flex items-center justify-center gap-2"- >- {isUnstaking ? (- <>- <Loader className="w-4 h-4 animate-spin" />- Unstaking...- </>- ) : (- 'Unstake'- )}+ <button onClick={handleUnstake} disabled={isUnstaking || !amount || parseFloat(amount) <= 0 || (stakingAssets.find((a) => a.asset === selectedAsset)?.stakedBalance || 0) === 0}+ style={{ flex: 1, padding: '10px 14px', backgroundColor: isUnstaking || !amount || parseFloat(amount) <= 0 ? BLOOMBERG.MUTED : BLOOMBERG.ORANGE, color: BLOOMBERG.WHITE, fontSize: '11px', fontWeight: 700, border: 'none', borderRadius: '2px', cursor: isUnstaking || !amount || parseFloat(amount) <= 0 ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', opacity: isUnstaking || !amount || parseFloat(amount) <= 0 ? 0.5 : 1, transition: 'all 0.2s', letterSpacing: '0.5px' }}>+ {isUnstaking ? <><Loader style={{ width: 14, height: 14, animation: 'spin 1s linear infinite' }} />UNSTAKING...</> : 'UNSTAKE'}</button></div>- {/* Info Note */}- <div className="p-3 bg-gray-800/50 border border-gray-700 rounded">- <div className="text-xs text-gray-400">- <strong className="text-gray-300">Note:</strong> Staking rewards are- automatically paid out. Unstaking may take up to the lock period to complete.- Check Kraken's terms for each asset's specific staking conditions.+ <div style={{ padding: '10px', backgroundColor: BLOOMBERG.HEADER_BG, border: `1px solid ${BLOOMBERG.BORDER}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY, lineHeight: '1.5' }}>+ <strong style={{ color: BLOOMBERG.WHITE }}>NOTE:</strong> Staking rewards are automatically paid out. Unstaking may take up to the lock period to complete. Check Kraken's terms for each asset's specific staking conditions.</div></div></div>diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.tsindex 05793b54e..2d4299757 100644--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts@@ -1,11 +1,11 @@/*** Paper Trading Database Operations*- * Thin wrapper over SQLite service for paper trading data persistence- * Uses existing paper_trading_* tables from sqliteService+ * Uses Rust SQLite backend via Tauri invoke() commands+ * NO raw SQL - all operations go through Rust backend*/-import { sqliteService } from '../services/sqliteService';+import { invoke } from '@tauri-apps/api/core';import type {PaperTradingPortfolio,PaperTradingPosition,@@ -32,67 +32,40 @@ export class PaperTradingDatabase {marginMode?: 'cross' | 'isolated';leverage?: number;}): Promise<void> {- const sql = `- INSERT INTO paper_trading_portfolios- (id, name, provider, initial_balance, current_balance, currency, margin_mode, leverage)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)- `;-- await sqliteService.execute(sql, [- portfolio.id,- portfolio.name,- portfolio.provider,- portfolio.initialBalance,- portfolio.initialBalance,- portfolio.currency || 'USD',- portfolio.marginMode || 'cross',- portfolio.leverage || 1,- ]);+ await invoke('db_create_portfolio', {+ id: portfolio.id,+ name: portfolio.name,+ provider: portfolio.provider,+ initialBalance: portfolio.initialBalance,+ currency: portfolio.currency || 'USD',+ marginMode: portfolio.marginMode || 'cross',+ leverage: portfolio.leverage || 1,+ });}async getPortfolio(portfolioId: string): Promise<PaperTradingPortfolio | null> {- const sql = `- SELECT id, name, provider, initial_balance, current_balance, currency,- margin_mode, leverage, created_at, updated_at- FROM paper_trading_portfolios- WHERE id = $1- `;-- const result = await sqliteService.select<DBPortfolio[]>(sql, [portfolioId]);-- if (!result || result.length === 0) {+ try {+ const result = await invoke<any>('db_get_portfolio', { id: portfolioId });+ return this.mapDBPortfolio(result);+ } catch (error) {+ console.error('[PaperTradingDatabase] getPortfolio error:', error);return null;}-- const row = result[0];- return this.mapDBPortfolio(row);}async updatePortfolioBalance(portfolioId: string, newBalance: number): Promise<void> {- const sql = `- UPDATE paper_trading_portfolios- SET current_balance = $1, updated_at = CURRENT_TIMESTAMP- WHERE id = $2- `;-- await sqliteService.execute(sql, [newBalance, portfolioId]);+ await invoke('db_update_portfolio_balance', {+ id: portfolioId,+ newBalance+ });}async deletePortfolio(portfolioId: string): Promise<void> {- // Cascading deletes will remove positions, orders, and trades- const sql = `DELETE FROM paper_trading_portfolios WHERE id = $1`;- await sqliteService.execute(sql, [portfolioId]);+ await invoke('db_delete_portfolio', { id: portfolioId });}async listPortfolios(): Promise<PaperTradingPortfolio[]> {- const sql = `- SELECT id, name, provider, initial_balance, current_balance, currency,- margin_mode, leverage, created_at, updated_at- FROM paper_trading_portfolios- ORDER BY created_at DESC- `;-- const result = await sqliteService.select<DBPortfolio[]>(sql, []);+ const result = await invoke<any[]>('db_list_portfolios');return result.map((row: any) => this.mapDBPortfolio(row));}@@ -110,63 +83,40 @@ 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, position_value, leverage, margin_mode, status)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'open')- `;-- await sqliteService.execute(sql, [- position.id,- position.portfolioId,- position.symbol,- position.side,- position.entryPrice,- position.quantity,- positionValue,- position.leverage || 1,- position.marginMode || 'cross',- ]);+ await invoke('db_create_position', {+ id: position.id,+ portfolioId: position.portfolioId,+ symbol: position.symbol,+ side: position.side,+ entryPrice: position.entryPrice,+ quantity: position.quantity,+ leverage: position.leverage || 1,+ marginMode: position.marginMode || 'cross',+ });}async getPosition(positionId: string): 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 id = $1- `;-- const result = await sqliteService.select<DBPosition[]>(sql, [positionId]);-- if (!result || result.length === 0) {+ try {+ const result = await invoke<any>('db_get_position', { id: positionId });+ return this.mapDBPosition(result);+ } catch (error) {+ console.error('[PaperTradingDatabase] getPosition error:', error);return null;}-- return this.mapDBPosition(result[0]);}async getPositionBySymbol(portfolioId: string, symbol: string, 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 status = $3- ORDER BY opened_at DESC- LIMIT 1- `;-- const result = await sqliteService.select<DBPosition[]>(sql, [portfolioId, symbol, status]);-- if (!result || result.length === 0) {+ try {+ const result = await invoke<any | null>('db_get_position_by_symbol', {+ portfolioId,+ symbol,+ status,+ });+ return result ? this.mapDBPosition(result) : null;+ } catch (error) {+ console.error('[PaperTradingDatabase] getPositionBySymbol error:', error);return null;}-- return this.mapDBPosition(result[0]);}async getPositionBySymbolAndSide(@@ -175,44 +125,25 @@ export class PaperTradingDatabase {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) {+ try {+ const result = await invoke<any | null>('db_get_position_by_symbol_and_side', {+ portfolioId,+ symbol,+ side,+ status,+ });+ return result ? this.mapDBPosition(result) : null;+ } catch (error) {+ console.error('[PaperTradingDatabase] getPositionBySymbolAndSide error:', error);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, 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- `;-- const params: any[] = [portfolioId];-- if (status) {- sql += ` AND status = $2`;- params.push(status);- }-- sql += ` ORDER BY opened_at DESC`;-- const result = await sqliteService.select<DBPosition[]>(sql, params);+ const result = await invoke<any[]>('db_get_portfolio_positions', {+ portfolioId,+ status: status || null,+ });return result.map((row: any) => this.mapDBPosition(row));}@@ -226,54 +157,21 @@ export class PaperTradingDatabase {status?: 'open' | 'closed';closedAt?: string | null;}): Promise<void> {- const fields: string[] = [];- const values: any[] = [];- let paramIndex = 1;-- if (updates.quantity !== undefined) {- fields.push(`quantity = $${paramIndex++}`);- values.push(updates.quantity);- }- if (updates.entryPrice !== undefined) {- fields.push(`entry_price = $${paramIndex++}`);- values.push(updates.entryPrice);- }- if (updates.currentPrice !== undefined) {- fields.push(`current_price = $${paramIndex++}`);- values.push(updates.currentPrice);- }- if (updates.unrealizedPnl !== undefined) {- fields.push(`unrealized_pnl = $${paramIndex++}`);- values.push(updates.unrealizedPnl);- }- if (updates.realizedPnl !== undefined) {- fields.push(`realized_pnl = $${paramIndex++}`);- values.push(updates.realizedPnl);- }- if (updates.liquidationPrice !== undefined) {- fields.push(`liquidation_price = $${paramIndex++}`);- values.push(updates.liquidationPrice);- }- if (updates.status !== undefined) {- fields.push(`status = $${paramIndex++}`);- values.push(updates.status);- }- if (updates.closedAt !== undefined) {- fields.push(`closed_at = $${paramIndex++}`);- values.push(updates.closedAt);- }-- if (fields.length === 0) return;-- values.push(positionId);- const sql = `UPDATE paper_trading_positions SET ${fields.join(', ')} WHERE id = $${paramIndex}`;-- await sqliteService.execute(sql, values);+ await invoke('db_update_position', {+ id: positionId,+ quantity: updates.quantity || null,+ entryPrice: updates.entryPrice || null,+ currentPrice: updates.currentPrice || null,+ unrealizedPnl: updates.unrealizedPnl || null,+ realizedPnl: updates.realizedPnl || null,+ liquidationPrice: updates.liquidationPrice !== undefined ? updates.liquidationPrice : null,+ status: updates.status || null,+ closedAt: updates.closedAt !== undefined ? updates.closedAt : null,+ });}async deletePosition(positionId: string): Promise<void> {- const sql = `DELETE FROM paper_trading_positions WHERE id = $1`;- await sqliteService.execute(sql, [positionId]);+ await invoke('db_delete_position', { id: positionId });}// ============================================================================@@ -298,96 +196,40 @@ export class PaperTradingDatabase {leverage?: number;marginMode?: string;}): Promise<void> {- const sql = `- INSERT INTO paper_trading_orders- (id, portfolio_id, symbol, side, type, quantity, price, stop_price, status,- time_in_force, post_only, reduce_only, trailing_percent, trailing_amount,- iceberg_qty, leverage, margin_mode, filled_quantity, created_at, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9, $10, $11, $12, $13, $14, $15, $16, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)- `;-- await sqliteService.execute(sql, [- order.id,- order.portfolioId,- order.symbol,- order.side,- order.type,- order.quantity,- order.price || null,- order.stopPrice || null,- order.timeInForce || 'GTC',- order.postOnly ? 1 : 0,- order.reduceOnly ? 1 : 0,- order.trailingPercent || null,- order.trailingAmount || null,- order.icebergQty || null,- order.leverage || null,- order.marginMode || null,- ]);+ await invoke('db_create_order', {+ id: order.id,+ portfolioId: order.portfolioId,+ symbol: order.symbol,+ side: order.side,+ orderType: order.type,+ quantity: order.quantity,+ price: order.price || null,+ timeInForce: order.timeInForce || 'GTC',+ });}async getOrder(orderId: string): Promise<PaperTradingOrder | null> {- const sql = `- SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price,- filled_quantity, avg_fill_price, status, time_in_force, post_only,- reduce_only, trailing_percent, trailing_amount, iceberg_qty, leverage,- margin_mode, created_at, filled_at, updated_at- FROM paper_trading_orders- WHERE id = $1- `;-- const result = await sqliteService.select<DBOrder[]>(sql, [orderId]);-- if (!result || result.length === 0) {+ try {+ const result = await invoke<any>('db_get_order', { id: orderId });+ return this.mapDBOrder(result);+ } catch (error) {+ console.error('[PaperTradingDatabase] getOrder error:', error);return null;}-- return this.mapDBOrder(result[0]);}async getPortfolioOrders(portfolioId: string, status?: string): Promise<PaperTradingOrder[]> {- let sql = `- SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price,- filled_quantity, avg_fill_price, status, time_in_force, post_only,- reduce_only, trailing_percent, trailing_amount, iceberg_qty, leverage,- margin_mode, created_at, filled_at, updated_at- FROM paper_trading_orders- WHERE portfolio_id = $1- `;-- const params: any[] = [portfolioId];-- if (status) {- sql += ` AND status = $2`;- params.push(status);- }-- sql += ` ORDER BY created_at DESC`;-- const result = await sqliteService.select<DBOrder[]>(sql, params);+ const result = await invoke<any[]>('db_get_portfolio_orders', {+ portfolioId,+ status: status || null,+ });return result.map(row => this.mapDBOrder(row));}async getPendingOrders(portfolioId?: string): Promise<PaperTradingOrder[]> {- let sql = `- SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price,- filled_quantity, avg_fill_price, status, time_in_force, post_only,- reduce_only, trailing_percent, trailing_amount, iceberg_qty, leverage,- margin_mode, created_at, filled_at, updated_at- FROM paper_trading_orders- WHERE status IN ('pending', 'triggered', 'partial')- `;-- const params: any[] = [];-- if (portfolioId) {- sql += ` AND portfolio_id = $1`;- params.push(portfolioId);- }-- sql += ` ORDER BY created_at ASC`;-- const result = await sqliteService.select<DBOrder[]>(sql, params);+ const result = await invoke<any[]>('db_get_pending_orders', {+ portfolioId: portfolioId || null,+ });return result.map(row => this.mapDBOrder(row));}@@ -397,36 +239,17 @@ export class PaperTradingDatabase {status?: string;filledAt?: string | null;}): Promise<void> {- const fields: string[] = ['updated_at = CURRENT_TIMESTAMP'];- const values: any[] = [];- let paramIndex = 1;-- if (updates.filledQuantity !== undefined) {- fields.push(`filled_quantity = $${paramIndex++}`);- values.push(updates.filledQuantity);- }- if (updates.avgFillPrice !== undefined) {- fields.push(`avg_fill_price = $${paramIndex++}`);- values.push(updates.avgFillPrice);- }- if (updates.status !== undefined) {- fields.push(`status = $${paramIndex++}`);- values.push(updates.status);- }- if (updates.filledAt !== undefined) {- fields.push(`filled_at = $${paramIndex++}`);- values.push(updates.filledAt);- }-- values.push(orderId);- const sql = `UPDATE paper_trading_orders SET ${fields.join(', ')} WHERE id = $${paramIndex}`;-- await sqliteService.execute(sql, values);+ await invoke('db_update_order', {+ id: orderId,+ filledQuantity: updates.filledQuantity || null,+ avgFillPrice: updates.avgFillPrice || null,+ status: updates.status || null,+ filledAt: updates.filledAt !== undefined ? updates.filledAt : null,+ });}async deleteOrder(orderId: string): Promise<void> {- const sql = `DELETE FROM paper_trading_orders WHERE id = $1`;- await sqliteService.execute(sql, [orderId]);+ await invoke('db_delete_order', { id: orderId });}// ============================================================================@@ -445,86 +268,52 @@ export class PaperTradingDatabase {feeRate: number;isMaker: boolean;}): Promise<void> {- const sql = `- INSERT INTO paper_trading_trades- (id, portfolio_id, order_id, symbol, side, price, quantity, fee, fee_rate, is_maker, timestamp)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, CURRENT_TIMESTAMP)- `;-- await sqliteService.execute(sql, [- trade.id,- trade.portfolioId,- trade.orderId,- trade.symbol,- trade.side,- trade.price,- trade.quantity,- trade.fee,- trade.feeRate,- trade.isMaker ? 1 : 0,- ]);+ await invoke('db_create_trade', {+ id: trade.id,+ portfolioId: trade.portfolioId,+ orderId: trade.orderId,+ symbol: trade.symbol,+ side: trade.side,+ price: trade.price,+ quantity: trade.quantity,+ fee: trade.fee,+ feeRate: trade.feeRate,+ isMaker: trade.isMaker,+ });}async getTrade(tradeId: string): Promise<PaperTradingTrade | null> {- const sql = `- SELECT id, portfolio_id, order_id, symbol, side, price, quantity,- fee, fee_rate, is_maker, timestamp- FROM paper_trading_trades- WHERE id = $1- `;-- const result = await sqliteService.select<DBTrade[]>(sql, [tradeId]);-- if (!result || result.length === 0) {+ try {+ const result = await invoke<any>('db_get_trade', { id: tradeId });+ return this.mapDBTrade(result);+ } catch (error) {+ console.error('[PaperTradingDatabase] getTrade error:', error);return null;}-- return this.mapDBTrade(result[0]);}async getPortfolioTrades(portfolioId: string, limit?: number): Promise<PaperTradingTrade[]> {- let sql = `- SELECT id, portfolio_id, order_id, symbol, side, price, quantity,- fee, fee_rate, is_maker, timestamp- FROM paper_trading_trades- WHERE portfolio_id = $1- ORDER BY timestamp DESC- `;-- const params: any[] = [portfolioId];-- if (limit) {- sql += ` LIMIT $2`;- params.push(limit);- }-- const result = await sqliteService.select<DBTrade[]>(sql, params);+ const result = await invoke<any[]>('db_get_portfolio_trades', {+ portfolioId,+ limit: limit || null,+ });return result.map(row => this.mapDBTrade(row));}async getOrderTrades(orderId: string): Promise<PaperTradingTrade[]> {- const sql = `- SELECT id, portfolio_id, order_id, symbol, side, price, quantity,- fee, fee_rate, is_maker, timestamp- FROM paper_trading_trades- WHERE order_id = $1- ORDER BY timestamp ASC- `;-- const result = await sqliteService.select<DBTrade[]>(sql, [orderId]);+ const result = await invoke<any[]>('db_get_order_trades', { orderId });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]);+ await invoke('db_delete_trade', { id: tradeId });}// ============================================================================// MAPPING FUNCTIONS// ============================================================================- private mapDBPortfolio(row: DBPortfolio): PaperTradingPortfolio {+ private mapDBPortfolio(row: any): PaperTradingPortfolio {return {id: row.id,name: row.name,@@ -539,7 +328,7 @@ export class PaperTradingDatabase {};}- private mapDBPosition(row: DBPosition): PaperTradingPosition {+ private mapDBPosition(row: any): PaperTradingPosition {return {id: row.id,portfolioId: row.portfolio_id,@@ -560,13 +349,13 @@ export class PaperTradingDatabase {};}- private mapDBOrder(row: DBOrder): PaperTradingOrder {+ private mapDBOrder(row: any): PaperTradingOrder {return {id: row.id,portfolioId: row.portfolio_id,symbol: row.symbol,side: row.side,- type: row.type as any,+ type: row.order_type as any,amount: row.quantity,price: row.price || undefined,stopPrice: row.stop_price || undefined,@@ -576,13 +365,13 @@ export class PaperTradingDatabase {timestamp: new Date(row.created_at).getTime(),datetime: row.created_at,timeInForce: row.time_in_force || undefined,- postOnly: row.post_only === 1,- reduceOnly: row.reduce_only === 1,- trailingPercent: row.trailing_percent || undefined,- trailingAmount: row.trailing_amount || undefined,- icebergQty: row.iceberg_qty || undefined,- leverage: row.leverage || undefined,- marginMode: row.margin_mode as any,+ postOnly: row.post_only === true || row.post_only === 1,+ reduceOnly: row.reduce_only === true || row.reduce_only === 1,+ trailingPercent: undefined,+ trailingAmount: undefined,+ icebergQty: undefined,+ leverage: undefined,+ marginMode: undefined,lastTradeTimestamp: row.filled_at ? new Date(row.filled_at).getTime() : undefined,remaining: row.quantity - row.filled_quantity,cost: (row.avg_fill_price || 0) * row.filled_quantity,@@ -590,7 +379,7 @@ export class PaperTradingDatabase {} as PaperTradingOrder;}- private mapDBTrade(row: DBTrade): PaperTradingTrade {+ private mapDBTrade(row: any): PaperTradingTrade {return {id: row.id,portfolioId: row.portfolio_id,@@ -601,7 +390,7 @@ export class PaperTradingDatabase {quantity: row.quantity,fee: row.fee,feeRate: row.fee_rate,- isMaker: row.is_maker === 1,+ isMaker: row.is_maker === true || row.is_maker === 1,timestamp: row.timestamp,};}diff --git a/fincept-terminal-desktop/src/services/excelService.ts b/fincept-terminal-desktop/src/services/excelService.tsnew file mode 100644index 000000000..deeac71f2--- /dev/null+++ b/fincept-terminal-desktop/src/services/excelService.ts@@ -0,0 +1,92 @@+// Excel Service - Now using high-performance Rust SQLite backend via Tauri commands++import { invoke } from '@tauri-apps/api/core';++export interface ExcelFile {+ id?: number;+ file_name: string;+ file_path: string;+ sheet_count: number;+ last_opened: string;+ last_modified: string;+ created_at: string;+}++export interface ExcelSnapshot {+ id?: number;+ file_id: number;+ snapshot_name: string;+ sheet_data: string; // JSON stringified sheet data+ created_at: string;+}++class ExcelService {+ // No initialization needed - Rust backend handles it++ async initialize() {+ console.log('[ExcelService] Using Rust SQLite backend');+ }++ async addOrUpdateFile(file: Omit<ExcelFile, 'id'>): Promise<number> {+ try {+ const fileData = {+ ...file,+ created_at: file.created_at || new Date().toISOString()+ };+ const id = await invoke<number>('db_add_or_update_excel_file', { file: fileData });+ console.log('[ExcelService] Added/updated excel file with ID:', id);+ return id;+ } catch (error) {+ console.error('[ExcelService] Failed to add/update file:', error);+ throw error;+ }+ }++ async getRecentFiles(limit: number = 10): Promise<ExcelFile[]> {+ try {+ return await invoke<ExcelFile[]>('db_get_recent_excel_files', { limit });+ } catch (error) {+ console.error('[ExcelService] Failed to get recent files:', error);+ throw error;+ }+ }++ async createSnapshot(fileId: number, snapshotName: string, sheetData: string): Promise<number> {+ try {+ const createdAt = new Date().toISOString();+ const id = await invoke<number>('db_create_excel_snapshot', {+ fileId,+ snapshotName,+ sheetData,+ createdAt+ });+ console.log('[ExcelService] Created snapshot with ID:', id);+ return id;+ } catch (error) {+ console.error('[ExcelService] Failed to create snapshot:', error);+ throw error;+ }+ }++ async getSnapshots(fileId: number): Promise<ExcelSnapshot[]> {+ try {+ return await invoke<ExcelSnapshot[]>('db_get_excel_snapshots', { fileId });+ } catch (error) {+ console.error('[ExcelService] Failed to get snapshots:', error);+ throw error;+ }+ }++ async deleteSnapshot(id: number): Promise<void> {+ try {+ await invoke('db_delete_excel_snapshot', { id });+ console.log('[ExcelService] Deleted snapshot:', id);+ } catch (error) {+ console.error('[ExcelService] Failed to delete snapshot:', error);+ throw error;+ }+ }+}++export const excelService = new ExcelService();+export default excelService;diff --git a/fincept-terminal-desktop/src/services/llmApi.ts b/fincept-terminal-desktop/src/services/llmApi.tsindex 20d17fc08..8f0e647f1 100644--- a/fincept-terminal-desktop/src/services/llmApi.ts+++ b/fincept-terminal-desktop/src/services/llmApi.ts@@ -2,7 +2,7 @@// Unified interface for different LLM providers with streaming supportimport { fetch } from '@tauri-apps/plugin-http';-import { sqliteService } from './sqliteService';+import { invoke } from '@tauri-apps/api/core';import { llmLogger } from './loggerService';export interface LLMConfig {@@ -887,8 +887,9 @@ class LLMApiService {onStream?: StreamCallback): Promise<LLMResponse> {try {- // Get active provider config from SQLite- const activeConfig = await sqliteService.getActiveLLMConfig();+ // Get active provider config from Rust SQLite+ const configs = await invoke<any[]>('db_get_llm_configs');+ const activeConfig = configs.find(c => c.is_active);if (!activeConfig) {return {content: '',@@ -897,7 +898,7 @@ class LLMApiService {}// Get global settings- const globalSettings = await sqliteService.getLLMGlobalSettings();+ const globalSettings = await invoke<any>('db_get_llm_global_settings');// Build complete configconst config: LLMConfig = {@@ -961,8 +962,9 @@ class LLMApiService {onToolCall?: (toolName: string, args: any, result?: any) => void): Promise<LLMResponse> {try {- // Get active provider config- const activeConfig = await sqliteService.getActiveLLMConfig();+ // Get active provider config from Rust SQLite+ const configs = await invoke<any[]>('db_get_llm_configs');+ const activeConfig = configs.find(c => c.is_active);if (!activeConfig) {return {content: '',@@ -995,7 +997,7 @@ class LLMApiService {return this.chat(userMessage, conversationHistory, onStream);}- const globalSettings = await sqliteService.getLLMGlobalSettings();+ const globalSettings = await invoke<any>('db_get_llm_global_settings');const config: LLMConfig = {provider: activeConfig.provider,@@ -1206,7 +1208,8 @@ class LLMApiService {// Test connectionasync testConnection(): Promise<{ success: boolean; error?: string; model?: string }> {try {- const activeConfig = await sqliteService.getActiveLLMConfig();+ const configs = await invoke<any[]>('db_get_llm_configs');+ const activeConfig = configs.find(c => c.is_active);if (!activeConfig) {return { success: false, error: 'No active provider configured' };}diff --git a/fincept-terminal-desktop/src/services/marketDataService.ts b/fincept-terminal-desktop/src/services/marketDataService.tsindex 3a1be4607..0366a3796 100644--- a/fincept-terminal-desktop/src/services/marketDataService.ts+++ b/fincept-terminal-desktop/src/services/marketDataService.ts@@ -179,8 +179,23 @@ class MarketDataService {return await this.getEnhancedQuotes(symbols);}- // Try to get cached data for all symbols- const cachedData = await sqliteService.getCachedCategoryData(category, symbols, maxCacheAgeMinutes);+ // Try to get cached data for each symbol+ const cachedDataPromises = symbols.map(symbol =>+ sqliteService.getCachedMarketData(symbol, category, maxCacheAgeMinutes)+ );+ const cachedDataResults = await Promise.all(cachedDataPromises);++ const cachedData = new Map<string, QuoteData & { seven_day?: number; thirty_day?: number }>();+ symbols.forEach((symbol, index) => {+ const cached = cachedDataResults[index];+ if (cached) {+ try {+ cachedData.set(symbol, JSON.parse(cached));+ } catch (e) {+ // Invalid cached data, will fetch fresh+ }+ }+ });// Identify which symbols need fresh dataconst symbolsNeedingFetch = symbols.filter(symbol => !cachedData.has(symbol));@@ -198,7 +213,7 @@ class MarketDataService {// Cache the fresh dataawait Promise.all(freshQuotes.map(quote =>- sqliteService.saveMarketDataCache(quote.symbol, category, quote)+ sqliteService.saveMarketDataCache(quote.symbol, category, JSON.stringify(quote))));diff --git a/fincept-terminal-desktop/src/services/mcpManager.ts b/fincept-terminal-desktop/src/services/mcpManager.tsindex 291dadf70..7c2448cb3 100644--- a/fincept-terminal-desktop/src/services/mcpManager.ts+++ b/fincept-terminal-desktop/src/services/mcpManager.ts@@ -59,7 +59,7 @@ class MCPManager {// Update existing server configawait sqliteService.updateMCPServerConfig(config.id, {- env: config.env ? JSON.stringify(config.env) : null+ env: config.env ? JSON.stringify(config.env) : undefined});// Restart if running@@ -86,7 +86,7 @@ class MCPManager {description: config.description,command: config.command,args: JSON.stringify(config.args),- env: config.env ? JSON.stringify(config.env) : null,+ env: config.env ? JSON.stringify(config.env) : undefined,category: config.category,icon: config.icon,enabled: true,@@ -138,7 +138,7 @@ class MCPManager {}// Parse config- const args = JSON.parse(server.args);+ const args = server.args ? JSON.parse(server.args) : [];const env = server.env ? JSON.parse(server.env) : undefined;// Connect@@ -223,7 +223,7 @@ class MCPManager {return {...server,- args: JSON.parse(server.args),+ args: server.args ? JSON.parse(server.args) : [],env: server.env ? JSON.parse(server.env) : undefined,status: actualStatus as 'running' | 'stopped' | 'error',toolCount: stats.toolCount,@@ -302,7 +302,7 @@ class MCPManager {result: null,success: false,executionTime,- error: error instanceof Error ? error.message : 'Unknown error'+ errorMessage: error instanceof Error ? error.message : 'Unknown error'});throw error;diff --git a/fincept-terminal-desktop/src/services/noteReminderService.ts b/fincept-terminal-desktop/src/services/noteReminderService.tsindex 0aa660ebf..2e38abece 100644--- a/fincept-terminal-desktop/src/services/noteReminderService.ts+++ b/fincept-terminal-desktop/src/services/noteReminderService.ts@@ -1,200 +1,2 @@-import { notesService, Note } from './notesService';-import { toast } from 'sonner';--class NoteReminderService {- private checkInterval: NodeJS.Timeout | null = null;- private notifiedReminders: Set<number> = new Set();- private readonly CHECK_INTERVAL_MS = 60000; // Check every minute-- /**- * Start monitoring for note reminders- */- start() {- if (this.checkInterval) {- console.log('[NoteReminderService] Already running');- return;- }-- console.log('[NoteReminderService] Starting reminder monitoring');- this.checkReminders(); // Check immediately- this.checkInterval = setInterval(() => this.checkReminders(), this.CHECK_INTERVAL_MS);- }-- /**- * Stop monitoring for note reminders- */- stop() {- if (this.checkInterval) {- clearInterval(this.checkInterval);- this.checkInterval = null;- console.log('[NoteReminderService] Stopped reminder monitoring');- }- }-- /**- * Check for due reminders and show notifications- */- private async checkReminders() {- try {- const notesWithReminders = await notesService.getNotesWithReminders();- const now = new Date();-- for (const note of notesWithReminders) {- if (!note.reminder_date || !note.id) continue;-- const reminderDate = new Date(note.reminder_date);- const timeDiff = reminderDate.getTime() - now.getTime();-- // Show reminder if it's due (within the next minute or overdue)- if (timeDiff <= 60000 && timeDiff > -60000) {- if (!this.notifiedReminders.has(note.id)) {- this.showReminderNotification(note);- this.notifiedReminders.add(note.id);- }- }- // Clean up old notifications from the set- else if (timeDiff < -60000) {- this.notifiedReminders.delete(note.id);- }- }- } catch (error) {- console.error('[NoteReminderService] Failed to check reminders:', error);- }- }-- /**- * Show a toast notification for a note reminder- */- private showReminderNotification(note: Note) {- const priorityEmoji = this.getPriorityEmoji(note.priority);- const sentimentEmoji = this.getSentimentEmoji(note.sentiment);-- toast(- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>- <div style={{ fontWeight: 700, fontSize: '13px', color: '#FF8800' }}>- {priorityEmoji} NOTE REMINDER- </div>- <div style={{ fontSize: '12px', fontWeight: 600 }}>- {note.title}- </div>- <div style={{ fontSize: '10px', color: '#999', display: 'flex', gap: '8px' }}>- <span>{sentimentEmoji} {note.sentiment}</span>- <span>•</span>- <span>{note.category}</span>- {note.tickers && (- <>- <span>•</span>- <span style={{ color: '#00E5FF' }}>{note.tickers}</span>- </>- )}- </div>- {note.content && (- <div style={{ fontSize: '11px', color: '#aaa', marginTop: '4px', lineHeight: '1.4' }}>- {note.content.substring(0, 100)}{note.content.length > 100 ? '...' : ''}- </div>- )}- </div>,- {- duration: 10000, // Show for 10 seconds- position: 'top-right',- className: 'note-reminder-toast',- style: {- backgroundColor: '#1A1A1A',- border: '2px solid #FF8800',- borderRadius: '4px',- padding: '12px',- boxShadow: '0 4px 16px rgba(255, 136, 0, 0.3)'- },- action: {- label: 'View',- onClick: () => {- // Emit custom event to open the note- window.dispatchEvent(new CustomEvent('openNote', { detail: { noteId: note.id } }));- }- }- }- );-- console.log(`[NoteReminderService] Showed reminder for note: ${note.title}`);- }-- /**- * Get emoji for priority level- */- private getPriorityEmoji(priority: string): string {- switch (priority) {- case 'HIGH':- return '🔴';- case 'MEDIUM':- return '🟡';- case 'LOW':- return '🟢';- default:- return '⚪';- }- }-- /**- * Get emoji for sentiment- */- private getSentimentEmoji(sentiment: string): string {- switch (sentiment) {- case 'BULLISH':- return '📈';- case 'BEARISH':- return '📉';- case 'NEUTRAL':- return '➡️';- default:- return '📊';- }- }-- /**- * Manually trigger a reminder check (useful for testing or immediate updates)- */- async triggerCheck() {- await this.checkReminders();- }-- /**- * Clear the notification history for a specific note- */- clearNotificationHistory(noteId: number) {- this.notifiedReminders.delete(noteId);- }-- /**- * Get upcoming reminders (within next 24 hours)- */- async getUpcomingReminders(): Promise<Array<{ note: Note; hoursUntil: number }>> {- try {- const notesWithReminders = await notesService.getNotesWithReminders();- const now = new Date();- const upcoming: Array<{ note: Note; hoursUntil: number }> = [];-- for (const note of notesWithReminders) {- if (!note.reminder_date) continue;-- const reminderDate = new Date(note.reminder_date);- const timeDiff = reminderDate.getTime() - now.getTime();- const hoursUntil = timeDiff / (1000 * 60 * 60);-- if (hoursUntil >= 0 && hoursUntil <= 24) {- upcoming.push({ note, hoursUntil });- }- }-- // Sort by closest first- upcoming.sort((a, b) => a.hoursUntil - b.hoursUntil);-- return upcoming;- } catch (error) {- console.error('[NoteReminderService] Failed to get upcoming reminders:', error);- return [];- }- }-}--// Singleton instance-export const noteReminderService = new NoteReminderService();+// Re-export from .tsx file+export * from './noteReminderService.tsx';diff --git a/fincept-terminal-desktop/src/services/noteReminderService.tsx b/fincept-terminal-desktop/src/services/noteReminderService.tsxnew file mode 100644index 000000000..9b99b26be--- /dev/null+++ b/fincept-terminal-desktop/src/services/noteReminderService.tsx@@ -0,0 +1,201 @@+import React from 'react';+import { notesService, Note } from './notesService';+import { toast } from 'sonner';++class NoteReminderService {+ private checkInterval: NodeJS.Timeout | null = null;+ private notifiedReminders: Set<number> = new Set();+ private readonly CHECK_INTERVAL_MS = 60000; // Check every minute++ /**+ * Start monitoring for note reminders+ */+ start() {+ if (this.checkInterval) {+ console.log('[NoteReminderService] Already running');+ return;+ }++ console.log('[NoteReminderService] Starting reminder monitoring');+ this.checkReminders(); // Check immediately+ this.checkInterval = setInterval(() => this.checkReminders(), this.CHECK_INTERVAL_MS);+ }++ /**+ * Stop monitoring for note reminders+ */+ stop() {+ if (this.checkInterval) {+ clearInterval(this.checkInterval);+ this.checkInterval = null;+ console.log('[NoteReminderService] Stopped reminder monitoring');+ }+ }++ /**+ * Check for due reminders and show notifications+ */+ private async checkReminders() {+ try {+ const notesWithReminders = await notesService.getNotesWithReminders();+ const now = new Date();++ for (const note of notesWithReminders) {+ if (!note.reminder_date || !note.id) continue;++ const reminderDate = new Date(note.reminder_date);+ const timeDiff = reminderDate.getTime() - now.getTime();++ // Show reminder if it's due (within the next minute or overdue)+ if (timeDiff <= 60000 && timeDiff > -60000) {+ if (!this.notifiedReminders.has(note.id)) {+ this.showReminderNotification(note);+ this.notifiedReminders.add(note.id);+ }+ }+ // Clean up old notifications from the set+ else if (timeDiff < -60000) {+ this.notifiedReminders.delete(note.id);+ }+ }+ } catch (error) {+ console.error('[NoteReminderService] Failed to check reminders:', error);+ }+ }++ /**+ * Show a toast notification for a note reminder+ */+ private showReminderNotification(note: Note) {+ const priorityEmoji = this.getPriorityEmoji(note.priority);+ const sentimentEmoji = this.getSentimentEmoji(note.sentiment);++ toast(+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>+ <div style={{ fontWeight: 700, fontSize: '13px', color: '#FF8800' }}>+ {priorityEmoji} NOTE REMINDER+ </div>+ <div style={{ fontSize: '12px', fontWeight: 600 }}>+ {note.title}+ </div>+ <div style={{ fontSize: '10px', color: '#999', display: 'flex', gap: '8px' }}>+ <span>{sentimentEmoji} {note.sentiment}</span>+ <span>•</span>+ <span>{note.category}</span>+ {note.tickers && (+ <>+ <span>•</span>+ <span style={{ color: '#00E5FF' }}>{note.tickers}</span>+ </>+ )}+ </div>+ {note.content && (+ <div style={{ fontSize: '11px', color: '#aaa', marginTop: '4px', lineHeight: '1.4' }}>+ {note.content.substring(0, 100)}{note.content.length > 100 ? '...' : ''}+ </div>+ )}+ </div>,+ {+ duration: 10000, // Show for 10 seconds+ position: 'top-right',+ className: 'note-reminder-toast',+ style: {+ backgroundColor: '#1A1A1A',+ border: '2px solid #FF8800',+ borderRadius: '4px',+ padding: '12px',+ boxShadow: '0 4px 16px rgba(255, 136, 0, 0.3)'+ },+ action: {+ label: 'View',+ onClick: () => {+ // Emit custom event to open the note+ window.dispatchEvent(new CustomEvent('openNote', { detail: { noteId: note.id } }));+ }+ }+ }+ );++ console.log(`[NoteReminderService] Showed reminder for note: ${note.title}`);+ }++ /**+ * Get emoji for priority level+ */+ private getPriorityEmoji(priority: string): string {+ switch (priority) {+ case 'HIGH':+ return '🔴';+ case 'MEDIUM':+ return '🟡';+ case 'LOW':+ return '🟢';+ default:+ return '⚪';+ }+ }++ /**+ * Get emoji for sentiment+ */+ private getSentimentEmoji(sentiment: string): string {+ switch (sentiment) {+ case 'BULLISH':+ return '📈';+ case 'BEARISH':+ return '📉';+ case 'NEUTRAL':+ return '➡️';+ default:+ return '📊';+ }+ }++ /**+ * Manually trigger a reminder check (useful for testing or immediate updates)+ */+ async triggerCheck() {+ await this.checkReminders();+ }++ /**+ * Clear the notification history for a specific note+ */+ clearNotificationHistory(noteId: number) {+ this.notifiedReminders.delete(noteId);+ }++ /**+ * Get upcoming reminders (within next 24 hours)+ */+ async getUpcomingReminders(): Promise<Array<{ note: Note; hoursUntil: number }>> {+ try {+ const notesWithReminders = await notesService.getNotesWithReminders();+ const now = new Date();+ const upcoming: Array<{ note: Note; hoursUntil: number }> = [];++ for (const note of notesWithReminders) {+ if (!note.reminder_date) continue;++ const reminderDate = new Date(note.reminder_date);+ const timeDiff = reminderDate.getTime() - now.getTime();+ const hoursUntil = timeDiff / (1000 * 60 * 60);++ if (hoursUntil >= 0 && hoursUntil <= 24) {+ upcoming.push({ note, hoursUntil });+ }+ }++ // Sort by closest first+ upcoming.sort((a, b) => a.hoursUntil - b.hoursUntil);++ return upcoming;+ } catch (error) {+ console.error('[NoteReminderService] Failed to get upcoming reminders:', error);+ return [];+ }+ }+}++// Singleton instance+export const noteReminderService = new NoteReminderService();diff --git a/fincept-terminal-desktop/src/services/notesService.ts b/fincept-terminal-desktop/src/services/notesService.tsindex b5b722372..6a7d69d02 100644--- a/fincept-terminal-desktop/src/services/notesService.ts+++ b/fincept-terminal-desktop/src/services/notesService.ts@@ -1,4 +1,6 @@-import Database from '@tauri-apps/plugin-sql';+// Notes Service - Now using high-performance Rust SQLite backend via Tauri commands++import { invoke } from '@tauri-apps/api/core';export interface Note {id?: number;@@ -9,8 +11,8 @@ export interface Note {tags: string; // Comma-separated tagstickers: string; // Comma-separated ticker symbolssentiment: string; // BULLISH, BEARISH, NEUTRAL- is_favorite: number; // 0 or 1- is_archived: number; // 0 or 1+ is_favorite: boolean;+ is_archived: boolean;color_code: string; // Hex color for visual organizationattachments: string; // JSON array of attachment pathscreated_at: string;@@ -29,376 +31,54 @@ export interface NoteTemplate {}class NotesService {- private db: Database | null = null;- private isInitialized = false;+ // No initialization needed - Rust backend handles itasync initialize() {- if (this.isInitialized) return;+ console.log('[NotesService] Using Rust SQLite backend');+ }+ async createNote(note: Omit<Note, 'id' | 'created_at' | 'updated_at'>): Promise<number> {try {- this.db = await Database.load('sqlite:financial_notes.db');-- // Create notes table with financial-specific fields- await this.db.execute(`- CREATE TABLE IF NOT EXISTS financial_notes (- id INTEGER PRIMARY KEY AUTOINCREMENT,- title TEXT NOT NULL,- content TEXT NOT NULL,- category TEXT NOT NULL,- priority TEXT DEFAULT 'MEDIUM',- tags TEXT,- tickers TEXT,- sentiment TEXT DEFAULT 'NEUTRAL',- is_favorite INTEGER DEFAULT 0,- is_archived INTEGER DEFAULT 0,- color_code TEXT DEFAULT '#FF8800',- attachments TEXT,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- reminder_date TEXT,- word_count INTEGER DEFAULT 0- )- `);-- // Create note templates table- await this.db.execute(`- CREATE TABLE IF NOT EXISTS note_templates (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NOT NULL,- description TEXT,- content TEXT NOT NULL,- category TEXT NOT NULL,- created_at TEXT NOT NULL- )- `);-- // Create indexes for performance- await this.db.execute(`- CREATE INDEX IF NOT EXISTS idx_notes_category ON financial_notes(category)- `);- await this.db.execute(`- CREATE INDEX IF NOT EXISTS idx_notes_updated ON financial_notes(updated_at DESC)- `);- await this.db.execute(`- CREATE INDEX IF NOT EXISTS idx_notes_favorite ON financial_notes(is_favorite)- `);- await this.db.execute(`- CREATE INDEX IF NOT EXISTS idx_notes_archived ON financial_notes(is_archived)- `);- await this.db.execute(`- CREATE INDEX IF NOT EXISTS idx_notes_priority ON financial_notes(priority)- `);-- // Insert default templates if they don't exist- const existingTemplates = await this.db.select<NoteTemplate[]>(- 'SELECT COUNT(*) as count FROM note_templates'- );-- if (!existingTemplates || (existingTemplates as any)[0]?.count === 0) {- await this.insertDefaultTemplates();- }-- this.isInitialized = true;- console.log('[NotesService] Initialized successfully');+ const now = new Date().toISOString();+ const noteData = {+ ...note,+ created_at: now,+ updated_at: now+ };+ const id = await invoke<number>('db_create_note', { note: noteData });+ console.log('[NotesService] Created note with ID:', id);+ return id;} catch (error) {- console.error('[NotesService] Failed to initialize:', error);+ console.error('[NotesService] Failed to create note:', error);throw error;}}- private async insertDefaultTemplates() {- const templates: Omit<NoteTemplate, 'id'>[] = [- {- name: 'Trade Idea',- description: 'Document a new trading opportunity',- category: 'TRADE_IDEA',- content: `# Trade Idea--## Overview-**Ticker:** [SYMBOL]-**Entry Price:** $[PRICE]-**Target Price:** $[TARGET]-**Stop Loss:** $[STOP]-**Position Size:** [SIZE]--## Thesis-[Write your investment thesis here]--## Catalysts-- [Key catalyst 1]-- [Key catalyst 2]--## Risk Factors-- [Risk 1]-- [Risk 2]--## Timeline-**Expected Duration:** [TIMEFRAME]-**Key Dates:** [EVENTS]`,- created_at: new Date().toISOString()- },- {- name: 'Market Analysis',- description: 'Analyze overall market conditions',- category: 'MARKET_ANALYSIS',- content: `# Market Analysis - [DATE]--## Market Overview-**Sentiment:** [BULLISH/BEARISH/NEUTRAL]-**Key Indices:**-- S&P 500: [LEVEL] ([CHANGE]%)-- NASDAQ: [LEVEL] ([CHANGE]%)-- VIX: [LEVEL]--## Sector Performance-- Best: [SECTOR] (+[%])-- Worst: [SECTOR] (-[%])--## Key Developments-1. [Development 1]-2. [Development 2]--## Technical Indicators-- **RSI:** [VALUE]-- **Moving Averages:** [ANALYSIS]--## Outlook-[Your market outlook for the next period]`,- created_at: new Date().toISOString()- },- {- name: 'Earnings Notes',- description: 'Track company earnings and guidance',- category: 'EARNINGS',- content: `# Earnings Report - [TICKER]--## Report Date-**Quarter:** [Q1/Q2/Q3/Q4] [YEAR]-**Release Date:** [DATE]--## Key Metrics-- **EPS:** $[ACTUAL] vs $[ESTIMATE] (Expected)-- **Revenue:** $[ACTUAL] vs $[ESTIMATE]-- **Guidance:** [RAISED/LOWERED/MAINTAINED]--## Highlights-- [Highlight 1]-- [Highlight 2]--## Management Commentary-[Key quotes or insights from management]--## Market Reaction-**Stock Movement:** [+/-][%]-**After Hours:** [PRICE]--## Analysis-[Your analysis of the results]`,- created_at: new Date().toISOString()- },- {- name: 'Economic Data',- description: 'Track important economic releases',- category: 'ECONOMIC',- content: `# Economic Data Release--## Indicator-**Name:** [INDICATOR NAME]-**Date:** [RELEASE DATE]--## Results-**Actual:** [VALUE]-**Expected:** [VALUE]-**Previous:** [VALUE]--## Market Impact-**Asset Class Impact:**-- Equities: [ANALYSIS]-- Bonds: [ANALYSIS]-- Currencies: [ANALYSIS]--## Implications-[Analysis of what this data means for markets]`,- created_at: new Date().toISOString()- },- {- name: 'Research Note',- description: 'Deep dive research on a company or theme',- category: 'RESEARCH',- content: `# Research: [COMPANY/THEME]--## Executive Summary-[Brief overview]--## Investment Thesis-[Detailed thesis]--## Business Model-[How the company makes money]--## Competitive Advantages-1. [Moat 1]-2. [Moat 2]--## Financial Analysis-**Margins:** [DATA]-**Growth:** [DATA]-**Valuation:** [P/E], [P/S], [EV/EBITDA]--## Risks-- [Risk 1]-- [Risk 2]--## Conclusion-[Buy/Hold/Sell recommendation and price target]`,- created_at: new Date().toISOString()- },- {- name: 'Portfolio Review',- description: 'Review and analyze your portfolio',- category: 'PORTFOLIO',- content: `# Portfolio Review - [DATE]--## Performance Summary-**Total Return:** [+/-][%]-**vs S&P 500:** [+/-][%]--## Top Performers-1. [TICKER]: [+%] - [REASON]-2. [TICKER]: [+%] - [REASON]--## Underperformers-1. [TICKER]: [-%%] - [REASON]-2. [TICKER]: [-%%] - [REASON]--## Allocation Analysis-- **Equities:** [%]-- **Fixed Income:** [%]-- **Cash:** [%]--## Adjustments Needed-- [ ] [Action item 1]-- [ ] [Action item 2]--## Next Review Date-[DATE]`,- created_at: new Date().toISOString()- }- ];-- for (const template of templates) {- await this.db!.execute(- `INSERT INTO note_templates (name, description, content, category, created_at)- VALUES (?, ?, ?, ?, ?)`,- [template.name, template.description, template.content, template.category, template.created_at]- );- }- }-- async createNote(note: Omit<Note, 'id'>): Promise<number> {- await this.initialize();-+ async getAllNotes(includeArchived: boolean = false): Promise<Note[]> {try {- const result = await this.db!.execute(- `INSERT INTO financial_notes- (title, content, category, priority, tags, tickers, sentiment, is_favorite,- is_archived, color_code, attachments, created_at, updated_at, reminder_date, word_count)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,- [- note.title,- note.content,- note.category,- note.priority,- note.tags || '',- note.tickers || '',- note.sentiment,- note.is_favorite || 0,- note.is_archived || 0,- note.color_code || '#FF8800',- note.attachments || '[]',- note.created_at,- note.updated_at,- note.reminder_date || null,- note.word_count || 0- ]- );-- return result.lastInsertId || 0;+ return await invoke<Note[]>('db_get_all_notes', { includeArchived });} catch (error) {- console.error('[NotesService] Failed to create note:', error);+ console.error('[NotesService] Failed to get notes:', error);throw error;}}- async updateNote(id: number, updates: Partial<Note>): Promise<void> {- await this.initialize();-+ async updateNote(id: number, updates: Partial<Omit<Note, 'id' | 'created_at' | 'updated_at'>>): Promise<void> {try {- const setParts: string[] = [];- const values: any[] = [];-- if (updates.title !== undefined) {- setParts.push('title = ?');- values.push(updates.title);- }- if (updates.content !== undefined) {- setParts.push('content = ?');- values.push(updates.content);- }- if (updates.category !== undefined) {- setParts.push('category = ?');- values.push(updates.category);- }- if (updates.priority !== undefined) {- setParts.push('priority = ?');- values.push(updates.priority);- }- if (updates.tags !== undefined) {- setParts.push('tags = ?');- values.push(updates.tags);- }- if (updates.tickers !== undefined) {- setParts.push('tickers = ?');- values.push(updates.tickers);- }- if (updates.sentiment !== undefined) {- setParts.push('sentiment = ?');- values.push(updates.sentiment);- }- if (updates.is_favorite !== undefined) {- setParts.push('is_favorite = ?');- values.push(updates.is_favorite);- }- if (updates.is_archived !== undefined) {- setParts.push('is_archived = ?');- values.push(updates.is_archived);- }- if (updates.color_code !== undefined) {- setParts.push('color_code = ?');- values.push(updates.color_code);- }- if (updates.attachments !== undefined) {- setParts.push('attachments = ?');- values.push(updates.attachments);- }- if (updates.reminder_date !== undefined) {- setParts.push('reminder_date = ?');- values.push(updates.reminder_date);- }- if (updates.word_count !== undefined) {- setParts.push('word_count = ?');- values.push(updates.word_count);+ const notes = await this.getAllNotes(true);+ const existingNote = notes.find(n => n.id === id);+ if (!existingNote) {+ throw new Error('Note not found');}- setParts.push('updated_at = ?');- values.push(new Date().toISOString());-- values.push(id);+ const updatedNote = {+ ...existingNote,+ ...updates,+ updated_at: new Date().toISOString()+ };- await this.db!.execute(- `UPDATE financial_notes SET ${setParts.join(', ')} WHERE id = ?`,- values- );+ await invoke('db_update_note', { id, updates: updatedNote });+ console.log('[NotesService] Updated note:', id);} catch (error) {console.error('[NotesService] Failed to update note:', error);throw error;@@ -406,190 +86,87 @@ class NotesService {}async deleteNote(id: number): Promise<void> {- await this.initialize();-try {- await this.db!.execute('DELETE FROM financial_notes WHERE id = ?', [id]);+ await invoke('db_delete_note', { id });+ console.log('[NotesService] Deleted note:', id);} catch (error) {console.error('[NotesService] Failed to delete note:', error);throw error;}}- async getNoteById(id: number): Promise<Note | null> {- await this.initialize();-+ async searchNotes(query: string): Promise<Note[]> {try {- const result = await this.db!.select<Note[]>(- 'SELECT * FROM financial_notes WHERE id = ?',- [id]- );- return result.length > 0 ? result[0] : null;+ return await invoke<Note[]>('db_search_notes', { query });} catch (error) {- console.error('[NotesService] Failed to get note by ID:', error);- return null;+ console.error('[NotesService] Failed to search notes:', error);+ throw error;}}- async getAllNotes(includeArchived = false): Promise<Note[]> {- await this.initialize();-+ async getTemplates(): Promise<NoteTemplate[]> {try {- const query = includeArchived- ? 'SELECT * FROM financial_notes ORDER BY updated_at DESC'- : 'SELECT * FROM financial_notes WHERE is_archived = 0 ORDER BY updated_at DESC';-- const result = await this.db!.select<Note[]>(query);- return result;+ return await invoke<NoteTemplate[]>('db_get_note_templates');} catch (error) {- console.error('[NotesService] Failed to get all notes:', error);- return [];+ console.error('[NotesService] Failed to get templates:', error);+ throw error;}}- async getNotesByCategory(category: string, includeArchived = false): Promise<Note[]> {- await this.initialize();-- try {- const query = includeArchived- ? 'SELECT * FROM financial_notes WHERE category = ? ORDER BY updated_at DESC'- : 'SELECT * FROM financial_notes WHERE category = ? AND is_archived = 0 ORDER BY updated_at DESC';-- const result = await this.db!.select<Note[]>(query, [category]);- return result;- } catch (error) {- console.error('[NotesService] Failed to get notes by category:', error);- return [];- }+ // Helper methods+ async getNotesByCategory(category: string, includeArchived: boolean = false): Promise<Note[]> {+ const allNotes = await this.getAllNotes(includeArchived);+ return allNotes.filter(note => note.category === category);}async getFavoriteNotes(): Promise<Note[]> {- await this.initialize();-- try {- const result = await this.db!.select<Note[]>(- 'SELECT * FROM financial_notes WHERE is_favorite = 1 AND is_archived = 0 ORDER BY updated_at DESC'- );- return result;- } catch (error) {- console.error('[NotesService] Failed to get favorite notes:', error);- return [];- }- }-- async searchNotes(query: string): Promise<Note[]> {- await this.initialize();-- try {- const result = await this.db!.select<Note[]>(- `SELECT * FROM financial_notes- WHERE (title LIKE ? OR content LIKE ? OR tags LIKE ? OR tickers LIKE ?)- AND is_archived = 0- ORDER BY updated_at DESC`,- [`%${query}%`, `%${query}%`, `%${query}%`, `%${query}%`]- );- return result;- } catch (error) {- console.error('[NotesService] Failed to search notes:', error);- return [];- }+ const allNotes = await this.getAllNotes(false);+ return allNotes.filter(note => note.is_favorite);}async getNotesWithReminders(): Promise<Note[]> {- await this.initialize();-- try {- const result = await this.db!.select<Note[]>(- `SELECT * FROM financial_notes- WHERE reminder_date IS NOT NULL AND is_archived = 0- ORDER BY reminder_date ASC`- );- return result;- } catch (error) {- console.error('[NotesService] Failed to get notes with reminders:', error);- return [];- }+ const allNotes = await this.getAllNotes(false);+ return allNotes.filter(note => note.reminder_date !== null);}- async getTemplates(): Promise<NoteTemplate[]> {- await this.initialize();-- try {- const result = await this.db!.select<NoteTemplate[]>(- 'SELECT * FROM note_templates ORDER BY name ASC'- );- return result;- } catch (error) {- console.error('[NotesService] Failed to get templates:', error);- return [];+ async toggleFavorite(id: number): Promise<void> {+ const notes = await this.getAllNotes(true);+ const note = notes.find(n => n.id === id);+ if (!note) {+ throw new Error('Note not found');}+ await this.updateNote(id, { is_favorite: !note.is_favorite });}- async createTemplate(template: Omit<NoteTemplate, 'id'>): Promise<number> {- await this.initialize();-- try {- const result = await this.db!.execute(- `INSERT INTO note_templates (name, description, content, category, created_at)- VALUES (?, ?, ?, ?, ?)`,- [template.name, template.description, template.content, template.category, template.created_at]- );- return result.lastInsertId || 0;- } catch (error) {- console.error('[NotesService] Failed to create template:', error);- throw error;- }+ async archiveNote(id: number): Promise<void> {+ await this.updateNote(id, { is_archived: true });}- async deleteTemplate(id: number): Promise<void> {- await this.initialize();+ async unarchiveNote(id: number): Promise<void> {+ await this.updateNote(id, { is_archived: false });+ }- try {- await this.db!.execute('DELETE FROM note_templates WHERE id = ?', [id]);- } catch (error) {- console.error('[NotesService] Failed to delete template:', error);- throw error;- }+ async getNoteById(id: number): Promise<Note | null> {+ const notes = await this.getAllNotes(true);+ return notes.find(n => n.id === id) || null;}async getStatistics() {- await this.initialize();-- try {- const totalNotes = await this.db!.select<any[]>(- 'SELECT COUNT(*) as count FROM financial_notes WHERE is_archived = 0'- );- const archivedNotes = await this.db!.select<any[]>(- 'SELECT COUNT(*) as count FROM financial_notes WHERE is_archived = 1'- );- const favoriteNotes = await this.db!.select<any[]>(- 'SELECT COUNT(*) as count FROM financial_notes WHERE is_favorite = 1'- );- const categoryStats = await this.db!.select<any[]>(- 'SELECT category, COUNT(*) as count FROM financial_notes WHERE is_archived = 0 GROUP BY category'- );- const totalWords = await this.db!.select<any[]>(- 'SELECT SUM(word_count) as total FROM financial_notes WHERE is_archived = 0'- );-- return {- total: totalNotes[0]?.count || 0,- archived: archivedNotes[0]?.count || 0,- favorites: favoriteNotes[0]?.count || 0,- byCategory: categoryStats,- totalWords: totalWords[0]?.total || 0- };- } catch (error) {- console.error('[NotesService] Failed to get statistics:', error);- return {- total: 0,- archived: 0,- favorites: 0,- byCategory: [],- totalWords: 0- };- }+ const notes = await this.getAllNotes(false);+ return {+ total: notes.length,+ favorites: notes.filter(n => n.is_favorite).length,+ byCategory: notes.reduce((acc, note) => {+ acc[note.category] = (acc[note.category] || 0) + 1;+ return acc;+ }, {} as Record<string, number>),+ byPriority: notes.reduce((acc, note) => {+ acc[note.priority] = (acc[note.priority] || 0) + 1;+ return acc;+ }, {} as Record<string, number>)+ };}}export const notesService = new NotesService();+export default notesService;diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.tsindex 69d0cbee8..d42502854 100644--- a/fincept-terminal-desktop/src/services/sqliteService.ts+++ b/fincept-terminal-desktop/src/services/sqliteService.ts@@ -1,24 +1,22 @@-/**- * SQLite Database Service- * Uses Tauri SQL plugin for database operations- */+// SQLite Service - Rust SQLite backend via Tauri commands+// All database operations now use high-performance Rust backend-import Database from '@tauri-apps/plugin-sql';+import { invoke } from '@tauri-apps/api/core';-// Type definitions-export interface Credential {- id?: number;- service_name: string;- username: string;- password: string;- api_key?: string;- api_secret?: string;- additional_data?: string;- created_at?: string;- updated_at?: string;-}+// Re-export watchlist services+export { watchlistService } from './watchlistService';+export type { Watchlist, WatchlistStock } from './watchlistService';++// Re-export notes services+export { notesService } from './notesService';+export type { Note, NoteTemplate } from './notesService';++// Re-export excel services+export { excelService } from './excelService';+export type { ExcelFile, ExcelSnapshot } from './excelService';++// ==================== API KEYS ====================-// Predefined API Keys structureexport interface ApiKeys {FRED_API_KEY?: string;POLYGON_API_KEY?: string;@@ -42,24 +40,74 @@ export const PREDEFINED_API_KEYS = [{ key: 'FINANCIAL_MODELING_PREP_API_KEY', label: 'Financial Modeling Prep', description: 'Financial statements & ratios' },] as const;+// ==================== SETTINGS ====================+export interface Setting {setting_key: string;setting_value: string;category?: string;- updated_at?: string;+ updated_at: string;+}++export const saveSetting = async (key: string, value: string, category?: string): Promise<void> => {+ await invoke('db_save_setting', { key, value, category });+};++export const getSetting = async (key: string): Promise<string | null> => {+ return await invoke<string | null>('db_get_setting', { key });+};++export const getAllSettings = async (): Promise<Setting[]> => {+ return await invoke<Setting[]>('db_get_all_settings');+};++// ==================== CREDENTIALS ====================++export interface Credential {+ id?: number;+ service_name: string;+ username?: string;+ password?: string;+ api_key?: string;+ api_secret?: string;+ additional_data?: string;+ created_at: string;+ updated_at: string;}+export const saveCredential = async (cred: Omit<Credential, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> => {+ const credWithTimestamps = {+ ...cred,+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString()+ };+ return await invoke('db_save_credential', { cred: credWithTimestamps });+};++export const getCredentials = async (): Promise<Credential[]> => {+ return await invoke<Credential[]>('db_get_credentials');+};++export const getCredentialByService = async (serviceName: string): Promise<Credential | null> => {+ return await invoke<Credential | null>('db_get_credential_by_service', { serviceName });+};++export const deleteCredential = async (id: number): Promise<{ success: boolean; message: string }> => {+ return await invoke('db_delete_credential', { id });+};++// ==================== LLM CONFIG ====================+export interface LLMConfig {provider: string;- api_key?: string;+ api_key: string;base_url?: string;model: string;is_active: boolean;- created_at?: string;- updated_at?: string;+ created_at: string;+ updated_at: string;}-// New interface for individual model configurations (multiple models per provider)export interface LLMModelConfig {id: string;provider: string;@@ -79,6 +127,134 @@ export interface LLMGlobalSettings {system_prompt: string;}+export const getLLMConfigs = async (): Promise<LLMConfig[]> => {+ return await invoke<LLMConfig[]>('db_get_llm_configs');+};++export const saveLLMConfig = async (config: LLMConfig): Promise<void> => {+ await invoke('db_save_llm_config', { config });+};++export const getActiveLLMConfig = async (): Promise<LLMConfig | null> => {+ const configs = await getLLMConfigs();+ return configs.find(c => c.is_active) || null;+};++export const getLLMGlobalSettings = async (): Promise<LLMGlobalSettings> => {+ return await invoke<LLMGlobalSettings>('db_get_llm_global_settings');+};++export const saveLLMGlobalSettings = async (settings: LLMGlobalSettings): Promise<void> => {+ await invoke('db_save_llm_global_settings', { settings });+};++// ==================== ALPHA ARENA ====================++export interface AlphaCompetition {+ id: string;+ name: string;+ symbol: string;+ mode: string;+ status: string;+ cycle_count: number;+ cycle_interval_seconds: number;+ initial_capital: number;+ started_at?: string;+ created_at?: string;+ updated_at?: string;+}++export interface AlphaModelState {+ id: string;+ competition_id: string;+ model_name: string;+ provider: string;+ model_id: string;+ capital: number;+ positions_json: string;+ last_decision?: string;+ trades_count?: number;+ total_pnl?: number;+ portfolio_value?: number;+ created_at?: string;+ updated_at?: string;+}++export interface AlphaPerformanceSnapshot {+ id?: number;+ competition_id: string;+ model_name: string;+ timestamp: string;+ cycle_number?: number;+ portfolio_value: number;+ cash: number;+ positions_value: number;+ total_return: number;+ created_at?: string;+}++export interface AlphaDecisionLog {+ id?: number;+ competition_id: string;+ model_name: string;+ cycle_number: number;+ timestamp: string;+ decision: string;+ action?: string;+ quantity?: number;+ price_at_decision?: number;+ reasoning?: string;+ trade_executed?: any;+ created_at?: string;+}++// Alpha Arena methods - These are stubs as the data is managed by Python service+export const createAlphaCompetition = async (competition: Partial<AlphaCompetition>): Promise<void> => {+ console.warn('[SqliteService] createAlphaCompetition - stub method, data managed by Python');+};++export const getAlphaCompetitions = async (limit?: number): Promise<AlphaCompetition[]> => {+ console.warn('[SqliteService] getAlphaCompetitions - stub method, data managed by Python');+ return [];+};++export const updateAlphaCompetition = async (id: string, updates: Partial<AlphaCompetition>): Promise<void> => {+ console.warn('[SqliteService] updateAlphaCompetition - stub method, data managed by Python');+};++export const deleteAlphaCompetition = async (id: string): Promise<void> => {+ console.warn('[SqliteService] deleteAlphaCompetition - stub method, data managed by Python');+};++export const saveAlphaModelState = async (state: Partial<AlphaModelState>): Promise<void> => {+ console.warn('[SqliteService] saveAlphaModelState - stub method, data managed by Python');+};++export const getAlphaModelStates = async (competitionId: string): Promise<AlphaModelState[]> => {+ console.warn('[SqliteService] getAlphaModelStates - stub method, data managed by Python');+ return [];+};++export const saveAlphaPerformanceSnapshot = async (snapshot: Partial<AlphaPerformanceSnapshot>): Promise<void> => {+ console.warn('[SqliteService] saveAlphaPerformanceSnapshot - stub method, data managed by Python');+};++export const getAlphaPerformanceSnapshots = async (competitionId: string, modelName?: string): Promise<AlphaPerformanceSnapshot[]> => {+ console.warn('[SqliteService] getAlphaPerformanceSnapshots - stub method, data managed by Python');+ return [];+};++export const saveAlphaDecisionLog = async (log: Partial<AlphaDecisionLog>): Promise<void> => {+ console.warn('[SqliteService] saveAlphaDecisionLog - stub method, data managed by Python');+};++export const getAlphaDecisionLogs = async (competitionId: string, modelName?: string): Promise<AlphaDecisionLog[]> => {+ console.warn('[SqliteService] getAlphaDecisionLogs - stub method, data managed by Python');+ return [];+};++// ==================== CHAT ====================+export interface ChatSession {session_uuid: string;title: string;@@ -90,7 +266,7 @@ export interface ChatSession {export interface ChatMessage {id: string;session_uuid: string;- role: 'user' | 'assistant';+ role: string;content: string;timestamp: string;provider?: string;@@ -98,6 +274,33 @@ export interface ChatMessage {tokens_used?: number;}+export const createChatSession = async (title: string): Promise<ChatSession> => {+ return await invoke<ChatSession>('db_create_chat_session', { title });+};++export const getChatSessions = async (limit?: number): Promise<ChatSession[]> => {+ return await invoke<ChatSession[]>('db_get_chat_sessions', { limit });+};++export const addChatMessage = async (msg: Omit<ChatMessage, 'id' | 'timestamp'>): Promise<ChatMessage> => {+ const messageWithDefaults = {+ id: crypto.randomUUID(),+ timestamp: new Date().toISOString(),+ ...msg+ };+ return await invoke<ChatMessage>('db_add_chat_message', { msg: messageWithDefaults });+};++export const getChatMessages = async (sessionUuid: string): Promise<ChatMessage[]> => {+ return await invoke<ChatMessage[]>('db_get_chat_messages', { sessionUuid });+};++export const deleteChatSession = async (sessionUuid: string): Promise<void> => {+ await invoke('db_delete_chat_session', { sessionUuid });+};++// ==================== DATA SOURCES ====================+export interface DataSource {id: string;alias: string;@@ -105,7 +308,7 @@ export interface DataSource {description?: string;type: 'websocket' | 'rest_api';provider: string;- category?: string;+ category: string;config: string;enabled: boolean;tags?: string;@@ -113,27 +316,72 @@ export interface DataSource {updated_at: string;}-export interface WSProviderConfig {- id: number;- provider_name: string;- enabled: boolean;- api_key: string | null;- api_secret: string | null;- endpoint: string | null;- config_data: string | null;- created_at: string;- updated_at: string;-}+export const saveDataSource = async (source: Omit<DataSource, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string; id?: string }> => {+ const sourceWithTimestamps = {+ ...source,+ ds_type: source.type, // Map 'type' to 'ds_type' for Rust backend+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString()+ };+ return await invoke('db_save_data_source', { source: sourceWithTimestamps });+};++export const getAllDataSources = async (): Promise<DataSource[]> => {+ const sources = await invoke<any[]>('db_get_all_data_sources');+ // Map ds_type back to type for frontend+ return sources.map(s => ({ ...s, type: s.ds_type || s.type }));+};++export const deleteDataSource = async (id: string): Promise<{ success: boolean; message: string }> => {+ return await invoke('db_delete_data_source', { id });+};++// Data Source Connection methods - stub implementations+// These methods are for the data-sources tab's connection management+export const saveDataSourceConnection = async (connection: any): Promise<void> => {+ console.warn('[SqliteService] saveDataSourceConnection - stub method, using getAllDataSources as fallback');+ // Could store as a data source with special category+};++export const updateDataSourceConnection = async (id: string, updates: any): Promise<void> => {+ console.warn('[SqliteService] updateDataSourceConnection - stub method');+};++export const deleteDataSourceConnection = async (id: string): Promise<void> => {+ console.warn('[SqliteService] deleteDataSourceConnection - stub method');+};++export const getDataSourceConnection = async (id: string): Promise<any | null> => {+ console.warn('[SqliteService] getDataSourceConnection - stub method');+ return null;+};++export const getAllDataSourceConnections = async (): Promise<any[]> => {+ console.warn('[SqliteService] getAllDataSourceConnections - stub method, returning empty array');+ return [];+};++export const getDataSourceConnectionsByCategory = async (category: string): Promise<any[]> => {+ console.warn('[SqliteService] getDataSourceConnectionsByCategory - stub method');+ return [];+};++export const getDataSourceConnectionsByType = async (type: string): Promise<any[]> => {+ console.warn('[SqliteService] getDataSourceConnectionsByType - stub method');+ return [];+};++// ==================== MCP SERVERS ====================export interface MCPServer {id: string;name: string;- description: string;+ description?: string;command: string;- args: string;- env?: string | null;+ args?: string;+ env?: string;category: string;- icon: string;+ icon?: string;enabled: boolean;auto_start: boolean;status: string;@@ -141,34 +389,24 @@ export interface MCPServer {updated_at: string;}-export interface RecordedContext {- id: string;- tab_name: string;- data_type: string;- label?: string;- raw_data: string;- metadata?: string;- data_size: number;- created_at: string;- tags?: string;-}+export const addMCPServer = async (server: Omit<MCPServer, 'created_at' | 'updated_at'> | MCPServer): Promise<void> => {+ const serverWithTimestamps = {+ ...server,+ created_at: 'created_at' in server ? server.created_at : new Date().toISOString(),+ updated_at: new Date().toISOString()+ };+ await invoke('db_add_mcp_server', { server: serverWithTimestamps });+};-export interface RecordingSession {- id: string;- tab_name: string;- is_active: boolean;- auto_record: boolean;- filters?: string;- started_at: string;- ended_at?: string;-}+export const getMCPServers = async (): Promise<MCPServer[]> => {+ return await invoke<MCPServer[]>('db_get_mcp_servers');+};-export interface ChatContextLink {- chat_session_uuid: string;- context_id: string;- added_at: string;- is_active: boolean;-}+export const deleteMCPServer = async (id: string): Promise<void> => {+ await invoke('db_delete_mcp_server', { id });+};++// ==================== BACKTESTING ====================export interface BacktestingProvider {id: string;@@ -188,7 +426,7 @@ export interface BacktestingStrategy {version: string;author?: string;provider_type: string;- strategy_type: 'code' | 'visual' | 'template';+ strategy_type: string;strategy_definition: string;tags?: string;created_at: string;@@ -197,11 +435,11 @@ export interface BacktestingStrategy {export interface BacktestRun {id: string;- strategy_id?: string;+ strategy_id: string;provider_name: string;config: string;results?: string;- status: 'completed' | 'failed' | 'running' | 'cancelled';+ status: string;performance_metrics?: string;error_message?: string;created_at: string;@@ -209,2889 +447,523 @@ export interface BacktestRun {duration_seconds?: number;}-export interface OptimizationRun {- id: string;- strategy_id?: string;- provider_name: string;- parameter_grid: string;- objective: string;- best_parameters?: string;- best_result?: string;- all_results?: string;- iterations?: number;- status: 'completed' | 'failed' | 'running' | 'cancelled';- error_message?: string;- created_at: string;- completed_at?: string;- duration_seconds?: number;-}+export const saveBacktestingProvider = async (provider: Omit<BacktestingProvider, 'created_at' | 'updated_at'> | BacktestingProvider): Promise<{ success: boolean; message: string }> => {+ const providerWithTimestamps = {+ ...provider,+ created_at: 'created_at' in provider ? provider.created_at : new Date().toISOString(),+ updated_at: new Date().toISOString()+ };+ return await invoke('db_save_backtesting_provider', { provider: providerWithTimestamps });+};-// ==================== ALPHA ARENA INTERFACES ====================+export const getBacktestingProviders = async (): Promise<BacktestingProvider[]> => {+ return await invoke<BacktestingProvider[]>('db_get_backtesting_providers');+};-export interface AlphaCompetition {+export const saveBacktestingStrategy = async (strategy: BacktestingStrategy): Promise<{ success: boolean; message: string }> => {+ return await invoke('db_save_backtesting_strategy', { strategy });+};++export const getBacktestingStrategies = async (): Promise<BacktestingStrategy[]> => {+ return await invoke<BacktestingStrategy[]>('db_get_backtesting_strategies');+};++export const saveBacktestRun = async (run: BacktestRun): Promise<{ success: boolean; message: string }> => {+ return await invoke('db_save_backtest_run', { run });+};++export const getBacktestRuns = async (limit?: number): Promise<BacktestRun[]> => {+ return await invoke<BacktestRun[]>('db_get_backtest_runs', { limit });+};++// ==================== CONTEXT RECORDING ====================++export interface RecordingSession {id: string;- name: string;- symbol: string;- mode: 'baseline' | 'monk' | 'situational' | 'max_leverage';- status: 'created' | 'running' | 'paused' | 'completed';- cycle_count: number;- cycle_interval_seconds: number;- initial_capital: number;- created_at: string;- started_at?: string;- ended_at?: string;- updated_at: string;+ tab_name: string;+ is_active: boolean;+ auto_record: boolean;+ filters?: string;+ started_at: string;+ stopped_at?: string;}-export interface AlphaModelState {+export interface RecordedContext {id: string;- competition_id: string;- model_name: string;- provider: string;- model_id: string;- capital: number;- positions_json: string;- trades_count: number;- total_pnl: number;- portfolio_value: number;+ tab_name: string;+ data_type: string;+ label: string;+ raw_data: string;+ metadata?: string;+ data_size: number;created_at: string;- updated_at: string;+ tags?: string;}-export interface AlphaPriceHistory {- id: string;- competition_id: string;- symbol: string;- price: number;- bid?: number;- ask?: number;- volume_24h?: number;- high_24h?: number;- low_24h?: number;- timestamp: string;-}+export const saveRecordedContext = async (context: Omit<RecordedContext, 'created_at'> | RecordedContext): Promise<void> => {+ const contextWithTimestamp = {+ ...context,+ created_at: 'created_at' in context ? context.created_at : new Date().toISOString()+ };+ await invoke('db_save_recorded_context', { context: contextWithTimestamp });+};++export const getRecordedContexts = async (filters?: string | { tabName?: string; limit?: number; dataType?: string; tags?: string[] }): Promise<RecordedContext[]> => {+ // Handle both old string API and new object API+ if (typeof filters === 'string') {+ return await invoke<RecordedContext[]>('db_get_recorded_contexts', { tabName: filters, limit: undefined });+ } else if (filters && typeof filters === 'object') {+ return await invoke<RecordedContext[]>('db_get_recorded_contexts', { tabName: filters.tabName, limit: filters.limit });+ } else {+ return await invoke<RecordedContext[]>('db_get_recorded_contexts', {});+ }+};++export const deleteRecordedContext = async (id: string): Promise<void> => {+ await invoke('db_delete_recorded_context', { id });+};++// Recording Session methods - stub implementation as not in Rust backend+export const startRecordingSession = async (session: Partial<RecordingSession>): Promise<void> => {+ console.warn('[SqliteService] startRecordingSession - stub method');+};++export const stopRecordingSession = async (tabName: string): Promise<void> => {+ console.warn('[SqliteService] stopRecordingSession - stub method');+};++export const getActiveRecordingSession = async (tabName: string): Promise<RecordingSession | null> => {+ console.warn('[SqliteService] getActiveRecordingSession - stub method');+ return null;+};++export const getRecordedContext = async (id: string): Promise<RecordedContext | null> => {+ const contexts = await getRecordedContexts();+ return contexts.find(c => c.id === id) || null;+};++export const linkContextToChat = async (contextId: string, chatSessionUuid: string): Promise<void> => {+ console.warn('[SqliteService] linkContextToChat - stub method');+};++export const unlinkContextFromChat = async (contextId: string, chatSessionUuid: string): Promise<void> => {+ console.warn('[SqliteService] unlinkContextFromChat - stub method');+};++export const getChatContexts = async (chatSessionUuid: string): Promise<RecordedContext[]> => {+ console.warn('[SqliteService] getChatContexts - stub method');+ return [];+};++export const toggleChatContextActive = async (contextId: string, chatSessionUuid: string): Promise<void> => {+ console.warn('[SqliteService] toggleChatContextActive - stub method');+};++export const clearOldContexts = async (olderThanDays: number): Promise<void> => {+ console.warn('[SqliteService] clearOldContexts - stub method');+};-export interface AlphaDecisionLog {- id: string;- competition_id: string;- model_name: string;- cycle_number: number;- action: 'buy' | 'sell' | 'hold';- symbol: string;- quantity?: number;- confidence: number;- reasoning: string;- trade_executed: string;- price_at_decision: number;- portfolio_value_before: number;- portfolio_value_after: number;- timestamp: string;-}+export const getContextStorageStats = async (): Promise<any> => {+ console.warn('[SqliteService] getContextStorageStats - stub method');+ return null;+};-export interface AlphaPerformanceSnapshot {- id: string;- competition_id: string;- cycle_number: number;- model_name: string;- portfolio_value: number;- cash: number;- pnl: number;- return_pct: number;- positions_count: number;- trades_count: number;- timestamp: string;-}+// ==================== CACHE ====================-class SQLiteService {- private db: Database | null = null;- private initPromise: Promise<void> | null = null;+export const saveMarketDataCache = async (symbol: string, category: string, quoteData: string): Promise<void> => {+ await invoke('db_save_market_data_cache', { symbol, category, quoteData });+};- /**- * Initialize database connection and schema- */- async initialize(): Promise<void> {- if (this.initPromise) {- return this.initPromise;- }+export const getCachedMarketData = async (symbol: string, category: string, maxAgeMinutes: number): Promise<string | null> => {+ return await invoke<string | null>('db_get_cached_market_data', { symbol, category, maxAgeMinutes });+};++export const clearMarketDataCache = async (): Promise<void> => {+ await invoke('db_clear_market_data_cache');+};++// Forum caching methods - stub implementation+export const getCachedForumCategories = async (maxAgeMinutes: number): Promise<any[] | null> => {+ console.warn('[SqliteService] getCachedForumCategories - stub method');+ return null;+};++export const cacheForumCategories = async (categories: any[]): Promise<void> => {+ console.warn('[SqliteService] cacheForumCategories - stub method');+};++export const getCachedForumPosts = async (categoryId: string | number | null, sortBy: string, maxAgeMinutes: number): Promise<any[] | null> => {+ console.warn('[SqliteService] getCachedForumPosts - stub method');+ return null;+};++export const cacheForumPosts = async (categoryId: string | number | null, sortBy: string, posts: any[]): Promise<void> => {+ console.warn('[SqliteService] cacheForumPosts - stub method');+};++export const getCachedForumStats = async (maxAgeMinutes: number): Promise<any | null> => {+ console.warn('[SqliteService] getCachedForumStats - stub method');+ return null;+};- this.initPromise = this._initializeDatabase();- return this.initPromise;- }+export const cacheForumStats = async (stats: any): Promise<void> => {+ console.warn('[SqliteService] cacheForumStats - stub method');+};- private async _initializeDatabase(): Promise<void> {- try {- console.log('[SQLite] Initializing database...');+// ==================== PAPER TRADING ====================- // Connect to SQLite database- this.db = await Database.load('sqlite:fincept_terminal.db');+export const createPortfolio = async (id: string, name: string, provider: string, initialBalance: number, currency: string, marginMode: string, leverage: number): Promise<any> => {+ return await invoke('db_create_portfolio', { id, name, provider, initialBalance, currency, marginMode, leverage });+};- console.log('[SQLite] Creating schema...');- await this.createSchema();+export const getPortfolio = async (id: string): Promise<any> => {+ return await invoke('db_get_portfolio', { id });+};- console.log('[SQLite] ✓ Database initialized successfully');- } catch (error) {- console.error('[SQLite] Failed to initialize:', error);- throw error;- }- }+export const listPortfolios = async (): Promise<any[]> => {+ return await invoke<any[]>('db_list_portfolios');+};- private async createSchema(): Promise<void> {- if (!this.db) throw new Error('Database not connected');-- const statements = [- // Credentials table- `CREATE TABLE IF NOT EXISTS credentials (- id INTEGER PRIMARY KEY AUTOINCREMENT,- service_name TEXT NOT NULL UNIQUE,- username TEXT,- password TEXT,- api_key TEXT,- api_secret TEXT,- additional_data TEXT,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // Settings table- `CREATE TABLE IF NOT EXISTS settings (- setting_key TEXT PRIMARY KEY,- setting_value TEXT NOT NULL,- category TEXT,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // LLM configurations table- `CREATE TABLE IF NOT EXISTS llm_configs (- provider TEXT PRIMARY KEY,- api_key TEXT,- base_url TEXT,- model TEXT NOT NULL,- is_active INTEGER DEFAULT 0,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // LLM global settings table- `CREATE TABLE IF NOT EXISTS llm_global_settings (- id INTEGER PRIMARY KEY CHECK (id = 1),- temperature REAL DEFAULT 0.7,- max_tokens INTEGER DEFAULT 2000,- system_prompt TEXT DEFAULT ''- )`,-- // LLM model configurations table (supports multiple models per provider)- `CREATE TABLE IF NOT EXISTS llm_model_configs (- id TEXT PRIMARY KEY,- provider TEXT NOT NULL,- model_id TEXT NOT NULL,- display_name TEXT NOT NULL,- api_key TEXT,- base_url TEXT,- is_enabled INTEGER DEFAULT 1,- is_default INTEGER DEFAULT 0,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- `CREATE INDEX IF NOT EXISTS idx_llm_model_configs_provider ON llm_model_configs(provider)`,- `CREATE INDEX IF NOT EXISTS idx_llm_model_configs_enabled ON llm_model_configs(is_enabled)`,-- // Chat sessions table- `CREATE TABLE IF NOT EXISTS chat_sessions (- session_uuid TEXT PRIMARY KEY,- title TEXT NOT NULL,- message_count INTEGER DEFAULT 0,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // Chat messages table- `CREATE TABLE IF NOT EXISTS chat_messages (- id TEXT PRIMARY KEY,- session_uuid TEXT NOT NULL,- role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),- content TEXT NOT NULL,- timestamp TEXT DEFAULT CURRENT_TIMESTAMP,- provider TEXT,- model TEXT,- tokens_used INTEGER,- FOREIGN KEY (session_uuid) REFERENCES chat_sessions(session_uuid) ON DELETE CASCADE- )`,-- // Data sources table- `CREATE TABLE IF NOT EXISTS data_sources (- id TEXT PRIMARY KEY,- alias TEXT NOT NULL UNIQUE,- display_name TEXT NOT NULL,- description TEXT,- type TEXT NOT NULL CHECK (type IN ('websocket', 'rest_api')),- provider TEXT NOT NULL,- category TEXT,- config TEXT NOT NULL,- enabled INTEGER DEFAULT 1,- tags TEXT,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // WebSocket provider configs table- `CREATE TABLE IF NOT EXISTS ws_provider_configs (- id INTEGER PRIMARY KEY AUTOINCREMENT,- provider_name TEXT NOT NULL UNIQUE,- enabled INTEGER DEFAULT 1,- api_key TEXT,- api_secret TEXT,- endpoint TEXT,- config_data TEXT,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // Paper trading portfolios table- `CREATE TABLE IF NOT EXISTS paper_trading_portfolios (- id TEXT PRIMARY KEY,- name TEXT NOT NULL,- 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- )`,-- // Paper trading positions table- `CREATE TABLE IF NOT EXISTS paper_trading_positions (- id TEXT PRIMARY KEY,- portfolio_id TEXT NOT NULL,- symbol TEXT NOT NULL,- 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')),- FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE- )`,-- // Paper trading orders table- `CREATE TABLE IF NOT EXISTS paper_trading_orders (- id TEXT PRIMARY KEY,- portfolio_id TEXT NOT NULL,- symbol TEXT NOT NULL,- side TEXT NOT NULL CHECK (side IN ('buy', 'sell')),- type TEXT NOT NULL CHECK (type IN ('market', 'limit', 'stop_market', 'stop_limit')),- quantity REAL NOT NULL,- price REAL,- stop_price REAL,- 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- )`,-- // Paper trading trades table- `CREATE TABLE IF NOT EXISTS paper_trading_trades (- id TEXT PRIMARY KEY,- portfolio_id TEXT NOT NULL,- order_id TEXT NOT NULL,- symbol TEXT NOT NULL,- side TEXT NOT NULL,- 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- )`,-- // Indexes for paper trading tables- `CREATE INDEX IF NOT EXISTS idx_paper_positions_portfolio ON paper_trading_positions(portfolio_id)`,- `CREATE INDEX IF NOT EXISTS idx_paper_positions_status ON paper_trading_positions(status)`,- `CREATE INDEX IF NOT EXISTS idx_paper_orders_portfolio ON paper_trading_orders(portfolio_id)`,- `CREATE INDEX IF NOT EXISTS idx_paper_orders_status ON paper_trading_orders(status)`,- `CREATE INDEX IF NOT EXISTS idx_paper_trades_portfolio ON paper_trading_trades(portfolio_id)`,-- // MCP servers table- `CREATE TABLE IF NOT EXISTS mcp_servers (- id TEXT PRIMARY KEY,- name TEXT NOT NULL,- description TEXT,- command TEXT NOT NULL,- args TEXT,- env TEXT,- category TEXT,- icon TEXT,- enabled INTEGER DEFAULT 1,- auto_start INTEGER DEFAULT 0,- status TEXT DEFAULT 'stopped',- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // MCP tools table- `CREATE TABLE IF NOT EXISTS mcp_tools (- id TEXT PRIMARY KEY,- server_id TEXT NOT NULL,- name TEXT NOT NULL,- description TEXT,- input_schema TEXT,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- FOREIGN KEY (server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE- )`,-- // MCP tool usage logs table- `CREATE TABLE IF NOT EXISTS mcp_tool_usage_logs (- id INTEGER PRIMARY KEY AUTOINCREMENT,- server_id TEXT NOT NULL,- tool_name TEXT NOT NULL,- args TEXT,- result TEXT,- success INTEGER,- execution_time INTEGER,- error TEXT,- timestamp TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // Market data cache table- `CREATE TABLE IF NOT EXISTS market_data_cache (- symbol TEXT NOT NULL,- category TEXT NOT NULL,- quote_data TEXT NOT NULL,- cached_at TEXT DEFAULT CURRENT_TIMESTAMP,- PRIMARY KEY (symbol, category)- )`,-- // Data source connections table- `CREATE TABLE IF NOT EXISTS data_source_connections (- id TEXT PRIMARY KEY,- name TEXT NOT NULL,- type TEXT NOT NULL,- category TEXT NOT NULL,- config TEXT NOT NULL,- status TEXT NOT NULL,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP,- last_tested TEXT,- error_message TEXT- )`,-- // Forum cache tables- `CREATE TABLE IF NOT EXISTS forum_categories_cache (- id INTEGER PRIMARY KEY,- data TEXT NOT NULL,- cached_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- `CREATE TABLE IF NOT EXISTS forum_posts_cache (- cache_key TEXT PRIMARY KEY,- category_id INTEGER,- sort_by TEXT,- data TEXT NOT NULL,- cached_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- `CREATE TABLE IF NOT EXISTS forum_stats_cache (- id INTEGER PRIMARY KEY CHECK (id = 1),- data TEXT NOT NULL,- cached_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- `CREATE TABLE IF NOT EXISTS forum_post_details_cache (- post_uuid TEXT PRIMARY KEY,- data TEXT NOT NULL,- comments_data TEXT NOT NULL,- cached_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // Context Recording tables- `CREATE TABLE IF NOT EXISTS recorded_contexts (- id TEXT PRIMARY KEY,- tab_name TEXT NOT NULL,- data_type TEXT NOT NULL,- label TEXT,- raw_data TEXT NOT NULL,- metadata TEXT,- data_size INTEGER,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- tags TEXT- )`,-- `CREATE INDEX IF NOT EXISTS idx_recorded_contexts_tab ON recorded_contexts(tab_name)`,- `CREATE INDEX IF NOT EXISTS idx_recorded_contexts_type ON recorded_contexts(data_type)`,- `CREATE INDEX IF NOT EXISTS idx_recorded_contexts_created ON recorded_contexts(created_at DESC)`,-- `CREATE TABLE IF NOT EXISTS recording_sessions (- id TEXT PRIMARY KEY,- tab_name TEXT NOT NULL,- is_active INTEGER DEFAULT 1,- auto_record INTEGER DEFAULT 0,- filters TEXT,- started_at TEXT DEFAULT CURRENT_TIMESTAMP,- ended_at TEXT- )`,-- `CREATE TABLE IF NOT EXISTS chat_context_links (- chat_session_uuid TEXT NOT NULL,- context_id TEXT NOT NULL,- added_at TEXT DEFAULT CURRENT_TIMESTAMP,- is_active INTEGER DEFAULT 1,- PRIMARY KEY (chat_session_uuid, context_id),- FOREIGN KEY(chat_session_uuid) REFERENCES chat_sessions(session_uuid) ON DELETE CASCADE,- FOREIGN KEY(context_id) REFERENCES recorded_contexts(id) ON DELETE CASCADE- )`,-- `CREATE TABLE IF NOT EXISTS report_templates (- id TEXT PRIMARY KEY,- name TEXT NOT NULL,- description TEXT,- template_data TEXT NOT NULL,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // Backtesting providers table- `CREATE TABLE IF NOT EXISTS backtesting_providers (- id TEXT PRIMARY KEY,- name TEXT NOT NULL UNIQUE,- adapter_type TEXT NOT NULL,- config TEXT NOT NULL,- enabled INTEGER DEFAULT 1,- is_active INTEGER DEFAULT 0,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- // Backtesting strategies table- `CREATE TABLE IF NOT EXISTS backtesting_strategies (- id TEXT PRIMARY KEY,- name TEXT NOT NULL,- description TEXT,- version TEXT DEFAULT '1.0.0',- author TEXT,- provider_type TEXT NOT NULL,- strategy_type TEXT NOT NULL CHECK (strategy_type IN ('code', 'visual', 'template')),- strategy_definition TEXT NOT NULL,- tags TEXT,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- `CREATE INDEX IF NOT EXISTS idx_strategies_provider ON backtesting_strategies(provider_type)`,- `CREATE INDEX IF NOT EXISTS idx_strategies_type ON backtesting_strategies(strategy_type)`,-- // Backtest runs table- `CREATE TABLE IF NOT EXISTS backtest_runs (- id TEXT PRIMARY KEY,- strategy_id TEXT,- provider_name TEXT NOT NULL,- config TEXT NOT NULL,- results TEXT,- status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'running', 'cancelled')),- performance_metrics TEXT,- error_message TEXT,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- completed_at TEXT,- duration_seconds INTEGER,- FOREIGN KEY(strategy_id) REFERENCES backtesting_strategies(id) ON DELETE SET NULL- )`,-- `CREATE INDEX IF NOT EXISTS idx_backtest_runs_strategy ON backtest_runs(strategy_id)`,- `CREATE INDEX IF NOT EXISTS idx_backtest_runs_provider ON backtest_runs(provider_name)`,- `CREATE INDEX IF NOT EXISTS idx_backtest_runs_status ON backtest_runs(status)`,- `CREATE INDEX IF NOT EXISTS idx_backtest_runs_created ON backtest_runs(created_at DESC)`,-- // Optimization runs table- `CREATE TABLE IF NOT EXISTS optimization_runs (- id TEXT PRIMARY KEY,- strategy_id TEXT,- provider_name TEXT NOT NULL,- parameter_grid TEXT NOT NULL,- objective TEXT NOT NULL,- best_parameters TEXT,- best_result TEXT,- all_results TEXT,- iterations INTEGER,- status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'running', 'cancelled')),- error_message TEXT,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- completed_at TEXT,- duration_seconds INTEGER,- FOREIGN KEY(strategy_id) REFERENCES backtesting_strategies(id) ON DELETE SET NULL- )`,-- `CREATE INDEX IF NOT EXISTS idx_optimization_runs_strategy ON optimization_runs(strategy_id)`,- `CREATE INDEX IF NOT EXISTS idx_optimization_runs_provider ON optimization_runs(provider_name)`,- `CREATE INDEX IF NOT EXISTS idx_optimization_runs_status ON optimization_runs(status)`,-- // ==================== ALPHA ARENA TABLES ====================-- // Alpha Arena competitions table- `CREATE TABLE IF NOT EXISTS alpha_competitions (- id TEXT PRIMARY KEY,- name TEXT NOT NULL,- symbol TEXT NOT NULL,- mode TEXT NOT NULL CHECK (mode IN ('baseline', 'monk', 'situational', 'max_leverage')),- status TEXT NOT NULL CHECK (status IN ('created', 'running', 'paused', 'completed')) DEFAULT 'created',- cycle_count INTEGER DEFAULT 0,- cycle_interval_seconds INTEGER DEFAULT 150,- initial_capital REAL DEFAULT 10000,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- started_at TEXT,- ended_at TEXT,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP- )`,-- `CREATE INDEX IF NOT EXISTS idx_alpha_competitions_status ON alpha_competitions(status)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_competitions_created ON alpha_competitions(created_at DESC)`,-- // Alpha Arena model states table (persistent model portfolios)- `CREATE TABLE IF NOT EXISTS alpha_model_states (- id TEXT PRIMARY KEY,- competition_id TEXT NOT NULL,- model_name TEXT NOT NULL,- provider TEXT NOT NULL,- model_id TEXT NOT NULL,- capital REAL NOT NULL,- positions_json TEXT NOT NULL DEFAULT '{}',- trades_count INTEGER DEFAULT 0,- total_pnl REAL DEFAULT 0,- portfolio_value REAL NOT NULL,- created_at TEXT DEFAULT CURRENT_TIMESTAMP,- updated_at TEXT DEFAULT CURRENT_TIMESTAMP,- FOREIGN KEY (competition_id) REFERENCES alpha_competitions(id) ON DELETE CASCADE,- UNIQUE(competition_id, model_name)- )`,-- `CREATE INDEX IF NOT EXISTS idx_alpha_model_states_competition ON alpha_model_states(competition_id)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_model_states_model ON alpha_model_states(model_name)`,-- // Alpha Arena price history table (for charting)- `CREATE TABLE IF NOT EXISTS alpha_price_history (- id TEXT PRIMARY KEY,- competition_id TEXT NOT NULL,- symbol TEXT NOT NULL,- price REAL NOT NULL,- bid REAL,- ask REAL,- volume_24h REAL,- high_24h REAL,- low_24h REAL,- timestamp TEXT DEFAULT CURRENT_TIMESTAMP,- FOREIGN KEY (competition_id) REFERENCES alpha_competitions(id) ON DELETE CASCADE- )`,-- `CREATE INDEX IF NOT EXISTS idx_alpha_price_history_competition ON alpha_price_history(competition_id)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_price_history_timestamp ON alpha_price_history(timestamp)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_price_history_symbol ON alpha_price_history(symbol)`,-- // Alpha Arena decision logs table (all model decisions and trades)- `CREATE TABLE IF NOT EXISTS alpha_decision_logs (- id TEXT PRIMARY KEY,- competition_id TEXT NOT NULL,- model_name TEXT NOT NULL,- cycle_number INTEGER NOT NULL,- action TEXT NOT NULL CHECK (action IN ('buy', 'sell', 'hold')),- symbol TEXT NOT NULL,- quantity REAL,- confidence REAL NOT NULL,- reasoning TEXT NOT NULL,- trade_executed TEXT NOT NULL,- price_at_decision REAL NOT NULL,- portfolio_value_before REAL NOT NULL,- portfolio_value_after REAL NOT NULL,- timestamp TEXT DEFAULT CURRENT_TIMESTAMP,- FOREIGN KEY (competition_id) REFERENCES alpha_competitions(id) ON DELETE CASCADE- )`,-- `CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_competition ON alpha_decision_logs(competition_id)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_model ON alpha_decision_logs(model_name)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_cycle ON alpha_decision_logs(cycle_number)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_timestamp ON alpha_decision_logs(timestamp DESC)`,-- // Alpha Arena performance snapshots table (portfolio value over time for charting)- `CREATE TABLE IF NOT EXISTS alpha_performance_snapshots (- id TEXT PRIMARY KEY,- competition_id TEXT NOT NULL,- cycle_number INTEGER NOT NULL,- model_name TEXT NOT NULL,- portfolio_value REAL NOT NULL,- cash REAL NOT NULL,- pnl REAL NOT NULL,- return_pct REAL NOT NULL,- positions_count INTEGER DEFAULT 0,- trades_count INTEGER DEFAULT 0,- timestamp TEXT DEFAULT CURRENT_TIMESTAMP,- FOREIGN KEY (competition_id) REFERENCES alpha_competitions(id) ON DELETE CASCADE- )`,-- `CREATE INDEX IF NOT EXISTS idx_alpha_performance_competition ON alpha_performance_snapshots(competition_id)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_performance_model ON alpha_performance_snapshots(model_name)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_performance_cycle ON alpha_performance_snapshots(cycle_number)`,- `CREATE INDEX IF NOT EXISTS idx_alpha_performance_timestamp ON alpha_performance_snapshots(timestamp)`,-- // Insert default LLM global settings- `INSERT OR IGNORE INTO llm_global_settings (id, temperature, max_tokens, system_prompt)- VALUES (1, 0.7, 2000, 'You are a helpful AI assistant specialized in financial analysis and market data.')`,- ];-- for (const sql of statements) {- try {- await this.db.execute(sql);- } catch (error: any) {- // Ignore "duplicate column" errors from ALTER TABLE- if (!error.message?.includes('duplicate column')) {- throw error;- }- }- }+export const updatePortfolioBalance = async (id: string, currentBalance: number, totalPnl: number): Promise<void> => {+ await invoke('db_update_portfolio_balance', { id, currentBalance, totalPnl });+};- // 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);- }- }+export const createPosition = async (position: any): Promise<any> => {+ return await invoke('db_create_position', { position });+};- // =========================- // CREDENTIALS METHODS- // =========================-- async saveCredential(credential: Omit<Credential, 'id' | 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO credentials (service_name, username, password, api_key, api_secret, additional_data, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP)`,- [- credential.service_name,- credential.username || null,- credential.password || null,- credential.api_key || null,- credential.api_secret || null,- credential.additional_data || null,- ]- );- return { success: true, message: 'Credential saved successfully' };- } catch (error) {- console.error('[SQLite] Failed to save credential:', error);- return { success: false, message: 'Failed to save credential' };- }- }+export const getPortfolioPositions = async (portfolioId: string): Promise<any[]> => {+ return await invoke<any[]>('db_get_portfolio_positions', { portfolioId });+};- async getCredentials(): Promise<Credential[]> {- await this.ensureInitialized();- return await this.db!.select<Credential[]>('SELECT * FROM credentials ORDER BY service_name');- }+export const createOrder = async (order: any): Promise<any> => {+ return await invoke('db_create_order', { order });+};- async getCredentialByService(serviceName: string): Promise<Credential | null> {- await this.ensureInitialized();- const results = await this.db!.select<Credential[]>(- 'SELECT * FROM credentials WHERE service_name = $1',- [serviceName]- );- return results[0] || null;- }+export const getPortfolioOrders = async (portfolioId: string, limit?: number): Promise<any[]> => {+ return await invoke<any[]>('db_get_portfolio_orders', { portfolioId, limit });+};- async getApiKey(serviceName: string): Promise<string | null> {- // Use settings table for predefined API keys- const keyName = serviceName.toUpperCase().replace(/[^A-Z0-9]/g, '_') + '_API_KEY';- return await this.getSetting(keyName);- }+export const getPortfolioTrades = async (portfolioId: string, limit?: number): Promise<any[]> => {+ return await invoke<any[]>('db_get_portfolio_trades', { portfolioId, limit });+};- async setApiKey(keyName: string, value: string): Promise<void> {- await this.saveSetting(keyName, value, 'api_keys');+// Legacy service class for compatibility+class SqliteService {+ async initialize() {+ console.log('[SqliteService] Using Rust SQLite backend - no initialization needed');+ return true;}- async getAllApiKeys(): Promise<ApiKeys> {- await this.ensureInitialized();- const results = await this.db!.select<Setting[]>(- "SELECT * FROM settings WHERE category = 'api_keys'"- );-- const keys: ApiKeys = {};- results.forEach(row => {- keys[row.setting_key] = row.setting_value;- });- return keys;+ isReady() {+ return true; // Rust backend is always ready}- async deleteCredential(id: number): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM credentials WHERE id = $1', [id]);- return { success: true, message: 'Credential deleted successfully' };- } catch (error) {- console.error('[SQLite] Failed to delete credential:', error);- return { success: false, message: 'Failed to delete credential' };- }+ async healthCheck() {+ return { healthy: true, message: 'Rust backend operational' };}- // =========================- // SETTINGS METHODS- // =========================+ // Settings+ saveSetting = saveSetting;+ getSetting = getSetting;+ getAllSettings = getAllSettings;- async saveSetting(key: string, value: string, category?: string): Promise<void> {- await this.ensureInitialized();+ // Credentials+ saveCredential = saveCredential;+ getCredentials = getCredentials;+ getCredentialByService = getCredentialByService;+ deleteCredential = deleteCredential;- await this.db!.execute(- `INSERT OR REPLACE INTO settings (setting_key, setting_value, category, updated_at)- VALUES ($1, $2, $3, CURRENT_TIMESTAMP)`,- [key, value, category || null]- );- }+ // LLM+ getLLMConfigs = getLLMConfigs;+ saveLLMConfig = saveLLMConfig;+ getActiveLLMConfig = getActiveLLMConfig;+ getLLMGlobalSettings = getLLMGlobalSettings;+ saveLLMGlobalSettings = saveLLMGlobalSettings;- async getSetting(key: string): Promise<string | null> {- await this.ensureInitialized();- const results = await this.db!.select<Setting[]>(- 'SELECT * FROM settings WHERE setting_key = $1',- [key]- );- return results[0]?.setting_value || null;+ async ensureDefaultLLMConfigs() {+ // Not needed with Rust backend - schema handles defaults+ return true;}- async getSettingsByCategory(category: string): Promise<Setting[]> {- await this.ensureInitialized();- return await this.db!.select<Setting[]>(- 'SELECT * FROM settings WHERE category = $1',- [category]- );+ // LLM Model Configs+ async getLLMModelConfigs(): Promise<LLMModelConfig[]> {+ // Stub - not implemented in Rust backend yet+ console.warn('[SqliteService] getLLMModelConfigs not implemented');+ return [];}- async getAllSettings(): Promise<Setting[]> {- await this.ensureInitialized();- return await this.db!.select<Setting[]>('SELECT * FROM settings');+ async saveLLMModelConfig(config: LLMModelConfig): Promise<{ success: boolean; message: string }> {+ console.warn('[SqliteService] saveLLMModelConfig not implemented');+ return { success: false, message: 'Not implemented' };}- // =========================- // LLM METHODS- // =========================-- async getLLMConfigs(): Promise<LLMConfig[]> {- await this.ensureInitialized();- return await this.db!.select<LLMConfig[]>('SELECT * FROM llm_configs ORDER BY provider');+ async deleteLLMModelConfig(id: string): Promise<{ success: boolean; message: string }> {+ console.warn('[SqliteService] deleteLLMModelConfig not implemented');+ return { success: false, message: 'Not implemented' };}- async getLLMConfig(provider: string): Promise<LLMConfig | null> {- await this.ensureInitialized();- const results = await this.db!.select<LLMConfig[]>(- 'SELECT * FROM llm_configs WHERE provider = $1',- [provider]- );- return results[0] || null;+ async toggleLLMModelConfigEnabled(id: string): Promise<{ success: boolean; message: string }> {+ console.warn('[SqliteService] toggleLLMModelConfigEnabled not implemented');+ return { success: false, message: 'Not implemented' };}- async getActiveLLMConfig(): Promise<LLMConfig | null> {- await this.ensureInitialized();- const results = await this.db!.select<LLMConfig[]>(- 'SELECT * FROM llm_configs WHERE is_active = 1 LIMIT 1'- );- return results[0] || null;- }+ async setActiveLLMProvider(provider: string): Promise<void> {+ console.warn('[SqliteService] setActiveLLMProvider not implemented');+ }++ // Alpha Arena+ createAlphaCompetition = createAlphaCompetition;+ getAlphaCompetitions = getAlphaCompetitions;+ updateAlphaCompetition = updateAlphaCompetition;+ deleteAlphaCompetition = deleteAlphaCompetition;+ saveAlphaModelState = saveAlphaModelState;+ getAlphaModelStates = getAlphaModelStates;+ saveAlphaPerformanceSnapshot = saveAlphaPerformanceSnapshot;+ getAlphaPerformanceSnapshots = getAlphaPerformanceSnapshots;+ saveAlphaDecisionLog = saveAlphaDecisionLog;+ getAlphaDecisionLogs = getAlphaDecisionLogs;++ // Chat+ createChatSession = createChatSession;+ getChatSessions = getChatSessions;+ addChatMessage = addChatMessage;+ getChatMessages = getChatMessages;+ deleteChatSession = deleteChatSession;++ async updateChatSessionTitle(sessionUuid: string, title: string) {+ // Not implemented in Rust yet - would need to add this command+ console.warn('[SqliteService] updateChatSessionTitle not implemented in Rust backend');+ }++ async clearChatSessionMessages(sessionUuid: string) {+ // Not implemented in Rust yet - would need to add this command+ console.warn('[SqliteService] clearChatSessionMessages not implemented in Rust backend');+ }++ // Data Sources+ saveDataSource = saveDataSource;+ getAllDataSources = getAllDataSources;+ deleteDataSource = deleteDataSource;+ saveDataSourceConnection = saveDataSourceConnection;+ updateDataSourceConnection = updateDataSourceConnection;+ deleteDataSourceConnection = deleteDataSourceConnection;+ getDataSourceConnection = getDataSourceConnection;+ getAllDataSourceConnections = getAllDataSourceConnections;+ getDataSourceConnectionsByCategory = getDataSourceConnectionsByCategory;+ getDataSourceConnectionsByType = getDataSourceConnectionsByType;- async saveLLMConfig(config: Omit<LLMConfig, 'created_at' | 'updated_at'>): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO llm_configs (provider, api_key, base_url, model, is_active, updated_at)- VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP)`,- [- config.provider,- config.api_key || null,- config.base_url || null,- config.model,- config.is_active ? 1 : 0,- ]- );+ async getEnabledDataSources(): Promise<DataSource[]> {+ const all = await getAllDataSources();+ return all.filter(ds => ds.enabled);}- async setActiveLLMProvider(provider: string): Promise<void> {- await this.ensureInitialized();-- // Deactivate all- await this.db!.execute('UPDATE llm_configs SET is_active = 0');+ async getDataSourceByAlias(alias: string): Promise<DataSource | null> {+ const all = await getAllDataSources();+ return all.find(ds => ds.alias === alias) || null;+ }- // Activate the selected one- await this.db!.execute(- 'UPDATE llm_configs SET is_active = 1 WHERE provider = $1',- [provider]- );+ async getDataSourcesByType(type: 'websocket' | 'rest_api'): Promise<DataSource[]> {+ const all = await getAllDataSources();+ return all.filter(ds => ds.type === type);}- async ensureDefaultLLMConfigs(): Promise<void> {- await this.ensureInitialized();-- const configs = await this.getLLMConfigs();-- // If no configs exist, create defaults- if (configs.length === 0) {- const defaultConfigs = [- { provider: 'ollama', model: 'llama3.2:3b', base_url: 'http://localhost:11434', is_active: true },- { provider: 'openai', model: 'gpt-4o-mini', is_active: false },- { provider: 'anthropic', model: 'claude-sonnet-4', is_active: false },- { provider: 'google', model: 'gemini-2.0-flash-exp', is_active: false },- { provider: 'groq', model: 'llama-3.1-70b-versatile', is_active: false },- { provider: 'deepseek', model: 'deepseek-chat', base_url: 'https://api.deepseek.com', is_active: false },- { provider: 'xai', model: 'grok-beta', is_active: false },- { provider: 'cohere', model: 'command-r-plus', is_active: false },- { provider: 'mistral', model: 'mistral-large-latest', is_active: false },- { provider: 'together', model: 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo', is_active: false },- { provider: 'fireworks', model: 'accounts/fireworks/models/llama-v3p1-70b-instruct', is_active: false },- { provider: 'openrouter', model: 'meta-llama/llama-3.1-8b-instruct:free', base_url: 'https://openrouter.ai/api/v1', is_active: false },- ];-- for (const config of defaultConfigs) {- await this.saveLLMConfig(config);- }+ async getDataSourcesByProvider(provider: string): Promise<DataSource[]> {+ const all = await getAllDataSources();+ return all.filter(ds => ds.provider === provider);+ }- console.log('[SQLite] Initialized default LLM configurations');+ async toggleDataSourceEnabled(id: string): Promise<{ success: boolean; message: string; enabled: boolean }> {+ const all = await getAllDataSources();+ const source = all.find(ds => ds.id === id);+ if (source) {+ const newEnabled = !source.enabled;+ await saveDataSource({ ...source, enabled: newEnabled });+ return { success: true, message: 'Data source toggled', enabled: newEnabled };}+ return { success: false, message: 'Data source not found', enabled: false };}- async getLLMGlobalSettings(): Promise<LLMGlobalSettings> {- await this.ensureInitialized();- const results = await this.db!.select<LLMGlobalSettings[]>(- 'SELECT temperature, max_tokens, system_prompt FROM llm_global_settings WHERE id = 1'+ async searchDataSources(query: string): Promise<DataSource[]> {+ const all = await getAllDataSources();+ const lowerQuery = query.toLowerCase();+ return all.filter(ds =>+ ds.display_name.toLowerCase().includes(lowerQuery) ||+ ds.alias.toLowerCase().includes(lowerQuery) ||+ ds.provider.toLowerCase().includes(lowerQuery));+ }- return results[0] || {- temperature: 0.7,- max_tokens: 2000,- system_prompt: 'You are a helpful AI assistant specialized in financial analysis and market data.',- };+ async getCachedCategoryData(category: string, maxAgeMinutes: number): Promise<string | null> {+ return await getCachedMarketData('*', category, maxAgeMinutes);}- async saveLLMGlobalSettings(settings: LLMGlobalSettings): Promise<void> {- await this.ensureInitialized();+ // MCP+ addMCPServer = addMCPServer;+ getMCPServers = getMCPServers;+ deleteMCPServer = deleteMCPServer;- await this.db!.execute(- `UPDATE llm_global_settings- SET temperature = $1, max_tokens = $2, system_prompt = $3- WHERE id = 1`,- [settings.temperature, settings.max_tokens, settings.system_prompt]- );+ async getMCPServer(id: string): Promise<MCPServer | null> {+ const all = await getMCPServers();+ return all.find(s => s.id === id) || null;}- // =========================- // LLM MODEL CONFIG METHODS (Multiple models per provider)- // =========================-- async saveLLMModelConfig(config: Omit<LLMModelConfig, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string; id?: string }> {- try {- await this.ensureInitialized();-- const id = config.id || crypto.randomUUID();-- await this.db!.execute(- `INSERT OR REPLACE INTO llm_model_configs- (id, provider, model_id, display_name, api_key, base_url, is_enabled, is_default, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, CURRENT_TIMESTAMP)`,- [- id,- config.provider,- config.model_id,- config.display_name,- config.api_key || null,- config.base_url || null,- config.is_enabled ? 1 : 0,- config.is_default ? 1 : 0,- ]- );-- return { success: true, message: 'LLM model configuration saved', id };- } catch (error) {- console.error('[SQLite] Failed to save LLM model config:', error);- return { success: false, message: 'Failed to save LLM model configuration' };+ async updateMCPServerConfig(id: string, updates: Partial<MCPServer>): Promise<void> {+ const server = await this.getMCPServer(id);+ if (server) {+ await addMCPServer({ ...server, ...updates });}}- async getLLMModelConfigs(): Promise<LLMModelConfig[]> {- await this.ensureInitialized();- return await this.db!.select<LLMModelConfig[]>(- 'SELECT * FROM llm_model_configs ORDER BY provider, display_name'- );+ async updateMCPServerStatus(id: string, status: string): Promise<void> {+ await this.updateMCPServerConfig(id, { status });}- async getLLMModelConfigsByProvider(provider: string): Promise<LLMModelConfig[]> {- await this.ensureInitialized();- return await this.db!.select<LLMModelConfig[]>(- 'SELECT * FROM llm_model_configs WHERE provider = $1 ORDER BY display_name',- [provider]- );+ async cacheMCPTools(serverId: string, tools: any[]): Promise<void> {+ // Not implemented - would need separate table for MCP tools cache+ console.warn('[SqliteService] cacheMCPTools not implemented');}- async getEnabledLLMModelConfigs(): Promise<LLMModelConfig[]> {- await this.ensureInitialized();- return await this.db!.select<LLMModelConfig[]>(- 'SELECT * FROM llm_model_configs WHERE is_enabled = 1 ORDER BY provider, display_name'- );+ async getMCPServerStats(serverId: string): Promise<any> {+ // Not implemented - would need MCP stats table+ return null;}- async getLLMModelConfig(id: string): Promise<LLMModelConfig | null> {- await this.ensureInitialized();- const results = await this.db!.select<LLMModelConfig[]>(- 'SELECT * FROM llm_model_configs WHERE id = $1',- [id]- );- return results[0] || null;- }-- async deleteLLMModelConfig(id: string): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM llm_model_configs WHERE id = $1', [id]);- return { success: true, message: 'LLM model configuration deleted' };- } catch (error) {- console.error('[SQLite] Failed to delete LLM model config:', error);- return { success: false, message: 'Failed to delete LLM model configuration' };- }- }-- async toggleLLMModelConfigEnabled(id: string): Promise<{ success: boolean; enabled: boolean }> {- try {- await this.ensureInitialized();-- const config = await this.getLLMModelConfig(id);- if (!config) {- return { success: false, enabled: false };- }-- const newEnabled = !config.is_enabled;- await this.db!.execute(- 'UPDATE llm_model_configs SET is_enabled = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2',- [newEnabled ? 1 : 0, id]- );-- return { success: true, enabled: newEnabled };- } catch (error) {- console.error('[SQLite] Failed to toggle LLM model config:', error);- return { success: false, enabled: false };- }- }-- async setDefaultLLMModelConfig(id: string, provider: string): Promise<{ success: boolean }> {- try {- await this.ensureInitialized();-- // Remove default from all models of this provider- await this.db!.execute(- 'UPDATE llm_model_configs SET is_default = 0 WHERE provider = $1',- [provider]- );-- // Set the new default- await this.db!.execute(- 'UPDATE llm_model_configs SET is_default = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $1',- [id]- );-- return { success: true };- } catch (error) {- console.error('[SQLite] Failed to set default LLM model:', error);- return { success: false };- }- }-- /**- * Get all configured LLMs with their API keys for Alpha Arena- * Returns models grouped by provider with API keys- */- async getConfiguredLLMsForArena(): Promise<{- provider: string;- api_key: string;- models: { id: string; model_id: string; display_name: string }[];- }[]> {- await this.ensureInitialized();-- // First get from new model configs table- const modelConfigs = await this.getEnabledLLMModelConfigs();-- // Also get from legacy llm_configs table- const legacyConfigs = await this.getLLMConfigs();-- // Combine and group by provider- const providerMap = new Map<string, {- api_key: string;- models: { id: string; model_id: string; display_name: string }[];- }>();-- // Add from new model configs- for (const config of modelConfigs) {- if (!config.api_key) continue;-- if (!providerMap.has(config.provider)) {- providerMap.set(config.provider, {- api_key: config.api_key,- models: []- });- }-- const entry = providerMap.get(config.provider)!;- // Update API key if this one has it- if (config.api_key) {- entry.api_key = config.api_key;- }- entry.models.push({- id: config.id,- model_id: config.model_id,- display_name: config.display_name- });- }-- // Add from legacy configs if not already present- for (const config of legacyConfigs) {- if (!config.api_key) continue;-- if (!providerMap.has(config.provider)) {- providerMap.set(config.provider, {- api_key: config.api_key,- models: [{- id: `legacy_${config.provider}`,- model_id: config.model,- display_name: config.model- }]- });- } else if (providerMap.get(config.provider)!.models.length === 0) {- // Add legacy model if no models from new table- providerMap.get(config.provider)!.models.push({- id: `legacy_${config.provider}`,- model_id: config.model,- display_name: config.model- });- }- }-- // Convert to array- return Array.from(providerMap.entries()).map(([provider, data]) => ({- provider,- ...data- }));- }-- // =========================- // CHAT METHODS- // =========================-- async createChatSession(title: string): Promise<ChatSession> {- await this.ensureInitialized();-- const sessionUuid = crypto.randomUUID();- const timestamp = new Date().toISOString();-- await this.db!.execute(- `INSERT INTO chat_sessions (session_uuid, title, message_count, created_at, updated_at)- VALUES ($1, $2, 0, $3, $4)`,- [sessionUuid, title, timestamp, timestamp]- );-- // Return the full session object- return {- session_uuid: sessionUuid,- title: title,- message_count: 0,- created_at: timestamp,- updated_at: timestamp- };- }-- async getChatSessions(limit: number = 50): Promise<ChatSession[]> {- await this.ensureInitialized();- return await this.db!.select<ChatSession[]>(- `SELECT * FROM chat_sessions ORDER BY updated_at DESC LIMIT $1`,- [limit]- );- }-- async getChatSession(sessionUuid: string): Promise<ChatSession | null> {- await this.ensureInitialized();- const results = await this.db!.select<ChatSession[]>(- 'SELECT * FROM chat_sessions WHERE session_uuid = $1',- [sessionUuid]- );- return results[0] || null;- }-- async updateChatSessionTitle(sessionUuid: string, title: string): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `UPDATE chat_sessions SET title = $1, updated_at = CURRENT_TIMESTAMP WHERE session_uuid = $2`,- [title, sessionUuid]- );- }-- async deleteChatSession(sessionUuid: string): Promise<void> {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM chat_sessions WHERE session_uuid = $1', [sessionUuid]);- }-- async addChatMessage(message: Omit<ChatMessage, 'id' | 'timestamp'>): Promise<ChatMessage> {- await this.ensureInitialized();-- const messageId = crypto.randomUUID();- const timestamp = new Date().toISOString();-- await this.db!.execute(- `INSERT INTO chat_messages (id, session_uuid, role, content, timestamp, provider, model, tokens_used)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,- [- messageId,- message.session_uuid,- message.role,- message.content,- timestamp,- message.provider || null,- message.model || null,- message.tokens_used || null,- ]- );-- // Update message count- await this.db!.execute(- `UPDATE chat_sessions- SET message_count = message_count + 1, updated_at = CURRENT_TIMESTAMP- WHERE session_uuid = $1`,- [message.session_uuid]- );-- // Return the full message object- return {- id: messageId,- session_uuid: message.session_uuid,- role: message.role,- content: message.content,- timestamp: timestamp,- provider: message.provider,- model: message.model,- tokens_used: message.tokens_used,- };- }-- async getChatMessages(sessionUuid: string): Promise<ChatMessage[]> {- await this.ensureInitialized();- return await this.db!.select<ChatMessage[]>(- 'SELECT * FROM chat_messages WHERE session_uuid = $1 ORDER BY timestamp ASC',- [sessionUuid]- );- }-- async deleteChatMessage(id: string): Promise<void> {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM chat_messages WHERE id = $1', [id]);- }-- async clearChatSessionMessages(sessionUuid: string): Promise<void> {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM chat_messages WHERE session_uuid = $1', [sessionUuid]);- await this.db!.execute(- 'UPDATE chat_sessions SET message_count = 0, updated_at = CURRENT_TIMESTAMP WHERE session_uuid = $1',- [sessionUuid]- );- }-- // =========================- // DATA SOURCES METHODS- // =========================-- async saveDataSource(source: Omit<DataSource, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string; id?: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO data_sources- (id, alias, display_name, description, type, provider, category, config, enabled, tags, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, CURRENT_TIMESTAMP)`,- [- source.id,- source.alias,- source.display_name,- source.description || null,- source.type,- source.provider,- source.category || null,- source.config,- source.enabled ? 1 : 0,- source.tags || null,- ]- );- return { success: true, message: 'Data source saved successfully', id: source.id };- } catch (error) {- console.error('[SQLite] Failed to save data source:', error);- return { success: false, message: 'Failed to save data source' };- }- }-- async getAllDataSources(): Promise<DataSource[]> {- await this.ensureInitialized();- return await this.db!.select<DataSource[]>('SELECT * FROM data_sources ORDER BY display_name');- }-- async getDataSourceById(id: string): Promise<DataSource | null> {- await this.ensureInitialized();- const results = await this.db!.select<DataSource[]>(- 'SELECT * FROM data_sources WHERE id = $1',- [id]- );- return results[0] || null;- }-- async getDataSourceByAlias(alias: string): Promise<DataSource | null> {- await this.ensureInitialized();- const results = await this.db!.select<DataSource[]>(- 'SELECT * FROM data_sources WHERE alias = $1',- [alias]- );- return results[0] || null;- }-- async getDataSourcesByType(type: 'websocket' | 'rest_api'): Promise<DataSource[]> {- await this.ensureInitialized();- return await this.db!.select<DataSource[]>(- 'SELECT * FROM data_sources WHERE type = $1',- [type]- );- }-- async getDataSourcesByProvider(provider: string): Promise<DataSource[]> {- await this.ensureInitialized();- return await this.db!.select<DataSource[]>(- 'SELECT * FROM data_sources WHERE provider = $1',- [provider]- );- }-- async getEnabledDataSources(): Promise<DataSource[]> {- await this.ensureInitialized();- return await this.db!.select<DataSource[]>(- 'SELECT * FROM data_sources WHERE enabled = 1'- );- }-- async toggleDataSourceEnabled(id: string): Promise<{ success: boolean; message: string; enabled: boolean }> {- try {- await this.ensureInitialized();-- // Get current state- const source = await this.getDataSourceById(id);- if (!source) {- return { success: false, message: 'Data source not found', enabled: false };- }-- const newEnabledState = !source.enabled;-- await this.db!.execute(- 'UPDATE data_sources SET enabled = NOT enabled, updated_at = CURRENT_TIMESTAMP WHERE id = $1',- [id]- );-- return { success: true, message: `Data source ${newEnabledState ? 'enabled' : 'disabled'}`, enabled: newEnabledState };- } catch (error) {- console.error('[SQLite] Failed to toggle data source:', error);- return { success: false, message: 'Failed to toggle data source', enabled: false };- }- }-- async deleteDataSource(id: string): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM data_sources WHERE id = $1', [id]);- return { success: true, message: 'Data source deleted successfully' };- } catch (error) {- console.error('[SQLite] Failed to delete data source:', error);- return { success: false, message: 'Failed to delete data source' };- }- }-- async searchDataSources(query: string): Promise<DataSource[]> {- await this.ensureInitialized();- const searchPattern = `%${query}%`;- return await this.db!.select<DataSource[]>(- `SELECT * FROM data_sources- WHERE display_name LIKE $1 OR alias LIKE $1 OR provider LIKE $1 OR tags LIKE $1`,- [searchPattern]- );- }-- // =========================- // WS PROVIDER CONFIG METHODS- // =========================-- async saveWSProviderConfig(config: Omit<WSProviderConfig, 'id' | 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO ws_provider_configs- (provider_name, enabled, api_key, api_secret, endpoint, config_data, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP)`,- [- config.provider_name,- config.enabled ? 1 : 0,- config.api_key || null,- config.api_secret || null,- config.endpoint || null,- config.config_data || null,- ]- );- return { success: true, message: 'WebSocket provider configuration saved successfully' };- } catch (error) {- console.error('[SQLite] Failed to save WS provider config:', error);- return { success: false, message: 'Failed to save WebSocket provider configuration' };- }- }-- async getWSProviderConfigs(): Promise<WSProviderConfig[]> {- await this.ensureInitialized();- return await this.db!.select<WSProviderConfig[]>('SELECT * FROM ws_provider_configs ORDER BY provider_name');- }-- async getWSProviderConfig(providerName: string): Promise<WSProviderConfig | null> {- await this.ensureInitialized();- const results = await this.db!.select<WSProviderConfig[]>(- 'SELECT * FROM ws_provider_configs WHERE provider_name = $1',- [providerName]- );- return results[0] || null;- }-- async getEnabledWSProviderConfigs(): Promise<WSProviderConfig[]> {- await this.ensureInitialized();- return await this.db!.select<WSProviderConfig[]>(- 'SELECT * FROM ws_provider_configs WHERE enabled = 1'- );- }-- async toggleWSProviderEnabled(providerName: string): Promise<{ success: boolean; message: string; enabled: boolean }> {- try {- await this.ensureInitialized();-- // Get current state- const config = await this.getWSProviderConfig(providerName);- if (!config) {- return { success: false, message: 'Provider configuration not found', enabled: false };- }-- const newEnabledState = !config.enabled;-- await this.db!.execute(- 'UPDATE ws_provider_configs SET enabled = NOT enabled, updated_at = CURRENT_TIMESTAMP WHERE provider_name = $1',- [providerName]- );-- return { success: true, message: `Provider ${newEnabledState ? 'enabled' : 'disabled'}`, enabled: newEnabledState };- } catch (error) {- console.error('[SQLite] Failed to toggle WS provider:', error);- return { success: false, message: 'Failed to toggle provider', enabled: false };- }- }-- async deleteWSProviderConfig(providerName: string): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM ws_provider_configs WHERE provider_name = $1', [providerName]);- return { success: true, message: 'Provider configuration deleted successfully' };- } catch (error) {- console.error('[SQLite] Failed to delete WS provider config:', error);- return { success: false, message: 'Failed to delete provider configuration' };- }- }-- // =========================- // MCP METHODS- // =========================-- async addMCPServer(server: Omit<MCPServer, 'created_at' | 'updated_at'>): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO mcp_servers- (id, name, description, command, args, env, category, icon, enabled, auto_start, status, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, CURRENT_TIMESTAMP)`,- [- server.id,- server.name,- server.description,- server.command,- server.args,- server.env || null,- server.category,- server.icon,- server.enabled ? 1 : 0,- server.auto_start ? 1 : 0,- server.status,- ]- );- }-- async getMCPServers(): Promise<MCPServer[]> {- await this.ensureInitialized();- return await this.db!.select<MCPServer[]>('SELECT * FROM mcp_servers ORDER BY name');- }-- async getMCPServer(id: string): Promise<MCPServer | null> {- await this.ensureInitialized();- const results = await this.db!.select<MCPServer[]>(- 'SELECT * FROM mcp_servers WHERE id = $1',- [id]- );- return results[0] || null;- }-- async updateMCPServerStatus(id: string, status: string): Promise<void> {- await this.ensureInitialized();- await this.db!.execute(- 'UPDATE mcp_servers SET status = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2',- [status, id]- );- }-- async updateMCPServerConfig(id: string, updates: Partial<MCPServer>): Promise<void> {- await this.ensureInitialized();-- const fields: string[] = [];- const values: any[] = [];- let paramIndex = 1;-- if (updates.name !== undefined) {- fields.push(`name = $${paramIndex++}`);- values.push(updates.name);- }- if (updates.description !== undefined) {- fields.push(`description = $${paramIndex++}`);- values.push(updates.description);- }- if (updates.command !== undefined) {- fields.push(`command = $${paramIndex++}`);- values.push(updates.command);- }- if (updates.args !== undefined) {- fields.push(`args = $${paramIndex++}`);- values.push(updates.args);- }- if (updates.env !== undefined) {- fields.push(`env = $${paramIndex++}`);- values.push(updates.env);- }- if (updates.category !== undefined) {- fields.push(`category = $${paramIndex++}`);- values.push(updates.category);- }- if (updates.icon !== undefined) {- fields.push(`icon = $${paramIndex++}`);- values.push(updates.icon);- }- if (updates.enabled !== undefined) {- fields.push(`enabled = $${paramIndex++}`);- values.push(updates.enabled ? 1 : 0);- }- if (updates.auto_start !== undefined) {- fields.push(`auto_start = $${paramIndex++}`);- values.push(updates.auto_start ? 1 : 0);- }-- if (fields.length === 0) return;-- fields.push(`updated_at = CURRENT_TIMESTAMP`);- values.push(id);-- const sql = `UPDATE mcp_servers SET ${fields.join(', ')} WHERE id = $${paramIndex}`;- await this.db!.execute(sql, values);- }-- async deleteMCPServer(id: string): Promise<void> {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM mcp_servers WHERE id = $1', [id]);+ async logMCPToolUsage(params: { serverId: string; toolName: string; args: string; result: string | null; success: boolean; executionTime: number; errorMessage?: string }): Promise<void> {+ // Not implemented - would need MCP usage logs table+ console.warn('[SqliteService] logMCPToolUsage not implemented');}async getAutoStartServers(): Promise<MCPServer[]> {- await this.ensureInitialized();- return await this.db!.select<MCPServer[]>(- 'SELECT * FROM mcp_servers WHERE auto_start = 1 AND enabled = 1'- );- }-- async cacheMCPTools(serverId: string, tools: any[]): Promise<void> {- await this.ensureInitialized();-- // Delete existing tools for this server- await this.db!.execute('DELETE FROM mcp_tools WHERE server_id = $1', [serverId]);-- // Insert new tools- for (const tool of tools) {- await this.db!.execute(- `INSERT INTO mcp_tools (id, server_id, name, description, input_schema)- VALUES ($1, $2, $3, $4, $5)`,- [- `${serverId}_${tool.name}`,- serverId,- tool.name,- tool.description || null,- tool.inputSchema ? JSON.stringify(tool.inputSchema) : null- ]- );- }- }-- async getMCPServerStats(serverId: string): Promise<{ toolCount: number; callsToday: number; lastUsed: string | null }> {- await this.ensureInitialized();-- // Get tool count- const toolCountResult = await this.db!.select<{ count: number }[]>(- 'SELECT COUNT(*) as count FROM mcp_tools WHERE server_id = $1',- [serverId]- );- const toolCount = toolCountResult[0]?.count || 0;-- // Get calls today- const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD- const callsTodayResult = await this.db!.select<{ count: number }[]>(- `SELECT COUNT(*) as count FROM mcp_tool_usage_logs- WHERE server_id = $1 AND DATE(timestamp) = $2`,- [serverId, today]- );- const callsToday = callsTodayResult[0]?.count || 0;-- // Get last used timestamp- const lastUsedResult = await this.db!.select<{ timestamp: string }[]>(- `SELECT timestamp FROM mcp_tool_usage_logs- WHERE server_id = $1 ORDER BY timestamp DESC LIMIT 1`,- [serverId]- );- const lastUsed = lastUsedResult[0]?.timestamp || null;-- return {- toolCount,- callsToday,- lastUsed- };- }-- async logMCPToolUsage(log: {- serverId: string;- toolName: string;- args: string;- result: string | null;- success: boolean;- executionTime: number;- error?: string;- }): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT INTO mcp_tool_usage_logs (server_id, tool_name, args, result, success, execution_time, error)- VALUES ($1, $2, $3, $4, $5, $6, $7)`,- [- log.serverId,- log.toolName,- log.args,- log.result,- log.success ? 1 : 0,- log.executionTime,- log.error || null- ]- );+ const all = await getMCPServers();+ return all.filter(s => s.auto_start && s.enabled);}async getMCPTools(): Promise<any[]> {- await this.ensureInitialized();- return await this.db!.select<any[]>(- 'SELECT * FROM mcp_tools ORDER BY name'- );- }-- async getMCPToolsByServer(serverId: string): Promise<any[]> {- await this.ensureInitialized();- return await this.db!.select<any[]>(- 'SELECT * FROM mcp_tools WHERE server_id = $1 ORDER BY name',- [serverId]- );- }-- // =========================- // MARKET DATA CACHE METHODS- // =========================-- async saveMarketDataCache(symbol: string, category: string, quoteData: any): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO market_data_cache (symbol, category, quote_data, cached_at)- VALUES ($1, $2, $3, CURRENT_TIMESTAMP)`,- [symbol, category, JSON.stringify(quoteData)]- );- }-- async getCachedMarketData(symbol: string, category: string, maxAgeMinutes: number = 5): Promise<any | null> {- await this.ensureInitialized();-- const results = await this.db!.select<{ quote_data: string; cached_at: string }[]>(- `SELECT quote_data, cached_at FROM market_data_cache- WHERE symbol = $1 AND category = $2- AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`,- [symbol, category]- );-- if (!results[0]) return null;-- return JSON.parse(results[0].quote_data);- }-- async clearMarketDataCache(): Promise<void> {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM market_data_cache');- }-- async clearExpiredMarketCache(maxAgeMinutes: number = 60): Promise<void> {- await this.ensureInitialized();- await this.db!.execute(- `DELETE FROM market_data_cache- WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`- );- }-- async getCachedCategoryData(category: string, symbols: string[], maxAgeMinutes: number = 5): Promise<Map<string, any>> {- await this.ensureInitialized();-- const result = new Map<string, any>();-- try {- // Build placeholders using $ syntax- const placeholders = symbols.map((_, i) => `$${i + 1}`).join(',');- const categoryParam = symbols.length + 1;-- const results = await this.db!.select<{ symbol: string; quote_data: string; cached_at: string }[]>(- `SELECT symbol, quote_data, cached_at FROM market_data_cache- WHERE symbol IN (${placeholders}) AND category = $${categoryParam}- AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`,- [...symbols, category]- );-- for (const row of results) {- result.set(row.symbol, JSON.parse(row.quote_data));- }- } catch (error) {- console.error('[SQLite] Error getting cached category data:', error);- }-- return result;- }-- // =========================- // DATA SOURCE CONNECTIONS METHODS- // =========================-- async saveDataSourceConnection(connection: {- id: string;- name: string;- type: string;- category: string;- config: string;- status: string;- lastTested?: string;- errorMessage?: string;- }): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO data_source_connections- (id, name, type, category, config, status, updated_at, last_tested, error_message)- VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP, $7, $8)`,- [- connection.id,- connection.name,- connection.type,- connection.category,- connection.config,- connection.status,- connection.lastTested || null,- connection.errorMessage || null,- ]- );- }-- async getDataSourceConnection(id: string): Promise<any | null> {- await this.ensureInitialized();- const results = await this.db!.select<any[]>(- 'SELECT * FROM data_source_connections WHERE id = $1',- [id]- );- return results[0] || null;- }-- async getAllDataSourceConnections(): Promise<any[]> {- await this.ensureInitialized();- return await this.db!.select<any[]>(- 'SELECT * FROM data_source_connections ORDER BY created_at DESC'- );- }-- async getDataSourceConnectionsByCategory(category: string): Promise<any[]> {- await this.ensureInitialized();- return await this.db!.select<any[]>(- 'SELECT * FROM data_source_connections WHERE category = $1 ORDER BY created_at DESC',- [category]- );- }-- async getDataSourceConnectionsByType(type: string): Promise<any[]> {- await this.ensureInitialized();- return await this.db!.select<any[]>(- 'SELECT * FROM data_source_connections WHERE type = $1',- [type]- );- }-- async updateDataSourceConnection(- id: string,- updates: {- name?: string;- config?: string;- status?: string;- lastTested?: string;- errorMessage?: string;- }- ): Promise<void> {- await this.ensureInitialized();-- const fields: string[] = [];- const values: any[] = [];- let paramIndex = 1;-- if (updates.name !== undefined) {- fields.push(`name = $${paramIndex++}`);- values.push(updates.name);- }- if (updates.config !== undefined) {- fields.push(`config = $${paramIndex++}`);- values.push(updates.config);- }- if (updates.status !== undefined) {- fields.push(`status = $${paramIndex++}`);- values.push(updates.status);- }- if (updates.lastTested !== undefined) {- fields.push(`last_tested = $${paramIndex++}`);- values.push(updates.lastTested);- }- if (updates.errorMessage !== undefined) {- fields.push(`error_message = $${paramIndex++}`);- values.push(updates.errorMessage);- }-- if (fields.length === 0) return;-- fields.push(`updated_at = CURRENT_TIMESTAMP`);- values.push(id);-- const sql = `UPDATE data_source_connections SET ${fields.join(', ')} WHERE id = $${paramIndex}`;- await this.db!.execute(sql, values);- }-- async deleteDataSourceConnection(id: string): Promise<void> {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM data_source_connections WHERE id = $1', [id]);- }-- // =========================- // FORUM CACHE METHODS- // =========================-- /**- * Cache forum categories- */- async cacheForumCategories(categories: any[]): Promise<void> {- await this.ensureInitialized();- await this.db!.execute(- `INSERT OR REPLACE INTO forum_categories_cache (id, data, cached_at)- VALUES (1, $1, CURRENT_TIMESTAMP)`,- [JSON.stringify(categories)]- );- }-- /**- * Get cached forum categories- */- async getCachedForumCategories(maxAgeMinutes: number = 5): Promise<any[] | null> {- await this.ensureInitialized();-- const results = await this.db!.select<{ data: string; cached_at: string }[]>(- `SELECT data, cached_at FROM forum_categories_cache- WHERE id = 1- AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`- );-- if (!results[0]) return null;-- return JSON.parse(results[0].data);- }-- /**- * Cache forum posts by category and sort type- */- async cacheForumPosts(categoryId: number | null, sortBy: string, posts: any[]): Promise<void> {- await this.ensureInitialized();-- const cacheKey = `${categoryId || 'all'}_${sortBy}`;- await this.db!.execute(- `INSERT OR REPLACE INTO forum_posts_cache (cache_key, category_id, sort_by, data, cached_at)- VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)`,- [cacheKey, categoryId, sortBy, JSON.stringify(posts)]- );- }-- /**- * Get cached forum posts- */- async getCachedForumPosts(categoryId: number | null, sortBy: string, maxAgeMinutes: number = 5): Promise<any[] | null> {- await this.ensureInitialized();-- const cacheKey = `${categoryId || 'all'}_${sortBy}`;- const results = await this.db!.select<{ data: string; cached_at: string }[]>(- `SELECT data, cached_at FROM forum_posts_cache- WHERE cache_key = $1- AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`,- [cacheKey]- );-- if (!results[0]) return null;-- return JSON.parse(results[0].data);- }-- /**- * Cache forum statistics- */- async cacheForumStats(stats: any): Promise<void> {- await this.ensureInitialized();- await this.db!.execute(- `INSERT OR REPLACE INTO forum_stats_cache (id, data, cached_at)- VALUES (1, $1, CURRENT_TIMESTAMP)`,- [JSON.stringify(stats)]- );- }-- /**- * Get cached forum statistics- */- async getCachedForumStats(maxAgeMinutes: number = 5): Promise<any | null> {- await this.ensureInitialized();-- const results = await this.db!.select<{ data: string; cached_at: string }[]>(- `SELECT data, cached_at FROM forum_stats_cache- WHERE id = 1- AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`- );-- if (!results[0]) return null;-- return JSON.parse(results[0].data);- }-- /**- * Cache forum post details with comments- */- async cacheForumPostDetails(postUuid: string, post: any, comments: any[]): Promise<void> {- await this.ensureInitialized();- await this.db!.execute(- `INSERT OR REPLACE INTO forum_post_details_cache (post_uuid, data, comments_data, cached_at)- VALUES ($1, $2, $3, CURRENT_TIMESTAMP)`,- [postUuid, JSON.stringify(post), JSON.stringify(comments)]- );- }-- /**- * Get cached forum post details- */- async getCachedForumPostDetails(postUuid: string, maxAgeMinutes: number = 5): Promise<{ post: any; comments: any[] } | null> {- await this.ensureInitialized();-- const results = await this.db!.select<{ data: string; comments_data: string; cached_at: string }[]>(- `SELECT data, comments_data, cached_at FROM forum_post_details_cache- WHERE post_uuid = $1- AND datetime(cached_at) >= datetime('now', '-${maxAgeMinutes} minutes')`,- [postUuid]- );-- if (!results[0]) return null;-- return {- post: JSON.parse(results[0].data),- comments: JSON.parse(results[0].comments_data)- };- }-- /**- * Clear all forum cache- */- async clearForumCache(): Promise<void> {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM forum_categories_cache');- await this.db!.execute('DELETE FROM forum_posts_cache');- await this.db!.execute('DELETE FROM forum_stats_cache');- await this.db!.execute('DELETE FROM forum_post_details_cache');- }-- /**- * Clear expired forum cache- */- async clearExpiredForumCache(maxAgeMinutes: number = 60): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `DELETE FROM forum_categories_cache- WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`- );-- await this.db!.execute(- `DELETE FROM forum_posts_cache- WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`- );-- await this.db!.execute(- `DELETE FROM forum_stats_cache- WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`- );-- await this.db!.execute(- `DELETE FROM forum_post_details_cache- WHERE datetime(cached_at) < datetime('now', '-${maxAgeMinutes} minutes')`- );- }-- // =========================- // CONTEXT RECORDING METHODS- // =========================-- /**- * Save recorded context data- */- async saveRecordedContext(context: Omit<RecordedContext, 'created_at'>): Promise<void> {- await this.ensureInitialized();-- const dataSize = new TextEncoder().encode(context.raw_data).length;-- await this.db!.execute(- `INSERT INTO recorded_contexts (id, tab_name, data_type, label, raw_data, metadata, data_size, tags)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,- [- context.id,- context.tab_name,- context.data_type,- context.label || null,- context.raw_data,- context.metadata || null,- dataSize,- context.tags || null- ]- );- }-- /**- * Get all recorded contexts with optional filters- */- async getRecordedContexts(filters?: {- tabName?: string;- dataType?: string;- tags?: string[];- limit?: number;- }): Promise<RecordedContext[]> {- await this.ensureInitialized();-- let sql = 'SELECT * FROM recorded_contexts WHERE 1=1';- const params: any[] = [];- let paramIndex = 1;-- if (filters?.tabName) {- sql += ` AND tab_name = $${paramIndex++}`;- params.push(filters.tabName);- }-- if (filters?.dataType) {- sql += ` AND data_type = $${paramIndex++}`;- params.push(filters.dataType);- }-- if (filters?.tags && filters.tags.length > 0) {- const tagConditions = filters.tags.map(() => `tags LIKE $${paramIndex++}`).join(' OR ');- sql += ` AND (${tagConditions})`;- params.push(...filters.tags.map(tag => `%${tag}%`));- }-- sql += ' ORDER BY created_at DESC';-- if (filters?.limit) {- sql += ` LIMIT $${paramIndex}`;- params.push(filters.limit);- }-- return await this.db!.select<RecordedContext[]>(sql, params);- }-- /**- * Get context by ID- */- async getRecordedContext(id: string): Promise<RecordedContext | null> {- await this.ensureInitialized();-- const results = await this.db!.select<RecordedContext[]>(- 'SELECT * FROM recorded_contexts WHERE id = $1',- [id]- );-- return results[0] || null;- }-- /**- * Delete recorded context- */- async deleteRecordedContext(id: string): Promise<void> {- await this.ensureInitialized();- await this.db!.execute('DELETE FROM recorded_contexts WHERE id = $1', [id]);- }-- /**- * Clear old contexts- */- async clearOldContexts(maxAgeDays: number): Promise<void> {- await this.ensureInitialized();- await this.db!.execute(- `DELETE FROM recorded_contexts- WHERE datetime(created_at) < datetime('now', '-${maxAgeDays} days')`- );- }-- /**- * Get storage statistics- */- async getContextStorageStats(): Promise<{ count: number; totalSize: number }> {- await this.ensureInitialized();-- const result = await this.db!.select<{ count: number; total_size: number }[]>(- 'SELECT COUNT(*) as count, SUM(data_size) as total_size FROM recorded_contexts'- );-- return {- count: result[0]?.count || 0,- totalSize: result[0]?.total_size || 0- };- }-- /**- * Start recording session- */- async startRecordingSession(session: Omit<RecordingSession, 'started_at'>): Promise<void> {- await this.ensureInitialized();-- // End any existing active session for this tab- await this.db!.execute(- `UPDATE recording_sessions SET is_active = 0, ended_at = CURRENT_TIMESTAMP- WHERE tab_name = $1 AND is_active = 1`,- [session.tab_name]- );-- // Start new session- await this.db!.execute(- `INSERT INTO recording_sessions (id, tab_name, is_active, auto_record, filters)- VALUES ($1, $2, $3, $4, $5)`,- [- session.id,- session.tab_name,- session.is_active ? 1 : 0,- session.auto_record ? 1 : 0,- session.filters || null- ]- );- }-- /**- * Get active recording session for tab- */- async getActiveRecordingSession(tabName: string): Promise<RecordingSession | null> {- await this.ensureInitialized();-- const results = await this.db!.select<RecordingSession[]>(- 'SELECT * FROM recording_sessions WHERE tab_name = $1 AND is_active = 1 LIMIT 1',- [tabName]- );-- return results[0] || null;- }-- /**- * Stop recording session- */- async stopRecordingSession(tabName: string): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `UPDATE recording_sessions SET is_active = 0, ended_at = CURRENT_TIMESTAMP- WHERE tab_name = $1 AND is_active = 1`,- [tabName]- );- }-- /**- * Link context to chat session- */- async linkContextToChat(chatSessionUuid: string, contextId: string): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO chat_context_links (chat_session_uuid, context_id)- VALUES ($1, $2)`,- [chatSessionUuid, contextId]- );- }-- /**- * Unlink context from chat session- */- async unlinkContextFromChat(chatSessionUuid: string, contextId: string): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- 'DELETE FROM chat_context_links WHERE chat_session_uuid = $1 AND context_id = $2',- [chatSessionUuid, contextId]- );- }-- /**- * Get active contexts for chat session- */- async getChatContexts(chatSessionUuid: string): Promise<RecordedContext[]> {- await this.ensureInitialized();-- return await this.db!.select<RecordedContext[]>(- `SELECT rc.* FROM recorded_contexts rc- INNER JOIN chat_context_links ccl ON rc.id = ccl.context_id- WHERE ccl.chat_session_uuid = $1 AND ccl.is_active = 1- ORDER BY ccl.added_at DESC`,- [chatSessionUuid]- );- }-- /**- * Toggle context active state in chat- */- async toggleChatContextActive(chatSessionUuid: string, contextId: string): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `UPDATE chat_context_links SET is_active = NOT is_active- WHERE chat_session_uuid = $1 AND context_id = $2`,- [chatSessionUuid, contextId]- );- }-- // =========================- // BACKTESTING METHODS- // =========================-- async saveBacktestingProvider(provider: Omit<BacktestingProvider, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO backtesting_providers (id, name, adapter_type, config, enabled, is_active, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP)`,- [provider.id, provider.name, provider.adapter_type, provider.config, provider.enabled ? 1 : 0, provider.is_active ? 1 : 0]- );-- return { success: true, message: 'Backtesting provider saved successfully' };- } catch (error) {- console.error('[SQLite] Failed to save backtesting provider:', error);- return { success: false, message: 'Failed to save backtesting provider' };- }- }-- async getBacktestingProviders(): Promise<BacktestingProvider[]> {- await this.ensureInitialized();- return await this.db!.select<BacktestingProvider[]>('SELECT * FROM backtesting_providers ORDER BY name');- }-- async getBacktestingProvider(name: string): Promise<BacktestingProvider | null> {- await this.ensureInitialized();- const results = await this.db!.select<BacktestingProvider[]>(- 'SELECT * FROM backtesting_providers WHERE name = $1',- [name]- );- return results[0] || null;- }-- async getActiveBacktestingProvider(): Promise<BacktestingProvider | null> {- await this.ensureInitialized();- const results = await this.db!.select<BacktestingProvider[]>(- 'SELECT * FROM backtesting_providers WHERE is_active = 1 LIMIT 1'- );- return results[0] || null;- }-- async setActiveBacktestingProvider(name: string): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- // Deactivate all providers first- await this.db!.execute('UPDATE backtesting_providers SET is_active = 0');-- // Activate the specified provider- await this.db!.execute(- 'UPDATE backtesting_providers SET is_active = 1, updated_at = CURRENT_TIMESTAMP WHERE name = $1',- [name]- );-- return { success: true, message: `Activated backtesting provider: ${name}` };- } catch (error) {- console.error('[SQLite] Failed to set active provider:', error);- return { success: false, message: 'Failed to set active provider' };- }- }-- async deleteBacktestingProvider(name: string): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- 'DELETE FROM backtesting_providers WHERE name = $1',- [name]- );-- return { success: true, message: 'Provider deleted successfully' };- } catch (error) {- console.error('[SQLite] Failed to delete provider:', error);- return { success: false, message: 'Failed to delete provider' };- }- }-- async saveBacktestingStrategy(strategy: Omit<BacktestingStrategy, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT OR REPLACE INTO backtesting_strategies- (id, name, description, version, author, provider_type, strategy_type, strategy_definition, tags, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, CURRENT_TIMESTAMP)`,- [- strategy.id,- strategy.name,- strategy.description || null,- strategy.version,- strategy.author || null,- strategy.provider_type,- strategy.strategy_type,- strategy.strategy_definition,- strategy.tags || null,- ]- );-- return { success: true, message: 'Strategy saved successfully' };- } catch (error) {- console.error('[SQLite] Failed to save strategy:', error);- return { success: false, message: 'Failed to save strategy' };- }- }-- async getBacktestingStrategies(): Promise<BacktestingStrategy[]> {- await this.ensureInitialized();- return await this.db!.select<BacktestingStrategy[]>('SELECT * FROM backtesting_strategies ORDER BY updated_at DESC');- }-- async getBacktestingStrategy(id: string): Promise<BacktestingStrategy | null> {- await this.ensureInitialized();- const results = await this.db!.select<BacktestingStrategy[]>(- 'SELECT * FROM backtesting_strategies WHERE id = $1',- [id]- );- return results[0] || null;- }-- async getBacktestingStrategiesByProvider(providerType: string): Promise<BacktestingStrategy[]> {- await this.ensureInitialized();- return await this.db!.select<BacktestingStrategy[]>(- 'SELECT * FROM backtesting_strategies WHERE provider_type = $1 ORDER BY updated_at DESC',- [providerType]- );- }-- async deleteBacktestingStrategy(id: string): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- 'DELETE FROM backtesting_strategies WHERE id = $1',- [id]- );-- return { success: true, message: 'Strategy deleted successfully' };- } catch (error) {- console.error('[SQLite] Failed to delete strategy:', error);- return { success: false, message: 'Failed to delete strategy' };+ // Stub - not implemented+ console.warn('[SqliteService] getMCPTools not implemented');+ return [];+ }++ // Backtesting+ saveBacktestingProvider = saveBacktestingProvider;+ getBacktestingProviders = getBacktestingProviders;+ saveBacktestingStrategy = saveBacktestingStrategy;+ getBacktestingStrategies = getBacktestingStrategies;+ saveBacktestRun = saveBacktestRun;+ getBacktestRuns = getBacktestRuns;++ async setActiveBacktestingProvider(id: string): Promise<void> {+ const providers = await getBacktestingProviders();+ for (const provider of providers) {+ await saveBacktestingProvider({+ ...provider,+ is_active: provider.id === id+ });}}- async saveBacktestRun(run: Omit<BacktestRun, 'created_at' | 'completed_at' | 'duration_seconds'>): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT INTO backtest_runs- (id, strategy_id, provider_name, config, results, status, performance_metrics, error_message)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,- [- run.id,- run.strategy_id || null,- run.provider_name,- run.config,- run.results || null,- run.status,- run.performance_metrics || null,- run.error_message || null,- ]- );-- return { success: true, message: 'Backtest run saved successfully' };- } catch (error) {- console.error('[SQLite] Failed to save backtest run:', error);- return { success: false, message: 'Failed to save backtest run' };- }+ async deleteBacktestingProvider(id: string): Promise<void> {+ // Not implemented in Rust - would need to add delete command+ console.warn('[SqliteService] deleteBacktestingProvider not implemented');}- async updateBacktestRun(id: string, updates: Partial<BacktestRun>): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- const fields: string[] = [];- const values: any[] = [];-- if (updates.results !== undefined) {- fields.push('results = $' + (values.length + 1));- values.push(updates.results);- }- if (updates.status !== undefined) {- fields.push('status = $' + (values.length + 1));- values.push(updates.status);- }- if (updates.performance_metrics !== undefined) {- fields.push('performance_metrics = $' + (values.length + 1));- values.push(updates.performance_metrics);- }- if (updates.error_message !== undefined) {- fields.push('error_message = $' + (values.length + 1));- values.push(updates.error_message);- }- if (updates.completed_at !== undefined) {- fields.push('completed_at = $' + (values.length + 1));- values.push(updates.completed_at);- }- if (updates.duration_seconds !== undefined) {- fields.push('duration_seconds = $' + (values.length + 1));- values.push(updates.duration_seconds);- }-- if (fields.length === 0) {- return { success: true, message: 'No updates to apply' };- }+ // Context Recording+ saveRecordedContext = saveRecordedContext;+ getRecordedContexts = getRecordedContexts;+ deleteRecordedContext = deleteRecordedContext;+ startRecordingSession = startRecordingSession;+ stopRecordingSession = stopRecordingSession;+ getActiveRecordingSession = getActiveRecordingSession;+ getRecordedContext = getRecordedContext;+ linkContextToChat = linkContextToChat;+ unlinkContextFromChat = unlinkContextFromChat;+ getChatContexts = getChatContexts;+ toggleChatContextActive = toggleChatContextActive;+ clearOldContexts = clearOldContexts;+ getContextStorageStats = getContextStorageStats;- values.push(id);- await this.db!.execute(- `UPDATE backtest_runs SET ${fields.join(', ')} WHERE id = $${values.length}`,- values- );+ // Cache+ saveMarketDataCache = saveMarketDataCache;+ getCachedMarketData = getCachedMarketData;+ clearMarketDataCache = clearMarketDataCache;+ getCachedForumCategories = getCachedForumCategories;+ cacheForumCategories = cacheForumCategories;+ getCachedForumPosts = getCachedForumPosts;+ cacheForumPosts = cacheForumPosts;+ getCachedForumStats = getCachedForumStats;+ cacheForumStats = cacheForumStats;- return { success: true, message: 'Backtest run updated successfully' };- } catch (error) {- console.error('[SQLite] Failed to update backtest run:', error);- return { success: false, message: 'Failed to update backtest run' };- }- }+ // Paper Trading+ createPortfolio = createPortfolio;+ getPortfolio = getPortfolio;+ listPortfolios = listPortfolios;+ updatePortfolioBalance = updatePortfolioBalance;+ createPosition = createPosition;+ getPortfolioPositions = getPortfolioPositions;+ createOrder = createOrder;+ getPortfolioOrders = getPortfolioOrders;+ getPortfolioTrades = getPortfolioTrades;- async getBacktestRuns(limit?: number): Promise<BacktestRun[]> {- await this.ensureInitialized();- const sql = limit- ? `SELECT * FROM backtest_runs ORDER BY created_at DESC LIMIT ${limit}`- : 'SELECT * FROM backtest_runs ORDER BY created_at DESC';- return await this.db!.select<BacktestRun[]>(sql);+ // WebSocket Provider Configs (not in Rust backend yet)+ async getWSProviderConfigs(): Promise<any[]> {+ // Not implemented - return empty array+ console.warn('[SqliteService] getWSProviderConfigs not implemented in Rust backend');+ return [];}- async getBacktestRun(id: string): Promise<BacktestRun | null> {- await this.ensureInitialized();- const results = await this.db!.select<BacktestRun[]>(- 'SELECT * FROM backtest_runs WHERE id = $1',- [id]- );- return results[0] || null;+ async saveWSProviderConfig(config: any): Promise<{ success: boolean; message: string }> {+ console.warn('[SqliteService] saveWSProviderConfig not implemented in Rust backend');+ return { success: false, message: 'Not implemented' };}- async getBacktestRunsByStrategy(strategyId: string): Promise<BacktestRun[]> {- await this.ensureInitialized();- return await this.db!.select<BacktestRun[]>(- 'SELECT * FROM backtest_runs WHERE strategy_id = $1 ORDER BY created_at DESC',- [strategyId]- );- }-- async getBacktestRunsByProvider(providerName: string): Promise<BacktestRun[]> {- await this.ensureInitialized();- return await this.db!.select<BacktestRun[]>(- 'SELECT * FROM backtest_runs WHERE provider_name = $1 ORDER BY created_at DESC',- [providerName]- );+ async deleteWSProviderConfig(id: number | string): Promise<{ success: boolean; message: string }> {+ console.warn('[SqliteService] deleteWSProviderConfig not implemented in Rust backend');+ return { success: false, message: 'Not implemented' };}- async deleteBacktestRun(id: string): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- 'DELETE FROM backtest_runs WHERE id = $1',- [id]- );-- return { success: true, message: 'Backtest run deleted successfully' };- } catch (error) {- console.error('[SQLite] Failed to delete backtest run:', error);- return { success: false, message: 'Failed to delete backtest run' };- }+ async toggleWSProviderEnabled(id: number | string): Promise<{ success: boolean; message: string; enabled: boolean }> {+ console.warn('[SqliteService] toggleWSProviderEnabled not implemented in Rust backend');+ return { success: false, message: 'Not implemented', enabled: false };}- async saveOptimizationRun(run: Omit<OptimizationRun, 'created_at' | 'completed_at' | 'duration_seconds'>): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT INTO optimization_runs- (id, strategy_id, provider_name, parameter_grid, objective, best_parameters, best_result, all_results, iterations, status, error_message)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,- [- run.id,- run.strategy_id || null,- run.provider_name,- run.parameter_grid,- run.objective,- run.best_parameters || null,- run.best_result || null,- run.all_results || null,- run.iterations || null,- run.status,- run.error_message || null,- ]- );-- return { success: true, message: 'Optimization run saved successfully' };- } catch (error) {- console.error('[SQLite] Failed to save optimization run:', error);- return { success: false, message: 'Failed to save optimization run' };- }+ async getWSProviderConfig(id: string): Promise<any | null> {+ console.warn('[SqliteService] getWSProviderConfig not implemented in Rust backend');+ return null;}- async updateOptimizationRun(id: string, updates: Partial<OptimizationRun>): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- const fields: string[] = [];- const values: any[] = [];-- if (updates.best_parameters !== undefined) {- fields.push('best_parameters = $' + (values.length + 1));- values.push(updates.best_parameters);- }- if (updates.best_result !== undefined) {- fields.push('best_result = $' + (values.length + 1));- values.push(updates.best_result);- }- if (updates.all_results !== undefined) {- fields.push('all_results = $' + (values.length + 1));- values.push(updates.all_results);- }- if (updates.iterations !== undefined) {- fields.push('iterations = $' + (values.length + 1));- values.push(updates.iterations);- }- if (updates.status !== undefined) {- fields.push('status = $' + (values.length + 1));- values.push(updates.status);- }- if (updates.error_message !== undefined) {- fields.push('error_message = $' + (values.length + 1));- values.push(updates.error_message);- }- if (updates.completed_at !== undefined) {- fields.push('completed_at = $' + (values.length + 1));- values.push(updates.completed_at);- }- if (updates.duration_seconds !== undefined) {- fields.push('duration_seconds = $' + (values.length + 1));- values.push(updates.duration_seconds);- }-- if (fields.length === 0) {- return { success: true, message: 'No updates to apply' };+ // API Keys helper methods+ async getAllApiKeys(): Promise<ApiKeys> {+ const settings = await getAllSettings();+ const apiKeys: ApiKeys = {};+ for (const predefinedKey of PREDEFINED_API_KEYS) {+ const setting = settings.find(s => s.setting_key === predefinedKey.key);+ if (setting) {+ apiKeys[predefinedKey.key] = setting.setting_value;}-- values.push(id);- await this.db!.execute(- `UPDATE optimization_runs SET ${fields.join(', ')} WHERE id = $${values.length}`,- values- );-- return { success: true, message: 'Optimization run updated successfully' };- } catch (error) {- console.error('[SQLite] Failed to update optimization run:', error);- return { success: false, message: 'Failed to update optimization run' };- }- }-- async getOptimizationRuns(limit?: number): Promise<OptimizationRun[]> {- await this.ensureInitialized();- const sql = limit- ? `SELECT * FROM optimization_runs ORDER BY created_at DESC LIMIT ${limit}`- : 'SELECT * FROM optimization_runs ORDER BY created_at DESC';- return await this.db!.select<OptimizationRun[]>(sql);- }-- async getOptimizationRun(id: string): Promise<OptimizationRun | null> {- await this.ensureInitialized();- const results = await this.db!.select<OptimizationRun[]>(- 'SELECT * FROM optimization_runs WHERE id = $1',- [id]- );- return results[0] || null;- }-- async deleteOptimizationRun(id: string): Promise<{ success: boolean; message: string }> {- try {- await this.ensureInitialized();-- await this.db!.execute(- 'DELETE FROM optimization_runs WHERE id = $1',- [id]- );-- return { success: true, message: 'Optimization run deleted successfully' };- } catch (error) {- console.error('[SQLite] Failed to delete optimization run:', error);- return { success: false, message: 'Failed to delete optimization run' };- }- }-- // ==================== ALPHA ARENA METHODS ====================-- /**- * Create a new Alpha Arena competition- */- async createAlphaCompetition(competition: Omit<AlphaCompetition, 'created_at' | 'updated_at'>): Promise<AlphaCompetition> {- await this.ensureInitialized();-- const now = new Date().toISOString();- const comp: AlphaCompetition = {- ...competition,- created_at: now,- updated_at: now- };-- await this.db!.execute(- `INSERT INTO alpha_competitions- (id, name, symbol, mode, status, cycle_count, cycle_interval_seconds, initial_capital, created_at, started_at, ended_at, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,- [comp.id, comp.name, comp.symbol, comp.mode, comp.status, comp.cycle_count, comp.cycle_interval_seconds, comp.initial_capital, comp.created_at, comp.started_at, comp.ended_at, comp.updated_at]- );-- return comp;- }-- /**- * Get all competitions- */- async getAlphaCompetitions(limit?: number): Promise<AlphaCompetition[]> {- await this.ensureInitialized();- const sql = limit- ? 'SELECT * FROM alpha_competitions ORDER BY created_at DESC LIMIT $1'- : 'SELECT * FROM alpha_competitions ORDER BY created_at DESC';- return limit ? await this.db!.select(sql, [limit]) : await this.db!.select(sql);- }-- /**- * Get a specific competition by ID- */- async getAlphaCompetition(id: string): Promise<AlphaCompetition | null> {- await this.ensureInitialized();- const results = await this.db!.select<AlphaCompetition[]>(- 'SELECT * FROM alpha_competitions WHERE id = $1',- [id]- );- return results[0] || null;- }-- /**- * Update competition status and metadata- */- async updateAlphaCompetition(id: string, updates: Partial<Omit<AlphaCompetition, 'id' | 'created_at'>>): Promise<void> {- await this.ensureInitialized();-- const fields: string[] = [];- const values: any[] = [];- let paramIndex = 1;-- Object.entries(updates).forEach(([key, value]) => {- fields.push(`${key} = $${paramIndex}`);- values.push(value);- paramIndex++;- });-- fields.push(`updated_at = $${paramIndex}`);- values.push(new Date().toISOString());- values.push(id);-- await this.db!.execute(- `UPDATE alpha_competitions SET ${fields.join(', ')} WHERE id = $${paramIndex + 1}`,- values- );- }-- /**- * Delete a competition and all related data- */- async deleteAlphaCompetition(id: string): Promise<void> {- await this.ensureInitialized();-- // Delete from all related tables- await this.db!.execute('DELETE FROM alpha_performance_snapshots WHERE competition_id = $1', [id]);- await this.db!.execute('DELETE FROM alpha_model_states WHERE competition_id = $1', [id]);- await this.db!.execute('DELETE FROM alpha_decision_logs WHERE competition_id = $1', [id]);- await this.db!.execute('DELETE FROM alpha_price_history WHERE competition_id = $1', [id]);- await this.db!.execute('DELETE FROM alpha_competitions WHERE id = $1', [id]);-- console.log(`[SQLite] Deleted competition ${id} and all related data`);- }-- /**- * Save/update model state- */- async saveAlphaModelState(state: Omit<AlphaModelState, 'created_at' | 'updated_at'>): Promise<void> {- await this.ensureInitialized();-- const now = new Date().toISOString();-- await this.db!.execute(- `INSERT OR REPLACE INTO alpha_model_states- (id, competition_id, model_name, provider, model_id, capital, positions_json, trades_count, total_pnl, portfolio_value, created_at, updated_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, COALESCE((SELECT created_at FROM alpha_model_states WHERE id = $1), $11), $12)`,- [state.id, state.competition_id, state.model_name, state.provider, state.model_id, state.capital, state.positions_json, state.trades_count, state.total_pnl, state.portfolio_value, now, now]- );- }-- /**- * Get all model states for a competition- */- async getAlphaModelStates(competitionId: string): Promise<AlphaModelState[]> {- await this.ensureInitialized();- return await this.db!.select<AlphaModelState[]>(- 'SELECT * FROM alpha_model_states WHERE competition_id = $1',- [competitionId]- );- }-- /**- * Get a specific model state- */- async getAlphaModelState(competitionId: string, modelName: string): Promise<AlphaModelState | null> {- await this.ensureInitialized();- const results = await this.db!.select<AlphaModelState[]>(- 'SELECT * FROM alpha_model_states WHERE competition_id = $1 AND model_name = $2',- [competitionId, modelName]- );- return results[0] || null;- }-- /**- * Log price data for charting- */- async logAlphaPrice(price: Omit<AlphaPriceHistory, 'timestamp'>): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT INTO alpha_price_history- (id, competition_id, symbol, price, bid, ask, volume_24h, high_24h, low_24h, timestamp)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,- [price.id, price.competition_id, price.symbol, price.price, price.bid, price.ask, price.volume_24h, price.high_24h, price.low_24h, new Date().toISOString()]- );- }-- /**- * Get price history for a competition- */- async getAlphaPriceHistory(competitionId: string, limit?: number): Promise<AlphaPriceHistory[]> {- await this.ensureInitialized();- const sql = limit- ? 'SELECT * FROM alpha_price_history WHERE competition_id = $1 ORDER BY timestamp DESC LIMIT $2'- : 'SELECT * FROM alpha_price_history WHERE competition_id = $1 ORDER BY timestamp DESC';- return limit ? await this.db!.select(sql, [competitionId, limit]) : await this.db!.select(sql, [competitionId]);- }-- /**- * Log a model decision- */- async logAlphaDecision(decision: Omit<AlphaDecisionLog, 'timestamp'>): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT INTO alpha_decision_logs- (id, competition_id, model_name, cycle_number, action, symbol, quantity, confidence, reasoning, trade_executed, price_at_decision, portfolio_value_before, portfolio_value_after, timestamp)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)`,- [decision.id, decision.competition_id, decision.model_name, decision.cycle_number, decision.action, decision.symbol, decision.quantity, decision.confidence, decision.reasoning, decision.trade_executed, decision.price_at_decision, decision.portfolio_value_before, decision.portfolio_value_after, new Date().toISOString()]- );- }-- /**- * Get decision logs for a competition- */- async getAlphaDecisionLogs(competitionId: string, modelName?: string, limit?: number): Promise<AlphaDecisionLog[]> {- await this.ensureInitialized();-- let sql = 'SELECT * FROM alpha_decision_logs WHERE competition_id = $1';- const params: any[] = [competitionId];-- if (modelName) {- sql += ' AND model_name = $2';- params.push(modelName);- }-- sql += ' ORDER BY timestamp DESC';-- if (limit) {- sql += ` LIMIT $${params.length + 1}`;- params.push(limit);- }-- return await this.db!.select(sql, params);- }-- /**- * Save a performance snapshot- */- async saveAlphaPerformanceSnapshot(snapshot: Omit<AlphaPerformanceSnapshot, 'timestamp'>): Promise<void> {- await this.ensureInitialized();-- await this.db!.execute(- `INSERT INTO alpha_performance_snapshots- (id, competition_id, cycle_number, model_name, portfolio_value, cash, pnl, return_pct, positions_count, trades_count, timestamp)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,- [snapshot.id, snapshot.competition_id, snapshot.cycle_number, snapshot.model_name, snapshot.portfolio_value, snapshot.cash, snapshot.pnl, snapshot.return_pct, snapshot.positions_count, snapshot.trades_count, new Date().toISOString()]- );- }-- /**- * Get performance snapshots for charting- */- async getAlphaPerformanceSnapshots(competitionId: string, modelName?: string): Promise<AlphaPerformanceSnapshot[]> {- await this.ensureInitialized();-- let sql = 'SELECT * FROM alpha_performance_snapshots WHERE competition_id = $1';- const params: any[] = [competitionId];-- if (modelName) {- sql += ' AND model_name = $2';- params.push(modelName);}-- sql += ' ORDER BY cycle_number ASC';-- return await this.db!.select(sql, params);+ return apiKeys;}- /**- * Get latest performance snapshot for each model in a competition (for leaderboard)- */- async getAlphaLatestPerformance(competitionId: string): Promise<AlphaPerformanceSnapshot[]> {- await this.ensureInitialized();-- return await this.db!.select(- `SELECT * FROM alpha_performance_snapshots- WHERE competition_id = $1- AND (model_name, cycle_number) IN (- SELECT model_name, MAX(cycle_number)- FROM alpha_performance_snapshots- WHERE competition_id = $1- GROUP BY model_name- )- ORDER BY pnl DESC`,- [competitionId]- );+ async getApiKey(key: string): Promise<string | null> {+ return await getSetting(key);}- // =========================- // UTILITY METHODS- // =========================-- private async ensureInitialized(): Promise<void> {- if (!this.db) {- await this.initialize();- }+ async setApiKey(key: string, value: string): Promise<void> {+ await saveSetting(key, value, 'api_keys');}- isReady(): boolean {- return this.db !== null;+ // Raw SQL methods for compatibility - these are stubs+ async execute(sql: string, params?: any[]): Promise<void> {+ console.warn('[SqliteService] execute() - raw SQL not supported, use Rust invoke commands');+ throw new Error('Raw SQL execute() not supported - use Rust invoke() commands instead');}- /**- * Execute raw SQL statement- */- async execute(sql: string, params?: any[]): Promise<any> {- await this.ensureInitialized();- return await this.db!.execute(sql, params);- }-- /**- * Execute raw SQL select query- */- async select<T = any>(sql: string, params?: any[]): Promise<T> {- await this.ensureInitialized();- return await this.db!.select<T>(sql, params);- }-- async healthCheck(): Promise<{ healthy: boolean; message: string }> {- try {- await this.ensureInitialized();- const results = await this.db!.select<{ result: number }[]>('SELECT 1 as result');-- if (results[0]?.result === 1) {- return { healthy: true, message: 'Database connection healthy' };- }-- return { healthy: false, message: 'Unexpected query result' };- } catch (error) {- const errorMsg = error instanceof Error ? error.message : String(error);- return { healthy: false, message: `Health check failed: ${errorMsg}` };- }+ async select<T = any>(sql: string, params?: any[]): Promise<T[]> {+ console.warn('[SqliteService] select() - raw SQL not supported, use Rust invoke commands');+ return [];}}-// Export singleton instance-export const sqliteService = new SQLiteService();+export const sqliteService = new SqliteService();export default sqliteService;diff --git a/fincept-terminal-desktop/src/services/watchlistService.ts b/fincept-terminal-desktop/src/services/watchlistService.tsindex 329c0aca5..23d8d0247 100644--- a/fincept-terminal-desktop/src/services/watchlistService.ts+++ b/fincept-terminal-desktop/src/services/watchlistService.ts@@ -1,7 +1,7 @@// Watchlist Service - Manages watchlists and stock tracking for Fincept Terminal-// Handles watchlist CRUD, stock management, and live market data integration+// Now using high-performance Rust SQLite backend via Tauri commands-import Database from '@tauri-apps/plugin-sql';+import { invoke } from '@tauri-apps/api/core';import { marketDataService, QuoteData } from './marketDataService';import { watchlistLogger } from './loggerService';@@ -37,36 +37,7 @@ export interface WatchlistWithStocks {// ==================== WATCHLIST SERVICE CLASS ====================class WatchlistService {- private db: Database | null = null;- private dbPath = 'sqlite:fincept_terminal.db';- private isInitialized = false;-- /**- * Initialize database connection- */- async initialize(): Promise<void> {- if (this.isInitialized && this.db) {- return;- }-- try {- this.db = await Database.load(this.dbPath);- this.isInitialized = true;- watchlistLogger.info('Initialized successfully');- } catch (error) {- watchlistLogger.error('Initialization failed:', error);- throw error;- }- }-- /**- * Ensure database is initialized- */- private ensureInitialized(): void {- if (!this.db || !this.isInitialized) {- throw new Error('WatchlistService not initialized. Call initialize() first.');- }- }+ // No database initialization needed - Rust backend handles it// ==================== WATCHLIST CRUD ====================@@ -74,81 +45,42 @@ class WatchlistService {* Create a new watchlist*/async createWatchlist(name: string, description?: string, color: string = '#FFA500'): Promise<Watchlist> {- this.ensureInitialized();-- const id = crypto.randomUUID();- await this.db!.execute(- `INSERT INTO watchlists (id, name, description, color)- VALUES ($1, $2, $3, $4)`,- [id, name, description || null, color]- );-- const result = await this.db!.select<Watchlist[]>(- 'SELECT * FROM watchlists WHERE id = $1',- [id]- );-- watchlistLogger.info(`Created watchlist: ${name}`, { id });- return result[0];+ try {+ const watchlist = await invoke<Watchlist>('db_create_watchlist', {+ name,+ description: description || null,+ color+ });+ watchlistLogger.info(`Created watchlist: ${name}`, { id: watchlist.id });+ return watchlist;+ } catch (error) {+ watchlistLogger.error('Failed to create watchlist:', error);+ throw error;+ }}/*** Get all watchlists*/async getWatchlists(): Promise<Watchlist[]> {- this.ensureInitialized();-- const watchlists = await this.db!.select<Watchlist[]>(- 'SELECT * FROM watchlists ORDER BY created_at DESC'- );-- return watchlists;+ try {+ return await invoke<Watchlist[]>('db_get_watchlists');+ } catch (error) {+ watchlistLogger.error('Failed to get watchlists:', error);+ throw error;+ }}/*** Get watchlist by ID*/async getWatchlist(watchlistId: string): Promise<Watchlist | null> {- this.ensureInitialized();-- const result = await this.db!.select<Watchlist[]>(- 'SELECT * FROM watchlists WHERE id = $1',- [watchlistId]- );-- return result.length > 0 ? result[0] : null;- }-- /**- * Update watchlist- */- async updateWatchlist(watchlistId: string, updates: Partial<Omit<Watchlist, 'id' | 'created_at' | 'updated_at'>>): Promise<void> {- this.ensureInitialized();-- const sets: string[] = [];- const values: any[] = [];-- if (updates.name !== undefined) {- sets.push('name = $' + (values.length + 1));- values.push(updates.name);- }- if (updates.description !== undefined) {- sets.push('description = $' + (values.length + 1));- values.push(updates.description);- }- if (updates.color !== undefined) {- sets.push('color = $' + (values.length + 1));- values.push(updates.color);- }-- if (sets.length > 0) {- sets.push("updated_at = datetime('now')");- values.push(watchlistId);-- await this.db!.execute(- `UPDATE watchlists SET ${sets.join(', ')} WHERE id = $${values.length}`,- values- );+ try {+ const watchlists = await this.getWatchlists();+ return watchlists.find(w => w.id === watchlistId) || null;+ } catch (error) {+ watchlistLogger.error('Failed to get watchlist:', error);+ return null;}}@@ -156,10 +88,13 @@ class WatchlistService {* Delete watchlist (cascades to stocks)*/async deleteWatchlist(watchlistId: string): Promise<void> {- this.ensureInitialized();-- await this.db!.execute('DELETE FROM watchlists WHERE id = $1', [watchlistId]);- watchlistLogger.info(`Deleted watchlist: ${watchlistId}`);+ try {+ await invoke('db_delete_watchlist', { watchlistId });+ watchlistLogger.info(`Deleted watchlist: ${watchlistId}`);+ } catch (error) {+ watchlistLogger.error('Failed to delete watchlist:', error);+ throw error;+ }}// ==================== STOCK MANAGEMENT ====================@@ -168,78 +103,52 @@ class WatchlistService {* Add stock to watchlist*/async addStock(watchlistId: string, symbol: string, notes?: string): Promise<WatchlistStock> {- this.ensureInitialized();-- // Check if stock already exists in watchlist- const existing = await this.db!.select<WatchlistStock[]>(- 'SELECT * FROM watchlist_stocks WHERE watchlist_id = $1 AND symbol = $2',- [watchlistId, symbol]- );-- if (existing.length > 0) {- throw new Error(`Stock ${symbol} already exists in watchlist`);+ try {+ const stock = await invoke<WatchlistStock>('db_add_watchlist_stock', {+ watchlistId,+ symbol: symbol.toUpperCase(),+ notes: notes || null+ });+ watchlistLogger.info(`Added stock ${symbol} to watchlist`, { watchlistId });+ return stock;+ } catch (error) {+ watchlistLogger.error('Failed to add stock:', error);+ throw error;}-- const id = crypto.randomUUID();- await this.db!.execute(- `INSERT INTO watchlist_stocks (id, watchlist_id, symbol, notes)- VALUES ($1, $2, $3, $4)`,- [id, watchlistId, symbol.toUpperCase(), notes || null]- );-- const result = await this.db!.select<WatchlistStock[]>(- 'SELECT * FROM watchlist_stocks WHERE id = $1',- [id]- );-- watchlistLogger.info(`Added stock ${symbol} to watchlist`, { watchlistId });- return result[0];}/*** Remove stock from watchlist*/async removeStock(watchlistId: string, symbol: string): Promise<void> {- this.ensureInitialized();-- await this.db!.execute(- 'DELETE FROM watchlist_stocks WHERE watchlist_id = $1 AND symbol = $2',- [watchlistId, symbol.toUpperCase()]- );-- watchlistLogger.info(`Removed stock ${symbol} from watchlist`, { watchlistId });- }-- /**- * Update stock notes- */- async updateStockNotes(watchlistId: string, symbol: string, notes: string): Promise<void> {- this.ensureInitialized();-- await this.db!.execute(- 'UPDATE watchlist_stocks SET notes = $1 WHERE watchlist_id = $2 AND symbol = $3',- [notes, watchlistId, symbol.toUpperCase()]- );+ try {+ await invoke('db_remove_watchlist_stock', {+ watchlistId,+ symbol: symbol.toUpperCase()+ });+ watchlistLogger.info(`Removed stock ${symbol} from watchlist`, { watchlistId });+ } catch (error) {+ watchlistLogger.error('Failed to remove stock:', error);+ throw error;+ }}/*** Get all stocks in a watchlist*/async getWatchlistStocks(watchlistId: string): Promise<WatchlistStock[]> {- this.ensureInitialized();-- return await this.db!.select<WatchlistStock[]>(- 'SELECT * FROM watchlist_stocks WHERE watchlist_id = $1 ORDER BY added_at DESC',- [watchlistId]- );+ try {+ return await invoke<WatchlistStock[]>('db_get_watchlist_stocks', { watchlistId });+ } catch (error) {+ watchlistLogger.error('Failed to get watchlist stocks:', error);+ throw error;+ }}/*** Get watchlist stocks with live market quotes (with 10-min cache)*/async getWatchlistStocksWithQuotes(watchlistId: string): Promise<WatchlistStockWithQuote[]> {- this.ensureInitialized();-const stocks = await this.getWatchlistStocks(watchlistId);if (stocks.length === 0) {@@ -270,8 +179,6 @@ class WatchlistService {* Get complete watchlist with stocks and quotes*/async getWatchlistWithStocks(watchlistId: string): Promise<WatchlistWithStocks | null> {- this.ensureInitialized();-const watchlist = await this.getWatchlist(watchlistId);if (!watchlist) {return null;@@ -290,8 +197,6 @@ class WatchlistService {* Get all watchlists with stock counts*/async getWatchlistsWithCounts(): Promise<Array<Watchlist & { stock_count: number }>> {- this.ensureInitialized();-const watchlists = await this.getWatchlists();const withCounts = await Promise.all(@@ -316,20 +221,21 @@ class WatchlistService {gainers: WatchlistStockWithQuote[];losers: WatchlistStockWithQuote[];}> {- this.ensureInitialized();-- // Get all unique symbols from all watchlists- const allStocks = await this.db!.select<{ symbol: string }[]>(- 'SELECT DISTINCT symbol FROM watchlist_stocks'+ // Get all watchlists and their stocks+ const watchlists = await this.getWatchlists();+ const allStocksArrays = await Promise.all(+ watchlists.map(w => this.getWatchlistStocks(w.id)));- if (allStocks.length === 0) {+ const allStocks = allStocksArrays.flat();+ const uniqueSymbols = [...new Set(allStocks.map(s => s.symbol))];++ if (uniqueSymbols.length === 0) {return { gainers: [], losers: [] };}- const symbols = allStocks.map(s => s.symbol);const quotes = await marketDataService.getEnhancedQuotesWithCache(- symbols,+ uniqueSymbols,'market_movers',10 // 10-minute cache);@@ -360,19 +266,21 @@ class WatchlistService {* Get volume leaders from all watchlists (with 10-min cache)*/async getVolumeLeaders(limit: number = 5): Promise<WatchlistStockWithQuote[]> {- this.ensureInitialized();-- const allStocks = await this.db!.select<{ symbol: string }[]>(- 'SELECT DISTINCT symbol FROM watchlist_stocks'+ // Get all watchlists and their stocks+ const watchlists = await this.getWatchlists();+ const allStocksArrays = await Promise.all(+ watchlists.map(w => this.getWatchlistStocks(w.id)));- if (allStocks.length === 0) {+ const allStocks = allStocksArrays.flat();+ const uniqueSymbols = [...new Set(allStocks.map(s => s.symbol))];++ if (uniqueSymbols.length === 0) {return [];}- const symbols = allStocks.map(s => s.symbol);const quotes = await marketDataService.getEnhancedQuotesWithCache(- symbols,+ uniqueSymbols,'volume_leaders',10 // 10-minute cache);@@ -420,10 +328,10 @@ class WatchlistService {// ==================== UTILITY ====================/**- * Check if service is ready+ * Check if service is ready (always ready with Rust backend)*/isReady(): boolean {- return this.isInitialized && this.db !== null;+ return true;}/**@@ -431,10 +339,18 @@ class WatchlistService {*/getStatus(): { initialized: boolean; ready: boolean } {return {- initialized: this.isInitialized,- ready: this.isReady()+ initialized: true,+ ready: true};}++ /**+ * Initialize - kept for compatibility but not needed with Rust backend+ */+ async initialize(): Promise<void> {+ // Rust backend auto-initializes on app startup+ watchlistLogger.info('Using Rust SQLite backend');+ }}// Export singleton instancediff --git a/fincept-terminal-desktop/test-file.txt b/fincept-terminal-desktop/test-file.txtdeleted file mode 100644index d670460b4..000000000--- a/fincept-terminal-desktop/test-file.txt+++ /dev/null@@ -1 +0,0 @@-test contentdiff --git a/fincept-terminal-desktop/test-positions.html b/fincept-terminal-desktop/test-positions.htmlnew file mode 100644index 000000000..b2aa8397a--- /dev/null+++ b/fincept-terminal-desktop/test-positions.html@@ -0,0 +1,75 @@+<!DOCTYPE html>+<html>+<head>+ <title>Test Paper Trading Positions</title>+</head>+<body>+ <h1>Paper Trading Positions Test</h1>+ <button onclick="testPositions()">Test Fetch Positions</button>+ <button onclick="testPortfolios()">Test List Portfolios</button>+ <button onclick="testOrders()">Test Fetch Orders</button>+ <pre id="output"></pre>++ <script>+ const { invoke } = window.__TAURI__.core;++ async function testPortfolios() {+ const output = document.getElementById('output');+ output.textContent = 'Fetching portfolios...\n';++ try {+ const portfolios = await invoke('db_list_portfolios');+ output.textContent += JSON.stringify(portfolios, null, 2);+ } catch (error) {+ output.textContent += 'ERROR: ' + error;+ }+ }++ async function testPositions() {+ const output = document.getElementById('output');+ output.textContent = 'Fetching positions...\n';++ try {+ // Try to get all portfolios first+ const portfolios = await invoke('db_list_portfolios');+ output.textContent += 'Found ' + portfolios.length + ' portfolios:\n';+ output.textContent += JSON.stringify(portfolios, null, 2) + '\n\n';++ // For each portfolio, get positions+ for (const portfolio of portfolios) {+ output.textContent += `\nFetching positions for portfolio: ${portfolio.id}\n`;+ const positions = await invoke('db_get_portfolio_positions', {+ portfolioId: portfolio.id,+ status: null+ });+ output.textContent += `Found ${positions.length} positions:\n`;+ output.textContent += JSON.stringify(positions, null, 2) + '\n';+ }+ } catch (error) {+ output.textContent += '\nERROR: ' + error;+ }+ }++ async function testOrders() {+ const output = document.getElementById('output');+ output.textContent = 'Fetching orders...\n';++ try {+ const portfolios = await invoke('db_list_portfolios');+ output.textContent += 'Found ' + portfolios.length + ' portfolios:\n';++ for (const portfolio of portfolios) {+ output.textContent += `\nFetching orders for portfolio: ${portfolio.id}\n`;+ const orders = await invoke('db_get_portfolio_orders', {+ portfolioId: portfolio.id+ });+ output.textContent += `Found ${orders.length} orders:\n`;+ output.textContent += JSON.stringify(orders, null, 2) + '\n';+ }+ } catch (error) {+ output.textContent += '\nERROR: ' + error;+ }+ }+ </script>+</body>+</html>diff --git a/fincept-terminal-desktop/test.txt b/fincept-terminal-desktop/test.txtdeleted file mode 100644index 9daeafb98..000000000--- a/fincept-terminal-desktop/test.txt+++ /dev/null@@ -1 +0,0 @@-test