Skip to content

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

flow update

tilakpatel226266bf8b2678
diff --git "a/fincept-terminal-desktop/C\357\200\272windowsdiskfinceptTerminalopenapi_temp.json" "b/fincept-terminal-desktop/C\357\200\272windowsdiskfinceptTerminalopenapi_temp.json"
new file mode 100644
index 000000000..e90b76b5a
--- /dev/null
+++ "b/fincept-terminal-desktop/C\357\200\272windowsdiskfinceptTerminalopenapi_temp.json"
@@ -0,0 +1 @@
+{"openapi":"3.1.0","info":{"title":"Fincept API","description":"Modular Financial Data API","version":"3.0.0"},"paths":{"/auth/user/verify-simulate":{"post":{"tags":["authentication"],"summary":"Simulate User Verification","description":"Simulate OTP verification for testing purposes","operationId":"simulate_user_verification_auth_user_verify_simulate_post","parameters":[{"name":"email","in":"query","required":true,"schema":{"type":"string","title":"Email"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/register":{"post":{"tags":["users"],"summary":"Register User","description":"Register new user account","operationId":"register_user_user_register_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserRegistration"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/verify-otp":{"post":{"tags":["users"],"summary":"Verify Otp","description":"Verify OTP and activate account","operationId":"verify_otp_user_verify_otp_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OTPVerification"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/login":{"post":{"tags":["users"],"summary":"Login User","description":"User login with history tracking","operationId":"login_user_user_login_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserLogin"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/forgot-password":{"post":{"tags":["users"],"summary":"Forgot Password","description":"Request password reset","operationId":"forgot_password_user_forgot_password_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PasswordReset"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/reset-password":{"post":{"tags":["users"],"summary":"Reset Password","description":"Reset password with OTP","operationId":"reset_password_user_reset_password_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PasswordResetConfirm"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/profile":{"get":{"tags":["users"],"summary":"Get User Profile","description":"Get user profile information","operationId":"get_user_profile_user_profile_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"put":{"tags":["users"],"summary":"Update User Profile","description":"Update user profile","operationId":"update_user_profile_user_profile_put","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Profile Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/regenerate-api-key":{"post":{"tags":["users"],"summary":"Regenerate Api Key","description":"Regenerate user API key","operationId":"regenerate_api_key_user_regenerate_api_key_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/usage":{"get":{"tags":["users"],"summary":"Get User Usage","description":"Get user's API usage statistics","operationId":"get_user_usage_user_usage_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/login-history":{"get":{"tags":["users"],"summary":"Get My Login History","description":"Get current user's login history","operationId":"get_my_login_history_user_login_history_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","default":0,"title":"Offset"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/subscribe":{"post":{"tags":["users"],"summary":"Subscribe To Database","description":"Subscribe to a database","operationId":"subscribe_to_database_user_subscribe_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DatabaseSubscriptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/subscriptions":{"get":{"tags":["users"],"summary":"Get User Subscriptions","description":"Get user's database subscriptions","operationId":"get_user_subscriptions_user_subscriptions_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/transactions":{"get":{"tags":["users"],"summary":"Get User Transactions","description":"Get user's transaction history","operationId":"get_user_transactions_user_transactions_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/account":{"delete":{"tags":["users"],"summary":"Delete User Account","description":"Delete user account","operationId":"delete_user_account_user_account_delete","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Confirmation Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/admin/users":{"get":{"tags":["users"],"summary":"List All Users","description":"List all users (admin only)","operationId":"list_all_users_user_admin_users_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/admin/user/{user_id}":{"get":{"tags":["users"],"summary":"Get User Details","description":"Get detailed user information (admin only)","operationId":"get_user_details_user_admin_user__user_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/admin/user/{user_id}/credits":{"post":{"tags":["users"],"summary":"Manage User Credits","description":"Manage user credits (admin only)","operationId":"manage_user_credits_user_admin_user__user_id__credits_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Credits Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/admin/stats":{"get":{"tags":["users"],"summary":"Get Admin Statistics","description":"Get system statistics (admin only)","operationId":"get_admin_statistics_user_admin_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/register":{"post":{"tags":["guests"],"summary":"Register Device","description":"Register device and create guest user with temporary API key (50 credits one-time per IP)","operationId":"register_device_guest_register_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeviceRegistration"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/guest/status":{"get":{"tags":["guests"],"summary":"Guest Status","description":"Get guest user status and usage","operationId":"guest_status_guest_status_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/extend":{"post":{"tags":["guests"],"summary":"Extend Guest Session","description":"Extend guest session if near expiry","operationId":"extend_guest_session_guest_extend_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/usage":{"get":{"tags":["guests"],"summary":"Get Guest Usage","description":"Get guest user's API usage statistics","operationId":"get_guest_usage_guest_usage_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/session":{"delete":{"tags":["guests"],"summary":"Delete Guest Session","description":"Delete guest session and all associated data","operationId":"delete_guest_session_guest_session_delete","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/databases":{"get":{"tags":["guests"],"summary":"List Public Databases","description":"List public databases available to guests","operationId":"list_public_databases_guest_databases_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/database/{database_name}/tables":{"get":{"tags":["guests"],"summary":"Get Database Tables Guest","description":"Get tables in database for guests","operationId":"get_database_tables_guest_guest_database__database_name__tables_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"database_name","in":"path","required":true,"schema":{"type":"string","title":"Database Name"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/guest/database/{database_name}/{table_name}/data":{"get":{"tags":["guests"],"summary":"Get Table Data Guest","description":"Get data from table for guests (limited)","operationId":"get_table_data_guest_guest_database__database_name___table_name__data_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"database_name","in":"path","required":true,"schema":{"type":"string","title":"Database Name"}},{"name":"table_name","in":"path","required":true,"schema":{"type":"string","title":"Table Name"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":5,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/guest/admin/guests":{"get":{"tags":["guests"],"summary":"Get All Guests","description":"Get all guest users (admin only - would need admin auth in production)","operationId":"get_all_guests_guest_admin_guests_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/guest/admin/cleanup":{"post":{"tags":["guests"],"summary":"Manual Cleanup Expired Guests","description":"Manually trigger cleanup of expired guests (admin only)","operationId":"manual_cleanup_expired_guests_guest_admin_cleanup_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/guest/admin/stats":{"get":{"tags":["guests"],"summary":"Get Guest Statistics","description":"Get guest user statistics (admin only)","operationId":"get_guest_statistics_guest_admin_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/admin/system/config":{"get":{"tags":["admin"],"summary":"Get System Config","description":"Get all system configurations","operationId":"get_system_config_admin_system_config_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"post":{"tags":["admin"],"summary":"Create System Config","description":"Create system configuration","operationId":"create_system_config_admin_system_config_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SystemConfigRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/system/config/{config_id}":{"put":{"tags":["admin"],"summary":"Update System Config","description":"Update system configuration","operationId":"update_system_config_admin_system_config__config_id__put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"config_id","in":"path","required":true,"schema":{"type":"integer","title":"Config Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Config Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"delete":{"tags":["admin"],"summary":"Delete System Config","description":"Delete system configuration","operationId":"delete_system_config_admin_system_config__config_id__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"config_id","in":"path","required":true,"schema":{"type":"integer","title":"Config Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/analytics/usage":{"get":{"tags":["admin"],"summary":"Get Usage Analytics","description":"Get detailed API usage analytics","operationId":"get_usage_analytics_admin_analytics_usage_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/analytics/performance":{"get":{"tags":["admin"],"summary":"Get Performance Analytics","description":"Get performance analytics","operationId":"get_performance_analytics_admin_analytics_performance_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"hours","in":"query","required":false,"schema":{"type":"integer","default":24,"title":"Hours"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/login-audit":{"get":{"tags":["admin"],"summary":"Get Login Audit","description":"Get login audit log for all users","operationId":"get_login_audit_admin_login_audit_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"User Id"}},{"name":"ip_address","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Ip Address"}},{"name":"success_only","in":"query","required":false,"schema":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Success Only"}},{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":100,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","default":0,"title":"Offset"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/login-stats":{"get":{"tags":["admin"],"summary":"Get Login Stats","description":"Get login statistics","operationId":"get_login_stats_admin_login_stats_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/broadcast":{"post":{"tags":["admin"],"summary":"Broadcast Message","description":"Send broadcast message to users","operationId":"broadcast_message_admin_broadcast_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BroadcastMessageRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/maintenance/cleanup":{"post":{"tags":["admin"],"summary":"Run Maintenance Cleanup","description":"Run system maintenance and cleanup","operationId":"run_maintenance_cleanup_admin_maintenance_cleanup_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/logs":{"get":{"tags":["admin"],"summary":"Get System Logs","description":"Get system logs (mock implementation)","operationId":"get_system_logs_admin_logs_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"lines","in":"query","required":false,"schema":{"type":"integer","default":100,"title":"Lines"}},{"name":"level","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Level"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/export/users":{"get":{"tags":["admin"],"summary":"Export Users Data","description":"Export users data","operationId":"export_users_data_admin_export_users_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"format","in":"query","required":false,"schema":{"type":"string","default":"json","title":"Format"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/export/usage":{"get":{"tags":["admin"],"summary":"Export Usage Data","description":"Export API usage data","operationId":"export_usage_data_admin_export_usage_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}},{"name":"format","in":"query","required":false,"schema":{"type":"string","default":"json","title":"Format"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/health":{"get":{"tags":["admin"],"summary":"Admin System Health","description":"Check admin system health","operationId":"admin_system_health_admin_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/users/simple":{"get":{"tags":["admin"],"summary":"Get All Users Simple","description":"Get all users' names and emails (simple list)","operationId":"get_all_users_simple_admin_users_simple_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/users":{"get":{"tags":["admin"],"summary":"List All Users","description":"List all users with filtering and pagination","operationId":"list_all_users_admin_users_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}},{"name":"search","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Search"}},{"name":"account_type","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Account Type"}},{"name":"is_verified","in":"query","required":false,"schema":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Is Verified"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"post":{"tags":["admin"],"summary":"Create User","description":"Create new user (admin only)","operationId":"create_user_admin_users_post","security":[{"APIKeyHeader":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserCreateRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/users/{user_id}":{"get":{"tags":["admin"],"summary":"Get User Details","description":"Get detailed user information","operationId":"get_user_details_admin_users__user_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"put":{"tags":["admin"],"summary":"Update User","description":"Update user information","operationId":"update_user_admin_users__user_id__put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserUpdateRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"delete":{"tags":["admin"],"summary":"Delete User","description":"Delete user account","operationId":"delete_user_admin_users__user_id__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/users/{user_id}/credits":{"post":{"tags":["admin"],"summary":"Adjust User Credits","description":"Adjust user credit balance","operationId":"adjust_user_credits_admin_users__user_id__credits_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreditAdjustmentRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/users/{user_id}/reset-password":{"post":{"tags":["admin"],"summary":"Reset User Password","description":"Reset user password","operationId":"reset_user_password_admin_users__user_id__reset_password_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Password Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/guests":{"get":{"tags":["admin"],"summary":"List Guest Users","description":"List all guest users","operationId":"list_guest_users_admin_guests_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}},{"name":"platform","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Platform"}},{"name":"is_active","in":"query","required":false,"schema":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Is Active"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/guests/cleanup":{"post":{"tags":["admin"],"summary":"Cleanup Expired Guests Endpoint","description":"Manually cleanup expired guests","operationId":"cleanup_expired_guests_endpoint_admin_guests_cleanup_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/guests/{guest_id}":{"delete":{"tags":["admin"],"summary":"Delete Guest User","description":"Delete specific guest user","operationId":"delete_guest_user_admin_guests__guest_id__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"guest_id","in":"path","required":true,"schema":{"type":"integer","title":"Guest Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/databases":{"get":{"tags":["admin"],"summary":"List Databases","description":"List all databases in registry","operationId":"list_databases_admin_databases_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"post":{"tags":["admin"],"summary":"Create Database","description":"Create new database registry entry","operationId":"create_database_admin_databases_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DatabaseCreateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/databases/{database_id}":{"put":{"tags":["admin"],"summary":"Update Database","description":"Update database registry entry","operationId":"update_database_admin_databases__database_id__put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"database_id","in":"path","required":true,"schema":{"type":"integer","title":"Database Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Db Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/system/stats":{"get":{"tags":["admin"],"summary":"Get System Statistics","description":"Get comprehensive system statistics","operationId":"get_system_statistics_admin_system_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/payment/create-order":{"post":{"tags":["payments"],"summary":"Create Payment Order","description":"Create multi-currency payment order\n\nFlow:\n1. Get plan base price (INR)\n2. Convert to user's currency\n3. Create Cashfree order\n4. Save to database\n5. Return checkout URL","operationId":"create_payment_order_payment_create_order_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/payment/webhook":{"post":{"tags":["payments"],"summary":"Cashfree Webhook","description":"Cashfree webhook handler - Processes payment confirmations\n\nSecurity Layers:\n1. Signature verification\n2. Timestamp validation\n3. Multi-currency amount verification\n4. Idempotency check","operationId":"cashfree_webhook_payment_webhook_post","parameters":[{"name":"x-webhook-signature","in":"header","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"X-Webhook-Signature"}},{"name":"x-webhook-timestamp","in":"header","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"X-Webhook-Timestamp"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/status/{order_id}":{"get":{"tags":["payments"],"summary":"Get Payment Status","description":"Poll payment status (for Terminal app)","operationId":"get_payment_status_payment_status__order_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"order_id","in":"path","required":true,"schema":{"type":"string","title":"Order Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/verify/{order_id}":{"post":{"tags":["payments"],"summary":"Manual Verify Payment","description":"Fallback verification via Cashfree API","operationId":"manual_verify_payment_payment_verify__order_id__post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"order_id","in":"path","required":true,"schema":{"type":"string","title":"Order Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/history":{"get":{"tags":["payments"],"summary":"Get Payment History","description":"Get user's payment history with currency info","operationId":"get_payment_history_payment_history_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/plans":{"get":{"tags":["payments"],"summary":"Get Available Plans","description":"Get all subscription plans with prices in specified currency\n\nArgs:\n currency: ISO currency code (default: USD)","operationId":"get_available_plans_payment_plans_get","parameters":[{"name":"currency","in":"query","required":false,"schema":{"type":"string","default":"USD","title":"Currency"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/currencies":{"get":{"tags":["payments"],"summary":"Get Supported Currencies","description":"Get list of all supported currencies with current rates","operationId":"get_supported_currencies_payment_currencies_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/payment/refresh-rates":{"post":{"tags":["payments"],"summary":"Refresh Currency Rates","description":"Force refresh currency rates (admin/debugging)\nRate limit: once per hour per user","operationId":"refresh_currency_rates_payment_refresh_rates_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/payment/admin/transactions":{"get":{"tags":["payments"],"summary":"Admin Get Transactions","description":"Admin: View all transactions with currency filters","operationId":"admin_get_transactions_payment_admin_transactions_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"status","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"}},{"name":"currency","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Currency"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/news/single-domain/{domain}":{"get":{"tags":["news"],"summary":"Get News From Single Domain","description":"Get news from a single domain with 0.10 credit cost","operationId":"get_news_from_single_domain_news_single_domain__domain__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"domain","in":"path","required":true,"schema":{"type":"string","title":"Domain"}},{"name":"category","in":"query","required":false,"schema":{"anyOf":[{"$ref":"#/components/schemas/NewsCategory"},{"type":"null"}],"title":"Category"}},{"name":"country","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":100,"minimum":1,"default":10,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/news/multiple-domains":{"post":{"tags":["news"],"summary":"Get News From Multiple Domains","description":"Get news from multiple domains with 0.25 credit cost","operationId":"get_news_from_multiple_domains_news_multiple_domains_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NewsRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/news/date-range":{"post":{"tags":["news"],"summary":"Get News By Date Range","description":"Get news within a specific date range with 0.15 credit cost","operationId":"get_news_by_date_range_news_date_range_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DateRangeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/news/country/{country_code}":{"get":{"tags":["news"],"summary":"Get News By Country","description":"Get news from a specific country with 0.12 credit cost","operationId":"get_news_by_country_news_country__country_code__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country_code","in":"path","required":true,"schema":{"type":"string","title":"Country Code"}},{"name":"category","in":"query","required":false,"schema":{"anyOf":[{"$ref":"#/components/schemas/NewsCategory"},{"type":"null"}],"title":"Category"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":100,"minimum":1,"default":10,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/news/topic-search":{"post":{"tags":["news"],"summary":"Search News By Topic","description":"Search news by keywords/topics with 0.12 credit cost","operationId":"search_news_by_topic_news_topic_search_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TopicSearchRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/news/categories":{"get":{"tags":["news"],"summary":"Get Available Categories","description":"Get list of available news categories (free endpoint)","operationId":"get_available_categories_news_categories_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/news/pricing":{"get":{"tags":["news"],"summary":"Get News Pricing","description":"Get credit costs for different news operations (free endpoint)","operationId":"get_news_pricing_news_pricing_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/news/stats":{"get":{"tags":["news"],"summary":"Get News Usage Stats","description":"Get user's news API usage statistics","operationId":"get_news_usage_stats_news_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/news/analyze":{"post":{"tags":["news"],"summary":"Analyze News Article","description":"AI-powered news article analysis\nExtracts article content and performs comprehensive financial analysis\nCost: 10 credits","operationId":"analyze_news_article_news_analyze_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NewsAnalysisRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/support/tickets":{"get":{"tags":["support"],"summary":"Get User Tickets","description":"Get user's support tickets","operationId":"get_user_tickets_support_tickets_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"post":{"tags":["support"],"summary":"Create Ticket","description":"Create new support ticket (requires authentication)","operationId":"create_ticket_support_tickets_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TicketCreate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/support/tickets/{ticket_id}":{"get":{"tags":["support"],"summary":"Get Ticket Details","description":"Get detailed ticket information with messages","operationId":"get_ticket_details_support_tickets__ticket_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"ticket_id","in":"path","required":true,"schema":{"type":"integer","title":"Ticket Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"put":{"tags":["support"],"summary":"Update Ticket","description":"Update ticket status (user can only close/reopen)","operationId":"update_ticket_support_tickets__ticket_id__put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"ticket_id","in":"path","required":true,"schema":{"type":"integer","title":"Ticket Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TicketUpdate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/tickets/{ticket_id}/messages":{"post":{"tags":["support"],"summary":"Add Ticket Message","description":"Add message to support ticket","operationId":"add_ticket_message_support_tickets__ticket_id__messages_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"ticket_id","in":"path","required":true,"schema":{"type":"integer","title":"Ticket Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MessageCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/contact":{"post":{"tags":["support"],"summary":"Submit Contact Form","description":"Submit contact form (public endpoint)","operationId":"submit_contact_form_support_contact_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContactFormCreate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/feedback":{"post":{"tags":["support"],"summary":"Submit Feedback","description":"Submit feedback (public endpoint)","operationId":"submit_feedback_support_feedback_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeedbackCreate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/categories":{"get":{"tags":["support"],"summary":"Get Support Categories","description":"Get available support categories (public endpoint)","operationId":"get_support_categories_support_categories_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/support/stats":{"get":{"tags":["support"],"summary":"Get Support Stats","description":"Get user's support statistics","operationId":"get_support_stats_support_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/support/newsletter/subscribe":{"post":{"tags":["support"],"summary":"Subscribe To Newsletter","description":"Subscribe to Fincept newsletter (public endpoint - no authentication required)","operationId":"subscribe_to_newsletter_support_newsletter_subscribe_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NewsletterSubscribe"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/newsletter/unsubscribe":{"post":{"tags":["support"],"summary":"Unsubscribe From Newsletter","description":"Unsubscribe from newsletter (public endpoint)","operationId":"unsubscribe_from_newsletter_support_newsletter_unsubscribe_post","parameters":[{"name":"email","in":"query","required":true,"schema":{"type":"string","format":"email","title":"Email"}},{"name":"token","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Token"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/newsletter/status":{"get":{"tags":["support"],"summary":"Check Newsletter Status","description":"Check newsletter subscription status (public endpoint)","operationId":"check_newsletter_status_support_newsletter_status_get","parameters":[{"name":"email","in":"query","required":true,"schema":{"type":"string","format":"email","title":"Email"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions":{"get":{"tags":["chat"],"summary":"Get Chat Sessions","description":"Get user's chat sessions (both registered and guest users)","operationId":"get_chat_sessions_chat_sessions_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"post":{"tags":["chat"],"summary":"Create Chat Session","description":"Create new chat session","operationId":"create_chat_session_chat_sessions_post","security":[{"APIKeyHeader":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatSessionCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions/bulk-delete":{"delete":{"tags":["chat"],"summary":"Bulk Delete Sessions","description":"Bulk delete chat sessions (registered users only)","operationId":"bulk_delete_sessions_chat_sessions_bulk_delete_delete","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Session Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/sessions/{session_uuid}":{"get":{"tags":["chat"],"summary":"Get Chat Session","description":"Get specific chat session with messages","operationId":"get_chat_session_chat_sessions__session_uuid__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"delete":{"tags":["chat"],"summary":"Delete Chat Session","description":"Delete chat session and all messages","operationId":"delete_chat_session_chat_sessions__session_uuid__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions/{session_uuid}/messages":{"post":{"tags":["chat"],"summary":"Send Chat Message","description":"Send message to chat session and get AI response","operationId":"send_chat_message_chat_sessions__session_uuid__messages_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatMessageCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions/{session_uuid}/activate":{"put":{"tags":["chat"],"summary":"Activate Chat Session","description":"Activate a chat session (deactivates others)","operationId":"activate_chat_session_chat_sessions__session_uuid__activate_put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions/{session_uuid}/title":{"put":{"tags":["chat"],"summary":"Update Chat Title","description":"Update chat session title","operationId":"update_chat_title_chat_sessions__session_uuid__title_put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Title Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/stats":{"get":{"tags":["chat"],"summary":"Get Chat Statistics","description":"Get chat statistics for current user","operationId":"get_chat_statistics_chat_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/export":{"post":{"tags":["chat"],"summary":"Export Chat Sessions","description":"Export chat sessions to JSON (registered users only)","operationId":"export_chat_sessions_chat_export_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Export Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/admin/statistics":{"get":{"tags":["chat"],"summary":"Get Admin Chat Statistics","description":"Get system-wide chat statistics (admin only)","operationId":"get_admin_chat_statistics_chat_admin_statistics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/admin/sessions":{"get":{"tags":["chat"],"summary":"Get Admin Chat Sessions","description":"Get all chat sessions with pagination (admin only)","operationId":"get_admin_chat_sessions_chat_admin_sessions_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}},{"name":"user_type","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"User Type"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/quick-chat":{"post":{"tags":["chat"],"summary":"Quick Chat","description":"Quick chat without session management (for testing)","operationId":"quick_chat_chat_quick_chat_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatMessageCreate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/search":{"get":{"tags":["chat"],"summary":"Search Chat Messages","description":"Search chat messages","operationId":"search_chat_messages_chat_search_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"query","in":"query","required":true,"schema":{"type":"string","title":"Query"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/templates":{"get":{"tags":["chat"],"summary":"Get Chat Templates","description":"Get predefined chat templates (registered users only)","operationId":"get_chat_templates_chat_templates_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/templates/{template_id}/start":{"post":{"tags":["chat"],"summary":"Start Template Session","description":"Start a chat session from template (registered users only)","operationId":"start_template_session_chat_templates__template_id__start_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"template_id","in":"path","required":true,"schema":{"type":"string","title":"Template Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/categories":{"get":{"tags":["forum"],"summary":"Get Forum Categories","description":"Get all forum categories (accessible to both users and guests)","operationId":"get_forum_categories_forum_categories_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/forum/categories/{category_id}/posts":{"get":{"tags":["forum"],"summary":"Get Category Posts","description":"Get posts in a specific category","operationId":"get_category_posts_forum_categories__category_id__posts_get","parameters":[{"name":"category_id","in":"path","required":true,"schema":{"type":"integer","title":"Category Id"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":50,"minimum":1,"default":20,"title":"Limit"}},{"name":"sort_by","in":"query","required":false,"schema":{"type":"string","pattern":"^(latest|popular|views|replies)$","default":"latest","title":"Sort By"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"post":{"tags":["forum"],"summary":"Create Forum Post","description":"Create new forum post (registered users only)","operationId":"create_forum_post_forum_categories__category_id__posts_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"category_id","in":"path","required":true,"schema":{"type":"integer","title":"Category Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumPostCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/posts/trending":{"get":{"tags":["forum"],"summary":"Get Trending Posts","description":"Get trending forum posts","operationId":"get_trending_posts_forum_posts_trending_get","parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":50,"minimum":1,"default":10,"title":"Limit"}},{"name":"timeframe","in":"query","required":false,"schema":{"type":"string","pattern":"^(day|week|month)$","default":"week","title":"Timeframe"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/posts/{post_uuid}":{"get":{"tags":["forum"],"summary":"Get Forum Post","description":"Get specific forum post with comments","operationId":"get_forum_post_forum_posts__post_uuid__get","parameters":[{"name":"post_uuid","in":"path","required":true,"schema":{"type":"string","title":"Post Uuid"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/posts/{post_uuid}/comments":{"post":{"tags":["forum"],"summary":"Create Forum Comment","description":"Create comment on forum post (registered users only)","operationId":"create_forum_comment_forum_posts__post_uuid__comments_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"post_uuid","in":"path","required":true,"schema":{"type":"string","title":"Post Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumCommentCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/posts/{post_uuid}/vote":{"post":{"tags":["forum"],"summary":"Vote On Post","description":"Vote on forum post (registered users only)","operationId":"vote_on_post_forum_posts__post_uuid__vote_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"post_uuid","in":"path","required":true,"schema":{"type":"string","title":"Post Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumVoteCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/comments/{comment_uuid}/vote":{"post":{"tags":["forum"],"summary":"Vote On Comment","description":"Vote on forum comment (registered users only)","operationId":"vote_on_comment_forum_comments__comment_uuid__vote_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"comment_uuid","in":"path","required":true,"schema":{"type":"string","title":"Comment Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumVoteCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/search":{"get":{"tags":["forum"],"summary":"Search Forum","description":"Search forum posts and comments","operationId":"search_forum_forum_search_get","parameters":[{"name":"q","in":"query","required":true,"schema":{"type":"string","minLength":2,"maxLength":100,"title":"Q"}},{"name":"category_id","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Category Id"}},{"name":"post_type","in":"query","required":false,"schema":{"type":"string","pattern":"^(all|posts|comments)$","default":"all","title":"Post Type"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":50,"minimum":1,"default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/stats":{"get":{"tags":["forum"],"summary":"Get Forum Statistics","description":"Get forum statistics","operationId":"get_forum_statistics_forum_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/forum/profile/{username}":{"get":{"tags":["forum"],"summary":"Get Forum User Profile","description":"Get forum user profile (registered users only)","operationId":"get_forum_user_profile_forum_profile__username__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"username","in":"path","required":true,"schema":{"type":"string","title":"Username"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/profile":{"get":{"tags":["forum"],"summary":"Get My Forum Profile","description":"Get current user's forum profile","operationId":"get_my_forum_profile_forum_profile_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"put":{"tags":["forum"],"summary":"Update Forum Profile","description":"Update current user's forum profile","operationId":"update_forum_profile_forum_profile_put","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumProfileUpdate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/forum/admin/categories":{"post":{"tags":["forum"],"summary":"Create Forum Category","description":"Create new forum category (admin only)","operationId":"create_forum_category_forum_admin_categories_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Category Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/forum/admin/statistics":{"get":{"tags":["forum"],"summary":"Get Admin Forum Statistics","description":"Get detailed forum statistics (admin only)","operationId":"get_admin_forum_statistics_forum_admin_statistics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/upload":{"post":{"tags":["marketplace"],"summary":"Upload Dataset","description":"Upload dataset to marketplace with pricing options","operationId":"upload_dataset_marketplace_upload_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"metadata","in":"query","required":true,"schema":{"type":"string","title":"Metadata"}}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_upload_dataset_marketplace_upload_post"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/datasets":{"get":{"tags":["marketplace"],"summary":"Browse Datasets","description":"Browse marketplace datasets (registered users only)","operationId":"browse_datasets_marketplace_datasets_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"category","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Category"}},{"name":"search","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Search"}},{"name":"price_tier","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Price Tier"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}},{"name":"sort_by","in":"query","required":false,"schema":{"type":"string","default":"uploaded_at","title":"Sort By"}},{"name":"sort_order","in":"query","required":false,"schema":{"type":"string","default":"desc","title":"Sort Order"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/my-purchases":{"get":{"tags":["marketplace"],"summary":"Get User Purchases","description":"Get user's dataset purchases","operationId":"get_user_purchases_marketplace_my_purchases_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/pricing":{"get":{"tags":["marketplace"],"summary":"Get Pricing Tiers","description":"Get available pricing tiers for dataset uploads","operationId":"get_pricing_tiers_marketplace_pricing_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/my-datasets":{"get":{"tags":["marketplace"],"summary":"Get My Datasets","description":"Get user's uploaded datasets with status filtering","operationId":"get_my_datasets_marketplace_my_datasets_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}},{"name":"status","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/datasets/{dataset_id}":{"patch":{"tags":["marketplace"],"summary":"Update Dataset","description":"Update dataset metadata (only owner can update, only if pending/rejected)","operationId":"update_dataset_marketplace_datasets__dataset_id__patch","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Update Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"delete":{"tags":["marketplace"],"summary":"Delete Dataset","description":"Delete dataset (only owner can delete, only if not purchased by others)","operationId":"delete_dataset_marketplace_datasets__dataset_id__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"get":{"tags":["marketplace"],"summary":"Get Dataset Details","description":"Get detailed dataset information","operationId":"get_dataset_details_marketplace_datasets__dataset_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/datasets/{dataset_id}/purchase":{"post":{"tags":["marketplace"],"summary":"Purchase Dataset","description":"Get free access to dataset (no payment required)","operationId":"purchase_dataset_marketplace_datasets__dataset_id__purchase_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DatasetPurchaseRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/datasets/{dataset_id}/download":{"post":{"tags":["marketplace"],"summary":"Download Dataset","description":"Download dataset file (free for all registered users)","operationId":"download_dataset_marketplace_datasets__dataset_id__download_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/my-datasets/analytics":{"get":{"tags":["marketplace"],"summary":"Get Dataset Analytics","description":"Get analytics for user's uploaded datasets","operationId":"get_dataset_analytics_marketplace_my_datasets_analytics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/admin/revenue-analytics":{"get":{"tags":["marketplace"],"summary":"Get Admin Revenue Analytics","description":"Get marketplace revenue analytics for admin","operationId":"get_admin_revenue_analytics_marketplace_admin_revenue_analytics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/admin/stats":{"get":{"tags":["marketplace"],"summary":"Get Marketplace Stats","description":"Get comprehensive marketplace statistics","operationId":"get_marketplace_stats_marketplace_admin_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/admin/pending-datasets":{"get":{"tags":["marketplace"],"summary":"Get Pending Datasets","description":"Get all pending datasets for approval","operationId":"get_pending_datasets_marketplace_admin_pending_datasets_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/admin/datasets/{dataset_id}/approve":{"post":{"tags":["marketplace"],"summary":"Approve Dataset","description":"Approve a pending dataset","operationId":"approve_dataset_marketplace_admin_datasets__dataset_id__approve_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/admin/datasets/{dataset_id}/reject":{"post":{"tags":["marketplace"],"summary":"Reject Dataset","description":"Reject a pending dataset","operationId":"reject_dataset_marketplace_admin_datasets__dataset_id__reject_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Rejection Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/research/papers/search":{"get":{"tags":["research","research"],"summary":"Search Papers","description":"Search academic papers from arXiv with pagination\nCost: 1 credit per 10 papers (per page)\nRate limit: 1 request per second\n\nReturns 10 papers per page. Each page costs 1 credit.\nExample: page=1 returns papers 1-10, page=2 returns papers 11-20","operationId":"search_papers_research_papers_search_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"query","in":"query","required":true,"schema":{"type":"string","description":"Search query (keywords separated by space)","title":"Query"},"description":"Search query (keywords separated by space)"},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"description":"Page number (1-indexed)","default":1,"title":"Page"},"description":"Page number (1-indexed)"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/research/papers/trending":{"get":{"tags":["research","research"],"summary":"Get Trending Papers","description":"Get trending recent papers by topic with pagination\nCost: 1 credit per 10 papers (per page)\nRate limit: 1 request per second","operationId":"get_trending_papers_research_papers_trending_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"topic","in":"query","required":true,"schema":{"type":"string","description":"Research topic","title":"Topic"},"description":"Research topic"},{"name":"days","in":"query","required":false,"schema":{"type":"integer","maximum":365,"minimum":7,"description":"Days to look back","default":30,"title":"Days"},"description":"Days to look back"},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"description":"Page number","default":1,"title":"Page"},"description":"Page number"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/research/content-reader":{"post":{"tags":["research","research"],"summary":"Content Reader","description":"Extract and read content from web documents\nCost: 0.25 credits per request\nRate limit: 1 request per second","operationId":"content_reader_research_content_reader_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContentReaderRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/web-search":{"post":{"tags":["research","research"],"summary":"Web Search","description":"Search the web for financial and market intelligence","operationId":"web_search_research_web_search_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebSearchRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/chat":{"post":{"tags":["research","research"],"summary":"Fincept Chat","description":"Official Fincept AI Chat","operationId":"fincept_chat_research_chat_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/grokipedia":{"post":{"tags":["research","research"],"summary":"Grokipedia Fetch","description":"Fetch knowledge articles from Grokipedia (xAI's knowledge base)\n\nThis endpoint retrieves comprehensive articles from Grokipedia, covering various topics\nwith detailed content, references, and citations.\n\nCost: 0.25 credits per request\nRate limit: 1 request per second\n\nParameters:\n- slug: Article slug/identifier (e.g., \"artificial-intelligence\", \"climate-change\")\n- extract_refs: Extract and include references (default: true)\n- truncate: Limit content to N characters (optional)\n- citations: Include citation formatting (default: false)\n\nExample slugs:\n- \"bitcoin\"\n- \"machine-learning\"\n- \"quantum-computing\"\n- \"financial-markets\"","operationId":"grokipedia_fetch_research_grokipedia_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GrokipediaRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/pdf/extract":{"post":{"tags":["research","research"],"summary":"Extract Pdf Text","description":"Extract text from uploaded PDF file\nDynamic Pricing:\n- 1-10 pages: 1 credit\n- 11-50 pages: 2 credits\n- 51-100 pages: 3 credits\n- 101-200 pages: 5 credits\n- 201+ pages: 10 credits\nRate limit: 1 request per second\nMax file size: 10MB","operationId":"extract_pdf_text_research_pdf_extract_post","requestBody":{"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_extract_pdf_text_research_pdf_extract_post"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/health":{"get":{"tags":["research","research"],"summary":"Research Health","description":"Health check for Fincept research module","operationId":"research_health_research_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/research/llm":{"post":{"tags":["research","research"],"summary":"General Llm Inference","description":"General-purpose LLM endpoint for running agents, processing data, and AI tasks.\n\nThis endpoint allows you to use Fincept API as your LLM provider for:\n- Running AI agents\n- Data processing and analysis\n- Code generation\n- Text summarization\n- Question answering\n- Any other LLM-based tasks\n\nCost: 5 credits per successful response\nNote: Credits are ONLY deducted on successful LLM response. If the LLM fails, no credits are charged.\n\nRate limit: 1 request per second","operationId":"general_llm_inference_research_llm_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LLMRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/visual-analysis":{"post":{"tags":["research","research"],"summary":"Satellite Visual Analysis","description":"Multimodal Visual Analysis using GLM-4.6V for satellite imagery and visual understanding.\n\nThis endpoint enables advanced visual analysis capabilities including:\n- Satellite image analysis and interpretation\n- Geographic feature detection and classification\n- Land use and land cover analysis\n- Urban planning and infrastructure mapping\n- Environmental monitoring\n- Agricultural assessment\n- Disaster response and damage assessment\n- Object detection and counting in images\n- Visual question answering\n- Image description and captioning\n\nModel: GLM-4.6V (Multimodal Vision-Language Model)\n- Native multimodal understanding\n- 128K context window\n- Advanced visual reasoning\n- Function calling capabilities\n- High-resolution image processing\n\nCost: 10 credits per successful response\nNote: Credits are ONLY deducted on successful analysis. If the model fails, no credits are charged.\n\nRate limit: 1 request per second\n\nExample Use Cases:\n- \"Identify all buildings in this satellite image\"\n- \"What type of land use is shown in this area?\"\n- \"Detect any changes or anomalies in this image\"\n- \"Count the number of vehicles in this parking lot\"\n- \"Analyze the vegetation health in this agricultural field\"","operationId":"satellite_visual_analysis_research_visual_analysis_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VisualAnalysisRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/marine/vessel/position":{"post":{"tags":["marine","marine"],"summary":"Get Vessel Position","description":"Get last known position of a vessel by IMO\nCost: 1 credit per request","operationId":"get_vessel_position_marine_vessel_position_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VesselPositionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/marine/vessel/history":{"post":{"tags":["marine","marine"],"summary":"Get Vessel History","description":"Get complete historical location data for a vessel\nCost: 5 credits per request","operationId":"get_vessel_history_marine_vessel_history_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VesselPositionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/marine/vessel/multi":{"post":{"tags":["marine","marine"],"summary":"Get Multi Vessel Positions","description":"Get last known positions for multiple vessels (max 50)\nCost: 3 credits per request","operationId":"get_multi_vessel_positions_marine_vessel_multi_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MultiVesselRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/marine/vessel/area-search":{"post":{"tags":["marine","marine"],"summary":"Search Vessels In Area","description":"Search for all vessels in a defined geographic area\nCost: 2 credits per request","operationId":"search_vessels_in_area_marine_vessel_area_search_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AreaSearchRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/marine/health":{"get":{"tags":["marine","marine"],"summary":"Marine Health","description":"Health check for marine module","operationId":"marine_health_marine_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/aircraft/health":{"get":{"tags":["aircraft","aircraft"],"summary":"Aircraft Health","description":"Health check for aircraft tracking module","operationId":"aircraft_health_aircraft_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/aircraft/track":{"post":{"tags":["aircraft","aircraft"],"summary":"Track Aircraft","description":"Track aircraft by ID using PlaneFinder API with Selenium\nCost: 0.25 credits per successful request\nRate limit: 1 request per second","operationId":"track_aircraft_aircraft_track_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AircraftRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/aircraft/{aircraft_id}":{"get":{"tags":["aircraft","aircraft"],"summary":"Get Aircraft Endpoint","description":"Get aircraft data by ID (raw format)\nSimple endpoint without authentication for testing","operationId":"get_aircraft_endpoint_aircraft__aircraft_id__get","parameters":[{"name":"aircraft_id","in":"path","required":true,"schema":{"type":"string","title":"Aircraft Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/aircraft/{aircraft_id}/raw":{"get":{"tags":["aircraft","aircraft"],"summary":"Get Aircraft Raw","description":"Get raw aircraft data by ID\nSimple endpoint without authentication for testing","operationId":"get_aircraft_raw_aircraft__aircraft_id__raw_get","parameters":[{"name":"aircraft_id","in":"path","required":true,"schema":{"type":"string","title":"Aircraft Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/health":{"get":{"tags":["twitter","twitter"],"summary":"Twitter Health","description":"Health check for Twitter integration module","operationId":"twitter_health_twitter_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/twitter/countries":{"get":{"tags":["twitter","twitter"],"summary":"Get Available Countries","description":"Get list of all available countries for Twitter trends\nNo authentication required","operationId":"get_available_countries_twitter_countries_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/twitter/trends":{"get":{"tags":["twitter","twitter"],"summary":"Get Twitter Trends","description":"Get current Twitter trending topics for a country\n\nParameters:\n- country: Country name (optional, default: \"worldwide\")\n Examples: \"india\", \"usa\", \"uk\", \"japan\", \"brazil\", \"france\", etc.\n Use /twitter/countries to see all available countries\n\nCost: 0.5 credits per request\nRate limit: 1 request per 2 seconds","operationId":"get_twitter_trends_twitter_trends_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/user/tweets":{"get":{"tags":["twitter","twitter"],"summary":"Get User Tweets","description":"Get user's latest tweets (up to 20 per request)\n\nParameters:\n- username: Twitter screen name (e.g., \"elonmusk\")\n- user_id: Twitter user ID (recommended, more stable than username)\n- cursor: Pagination cursor for next page\n\nNote: Either username OR user_id is required. If both provided, user_id takes priority.\n\nCost: 1.0 credit per request (returns up to 20 tweets)\nRate limit: 1 request per 2 seconds\n\nReturns tweets sorted by created_at with pagination support.","operationId":"get_user_tweets_twitter_user_tweets_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"username","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Username"}},{"name":"user_id","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"User Id"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweets":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweets By Ids","description":"Get tweets by their IDs\n\nParameters:\n- tweet_ids: Comma-separated tweet IDs (e.g., \"1846987139428634858,1866332309399781537\")\n\nCost: 0.5 credits per request\nRate limit: 1 request per 2 seconds\n\nReturns tweet data for the specified IDs.","operationId":"get_tweets_by_ids_twitter_tweets_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_ids","in":"query","required":true,"schema":{"type":"string","title":"Tweet Ids"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/replies":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweet Replies","description":"Get replies to a tweet (up to 20 per request)\n\nParameters:\n- tweet_id: The tweet ID to get replies for (required)\n- since_time: On or after specified unix timestamp in seconds (optional)\n- until_time: Before specified unix timestamp in seconds (optional)\n- cursor: Pagination cursor for next page (optional)\n\nNote: tweet_id must be an original tweet (not a reply to another tweet)\n and should be the first tweet in a thread.\n\nCost: 1.0 credit per request (returns up to 20 replies)\nRate limit: 1 request per 2 seconds\n\nReturns replies sorted by reply time (descending) with pagination support.","operationId":"get_tweet_replies_twitter_tweet_replies_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}},{"name":"since_time","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Since Time"}},{"name":"until_time","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Until Time"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/quotes":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweet Quotes","description":"Get quote tweets of a tweet (20 quotes per request)\n\nParameters:\n- tweet_id: The tweet ID to get quotes for (required)\n- since_time: On or after specified unix timestamp in seconds (optional)\n- until_time: Before specified unix timestamp in seconds (optional)\n- include_replies: Include replies in results (default: true)\n- cursor: Pagination cursor for next page (optional)\n\nCost: 1.0 credit per request (returns 20 quotes)\nRate limit: 1 request per 2 seconds\n\nReturns quote tweets sorted by quote time (descending) with pagination support.","operationId":"get_tweet_quotes_twitter_tweet_quotes_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}},{"name":"since_time","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Since Time"}},{"name":"until_time","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Until Time"}},{"name":"include_replies","in":"query","required":false,"schema":{"type":"boolean","default":true,"title":"Include Replies"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/retweeters":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweet Retweeters","description":"Get users who retweeted a tweet (~100 users per request)\n\nParameters:\n- tweet_id: The tweet ID to get retweeters for (required)\n- cursor: Pagination cursor for next page (optional)\n\nCost: 1.5 credits per request (returns ~100 users)\nRate limit: 1 request per 2 seconds\n\nReturns users who retweeted the tweet, sorted by retweet time (descending) with pagination support.","operationId":"get_tweet_retweeters_twitter_tweet_retweeters_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/article":{"get":{"tags":["twitter","twitter"],"summary":"Get Twitter Article","description":"Get full article content from a Twitter article tweet\n\n⚠️ PREMIUM ENDPOINT - Costs 100 credits per article!\n\nParameters:\n- tweet_id: The tweet ID of the article (required)\n\nCost: 100 credits per article (PREMIUM)\nRate limit: 1 request per 2 seconds\n\nReturns full article content including title, preview, cover image, and full text.\nThis is a premium endpoint due to the comprehensive article data provided.","operationId":"get_twitter_article_twitter_article_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/thread_context":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweet Thread Context","description":"Get the full thread context of a tweet\n\nThis endpoint retrieves the entire conversation thread containing the specified tweet.\nFor example, if a thread has tweets t1 -> t2 -> t3 -> t4, t5, t6 (all replying to t3),\nproviding t3 will return the entire thread: t1, t2, t3, t4, t5, t6.\n\nParameters:\n- tweet_id: The tweet ID (can be a reply or original tweet)\n- cursor: Pagination cursor for next page (optional)\n\nNote: Pagination size varies due to Twitter API limitations.\nThe number of tweets per page is not fixed.\n\nCost: 2.0 credits per request (variable tweets per page)\nRate limit: 1 request per 2 seconds\n\nReturns the full thread context with pagination support.","operationId":"get_tweet_thread_context_twitter_tweet_thread_context_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/advanced_search":{"get":{"tags":["twitter","twitter"],"summary":"Advanced Tweet Search","description":"Advanced search for tweets with powerful query syntax\n\nSupports advanced Twitter search operators for precise tweet discovery.\n\nParameters:\n- query: Search query with advanced operators (required)\n Examples:\n - \"AI\" OR \"Twitter\" from:elonmusk since:2021-12-31_23:59:59_UTC\n - \"#bitcoin\" min_faves:100\n - \"python\" filter:verified\n See: https://github.com/igorbrigadir/twitter-advanced-search\n\n- query_type: \"Latest\" (chronological) or \"Top\" (most relevant)\n- cursor: Pagination cursor for next page (optional)\n\nCost: 2.5 credits per request (up to 20 tweets)\nRate limit: 1 request per 2 seconds\n\nReturns search results with pagination support.","operationId":"advanced_tweet_search_twitter_tweet_advanced_search_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"query","in":"query","required":true,"schema":{"type":"string","title":"Query"}},{"name":"query_type","in":"query","required":false,"schema":{"type":"string","default":"Latest","title":"Query Type"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/user/search":{"get":{"tags":["twitter","twitter"],"summary":"Search Users","description":"Search for Twitter users by keyword\n\nParameters:\n- query: Search keyword (required)\n- cursor: Pagination cursor for next page (optional)\n\nCost: 1.5 credits per request\nRate limit: 1 request per 2 seconds\n\nReturns matching users with pagination support.","operationId":"search_users_twitter_user_search_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"query","in":"query","required":true,"schema":{"type":"string","title":"Query"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/user/mentions":{"get":{"tags":["twitter","twitter"],"summary":"Get User Mentions","description":"Get tweet mentions by user screen name\nEach page returns exactly 20 mentions\nOrder by mention time descending\nCost: 1.0 credit per request\nRate limit: 1 request per 2 seconds","operationId":"get_user_mentions_twitter_user_mentions_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"userName","in":"query","required":true,"schema":{"type":"string","title":"Username"}},{"name":"sinceTime","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Sincetime"}},{"name":"untilTime","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Untiltime"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/my-login-history":{"get":{"tags":["analytics"],"summary":"Get My Login History","description":"Get current user's login history (User only sees their own)","operationId":"get_my_login_history_analytics_my_login_history_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","default":0,"title":"Offset"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/admin/dashboard":{"get":{"tags":["analytics"],"summary":"Get Admin Dashboard","description":"Get comprehensive dashboard statistics (Admin only)","operationId":"get_admin_dashboard_analytics_admin_dashboard_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/users/growth":{"get":{"tags":["analytics"],"summary":"Get User Growth","description":"Get user growth analytics (Admin only)","operationId":"get_user_growth_analytics_admin_users_growth_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/engagement":{"get":{"tags":["analytics"],"summary":"Get Engagement Metrics","description":"Get user engagement metrics (Admin only)","operationId":"get_engagement_metrics_analytics_admin_engagement_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/api-stats":{"get":{"tags":["analytics"],"summary":"Get Api Statistics","description":"Get API usage statistics (Admin only)","operationId":"get_api_statistics_analytics_admin_api_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/usage":{"get":{"tags":["analytics"],"summary":"Get Usage Analytics","description":"Get detailed API usage analytics (Admin only)","operationId":"get_usage_analytics_analytics_admin_usage_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/admin/performance":{"get":{"tags":["analytics"],"summary":"Get Performance Analytics","description":"Get performance analytics (Admin only)","operationId":"get_performance_analytics_analytics_admin_performance_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"hours","in":"query","required":false,"schema":{"type":"integer","default":24,"title":"Hours"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/admin/login-audit":{"get":{"tags":["analytics"],"summary":"Get Login Audit","description":"Get login audit log for all users (Admin only)","operationId":"get_login_audit_analytics_admin_login_audit_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"User Id"}},{"name":"ip_address","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Ip Address"}},{"name":"success_only","in":"query","required":false,"schema":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Success Only"}},{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":100,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","default":0,"title":"Offset"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/admin/revenue-analytics":{"get":{"tags":["analytics"],"summary":"Get Admin Revenue Analytics","description":"Get marketplace revenue analytics (Admin only)","operationId":"get_admin_revenue_analytics_analytics_admin_revenue_analytics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/subscription-analytics":{"get":{"tags":["analytics"],"summary":"Get Subscription Analytics","description":"Get subscription analytics (Admin only) - DISABLED - Payment system to be reimplemented","operationId":"get_subscription_analytics_analytics_admin_subscription_analytics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/":{"get":{"summary":"Root","description":"API status endpoint","operationId":"root__get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/cashfree-test":{"get":{"summary":"Cashfree Test Page","description":"Serve Cashfree payment test page","operationId":"cashfree_test_page_cashfree_test_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/health":{"get":{"summary":"Health Check","description":"System health check","operationId":"health_check_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/auth/status":{"get":{"summary":"Auth Status","description":"Check authentication status","operationId":"auth_status_auth_status_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/test":{"get":{"summary":"Test Endpoint","description":"Test endpoint","operationId":"test_endpoint_test_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/mcp/sync":{"post":{"summary":"Manual Mcp Sync","description":"Manually trigger MCP scripts sync from GitHub (Admin only)\n\nArgs:\n force: Force sync even if not time yet (default False)","operationId":"manual_mcp_sync_mcp_sync_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"force","in":"query","required":false,"schema":{"type":"boolean","default":false,"title":"Force"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/mcp/status":{"get":{"summary":"Mcp Status","description":"Get MCP system status (tools available, last sync, etc.)","operationId":"mcp_status_mcp_status_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}}},"components":{"schemas":{"AircraftRequest":{"properties":{"aircraft_id":{"type":"string","title":"Aircraft Id"}},"type":"object","required":["aircraft_id"],"title":"AircraftRequest"},"AreaSearchRequest":{"properties":{"min_lat":{"type":"number","title":"Min Lat"},"max_lat":{"type":"number","title":"Max Lat"},"min_lng":{"type":"number","title":"Min Lng"},"max_lng":{"type":"number","title":"Max Lng"}},"type":"object","required":["min_lat","max_lat","min_lng","max_lng"],"title":"AreaSearchRequest"},"Body_extract_pdf_text_research_pdf_extract_post":{"properties":{"file":{"type":"string","format":"binary","title":"File","description":"PDF file to process"}},"type":"object","required":["file"],"title":"Body_extract_pdf_text_research_pdf_extract_post"},"Body_upload_dataset_marketplace_upload_post":{"properties":{"file":{"type":"string","format":"binary","title":"File"}},"type":"object","required":["file"],"title":"Body_upload_dataset_marketplace_upload_post"},"BroadcastMessageRequest":{"properties":{"subject":{"type":"string","title":"Subject"},"message":{"type":"string","title":"Message"},"target_users":{"type":"string","title":"Target Users","default":"all"}},"type":"object","required":["subject","message"],"title":"BroadcastMessageRequest"},"ChatMessageCreate":{"properties":{"content":{"type":"string","title":"Content"}},"type":"object","required":["content"],"title":"ChatMessageCreate"},"ChatRequest":{"properties":{"messages":{"items":{},"type":"array","title":"Messages"},"model":{"type":"string","title":"Model","default":"meituan/longcat-flash-chat:free"}},"type":"object","required":["messages"],"title":"ChatRequest"},"ChatSessionCreate":{"properties":{"title":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Title","default":"New Conversation"}},"type":"object","title":"ChatSessionCreate"},"ContactFormCreate":{"properties":{"name":{"type":"string","title":"Name"},"email":{"type":"string","format":"email","title":"Email"},"subject":{"type":"string","title":"Subject"},"message":{"type":"string","title":"Message"}},"type":"object","required":["name","email","subject","message"],"title":"ContactFormCreate"},"ContentReaderRequest":{"properties":{"url":{"type":"string","maxLength":2083,"minLength":1,"format":"uri","title":"Url"},"format":{"type":"string","title":"Format","default":"markdown"}},"type":"object","required":["url"],"title":"ContentReaderRequest"},"CreateOrderRequest":{"properties":{"plan_id":{"type":"string","title":"Plan Id"},"currency":{"type":"string","title":"Currency","default":"USD"}},"type":"object","required":["plan_id"],"title":"CreateOrderRequest"},"CreditAdjustmentRequest":{"properties":{"action":{"type":"string","title":"Action"},"amount":{"type":"integer","title":"Amount"},"reason":{"type":"string","title":"Reason","default":"Admin adjustment"}},"type":"object","required":["action","amount"],"title":"CreditAdjustmentRequest"},"DatabaseCreateRequest":{"properties":{"database_name":{"type":"string","title":"Database Name"},"display_name":{"type":"string","title":"Display Name"},"description":{"type":"string","title":"Description","default":""},"category":{"type":"string","title":"Category","default":"general"},"is_public":{"type":"boolean","title":"Is Public","default":false},"requires_subscription":{"type":"boolean","title":"Requires Subscription","default":true},"cost_per_request":{"type":"integer","title":"Cost Per Request","default":20},"free_tier_limit":{"type":"integer","title":"Free Tier Limit","default":10},"total_tables":{"type":"integer","title":"Total Tables","default":0}},"type":"object","required":["database_name","display_name"],"title":"DatabaseCreateRequest"},"DatabaseSubscriptionRequest":{"properties":{"database_name":{"type":"string","title":"Database Name"}},"type":"object","required":["database_name"],"title":"DatabaseSubscriptionRequest"},"DatasetPurchaseRequest":{"properties":{"payment_method":{"type":"string","title":"Payment Method","default":"subscription_credit"}},"type":"object","title":"DatasetPurchaseRequest"},"DateRangeRequest":{"properties":{"start_date":{"type":"string","format":"date-time","title":"Start Date"},"end_date":{"type":"string","format":"date-time","title":"End Date"},"domains":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Domains"},"category":{"anyOf":[{"$ref":"#/components/schemas/NewsCategory"},{"type":"null"}]},"limit":{"type":"integer","title":"Limit","default":10}},"type":"object","required":["start_date","end_date"],"title":"DateRangeRequest"},"DeviceRegistration":{"properties":{"device_id":{"type":"string","title":"Device Id"},"device_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Device Name"},"platform":{"type":"string","title":"Platform"},"hardware_info":{"additionalProperties":true,"type":"object","title":"Hardware Info"}},"type":"object","required":["device_id","platform","hardware_info"],"title":"DeviceRegistration"},"FeedbackCreate":{"properties":{"name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Name"},"email":{"anyOf":[{"type":"string","format":"email"},{"type":"null"}],"title":"Email"},"rating":{"type":"integer","title":"Rating"},"feedback_text":{"type":"string","title":"Feedback Text"},"category":{"type":"string","title":"Category","default":"general"}},"type":"object","required":["rating","feedback_text"],"title":"FeedbackCreate"},"ForumCommentCreate":{"properties":{"content":{"type":"string","title":"Content"},"parent_comment_id":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Parent Comment Id"}},"type":"object","required":["content"],"title":"ForumCommentCreate"},"ForumPostCreate":{"properties":{"title":{"type":"string","title":"Title"},"content":{"type":"string","title":"Content"},"category_id":{"type":"integer","title":"Category Id"}},"type":"object","required":["title","content","category_id"],"title":"ForumPostCreate"},"ForumProfileUpdate":{"properties":{"display_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Display Name"},"bio":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Bio"},"avatar_color":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Avatar Color"},"signature":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Signature"},"show_email":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Show Email"},"email_notifications":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Email Notifications"}},"type":"object","title":"ForumProfileUpdate"},"ForumVoteCreate":{"properties":{"vote_type":{"type":"string","title":"Vote Type"}},"type":"object","required":["vote_type"],"title":"ForumVoteCreate"},"GrokipediaRequest":{"properties":{"slug":{"type":"string","title":"Slug"},"extract_refs":{"type":"boolean","title":"Extract Refs","default":true},"truncate":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Truncate"},"citations":{"type":"boolean","title":"Citations","default":false}},"type":"object","required":["slug"],"title":"GrokipediaRequest"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"LLMRequest":{"properties":{"prompt":{"type":"string","title":"Prompt"},"max_tokens":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Max Tokens","default":4096},"temperature":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Temperature","default":0.7}},"type":"object","required":["prompt"],"title":"LLMRequest"},"MessageCreate":{"properties":{"message":{"type":"string","title":"Message"}},"type":"object","required":["message"],"title":"MessageCreate"},"MultiVesselRequest":{"properties":{"imos":{"items":{"type":"string"},"type":"array","title":"Imos"}},"type":"object","required":["imos"],"title":"MultiVesselRequest"},"NewsAnalysisRequest":{"properties":{"url":{"type":"string","title":"Url"}},"type":"object","required":["url"],"title":"NewsAnalysisRequest"},"NewsCategory":{"type":"string","enum":["business","technology","sports","entertainment","health","science","politics","world","local"],"title":"NewsCategory"},"NewsRequest":{"properties":{"domains":{"items":{"type":"string"},"type":"array","title":"Domains"},"category":{"anyOf":[{"$ref":"#/components/schemas/NewsCategory"},{"type":"null"}]},"country":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country"},"language":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Language","default":"en"},"limit":{"type":"integer","title":"Limit","default":10}},"type":"object","required":["domains"],"title":"NewsRequest"},"NewsletterSubscribe":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Name"},"source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source","default":"website"}},"type":"object","required":["email"],"title":"NewsletterSubscribe"},"OTPVerification":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"otp":{"type":"string","title":"Otp"}},"type":"object","required":["email","otp"],"title":"OTPVerification"},"PasswordReset":{"properties":{"email":{"type":"string","format":"email","title":"Email"}},"type":"object","required":["email"],"title":"PasswordReset"},"PasswordResetConfirm":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"otp":{"type":"string","title":"Otp"},"new_password":{"type":"string","title":"New Password"}},"type":"object","required":["email","otp","new_password"],"title":"PasswordResetConfirm"},"SystemConfigRequest":{"properties":{"config_key":{"type":"string","title":"Config Key"},"config_value":{"type":"string","title":"Config Value"},"config_type":{"type":"string","title":"Config Type","default":"string"},"description":{"type":"string","title":"Description","default":""}},"type":"object","required":["config_key","config_value"],"title":"SystemConfigRequest"},"TicketCreate":{"properties":{"subject":{"type":"string","title":"Subject"},"description":{"type":"string","title":"Description"},"category":{"type":"string","title":"Category"},"priority":{"type":"string","title":"Priority","default":"medium"}},"type":"object","required":["subject","description","category"],"title":"TicketCreate"},"TicketUpdate":{"properties":{"status":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"}},"type":"object","title":"TicketUpdate"},"TopicSearchRequest":{"properties":{"keywords":{"items":{"type":"string"},"type":"array","title":"Keywords"},"domains":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Domains"},"country":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country"},"limit":{"type":"integer","title":"Limit","default":10}},"type":"object","required":["keywords"],"title":"TopicSearchRequest"},"UserCreateRequest":{"properties":{"username":{"type":"string","title":"Username"},"email":{"type":"string","format":"email","title":"Email"},"password":{"type":"string","title":"Password"},"account_type":{"type":"string","title":"Account Type","default":"free"},"is_admin":{"type":"boolean","title":"Is Admin","default":false},"is_verified":{"type":"boolean","title":"Is Verified","default":true},"credit_balance":{"type":"integer","title":"Credit Balance","default":0}},"type":"object","required":["username","email","password"],"title":"UserCreateRequest"},"UserLogin":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"password":{"type":"string","title":"Password"}},"type":"object","required":["email","password"],"title":"UserLogin"},"UserRegistration":{"properties":{"username":{"type":"string","title":"Username"},"email":{"type":"string","format":"email","title":"Email"},"password":{"type":"string","title":"Password"}},"type":"object","required":["username","email","password"],"title":"UserRegistration"},"UserUpdateRequest":{"properties":{"username":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Username"},"email":{"anyOf":[{"type":"string","format":"email"},{"type":"null"}],"title":"Email"},"account_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Account Type"},"is_verified":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Is Verified"},"is_admin":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Is Admin"},"credit_balance":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Credit Balance"}},"type":"object","title":"UserUpdateRequest"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"},"VesselPositionRequest":{"properties":{"imo":{"type":"string","title":"Imo"}},"type":"object","required":["imo"],"title":"VesselPositionRequest"},"VisualAnalysisRequest":{"properties":{"image_url":{"type":"string","title":"Image Url"},"prompt":{"type":"string","title":"Prompt"},"max_tokens":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Max Tokens","default":4096},"temperature":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Temperature","default":0.7},"enable_thinking":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Enable Thinking","default":false}},"type":"object","required":["image_url","prompt"],"title":"VisualAnalysisRequest"},"WebSearchRequest":{"properties":{"query":{"type":"string","title":"Query"},"engine":{"type":"string","title":"Engine","default":"google"}},"type":"object","required":["query"],"title":"WebSearchRequest"}},"securitySchemes":{"APIKeyHeader":{"type":"apiKey","in":"header","name":"X-API-Key"}}}}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/public/locales/en/auth.json b/fincept-terminal-desktop/public/locales/en/auth.json
index a8a5e1d90..3c435afe5 100644
--- a/fincept-terminal-desktop/public/locales/en/auth.json
+++ b/fincept-terminal-desktop/public/locales/en/auth.json
@@ -13,7 +13,7 @@
"forgotPassword": "Forgot Password?",
"noAccount": "Don't have an account?",
"signUp": "Sign Up",
- "guestInfo": "Guest Access: 50 API requests • 24-hour session",
+ "guestInfo": "Guest Access: 50 credits (one-time) • 24-hour session",
"errors": {
"emailPassword": "Please enter both email and password",
"accountNotFound": "Account not found. Please sign up first to create an account.",
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lock
index 5a075c9c0..cf99a9cfe 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.lock
+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock
@@ -800,6 +800,26 @@ dependencies = [
"syn 2.0.111",
]
+[[package]]
+name = "dashmap"
+version = "6.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf"
+dependencies = [
+ "cfg-if",
+ "crossbeam-utils",
+ "hashbrown 0.14.5",
+ "lock_api",
+ "once_cell",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "data-encoding"
+version = "2.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476"
+
[[package]]
name = "data-url"
version = "0.3.2"
@@ -1161,7 +1181,9 @@ version = "3.0.12"
dependencies = [
"ahash",
"anyhow",
+ "async-trait",
"chrono",
+ "dashmap",
"flate2",
"futures-util",
"hashbrown 0.15.5",
@@ -1189,7 +1211,10 @@ dependencies = [
"tauri-plugin-process",
"tauri-plugin-shell",
"tauri-plugin-updater",
+ "thiserror 2.0.17",
"tokio",
+ "tokio-tungstenite",
+ "url",
"uuid",
"which",
"zip 2.4.2",
@@ -5372,6 +5397,18 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "tokio-tungstenite"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6989540ced10490aaf14e6bad2e3d33728a2813310a0c71d1574304c49631cd"
+dependencies = [
+ "futures-util",
+ "log",
+ "tokio",
+ "tungstenite",
+]
+
[[package]]
name = "tokio-util"
version = "0.7.17"
@@ -5591,6 +5628,24 @@ version = "0.19.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49d64318d8311fc2668e48b63969f4343e0a85c4a109aa8460d6672e364b8bd1"
+[[package]]
+name = "tungstenite"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e2ce1e47ed2994fd43b04c8f618008d4cabdd5ee34027cf14f9d918edd9c8"
+dependencies = [
+ "byteorder",
+ "bytes",
+ "data-encoding",
+ "http 1.4.0",
+ "httparse",
+ "log",
+ "rand 0.8.5",
+ "sha1",
+ "thiserror 1.0.69",
+ "utf-8",
+]
+
[[package]]
name = "typeid"
version = "1.0.3"
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.toml
index 3b400f393..8de59e2b1 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.toml
+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml
@@ -54,6 +54,13 @@ hashbrown = "0.15" # Faster HashMap alternative
ahash = "0.8" # Fast hashing for orderbook
smallvec = "1.13" # Stack-allocated vectors for small arrays
+# WebSocket dependencies
+tokio-tungstenite = "0.23" # WebSocket client
+dashmap = "6" # Concurrent HashMap for subscriptions
+url = "2" # URL parsing for WebSocket connections
+async-trait = "0.1" # Async trait support
+thiserror = "2" # Error handling
+
[target.'cfg(target_os = "windows")'.dependencies]
[target.'cfg(target_os = "macos")'.dependencies]
nix = { version = "0.29", features = ["signal", "process"] }
diff --git a/fincept-terminal-desktop/src-tauri/capabilities/default.json b/fincept-terminal-desktop/src-tauri/capabilities/default.json
index b5e30a07f..6e2efcb83 100644
--- a/fincept-terminal-desktop/src-tauri/capabilities/default.json
+++ b/fincept-terminal-desktop/src-tauri/capabilities/default.json
@@ -17,7 +17,13 @@
{ "url": "http://*" }
]
},
- "cors-fetch:default",
+ {
+ "identifier": "cors-fetch:default",
+ "allow": [
+ { "url": "https://*" },
+ { "url": "http://*" }
+ ]
+ },
"dialog:default",
"dialog:allow-ask",
"dialog:allow-message",
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index 8a30cb5f2..fdef4a374 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -17,6 +17,7 @@ mod utils;
mod setup;
mod database;
mod python_runtime;
+mod websocket;
// mod finscript; // TODO: Implement FinScript module
// MCP Server Process with communication channels
@@ -31,6 +32,19 @@ struct MCPState {
processes: Mutex<HashMap<String, MCPProcess>>,
}
+// Global state for WebSocket manager
+struct WebSocketState {
+ manager: Arc<tokio::sync::RwLock<websocket::WebSocketManager>>,
+ router: Arc<tokio::sync::RwLock<websocket::MessageRouter>>,
+ services: Arc<tokio::sync::RwLock<WebSocketServices>>,
+}
+
+struct WebSocketServices {
+ paper_trading: websocket::services::PaperTradingService,
+ arbitrage: websocket::services::ArbitrageService,
+ portfolio: websocket::services::PortfolioService,
+}
+
#[derive(Debug, Serialize)]
struct SpawnResult {
pid: u32,
@@ -296,6 +310,108 @@ fn sha256_hash(input: String) -> String {
format!("{:x}", result)
}
+// ============================================================================
+// WEBSOCKET COMMANDS
+// ============================================================================
+
+/// Set WebSocket provider configuration
+#[tauri::command]
+async fn ws_set_config(
+ state: tauri::State<'_, WebSocketState>,
+ config: websocket::types::ProviderConfig,
+) -> Result<(), String> {
+ let manager = state.manager.read().await;
+ manager.set_config(config);
+ Ok(())
+}
+
+/// Connect to WebSocket provider
+#[tauri::command]
+async fn ws_connect(
+ state: tauri::State<'_, WebSocketState>,
+ provider: String,
+) -> Result<(), String> {
+ let manager = state.manager.read().await;
+ manager.connect(&provider).await
+ .map_err(|e| e.to_string())
+}
+
+/// Disconnect from WebSocket provider
+#[tauri::command]
+async fn ws_disconnect(
+ state: tauri::State<'_, WebSocketState>,
+ provider: String,
+) -> Result<(), String> {
+ let manager = state.manager.read().await;
+ manager.disconnect(&provider).await
+ .map_err(|e| e.to_string())
+}
+
+/// Subscribe to WebSocket channel
+#[tauri::command]
+async fn ws_subscribe(
+ state: tauri::State<'_, WebSocketState>,
+ provider: String,
+ symbol: String,
+ channel: String,
+ params: Option<serde_json::Value>,
+) -> Result<(), String> {
+ // Register frontend subscriber
+ state.router.write().await.subscribe_frontend(&format!("{}.{}.{}", provider, channel, symbol));
+
+ // Subscribe via manager
+ let manager = state.manager.read().await;
+ manager.subscribe(&provider, &symbol, &channel, params).await
+ .map_err(|e| e.to_string())
+}
+
+/// Unsubscribe from WebSocket channel
+#[tauri::command]
+async fn ws_unsubscribe(
+ state: tauri::State<'_, WebSocketState>,
+ provider: String,
+ symbol: String,
+ channel: String,
+) -> Result<(), String> {
+ // Unregister frontend subscriber
+ state.router.write().await.unsubscribe_frontend(&format!("{}.{}.{}", provider, channel, symbol));
+
+ // Unsubscribe via manager
+ let manager = state.manager.read().await;
+ manager.unsubscribe(&provider, &symbol, &channel).await
+ .map_err(|e| e.to_string())
+}
+
+/// Get connection metrics for a provider
+#[tauri::command]
+async fn ws_get_metrics(
+ state: tauri::State<'_, WebSocketState>,
+ provider: String,
+) -> Result<Option<websocket::types::ConnectionMetrics>, String> {
+ let manager = state.manager.read().await;
+ Ok(manager.get_metrics(&provider))
+}
+
+/// Get all connection metrics
+#[tauri::command]
+async fn ws_get_all_metrics(
+ state: tauri::State<'_, WebSocketState>,
+) -> Result<Vec<websocket::types::ConnectionMetrics>, String> {
+ let manager = state.manager.read().await;
+ Ok(manager.get_all_metrics())
+}
+
+/// Reconnect to provider
+#[tauri::command]
+async fn ws_reconnect(
+ state: tauri::State<'_, WebSocketState>,
+ provider: String,
+) -> Result<(), String> {
+ let manager = state.manager.read().await;
+ manager.reconnect(&provider).await
+ .map_err(|e| e.to_string())
+}
+
// Windows-specific imports to hide console windows
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
@@ -362,6 +478,21 @@ pub fn run() {
eprintln!("Failed to initialize database: {}", e);
}
+ // Initialize WebSocket system
+ let router = Arc::new(tokio::sync::RwLock::new(websocket::MessageRouter::new()));
+ let manager = Arc::new(tokio::sync::RwLock::new(websocket::WebSocketManager::new(router.clone())));
+ let services = Arc::new(tokio::sync::RwLock::new(WebSocketServices {
+ paper_trading: websocket::services::PaperTradingService::new(),
+ arbitrage: websocket::services::ArbitrageService::new(),
+ portfolio: websocket::services::PortfolioService::new(),
+ }));
+
+ let ws_state = WebSocketState {
+ manager: manager.clone(),
+ router: router.clone(),
+ services: services.clone(),
+ };
+
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_shell::init())
@@ -375,6 +506,13 @@ pub fn run() {
processes: Mutex::new(HashMap::new()),
})
.manage(commands::backtesting::BacktestingState::default())
+ .manage(ws_state)
+ .setup(move |app| {
+ // Set app handle for router to emit events to frontend (no-op for now, events are emitted directly)
+ let _ = router; // Silence unused warning
+ let _ = app.handle().clone();
+ Ok(())
+ })
.invoke_handler(tauri::generate_handler![
greet,
cleanup_running_workflows,
@@ -386,6 +524,14 @@ pub fn run() {
ping_mcp_server,
kill_mcp_server,
sha256_hash,
+ ws_set_config,
+ ws_connect,
+ ws_disconnect,
+ ws_subscribe,
+ ws_unsubscribe,
+ ws_get_metrics,
+ ws_get_all_metrics,
+ ws_reconnect,
execute_python_script,
commands::market_data::get_market_quote,
commands::market_data::get_market_quotes,
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs
new file mode 100644
index 000000000..1c39cdb54
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs
@@ -0,0 +1,57 @@
+// Fyers WebSocket Adapter (Stub - to be implemented)
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use serde_json::Value;
+
+pub struct FyersAdapter {
+ config: ProviderConfig,
+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,
+}
+
+impl FyersAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ message_callback: None,
+ }
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for FyersAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ // TODO: Implement Fyers connection
+ Err(anyhow::anyhow!("Fyers adapter not yet implemented"))
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ _symbol: &str,
+ _channel: &str,
+ _params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ Err(anyhow::anyhow!("Fyers adapter not yet implemented"))
+ }
+
+ async fn unsubscribe(&mut self, _symbol: &str, _channel: &str) -> anyhow::Result<()> {
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(callback);
+ }
+
+ fn provider_name(&self) -> &str {
+ "fyers"
+ }
+
+ fn is_connected(&self) -> bool {
+ false
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/hyperliquid.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/hyperliquid.rs
new file mode 100644
index 000000000..a1981aa38
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/hyperliquid.rs
@@ -0,0 +1,57 @@
+// HyperLiquid WebSocket Adapter (Stub - to be implemented)
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use serde_json::Value;
+
+pub struct HyperLiquidAdapter {
+ config: ProviderConfig,
+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,
+}
+
+impl HyperLiquidAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ message_callback: None,
+ }
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for HyperLiquidAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ // TODO: Implement HyperLiquid connection
+ Err(anyhow::anyhow!("HyperLiquid adapter not yet implemented"))
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ _symbol: &str,
+ _channel: &str,
+ _params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ Err(anyhow::anyhow!("HyperLiquid adapter not yet implemented"))
+ }
+
+ async fn unsubscribe(&mut self, _symbol: &str, _channel: &str) -> anyhow::Result<()> {
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(callback);
+ }
+
+ fn provider_name(&self) -> &str {
+ "hyperliquid"
+ }
+
+ fn is_connected(&self) -> bool {
+ false
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kraken.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kraken.rs
new file mode 100644
index 000000000..7b8be03ee
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kraken.rs
@@ -0,0 +1,363 @@
+// Kraken WebSocket Adapter
+//
+// Implements Kraken WebSocket API v2
+// Supports: ticker, book, trade, ohlc channels
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::sync::Arc;
+use std::time::{SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+const KRAKEN_WS_URL: &str = "wss://ws.kraken.com/v2";
+
+pub struct KrakenAdapter {
+ config: ProviderConfig,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ connected: Arc<RwLock<bool>>,
+}
+
+impl KrakenAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ Self {
+ config,
+ ws: None,
+ message_callback: None,
+ connected: Arc::new(RwLock::new(false)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_millis() as u64
+ }
+
+ /// Normalize Kraken symbol (XBT -> BTC)
+ fn normalize_kraken_symbol(symbol: &str) -> String {
+ symbol.replace("XBT", "BTC").replace('/', "")
+ }
+
+ /// Parse Kraken ticker message
+ fn parse_ticker(&self, data: &Value) -> Option<TickerData> {
+ let symbol = data.get("symbol")?.as_str()?;
+ let ticker_data = data.get("data")?.as_array()?.get(0)?;
+
+ let last = ticker_data.get("last")?.as_str()?.parse::<f64>().ok()?;
+ let bid = ticker_data.get("bid")?.as_str()?.parse::<f64>().ok();
+ let ask = ticker_data.get("ask")?.as_str()?.parse::<f64>().ok();
+ let volume = ticker_data.get("volume")?.as_str()?.parse::<f64>().ok();
+ let high = ticker_data.get("high")?.as_str()?.parse::<f64>().ok();
+ let low = ticker_data.get("low")?.as_str()?.parse::<f64>().ok();
+
+ Some(TickerData {
+ provider: "kraken".to_string(),
+ symbol: Self::normalize_kraken_symbol(symbol),
+ price: last,
+ bid,
+ ask,
+ bid_size: None,
+ ask_size: None,
+ volume,
+ high,
+ low,
+ open: None,
+ close: None,
+ change: None,
+ change_percent: None,
+ timestamp: Self::now(),
+ })
+ }
+
+ /// Parse Kraken order book message
+ fn parse_orderbook(&self, data: &Value, is_snapshot: bool) -> Option<OrderBookData> {
+ let symbol = data.get("symbol")?.as_str()?;
+ let book_data = data.get("data")?.as_array()?.get(0)?;
+
+ let parse_levels = |levels: &Value| -> Vec<OrderBookLevel> {
+ levels.as_array()
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|level| {
+ Some(OrderBookLevel {
+ price: level.get("price")?.as_str()?.parse().ok()?,
+ quantity: level.get("qty")?.as_str()?.parse().ok()?,
+ count: None,
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+ };
+
+ let bids = if let Some(b) = book_data.get("bids") {
+ parse_levels(b)
+ } else {
+ vec![]
+ };
+
+ let asks = if let Some(a) = book_data.get("asks") {
+ parse_levels(a)
+ } else {
+ vec![]
+ };
+
+ Some(OrderBookData {
+ provider: "kraken".to_string(),
+ symbol: Self::normalize_kraken_symbol(symbol),
+ bids,
+ asks,
+ timestamp: Self::now(),
+ is_snapshot,
+ })
+ }
+
+ /// Parse Kraken trade message
+ fn parse_trade(&self, data: &Value) -> Option<Vec<TradeData>> {
+ let symbol = data.get("symbol")?.as_str()?;
+ let trades = data.get("data")?.as_array()?;
+
+ Some(
+ trades
+ .iter()
+ .filter_map(|trade| {
+ let price = trade.get("price")?.as_str()?.parse().ok()?;
+ let qty = trade.get("qty")?.as_str()?.parse().ok()?;
+ let side_str = trade.get("side")?.as_str()?;
+
+ let side = match side_str {
+ "buy" => TradeSide::Buy,
+ "sell" => TradeSide::Sell,
+ _ => TradeSide::Unknown,
+ };
+
+ Some(TradeData {
+ provider: "kraken".to_string(),
+ symbol: Self::normalize_kraken_symbol(symbol),
+ trade_id: trade.get("trade_id").and_then(|v| v.as_str()).map(String::from),
+ price,
+ quantity: qty,
+ side,
+ timestamp: Self::now(),
+ })
+ })
+ .collect(),
+ )
+ }
+
+ /// Parse Kraken candle message
+ fn parse_candle(&self, data: &Value) -> Option<CandleData> {
+ let symbol = data.get("symbol")?.as_str()?;
+ let candle_data = data.get("data")?.as_array()?.get(0)?;
+
+ Some(CandleData {
+ provider: "kraken".to_string(),
+ symbol: Self::normalize_kraken_symbol(symbol),
+ open: candle_data.get("open")?.as_str()?.parse().ok()?,
+ high: candle_data.get("high")?.as_str()?.parse().ok()?,
+ low: candle_data.get("low")?.as_str()?.parse().ok()?,
+ close: candle_data.get("close")?.as_str()?.parse().ok()?,
+ volume: candle_data.get("volume")?.as_str()?.parse().ok()?,
+ timestamp: Self::now(),
+ interval: candle_data.get("interval")?.as_str()?.to_string(),
+ })
+ }
+
+ /// Handle incoming message
+ async fn handle_message(&self, msg: Message) {
+ if let Message::Text(text) = msg {
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ // Check message type
+ if let Some(channel) = data.get("channel").and_then(|c| c.as_str()) {
+ let market_msg = match channel {
+ "ticker" => {
+ self.parse_ticker(&data).map(MarketMessage::Ticker)
+ }
+ "book" => {
+ // Check if snapshot or update
+ let is_snapshot = data.get("type")
+ .and_then(|t| t.as_str())
+ .map(|t| t == "snapshot")
+ .unwrap_or(false);
+
+ self.parse_orderbook(&data, is_snapshot).map(MarketMessage::OrderBook)
+ }
+ "trade" => {
+ if let Some(trades) = self.parse_trade(&data) {
+ // Emit each trade separately
+ if let Some(callback) = &self.message_callback {
+ for trade in trades {
+ callback(MarketMessage::Trade(trade));
+ }
+ }
+ return;
+ }
+ None
+ }
+ "ohlc" => {
+ self.parse_candle(&data).map(MarketMessage::Candle)
+ }
+ _ => None,
+ };
+
+ if let Some(msg) = market_msg {
+ if let Some(callback) = &self.message_callback {
+ callback(msg);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /// Message receiver loop
+ async fn receive_loop(
+ ws: Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>,
+ callback: Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>,
+ connected: Arc<RwLock<bool>>,
+ ) {
+ loop {
+ let msg_result = {
+ let mut ws_lock = ws.write().await;
+ ws_lock.next().await
+ };
+
+ match msg_result {
+ Some(Ok(msg)) => {
+ // Handle message in separate task to avoid blocking
+ let adapter = KrakenAdapter {
+ config: ProviderConfig::default(),
+ ws: None,
+ message_callback: Some(callback.clone()),
+ connected: connected.clone(),
+ };
+ tokio::spawn(async move {
+ adapter.handle_message(msg).await;
+ });
+ }
+ Some(Err(e)) => {
+ eprintln!("[Kraken] WebSocket error: {}", e);
+ *connected.write().await = false;
+ break;
+ }
+ None => {
+ eprintln!("[Kraken] WebSocket connection closed");
+ *connected.write().await = false;
+ break;
+ }
+ }
+ }
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for KrakenAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ let url = self.config.url.clone();
+ let (ws_stream, _) = connect_async(if url.is_empty() { KRAKEN_WS_URL } else { &url }).await?;
+
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ *self.connected.write().await = true;
+
+ // Start receive loop
+ if let Some(callback) = self.message_callback.clone() {
+ let connected = self.connected.clone();
+ tokio::spawn(async move {
+ Self::receive_loop(ws, callback, connected).await;
+ });
+ }
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ *self.connected.write().await = false;
+
+ if let Some(ws) = &self.ws {
+ ws.write().await.close(None).await?;
+ }
+
+ self.ws = None;
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+
+ // Build subscription message
+ let mut sub_msg = serde_json::json!({
+ "method": "subscribe",
+ "params": {
+ "channel": channel,
+ "symbol": [symbol],
+ }
+ });
+
+ // Add optional params (depth, snapshot, etc.)
+ if let Some(p) = params {
+ if let Some(obj) = sub_msg.get_mut("params") {
+ if let Some(params_obj) = obj.as_object_mut() {
+ if let Some(p_obj) = p.as_object() {
+ for (k, v) in p_obj {
+ params_obj.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ }
+ }
+
+ let msg_str = serde_json::to_string(&sub_msg)?;
+ ws.write().await.send(Message::Text(msg_str)).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ let ws = self.ws.as_ref()
+ .ok_or_else(|| anyhow::anyhow!("Not connected"))?;
+
+ let unsub_msg = serde_json::json!({
+ "method": "unsubscribe",
+ "params": {
+ "channel": channel,
+ "symbol": [symbol],
+ }
+ });
+
+ let msg_str = serde_json::to_string(&unsub_msg)?;
+ ws.write().await.send(Message::Text(msg_str)).await?;
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "kraken"
+ }
+
+ fn is_connected(&self) -> bool {
+ // Use tokio runtime instead of futures executor
+ tokio::task::block_in_place(|| {
+ tokio::runtime::Handle::current().block_on(async {
+ *self.connected.read().await
+ })
+ })
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs
new file mode 100644
index 000000000..06f976eda
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs
@@ -0,0 +1,77 @@
+// WebSocket Adapters - Provider-specific implementations
+
+use super::types::*;
+use async_trait::async_trait;
+use std::sync::Arc;
+
+pub mod kraken;
+pub mod hyperliquid;
+pub mod fyers;
+
+pub use kraken::KrakenAdapter;
+pub use hyperliquid::HyperLiquidAdapter;
+pub use fyers::FyersAdapter;
+
+// ============================================================================
+// ADAPTER TRAIT
+// ============================================================================
+
+/// WebSocket adapter trait - all providers must implement this
+#[async_trait]
+pub trait WebSocketAdapter: Send + Sync {
+ /// Connect to WebSocket
+ async fn connect(&mut self) -> anyhow::Result<()>;
+
+ /// Disconnect from WebSocket
+ async fn disconnect(&mut self) -> anyhow::Result<()>;
+
+ /// Subscribe to a channel
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ params: Option<serde_json::Value>,
+ ) -> anyhow::Result<()>;
+
+ /// Unsubscribe from a channel
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()>;
+
+ /// Set message callback
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>);
+
+ /// Get provider name
+ fn provider_name(&self) -> &str;
+
+ /// Check if connected
+ fn is_connected(&self) -> bool;
+}
+
+// ============================================================================
+// ADAPTER FACTORY
+// ============================================================================
+
+/// Create adapter for a provider
+pub fn create_adapter(
+ provider: &str,
+ config: ProviderConfig,
+) -> anyhow::Result<Box<dyn WebSocketAdapter>> {
+ match provider.to_lowercase().as_str() {
+ "kraken" => Ok(Box::new(KrakenAdapter::new(config))),
+ "hyperliquid" => Ok(Box::new(HyperLiquidAdapter::new(config))),
+ "fyers" => Ok(Box::new(FyersAdapter::new(config))),
+ _ => Err(anyhow::anyhow!("Unknown provider: {}", provider)),
+ }
+}
+
+// ============================================================================
+// HELPER FUNCTIONS
+// ============================================================================
+
+/// Normalize symbol (remove special characters, uppercase)
+pub fn normalize_symbol(symbol: &str) -> String {
+ symbol
+ .replace('/', "")
+ .replace('-', "")
+ .replace('_', "")
+ .to_uppercase()
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/manager.rs b/fincept-terminal-desktop/src-tauri/src/websocket/manager.rs
new file mode 100644
index 000000000..776cab2cd
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/manager.rs
@@ -0,0 +1,354 @@
+// WebSocket Manager - Connection pool and lifecycle management
+//
+// Responsibilities:
+// - Maintain single connection per provider (connection pooling)
+// - Multiplex thousands of subscriptions over each connection
+// - Auto-reconnection with subscription restoration
+// - Lifecycle management (connect, disconnect, cleanup)
+// - Metrics tracking
+
+use super::adapters::{create_adapter, WebSocketAdapter};
+use super::router::MessageRouter;
+use super::types::*;
+use dashmap::DashMap;
+use std::sync::Arc;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio::time;
+
+/// WebSocket Manager - orchestrates all WebSocket connections
+pub struct WebSocketManager {
+ // Connection pool (1 connection per provider)
+ connections: Arc<DashMap<String, Arc<RwLock<Box<dyn WebSocketAdapter>>>>>,
+
+ // Message router
+ router: Arc<RwLock<MessageRouter>>,
+
+ // Provider configurations
+ configs: Arc<DashMap<String, ProviderConfig>>,
+
+ // Connection metrics
+ metrics: Arc<DashMap<String, ConnectionMetrics>>,
+
+ // Subscription tracking (provider -> symbol -> channels)
+ subscriptions: Arc<DashMap<String, DashMap<String, Vec<String>>>>,
+
+ // Prevent duplicate connections
+ connecting: Arc<DashMap<String, bool>>,
+}
+
+impl WebSocketManager {
+ pub fn new(router: Arc<RwLock<MessageRouter>>) -> Self {
+ Self {
+ connections: Arc::new(DashMap::new()),
+ router,
+ configs: Arc::new(DashMap::new()),
+ metrics: Arc::new(DashMap::new()),
+ subscriptions: Arc::new(DashMap::new()),
+ connecting: Arc::new(DashMap::new()),
+ }
+ }
+
+ // ========================================================================
+ // CONFIGURATION
+ // ========================================================================
+
+ /// Set provider configuration
+ pub fn set_config(&self, config: ProviderConfig) {
+ self.configs.insert(config.name.clone(), config);
+ }
+
+ /// Get provider configuration
+ pub fn get_config(&self, provider: &str) -> Option<ProviderConfig> {
+ self.configs.get(provider).map(|c| c.clone())
+ }
+
+ // ========================================================================
+ // CONNECTION MANAGEMENT
+ // ========================================================================
+
+ /// Connect to a provider
+ pub async fn connect(&self, provider: &str) -> Result<()> {
+ // Check if already connected
+ if self.is_connected(provider) {
+ return Err(WebSocketError::AlreadyConnected(provider.to_string()));
+ }
+
+ // Check if already connecting
+ if self.connecting.contains_key(provider) {
+ return Ok(()); // Wait for existing connection attempt
+ }
+
+ self.connecting.insert(provider.to_string(), true);
+
+ let result = self.connect_internal(provider).await;
+
+ self.connecting.remove(provider);
+
+ result
+ }
+
+ async fn connect_internal(&self, provider: &str) -> Result<()> {
+ // Get configuration
+ let config = self.get_config(provider)
+ .ok_or_else(|| WebSocketError::ProviderNotFound(provider.to_string()))?;
+
+ if !config.enabled {
+ return Err(WebSocketError::ConnectionError(
+ format!("Provider {} is disabled", provider)
+ ));
+ }
+
+ // Create adapter
+ let mut adapter = create_adapter(provider, config.clone())
+ .map_err(|e| WebSocketError::ConnectionError(e.to_string()))?;
+
+ // Set message callback
+ let router = self.router.clone();
+ adapter.set_message_callback(Box::new(move |msg| {
+ let router = router.clone();
+ tokio::spawn(async move {
+ router.read().await.route(msg).await;
+ });
+ }));
+
+ // Connect
+ adapter.connect().await
+ .map_err(|e| WebSocketError::ConnectionError(e.to_string()))?;
+
+ // Store connection
+ self.connections.insert(
+ provider.to_string(),
+ Arc::new(RwLock::new(adapter))
+ );
+
+ // Initialize metrics
+ let metrics = ConnectionMetrics {
+ provider: provider.to_string(),
+ status: ConnectionStatus::Connected,
+ connected_at: Some(Self::now()),
+ ..Default::default()
+ };
+ self.metrics.insert(provider.to_string(), metrics);
+
+ // Update status
+ self.emit_status(provider, ConnectionStatus::Connected, None).await;
+
+ Ok(())
+ }
+
+ /// Disconnect from a provider
+ pub async fn disconnect(&self, provider: &str) -> Result<()> {
+ if let Some((_, adapter)) = self.connections.remove(provider) {
+ adapter.write().await.disconnect().await
+ .map_err(|e| WebSocketError::ConnectionError(e.to_string()))?;
+
+ // Update metrics
+ if let Some(mut metrics) = self.metrics.get_mut(provider) {
+ metrics.status = ConnectionStatus::Disconnected;
+ metrics.connected_at = None;
+ }
+
+ // Update status
+ self.emit_status(provider, ConnectionStatus::Disconnected, None).await;
+
+ Ok(())
+ } else {
+ Err(WebSocketError::NotConnected(provider.to_string()))
+ }
+ }
+
+ /// Reconnect to a provider
+ pub async fn reconnect(&self, provider: &str) -> Result<()> {
+ // Get existing subscriptions
+ let subs = self.get_provider_subscriptions(provider);
+
+ // Disconnect
+ let _ = self.disconnect(provider).await;
+
+ // Small delay
+ time::sleep(Duration::from_millis(1000)).await;
+
+ // Connect
+ self.connect(provider).await?;
+
+ // Restore subscriptions
+ for (symbol, channels) in subs {
+ for channel in channels {
+ let _ = self.subscribe(provider, &symbol, &channel, None).await;
+ }
+ }
+
+ Ok(())
+ }
+
+ /// Check if provider is connected
+ pub fn is_connected(&self, provider: &str) -> bool {
+ self.connections.contains_key(provider)
+ }
+
+ // ========================================================================
+ // SUBSCRIPTION MANAGEMENT
+ // ========================================================================
+
+ /// Subscribe to a channel
+ pub async fn subscribe(
+ &self,
+ provider: &str,
+ symbol: &str,
+ channel: &str,
+ params: Option<serde_json::Value>,
+ ) -> Result<()> {
+ // Ensure connected
+ if !self.is_connected(provider) {
+ self.connect(provider).await?;
+ }
+
+ // Get adapter
+ let adapter = self.connections.get(provider)
+ .ok_or_else(|| WebSocketError::NotConnected(provider.to_string()))?;
+
+ // Subscribe via adapter
+ adapter.write().await.subscribe(symbol, channel, params).await
+ .map_err(|e| WebSocketError::SubscriptionError(e.to_string()))?;
+
+ // Track subscription
+ self.subscriptions
+ .entry(provider.to_string())
+ .or_insert_with(DashMap::new)
+ .entry(symbol.to_string())
+ .or_insert_with(Vec::new)
+ .push(channel.to_string());
+
+ // Update metrics
+ if let Some(mut metrics) = self.metrics.get_mut(provider) {
+ metrics.active_subscriptions = self.count_subscriptions(provider);
+ }
+
+ Ok(())
+ }
+
+ /// Unsubscribe from a channel
+ pub async fn unsubscribe(
+ &self,
+ provider: &str,
+ symbol: &str,
+ channel: &str,
+ ) -> Result<()> {
+ // Get adapter
+ let adapter = self.connections.get(provider)
+ .ok_or_else(|| WebSocketError::NotConnected(provider.to_string()))?;
+
+ // Unsubscribe via adapter
+ adapter.write().await.unsubscribe(symbol, channel).await
+ .map_err(|e| WebSocketError::SubscriptionError(e.to_string()))?;
+
+ // Remove from tracking
+ if let Some(provider_subs) = self.subscriptions.get(provider) {
+ if let Some(mut symbol_channels) = provider_subs.get_mut(symbol) {
+ symbol_channels.retain(|c| c != channel);
+ if symbol_channels.is_empty() {
+ provider_subs.remove(symbol);
+ }
+ }
+ }
+
+ // Update metrics
+ if let Some(mut metrics) = self.metrics.get_mut(provider) {
+ metrics.active_subscriptions = self.count_subscriptions(provider);
+ }
+
+ Ok(())
+ }
+
+ /// Get all subscriptions for a provider
+ fn get_provider_subscriptions(&self, provider: &str) -> Vec<(String, Vec<String>)> {
+ self.subscriptions.get(provider)
+ .map(|subs| {
+ subs.iter()
+ .map(|entry| (entry.key().clone(), entry.value().clone()))
+ .collect()
+ })
+ .unwrap_or_default()
+ }
+
+ /// Count total subscriptions for a provider
+ fn count_subscriptions(&self, provider: &str) -> usize {
+ self.subscriptions.get(provider)
+ .map(|subs| {
+ subs.iter()
+ .map(|entry| entry.value().len())
+ .sum()
+ })
+ .unwrap_or(0)
+ }
+
+ // ========================================================================
+ // METRICS
+ // ========================================================================
+
+ /// Get metrics for a provider
+ pub fn get_metrics(&self, provider: &str) -> Option<ConnectionMetrics> {
+ self.metrics.get(provider).map(|m| m.clone())
+ }
+
+ /// Get all metrics
+ pub fn get_all_metrics(&self) -> Vec<ConnectionMetrics> {
+ self.metrics.iter()
+ .map(|entry| entry.value().clone())
+ .collect()
+ }
+
+ /// Update message count
+ pub fn increment_message_count(&self, provider: &str) {
+ if let Some(mut metrics) = self.metrics.get_mut(provider) {
+ metrics.messages_received += 1;
+ metrics.last_message_at = Some(Self::now());
+ }
+ }
+
+ // ========================================================================
+ // UTILITIES
+ // ========================================================================
+
+ async fn emit_status(&self, provider: &str, status: ConnectionStatus, message: Option<String>) {
+ let status_data = StatusData {
+ provider: provider.to_string(),
+ status,
+ message,
+ timestamp: Self::now(),
+ };
+ self.router.read().await.route(MarketMessage::Status(status_data)).await;
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_millis() as u64
+ }
+
+ /// Cleanup idle connections (called periodically)
+ pub async fn cleanup_idle(&self, idle_timeout_ms: u64) {
+ let now = Self::now();
+ let mut to_remove = Vec::new();
+
+ for entry in self.metrics.iter() {
+ let provider = entry.key();
+ let metrics = entry.value();
+
+ if let Some(last_msg) = metrics.last_message_at {
+ if now - last_msg > idle_timeout_ms {
+ // No subscriptions and idle
+ if metrics.active_subscriptions == 0 {
+ to_remove.push(provider.clone());
+ }
+ }
+ }
+ }
+
+ for provider in to_remove {
+ let _ = self.disconnect(&provider).await;
+ }
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/mod.rs b/fincept-terminal-desktop/src-tauri/src/websocket/mod.rs
new file mode 100644
index 000000000..21ef9eef4
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/mod.rs
@@ -0,0 +1,18 @@
+// WebSocket Module - High-performance multi-provider WebSocket manager
+//
+// Architecture:
+// - Single connection per provider (connection pooling)
+// - Multiplexed subscriptions (1000s of symbols per connection)
+// - Event-driven message routing (broadcast channels)
+// - Auto-reconnection with subscription restoration
+// - Zero-copy message parsing and routing
+
+pub mod types;
+pub mod manager;
+pub mod router;
+pub mod adapters;
+pub mod services;
+
+pub use types::*;
+pub use manager::WebSocketManager;
+pub use router::MessageRouter;
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/router.rs b/fincept-terminal-desktop/src-tauri/src/websocket/router.rs
new file mode 100644
index 000000000..c90c5688c
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/router.rs
@@ -0,0 +1,194 @@
+// Message Router - Event-driven message distribution
+//
+// Routes parsed WebSocket messages to multiple consumers:
+// - Frontend UI (via Tauri events)
+// - Paper trading engine
+// - Arbitrage detector
+// - Portfolio tracker
+// - Analytics services
+
+use super::types::*;
+use dashmap::DashMap;
+use serde::Serialize;
+use std::sync::Arc;
+use tauri::Emitter;
+use tokio::sync::broadcast;
+
+const CHANNEL_CAPACITY: usize = 1000;
+
+/// Message router that broadcasts messages to multiple consumers
+pub struct MessageRouter {
+ // Broadcast channels for different message types
+ ticker_tx: broadcast::Sender<TickerData>,
+ orderbook_tx: broadcast::Sender<OrderBookData>,
+ trade_tx: broadcast::Sender<TradeData>,
+ candle_tx: broadcast::Sender<CandleData>,
+ status_tx: broadcast::Sender<StatusData>,
+
+ // Track which topics have frontend subscribers
+ frontend_subscribers: Arc<DashMap<String, bool>>,
+
+ // Tauri app handle for emitting events
+ app_handle: Option<tauri::AppHandle>,
+}
+
+impl MessageRouter {
+ pub fn new() -> Self {
+ let (ticker_tx, _) = broadcast::channel(CHANNEL_CAPACITY);
+ let (orderbook_tx, _) = broadcast::channel(CHANNEL_CAPACITY);
+ let (trade_tx, _) = broadcast::channel(CHANNEL_CAPACITY);
+ let (candle_tx, _) = broadcast::channel(CHANNEL_CAPACITY);
+ let (status_tx, _) = broadcast::channel(CHANNEL_CAPACITY);
+
+ Self {
+ ticker_tx,
+ orderbook_tx,
+ trade_tx,
+ candle_tx,
+ status_tx,
+ frontend_subscribers: Arc::new(DashMap::new()),
+ app_handle: None,
+ }
+ }
+
+ /// Set Tauri app handle for frontend event emission
+ pub fn set_app_handle(&mut self, app_handle: tauri::AppHandle) {
+ self.app_handle = Some(app_handle);
+ }
+
+ /// Register frontend subscriber for a topic
+ pub fn subscribe_frontend(&self, topic: &str) {
+ self.frontend_subscribers.insert(topic.to_string(), true);
+ }
+
+ /// Unregister frontend subscriber
+ pub fn unsubscribe_frontend(&self, topic: &str) {
+ self.frontend_subscribers.remove(topic);
+ }
+
+ /// Check if frontend is subscribed to topic
+ fn has_frontend_subscriber(&self, provider: &str, symbol: &str, channel: &str) -> bool {
+ let topic = format!("{}.{}.{}", provider, channel, symbol);
+ self.frontend_subscribers.contains_key(&topic)
+ }
+
+ /// Route message to all consumers
+ pub async fn route(&self, message: MarketMessage) {
+ match message {
+ MarketMessage::Ticker(data) => {
+ self.route_ticker(data).await;
+ }
+ MarketMessage::OrderBook(data) => {
+ self.route_orderbook(data).await;
+ }
+ MarketMessage::Trade(data) => {
+ self.route_trade(data).await;
+ }
+ MarketMessage::Candle(data) => {
+ self.route_candle(data).await;
+ }
+ MarketMessage::Status(data) => {
+ self.route_status(data).await;
+ }
+ }
+ }
+
+ // ========================================================================
+ // ROUTING METHODS
+ // ========================================================================
+
+ async fn route_ticker(&self, data: TickerData) {
+ // 1. Broadcast to backend services
+ let _ = self.ticker_tx.send(data.clone());
+
+ // 2. Emit to frontend if subscribed
+ if self.has_frontend_subscriber(&data.provider, &data.symbol, "ticker") {
+ self.emit_to_frontend("ws_ticker", &data);
+ }
+ }
+
+ async fn route_orderbook(&self, data: OrderBookData) {
+ // 1. Broadcast to backend services
+ let _ = self.orderbook_tx.send(data.clone());
+
+ // 2. Emit to frontend if subscribed
+ if self.has_frontend_subscriber(&data.provider, &data.symbol, "book") {
+ self.emit_to_frontend("ws_orderbook", &data);
+ }
+ }
+
+ async fn route_trade(&self, data: TradeData) {
+ // 1. Broadcast to backend services
+ let _ = self.trade_tx.send(data.clone());
+
+ // 2. Emit to frontend if subscribed
+ if self.has_frontend_subscriber(&data.provider, &data.symbol, "trade") {
+ self.emit_to_frontend("ws_trade", &data);
+ }
+ }
+
+ async fn route_candle(&self, data: CandleData) {
+ // 1. Broadcast to backend services
+ let _ = self.candle_tx.send(data.clone());
+
+ // 2. Emit to frontend if subscribed
+ if self.has_frontend_subscriber(&data.provider, &data.symbol, "candle") {
+ self.emit_to_frontend("ws_candle", &data);
+ }
+ }
+
+ async fn route_status(&self, data: StatusData) {
+ // 1. Broadcast to backend services
+ let _ = self.status_tx.send(data.clone());
+
+ // 2. Always emit status to frontend
+ self.emit_to_frontend("ws_status", &data);
+ }
+
+ // ========================================================================
+ // CHANNEL SUBSCRIPTIONS (for backend services)
+ // ========================================================================
+
+ /// Subscribe to ticker updates
+ pub fn subscribe_ticker(&self) -> broadcast::Receiver<TickerData> {
+ self.ticker_tx.subscribe()
+ }
+
+ /// Subscribe to orderbook updates
+ pub fn subscribe_orderbook(&self) -> broadcast::Receiver<OrderBookData> {
+ self.orderbook_tx.subscribe()
+ }
+
+ /// Subscribe to trade updates
+ pub fn subscribe_trade(&self) -> broadcast::Receiver<TradeData> {
+ self.trade_tx.subscribe()
+ }
+
+ /// Subscribe to candle updates
+ pub fn subscribe_candle(&self) -> broadcast::Receiver<CandleData> {
+ self.candle_tx.subscribe()
+ }
+
+ /// Subscribe to status updates
+ pub fn subscribe_status(&self) -> broadcast::Receiver<StatusData> {
+ self.status_tx.subscribe()
+ }
+
+ // ========================================================================
+ // FRONTEND EMISSION
+ // ========================================================================
+
+ fn emit_to_frontend<T: Serialize + Clone>(&self, event: &str, payload: &T) {
+ if let Some(app) = &self.app_handle {
+ if let Err(e) = app.emit(event, payload) {
+ eprintln!("[Router] Failed to emit {} event: {}", event, e);
+ }
+ }
+ }
+}
+
+impl Default for MessageRouter {
+ fn default() -> Self {
+ Self::new()
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/services/arbitrage.rs b/fincept-terminal-desktop/src-tauri/src/websocket/services/arbitrage.rs
new file mode 100644
index 000000000..8dc8a9c79
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/services/arbitrage.rs
@@ -0,0 +1,37 @@
+// Arbitrage Detection Service (Stub - to be fully implemented)
+
+use crate::websocket::types::*;
+use dashmap::DashMap;
+use std::sync::Arc;
+
+pub struct ArbitrageService {
+ prices: Arc<DashMap<String, DashMap<String, f64>>>, // symbol -> provider -> price
+}
+
+impl ArbitrageService {
+ pub fn new() -> Self {
+ Self {
+ prices: Arc::new(DashMap::new()),
+ }
+ }
+
+ pub fn update_price(&self, data: &TickerData) {
+ self.prices
+ .entry(data.symbol.clone())
+ .or_insert_with(DashMap::new)
+ .insert(data.provider.clone(), data.price);
+ }
+
+ pub fn check_arbitrage(&self, symbol: &str) -> Option<f64> {
+ if let Some(providers) = self.prices.get(symbol) {
+ if providers.len() >= 2 {
+ let prices: Vec<f64> = providers.iter().map(|p| *p.value()).collect();
+ let min = prices.iter().copied().fold(f64::INFINITY, f64::min);
+ let max = prices.iter().copied().fold(f64::NEG_INFINITY, f64::max);
+ let spread = (max - min) / min * 100.0;
+ return Some(spread);
+ }
+ }
+ None
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/services/mod.rs b/fincept-terminal-desktop/src-tauri/src/websocket/services/mod.rs
new file mode 100644
index 000000000..9f2466cae
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/services/mod.rs
@@ -0,0 +1,9 @@
+// Backend Services - consume WebSocket data in Rust
+
+pub mod paper_trading;
+pub mod arbitrage;
+pub mod portfolio;
+
+pub use paper_trading::PaperTradingService;
+pub use arbitrage::ArbitrageService;
+pub use portfolio::PortfolioService;
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/services/paper_trading.rs b/fincept-terminal-desktop/src-tauri/src/websocket/services/paper_trading.rs
new file mode 100644
index 000000000..9c14553cc
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/services/paper_trading.rs
@@ -0,0 +1,29 @@
+// Paper Trading Service (Stub - to be fully implemented)
+
+use crate::websocket::types::*;
+use dashmap::DashMap;
+use std::sync::Arc;
+
+pub struct PaperTradingService {
+ price_cache: Arc<DashMap<String, f64>>,
+}
+
+impl PaperTradingService {
+ pub fn new() -> Self {
+ Self {
+ price_cache: Arc::new(DashMap::new()),
+ }
+ }
+
+ pub fn update_price(&self, data: &TickerData) {
+ self.price_cache.insert(
+ format!("{}.{}", data.provider, data.symbol),
+ data.price
+ );
+ }
+
+ pub fn get_price(&self, provider: &str, symbol: &str) -> Option<f64> {
+ let key = format!("{}.{}", provider, symbol);
+ self.price_cache.get(&key).map(|v| *v)
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/services/portfolio.rs b/fincept-terminal-desktop/src-tauri/src/websocket/services/portfolio.rs
new file mode 100644
index 000000000..43a6d170a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/services/portfolio.rs
@@ -0,0 +1,17 @@
+// Portfolio Tracking Service (Stub - to be fully implemented)
+
+use crate::websocket::types::*;
+
+pub struct PortfolioService {
+ // TODO: Implement portfolio tracking
+}
+
+impl PortfolioService {
+ pub fn new() -> Self {
+ Self {}
+ }
+
+ pub fn update_price(&self, _data: &TickerData) {
+ // TODO: Update position values
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/types.rs b/fincept-terminal-desktop/src-tauri/src/websocket/types.rs
new file mode 100644
index 000000000..56169ea56
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/types.rs
@@ -0,0 +1,227 @@
+// WebSocket Type Definitions
+// Normalized message formats for all providers
+
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+
+// ============================================================================
+// CORE MESSAGE TYPES
+// ============================================================================
+
+/// Normalized market message - all providers convert to this format
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "lowercase")]
+pub enum MarketMessage {
+ Ticker(TickerData),
+ OrderBook(OrderBookData),
+ Trade(TradeData),
+ Candle(CandleData),
+ Status(StatusData),
+}
+
+/// Ticker/Quote data
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TickerData {
+ pub provider: String,
+ pub symbol: String,
+ pub price: f64,
+ pub bid: Option<f64>,
+ pub ask: Option<f64>,
+ pub bid_size: Option<f64>,
+ pub ask_size: Option<f64>,
+ pub volume: Option<f64>,
+ pub high: Option<f64>,
+ pub low: Option<f64>,
+ pub open: Option<f64>,
+ pub close: Option<f64>,
+ pub change: Option<f64>,
+ pub change_percent: Option<f64>,
+ pub timestamp: u64,
+}
+
+/// Order book data (market depth)
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct OrderBookData {
+ pub provider: String,
+ pub symbol: String,
+ pub bids: Vec<OrderBookLevel>,
+ pub asks: Vec<OrderBookLevel>,
+ pub timestamp: u64,
+ pub is_snapshot: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct OrderBookLevel {
+ pub price: f64,
+ pub quantity: f64,
+ pub count: Option<u32>,
+}
+
+/// Trade execution data
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TradeData {
+ pub provider: String,
+ pub symbol: String,
+ pub trade_id: Option<String>,
+ pub price: f64,
+ pub quantity: f64,
+ pub side: TradeSide,
+ pub timestamp: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum TradeSide {
+ Buy,
+ Sell,
+ Unknown,
+}
+
+/// OHLCV candle data
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CandleData {
+ pub provider: String,
+ pub symbol: String,
+ pub open: f64,
+ pub high: f64,
+ pub low: f64,
+ pub close: f64,
+ pub volume: f64,
+ pub timestamp: u64,
+ pub interval: String,
+}
+
+/// Connection/status data
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct StatusData {
+ pub provider: String,
+ pub status: ConnectionStatus,
+ pub message: Option<String>,
+ pub timestamp: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum ConnectionStatus {
+ Connected,
+ Connecting,
+ Disconnected,
+ Reconnecting,
+ Error,
+}
+
+// ============================================================================
+// SUBSCRIPTION TYPES
+// ============================================================================
+
+/// Subscription request
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SubscriptionRequest {
+ pub provider: String,
+ pub symbol: String,
+ pub channels: Vec<String>, // ["ticker", "book", "trade", "candle"]
+ pub params: Option<HashMap<String, serde_json::Value>>,
+}
+
+/// Subscription info
+#[derive(Debug, Clone)]
+pub struct Subscription {
+ pub id: String,
+ pub provider: String,
+ pub symbol: String,
+ pub channel: String,
+ pub params: Option<HashMap<String, serde_json::Value>>,
+}
+
+// ============================================================================
+// PROVIDER CONFIG
+// ============================================================================
+
+/// Provider configuration
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProviderConfig {
+ pub name: String,
+ pub url: String,
+ pub api_key: Option<String>,
+ pub api_secret: Option<String>,
+ pub enabled: bool,
+ pub reconnect_delay_ms: u64,
+ pub max_reconnect_attempts: u32,
+ pub heartbeat_interval_ms: u64,
+}
+
+impl Default for ProviderConfig {
+ fn default() -> Self {
+ Self {
+ name: String::new(),
+ url: String::new(),
+ api_key: None,
+ api_secret: None,
+ enabled: true,
+ reconnect_delay_ms: 5000,
+ max_reconnect_attempts: 10,
+ heartbeat_interval_ms: 30000,
+ }
+ }
+}
+
+// ============================================================================
+// METRICS
+// ============================================================================
+
+/// Connection metrics
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ConnectionMetrics {
+ pub provider: String,
+ pub status: ConnectionStatus,
+ pub connected_at: Option<u64>,
+ pub last_message_at: Option<u64>,
+ pub messages_received: u64,
+ pub messages_sent: u64,
+ pub active_subscriptions: usize,
+ pub reconnect_count: u32,
+ pub latency_ms: Option<u64>,
+}
+
+impl Default for ConnectionMetrics {
+ fn default() -> Self {
+ Self {
+ provider: String::new(),
+ status: ConnectionStatus::Disconnected,
+ connected_at: None,
+ last_message_at: None,
+ messages_received: 0,
+ messages_sent: 0,
+ active_subscriptions: 0,
+ reconnect_count: 0,
+ latency_ms: None,
+ }
+ }
+}
+
+// ============================================================================
+// ERROR TYPES
+// ============================================================================
+
+#[derive(Debug, thiserror::Error)]
+pub enum WebSocketError {
+ #[error("Connection error: {0}")]
+ ConnectionError(String),
+
+ #[error("Parse error: {0}")]
+ ParseError(String),
+
+ #[error("Provider not found: {0}")]
+ ProviderNotFound(String),
+
+ #[error("Subscription error: {0}")]
+ SubscriptionError(String),
+
+ #[error("Already connected: {0}")]
+ AlreadyConnected(String),
+
+ #[error("Not connected: {0}")]
+ NotConnected(String),
+}
+
+pub type Result<T> = std::result::Result<T, WebSocketError>;
diff --git a/fincept-terminal-desktop/src/App.tsx b/fincept-terminal-desktop/src/App.tsx
index e104c5e91..e8727383a 100644
--- a/fincept-terminal-desktop/src/App.tsx
+++ b/fincept-terminal-desktop/src/App.tsx
@@ -7,7 +7,6 @@ import { NavigationProvider } from './contexts/NavigationContext';
import { ThemeProvider } from './contexts/ThemeContext';
import { DataSourceProvider } from './contexts/DataSourceContext';
import { ProviderProvider } from './contexts/ProviderContext';
-import { setPaymentWindowManager } from './services/paymentApi';
import { workflowService } from './services/workflowService';
// Import screens
@@ -26,7 +25,6 @@ import DashboardScreen from './components/dashboard/DashboardScreen';
import BackgroundPattern from './components/common/BackgroundPattern';
import Header from './components/common/Header';
import Footer from './components/common/Footer';
-import PaymentOverlay from './components/payment/PaymentOverlay';
import SetupScreen from './components/setup/SetupScreen';
import { Toaster } from 'sonner';
@@ -44,16 +42,6 @@ export type Screen =
| 'paymentSuccess'
| 'dashboard';
-interface PaymentWindowState {
- isOpen: boolean;
- checkoutUrl: string;
- planName: string;
- planPrice: number;
- onSuccess?: () => void;
- onCancel?: () => void;
- onError?: (error: string) => void;
-}
-
const App: React.FC = () => {
const { session, isLoading } = useAuth();
const [currentScreen, setCurrentScreen] = useState<Screen>('login');
@@ -62,12 +50,6 @@ const App: React.FC = () => {
const [activeTab, setActiveTab] = useState('dashboard');
const [setupComplete, setSetupComplete] = useState(false);
const [checkingSetup, setCheckingSetup] = useState(true);
- const [paymentWindow, setPaymentWindow] = useState<PaymentWindowState>({
- isOpen: false,
- checkoutUrl: '',
- planName: '',
- planPrice: 0
- });
// Check setup status on app initialization
useEffect(() => {
@@ -88,55 +70,14 @@ const App: React.FC = () => {
checkSetup();
}, []);
- // Set up payment window manager on app initialization
- useEffect(() => {
- const paymentManager = {
- openPaymentWindow: (
- url: string,
- planName: string,
- planPrice: number
- ): Promise<boolean> => {
- return new Promise((resolve) => {
- console.log('PaymentManager: Opening payment window for:', planName);
-
- setPaymentWindow({
- isOpen: true,
- checkoutUrl: url,
- planName,
- planPrice,
- onSuccess: () => {
- console.log('PaymentManager: Payment completed successfully');
- setPaymentWindow(prev => ({ ...prev, isOpen: false }));
- setCurrentScreen('paymentProcessing');
- resolve(true);
- },
- onCancel: () => {
- console.log('PaymentManager: Payment cancelled by user');
- setPaymentWindow(prev => ({ ...prev, isOpen: false }));
- setCurrentScreen('pricing');
- resolve(false);
- },
- onError: (error: string) => {
- console.error('PaymentManager: Payment error:', error);
- setPaymentWindow(prev => ({ ...prev, isOpen: false }));
- setCurrentScreen('pricing');
- resolve(false);
- }
- });
- });
- }
- };
-
- setPaymentWindowManager(paymentManager);
- console.log('PaymentManager: Initialized in-app payment window manager');
- }, []);
+ // Payment window manager no longer needed - using external browser
+ // Removed in-app payment window code
// Cleanup running workflows on app unmount
useEffect(() => {
return () => {
- console.log('[App] App unmounting, cleaning up running workflows...');
workflowService.cleanupRunningWorkflows().catch((error: Error) => {
- console.error('[App] Failed to cleanup running workflows:', error);
+ console.error('Failed to cleanup running workflows:', error);
});
};
}, []);
@@ -147,56 +88,44 @@ const App: React.FC = () => {
const sessionId = urlParams.get('session_id');
const paymentId = urlParams.get('payment_id');
- // If we have payment parameters, go directly to success screen (don't wait for session)
if (sessionId || paymentId) {
- console.log('Payment success URL detected, redirecting to payment success screen');
setCurrentScreen('paymentSuccess');
- // Clear URL parameters to prevent issues on refresh
window.history.replaceState({}, document.title, window.location.pathname);
return;
}
- }, []); // Run only once on mount
+ }, []);
// Auto-navigation based on authentication state
useEffect(() => {
- console.log('App.tsx useEffect triggered:', {
- session: session?.authenticated,
- isLoading,
- currentScreen,
- userType: session?.user_type,
- accountType: session?.user_info?.account_type,
- hasSubscription: session?.subscription?.has_subscription,
- cameFromLogin,
- hasChosenFreePlan
- });
-
if (!isLoading) {
if (session?.authenticated) {
- console.log('Session is authenticated');
-
- // Check if user is on free plan and needs to see pricing
const isFreePlan = session.user_info?.account_type === 'free';
- const hasActiveSubscription = (session.subscription as any)?.data?.has_subscription || session.subscription?.has_subscription;
+ const hasPaidPlan = session.user_info?.account_type &&
+ ['basic', 'standard', 'pro', 'enterprise'].includes(session.user_info.account_type);
- // Show pricing if:
- // 1. User is registered with free account type AND
- // 2. No active subscription AND
- // 3. Either came from fresh login OR hasn't chosen free plan yet
- if (session.user_type === 'registered' &&
+ // If user has a paid plan (basic, standard, pro, enterprise), go to dashboard
+ if (session.user_type === 'registered' && hasPaidPlan) {
+ if (currentScreen !== 'paymentProcessing' &&
+ currentScreen !== 'paymentSuccess' &&
+ currentScreen !== 'pricing' &&
+ currentScreen !== 'dashboard') {
+ console.log('User has paid plan, navigating to dashboard');
+ setCurrentScreen('dashboard');
+ }
+ }
+ // If free plan user just logged in, show pricing
+ else if (session.user_type === 'registered' &&
isFreePlan &&
- !hasActiveSubscription &&
currentScreen !== 'pricing' &&
currentScreen !== 'paymentProcessing' &&
currentScreen !== 'paymentSuccess' &&
(cameFromLogin || !hasChosenFreePlan)) {
- console.log('Free user without subscription detected, showing pricing screen');
setCurrentScreen('pricing');
- } else if (hasActiveSubscription ||
- session.user_type === 'guest' ||
+ }
+ // Guest users or free plan users who chose to continue with free
+ else if (session.user_type === 'guest' ||
(hasChosenFreePlan && !cameFromLogin) ||
(isFreePlan && hasChosenFreePlan)) {
- console.log('User has subscription, is guest, or chose free plan - redirecting to dashboard');
- // Don't force redirect if user manually navigated to pricing
if (currentScreen !== 'paymentProcessing' &&
currentScreen !== 'paymentSuccess' &&
currentScreen !== 'pricing') {
@@ -204,14 +133,11 @@ const App: React.FC = () => {
}
}
} else {
- console.log('Session not authenticated, staying on auth screens');
- // Don't redirect if on payment success screen - let it handle authentication internally
if (currentScreen === 'dashboard' ||
currentScreen === 'pricing' ||
currentScreen === 'paymentProcessing') {
setCurrentScreen('login');
}
- // Don't reset flags or redirect from paymentSuccess - it needs to complete first
if (currentScreen !== 'paymentSuccess') {
setHasChosenFreePlan(false);
setCameFromLogin(false);
@@ -263,8 +189,6 @@ const App: React.FC = () => {
</ThemeProvider>
</DataSourceProvider>
</ProviderProvider>
- {/* In-App Payment Window Overlay */}
- <PaymentOverlay paymentWindow={paymentWindow} />
{/* Toast Notifications */}
<Toaster position="top-right" richColors closeButton />
</>
@@ -279,8 +203,6 @@ const App: React.FC = () => {
<div className="relative z-10 flex items-center justify-center">
{renderPaymentScreen()}
</div>
- {/* In-App Payment Window Overlay */}
- <PaymentOverlay paymentWindow={paymentWindow} />
</div>
);
}
@@ -374,18 +296,15 @@ const App: React.FC = () => {
};
return (
- <div className="min-h-screen bg-black relative overflow-hidden flex flex-col" style={{ minHeight: '100vh', height: '100%' }}>
+ <div className="h-screen bg-black relative overflow-hidden flex flex-col">
<BackgroundPattern />
<Header onNavigate={setCurrentScreen} />
- <div className="relative z-10 flex items-center justify-center flex-1">
+ <div className="relative z-10 flex items-center justify-center flex-1 overflow-hidden">
{renderCurrentScreen()}
</div>
<Footer onNavigate={setCurrentScreen} />
-
- {/* In-App Payment Window Overlay - Available on all screens */}
- <PaymentOverlay paymentWindow={paymentWindow} />
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
index a0208b81d..9f1996471 100644
--- a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
+++ b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
@@ -36,15 +36,11 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
setError("");
try {
- console.log('Login attempt for:', email);
-
const result = await login(email, password);
if (result.success) {
- console.log('Login successful - App.tsx will handle routing based on account type');
// App.tsx useEffect will handle navigation based on account_type
} else {
- console.log('Login failed:', result.error);
// Provide user-friendly error messages
const errorMessage = result.error || 'Login failed. Please check your credentials.';
@@ -70,7 +66,6 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
}
}
} catch (err) {
- console.error('Login error:', err);
setError(t('login.errors.unexpectedError'));
} finally {
setIsLoading(false);
@@ -82,19 +77,14 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
setError("");
try {
- console.log('Setting up guest access...');
-
const result = await setupGuestAccess();
if (result.success) {
- console.log('Guest access setup successful - App.tsx will handle routing');
// App.tsx useEffect will handle navigation to dashboard
} else {
- console.log('Guest access setup failed:', result.error);
setError(result.error || t('login.errors.guestSetupFailed'));
}
} catch (err) {
- console.error('Guest access error:', err);
setError(t('login.errors.guestSetupFailed'));
} finally {
setIsGuestLoading(false);
diff --git a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx
index eb96a68ac..a79387d65 100644
--- a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx
+++ b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx
@@ -25,48 +25,63 @@ const PricingScreen: React.FC<PricingScreenProps> = ({
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string>('');
const [hasLoadedPlans, setHasLoadedPlans] = useState(false);
+ const [showDowngradeConfirm, setShowDowngradeConfirm] = useState(false);
+ const [pendingPlanSelection, setPendingPlanSelection] = useState<string>('');
// Prevent multiple simultaneous requests
const loadingRef = useRef(false);
const retryTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
+ const retryCountRef = useRef(0);
+ const MAX_RETRIES = 2; // Only retry twice to prevent infinite loops
// Load plans on component mount - with debouncing
useEffect(() => {
const loadPlans = async () => {
- // Prevent multiple simultaneous requests
if (loadingRef.current || hasLoadedPlans || isLoadingPlans) {
- console.log('Skipping plan load - already in progress or completed');
return;
}
if (availablePlans.length > 0) {
- console.log('Plans already available, skipping load');
setHasLoadedPlans(true);
return;
}
loadingRef.current = true;
- console.log('Loading subscription plans from API...');
try {
const result = await fetchPlans();
if (result.success) {
setHasLoadedPlans(true);
setError('');
+ retryCountRef.current = 0;
} else {
setError(result.error || 'Failed to load subscription plans');
- // Retry after 3 seconds if it failed
+ if (retryCountRef.current < MAX_RETRIES) {
+ retryCountRef.current += 1;
+
+ retryTimeoutRef.current = setTimeout(() => {
+ loadingRef.current = false;
+ setHasLoadedPlans(false);
+ loadPlans();
+ }, 3000);
+ } else {
+ setError('Unable to load plans after multiple attempts. Please try again later or continue with free plan.');
+ }
+ }
+ } catch (err) {
+ console.error('Error loading plans:', err);
+ setError('Failed to load subscription plans');
+
+ if (retryCountRef.current < MAX_RETRIES) {
+ retryCountRef.current += 1;
+
retryTimeoutRef.current = setTimeout(() => {
- console.log('Retrying to load plans...');
loadingRef.current = false;
setHasLoadedPlans(false);
loadPlans();
}, 3000);
}
- } catch (err) {
- console.error('Error loading plans:', err);
- setError('Failed to load subscription plans');
} finally {
loadingRef.current = false;
}
@@ -101,6 +116,11 @@ const PricingScreen: React.FC<PricingScreenProps> = ({
const getPlanIcon = (planId: string) => {
const iconMap: Record<string, React.ReactNode> = {
+ 'free': <Shield className="w-4 h-4" />,
+ 'basic': <Shield className="w-4 h-4" />,
+ 'standard': <Star className="w-4 h-4" />,
+ 'pro': <Crown className="w-4 h-4" />,
+ 'enterprise': <Zap className="w-4 h-4" />,
'starter_20': <Star className="w-4 h-4" />,
'professional_49': <Zap className="w-4 h-4" />,
'enterprise_99': <Crown className="w-4 h-4" />,
@@ -109,6 +129,46 @@ const PricingScreen: React.FC<PricingScreenProps> = ({
return iconMap[planId] || <Shield className="w-4 h-4" />;
};
+ // Check if selecting a plan is a downgrade
+ const isDowngrade = (targetPlanId: string): boolean => {
+ const currentPlanId = session?.user_info?.account_type || 'free';
+ const planTiers: { [key: string]: number } = {
+ 'free': 0,
+ 'basic': 1,
+ 'standard': 2,
+ 'pro': 3,
+ 'enterprise': 4
+ };
+
+ const currentTier = planTiers[currentPlanId] || 0;
+ const targetTier = planTiers[targetPlanId] || 0;
+
+ return targetTier < currentTier && currentTier > 0;
+ };
+
+ // Handle plan selection with downgrade confirmation
+ const handlePlanClick = (planId: string) => {
+ if (isDowngrade(planId)) {
+ setPendingPlanSelection(planId);
+ setShowDowngradeConfirm(true);
+ } else {
+ setSelectedPlan(planId);
+ }
+ };
+
+ // Confirm downgrade
+ const confirmDowngrade = () => {
+ setSelectedPlan(pendingPlanSelection);
+ setShowDowngradeConfirm(false);
+ setPendingPlanSelection('');
+ };
+
+ // Cancel downgrade
+ const cancelDowngrade = () => {
+ setShowDowngradeConfirm(false);
+ setPendingPlanSelection('');
+ };
+
const handleSelectPlan = async () => {
if (!selectedPlan) {
setError('Please select a plan');
@@ -124,30 +184,36 @@ const handleSelectPlan = async () => {
setError('');
try {
- console.log('Creating payment session for plan:', selectedPlan);
-
- const result = await createPaymentSession(selectedPlan);
+ const result = await createPaymentSession(selectedPlan, 'USD');
if (result.success && result.data) {
- console.log('Payment session created:', result.data);
+ console.log('=== PAYMENT SESSION DEBUG ===');
+ console.log('Full response data:', JSON.stringify(result.data, null, 2));
+ console.log('checkout_url:', result.data.checkout_url);
+ console.log('session_id:', result.data.session_id);
+ console.log('order_id:', result.data.payment_uuid);
+ console.log('========================');
- // DEBUG: Log the exact structure
- console.log('result.data structure:', JSON.stringify(result.data, null, 2));
- console.log('checkout_url direct access:', (result.data as any).checkout_url);
- console.log('checkout_url via data.data:', (result.data as any).data?.checkout_url);
+ // Use checkout_url from the new API format
+ const checkoutUrl = result.data.checkout_url;
- // Try different data access patterns
- const checkoutUrl = (result.data as any).checkout_url || (result.data as any).data?.checkout_url;
+ if (checkoutUrl && checkoutUrl !== 'undefined') {
+ console.log('Opening payment in external browser:', checkoutUrl);
- if (checkoutUrl) {
- console.log('Found checkout URL:', checkoutUrl);
+ // Store order_id in localStorage for payment processing screen
+ localStorage.setItem('pending_payment_order_id', result.data.payment_uuid);
+ // Open in external browser using Tauri shell
+ const { open } = await import('@tauri-apps/plugin-shell');
+ await open(checkoutUrl);
- PaymentUtils.openPaymentUrl(checkoutUrl);
+ // Navigate to payment processing screen which will poll for status
onNavigate('paymentProcessing' as Screen);
} else {
- console.error('No checkout URL found in result data');
- setError('No payment URL received. Please try again.');
+ console.error('❌ No checkout_url found in response!');
+ console.error('Available fields:', Object.keys(result.data));
+ console.error('Full response:', result.data);
+ setError(`No payment session received. Available fields: ${Object.keys(result.data).join(', ')}`);
}
} else {
console.error('Failed to create payment session:', result.error);
@@ -162,7 +228,6 @@ const handleSelectPlan = async () => {
};
const handleContinueWithFree = () => {
- console.log('Continuing with free plan');
onProceedToDashboard();
};
@@ -170,8 +235,8 @@ const handleSelectPlan = async () => {
setError('');
setHasLoadedPlans(false);
loadingRef.current = false;
+ retryCountRef.current = 0;
- console.log('Manual retry - loading plans...');
const result = await fetchPlans();
if (result.success) {
setHasLoadedPlans(true);
@@ -183,23 +248,21 @@ const handleSelectPlan = async () => {
const getPlanCard = (plan: any) => {
const isSelected = selectedPlan === plan.plan_id;
const displayPrice = plan.price_usd;
- const priceUnit = 'month';
- // Determine if plan is popular or recommended
- const isPopular = plan.plan_id === 'starter_20';
- const isRecommended = plan.plan_id === 'unlimited_199';
+ // Use API's is_popular flag
+ const isPopular = plan.is_popular;
+ const isRecommended = plan.plan_id === 'pro' || plan.plan_id === 'enterprise';
// Check if this is the current plan
- const currentPlanId = (session?.subscription as any)?.data?.subscription?.plan?.plan_id ||
- session?.subscription?.subscription?.plan?.plan_id;
+ const currentPlanId = session?.user_info?.account_type || 'free';
const isCurrentPlan = currentPlanId === plan.plan_id;
return (
<div
key={plan.plan_id}
- onClick={() => !isCurrentPlan && setSelectedPlan(plan.plan_id)}
+ onClick={() => !isCurrentPlan && handlePlanClick(plan.plan_id)}
className={`
- relative rounded-lg border-2 p-4 transition-all duration-200
+ relative rounded-lg border-2 p-4 transition-all duration-200 flex flex-col
${isCurrentPlan
? 'border-green-500 bg-green-600/10 cursor-default'
: isSelected
@@ -232,6 +295,7 @@ const handleSelectPlan = async () => {
</div>
)}
+ {/* Header Section - Fixed Height */}
<div className="text-center mb-3">
<div className={`
inline-flex items-center justify-center w-8 h-8 rounded-full mb-2
@@ -245,47 +309,42 @@ const handleSelectPlan = async () => {
<div className="mb-2">
<div className="flex items-baseline justify-center">
<span className="text-2xl font-bold text-white">
- {PaymentUtils.formatCurrency(displayPrice)}
+ {plan.price_display}
</span>
- <span className="text-zinc-400 text-xs ml-1">/{priceUnit}</span>
</div>
</div>
- <p className="text-zinc-400 text-xs">{plan.description}</p>
+ <p className="text-zinc-400 text-xs h-10 line-clamp-2">{plan.description}</p>
</div>
- <div className="space-y-2 mb-3">
+ {/* Credits/Validity Section - Fixed Height */}
+ <div className="mb-3">
<div className="grid grid-cols-2 gap-1 text-xs">
<div className="bg-zinc-800/30 p-1.5 rounded text-center">
- <div className="text-zinc-400 text-xs">{plan.features.api_calls}</div>
- <div className="text-white font-medium text-xs">API Calls</div>
+ <div className="text-zinc-400 text-xs">{plan.credits_amount.toLocaleString()}</div>
+ <div className="text-white font-medium text-xs">Credits</div>
</div>
<div className="bg-zinc-800/30 p-1.5 rounded text-center">
- <div className="text-zinc-400 text-xs">{plan.features.databases}</div>
- <div className="text-white font-medium text-xs">Databases</div>
+ <div className="text-zinc-400 text-xs">{plan.validity_display}</div>
+ <div className="text-white font-medium text-xs">Validity</div>
</div>
</div>
</div>
- <div className="space-y-1">
+ {/* Features Section - Flexible Height */}
+ <div className="flex-1">
<div className="text-xs text-zinc-300 space-y-0.5">
<div className="flex items-center">
<Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />
- <span>{plan.features.support}</span>
+ <span>{plan.support_display}</span>
</div>
- {plan.priority_support && (
- <div className="flex items-center">
- <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />
- <span>Priority support</span>
- </div>
- )}
<div className="flex items-center">
<Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />
- <span>Real-time data</span>
+ <span>All API endpoints</span>
</div>
<div className="flex items-center">
<Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />
- <span>Custom dashboards</span>
+ <span>Real-time data access</span>
</div>
</div>
</div>
@@ -344,16 +403,66 @@ const handleSelectPlan = async () => {
const selectedPlanData = availablePlans.find(p => p.plan_id === selectedPlan);
- // Get current plan info
- const currentPlanId = (session?.subscription as any)?.data?.subscription?.plan?.plan_id ||
- session?.subscription?.subscription?.plan?.plan_id;
+ // Get current plan info (credit-based system)
+ // In credit system, users can always buy more credits
+ // Free plan users have 350 credits, can purchase any plan
+ const currentPlanId = session?.user_info?.account_type || 'free';
const currentPlanData = availablePlans.find(p => p.plan_id === currentPlanId);
- const hasActiveSubscription = (session?.subscription as any)?.data?.has_subscription ||
- session?.subscription?.has_subscription;
+ const hasActiveSubscription = !!session?.user_info?.account_type && session.user_info.account_type !== 'free';
const isCurrentPlanSelected = selectedPlan === currentPlanId;
+ const pendingPlanData = availablePlans.find(p => p.plan_id === pendingPlanSelection);
return (
- <div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-6 w-full max-w-5xl mx-auto shadow-2xl">
+ <>
+ {/* Downgrade Confirmation Modal */}
+ {showDowngradeConfirm && pendingPlanData && currentPlanData && (
+ <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50">
+ <div className="bg-zinc-900 border border-zinc-700 rounded-xl p-6 max-w-md mx-4 shadow-2xl">
+ <div className="flex items-center mb-4">
+ <AlertCircle className="w-6 h-6 text-orange-500 mr-3" />
+ <h3 className="text-white text-lg font-semibold">Confirm Plan Downgrade</h3>
+ </div>
+
+ <div className="space-y-3 mb-6">
+ <p className="text-zinc-300 text-sm">
+ You are about to downgrade from <span className="font-semibold text-white">{currentPlanData.name}</span> to <span className="font-semibold text-white">{pendingPlanData.name}</span>.
+ </p>
+
+ <div className="bg-orange-500/10 border border-orange-500/30 rounded-lg p-3">
+ <p className="text-orange-200 text-xs font-medium mb-2">What happens when you downgrade:</p>
+ <ul className="text-orange-200/80 text-xs space-y-1">
+ <li>• Credits: {currentPlanData.credits_amount.toLocaleString()} → {pendingPlanData.credits_amount.toLocaleString()} per month</li>
+ <li>• Price: {currentPlanData.price_display} → {pendingPlanData.price_display} per month</li>
+ <li>• Your remaining credits from the current plan will be lost</li>
+ <li>• The new plan will take effect immediately after payment</li>
+ </ul>
+ </div>
+
+ <p className="text-zinc-400 text-xs">
+ Are you sure you want to continue with the downgrade?
+ </p>
+ </div>
+
+ <div className="flex gap-3">
+ <Button
+ onClick={cancelDowngrade}
+ variant="outline"
+ className="flex-1 bg-zinc-800 border-zinc-600 text-white hover:bg-zinc-700"
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={confirmDowngrade}
+ className="flex-1 bg-orange-500 hover:bg-orange-600 text-white"
+ >
+ Confirm Downgrade
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-6 w-full max-w-6xl mx-auto shadow-2xl overflow-y-auto max-h-[90vh]">
<div className="mb-6">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center">
@@ -401,7 +510,7 @@ const handleSelectPlan = async () => {
</div>
) : (
<>
- <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
+ <div className="grid grid-cols-5 gap-3 mb-6">
{availablePlans.map(getPlanCard)}
</div>
@@ -423,7 +532,7 @@ const handleSelectPlan = async () => {
<div className="text-zinc-400 text-xs">
{selectedPlanData ? (
<>
- {PaymentUtils.formatCurrency(selectedPlanData.price_usd)}/month • 14-day free trial • Cancel anytime
+ {selectedPlanData.price_display} • {selectedPlanData.credits_amount.toLocaleString()} credits • {selectedPlanData.validity_display}
</>
) : (
'Select a plan to continue'
@@ -478,6 +587,7 @@ const handleSelectPlan = async () => {
</>
)}
</div>
+ </>
);
};
diff --git a/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx b/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx
index d19769d5f..88a9f75d9 100644
--- a/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx
+++ b/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx
@@ -53,24 +53,39 @@ const PaymentProcessingScreen: React.FC<PaymentProcessingScreenProps> = ({
try {
console.log(`Payment status check #${checkCount + 1}`);
- // Get updated user subscription to see if payment completed
- const subscriptionResult = await PaymentApiService.getUserSubscription(session.api_key);
-
- if (subscriptionResult.success && subscriptionResult.data?.has_subscription) {
- console.log('Payment completed - user now has active subscription');
- setStatus('completed');
- setPaymentData(subscriptionResult.data);
-
- // Refresh user data in context
- await refreshUserData();
-
- // Clear intervals
- if (intervalRef.current) clearInterval(intervalRef.current);
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
-
- return;
+ // Check if we have an order_id from localStorage (set by PricingScreen)
+ const pendingOrderId = localStorage.getItem('pending_payment_order_id');
+
+ if (pendingOrderId) {
+ // Check the actual order status from backend
+ const statusResponse = await PaymentApiService.getPaymentHistory(session.api_key, 1, 10);
+
+ if (statusResponse.success && statusResponse.data?.payments) {
+ const recentPayment = statusResponse.data.payments.find(
+ (p: any) => p.payment_uuid === pendingOrderId
+ );
+
+ if (recentPayment && recentPayment.status === 'completed') {
+ console.log('Payment completed!', recentPayment);
+ setStatus('completed');
+ setPaymentData(recentPayment);
+ localStorage.removeItem('pending_payment_order_id');
+
+ // Refresh user data to get updated credits
+ await refreshUserData();
+
+ // Clear intervals
+ if (intervalRef.current) clearInterval(intervalRef.current);
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
+ return;
+ }
+ }
}
+ // Fallback: Check credit balance increase
+ await refreshUserData();
+ console.log('User credits:', session.user_info?.credit_balance);
+
setCheckCount(prev => prev + 1);
setLastChecked(new Date());
diff --git a/fincept-terminal-desktop/src/components/settings/DataSourcesPanel.tsx b/fincept-terminal-desktop/src/components/settings/DataSourcesPanel.tsx
index 616765e9b..751043d09 100644
--- a/fincept-terminal-desktop/src/components/settings/DataSourcesPanel.tsx
+++ b/fincept-terminal-desktop/src/components/settings/DataSourcesPanel.tsx
@@ -14,7 +14,7 @@ import {
getWebSocketTopic,
parseDataSourceConfig
} from '@/services/dataSourceRegistry';
-import { getAvailableProviders } from '@/services/websocket';
+import { getAvailableProviders } from '@/services/websocketBridge';
interface DataSourcesPanelProps {
colors: any;
@@ -595,7 +595,7 @@ export function DataSourcesPanel({ colors }: DataSourcesPanelProps) {
borderRadius: '4px'
}}
>
- {availableProviders.map(p => (
+ {availableProviders.map((p: string) => (
<option key={p} value={p} style={{ backgroundColor: colors.background, color: colors.text }}>{p}</option>
))}
</select>
@@ -791,7 +791,7 @@ export function DataSourcesPanel({ colors }: DataSourcesPanelProps) {
borderRadius: '4px'
}}
>
- {availableProviders.map(p => (
+ {availableProviders.map((p: string) => (
<option key={p} value={p} style={{ backgroundColor: colors.background, color: colors.text }}>{p}</option>
))}
</select>
diff --git a/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx b/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx
index 4bec2e842..14bf06fb8 100644
--- a/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx
@@ -117,12 +117,15 @@ const AgentConfigTab: React.FC = () => {
if (!finceptExists && userApiKey) {
console.log('[AgentConfigTab] Creating new Fincept config with user API key');
+ const now = new Date().toISOString();
const finceptConfig = {
provider: 'fincept',
api_key: userApiKey,
base_url: 'https://finceptbackend.share.zrok.io/research/llm',
model: 'fincept-llm',
is_active: true,
+ created_at: now,
+ updated_at: now,
};
await sqliteService.saveLLMConfig(finceptConfig);
configs = await sqliteService.getLLMConfigs();
diff --git a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
index 1f5ca9b45..73c2fc4f8 100644
--- a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
@@ -20,7 +20,7 @@ interface ChatTabProps {
const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab }) => {
const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const { refreshUserProfile } = useAuth();
+ const auth = useAuth();
const { t } = useTranslation('chat');
const [currentTime, setCurrentTime] = useState(new Date());
const [currentSessionUuid, setCurrentSessionUuid] = useState<string | null>(null);
@@ -490,7 +490,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
await loadStatistics();
// Refresh user profile to update credits in realtime
- await refreshUserProfile();
+ await auth.refreshUserData();
} catch (error) {
console.error('Chat error:', error);
diff --git a/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
index a90e148c0..31bab5582 100644
--- a/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
@@ -109,10 +109,10 @@ const NewsTab: React.FC = () => {
try {
const result = await analyzeNewsArticle(selectedArticle.link);
- if (result.success) {
+ if (result.success && 'data' in result) {
setAnalysisData(result.data);
setShowAnalysis(true);
- } else {
+ } else if ('error' in result) {
console.error('Analysis failed:', result.error);
}
} catch (error) {
@@ -205,7 +205,7 @@ const NewsTab: React.FC = () => {
}
};
- const getSentimentColor = (sentiment: string) => {
+ const getArticleSentimentColor = (sentiment: string) => {
switch (sentiment) {
case 'BULLISH': return colors.secondary;
case 'BEARISH': return colors.alert;
@@ -494,7 +494,7 @@ const NewsTab: React.FC = () => {
</span>
<span style={{ color: colors.info, minWidth: '50px' }}>[{article.category}]</span>
<span style={{ color: colors.purple, minWidth: '30px' }}>{article.region}</span>
- <span style={{ color: getSentimentColor(article.sentiment), minWidth: '50px' }}>{article.sentiment}</span>
+ <span style={{ color: getArticleSentimentColor(article.sentiment), minWidth: '50px' }}>{article.sentiment}</span>
</div>
<div style={{ color: colors.text, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
@@ -543,7 +543,7 @@ const NewsTab: React.FC = () => {
</span>
<span style={{ color: colors.info, minWidth: '50px' }}>[{article.category}]</span>
<span style={{ color: colors.purple, minWidth: '30px' }}>{article.region}</span>
- <span style={{ color: getSentimentColor(article.sentiment), minWidth: '50px' }}>{article.sentiment}</span>
+ <span style={{ color: getArticleSentimentColor(article.sentiment), minWidth: '50px' }}>{article.sentiment}</span>
</div>
<div style={{ color: colors.text, fontWeight: 'bold', fontSize: '10px', lineHeight: '1.2', marginBottom: '2px' }}>
@@ -995,7 +995,7 @@ const NewsTab: React.FC = () => {
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8px' }}>
<span style={{ color: colors.accent }}>{article.source}</span>
- <span style={{ color: getSentimentColor(article.sentiment) }}>{article.sentiment}</span>
+ <span style={{ color: getArticleSentimentColor(article.sentiment) }}>{article.sentiment}</span>
</div>
</div>
))}
@@ -1203,7 +1203,7 @@ const NewsTab: React.FC = () => {
{selectedArticle.category}
</span>
<span style={{
- backgroundColor: getSentimentColor(selectedArticle.sentiment),
+ backgroundColor: getArticleSentimentColor(selectedArticle.sentiment),
color: colors.background,
padding: '2px 8px',
borderRadius: '2px',
@@ -1297,7 +1297,7 @@ const NewsTab: React.FC = () => {
</div>
<div>
<span style={{ color: colors.textMuted }}>SENTIMENT: </span>
- <span style={{ color: getSentimentColor(selectedArticle.sentiment), fontWeight: 'bold' }}>
+ <span style={{ color: getArticleSentimentColor(selectedArticle.sentiment), fontWeight: 'bold' }}>
{selectedArticle.sentiment}
</span>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx b/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx
index 3b2907bda..88451f20c 100644
--- a/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx
@@ -555,15 +555,15 @@ const RelationshipMapTab: React.FC = () => {
{/* Header */}
<div
className="border-b px-4 py-3 flex items-center justify-between"
- style={{ borderColor: colors.border }}
+ style={{ borderColor: colors.textMuted }}
>
<div className="flex items-center gap-3">
<Globe className="w-5 h-5" style={{ color: colors.accent }} />
<h2 className="text-lg font-semibold">Relationship Map</h2>
<span className="text-xs px-2 py-1 rounded font-mono" style={{
- backgroundColor: colors.surface,
+ backgroundColor: colors.panel,
color: colors.accent,
- border: `1px solid ${colors.border}`
+ border: `1px solid ${colors.textMuted}`
}}>
{selectedSymbol}
</span>
@@ -581,8 +581,8 @@ const RelationshipMapTab: React.FC = () => {
placeholder="Enter ticker (e.g., AAPL, TSLA, GOOGL)..."
className="w-full pl-10 pr-4 py-2 rounded border focus:outline-none focus:ring-1"
style={{
- backgroundColor: colors.surface,
- borderColor: colors.border,
+ backgroundColor: colors.panel,
+ borderColor: colors.textMuted,
color: colors.text,
}}
/>
@@ -609,10 +609,10 @@ const RelationshipMapTab: React.FC = () => {
) : error ? (
<div className="flex items-center justify-center h-full">
<div className="text-center p-8 rounded border" style={{
- backgroundColor: colors.surface,
- borderColor: colors.error
+ backgroundColor: colors.panel,
+ borderColor: colors.alert
}}>
- <p className="text-lg font-semibold mb-2" style={{ color: colors.error }}>Error</p>
+ <p className="text-lg font-semibold mb-2" style={{ color: colors.alert }}>Error</p>
<p style={{ color: colors.textMuted }}>{error}</p>
</div>
</div>
@@ -638,14 +638,14 @@ const RelationshipMapTab: React.FC = () => {
<Controls
style={{
background: '#1a1a1a',
- border: `1px solid ${colors.border}`,
+ border: `1px solid ${colors.textMuted}`,
borderRadius: '4px',
}}
/>
<MiniMap
style={{
background: '#1a1a1a',
- border: `1px solid ${colors.border}`,
+ border: `1px solid ${colors.textMuted}`,
}}
maskColor="#0a0a0a90"
nodeColor={(node) => {
diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
index 7ca5ba72c..02de2b911 100644
--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
@@ -4,8 +4,7 @@ import { sqliteService, type LLMConfig, type LLMGlobalSettings, type LLMModelCon
import { ollamaService } from '@/services/ollamaService';
import { useTerminalTheme } from '@/contexts/ThemeContext';
import { terminalThemeService, FONT_FAMILIES, COLOR_THEMES, FontSettings } from '@/services/terminalThemeService';
-import { getWebSocketManager, ConnectionStatus, getAvailableProviders } from '@/services/websocket';
-import { useWebSocketManager } from '@/hooks/useWebSocket';
+import { getWebSocketManager, ConnectionStatus, getAvailableProviders } from '@/services/websocketBridge';
import { DataSourcesPanel } from '@/components/settings/DataSourcesPanel';
import { BacktestingProvidersPanel } from '@/components/settings/BacktestingProvidersPanel';
import { LanguageSelector } from '@/components/settings/LanguageSelector';
@@ -18,7 +17,7 @@ import { useAuth } from '@/contexts/AuthContext';
export default function SettingsTab() {
const { t } = useTranslation('settings');
- const { user } = useAuth();
+ const { session } = useAuth();
const { theme, updateTheme, resetTheme, colors, fontSize: themeFontSize, fontFamily: themeFontFamily, fontWeight: themeFontWeight, fontStyle } = useTerminalTheme();
const { defaultTimezone, setDefaultTimezone, options: timezoneOptions } = useTimezone();
const [activeSection, setActiveSection] = useState<'credentials' | 'terminal' | 'terminalConfig' | 'llm' | 'dataConnections' | 'backtesting' | 'language'>('credentials');
@@ -28,7 +27,7 @@ export default function SettingsTab() {
const [dbInitialized, setDbInitialized] = useState(false);
// WebSocket Data Connections State
- const { stats, statuses, metrics, manager } = useWebSocketManager();
+ // WebSocket manager removed - now using Rust backend
const [wsProviders, setWsProviders] = useState<Array<{
id: number;
provider_name: string;
@@ -116,23 +115,24 @@ export default function SettingsTab() {
}, []);
// Track programmatic providers that get initialized
- useEffect(() => {
- const detectedProviders = new Set<string>([
- ...Array.from(statuses.keys()),
- ...manager.getSubscriptions().map(sub => sub.topic.split('.')[0])
- ]);
-
- // Filter out database-configured providers
- detectedProviders.forEach(p => {
- if (wsProviders.find(wp => wp.provider_name === p)) {
- detectedProviders.delete(p);
- }
- });
-
- if (detectedProviders.size > 0) {
- setProgrammaticProviders(prev => new Set([...prev, ...detectedProviders]));
- }
- }, [statuses, wsProviders]);
+ // TODO: Re-implement with new Rust WebSocket backend
+ // useEffect(() => {
+ // const detectedProviders = new Set<string>([
+ // ...Array.from(statuses.keys()),
+ // ...manager.getSubscriptions().map(sub => sub.topic.split('.')[0])
+ // ]);
+
+ // // Filter out database-configured providers
+ // detectedProviders.forEach(p => {
+ // if (wsProviders.find(wp => wp.provider_name === p)) {
+ // detectedProviders.delete(p);
+ // }
+ // });
+
+ // if (detectedProviders.size > 0) {
+ // setProgrammaticProviders(prev => new Set([...prev, ...detectedProviders]));
+ // }
+ // }, [wsProviders]);
const checkAndLoadData = async () => {
try {
@@ -176,20 +176,20 @@ export default function SettingsTab() {
const providers = await sqliteService.getWSProviderConfigs();
setWsProviders(providers);
- // Auto-initialize enabled providers in WebSocket Manager
- const wsManager = getWebSocketManager();
- for (const provider of providers) {
- if (provider.enabled) {
- wsManager.setProviderConfig(provider.provider_name, {
- provider_name: provider.provider_name,
- enabled: provider.enabled,
- api_key: provider.api_key || undefined,
- api_secret: provider.api_secret || undefined,
- endpoint: provider.endpoint || undefined
- });
- console.log(`[Settings] Auto-initialized provider: ${provider.provider_name}`);
- }
- }
+ // TODO: Re-implement auto-initialization with new Rust WebSocket backend
+ // const wsManager = getWebSocketManager();
+ // for (const provider of providers) {
+ // if (provider.enabled) {
+ // wsManager.setProviderConfig(provider.provider_name, {
+ // provider_name: provider.provider_name,
+ // enabled: provider.enabled,
+ // api_key: provider.api_key || undefined,
+ // api_secret: provider.api_secret || undefined,
+ // endpoint: provider.endpoint || undefined
+ // });
+ // console.log(`[Settings] Auto-initialized provider: ${provider.provider_name}`);
+ // }
+ // }
} catch (error) {
console.error('Failed to load WS providers:', error);
}
@@ -208,15 +208,15 @@ export default function SettingsTab() {
if (result.success) {
showMessage('success', result.message);
- // Initialize provider in WebSocket Manager
- const manager = getWebSocketManager();
- manager.setProviderConfig(providerForm.provider_name, {
- provider_name: providerForm.provider_name,
- enabled: providerForm.enabled,
- api_key: providerForm.api_key || undefined,
- api_secret: providerForm.api_secret || undefined,
- endpoint: providerForm.endpoint || undefined
- });
+ // TODO: Re-implement with new Rust WebSocket backend
+ // const manager = getWebSocketManager();
+ // manager.setProviderConfig(providerForm.provider_name, {
+ // provider_name: providerForm.provider_name,
+ // enabled: providerForm.enabled,
+ // api_key: providerForm.api_key || undefined,
+ // api_secret: providerForm.api_secret || undefined,
+ // endpoint: providerForm.endpoint || undefined
+ // });
// Reset form
setProviderForm({
@@ -246,16 +246,16 @@ export default function SettingsTab() {
showMessage('success', result.message);
await loadWSProviders();
- // Reconnect or disconnect based on new state
- const manager = getWebSocketManager();
- if (result.enabled) {
- const config = await sqliteService.getWSProviderConfig(providerName);
- if (config) {
- manager.setProviderConfig(providerName, config);
- }
- } else {
- await manager.disconnect(providerName);
- }
+ // TODO: Re-implement with new Rust WebSocket backend
+ // const manager = getWebSocketManager();
+ // if (result.enabled) {
+ // const config = await sqliteService.getWSProviderConfig(providerName);
+ // if (config) {
+ // manager.setProviderConfig(providerName, config);
+ // }
+ // } else {
+ // await manager.disconnect(providerName);
+ // }
}
} catch (error) {
showMessage('error', 'Failed to toggle provider');
@@ -293,18 +293,14 @@ export default function SettingsTab() {
const config = await sqliteService.getWSProviderConfig(providerName);
if (config) {
- manager.setProviderConfig(providerName, config);
-
- // Check if there are existing subscriptions to restore
- const hasSubscriptions = manager.getProviderSubscriptions(providerName).length > 0;
-
- if (hasSubscriptions) {
- // Use reconnect to restore subscriptions
- await manager.reconnect(providerName);
- } else {
- // Just connect if no subscriptions
+ // TODO: Re-implement with new Rust WebSocket backend
+ // manager.setProviderConfig(providerName, config);
+ // const hasSubscriptions = manager.getProviderSubscriptions(providerName).length > 0;
+ // if (hasSubscriptions) {
+ // await manager.reconnect(providerName);
+ // } else {
await manager.connect(providerName);
- }
+ // }
showMessage('success', `Connected to ${providerName}`);
} else {
@@ -327,9 +323,11 @@ export default function SettingsTab() {
const handleTestProvider = async (providerName: string) => {
try {
- const manager = getWebSocketManager();
- const latency = await manager.ping(providerName);
- showMessage('success', `Ping: ${latency}ms`);
+ // TODO: Re-implement ping with new Rust WebSocket backend
+ // const manager = getWebSocketManager();
+ // const latency = await manager.ping(providerName);
+ // showMessage('success', `Ping: ${latency}ms`);
+ showMessage('success', `Test connection feature coming soon`);
} catch (error) {
showMessage('error', `Ping failed for ${providerName}`);
}
@@ -337,16 +335,17 @@ export default function SettingsTab() {
const handleUnsubscribe = async (subscriptionId: string, topic: string) => {
try {
- const manager = getWebSocketManager();
- const subscriptions = manager.getSubscriptions();
- const sub = subscriptions.find(s => s.id === subscriptionId);
-
- if (sub) {
- sub.unsubscribe();
- showMessage('success', `Unsubscribed from ${topic}`);
- } else {
- showMessage('error', 'Subscription not found');
- }
+ // TODO: Re-implement with new Rust WebSocket backend
+ // const manager = getWebSocketManager();
+ // const subscriptions = manager.getSubscriptions();
+ // const sub = subscriptions.find(s => s.id === subscriptionId);
+
+ // if (sub) {
+ // sub.unsubscribe();
+ // showMessage('success', `Unsubscribed from ${topic}`);
+ // } else {
+ showMessage('error', 'Subscription management coming soon');
+ // }
} catch (error) {
showMessage('error', `Failed to unsubscribe from ${topic}`);
}
@@ -381,15 +380,18 @@ export default function SettingsTab() {
// Initialize Fincept LLM as default if no configs exist
if (configs.length === 0) {
- // Try to get API key from user profile
- const userApiKey = user?.api_key || '';
+ // Try to get API key from session profile
+ const userApiKey = session?.api_key || '';
+ const now = new Date().toISOString();
const finceptConfig = {
provider: 'fincept',
api_key: userApiKey,
base_url: 'https://finceptbackend.share.zrok.io/research/llm',
model: 'fincept-llm',
is_active: true,
+ created_at: now,
+ updated_at: now,
};
await sqliteService.saveLLMConfig(finceptConfig);
configs = await sqliteService.getLLMConfigs();
@@ -895,7 +897,7 @@ export default function SettingsTab() {
✓ FINCEPT AUTO-CONFIGURED
</div>
<div style={{ color: '#888', fontSize: '8px' }}>
- Key: {user?.api_key?.substring(0, 8)}... • 5 credits/response
+ Key: {session?.api_key?.substring(0, 8)}... • 5 credits/response
</div>
</div>
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
index e4a3b7f1d..5bc60e5b2 100644
--- a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
@@ -9,7 +9,7 @@ import {
Clock, TrendingDown as ArrowDown, TrendingUp as ArrowUp, ChevronUp, Minimize2
} from 'lucide-react';
import { useBrokerContext } from '../../contexts/BrokerContext';
-import { useWebSocket } from '../../hooks/useWebSocket';
+import { useRustTicker, useRustOrderBook, useRustTrades } from '../../hooks/useRustWebSocket';
import { invoke } from '@tauri-apps/api/core';
// Import new enhanced order form
import { EnhancedOrderForm } from './trading/core/OrderForm';
@@ -98,9 +98,9 @@ export function TradingTab() {
const [currentTime, setCurrentTime] = useState(new Date());
const [selectedSymbol, setSelectedSymbol] = useState(defaultSymbols[0] || 'BTC/USD');
- const [tickerData, setTickerData] = useState<any>(null);
+ const [tickerState, setTickerData] = useState<any>(null);
const [orderBook, setOrderBook] = useState<OrderBook>({ bids: [], asks: [], symbol: '' });
- const [tradesData, setTradesData] = useState<any[]>([]);
+ const [tradesState, setTradesData] = useState<any[]>([]);
const [isPlacingOrder, setIsPlacingOrder] = useState(false);
const [lastOrderBookUpdate, setLastOrderBookUpdate] = useState<number>(0);
@@ -247,108 +247,80 @@ export function TradingTab() {
setLastOrderBookUpdate(0);
}, [selectedSymbol]);
- // Subscribe to WebSocket feeds
- const { message: tickerMessage } = useWebSocket(
- activeBroker ? `${activeBroker}.ticker.${selectedSymbol}` : null
+ // Subscribe to Rust WebSocket feeds (10,000+ connections, minimal memory)
+ const { data: tickerData, error: tickerError } = useRustTicker(
+ activeBroker || '',
+ selectedSymbol,
+ !!activeBroker
);
- const { message: orderbookMessage } = useWebSocket(
- activeBroker ? `${activeBroker}.book.${selectedSymbol}` : null
+ const { data: orderbookData, error: orderbookError } = useRustOrderBook(
+ activeBroker || '',
+ selectedSymbol,
+ 25,
+ !!activeBroker
);
- const { message: tradesMessage } = useWebSocket(
- activeBroker ? `${activeBroker}.trade.${selectedSymbol}` : null
+ const { trades: tradesData, error: tradesError } = useRustTrades(
+ activeBroker || '',
+ selectedSymbol,
+ 50,
+ !!activeBroker
);
- // Update ticker data
+ // Update ticker data from Rust WebSocket
useEffect(() => {
- if (tickerMessage && tickerMessage.data) {
- const data = tickerMessage.data;
- if (data.symbol === selectedSymbol) {
- setTickerData(data);
- if (tradingMode === 'paper' && paperAdapter) {
- const matchingEngine = (paperAdapter as any).matchingEngine;
- if (matchingEngine && typeof matchingEngine.updatePriceFromWebSocket === 'function') {
- matchingEngine.updatePriceFromWebSocket(selectedSymbol, {
- bid: data.bid,
- ask: data.ask,
- last: data.last,
- });
- }
+ if (tickerData && tickerData.symbol === selectedSymbol) {
+ setTickerData({
+ symbol: tickerData.symbol,
+ price: tickerData.price,
+ bid: tickerData.bid,
+ ask: tickerData.ask,
+ last: tickerData.price,
+ volume: tickerData.volume,
+ high: tickerData.high,
+ low: tickerData.low,
+ change: tickerData.change,
+ changePercent: tickerData.change_percent,
+ });
+
+ if (tradingMode === 'paper' && paperAdapter) {
+ const matchingEngine = (paperAdapter as any).matchingEngine;
+ if (matchingEngine && typeof matchingEngine.updatePriceFromWebSocket === 'function') {
+ matchingEngine.updatePriceFromWebSocket(selectedSymbol, {
+ bid: tickerData.bid,
+ ask: tickerData.ask,
+ last: tickerData.price,
+ });
}
}
}
- }, [tickerMessage, tradingMode, paperAdapter, selectedSymbol]);
+ }, [tickerData, tradingMode, paperAdapter, selectedSymbol]);
- // Update orderbook using high-performance Rust backend (20-50x faster)
+ // Update orderbook from Rust WebSocket
useEffect(() => {
- if (!orderbookMessage || !orderbookMessage.data) return;
- const data = orderbookMessage.data;
- const messageType = data.messageType;
- const dataSymbol = data.symbol || selectedSymbol;
-
- if (dataSymbol !== selectedSymbol) return;
-
- const updateOrderBook = async () => {
- try {
- if (messageType === 'snapshot') {
- // Rust-powered snapshot processing
- const [sortedBids, sortedAsks] = await invoke<[OrderBookLevel[], OrderBookLevel[]]>(
- 'update_orderbook_snapshot',
- {
- bids: data.bids || [],
- asks: data.asks || [],
- maxDepth: 25
- }
- );
-
- setOrderBook({
- bids: sortedBids,
- asks: sortedAsks,
- symbol: dataSymbol,
- checksum: data.checksum
- });
- setLastOrderBookUpdate(Date.now());
- } else if (messageType === 'update') {
- // High-performance Rust merge with HashMap optimization
- const [mergedBids, mergedAsks] = await invoke<[OrderBookLevel[], OrderBookLevel[]]>(
- 'merge_orderbook',
- {
- existingBids: orderBook.bids,
- existingAsks: orderBook.asks,
- updateBids: data.bids || null,
- updateAsks: data.asks || null,
- maxDepth: 25
- }
- );
-
- setOrderBook({
- bids: mergedBids,
- asks: mergedAsks,
- symbol: dataSymbol,
- checksum: data.checksum
- });
- setLastOrderBookUpdate(Date.now());
- }
- } catch (error) {
- console.error('[TradingTab] Rust orderbook processing failed:', error);
- // Fallback: Keep existing orderbook on error
- }
- };
-
- updateOrderBook();
- }, [orderbookMessage, selectedSymbol, orderBook.bids, orderBook.asks]);
+ if (orderbookData && orderbookData.symbol === selectedSymbol) {
+ setOrderBook({
+ bids: orderbookData.bids.map(b => ({ price: b.price, size: b.quantity })),
+ asks: orderbookData.asks.map(a => ({ price: a.price, size: a.quantity })),
+ symbol: orderbookData.symbol,
+ });
+ setLastOrderBookUpdate(Date.now());
+ }
+ }, [orderbookData, selectedSymbol]);
- // Update trades
+ // Update trades from Rust WebSocket (auto-maintains 50 trades)
useEffect(() => {
- if (tradesMessage && tradesMessage.data) {
- const data = tradesMessage.data;
- const dataSymbol = data.symbol || selectedSymbol;
- if (dataSymbol === selectedSymbol) {
- setTradesData(prev => [data, ...prev].slice(0, 50));
- }
+ if (tradesData && tradesData.length > 0) {
+ setTradesData(tradesData.map(t => ({
+ symbol: t.symbol,
+ price: t.price,
+ quantity: t.quantity,
+ side: t.side,
+ timestamp: t.timestamp,
+ })));
}
- }, [tradesMessage, selectedSymbol]);
+ }, [tradesData]);
// Load paper trading data
useEffect(() => {
@@ -507,17 +479,17 @@ export function TradingTab() {
await setActiveBroker(brokerId);
};
- const currentPrice = tickerData?.last || orderBook.asks[0]?.price || 0;
+ const currentPrice = tickerState?.last || tickerState?.price || orderBook.asks[0]?.price || 0;
// Calculate price change - try multiple field names
- const priceChange = tickerData?.change || tickerData?.price_change || 0;
+ const priceChange = tickerState?.change || tickerState?.price_change || 0;
// Calculate percentage change - try from data or calculate manually
- let priceChangePercent = tickerData?.change_percent || tickerData?.percentage || tickerData?.percent_change || 0;
+ let priceChangePercent = tickerState?.changePercent || tickerState?.change_percent || tickerState?.percentage || tickerState?.percent_change || 0;
// If no percentage provided, calculate it from price change and current price
- if (priceChangePercent === 0 && tickerData?.last && tickerData?.open && tickerData.open > 0) {
- priceChangePercent = ((tickerData.last - tickerData.open) / tickerData.open) * 100;
+ if (priceChangePercent === 0 && tickerState?.last && tickerState?.open && tickerState.open > 0) {
+ priceChangePercent = ((tickerState.last - tickerState.open) / tickerState.open) * 100;
} else if (priceChangePercent === 0 && priceChange !== 0 && currentPrice > 0) {
// Calculate from absolute change if we have it
const previousPrice = currentPrice - priceChange;
@@ -527,9 +499,9 @@ export function TradingTab() {
}
// Calculate 24h price range (High - Low)
- const spread24h = (tickerData?.high && tickerData?.low) ? (tickerData.high - tickerData.low) : 0;
- const spread24hPercent = (spread24h > 0 && tickerData?.low && tickerData.low > 0)
- ? ((spread24h / tickerData.low) * 100)
+ const spread24h = (tickerState?.high && tickerState?.low) ? (tickerState.high - tickerState.low) : 0;
+ const spread24hPercent = (spread24h > 0 && tickerState?.low && tickerState.low > 0)
+ ? ((spread24h / tickerState.low) * 100)
: 0;
return (
@@ -858,9 +830,9 @@ export function TradingTab() {
{/* Price Display */}
<div style={{ display: 'flex', alignItems: 'baseline', gap: '8px' }}>
<span style={{ fontSize: '24px', fontWeight: 700, color: BLOOMBERG.YELLOW }}>
- {tickerData ? `$${tickerData.last?.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '0.00'}` : '--'}
+ {tickerState ? `$${(tickerState.last || tickerState.price)?.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '0.00'}` : '--'}
</span>
- {tickerData && (
+ {tickerState && (
<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
{priceChange >= 0 ? (
<ArrowUp size={16} color={BLOOMBERG.GREEN} />
@@ -906,38 +878,38 @@ export function TradingTab() {
)}
</div>
</div>
- {tickerData && (
+ {tickerState && (
<>
<div>
<div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H HIGH</div>
- <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600 }}>${tickerData.high?.toFixed(2) || '--'}</div>
+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600 }}>${tickerState.high?.toFixed(2) || '--'}</div>
</div>
<div>
<div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H LOW</div>
- <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600 }}>${tickerData.low?.toFixed(2) || '--'}</div>
+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600 }}>${tickerState.low?.toFixed(2) || '--'}</div>
</div>
<div>
<div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H VOLUME</div>
<div style={{ color: BLOOMBERG.PURPLE, fontWeight: 600 }}>
- {tickerData.volume ? (
+ {tickerState.volume ? (
<>
{/* Show volume in USD if available */}
- {tickerData.quoteVolume ? (
- `$${tickerData.quoteVolume.toLocaleString(undefined, { maximumFractionDigits: 0 })}`
- ) : tickerData.volumeUsd ? (
- `$${tickerData.volumeUsd.toLocaleString(undefined, { maximumFractionDigits: 0 })}`
+ {tickerState.quoteVolume ? (
+ `$${tickerState.quoteVolume.toLocaleString(undefined, { maximumFractionDigits: 0 })}`
+ ) : tickerState.volume ? (
+ `$${(tickerState.volume * currentPrice).toLocaleString(undefined, { maximumFractionDigits: 0 })}`
) : (
// Calculate USD value from volume * current price
currentPrice > 0 ? (
<>
- ${(tickerData.volume * currentPrice).toLocaleString(undefined, { maximumFractionDigits: 0 })}
+ ${(tickerState.volume * currentPrice).toLocaleString(undefined, { maximumFractionDigits: 0 })}
<span style={{ fontSize: '8px', color: BLOOMBERG.GRAY, marginLeft: '4px' }}>
- ({tickerData.volume.toLocaleString(undefined, { maximumFractionDigits: 2 })} {selectedSymbol.split('/')[0]})
+ ({tickerState.volume.toLocaleString(undefined, { maximumFractionDigits: 2 })} {selectedSymbol.split('/')[0]})
</span>
</>
) : (
<>
- {tickerData.volume.toLocaleString(undefined, { maximumFractionDigits: 2 })}
+ {tickerState.volume.toLocaleString(undefined, { maximumFractionDigits: 2 })}
<span style={{ fontSize: '8px', color: BLOOMBERG.GRAY, marginLeft: '2px' }}>
{selectedSymbol.split('/')[0]}
</span>
@@ -1255,7 +1227,7 @@ export function TradingTab() {
${trade.price?.toFixed(2)}
</td>
<td style={{ padding: '4px 6px', textAlign: 'right', color: BLOOMBERG.WHITE }}>
- {trade.amount?.toFixed(4)}
+ {trade.quantity?.toFixed(4)}
</td>
</tr>
))}
diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/DataSourceWidget.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/DataSourceWidget.tsx
index 9921391c6..603e0661d 100644
--- a/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/DataSourceWidget.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/widgets/DataSourceWidget.tsx
@@ -24,15 +24,20 @@ export const DataSourceWidget: React.FC<DataSourceWidgetProps> = ({
onRemove
}) => {
const { t } = useTranslation('dashboard');
- const { data, error, loading, connected, source, refresh } = useDataSource(alias);
+ const { dataSources, loading, error, refreshDataSources } = useDataSource();
const [lastUpdate, setLastUpdate] = useState<Date | null>(null);
const [updateCount, setUpdateCount] = useState(0);
const [isBlinking, setIsBlinking] = useState(false);
+ // Find the specific data source by alias
+ const source = dataSources.find(ds => ds.alias === alias);
+ const connected = source?.enabled || false;
+ const data = null; // Data will be handled separately
+
// Log data updates for debugging
useEffect(() => {
- if (data) {
- console.log(`[DataSourceWidget ${alias}] Data update #${updateCount}:`, data);
+ if (source) {
+ console.log(`[DataSourceWidget ${alias}] Data source:`, source);
}
}, [data, alias, updateCount]);
@@ -123,7 +128,7 @@ export const DataSourceWidget: React.FC<DataSourceWidgetProps> = ({
<div>{t('widgets.noData')}</div>
{source?.type === 'rest_api' && (
<button
- onClick={refresh}
+ onClick={refreshDataSources}
style={{
background: BLOOMBERG_ORANGE,
color: '#000',
@@ -197,7 +202,7 @@ export const DataSourceWidget: React.FC<DataSourceWidgetProps> = ({
{source?.type === 'rest_api' && (
<div style={{ marginTop: '8px', textAlign: 'center' }}>
<button
- onClick={refresh}
+ onClick={refreshDataSources}
disabled={loading}
style={{
background: loading ? BLOOMBERG_GRAY : BLOOMBERG_ORANGE,
@@ -223,7 +228,7 @@ export const DataSourceWidget: React.FC<DataSourceWidgetProps> = ({
id={id}
title={displayName || source?.display_name || alias}
onRemove={onRemove}
- onRefresh={source?.type === 'rest_api' ? refresh : undefined}
+ onRefresh={source?.type === 'rest_api' ? refreshDataSources : undefined}
isLoading={loading && !data}
error={null}
headerColor={source?.type === 'websocket' ? BLOOMBERG_GREEN : BLOOMBERG_ORANGE}
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/NodeConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/NodeConfigPanel.tsx
new file mode 100644
index 000000000..ab5437498
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/NodeConfigPanel.tsx
@@ -0,0 +1,200 @@
+/**
+ * Node Configuration Panel
+ *
+ * Displays and allows editing of all parameters for a selected node.
+ * Renders the parameter input UI using NodeParameterInput component.
+ *
+ * Features:
+ * - Dynamic parameter rendering based on node type
+ * - Expression support for all parameters
+ * - Parameter validation
+ * - Conditional parameters (displayOptions)
+ * - Collection and FixedCollection support
+ * - Real-time parameter updates
+ */
+
+import React, { useCallback, useMemo } from 'react';
+import type {
+ INode,
+ INodeProperties,
+ NodeParameterValue,
+ INodeType,
+} from '@/services/nodeSystem';
+import { NodeRegistry } from '@/services/nodeSystem';
+import NodeParameterInput from './NodeParameterInput';
+import { Settings2, X, Info, AlertCircle } from 'lucide-react';
+
+interface NodeConfigPanelProps {
+ node: INode | null;
+ onNodeUpdate: (nodeId: string, parameters: Record<string, any>) => void;
+ onClose: () => void;
+}
+
+export const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
+ node,
+ onNodeUpdate,
+ onClose,
+}) => {
+ // Get node type definition
+ const nodeType = useMemo<INodeType | null>(() => {
+ if (!node) return null;
+ try {
+ return NodeRegistry.getNodeType(node.type, node.typeVersion);
+ } catch (error) {
+ console.error('Failed to get node type:', error);
+ return null;
+ }
+ }, [node]);
+
+ // Filter parameters based on displayOptions
+ const visibleParameters = useMemo(() => {
+ if (!nodeType?.description?.properties) return [];
+
+ return nodeType.description.properties.filter((param) => {
+ if (!param.displayOptions) return true;
+
+ // Check show conditions
+ if (param.displayOptions.show) {
+ for (const [paramName, allowedValues] of Object.entries(param.displayOptions.show)) {
+ const currentValue = node?.parameters[paramName];
+ const values = Array.isArray(allowedValues) ? allowedValues : [allowedValues];
+
+ if (!values.includes(currentValue as any)) {
+ return false;
+ }
+ }
+ }
+
+ // Check hide conditions
+ if (param.displayOptions.hide) {
+ for (const [paramName, hiddenValues] of Object.entries(param.displayOptions.hide)) {
+ const currentValue = node?.parameters[paramName];
+ const values = Array.isArray(hiddenValues) ? hiddenValues : [hiddenValues];
+
+ if (values.includes(currentValue as any)) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ });
+ }, [nodeType, node?.parameters]);
+
+ // Handle parameter change
+ const handleParameterChange = useCallback(
+ (paramName: string, value: NodeParameterValue) => {
+ if (!node) return;
+
+ const updatedParameters = {
+ ...node.parameters,
+ [paramName]: value,
+ };
+
+ onNodeUpdate(node.name, updatedParameters);
+ },
+ [node, onNodeUpdate]
+ );
+
+ if (!node) {
+ return (
+ <div className="w-96 bg-gray-900 border-l border-gray-800 flex items-center justify-center">
+ <div className="text-center text-gray-500">
+ <Settings2 size={48} className="mx-auto mb-4 opacity-30" />
+ <p>Select a node to configure</p>
+ </div>
+ </div>
+ );
+ }
+
+ if (!nodeType) {
+ return (
+ <div className="w-96 bg-gray-900 border-l border-gray-800 flex items-center justify-center">
+ <div className="text-center text-red-400">
+ <AlertCircle size={48} className="mx-auto mb-4" />
+ <p>Node type not found</p>
+ <p className="text-sm text-gray-500 mt-2">{node.type}</p>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="w-96 bg-gray-900 border-l border-gray-800 flex flex-col h-full">
+ {/* Panel Header */}
+ <div className="border-b border-gray-800 p-4 flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <div
+ className="w-10 h-10 rounded flex items-center justify-center"
+ style={{
+ background: `${nodeType.description.defaults.color}20`,
+ border: `2px solid ${nodeType.description.defaults.color}40`,
+ }}
+ >
+ <Settings2 size={20} style={{ color: nodeType.description.defaults.color }} />
+ </div>
+ <div>
+ <h3 className="text-sm font-semibold text-gray-200">
+ {nodeType.description.displayName}
+ </h3>
+ <p className="text-xs text-gray-500">{node.name}</p>
+ </div>
+ </div>
+ <button
+ onClick={onClose}
+ className="p-1.5 hover:bg-gray-800 rounded transition-colors"
+ title="Close"
+ >
+ <X size={18} className="text-gray-400" />
+ </button>
+ </div>
+
+ {/* Node Description */}
+ {nodeType.description.description && (
+ <div className="p-4 bg-blue-500/10 border-b border-gray-800">
+ <div className="flex items-start gap-2">
+ <Info size={16} className="text-blue-400 mt-0.5 flex-shrink-0" />
+ <p className="text-xs text-blue-300">{nodeType.description.description}</p>
+ </div>
+ </div>
+ )}
+
+ {/* Parameters List */}
+ <div className="flex-1 overflow-y-auto p-4 space-y-4">
+ {visibleParameters.length === 0 ? (
+ <div className="text-center text-gray-500 py-8">
+ <Settings2 size={32} className="mx-auto mb-2 opacity-30" />
+ <p className="text-sm">No parameters to configure</p>
+ </div>
+ ) : (
+ visibleParameters.map((param) => (
+ <div key={param.name} className="pb-4 border-b border-gray-800 last:border-0">
+ <NodeParameterInput
+ parameter={param}
+ value={node.parameters[param.name] ?? param.default}
+ onChange={(value) => handleParameterChange(param.name, value)}
+ disabled={node.disabled}
+ />
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Panel Footer */}
+ <div className="border-t border-gray-800 p-4 bg-gray-900">
+ <div className="flex items-center justify-between text-xs text-gray-500">
+ <span>Node ID: {node.name}</span>
+ <span>
+ {node.disabled ? (
+ <span className="text-yellow-500">Disabled</span>
+ ) : (
+ <span className="text-green-500">Active</span>
+ )}
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default NodeConfigPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/NodePalette.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/NodePalette.tsx
new file mode 100644
index 000000000..47e3d6efa
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/NodePalette.tsx
@@ -0,0 +1,268 @@
+/**
+ * Node Palette Component
+ *
+ * Displays available nodes from the NodeRegistry that can be added to the workflow.
+ * Organized by category with search functionality.
+ *
+ * Features:
+ * - Search nodes by name
+ * - Filter by category
+ * - Drag and drop to canvas
+ * - Node descriptions on hover
+ * - Category-based organization
+ */
+
+import React, { useState, useMemo } from 'react';
+import { NodeRegistry } from '@/services/nodeSystem';
+import type { INodeTypeDescription } from '@/services/nodeSystem';
+import {
+ Search,
+ Database,
+ Workflow,
+ FileText,
+ Code,
+ GitBranch,
+ Filter,
+ Settings,
+ ChevronRight,
+ ChevronDown,
+} from 'lucide-react';
+
+interface NodePaletteProps {
+ onNodeAdd: (nodeType: string) => void;
+ onDragStart?: (nodeType: string, event: React.DragEvent) => void;
+}
+
+export const NodePalette: React.FC<NodePaletteProps> = ({
+ onNodeAdd,
+ onDragStart,
+}) => {
+ const [searchQuery, setSearchQuery] = useState('');
+ const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
+ new Set(['Core'])
+ );
+
+ // Get all registered nodes
+ const allNodes = useMemo(() => {
+ return NodeRegistry.getAllNodes();
+ }, []);
+
+ // Group nodes by category
+ const nodesByCategory = useMemo(() => {
+ const grouped = new Map<string, INodeTypeDescription[]>();
+
+ for (const node of allNodes) {
+ const category = node.group || ['Uncategorized'];
+ const categoryName = Array.isArray(category) ? category[0] : category;
+
+ if (!grouped.has(categoryName)) {
+ grouped.set(categoryName, []);
+ }
+
+ grouped.get(categoryName)!.push(node);
+ }
+
+ // Sort each category alphabetically
+ for (const nodes of grouped.values()) {
+ nodes.sort((a, b) => a.displayName.localeCompare(b.displayName));
+ }
+
+ return grouped;
+ }, [allNodes]);
+
+ // Filter nodes based on search query
+ const filteredCategories = useMemo(() => {
+ if (!searchQuery.trim()) {
+ return nodesByCategory;
+ }
+
+ const query = searchQuery.toLowerCase();
+ const filtered = new Map<string, INodeTypeDescription[]>();
+
+ for (const [category, nodes] of nodesByCategory.entries()) {
+ const matchingNodes = nodes.filter(
+ (node) =>
+ node.displayName.toLowerCase().includes(query) ||
+ node.name.toLowerCase().includes(query) ||
+ node.description?.toLowerCase().includes(query)
+ );
+
+ if (matchingNodes.length > 0) {
+ filtered.set(category, matchingNodes);
+ }
+ }
+
+ return filtered;
+ }, [nodesByCategory, searchQuery]);
+
+ // Toggle category expansion
+ const toggleCategory = (category: string) => {
+ const newExpanded = new Set(expandedCategories);
+ if (newExpanded.has(category)) {
+ newExpanded.delete(category);
+ } else {
+ newExpanded.add(category);
+ }
+ setExpandedCategories(newExpanded);
+ };
+
+ // Get category icon
+ const getCategoryIcon = (category: string) => {
+ switch (category.toLowerCase()) {
+ case 'core':
+ return <Workflow size={16} />;
+ case 'data':
+ return <Database size={16} />;
+ case 'transform':
+ return <Filter size={16} />;
+ case 'control':
+ return <GitBranch size={16} />;
+ case 'output':
+ return <FileText size={16} />;
+ case 'developer':
+ return <Code size={16} />;
+ default:
+ return <Settings size={16} />;
+ }
+ };
+
+ // Get node icon color
+ const getNodeColor = (node: INodeTypeDescription) => {
+ return node.defaults?.color || '#888888';
+ };
+
+ // Handle drag start
+ const handleDragStart = (nodeType: string, event: React.DragEvent) => {
+ event.dataTransfer.setData('application/reactflow', nodeType);
+ event.dataTransfer.effectAllowed = 'move';
+ onDragStart?.(nodeType, event);
+ };
+
+ return (
+ <div className="w-80 bg-gray-900 border-r border-gray-800 flex flex-col h-full">
+ {/* Palette Header */}
+ <div className="p-4 border-b border-gray-800">
+ <h3 className="text-sm font-semibold text-gray-200 mb-3 flex items-center gap-2">
+ <Database size={16} className="text-blue-400" />
+ Node Palette
+ </h3>
+
+ {/* Search Input */}
+ <div className="relative">
+ <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Search nodes..."
+ className="w-full pl-10 pr-3 py-2 bg-gray-800 border border-gray-700 rounded text-sm text-gray-200 placeholder-gray-500 focus:border-blue-500 focus:outline-none"
+ />
+ </div>
+
+ <div className="text-xs text-gray-500 mt-2">
+ {allNodes.length} nodes available
+ </div>
+ </div>
+
+ {/* Node Categories */}
+ <div className="flex-1 overflow-y-auto">
+ {Array.from(filteredCategories.entries()).map(([category, nodes]) => (
+ <div key={category} className="border-b border-gray-800 last:border-0">
+ {/* Category Header */}
+ <button
+ onClick={() => toggleCategory(category)}
+ className="w-full px-4 py-3 flex items-center justify-between hover:bg-gray-800/50 transition-colors"
+ >
+ <div className="flex items-center gap-2 text-sm text-gray-300">
+ {getCategoryIcon(category)}
+ <span className="font-medium">{category}</span>
+ <span className="text-xs text-gray-600">({nodes.length})</span>
+ </div>
+ {expandedCategories.has(category) ? (
+ <ChevronDown size={16} className="text-gray-500" />
+ ) : (
+ <ChevronRight size={16} className="text-gray-500" />
+ )}
+ </button>
+
+ {/* Category Nodes */}
+ {expandedCategories.has(category) && (
+ <div className="pb-2">
+ {nodes.map((node) => (
+ <div
+ key={node.name}
+ draggable
+ onDragStart={(e) => handleDragStart(node.name, e)}
+ onClick={() => onNodeAdd(node.name)}
+ className="mx-2 mb-1 p-3 bg-gray-800/30 hover:bg-gray-800 rounded cursor-pointer transition-colors group"
+ title={node.description}
+ >
+ <div className="flex items-start gap-3">
+ {/* Node Icon */}
+ <div
+ className="w-8 h-8 rounded flex items-center justify-center flex-shrink-0 mt-0.5"
+ style={{
+ background: `${getNodeColor(node)}20`,
+ border: `1px solid ${getNodeColor(node)}40`,
+ }}
+ >
+ <div
+ className="text-xs font-bold"
+ style={{ color: getNodeColor(node) }}
+ >
+ {node.displayName[0]}
+ </div>
+ </div>
+
+ {/* Node Info */}
+ <div className="flex-1 min-w-0">
+ <div
+ className="text-sm font-medium mb-0.5"
+ style={{ color: getNodeColor(node) }}
+ >
+ {node.displayName}
+ </div>
+
+ {node.description && (
+ <div className="text-xs text-gray-500 line-clamp-2">
+ {node.description}
+ </div>
+ )}
+
+ {node.version && (
+ <div className="text-xs text-gray-600 mt-1">
+ v{node.version}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+
+ {/* No Results */}
+ {filteredCategories.size === 0 && (
+ <div className="p-8 text-center">
+ <Search size={32} className="mx-auto mb-2 text-gray-600" />
+ <p className="text-sm text-gray-500">No nodes found</p>
+ <p className="text-xs text-gray-600 mt-1">
+ Try a different search term
+ </p>
+ </div>
+ )}
+ </div>
+
+ {/* Palette Footer */}
+ <div className="p-4 border-t border-gray-800 bg-gray-900">
+ <div className="text-xs text-gray-500 text-center">
+ Drag nodes to the canvas or click to add
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default NodePalette;
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/NodeParameterInput.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/NodeParameterInput.tsx
new file mode 100644
index 000000000..6058e3168
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/NodeParameterInput.tsx
@@ -0,0 +1,408 @@
+/**
+ * Node Parameter Input Component
+ *
+ * Universal parameter input component that renders the appropriate UI control
+ * based on the parameter type from the node system.
+ *
+ * Supports all n8n parameter types:
+ * - String, Number, Boolean
+ * - Options, MultiOptions
+ * - Collection, FixedCollection
+ * - Color, DateTime
+ * - ResourceLocator
+ * - Code editor
+ * - Expression support
+ */
+
+import React, { useState, useCallback } from 'react';
+import type {
+ INodeProperties,
+ NodeParameterValue,
+ NodePropertyType,
+ INodePropertyOptions,
+ INodePropertyCollectionValue,
+} from '@/services/nodeSystem';
+import { ExpressionEngine, isExpression } from '@/services/nodeSystem';
+import { Check, Code2, Calendar, Hash, Type, List, Settings2, Palette } from 'lucide-react';
+
+interface NodeParameterInputProps {
+ parameter: INodeProperties;
+ value: NodeParameterValue;
+ onChange: (value: NodeParameterValue) => void;
+ onExpressionChange?: (isExpression: boolean) => void;
+ disabled?: boolean;
+ itemIndex?: number;
+ expressionContext?: any;
+}
+
+export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
+ parameter,
+ value,
+ onChange,
+ onExpressionChange,
+ disabled = false,
+ itemIndex = 0,
+ expressionContext,
+}) => {
+ const [isExpressionMode, setIsExpressionMode] = useState(
+ typeof value === 'string' && isExpression(value)
+ );
+
+ const handleToggleExpression = useCallback(() => {
+ const newMode = !isExpressionMode;
+ setIsExpressionMode(newMode);
+ onExpressionChange?.(newMode);
+
+ if (newMode) {
+ // Convert to expression
+ onChange(`={{${value}}}`);
+ } else {
+ // Convert back to regular value
+ const strValue = String(value);
+ if (strValue.startsWith('={{') && strValue.endsWith('}}')) {
+ onChange(strValue.slice(3, -2));
+ }
+ }
+ }, [isExpressionMode, value, onChange, onExpressionChange]);
+
+ const renderInput = () => {
+ // Expression mode - show code editor
+ if (isExpressionMode) {
+ return (
+ <textarea
+ value={String(value)}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ placeholder="={{$json.field}}"
+ className="w-full px-3 py-2 bg-gray-800 border border-yellow-500/30 rounded text-yellow-400 font-mono text-sm resize-y min-h-[60px]"
+ />
+ );
+ }
+
+ // Regular input based on type
+ switch (parameter.type) {
+ case 'string' as NodePropertyType:
+ return renderStringInput();
+
+ case 'number' as NodePropertyType:
+ return renderNumberInput();
+
+ case 'boolean' as NodePropertyType:
+ return renderBooleanInput();
+
+ case 'options' as NodePropertyType:
+ return renderOptionsInput();
+
+ case 'multiOptions' as NodePropertyType:
+ return renderMultiOptionsInput();
+
+ case 'color' as NodePropertyType:
+ return renderColorInput();
+
+ case 'dateTime' as NodePropertyType:
+ return renderDateTimeInput();
+
+ case 'json' as NodePropertyType:
+ case 'code' as NodePropertyType:
+ return renderCodeInput();
+
+ case 'collection' as NodePropertyType:
+ return renderCollectionInput();
+
+ case 'fixedCollection' as NodePropertyType:
+ return renderFixedCollectionInput();
+
+ case 'resourceLocator' as NodePropertyType:
+ return renderResourceLocatorInput();
+
+ default:
+ return renderStringInput();
+ }
+ };
+
+ const renderStringInput = () => (
+ <input
+ type="text"
+ value={String(value || '')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ placeholder={parameter.placeholder}
+ className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
+ />
+ );
+
+ const renderNumberInput = () => (
+ <input
+ type="number"
+ value={Number(value || 0)}
+ onChange={(e) => onChange(Number(e.target.value))}
+ disabled={disabled}
+ placeholder={parameter.placeholder}
+ className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
+ />
+ );
+
+ const renderBooleanInput = () => (
+ <label className="flex items-center gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={Boolean(value)}
+ onChange={(e) => onChange(e.target.checked)}
+ disabled={disabled}
+ className="w-4 h-4 rounded border-gray-700 bg-gray-800 text-blue-500 focus:ring-blue-500"
+ />
+ <span className="text-sm text-gray-300">
+ {parameter.description || 'Enable'}
+ </span>
+ </label>
+ );
+
+ const renderOptionsInput = () => {
+ const options = parameter.options as INodePropertyOptions[] | undefined;
+
+ return (
+ <select
+ value={String(value || parameter.default || '')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
+ >
+ {options?.map((option) => (
+ <option key={String(option.value)} value={String(option.value)}>
+ {option.name}
+ </option>
+ ))}
+ </select>
+ );
+ };
+
+ const renderMultiOptionsInput = () => {
+ const options = parameter.options as INodePropertyOptions[] | undefined;
+ const selectedValues = Array.isArray(value) ? value : [];
+
+ return (
+ <div className="space-y-2">
+ {options?.map((option) => (
+ <label key={String(option.value)} className="flex items-center gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={selectedValues.includes(option.value)}
+ onChange={(e) => {
+ const newValues = e.target.checked
+ ? [...selectedValues, option.value]
+ : selectedValues.filter((v) => v !== option.value);
+ onChange(newValues);
+ }}
+ disabled={disabled}
+ className="w-4 h-4 rounded border-gray-700 bg-gray-800 text-blue-500"
+ />
+ <span className="text-sm text-gray-300">{option.name}</span>
+ </label>
+ ))}
+ </div>
+ );
+ };
+
+ const renderColorInput = () => (
+ <div className="flex items-center gap-2">
+ <input
+ type="color"
+ value={String(value || '#000000')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ className="w-12 h-10 rounded border border-gray-700 bg-gray-800 cursor-pointer"
+ />
+ <input
+ type="text"
+ value={String(value || '#000000')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ placeholder="#000000"
+ className="flex-1 px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm font-mono focus:border-blue-500 focus:outline-none"
+ />
+ </div>
+ );
+
+ const renderDateTimeInput = () => (
+ <input
+ type="datetime-local"
+ value={value ? new Date(value as string | number).toISOString().slice(0, 16) : ''}
+ onChange={(e) => onChange(new Date(e.target.value).toISOString())}
+ disabled={disabled}
+ className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
+ />
+ );
+
+ const renderCodeInput = () => (
+ <textarea
+ value={String(value || '')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ placeholder={parameter.placeholder || '// Enter code here'}
+ className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded text-green-400 font-mono text-sm resize-y min-h-[120px] focus:border-blue-500 focus:outline-none"
+ />
+ );
+
+ const renderCollectionInput = () => (
+ <div className="p-3 bg-gray-800/50 border border-gray-700 rounded">
+ <div className="text-sm text-gray-400 mb-2">Collection (Advanced)</div>
+ <textarea
+ value={JSON.stringify(value, null, 2)}
+ onChange={(e) => {
+ try {
+ onChange(JSON.parse(e.target.value));
+ } catch {
+ // Invalid JSON, keep as string
+ }
+ }}
+ disabled={disabled}
+ className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded text-gray-200 font-mono text-xs resize-y min-h-[100px]"
+ />
+ </div>
+ );
+
+ const renderFixedCollectionInput = () => (
+ <div className="p-3 bg-gray-800/50 border border-gray-700 rounded">
+ <div className="text-sm text-gray-400 mb-2">Fixed Collection</div>
+ <div className="text-xs text-gray-500">
+ Complex input - configure in advanced editor
+ </div>
+ </div>
+ );
+
+ const renderResourceLocatorInput = () => {
+ // ResourceLocator typically has mode selector and value input
+ const resourceValue = (value as any) || { mode: 'id', value: '' };
+
+ return (
+ <div className="space-y-2">
+ <select
+ value={resourceValue.mode || 'id'}
+ onChange={(e) => onChange({ ...resourceValue, mode: e.target.value })}
+ disabled={disabled}
+ className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm"
+ >
+ <option value="id">By ID</option>
+ <option value="url">By URL</option>
+ <option value="list">From List</option>
+ </select>
+ <input
+ type="text"
+ value={resourceValue.value || ''}
+ onChange={(e) => onChange({ ...resourceValue, value: e.target.value })}
+ disabled={disabled}
+ placeholder={`Enter ${resourceValue.mode || 'ID'}...`}
+ className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
+ />
+ </div>
+ );
+ };
+
+ const getParameterIcon = () => {
+ switch (parameter.type) {
+ case 'string' as NodePropertyType:
+ return <Type size={14} />;
+ case 'number' as NodePropertyType:
+ return <Hash size={14} />;
+ case 'boolean' as NodePropertyType:
+ return <Check size={14} />;
+ case 'options' as NodePropertyType:
+ case 'multiOptions' as NodePropertyType:
+ return <List size={14} />;
+ case 'color' as NodePropertyType:
+ return <Palette size={14} />;
+ case 'dateTime' as NodePropertyType:
+ return <Calendar size={14} />;
+ case 'json' as NodePropertyType:
+ case 'code' as NodePropertyType:
+ return <Code2 size={14} />;
+ case 'collection' as NodePropertyType:
+ case 'fixedCollection' as NodePropertyType:
+ return <Settings2 size={14} />;
+ default:
+ return <Type size={14} />;
+ }
+ };
+
+ return (
+ <div className="space-y-2">
+ {/* Parameter Header */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <span className="text-gray-400">{getParameterIcon()}</span>
+ <label className="text-sm font-medium text-gray-200">
+ {parameter.displayName}
+ {parameter.required && <span className="text-red-400 ml-1">*</span>}
+ </label>
+ </div>
+
+ {/* Expression Toggle */}
+ {parameter.noDataExpression !== true && (
+ <button
+ onClick={handleToggleExpression}
+ disabled={disabled}
+ className={`px-2 py-1 text-xs rounded flex items-center gap-1 transition-colors ${
+ isExpressionMode
+ ? 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30'
+ : 'bg-gray-800 text-gray-400 border border-gray-700 hover:border-yellow-500/50'
+ }`}
+ title="Toggle expression mode"
+ >
+ <Code2 size={12} />
+ {isExpressionMode ? 'Expression' : 'Fixed'}
+ </button>
+ )}
+ </div>
+
+ {/* Parameter Description */}
+ {parameter.description && (
+ <div className="text-xs text-gray-500">{parameter.description}</div>
+ )}
+
+ {/* Parameter Input */}
+ {renderInput()}
+
+ {/* Expression Hint */}
+ {isExpressionMode && (
+ <div className="text-xs text-yellow-500/70">
+ Use expressions like: <code className="bg-gray-900 px-1 rounded">{'{{$json.field}}'}</code> or{' '}
+ <code className="bg-gray-900 px-1 rounded">={'{{1 + 2}}'}</code>
+ </div>
+ )}
+
+ {/* Validation Error */}
+ {parameter.validateType && value && (
+ <ValidationMessage parameter={parameter} value={value} />
+ )}
+ </div>
+ );
+};
+
+/**
+ * Validation Message Component
+ */
+const ValidationMessage: React.FC<{ parameter: INodeProperties; value: NodeParameterValue }> = ({
+ parameter,
+ value,
+}) => {
+ const { validateParameterValue } = require('@/services/nodeSystem');
+
+ if (!parameter.validateType || parameter.ignoreValidationDuringExecution) {
+ return null;
+ }
+
+ const validation = validateParameterValue(value, parameter.validateType);
+
+ if (validation.valid) {
+ return null;
+ }
+
+ return (
+ <div className="text-xs text-red-400 flex items-center gap-1">
+ <span>⚠️</span>
+ <span>{validation.error}</span>
+ </div>
+ );
+};
+
+export default NodeParameterInput;
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/SystemNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/SystemNode.tsx
new file mode 100644
index 000000000..c17680cb9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/SystemNode.tsx
@@ -0,0 +1,227 @@
+/**
+ * System Node Component for ReactFlow
+ *
+ * React component for rendering nodes from the n8n-inspired node system.
+ * Works with the NodeRegistry and displays nodes with their properties.
+ *
+ * Features:
+ * - Dynamic styling based on node type
+ * - Execution status indicators
+ * - Error display
+ * - Disabled state visualization
+ * - Input/output handles
+ * - Node configuration on click
+ */
+
+import React, { useMemo } from 'react';
+import { Handle, Position, NodeProps } from 'reactflow';
+import type { INode, INodeType } from '@/services/nodeSystem';
+import { NodeRegistry } from '@/services/nodeSystem';
+import {
+ Settings,
+ Play,
+ CheckCircle,
+ XCircle,
+ Clock,
+ AlertCircle,
+ Zap,
+} from 'lucide-react';
+
+export interface SystemNodeData {
+ node: INode;
+ onConfigure?: (node: INode) => void;
+ onExecute?: (node: INode) => void;
+ executionStatus?: 'idle' | 'running' | 'success' | 'error';
+ executionTime?: number;
+ error?: string;
+}
+
+export const SystemNode: React.FC<NodeProps<SystemNodeData>> = ({
+ data,
+ selected,
+}) => {
+ const node = data.node;
+
+ // Get node type definition
+ const nodeType = useMemo<INodeType | null>(() => {
+ try {
+ return NodeRegistry.getNodeType(node.type, node.typeVersion);
+ } catch (error) {
+ console.error('Failed to get node type:', error);
+ return null;
+ }
+ }, [node.type, node.typeVersion]);
+
+ // Node color
+ const nodeColor = nodeType?.description?.defaults?.color || '#888888';
+
+ // Execution status icon
+ const getStatusIcon = () => {
+ switch (data.executionStatus) {
+ case 'running':
+ return <Clock size={14} className="text-blue-400 animate-pulse" />;
+ case 'success':
+ return <CheckCircle size={14} className="text-green-400" />;
+ case 'error':
+ return <XCircle size={14} className="text-red-400" />;
+ default:
+ return null;
+ }
+ };
+
+ // Node icon or first letter
+ const getNodeIcon = () => {
+ if (nodeType?.description?.icon) {
+ // In a real implementation, you'd load the actual icon
+ return <Zap size={16} style={{ color: nodeColor }} />;
+ }
+
+ const displayName = nodeType?.description?.displayName || node.type;
+ return (
+ <div
+ className="w-6 h-6 rounded flex items-center justify-center text-xs font-bold"
+ style={{
+ background: `${nodeColor}30`,
+ color: nodeColor,
+ }}
+ >
+ {displayName[0].toUpperCase()}
+ </div>
+ );
+ };
+
+ if (!nodeType) {
+ return (
+ <div className="px-4 py-3 bg-red-900/20 border-2 border-red-500 rounded-lg min-w-[200px]">
+ <div className="flex items-center gap-2 text-red-400">
+ <AlertCircle size={16} />
+ <span className="text-sm font-medium">Unknown Node Type</span>
+ </div>
+ <div className="text-xs text-red-400/70 mt-1">{node.type}</div>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className={`relative bg-gray-900 rounded-lg min-w-[220px] transition-all ${
+ selected ? 'ring-2 ring-blue-500 shadow-lg shadow-blue-500/20' : 'shadow-md'
+ } ${node.disabled ? 'opacity-50' : ''}`}
+ style={{
+ borderLeft: `4px solid ${nodeColor}`,
+ }}
+ >
+ {/* Input Handle */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ className="w-3 h-3 !bg-gray-700 !border-2 !border-gray-900"
+ style={{
+ left: -6,
+ }}
+ />
+
+ {/* Node Header */}
+ <div
+ className="px-3 py-2 border-b border-gray-800 flex items-center justify-between gap-2"
+ style={{
+ background: `${nodeColor}10`,
+ }}
+ >
+ <div className="flex items-center gap-2 flex-1 min-w-0">
+ {getNodeIcon()}
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-gray-200 truncate">
+ {nodeType.description.displayName}
+ </div>
+ {node.name !== nodeType.description.displayName && (
+ <div className="text-xs text-gray-500 truncate">{node.name}</div>
+ )}
+ </div>
+ </div>
+
+ {/* Status Icon */}
+ {getStatusIcon()}
+ </div>
+
+ {/* Node Body */}
+ <div className="px-3 py-2 space-y-1">
+ {/* Execution Time */}
+ {data.executionTime !== undefined && (
+ <div className="text-xs text-gray-500 flex items-center gap-1">
+ <Clock size={12} />
+ <span>{data.executionTime}ms</span>
+ </div>
+ )}
+
+ {/* Error Message */}
+ {data.error && (
+ <div className="text-xs text-red-400 flex items-start gap-1 bg-red-900/20 px-2 py-1 rounded">
+ <XCircle size={12} className="mt-0.5 flex-shrink-0" />
+ <span className="break-words">{data.error}</span>
+ </div>
+ )}
+
+ {/* Node Type */}
+ <div className="text-xs text-gray-600">
+ {node.type} v{node.typeVersion || 1}
+ </div>
+
+ {/* Disabled Badge */}
+ {node.disabled && (
+ <div className="inline-flex items-center gap-1 px-2 py-0.5 bg-yellow-900/30 border border-yellow-700/30 rounded text-xs text-yellow-500">
+ <AlertCircle size={10} />
+ Disabled
+ </div>
+ )}
+ </div>
+
+ {/* Node Footer - Actions */}
+ <div className="px-3 py-2 border-t border-gray-800 flex items-center gap-2">
+ <button
+ onClick={() => data.onConfigure?.(node)}
+ className="flex-1 px-2 py-1 bg-gray-800 hover:bg-gray-700 rounded text-xs text-gray-300 flex items-center justify-center gap-1 transition-colors"
+ title="Configure node"
+ >
+ <Settings size={12} />
+ Configure
+ </button>
+
+ {data.onExecute && (
+ <button
+ onClick={() => data.onExecute?.(node)}
+ disabled={node.disabled || data.executionStatus === 'running'}
+ className="px-2 py-1 bg-blue-600 hover:bg-blue-500 disabled:bg-gray-700 disabled:text-gray-500 rounded text-xs text-white flex items-center gap-1 transition-colors"
+ title="Execute node"
+ >
+ <Play size={12} />
+ </button>
+ )}
+ </div>
+
+ {/* Output Handle */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ className="w-3 h-3 !bg-gray-700 !border-2 !border-gray-900"
+ style={{
+ right: -6,
+ }}
+ />
+
+ {/* Execution Indicator Overlay */}
+ {data.executionStatus === 'running' && (
+ <div
+ className="absolute inset-0 rounded-lg pointer-events-none"
+ style={{
+ background: `linear-gradient(90deg, transparent 0%, ${nodeColor}20 50%, transparent 100%)`,
+ backgroundSize: '200% 100%',
+ animation: 'shimmer 2s infinite',
+ }}
+ />
+ )}
+ </div>
+ );
+};
+
+export default SystemNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/MarketDepthChart.tsx b/fincept-terminal-desktop/src/components/tabs/trading/MarketDepthChart.tsx
index 5cc74efe5..534552645 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/MarketDepthChart.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/MarketDepthChart.tsx
@@ -1,7 +1,7 @@
// MarketDepthChart.tsx - Market depth table with visual depth bars
import React, { useState, useEffect } from 'react';
-import { useWebSocket } from '../../../hooks/useWebSocket';
-import { isProviderAvailable } from '../../../services/websocket';
+import { useRustOrderBook } from '../../../hooks/useRustWebSocket';
+
interface MarketDepthChartProps {
symbol: string;
@@ -19,50 +19,44 @@ export function MarketDepthChart({ symbol, provider }: MarketDepthChartProps) {
const [asks, setAsks] = useState<DepthLevel[]>([]);
const [maxCumulative, setMaxCumulative] = useState(0);
- // Only subscribe if WebSocket adapter exists for this provider
- const hasWebSocket = isProviderAvailable(provider);
-
- const { message, isLoading } = useWebSocket(
- hasWebSocket ? `${provider}.book.${symbol}` : null,
- null,
- { autoSubscribe: hasWebSocket, params: { depth: 50 } }
- );
+ // Use Rust WebSocket hook with 50 levels depth
+ const { data: orderbookData } = useRustOrderBook(provider, symbol, 50, true);
useEffect(() => {
- if (!message || message.type !== 'orderbook') return;
+ if (!orderbookData) return;
- const data = message.data;
- if (!data || !Array.isArray(data.bids) || !Array.isArray(data.asks)) return;
+ const data = orderbookData;
+ if (!Array.isArray(data.bids) || !Array.isArray(data.asks)) return;
try {
// Process bids (buy orders) - highest to lowest
const rawBids = data.bids
- .filter((level: any) => level && typeof level.price === 'number' && typeof level.size === 'number')
+ .filter((level: any) => level && typeof level.price === 'number' && typeof level.quantity === 'number')
.sort((a: any, b: any) => b.price - a.price)
.slice(0, 25);
let bidCumulative = 0;
const processedBids: DepthLevel[] = rawBids.map((level: any) => {
- bidCumulative += level.size;
+ bidCumulative += level.quantity;
return {
price: level.price,
- size: level.size,
+ size: level.quantity,
cumulative: bidCumulative,
};
});
// Process asks (sell orders) - lowest to highest
const rawAsks = data.asks
- .filter((level: any) => level && typeof level.price === 'number' && typeof level.size === 'number')
+ .filter((level: any) => level && typeof level.price === 'number' && typeof level.quantity === 'number')
.sort((a: any, b: any) => a.price - b.price)
.slice(0, 25);
let askCumulative = 0;
const processedAsks: DepthLevel[] = rawAsks.map((level: any) => {
- askCumulative += level.size;
+ askCumulative += level.quantity;
return {
price: level.price,
- size: level.size,
+ size: level.quantity,
cumulative: askCumulative,
};
});
@@ -77,9 +71,9 @@ export function MarketDepthChart({ symbol, provider }: MarketDepthChartProps) {
} catch (error) {
console.error('[MarketDepthChart] Failed to process data:', error);
}
- }, [message]);
+ }, [orderbookData]);
- if (isLoading) {
+ if (!orderbookData) {
return (
<div className="bg-[#0d0d0d] border-t border-gray-800 p-3">
<h3 className="text-[10px] font-bold text-gray-400 tracking-wider mb-2">MARKET DEPTH</h3>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx b/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx
index 4dca67d88..1354da268 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx
@@ -2,8 +2,8 @@
// Provider-agnostic order book component
import React, { useState, useEffect } from 'react';
-import { useWebSocket } from '../../../hooks/useWebSocket';
-import { isProviderAvailable } from '../../../services/websocket';
+import { useRustOrderBook } from '../../../hooks/useRustWebSocket';
+
interface OrderBookLevel {
price: number;
@@ -22,67 +22,46 @@ export function OrderBook({ symbol, provider, depth = 25 }: OrderBookProps) {
const [asks, setAsks] = useState<OrderBookLevel[]>([]);
const [spread, setSpread] = useState<number>(0);
- // Only subscribe if WebSocket adapter exists for this provider
- const hasWebSocket = isProviderAvailable(provider);
-
- const { message } = useWebSocket(
- hasWebSocket ? `${provider}.book.${symbol}` : null,
- null,
- { autoSubscribe: hasWebSocket, params: { depth } }
+ // Use Rust WebSocket backend
+ const { data, error: wsError } = useRustOrderBook(
+ provider,
+ symbol,
+ depth
);
useEffect(() => {
- if (!message || message.type !== 'orderbook') return;
+ if (!data) return;
- const data = message.data;
-
- // Validate data structure
- if (!data || typeof data !== 'object') {
- console.warn('[OrderBook] Invalid data structure:', data);
- return;
- }
+ const rustBids = data.bids || [];
+ const rustAsks = data.asks || [];
// Process bids (buy orders) - highest first
- const rawBids = Array.isArray(data.bids) ? data.bids : [];
- const processedBids = rawBids
- .filter((level: any) =>
- level &&
- typeof level === 'object' &&
- typeof level.price === 'number' &&
- typeof level.size === 'number'
- )
+ const processedBids = rustBids
.slice(0, depth)
.sort((a: any, b: any) => b.price - a.price);
// Process asks (sell orders) - lowest first
- const rawAsks = Array.isArray(data.asks) ? data.asks : [];
- const processedAsks = rawAsks
- .filter((level: any) =>
- level &&
- typeof level === 'object' &&
- typeof level.price === 'number' &&
- typeof level.size === 'number'
- )
+ const processedAsks = rustAsks
.slice(0, depth)
.sort((a: any, b: any) => a.price - b.price);
// Calculate running totals
let bidTotal = 0;
const bidsWithTotal = processedBids.map((level: any) => {
- bidTotal += level.size || 0;
+ bidTotal += level.quantity || 0;
return {
price: level.price || 0,
- size: level.size || 0,
+ size: level.quantity || 0,
total: bidTotal
};
});
let askTotal = 0;
const asksWithTotal = processedAsks.map((level: any) => {
- askTotal += level.size || 0;
+ askTotal += level.quantity || 0;
return {
price: level.price || 0,
- size: level.size || 0,
+ size: level.quantity || 0,
total: askTotal
};
});
@@ -96,7 +75,7 @@ export function OrderBook({ symbol, provider, depth = 25 }: OrderBookProps) {
const bestAsk = processedAsks[0].price || 0;
setSpread(bestAsk - bestBid);
}
- }, [message, depth]);
+ }, [data, depth]);
const maxTotal = Math.max(
bids[bids.length - 1]?.total || 0,
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/OrderBook_old.tsx.bak b/fincept-terminal-desktop/src/components/tabs/trading/OrderBook_old.tsx.bak
new file mode 100644
index 000000000..83d9a7294
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/OrderBook_old.tsx.bak
@@ -0,0 +1,2 @@
+// Temporarily stubbed - migration to Rust WebSocket in progress
+export function OrderBook() { return <div>Migrating to Rust WebSocket...</div>; }
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx b/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx
index c0a642a41..e4efe4e69 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx
@@ -2,8 +2,7 @@
// Provider-agnostic ticker display component
import React, { useState, useEffect } from 'react';
-import { useWebSocket } from '../../../hooks/useWebSocket';
-import { isProviderAvailable } from '../../../services/websocket';
+import { useRustTicker } from '../../../hooks/useRustWebSocket';
interface TickerDisplayProps {
symbol: string;
@@ -24,38 +23,27 @@ interface TickerData {
export function TickerDisplay({ symbol, provider }: TickerDisplayProps) {
const [ticker, setTicker] = useState<TickerData | null>(null);
- // Only subscribe if WebSocket adapter exists for this provider
- const hasWebSocket = isProviderAvailable(provider);
-
- const { message } = useWebSocket(
- hasWebSocket ? `${provider}.ticker.${symbol}` : null,
- null,
- { autoSubscribe: hasWebSocket }
- );
+ // Use Rust WebSocket hook
+ const { data: tickerData } = useRustTicker(provider, symbol, true);
useEffect(() => {
- if (!message || message.type !== 'ticker') return;
-
- const data = message.data;
-
- // Parse nested data if needed
- const tickerData = data.ticker || data;
+ if (!tickerData) return;
- // Extract values with multiple fallbacks for different provider formats
- const last = parseFloat(tickerData.last || tickerData.close || tickerData.price || tickerData.mid || 0);
- const bid = parseFloat(tickerData.bid || tickerData.bid_price || tickerData.b || 0);
- const ask = parseFloat(tickerData.ask || tickerData.ask_price || tickerData.a || 0);
- const volume = parseFloat(tickerData.volume || tickerData.vol || tickerData.v || 0);
- const high = parseFloat(tickerData.high || tickerData.h || 0);
- const low = parseFloat(tickerData.low || tickerData.l || 0);
+ // Extract values with fallbacks
+ const last = tickerData.price || 0;
+ const bid = tickerData.bid || 0;
+ const ask = tickerData.ask || 0;
+ const volume = tickerData.volume || 0;
+ const high = tickerData.high || 0;
+ const low = tickerData.low || 0;
// Calculate change if not provided
- let change = parseFloat(tickerData.change || 0);
- let changePct = parseFloat(tickerData.change_pct || tickerData.changePct || 0);
+ let change = tickerData.change || 0;
+ let changePct = tickerData.change_percent || 0;
if (change === 0 && tickerData.open) {
- change = last - parseFloat(tickerData.open);
- changePct = (change / parseFloat(tickerData.open)) * 100;
+ change = last - tickerData.open;
+ changePct = (change / tickerData.open) * 100;
}
setTicker({
@@ -68,7 +56,7 @@ export function TickerDisplay({ symbol, provider }: TickerDisplayProps) {
change,
changePct
});
- }, [message]);
+ }, [tickerData]);
if (!ticker) {
return (
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx b/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx
index 087b9ae4e..d43bc1071 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx
@@ -2,8 +2,8 @@
// Provider-agnostic trades feed component
import React, { useState, useEffect } from 'react';
-import { useWebSocket } from '../../../hooks/useWebSocket';
-import { isProviderAvailable } from '../../../services/websocket';
+import { useRustTrades } from '../../../hooks/useRustWebSocket';
+
interface Trade {
price: number;
@@ -21,46 +21,26 @@ interface TradesFeedProps {
export function TradesFeed({ symbol, provider, maxTrades = 50 }: TradesFeedProps) {
const [trades, setTrades] = useState<Trade[]>([]);
- // Only subscribe if WebSocket adapter exists for this provider
- const hasWebSocket = isProviderAvailable(provider);
-
- const { message, isLoading, error } = useWebSocket(
- hasWebSocket ? `${provider}.trades.${symbol}` : null,
- null,
- { autoSubscribe: hasWebSocket }
+ // Use Rust WebSocket backend
+ const { trades: rustTrades, error: wsError } = useRustTrades(
+ provider,
+ symbol,
+ maxTrades
);
useEffect(() => {
- if (!message || message.type !== 'trade') return;
-
- const data = message.data;
+ if (!rustTrades || rustTrades.length === 0) return;
- // Handle different data formats
- let newTrades: Trade[] = [];
+ // Map Rust trade data to component format
+ const newTrades: Trade[] = rustTrades.map((trade) => ({
+ price: trade.price,
+ size: trade.quantity,
+ side: trade.side === 'buy' || trade.side === 'sell' ? trade.side : 'buy',
+ time: trade.timestamp
+ }));
- if (Array.isArray(data.trades)) {
- // Multiple trades (e.g., HyperLiquid)
- newTrades = data.trades.map((trade: any) => ({
- price: trade.price || parseFloat(trade.px),
- size: trade.size || parseFloat(trade.sz),
- side: trade.side === 'sell' || trade.side === 'A' ? 'sell' : 'buy',
- time: trade.time || Date.now()
- }));
- } else {
- // Single trade (e.g., Kraken)
- newTrades = [{
- price: data.price || parseFloat(data.px),
- size: data.size || parseFloat(data.sz),
- side: data.side === 'sell' || data.side === 'A' ? 'sell' : 'buy',
- time: data.time || Date.now()
- }];
- }
-
- setTrades(prev => {
- const updated = [...newTrades, ...prev];
- return updated.slice(0, maxTrades);
- });
- }, [message, maxTrades]);
+ setTrades(newTrades.slice(0, maxTrades));
+ }, [rustTrades, maxTrades]);
return (
<div className="flex flex-col h-full bg-[#0d0d0d] text-white font-mono text-[11px]">
@@ -82,14 +62,9 @@ export function TradesFeed({ symbol, provider, maxTrades = 50 }: TradesFeedProps
{/* Trades List */}
<div className="flex-1 overflow-y-auto">
- {isLoading && trades.length === 0 ? (
- <div className="p-4 text-center text-gray-500">
- <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-orange-500 mx-auto mb-2"></div>
- Connecting...
- </div>
- ) : error && trades.length === 0 ? (
+ {wsError && trades.length === 0 ? (
<div className="p-4 text-center text-red-500 text-xs">
- Connection error
+ Connection error: {wsError}
</div>
) : trades.length === 0 ? (
<div className="p-4 text-center text-gray-500">Waiting for trades...</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed_old.tsx.bak b/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed_old.tsx.bak
new file mode 100644
index 000000000..83d9a7294
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed_old.tsx.bak
@@ -0,0 +1,2 @@
+// Temporarily stubbed - migration to Rust WebSocket in progress
+export function OrderBook() { return <div>Migrating to Rust WebSocket...</div>; }
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx
index 73efc9378..765106542 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/TradingChart.tsx
@@ -1,8 +1,8 @@
// TradingChart.tsx - TradingView Lightweight Charts with historical + live data
import React, { useEffect, useRef, useState } from 'react';
import { createChart, IChartApi, ISeriesApi, CandlestickData, Time } from 'lightweight-charts';
-import { useWebSocket } from '../../../hooks/useWebSocket';
-import { isProviderAvailable } from '../../../services/websocket';
+import { useRustCandles } from '../../../hooks/useRustWebSocket';
+
import { useBrokerContext } from '../../../contexts/BrokerContext';
interface TradingChartProps {
@@ -23,14 +23,11 @@ export function TradingChart({ symbol, provider, interval = '1m' }: TradingChart
const { realAdapter } = useBrokerContext();
- // Only subscribe if WebSocket adapter exists for this provider
- const hasWebSocket = isProviderAvailable(provider);
-
- // Subscribe to candle data
- const { message, error: wsError } = useWebSocket(
- hasWebSocket ? `${provider}.ohlc.${symbol}` : null,
- null,
- { autoSubscribe: hasWebSocket, params: { interval: parseInterval(interval) } }
+ // Use Rust WebSocket backend for candle data
+ const { candles: rustCandles, latestCandle, error: wsError } = useRustCandles(
+ provider,
+ symbol,
+ interval
);
// Initialize chart
@@ -179,16 +176,19 @@ export function TradingChart({ symbol, provider, interval = '1m' }: TradingChart
fetchHistoricalData();
}, [symbol, interval, realAdapter]);
- // Handle live candle updates from WebSocket
+ // Handle live candle updates from Rust WebSocket
useEffect(() => {
- if (!message || message.type !== 'candle') return;
+ if (!latestCandle) return;
if (!candlestickSeriesRef.current || !volumeSeriesRef.current) return;
- const data = message.data;
-
// Parse candle data
- const candle = parseCandleData(data);
- if (!candle) return;
+ const candle: CandlestickData = {
+ time: Math.floor(latestCandle.timestamp / 1000) as Time,
+ open: latestCandle.open,
+ high: latestCandle.high,
+ low: latestCandle.low,
+ close: latestCandle.close,
+ };
console.log('[TradingChart] Live candle update:', candle);
@@ -199,7 +199,7 @@ export function TradingChart({ symbol, provider, interval = '1m' }: TradingChart
// Update volume
volumeSeriesRef.current.update({
time: candle.time,
- value: (data.volume || data.v || 0) as number,
+ value: latestCandle.volume,
color: candle.close >= candle.open ? '#10b98180' : '#dc262680',
});
@@ -217,7 +217,7 @@ export function TradingChart({ symbol, provider, interval = '1m' }: TradingChart
} catch (error) {
console.error('[TradingChart] Failed to update candle:', error);
}
- }, [message]);
+ }, [latestCandle]);
return (
<div className="relative w-full h-full bg-[#0d0d0d]">
@@ -260,7 +260,7 @@ export function TradingChart({ symbol, provider, interval = '1m' }: TradingChart
<span>{interval}</span>
<span>•</span>
<span>{candleData.length} candles</span>
- {hasWebSocket && (
+ {latestCandle && (
<>
<span>•</span>
<span className="text-green-400">● Live</span>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TradingChart_old.tsx.bak b/fincept-terminal-desktop/src/components/tabs/trading/TradingChart_old.tsx.bak
new file mode 100644
index 000000000..83d9a7294
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/TradingChart_old.tsx.bak
@@ -0,0 +1,2 @@
+// Temporarily stubbed - migration to Rust WebSocket in progress
+export function OrderBook() { return <div>Migrating to Rust WebSocket...</div>; }
diff --git a/fincept-terminal-desktop/src/contexts/AuthContext.tsx b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
index d538028de..059172c3d 100644
--- a/fincept-terminal-desktop/src/contexts/AuthContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
@@ -57,21 +57,20 @@ export interface ApiResponse {
status_code?: number;
}
-// Payment related types
+// Payment related types - Credit-based system
export interface SubscriptionPlan {
plan_id: string;
name: string;
description: string;
price_usd: number;
- billing_interval: string;
- api_calls_limit: number | string;
- databases_access: string[];
- priority_support: boolean;
- features: {
- api_calls: string;
- databases: string;
- support: string;
- };
+ price_display: string;
+ credits_amount: number;
+ support_type: string;
+ support_display: string;
+ validity_days: number;
+ validity_display: string;
+ is_popular: boolean;
+ display_order: number;
}
export interface PaymentSession {
@@ -142,14 +141,14 @@ interface AuthContextType {
resetPassword: (email: string, otp: string, newPassword: string) => Promise<{ success: boolean; error?: string }>;
// Payment methods
fetchPlans: () => Promise<{ success: boolean; error?: string }>;
- createPaymentSession: (planId: string) => Promise<{ success: boolean; data?: PaymentSession; error?: string }>;
+ createPaymentSession: (planId: string, currency?: string) => Promise<{ success: boolean; data?: PaymentSession; error?: string }>;
getUserSubscription: () => Promise<{ success: boolean; data?: UserSubscription; error?: string }>;
refreshUserData: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
-// Device ID generation
+// Device ID generation (must be 10-255 characters for API)
const generateDeviceId = (): string => {
const getNavigatorInfo = () => {
return {
@@ -157,7 +156,9 @@ const generateDeviceId = (): string => {
userAgent: navigator.userAgent,
language: navigator.language,
cookieEnabled: navigator.cookieEnabled,
- onLine: navigator.onLine
+ onLine: navigator.onLine,
+ screenRes: `${window.screen.width}x${window.screen.height}`,
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
};
};
@@ -171,7 +172,16 @@ const generateDeviceId = (): string => {
hash = hash & hash;
}
- return `desktop_${Math.abs(hash).toString(16)}`;
+ // Generate a device ID that's between 10-255 characters
+ const hashStr = Math.abs(hash).toString(16);
+ const timestamp = Date.now().toString(36);
+ const random = Math.random().toString(36).substring(2);
+
+ // Format: fincept_desktop_{hash}_{timestamp}_{random}
+ const deviceId = `fincept_desktop_${hashStr}_${timestamp}_${random}`;
+
+ // Ensure it's within the valid range (10-255 characters)
+ return deviceId.length > 255 ? deviceId.substring(0, 255) : deviceId;
};
// Session storage utilities
@@ -237,12 +247,9 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['data'] | null> => {
try {
const result = await AuthApiService.getUserProfile(apiKey);
- console.log('AuthContext: Raw profile result:', result); // Add this debug line
if (result.success && result.data) {
- // Fix: Extract the nested data properly
const profileData = (result.data as any).data || result.data;
- console.log('AuthContext: Extracted profile data:', profileData); // Add this debug line
return profileData;
}
return null;
@@ -301,37 +308,22 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
// Validate session with API
const validateSession = async (sessionData: SessionData): Promise<SessionData | null> => {
if (!sessionData.api_key) {
- console.log('validateSession: No API key found');
return null;
}
- console.log('validateSession: Validating session with API...');
const result = await AuthApiService.getAuthStatus(sessionData.api_key, sessionData.device_id);
- console.log('validateSession: Auth status result:', result);
- console.log('validateSession: result.success =', result.success);
- console.log('validateSession: result.data =', result.data);
- // Backend returns nested structure: result.data.data contains the actual auth data
const authData = (result.data as any)?.data || result.data;
- console.log('validateSession: authData =', authData);
- console.log('validateSession: authData?.authenticated =', authData?.authenticated);
if (result.success && authData?.authenticated) {
const apiData = authData;
- console.log('validateSession: User authenticated, type:', apiData.user_type);
- // For registered users, fetch detailed profile and subscription
let userProfile = null;
let userSubscription = null;
if (apiData.user_type === 'registered') {
- console.log('validateSession: Fetching user profile...');
userProfile = await fetchUserProfile(sessionData.api_key);
- console.log('validateSession: User profile result:', userProfile);
-
- console.log('validateSession: Fetching user subscription...');
userSubscription = await fetchUserSubscription(sessionData.api_key);
- console.log('validateSession: User subscription result:', userSubscription);
}
const validatedSession = {
@@ -353,47 +345,37 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
subscription: userSubscription || undefined
};
- console.log('validateSession: Returning validated session:', validatedSession);
return validatedSession;
}
- console.log('validateSession: Auth status check failed or not authenticated');
return null;
};
// Initialize session on app load
useEffect(() => {
const initializeSession = async () => {
- console.log('AuthContext: Initializing session...');
-
try {
setIsFirstTimeUser(checkIsFirstTimeUser());
const savedSession = loadSession();
- console.log('AuthContext: Saved session:', savedSession ? 'Found' : 'Not found');
- // In your AuthContext useEffect:
if (savedSession) {
if (savedSession.user_type === 'registered') {
- // Always validate registered users, even in dev mode
const validatedSession = await validateSession(savedSession);
if (validatedSession) {
setSession(validatedSession);
saveSession(validatedSession);
} else {
- console.log('Session validation failed, clearing...');
clearSession();
}
} else {
- // Only skip validation for guest users in dev mode
setSession(savedSession);
}
}
} catch (error) {
- console.error('AuthContext: Initialization error:', error);
+ console.error('Session initialization error:', error);
} finally {
- console.log('AuthContext: Initialization complete');
setIsLoading(false);
}
};
@@ -412,46 +394,35 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
}
};
- // Fetch subscription plans
// Fetch subscription plans
const fetchPlans = async (): Promise<{ success: boolean; error?: string }> => {
setIsLoadingPlans(true);
try {
- console.log('AuthContext: Fetching plans from API...');
const result = await PaymentApiService.getSubscriptionPlans();
- console.log('AuthContext: Plans API result:', result);
-
if (result.success && result.data) {
- // Handle the nested response structure: result.data.data.plans
const plansData = (result.data as any).data || result.data;
const plans = plansData.plans || [];
- console.log('AuthContext: Extracted plans:', plans);
- console.log('AuthContext: Number of plans:', plans.length);
-
if (plans.length > 0) {
setAvailablePlans(plans);
- console.log('AuthContext: Plans set successfully');
return { success: true };
} else {
- console.log('AuthContext: No plans found in response');
return { success: false, error: 'No plans available' };
}
} else {
- console.log('AuthContext: API request failed:', result.error);
return { success: false, error: result.error || 'Failed to fetch plans' };
}
} catch (error) {
- console.error('AuthContext: Failed to fetch plans:', error);
+ console.error('Failed to fetch plans:', error);
return { success: false, error: 'Failed to fetch plans' };
} finally {
setIsLoadingPlans(false);
}
};
- // Create payment session
- const createPaymentSession = async (planId: string): Promise<{ success: boolean; data?: PaymentSession; error?: string }> => {
+ // Create payment session - Updated for new API format
+ const createPaymentSession = async (planId: string, currency: string = 'USD'): Promise<{ success: boolean; data?: PaymentSession; error?: string }> => {
if (!session?.api_key) {
return { success: false, error: 'No API key available' };
}
@@ -459,11 +430,24 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
try {
const result = await PaymentApiService.createCheckoutSession(session.api_key, {
plan_id: planId,
- return_url: `${window.location.origin}/payment-success`
+ currency: currency
});
if (result.success && result.data) {
- return { success: true, data: result.data };
+ // Handle double-wrapped response
+ const apiData = (result.data as any)?.data || result.data;
+
+ // Map the new API response to PaymentSession format
+ const paymentSession: PaymentSession = {
+ checkout_url: apiData.checkout_url,
+ session_id: apiData.payment_session_id,
+ payment_uuid: apiData.order_id,
+ plan: {
+ name: apiData.plan?.name || 'Unknown Plan',
+ price: apiData.pricing?.amount || 0
+ }
+ };
+ return { success: true, data: paymentSession };
} else {
return { success: false, error: result.error || 'Failed to create payment session' };
}
@@ -495,63 +479,59 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
// Login function
const login = async (email: string, password: string): Promise<{ success: boolean; error?: string }> => {
try {
- console.log('AuthContext: Attempting login for:', email);
-
const result = await AuthApiService.login({ email, password }) as ApiResponse;
- console.log('AuthContext: Full login result:', result);
- console.log('AuthContext: result.success:', result.success);
- console.log('AuthContext: result.data:', result.data);
-
- // In AuthContext.tsx, update the login function around line 480-515:
-
-if (result.success && result.data && result.data.data && result.data.data.api_key) {
- const apiKey = result.data.data.api_key;
- console.log('AuthContext: Login successful, API key received:', apiKey.substring(0, 20) + '...');
-
- // Fetch user profile and subscription to get account_type and other details
- const [userProfile, userSubscription] = await Promise.all([
- fetchUserProfile(apiKey),
- fetchUserSubscription(apiKey)
- ]);
-
- const newSession: SessionData = {
- authenticated: true,
- user_type: 'registered',
- api_key: apiKey,
- device_id: generateDeviceId(),
- user_info: userProfile ? {
- username: userProfile.username,
- email: userProfile.email,
- account_type: userProfile.account_type, // ← This should be working
- credit_balance: userProfile.credit_balance,
- is_verified: userProfile.is_verified,
- mfa_enabled: userProfile.mfa_enabled
- } : {
- // Fallback if profile fetch fails - assume free account
- email: email,
- account_type: 'free', // ← Make sure this fallback is 'free', not undefined
- credit_balance: 0
- },
- subscription: userSubscription || undefined
- };
+ console.log('=== LOGIN RESPONSE DEBUG ===');
+ console.log('Full result:', JSON.stringify(result, null, 2));
+ console.log('result.success:', result.success);
+ console.log('result.data:', result.data);
+ console.log('========================');
+
+ // Backend returns: { success: true, data: { api_key: "..." } }
+ // But makeApiRequest wraps it again, so we need to check result.data.data
+ const apiData = (result.data as any)?.data || result.data;
+
+ if (result.success && apiData && apiData.api_key) {
+ const apiKey = apiData.api_key;
+
+ const [userProfile, userSubscription] = await Promise.all([
+ fetchUserProfile(apiKey),
+ fetchUserSubscription(apiKey)
+ ]);
+
+ const newSession: SessionData = {
+ authenticated: true,
+ user_type: 'registered',
+ api_key: apiKey,
+ device_id: generateDeviceId(),
+ user_info: userProfile ? {
+ username: userProfile.username,
+ email: userProfile.email,
+ account_type: userProfile.account_type,
+ credit_balance: userProfile.credit_balance,
+ is_verified: userProfile.is_verified,
+ mfa_enabled: userProfile.mfa_enabled
+ } : {
+ email: email,
+ account_type: 'free',
+ credit_balance: 0
+ },
+ subscription: userSubscription || undefined
+ };
- setSession(newSession);
- saveSession(newSession);
- setIsFirstTimeUser(checkIsFirstTimeUser());
+ setSession(newSession);
+ saveSession(newSession);
+ setIsFirstTimeUser(checkIsFirstTimeUser());
- console.log('AuthContext: Login successful, account_type:', newSession.user_info?.account_type);
- console.log('AuthContext: Has subscription:', !!newSession.subscription?.has_subscription);
- return { success: true };
-} else {
- console.log('AuthContext: Login failed - success:', result.success, 'data:', result.data, 'error:', result.error);
+ return { success: true };
+ } else {
return {
success: false,
error: result.error || result.message || 'Login failed'
};
}
} catch (error) {
- console.error('AuthContext: Login error:', error);
+ console.error('Login error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Login failed'
@@ -589,11 +569,13 @@ if (result.success && result.data && result.data.data && result.data.data.api_ke
try {
const result = await AuthApiService.verifyOtp({ email, otp }) as ApiResponse;
- if (result.success && result.data && result.data.data && result.data.data.api_key) {
- const apiKey = result.data.data.api_key;
- console.log('AuthContext: OTP verification successful, API key received');
+ // Backend returns: { success: true, data: { api_key: "..." } }
+ // But makeApiRequest wraps it again, so we need to check result.data.data
+ const apiData = (result.data as any)?.data || result.data;
+
+ if (result.success && apiData && apiData.api_key) {
+ const apiKey = apiData.api_key;
- // Fetch user profile for new registered user (no subscription yet)
const userProfile = await fetchUserProfile(apiKey);
const newSession: SessionData = {
@@ -609,12 +591,11 @@ if (result.success && result.data && result.data.data && result.data.data.api_ke
is_verified: userProfile.is_verified,
mfa_enabled: userProfile.mfa_enabled
} : {
- // Fallback if profile fetch fails - assume free account
email: email,
account_type: 'free',
credit_balance: 0
},
- subscription: undefined // New user won't have subscription yet
+ subscription: undefined
};
setSession(newSession);
@@ -701,7 +682,10 @@ if (result.success && result.data && result.data.data && result.data.data.api_ke
hardware_info: {
platform: navigator.platform,
user_agent: navigator.userAgent,
- language: navigator.language
+ language: navigator.language,
+ screen_resolution: `${window.screen.width}x${window.screen.height}`,
+ cpu_cores: navigator.hardwareConcurrency || 4,
+ memory_gb: (navigator as any).deviceMemory || 8
}
}) as DeviceRegisterResponse;
@@ -738,13 +722,9 @@ if (result.success && result.data && result.data.data && result.data.data.api_ke
// Logout function
const logout = async (): Promise<void> => {
- console.log('AuthContext: Logging out...');
-
setSession(null);
clearSession();
setIsFirstTimeUser(checkIsFirstTimeUser());
-
- console.log('AuthContext: Logout complete');
};
const value: AuthContextType = {
diff --git a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
index 41d656395..ad5078bd2 100644
--- a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx
@@ -3,9 +3,6 @@
// Replaces ProviderContext with enhanced broker registry support
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef, ReactNode } from 'react';
-import { getWebSocketManager } from '../services/websocket';
-import type { ProviderConfig } from '../services/websocket/types';
-import { ConnectionStatus } from '../services/websocket/types';
import {
BROKER_REGISTRY,
getAllBrokers,
@@ -20,6 +17,7 @@ import {
import { createPaperTradingAdapter } from '../paper-trading';
import type { IExchangeAdapter } from '../brokers/crypto/types';
import type { PaperTradingAdapter } from '../paper-trading/PaperTradingAdapter';
+import type { ProviderConfig, ConnectionStatus } from '../services/websocketBridge';
interface BrokerContextType {
// Active broker
@@ -116,16 +114,19 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
setIsLoading(true);
try {
- const manager = getWebSocketManager();
+
const configs = new Map<string, ProviderConfig>();
// Initialize configs for all available brokers
for (const broker of availableBrokers) {
if (broker.websocket.enabled && broker.websocket.endpoint) {
configs.set(broker.id, {
- provider_name: broker.id,
+ name: broker.id,
+ url: broker.websocket.endpoint,
enabled: true,
- endpoint: broker.websocket.endpoint,
+ reconnect_delay_ms: 5000,
+ max_reconnect_attempts: 10,
+ heartbeat_interval_ms: 30000,
});
}
}
@@ -144,10 +145,10 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
setTradingModeState(savedMode);
}
- // Apply configurations to WebSocket manager
- configs.forEach((config, provider) => {
- manager.setProviderConfig(provider, config);
- });
+ // TODO: Re-implement with new Rust WebSocket backend
+ // configs.forEach((config, provider) => {
+ // manager.setProviderConfig(provider, config);
+ // });
} catch (error) {
console.error('[BrokerContext] Failed to load configurations:', error);
} finally {
@@ -259,42 +260,37 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
console.log(`[BrokerContext] ✓ setPaperAdapter() called`);
// Connect WebSocket AFTER adapters are ready
- const manager = getWebSocketManager();
+
const config = providerConfigs.get(activeBroker);
console.log(`[BrokerContext] WebSocket config for ${activeBroker}:`, config ? 'EXISTS' : 'MISSING');
if (config) {
- console.log(`[BrokerContext] Setting WebSocket config for ${activeBroker}...`);
- manager.setProviderConfig(activeBroker, config);
-
- console.log(`[BrokerContext] Connecting WebSocket for ${activeBroker}...`);
- try {
- await manager.connect(activeBroker);
-
- // Wait for WebSocket to actually OPEN (not just connect call to finish)
- let wsStatus = manager.getStatus(activeBroker);
- let waitCount = 0;
- const maxWait = 20; // 10 seconds max
-
- while (wsStatus !== ConnectionStatus.CONNECTED && waitCount < maxWait) {
- console.log(`[BrokerContext] Waiting for WebSocket... (${waitCount + 1}/${maxWait}) - Status: ${wsStatus}`);
- await new Promise(resolve => setTimeout(resolve, 500));
- wsStatus = manager.getStatus(activeBroker);
- waitCount++;
- }
-
- console.log(`[BrokerContext] ✓ ${activeBroker} WebSocket status: ${wsStatus}`);
- } catch (wsError) {
- console.error(`[BrokerContext] ⚠ WebSocket connection failed:`, wsError);
- console.log(`[BrokerContext] Continuing without WebSocket (real-time updates unavailable)`);
- }
+ console.log(`[BrokerContext] WebSocket config found for ${activeBroker}`);
+ // TODO: Re-implement with new Rust WebSocket backend
+ // manager.setProviderConfig(activeBroker, config);
+ // console.log(`[BrokerContext] Connecting WebSocket for ${activeBroker}...`);
+ // try {
+ // await manager.connect(activeBroker);
+ // let wsStatus = manager.getStatus(activeBroker);
+ // let waitCount = 0;
+ // const maxWait = 20;
+ // while (wsStatus !== ConnectionStatus.CONNECTED && waitCount < maxWait) {
+ // console.log(`[BrokerContext] Waiting for WebSocket... (${waitCount + 1}/${maxWait}) - Status: ${wsStatus}`);
+ // await new Promise(resolve => setTimeout(resolve, 500));
+ // wsStatus = manager.getStatus(activeBroker);
+ // waitCount++;
+ // }
+ // console.log(`[BrokerContext] ✓ ${activeBroker} WebSocket status: ${wsStatus}`);
+ // } catch (wsError) {
+ // console.error(`[BrokerContext] ⚠ WebSocket connection failed:`, wsError);
+ // console.log(`[BrokerContext] Continuing without WebSocket (real-time updates unavailable)`);
+ // }
console.log(`[BrokerContext] ========================================`);
console.log(`[BrokerContext] ${activeBroker} initialization complete!`);
console.log(`[BrokerContext] Real Adapter: ${newRealAdapter.isConnected() ? '✓ CONNECTED' : '✗ NOT CONNECTED'}`);
console.log(`[BrokerContext] Paper Adapter: ${newPaperAdapter.isConnected() ? '✓ CONNECTED' : '✗ NOT CONNECTED'}`);
- console.log(`[BrokerContext] WebSocket: ${manager.getStatus(activeBroker)}`);
console.log(`[BrokerContext] ========================================`);
} else {
console.warn(`[BrokerContext] No WebSocket config found for ${activeBroker}!`);
@@ -383,9 +379,8 @@ export function BrokerProvider({ children }: BrokerProviderProps) {
newConfigs.set(provider, updatedConfig);
- // Update WebSocket manager
- const manager = getWebSocketManager();
- manager.setProviderConfig(provider, updatedConfig);
+ // TODO: Re-implement with new Rust WebSocket backend
+ // manager.setProviderConfig(provider, updatedConfig);
return newConfigs;
});
diff --git a/fincept-terminal-desktop/src/hooks/useDataSource.ts b/fincept-terminal-desktop/src/hooks/useDataSource.ts
index 52e4d70f1..ac321f7d7 100644
--- a/fincept-terminal-desktop/src/hooks/useDataSource.ts
+++ b/fincept-terminal-desktop/src/hooks/useDataSource.ts
@@ -1,265 +1,46 @@
-// Universal Data Source Hook
-// Use this hook to access any data source (WebSocket or REST API) by alias
-
-import { useState, useEffect, useRef } from 'react';
-import { getDataSourceByAlias, getWebSocketTopic, parseDataSourceConfig, WebSocketSourceConfig, RestAPISourceConfig } from '../services/dataSourceRegistry';
-import { DataSource } from '../services/sqliteService';
-import { useWebSocket } from './useWebSocket';
-import { mappingDatabase } from '../components/tabs/data-mapping/services/MappingDatabase';
-import { mappingEngine } from '../components/tabs/data-mapping/engine/MappingEngine';
-
-export interface DataSourceHookResult {
- data: any;
- error: string | null;
- loading: boolean;
- connected: boolean;
- source: DataSource | null;
- refresh: () => Promise<void>;
-}
-
/**
- * Universal hook to access any data source by alias
- * Works with both WebSocket and REST API sources
- *
- * @example
- * ```tsx
- * // WebSocket source
- * const { data, connected } = useDataSource('btc_live');
- *
- * // REST API source
- * const { data, loading, refresh } = useDataSource('sp500_data');
- * ```
+ * useDataSource Hook
+ * React hook for managing data source connections and subscriptions
*/
-export function useDataSource(alias: string, parameters?: Record<string, any>): DataSourceHookResult {
- const [source, setSource] = useState<DataSource | null>(null);
- const [data, setData] = useState<any>(null);
- const [error, setError] = useState<string | null>(null);
- const [loading, setLoading] = useState<boolean>(true);
- const [connected, setConnected] = useState<boolean>(false);
-
- const wsTopicRef = useRef<string | null>(null);
- const refreshIntervalRef = useRef<NodeJS.Timeout | null>(null);
-
- // WebSocket hook (conditionally used)
- const wsResult = useWebSocket(
- source?.type === 'websocket' && source?.enabled ? (wsTopicRef.current || '') : null,
- null,
- {
- autoSubscribe: source?.type === 'websocket' && source?.enabled === true
- }
- );
-
- // Load data source on mount or alias change
- useEffect(() => {
- loadDataSource();
-
- return () => {
- // Cleanup
- if (refreshIntervalRef.current) {
- clearInterval(refreshIntervalRef.current);
- }
- };
- }, [alias]);
-
- // Handle WebSocket data updates
- useEffect(() => {
- if (source?.type === 'websocket' && wsResult.message) {
- setData(wsResult.message.data);
- setConnected(wsResult.status === 'connected');
- setError(null);
- setLoading(false);
- }
- }, [wsResult.message, wsResult.status, source?.type]);
-
- async function loadDataSource() {
- try {
- setLoading(true);
- setError(null);
-
- // Fetch data source from database
- const dataSource = await getDataSourceByAlias(alias);
-
- if (!dataSource) {
- setError(`Data source '${alias}' not found`);
- setLoading(false);
- return;
- }
-
- if (!dataSource.enabled) {
- setError(`Data source '${alias}' is disabled`);
- setLoading(false);
- return;
- }
-
- setSource(dataSource);
-
- // Handle based on type
- if (dataSource.type === 'websocket') {
- await handleWebSocketSource(dataSource);
- } else if (dataSource.type === 'rest_api') {
- await handleRestAPISource(dataSource);
- }
- } catch (err) {
- const errorMsg = err instanceof Error ? err.message : String(err);
- setError(errorMsg);
- setLoading(false);
- }
- }
-
- async function handleWebSocketSource(dataSource: DataSource) {
- try {
- const topic = getWebSocketTopic(dataSource);
-
- if (!topic) {
- throw new Error('Invalid WebSocket configuration');
- }
-
- // Ensure provider config is set in WebSocket Manager
- const config = parseDataSourceConfig(dataSource) as WebSocketSourceConfig;
- if (config) {
- const { getWebSocketManager } = await import('../services/websocket');
- const wsManager = getWebSocketManager();
-
- const existingConfig = wsManager.getProviderConfig(config.provider);
- if (!existingConfig) {
- wsManager.setProviderConfig(config.provider, {
- provider_name: config.provider,
- enabled: true,
- api_key: config.params?.api_key,
- api_secret: config.params?.api_secret,
- endpoint: config.params?.endpoint
- });
- console.log(`[useDataSource] Provider config set for: ${config.provider}`);
- }
- }
-
- wsTopicRef.current = topic;
- setLoading(false);
- // Data will come through wsResult
- } catch (err) {
- const errorMsg = err instanceof Error ? err.message : String(err);
- setError(errorMsg);
- setLoading(false);
- }
- }
-
- async function handleRestAPISource(dataSource: DataSource) {
- try {
- const config = parseDataSourceConfig(dataSource) as RestAPISourceConfig;
- if (!config || !config.mappingId) {
- throw new Error('Invalid REST API configuration');
- }
+import { useState, useEffect, useCallback } from 'react';
+import { getAllDataSources } from '@/services/dataSourceRegistry';
+import { DataSource } from '@/services/sqliteService';
- // Load mapping from database
- const mapping = await mappingDatabase.getMapping(config.mappingId);
-
- if (!mapping) {
- throw new Error(`Mapping '${config.mappingId}' not found`);
- }
-
- // Execute mapping
- const result = await mappingEngine.execute({
- mapping,
- parameters: parameters || config.parameters
- });
-
- if (result.success) {
- setData(result.data);
- setConnected(true);
- setError(null);
- } else {
- throw new Error(result.errors?.join(', ') || 'Mapping execution failed');
- }
-
- setLoading(false);
- } catch (err) {
- const errorMsg = err instanceof Error ? err.message : String(err);
- setError(errorMsg);
- setLoading(false);
- }
- }
-
- async function refresh() {
- if (!source) return;
-
- if (source.type === 'rest_api') {
- await handleRestAPISource(source);
- }
- // WebSocket sources refresh automatically
- }
-
- return {
- data,
- error,
- loading,
- connected,
- source,
- refresh
- };
+interface UseDataSourceReturn {
+ dataSources: DataSource[];
+ loading: boolean;
+ error: string | null;
+ refreshDataSources: () => Promise<void>;
}
-/**
- * Hook to get all available data sources
- */
-export function useDataSources() {
- const [sources, setSources] = useState<DataSource[]>([]);
+export function useDataSource(): UseDataSourceReturn {
+ const [dataSources, setDataSources] = useState<DataSource[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
- useEffect(() => {
- loadSources();
- }, []);
-
- async function loadSources() {
+ const refreshDataSources = useCallback(async () => {
try {
setLoading(true);
- const { sqliteService } = await import('../services/sqliteService');
- const allSources = await sqliteService.getAllDataSources();
- setSources(allSources);
setError(null);
+ const sources = await getAllDataSources();
+ setDataSources(sources);
} catch (err) {
- setError(err instanceof Error ? err.message : String(err));
+ setError(err instanceof Error ? err.message : 'Failed to load data sources');
+ console.error('Error loading data sources:', err);
} finally {
setLoading(false);
}
- }
-
- return {
- sources,
- loading,
- error,
- reload: loadSources
- };
-}
-
-/**
- * Hook to get data sources by type
- */
-export function useDataSourcesByType(type: 'websocket' | 'rest_api') {
- const [sources, setSources] = useState<DataSource[]>([]);
- const [loading, setLoading] = useState(true);
+ }, []);
useEffect(() => {
- loadSourcesByType();
- }, [type]);
-
- async function loadSourcesByType() {
- try {
- setLoading(true);
- const { sqliteService } = await import('../services/sqliteService');
- const filtered = await sqliteService.getDataSourcesByType(type);
- setSources(filtered);
- } catch (err) {
- console.error('Failed to load data sources:', err);
- } finally {
- setLoading(false);
- }
- }
+ refreshDataSources();
+ }, [refreshDataSources]);
return {
- sources,
+ dataSources,
loading,
- reload: loadSourcesByType
+ error,
+ refreshDataSources,
};
}
diff --git a/fincept-terminal-desktop/src/hooks/useRustWebSocket.ts b/fincept-terminal-desktop/src/hooks/useRustWebSocket.ts
new file mode 100644
index 000000000..d860f0ee6
--- /dev/null
+++ b/fincept-terminal-desktop/src/hooks/useRustWebSocket.ts
@@ -0,0 +1,382 @@
+// React hooks for Rust WebSocket system
+
+import { useEffect, useState, useCallback, useRef } from 'react';
+import {
+ websocketBridge,
+ TickerData,
+ OrderBookData,
+ TradeData,
+ CandleData,
+ StatusData,
+ ConnectionMetrics,
+} from '@/services/websocketBridge';
+
+// ============================================================================
+// TICKER HOOK
+// ============================================================================
+
+export function useRustTicker(provider: string, symbol: string, autoConnect = true) {
+ const [data, setData] = useState<TickerData | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const subscribed = useRef(false);
+
+ useEffect(() => {
+ let mounted = true;
+ let unlisten: (() => void) | null = null;
+
+ const subscribe = async () => {
+ try {
+ // Subscribe to ticker channel
+ if (!subscribed.current) {
+ await websocketBridge.subscribe(provider, symbol, 'ticker');
+ subscribed.current = true;
+ }
+
+ // Listen to ticker events
+ unlisten = await websocketBridge.onTicker((tickerData) => {
+ if (mounted && tickerData.provider === provider && tickerData.symbol === symbol) {
+ setData(tickerData);
+ }
+ });
+ } catch (err) {
+ if (mounted) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }
+ };
+
+ if (autoConnect && provider && symbol) {
+ subscribe();
+ }
+
+ return () => {
+ mounted = false;
+ if (unlisten) {
+ unlisten();
+ }
+ if (subscribed.current) {
+ websocketBridge.unsubscribe(provider, symbol, 'ticker').catch(console.error);
+ subscribed.current = false;
+ }
+ };
+ }, [provider, symbol, autoConnect]);
+
+ return { data, error };
+}
+
+// ============================================================================
+// ORDER BOOK HOOK
+// ============================================================================
+
+export function useRustOrderBook(
+ provider: string,
+ symbol: string,
+ depth: number = 25,
+ autoConnect = true
+) {
+ const [data, setData] = useState<OrderBookData | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const subscribed = useRef(false);
+
+ useEffect(() => {
+ let mounted = true;
+ let unlisten: (() => void) | null = null;
+
+ const subscribe = async () => {
+ try {
+ // Subscribe to book channel with depth parameter
+ if (!subscribed.current) {
+ await websocketBridge.subscribe(provider, symbol, 'book', { depth });
+ subscribed.current = true;
+ }
+
+ // Listen to orderbook events
+ unlisten = await websocketBridge.onOrderBook((bookData) => {
+ if (mounted && bookData.provider === provider && bookData.symbol === symbol) {
+ setData(bookData);
+ }
+ });
+ } catch (err) {
+ if (mounted) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }
+ };
+
+ if (autoConnect && provider && symbol) {
+ subscribe();
+ }
+
+ return () => {
+ mounted = false;
+ if (unlisten) {
+ unlisten();
+ }
+ if (subscribed.current) {
+ websocketBridge.unsubscribe(provider, symbol, 'book').catch(console.error);
+ subscribed.current = false;
+ }
+ };
+ }, [provider, symbol, depth, autoConnect]);
+
+ return { data, error };
+}
+
+// ============================================================================
+// TRADES HOOK
+// ============================================================================
+
+export function useRustTrades(provider: string, symbol: string, maxTrades = 50, autoConnect = true) {
+ const [trades, setTrades] = useState<TradeData[]>([]);
+ const [error, setError] = useState<string | null>(null);
+ const subscribed = useRef(false);
+
+ useEffect(() => {
+ let mounted = true;
+ let unlisten: (() => void) | null = null;
+
+ const subscribe = async () => {
+ try {
+ // Subscribe to trade channel
+ if (!subscribed.current) {
+ await websocketBridge.subscribe(provider, symbol, 'trade');
+ subscribed.current = true;
+ }
+
+ // Listen to trade events
+ unlisten = await websocketBridge.onTrade((tradeData) => {
+ if (mounted && tradeData.provider === provider && tradeData.symbol === symbol) {
+ setTrades((prev) => {
+ const updated = [tradeData, ...prev];
+ return updated.slice(0, maxTrades);
+ });
+ }
+ });
+ } catch (err) {
+ if (mounted) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }
+ };
+
+ if (autoConnect && provider && symbol) {
+ subscribe();
+ }
+
+ return () => {
+ mounted = false;
+ if (unlisten) {
+ unlisten();
+ }
+ if (subscribed.current) {
+ websocketBridge.unsubscribe(provider, symbol, 'trade').catch(console.error);
+ subscribed.current = false;
+ }
+ };
+ }, [provider, symbol, maxTrades, autoConnect]);
+
+ return { trades, error };
+}
+
+// ============================================================================
+// CANDLE/OHLC HOOK
+// ============================================================================
+
+export function useRustCandles(
+ provider: string,
+ symbol: string,
+ interval: string = '1m',
+ autoConnect = true
+) {
+ const [candles, setCandles] = useState<CandleData[]>([]);
+ const [latestCandle, setLatestCandle] = useState<CandleData | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const subscribed = useRef(false);
+
+ useEffect(() => {
+ let mounted = true;
+ let unlisten: (() => void) | null = null;
+
+ const subscribe = async () => {
+ try {
+ // Subscribe to candle channel
+ if (!subscribed.current) {
+ await websocketBridge.subscribe(provider, symbol, 'ohlc', { interval });
+ subscribed.current = true;
+ }
+
+ // Listen to candle events
+ unlisten = await websocketBridge.onCandle((candleData) => {
+ if (
+ mounted &&
+ candleData.provider === provider &&
+ candleData.symbol === symbol &&
+ candleData.interval === interval
+ ) {
+ setLatestCandle(candleData);
+ setCandles((prev) => {
+ // Update existing candle or add new one
+ const existingIndex = prev.findIndex((c) => c.timestamp === candleData.timestamp);
+ if (existingIndex >= 0) {
+ const updated = [...prev];
+ updated[existingIndex] = candleData;
+ return updated;
+ } else {
+ return [...prev, candleData].sort((a, b) => a.timestamp - b.timestamp);
+ }
+ });
+ }
+ });
+ } catch (err) {
+ if (mounted) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }
+ };
+
+ if (autoConnect && provider && symbol) {
+ subscribe();
+ }
+
+ return () => {
+ mounted = false;
+ if (unlisten) {
+ unlisten();
+ }
+ if (subscribed.current) {
+ websocketBridge.unsubscribe(provider, symbol, 'ohlc').catch(console.error);
+ subscribed.current = false;
+ }
+ };
+ }, [provider, symbol, interval, autoConnect]);
+
+ return { candles, latestCandle, error };
+}
+
+// ============================================================================
+// CONNECTION STATUS HOOK
+// ============================================================================
+
+export function useConnectionStatus(provider: string) {
+ const [status, setStatus] = useState<StatusData | null>(null);
+ const [metrics, setMetrics] = useState<ConnectionMetrics | null>(null);
+
+ useEffect(() => {
+ let mounted = true;
+ let unlisten: (() => void) | null = null;
+ let intervalId: NodeJS.Timeout | null = null;
+
+ const setup = async () => {
+ // Listen to status events
+ unlisten = await websocketBridge.onStatus((statusData) => {
+ if (mounted && statusData.provider === provider) {
+ setStatus(statusData);
+ }
+ });
+
+ // Poll metrics every 5 seconds
+ const fetchMetrics = async () => {
+ if (mounted) {
+ try {
+ const m = await websocketBridge.getMetrics(provider);
+ if (m) {
+ setMetrics(m);
+ }
+ } catch (err) {
+ console.error('Failed to fetch metrics:', err);
+ }
+ }
+ };
+
+ await fetchMetrics();
+ intervalId = setInterval(fetchMetrics, 5000);
+ };
+
+ if (provider) {
+ setup();
+ }
+
+ return () => {
+ mounted = false;
+ if (unlisten) {
+ unlisten();
+ }
+ if (intervalId) {
+ clearInterval(intervalId);
+ }
+ };
+ }, [provider]);
+
+ return { status, metrics };
+}
+
+// ============================================================================
+// MULTI-PROVIDER HOOK (for arbitrage, etc.)
+// ============================================================================
+
+export function useMultiProviderTicker(providers: string[], symbol: string) {
+ const [prices, setPrices] = useState<Map<string, TickerData>>(new Map());
+ const [error, setError] = useState<string | null>(null);
+ const subscribed = useRef<Set<string>>(new Set());
+
+ useEffect(() => {
+ let mounted = true;
+ let unlisten: (() => void) | null = null;
+
+ const subscribe = async () => {
+ try {
+ // Subscribe to all providers
+ for (const provider of providers) {
+ if (!subscribed.current.has(provider)) {
+ await websocketBridge.subscribe(provider, symbol, 'ticker');
+ subscribed.current.add(provider);
+ }
+ }
+
+ // Listen to ticker events from all providers
+ unlisten = await websocketBridge.onTicker((tickerData) => {
+ if (mounted && providers.includes(tickerData.provider) && tickerData.symbol === symbol) {
+ setPrices((prev) => {
+ const updated = new Map(prev);
+ updated.set(tickerData.provider, tickerData);
+ return updated;
+ });
+ }
+ });
+ } catch (err) {
+ if (mounted) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ }
+ };
+
+ if (providers.length > 0 && symbol) {
+ subscribe();
+ }
+
+ return () => {
+ mounted = false;
+ if (unlisten) {
+ unlisten();
+ }
+ for (const provider of subscribed.current) {
+ websocketBridge.unsubscribe(provider, symbol, 'ticker').catch(console.error);
+ }
+ subscribed.current.clear();
+ };
+ }, [providers.join(','), symbol]);
+
+ // Calculate arbitrage spread
+ const spread = useCallback(() => {
+ if (prices.size < 2) return null;
+
+ const priceValues = Array.from(prices.values()).map((t) => t.price);
+ const min = Math.min(...priceValues);
+ const max = Math.max(...priceValues);
+ const spreadPercent = ((max - min) / min) * 100;
+
+ return { min, max, spreadPercent };
+ }, [prices]);
+
+ return { prices, spread: spread(), error };
+}
diff --git a/fincept-terminal-desktop/src/hooks/useWebSocket.ts b/fincept-terminal-desktop/src/hooks/useWebSocket.ts
deleted file mode 100644
index 52cdacecb..000000000
--- a/fincept-terminal-desktop/src/hooks/useWebSocket.ts
+++ /dev/null
@@ -1,487 +0,0 @@
-// File: src/hooks/useWebSocket.ts
-// React hook for WebSocket subscriptions
-
-import { useState, useEffect, useCallback, useRef } from 'react';
-import {
- getWebSocketManager,
- Subscription,
- NormalizedMessage,
- ConnectionStatus,
- MessageCallback
-} from '@/services/websocket';
-
-/**
- * Hook options
- */
-export interface UseWebSocketOptions {
- /**
- * Auto-connect on mount (default: true)
- */
- autoConnect?: boolean;
-
- /**
- * Auto-subscribe on mount (default: true)
- */
- autoSubscribe?: boolean;
-
- /**
- * Optional subscription parameters
- */
- params?: Record<string, any>;
-
- /**
- * Custom error handler
- */
- onError?: (error: Error) => void;
-
- /**
- * Connection status change handler
- */
- onStatusChange?: (status: ConnectionStatus) => void;
-}
-
-/**
- * Hook return value
- */
-export interface UseWebSocketReturn {
- /**
- * Latest message received
- */
- message: NormalizedMessage | null;
-
- /**
- * All messages received (up to maxMessages)
- */
- messages: NormalizedMessage[];
-
- /**
- * Connection status
- */
- status: ConnectionStatus | null;
-
- /**
- * Loading state (connecting or subscribing)
- */
- isLoading: boolean;
-
- /**
- * Error state
- */
- error: Error | null;
-
- /**
- * Subscribe to topic manually
- */
- subscribe: (topic: string, params?: Record<string, any>) => Promise<void>;
-
- /**
- * Unsubscribe from current topic
- */
- unsubscribe: () => void;
-
- /**
- * Send message (for two-way communication if supported)
- */
- send: (data: any) => Promise<void>;
-
- /**
- * Reconnect to provider
- */
- reconnect: () => Promise<void>;
-
- /**
- * Clear message history
- */
- clearMessages: () => void;
-}
-
-/**
- * useWebSocket - React hook for WebSocket subscriptions
- *
- * @param topic - Topic to subscribe to (format: "provider.channel.symbol")
- * @param callback - Optional message callback (alternative to using message state)
- * @param options - Hook options
- *
- * @example
- * ```typescript
- * // Simple usage with state
- * const { message, status } = useWebSocket('kraken.ticker.BTC/USD');
- *
- * // With callback
- * useWebSocket('kraken.ticker.BTC/USD', (msg) => {
- * console.log('Price:', msg.data.last);
- * });
- *
- * // Manual subscription control
- * const { subscribe, unsubscribe, messages } = useWebSocket(
- * 'kraken.ticker.BTC/USD',
- * null,
- * { autoSubscribe: false }
- * );
- * ```
- */
-export function useWebSocket(
- topic: string | null,
- callback?: MessageCallback | null,
- options: UseWebSocketOptions = {}
-): UseWebSocketReturn {
- const {
- autoConnect = true,
- autoSubscribe = true,
- params,
- onError,
- onStatusChange
- } = options;
-
- // State
- const [message, setMessage] = useState<NormalizedMessage | null>(null);
- const [messages, setMessages] = useState<NormalizedMessage[]>([]);
- const [status, setStatus] = useState<ConnectionStatus | null>(null);
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState<Error | null>(null);
-
- // Refs
- const subscriptionRef = useRef<Subscription | null>(null);
- const callbackRef = useRef<MessageCallback | null>(callback || null);
- const maxMessages = 100; // Keep last 100 messages
-
- // Update callback ref when it changes
- useEffect(() => {
- callbackRef.current = callback || null;
- }, [callback]);
-
- /**
- * Internal message handler
- */
- const handleMessage = useCallback((msg: NormalizedMessage) => {
- // Only log chart/candle messages
- if (msg.channel === 'ohlc' || msg.type === 'candle') {
- console.log(`[useWebSocket] 📊 Chart message:`, {
- provider: msg.provider,
- channel: msg.channel,
- type: msg.type,
- symbol: msg.symbol,
- dataKeys: Object.keys(msg.data || {})
- });
- }
-
- setMessage(msg);
- setMessages(prev => {
- const updated = [...prev, msg];
- return updated.slice(-maxMessages);
- });
-
- // Call user callback if provided
- if (callbackRef.current) {
- callbackRef.current(msg);
- }
- }, []);
-
- /**
- * Subscribe to topic
- */
- const subscribe = useCallback(async (
- subscribeTopic: string,
- subscribeParams?: Record<string, any>
- ) => {
- console.log(`[useWebSocket] 📡 Attempting to subscribe to: ${subscribeTopic}`);
- console.log(`[useWebSocket] Params:`, subscribeParams || params);
-
- try {
- setIsLoading(true);
- setError(null);
-
- const manager = getWebSocketManager();
-
- // Parse provider from topic
- const provider = subscribeTopic.split('.')[0];
- console.log(`[useWebSocket] Provider: ${provider}`);
-
- // Check WebSocket status BEFORE subscribing
- const wsStatus = manager.getStatus(provider);
- console.log(`[useWebSocket] WebSocket status for ${provider}: ${wsStatus}`);
-
- // Get or create provider config if needed
- // Note: Config should be set via setProviderConfig before subscribing
- // This is handled in SettingsTab
-
- // Subscribe
- console.log(`[useWebSocket] Calling manager.subscribe()...`);
- const sub = await manager.subscribe(
- subscribeTopic,
- handleMessage,
- subscribeParams || params
- );
-
- subscriptionRef.current = sub;
- console.log(`[useWebSocket] ✓ Subscription created: ${sub.id}`);
-
- // Update status
- const providerStatus = manager.getStatus(provider);
- setStatus(providerStatus);
- console.log(`[useWebSocket] Final status: ${providerStatus}`);
-
- if (onStatusChange && providerStatus) {
- onStatusChange(providerStatus);
- }
- } catch (err) {
- const error = err instanceof Error ? err : new Error(String(err));
- setError(error);
-
- console.error(`[useWebSocket] ✗ Subscribe FAILED for ${subscribeTopic}:`, error.message);
-
- if (onError) {
- onError(error);
- }
-
- // Only log errors that aren't connection-related (those are logged elsewhere)
- if (!error.message.includes('not connected') && !error.message.includes('not open')) {
- console.error('[useWebSocket] Subscribe error:', error);
- }
- } finally {
- setIsLoading(false);
- }
- }, [handleMessage, params, onError, onStatusChange]);
-
- /**
- * Unsubscribe
- */
- const unsubscribe = useCallback(() => {
- if (subscriptionRef.current) {
- subscriptionRef.current.unsubscribe();
- subscriptionRef.current = null;
- setStatus(ConnectionStatus.DISCONNECTED);
- }
- }, []);
-
- /**
- * Send message
- */
- const send = useCallback(async (data: any) => {
- if (!topic) {
- throw new Error('No topic specified');
- }
-
- const manager = getWebSocketManager();
- const provider = topic.split('.')[0];
- const adapter = (manager as any).registry.get(provider);
-
- if (!adapter) {
- throw new Error(`Provider ${provider} not connected`);
- }
-
- await adapter.send(data);
- }, [topic]);
-
- /**
- * Reconnect
- */
- const reconnect = useCallback(async () => {
- if (!topic) {
- throw new Error('No topic specified');
- }
-
- try {
- setIsLoading(true);
- setError(null);
-
- const manager = getWebSocketManager();
- const provider = topic.split('.')[0];
-
- await manager.reconnect(provider);
-
- // Resubscribe
- if (subscriptionRef.current) {
- unsubscribe();
- await subscribe(topic, params);
- }
- } catch (err) {
- const error = err instanceof Error ? err : new Error(String(err));
- setError(error);
-
- if (onError) {
- onError(error);
- }
- } finally {
- setIsLoading(false);
- }
- }, [topic, params, onError, subscribe, unsubscribe]);
-
- /**
- * Clear messages
- */
- const clearMessages = useCallback(() => {
- setMessages([]);
- setMessage(null);
- }, []);
-
- /**
- * Auto-subscribe on mount if enabled
- */
- useEffect(() => {
- let isMounted = true;
-
- if (topic && autoSubscribe && autoConnect && isMounted) {
- subscribe(topic, params);
- }
-
- // Cleanup on unmount
- return () => {
- isMounted = false;
- unsubscribe();
- };
- }, [topic, autoSubscribe, autoConnect]); // Intentionally limited dependencies
-
- /**
- * Monitor connection status and resubscribe if connection is restored
- */
- useEffect(() => {
- if (!topic || !autoSubscribe) return;
-
- const manager = getWebSocketManager();
- const provider = topic.split('.')[0];
- let isMounted = true;
- let isResubscribing = false;
- let consecutiveFailures = 0;
-
- const checkInterval = setInterval(async () => {
- if (!isMounted || isResubscribing) return; // Guard against unmounted component or concurrent resubscribes
-
- const providerStatus = manager.getStatus(provider);
-
- // If connected but no active subscription, resubscribe
- if (providerStatus === ConnectionStatus.CONNECTED && !subscriptionRef.current) {
- // Exponential backoff if we're having repeated failures
- if (consecutiveFailures > 3) {
- console.debug(`[useWebSocket] Too many consecutive failures for ${topic}, pausing auto-resubscribe`);
- return;
- }
-
- isResubscribing = true;
- try {
- console.log(`[useWebSocket] Auto-resubscribing to ${topic} after reconnection`);
- await subscribe(topic, params);
- consecutiveFailures = 0; // Reset on success
- } catch (error) {
- consecutiveFailures++;
- // Silently fail - subscription will retry on next interval
- const errorMsg = error instanceof Error ? error.message : String(error);
- if (!errorMsg.includes('not connected') && !errorMsg.includes('not open')) {
- console.debug(`[useWebSocket] Auto-resubscribe failed (attempt ${consecutiveFailures}):`, error);
- }
- } finally {
- isResubscribing = false;
- }
- } else if (subscriptionRef.current) {
- // Reset failure counter when subscription is active
- consecutiveFailures = 0;
- }
- }, 5000); // Increased to 5 seconds to reduce noise
-
- return () => {
- isMounted = false;
- clearInterval(checkInterval);
- };
- }, [topic, autoSubscribe, params, subscribe]);
-
- return {
- message,
- messages,
- status,
- isLoading,
- error,
- subscribe,
- unsubscribe,
- send,
- reconnect,
- clearMessages
- };
-}
-
-/**
- * useWebSocketManager - Hook for accessing WebSocketManager directly
- */
-export function useWebSocketManager() {
- const manager = getWebSocketManager();
- const [stats, setStats] = useState(manager.getStats());
- const [statuses, setStatuses] = useState(manager.getAllStatuses());
- const [metrics, setMetrics] = useState(manager.getAllMetrics());
-
- useEffect(() => {
- let isMounted = true;
-
- // Update stats, statuses, and metrics periodically
- const interval = setInterval(() => {
- if (!isMounted) return; // Guard against unmounted component
-
- setStats(manager.getStats());
- setStatuses(manager.getAllStatuses());
- setMetrics(manager.getAllMetrics());
- }, 1000);
-
- return () => {
- isMounted = false;
- clearInterval(interval);
- };
- }, [manager]);
-
- return {
- manager,
- stats,
- statuses,
- metrics
- };
-}
-
-/**
- * useWebSocketConnection - Hook for managing provider connection
- */
-export function useWebSocketConnection(provider: string) {
- const manager = getWebSocketManager();
- const [status, setStatus] = useState<ConnectionStatus | null>(
- manager.getStatus(provider)
- );
- const [metrics, setMetrics] = useState(manager.getMetrics(provider));
-
- useEffect(() => {
- let isMounted = true;
-
- // Update status and metrics periodically
- const interval = setInterval(() => {
- if (!isMounted) return; // Guard against unmounted component
-
- setStatus(manager.getStatus(provider));
- setMetrics(manager.getMetrics(provider));
- }, 1000);
-
- return () => {
- isMounted = false;
- clearInterval(interval);
- };
- }, [manager, provider]);
-
- const connect = useCallback(async () => {
- await manager.connect(provider);
- }, [manager, provider]);
-
- const disconnect = useCallback(async () => {
- await manager.disconnect(provider);
- }, [manager, provider]);
-
- const reconnect = useCallback(async () => {
- await manager.reconnect(provider);
- }, [manager, provider]);
-
- const ping = useCallback(async () => {
- return manager.ping(provider);
- }, [manager, provider]);
-
- return {
- status,
- metrics,
- connect,
- disconnect,
- reconnect,
- ping
- };
-}
diff --git a/fincept-terminal-desktop/src/nodes/core/Code.node.ts b/fincept-terminal-desktop/src/nodes/core/Code.node.ts
new file mode 100644
index 000000000..678b1a1bc
--- /dev/null
+++ b/fincept-terminal-desktop/src/nodes/core/Code.node.ts
@@ -0,0 +1,250 @@
+/**
+ * Code Node
+ * Execute custom JavaScript code to transform data
+ *
+ * Use cases:
+ * - Custom calculations
+ * - Complex data transformations
+ * - Financial formulas
+ * - Custom algorithms
+ */
+
+import {
+ INodeType,
+ INodeTypeDescription,
+ IExecuteFunctions,
+ NodeOutput,
+ NodeConnectionType,
+ NodePropertyType,
+ IDataObject,
+ INodeExecutionData,
+} from '../../services/nodeSystem/types';
+
+export class CodeNode implements INodeType {
+ description: INodeTypeDescription = {
+ displayName: 'Code',
+ name: 'code',
+ icon: 'fa:code',
+ iconColor: '#8b5cf6',
+ group: ['transform'],
+ version: 1,
+ description: 'Execute custom JavaScript code to transform data',
+ subtitle: 'Run JavaScript Code',
+ defaults: {
+ name: 'Code',
+ color: '#8b5cf6',
+ },
+ inputs: [NodeConnectionType.Main],
+ outputs: [NodeConnectionType.Main],
+ properties: [
+ {
+ displayName: 'Mode',
+ name: 'mode',
+ type: NodePropertyType.Options,
+ noDataExpression: true,
+ options: [
+ {
+ name: 'Run Once for All Items',
+ value: 'runOnceForAllItems',
+ description: 'Execute code once with all items available',
+ },
+ {
+ name: 'Run Once for Each Item',
+ value: 'runOnceForEachItem',
+ description: 'Execute code separately for each item',
+ },
+ ],
+ default: 'runOnceForEachItem',
+ },
+ {
+ displayName: 'JavaScript Code',
+ name: 'jsCode',
+ type: NodePropertyType.String,
+ typeOptions: {
+ editor: 'code',
+ rows: 15,
+ },
+ default: `// Access input data
+// For "Run Once for Each Item": use $input.item
+// For "Run Once for All Items": use $input.all()
+
+// Example 1: Calculate percentage change
+const item = $input.item.json;
+const percentChange = ((item.close - item.open) / item.open) * 100;
+
+return {
+ ...item,
+ percentChange: percentChange.toFixed(2)
+};
+
+// Example 2: Filter and transform
+// const items = $input.all();
+// return items
+// .filter(item => item.json.price > 100)
+// .map(item => ({
+// ...item.json,
+// priceCategory: 'premium'
+// }));`,
+ description: 'JavaScript code to execute. Return the transformed data.',
+ required: true,
+ },
+ {
+ displayName: 'Options',
+ name: 'options',
+ type: NodePropertyType.Collection,
+ placeholder: 'Add Option',
+ default: [],
+ options: [
+ {
+ displayName: 'Continue On Fail',
+ name: 'continueOnFail',
+ type: NodePropertyType.Boolean,
+ default: false,
+ description:
+ 'Whether to continue execution if the code throws an error',
+ },
+ ],
+ },
+ ],
+ };
+
+ async execute(this: IExecuteFunctions): Promise<NodeOutput> {
+ const items = this.getInputData();
+ const mode = this.getNodeParameter('mode', 0) as string;
+ const jsCode = this.getNodeParameter('jsCode', 0) as string;
+ const options = this.getNodeParameter('options', 0, {}) as IDataObject;
+ const continueOnFail = options.continueOnFail || false;
+
+ const returnData: INodeExecutionData[] = [];
+
+ try {
+ if (mode === 'runOnceForAllItems') {
+ // Execute code once with all items
+ const result = await executeCodeForAllItems(jsCode, items);
+ returnData.push(...result);
+ } else {
+ // Execute code for each item
+ for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
+ try {
+ const result = await executeCodeForItem(jsCode, items[itemIndex], itemIndex);
+ if (Array.isArray(result)) {
+ returnData.push(...result);
+ } else if (result !== null && result !== undefined) {
+ returnData.push(
+ typeof result === 'object' && 'json' in result
+ ? (result as INodeExecutionData)
+ : { json: result as IDataObject }
+ );
+ }
+ } catch (error: any) {
+ if (continueOnFail) {
+ returnData.push({
+ json: {
+ error: error.message,
+ itemIndex,
+ },
+ });
+ } else {
+ throw error;
+ }
+ }
+ }
+ }
+ } catch (error: any) {
+ if (continueOnFail) {
+ returnData.push({
+ json: {
+ error: error.message,
+ },
+ });
+ } else {
+ throw error;
+ }
+ }
+
+ return [returnData];
+ }
+}
+
+/**
+ * Execute code for a single item
+ */
+async function executeCodeForItem(
+ code: string,
+ item: INodeExecutionData,
+ itemIndex: number
+): Promise<any> {
+ // Create execution context
+ const $input = {
+ item,
+ index: itemIndex,
+ first: itemIndex === 0,
+ last: false, // Will be set correctly in actual implementation
+ };
+
+ // Helper functions
+ const helpers = {
+ // Add helper functions here
+ getWorkflowStaticData: () => ({}),
+ };
+
+ // Execute code in isolated context
+ // Using Function constructor for code execution
+ // This is a simplified version - production should use vm module or similar
+ const executeFunction = new Function('$input', 'helpers', `
+ 'use strict';
+ ${code}
+ `);
+
+ const result = executeFunction($input, helpers);
+ return result;
+}
+
+/**
+ * Execute code for all items
+ */
+async function executeCodeForAllItems(
+ code: string,
+ items: INodeExecutionData[]
+): Promise<INodeExecutionData[]> {
+ // Create execution context
+ const $input = {
+ all: () => items,
+ first: () => items[0],
+ last: () => items[items.length - 1],
+ item: items[0], // For backward compatibility
+ };
+
+ // Helper functions
+ const helpers = {
+ getWorkflowStaticData: () => ({}),
+ };
+
+ // Execute code
+ const executeFunction = new Function('$input', 'helpers', `
+ 'use strict';
+ ${code}
+ `);
+
+ const result = executeFunction($input, helpers);
+
+ // Ensure result is array of items
+ if (!result) {
+ return [];
+ }
+
+ if (Array.isArray(result)) {
+ return result.map((item) =>
+ typeof item === 'object' && 'json' in item
+ ? (item as INodeExecutionData)
+ : { json: item as IDataObject }
+ );
+ }
+
+ // Single item returned
+ return [
+ typeof result === 'object' && 'json' in result
+ ? (result as INodeExecutionData)
+ : { json: result as IDataObject },
+ ];
+}
diff --git a/fincept-terminal-desktop/src/nodes/core/Filter.node.ts b/fincept-terminal-desktop/src/nodes/core/Filter.node.ts
new file mode 100644
index 000000000..edc5f53df
--- /dev/null
+++ b/fincept-terminal-desktop/src/nodes/core/Filter.node.ts
@@ -0,0 +1,283 @@
+/**
+ * Filter Node
+ * Remove items that don't match specified conditions
+ *
+ * Use cases:
+ * - Filter stocks by price range
+ * - Remove rows with missing data
+ * - Select only profitable trades
+ * - Filter news by sentiment
+ */
+
+import {
+ INodeType,
+ INodeTypeDescription,
+ IExecuteFunctions,
+ NodeOutput,
+ NodeConnectionType,
+ NodePropertyType,
+ IDataObject,
+} from '../../services/nodeSystem/types';
+
+export class FilterNode implements INodeType {
+ description: INodeTypeDescription = {
+ displayName: 'Filter',
+ name: 'filter',
+ icon: 'fa:filter',
+ iconColor: '#60a5fa',
+ group: ['transform'],
+ version: 1,
+ description: 'Remove items that do not match specified conditions',
+ subtitle: '={{$parameter["operation"]}}',
+ defaults: {
+ name: 'Filter',
+ color: '#60a5fa',
+ },
+ inputs: [NodeConnectionType.Main],
+ outputs: [NodeConnectionType.Main],
+ properties: [
+ {
+ displayName: 'Operation',
+ name: 'operation',
+ type: NodePropertyType.Options,
+ noDataExpression: true,
+ options: [
+ {
+ name: 'Keep Matching Items',
+ value: 'keep',
+ description: 'Keep only items that match the conditions',
+ },
+ {
+ name: 'Remove Matching Items',
+ value: 'remove',
+ description: 'Remove items that match the conditions',
+ },
+ ],
+ default: 'keep',
+ },
+ {
+ displayName: 'Conditions',
+ name: 'conditions',
+ placeholder: 'Add Condition',
+ type: NodePropertyType.Collection,
+ typeOptions: {
+ multipleValues: true,
+ },
+ default: [],
+ options: [
+ {
+ name: 'condition',
+ description: 'Condition',
+ values: [
+ {
+ displayName: 'Field',
+ name: 'field',
+ type: NodePropertyType.String,
+ default: '',
+ placeholder: 'e.g., price',
+ description: 'The field name to check',
+ required: true,
+ },
+ {
+ displayName: 'Operation',
+ name: 'operator',
+ type: NodePropertyType.Options,
+ options: [
+ {
+ name: 'Equal',
+ value: 'equal',
+ },
+ {
+ name: 'Not Equal',
+ value: 'notEqual',
+ },
+ {
+ name: 'Greater Than',
+ value: 'greaterThan',
+ },
+ {
+ name: 'Greater Than or Equal',
+ value: 'greaterThanOrEqual',
+ },
+ {
+ name: 'Less Than',
+ value: 'lessThan',
+ },
+ {
+ name: 'Less Than or Equal',
+ value: 'lessThanOrEqual',
+ },
+ {
+ name: 'Contains',
+ value: 'contains',
+ },
+ {
+ name: 'Not Contains',
+ value: 'notContains',
+ },
+ {
+ name: 'Starts With',
+ value: 'startsWith',
+ },
+ {
+ name: 'Ends With',
+ value: 'endsWith',
+ },
+ {
+ name: 'Is Empty',
+ value: 'isEmpty',
+ },
+ {
+ name: 'Is Not Empty',
+ value: 'isNotEmpty',
+ },
+ ],
+ default: 'equal',
+ },
+ {
+ displayName: 'Value',
+ name: 'value',
+ type: NodePropertyType.String,
+ default: '',
+ description: 'The value to compare against',
+ displayOptions: {
+ hide: {
+ operator: ['isEmpty', 'isNotEmpty'],
+ },
+ },
+ },
+ ],
+ },
+ ],
+ },
+ {
+ displayName: 'Combine Conditions',
+ name: 'combineOperation',
+ type: NodePropertyType.Options,
+ options: [
+ {
+ name: 'AND (All conditions must match)',
+ value: 'and',
+ },
+ {
+ name: 'OR (Any condition can match)',
+ value: 'or',
+ },
+ ],
+ default: 'and',
+ description: 'How to combine multiple conditions',
+ },
+ ],
+ };
+
+ async execute(this: IExecuteFunctions): Promise<NodeOutput> {
+ const items = this.getInputData();
+ const returnData: IDataObject[] = [];
+
+ const operation = this.getNodeParameter('operation', 0) as string;
+ const combineOperation = this.getNodeParameter('combineOperation', 0) as string;
+
+ for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
+ const item = items[itemIndex];
+ const conditions = this.getNodeParameter('conditions.condition', itemIndex, []) as Array<{
+ field: string;
+ operator: string;
+ value: string;
+ }>;
+
+ // Evaluate all conditions
+ const conditionResults = conditions.map((condition) => {
+ return evaluateCondition(item.json, condition);
+ });
+
+ // Combine conditions based on combineOperation
+ let matches = false;
+ if (combineOperation === 'and') {
+ matches = conditionResults.every((result) => result === true);
+ } else {
+ matches = conditionResults.some((result) => result === true);
+ }
+
+ // Apply operation
+ const shouldKeep =
+ (operation === 'keep' && matches) || (operation === 'remove' && !matches);
+
+ if (shouldKeep) {
+ returnData.push(item.json);
+ }
+ }
+
+ return [this.helpers.returnJsonArray(returnData)];
+ }
+}
+
+/**
+ * Evaluate a single condition
+ */
+function evaluateCondition(
+ data: IDataObject,
+ condition: { field: string; operator: string; value: string }
+): boolean {
+ const { field, operator, value } = condition;
+
+ // Get field value (supports dot notation like "price.close")
+ const fieldValue = getNestedValue(data, field);
+
+ switch (operator) {
+ case 'equal':
+ return String(fieldValue) === String(value);
+
+ case 'notEqual':
+ return String(fieldValue) !== String(value);
+
+ case 'greaterThan':
+ return Number(fieldValue) > Number(value);
+
+ case 'greaterThanOrEqual':
+ return Number(fieldValue) >= Number(value);
+
+ case 'lessThan':
+ return Number(fieldValue) < Number(value);
+
+ case 'lessThanOrEqual':
+ return Number(fieldValue) <= Number(value);
+
+ case 'contains':
+ return String(fieldValue).toLowerCase().includes(String(value).toLowerCase());
+
+ case 'notContains':
+ return !String(fieldValue).toLowerCase().includes(String(value).toLowerCase());
+
+ case 'startsWith':
+ return String(fieldValue).toLowerCase().startsWith(String(value).toLowerCase());
+
+ case 'endsWith':
+ return String(fieldValue).toLowerCase().endsWith(String(value).toLowerCase());
+
+ case 'isEmpty':
+ return fieldValue === null || fieldValue === undefined || fieldValue === '';
+
+ case 'isNotEmpty':
+ return fieldValue !== null && fieldValue !== undefined && fieldValue !== '';
+
+ default:
+ return false;
+ }
+}
+
+/**
+ * Get nested value from object using dot notation
+ */
+function getNestedValue(obj: IDataObject, path: string): any {
+ const keys = path.split('.');
+ let current: any = obj;
+
+ for (const key of keys) {
+ if (current === null || current === undefined) {
+ return undefined;
+ }
+ current = current[key];
+ }
+
+ return current;
+}
diff --git a/fincept-terminal-desktop/src/nodes/core/Merge.node.ts b/fincept-terminal-desktop/src/nodes/core/Merge.node.ts
new file mode 100644
index 000000000..94d6b7245
--- /dev/null
+++ b/fincept-terminal-desktop/src/nodes/core/Merge.node.ts
@@ -0,0 +1,371 @@
+/**
+ * Merge Node
+ * Combine data from multiple inputs
+ *
+ * Use cases:
+ * - Combine price data from multiple sources
+ * - Merge technical indicators with price data
+ * - Join fundamental data with market data
+ * - Append multiple datasets
+ */
+
+import {
+ INodeType,
+ INodeTypeDescription,
+ IExecuteFunctions,
+ NodeOutput,
+ NodeConnectionType,
+ NodePropertyType,
+ IDataObject,
+ INodeExecutionData,
+} from '../../services/nodeSystem/types';
+
+export class MergeNode implements INodeType {
+ description: INodeTypeDescription = {
+ displayName: 'Merge',
+ name: 'merge',
+ icon: 'fa:code-branch',
+ iconColor: '#10b981',
+ group: ['transform'],
+ version: 1,
+ description: 'Combine data from multiple inputs',
+ subtitle: '={{$parameter["mode"]}}',
+ defaults: {
+ name: 'Merge',
+ color: '#10b981',
+ },
+ inputs: [NodeConnectionType.Main, NodeConnectionType.Main],
+ outputs: [NodeConnectionType.Main],
+ properties: [
+ {
+ displayName: 'Mode',
+ name: 'mode',
+ type: NodePropertyType.Options,
+ noDataExpression: true,
+ options: [
+ {
+ name: 'Append',
+ value: 'append',
+ description: 'Combine all items from both inputs into one output',
+ },
+ {
+ name: 'Merge By Position',
+ value: 'mergeByPosition',
+ description: 'Merge items at the same position (1st with 1st, 2nd with 2nd, etc.)',
+ },
+ {
+ name: 'Merge By Key',
+ value: 'mergeByKey',
+ description: 'Join items based on matching field values (like SQL JOIN)',
+ },
+ {
+ name: 'Choose Branch',
+ value: 'chooseBranch',
+ description: 'Output items from only one input',
+ },
+ ],
+ default: 'append',
+ },
+
+ // Merge By Key options
+ {
+ displayName: 'Join',
+ name: 'joinMode',
+ type: NodePropertyType.Options,
+ displayOptions: {
+ show: {
+ mode: ['mergeByKey'],
+ },
+ },
+ options: [
+ {
+ name: 'Inner Join',
+ value: 'inner',
+ description: 'Keep only items that have matches in both inputs',
+ },
+ {
+ name: 'Left Join',
+ value: 'left',
+ description: 'Keep all items from input 1, add matching data from input 2',
+ },
+ {
+ name: 'Outer Join',
+ value: 'outer',
+ description: 'Keep all items from both inputs',
+ },
+ ],
+ default: 'inner',
+ },
+ {
+ displayName: 'Key (Input 1)',
+ name: 'key1',
+ type: NodePropertyType.String,
+ displayOptions: {
+ show: {
+ mode: ['mergeByKey'],
+ },
+ },
+ default: '',
+ placeholder: 'e.g., symbol',
+ required: true,
+ description: 'Field name to match on in Input 1',
+ },
+ {
+ displayName: 'Key (Input 2)',
+ name: 'key2',
+ type: NodePropertyType.String,
+ displayOptions: {
+ show: {
+ mode: ['mergeByKey'],
+ },
+ },
+ default: '',
+ placeholder: 'e.g., ticker',
+ required: true,
+ description: 'Field name to match on in Input 2',
+ },
+
+ // Choose Branch options
+ {
+ displayName: 'Output',
+ name: 'output',
+ type: NodePropertyType.Options,
+ displayOptions: {
+ show: {
+ mode: ['chooseBranch'],
+ },
+ },
+ options: [
+ {
+ name: 'Input 1',
+ value: 'input1',
+ },
+ {
+ name: 'Input 2',
+ value: 'input2',
+ },
+ ],
+ default: 'input1',
+ },
+
+ // Merge By Position options
+ {
+ displayName: 'Clash Handling',
+ name: 'clashHandling',
+ type: NodePropertyType.Options,
+ displayOptions: {
+ show: {
+ mode: ['mergeByPosition'],
+ },
+ },
+ options: [
+ {
+ name: 'Prefer Input 1',
+ value: 'preferInput1',
+ description: 'If both inputs have the same field, use value from Input 1',
+ },
+ {
+ name: 'Prefer Input 2',
+ value: 'preferInput2',
+ description: 'If both inputs have the same field, use value from Input 2',
+ },
+ {
+ name: 'Add Suffix',
+ value: 'addSuffix',
+ description: 'If both inputs have the same field, add suffix (_1, _2)',
+ },
+ ],
+ default: 'preferInput1',
+ },
+ ],
+ };
+
+ async execute(this: IExecuteFunctions): Promise<NodeOutput> {
+ const mode = this.getNodeParameter('mode', 0) as string;
+
+ // Get input data
+ const input1 = this.getInputData(0) || [];
+ const input2 = this.getInputData(1) || [];
+
+ let returnData: INodeExecutionData[] = [];
+
+ switch (mode) {
+ case 'append':
+ returnData = mergeAppend(input1, input2);
+ break;
+
+ case 'mergeByPosition':
+ const clashHandling = this.getNodeParameter('clashHandling', 0) as string;
+ returnData = mergeByPosition(input1, input2, clashHandling);
+ break;
+
+ case 'mergeByKey':
+ const joinMode = this.getNodeParameter('joinMode', 0) as string;
+ const key1 = this.getNodeParameter('key1', 0) as string;
+ const key2 = this.getNodeParameter('key2', 0) as string;
+ returnData = mergeByKey(input1, input2, key1, key2, joinMode);
+ break;
+
+ case 'chooseBranch':
+ const output = this.getNodeParameter('output', 0) as string;
+ returnData = output === 'input1' ? input1 : input2;
+ break;
+
+ default:
+ returnData = input1;
+ }
+
+ return [returnData];
+ }
+}
+
+/**
+ * Append: Combine all items from both inputs
+ */
+function mergeAppend(
+ input1: INodeExecutionData[],
+ input2: INodeExecutionData[]
+): INodeExecutionData[] {
+ return [...input1, ...input2];
+}
+
+/**
+ * Merge By Position: Merge items at the same index
+ */
+function mergeByPosition(
+ input1: INodeExecutionData[],
+ input2: INodeExecutionData[],
+ clashHandling: string
+): INodeExecutionData[] {
+ const result: INodeExecutionData[] = [];
+ const maxLength = Math.max(input1.length, input2.length);
+
+ for (let i = 0; i < maxLength; i++) {
+ const item1 = input1[i]?.json || {};
+ const item2 = input2[i]?.json || {};
+
+ let merged: IDataObject = {};
+
+ if (clashHandling === 'preferInput1') {
+ merged = { ...item2, ...item1 };
+ } else if (clashHandling === 'preferInput2') {
+ merged = { ...item1, ...item2 };
+ } else if (clashHandling === 'addSuffix') {
+ // Add suffix to conflicting fields
+ const keys1 = Object.keys(item1);
+ const keys2 = Object.keys(item2);
+ const commonKeys = keys1.filter((key) => keys2.includes(key));
+
+ merged = { ...item1, ...item2 };
+
+ for (const key of commonKeys) {
+ merged[`${key}_1`] = item1[key];
+ merged[`${key}_2`] = item2[key];
+ delete merged[key];
+ }
+ }
+
+ result.push({ json: merged });
+ }
+
+ return result;
+}
+
+/**
+ * Merge By Key: Join items based on matching field values
+ */
+function mergeByKey(
+ input1: INodeExecutionData[],
+ input2: INodeExecutionData[],
+ key1: string,
+ key2: string,
+ joinMode: string
+): INodeExecutionData[] {
+ const result: INodeExecutionData[] = [];
+
+ // Create lookup map for input2
+ const input2Map = new Map<any, IDataObject[]>();
+ for (const item of input2) {
+ const keyValue = getNestedValue(item.json, key2);
+ if (!input2Map.has(keyValue)) {
+ input2Map.set(keyValue, []);
+ }
+ input2Map.get(keyValue)!.push(item.json);
+ }
+
+ if (joinMode === 'inner' || joinMode === 'left') {
+ // Process input1 items
+ for (const item1 of input1) {
+ const keyValue = getNestedValue(item1.json, key1);
+ const matches = input2Map.get(keyValue) || [];
+
+ if (matches.length > 0) {
+ // Found matches - merge with each
+ for (const item2 of matches) {
+ result.push({
+ json: { ...item1.json, ...item2 },
+ });
+ }
+ } else if (joinMode === 'left') {
+ // Left join - keep item1 even without matches
+ result.push({
+ json: { ...item1.json },
+ });
+ }
+ }
+ }
+
+ if (joinMode === 'outer') {
+ // Outer join - include all items from both inputs
+ const processedKeys = new Set<any>();
+
+ // Process input1
+ for (const item1 of input1) {
+ const keyValue = getNestedValue(item1.json, key1);
+ processedKeys.add(keyValue);
+ const matches = input2Map.get(keyValue) || [];
+
+ if (matches.length > 0) {
+ for (const item2 of matches) {
+ result.push({
+ json: { ...item1.json, ...item2 },
+ });
+ }
+ } else {
+ result.push({
+ json: { ...item1.json },
+ });
+ }
+ }
+
+ // Add unmatched items from input2
+ for (const [keyValue, items] of input2Map) {
+ if (!processedKeys.has(keyValue)) {
+ for (const item of items) {
+ result.push({
+ json: { ...item },
+ });
+ }
+ }
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Get nested value from object using dot notation
+ */
+function getNestedValue(obj: IDataObject, path: string): any {
+ const keys = path.split('.');
+ let current: any = obj;
+
+ for (const key of keys) {
+ if (current === null || current === undefined) {
+ return undefined;
+ }
+ current = current[key];
+ }
+
+ return current;
+}
diff --git a/fincept-terminal-desktop/src/nodes/core/Set.node.ts b/fincept-terminal-desktop/src/nodes/core/Set.node.ts
new file mode 100644
index 000000000..74be65224
--- /dev/null
+++ b/fincept-terminal-desktop/src/nodes/core/Set.node.ts
@@ -0,0 +1,272 @@
+/**
+ * Set Node
+ * Add, edit, or remove fields from items
+ *
+ * Use cases:
+ * - Add calculated fields (e.g., percentage change)
+ * - Rename fields
+ * - Remove sensitive fields
+ * - Set default values
+ * - Transform data structure
+ */
+
+import {
+ INodeType,
+ INodeTypeDescription,
+ IExecuteFunctions,
+ NodeOutput,
+ NodeConnectionType,
+ NodePropertyType,
+ IDataObject,
+} from '../../services/nodeSystem/types';
+
+export class SetNode implements INodeType {
+ description: INodeTypeDescription = {
+ displayName: 'Set',
+ name: 'set',
+ icon: 'fa:pen',
+ iconColor: '#3b82f6',
+ group: ['transform'],
+ version: 1,
+ description: 'Add, edit, or remove fields from items',
+ subtitle: 'Edit Fields',
+ defaults: {
+ name: 'Set',
+ color: '#3b82f6',
+ },
+ inputs: [NodeConnectionType.Main],
+ outputs: [NodeConnectionType.Main],
+ properties: [
+ {
+ displayName: 'Fields to Set',
+ name: 'fields',
+ placeholder: 'Add Field',
+ type: NodePropertyType.FixedCollection,
+ typeOptions: {
+ multipleValues: true,
+ },
+ default: [],
+ options: [
+ {
+ name: 'field',
+ description: 'Field',
+ values: [
+ {
+ displayName: 'Name',
+ name: 'name',
+ type: NodePropertyType.String,
+ default: '',
+ placeholder: 'e.g., percentage_change',
+ description: 'Name of the field to set',
+ required: true,
+ },
+ {
+ displayName: 'Type',
+ name: 'type',
+ type: NodePropertyType.Options,
+ options: [
+ {
+ name: 'String',
+ value: 'string',
+ },
+ {
+ name: 'Number',
+ value: 'number',
+ },
+ {
+ name: 'Boolean',
+ value: 'boolean',
+ },
+ {
+ name: 'Object',
+ value: 'object',
+ },
+ {
+ name: 'Array',
+ value: 'array',
+ },
+ ],
+ default: 'string',
+ },
+ {
+ displayName: 'Value',
+ name: 'value',
+ type: NodePropertyType.String,
+ default: '',
+ description: 'The value to set. Can use expressions like {{$json.field}}',
+ },
+ ],
+ },
+ ],
+ },
+ {
+ displayName: 'Include Other Fields',
+ name: 'includeOtherFields',
+ type: NodePropertyType.Boolean,
+ default: true,
+ description:
+ 'Whether to include all other fields from the input (true) or only the fields specified above (false)',
+ },
+ {
+ displayName: 'Options',
+ name: 'options',
+ type: NodePropertyType.Collection,
+ placeholder: 'Add Option',
+ default: [],
+ options: [
+ {
+ displayName: 'Dot Notation',
+ name: 'dotNotation',
+ type: NodePropertyType.Boolean,
+ default: true,
+ description:
+ 'Whether to support dot notation (e.g., "user.name") for nested fields',
+ },
+ ],
+ },
+ ],
+ };
+
+ async execute(this: IExecuteFunctions): Promise<NodeOutput> {
+ const items = this.getInputData();
+ const returnData: IDataObject[] = [];
+
+ const includeOtherFields = this.getNodeParameter('includeOtherFields', 0) as boolean;
+ const options = this.getNodeParameter('options', 0, {}) as IDataObject;
+ const dotNotation = options.dotNotation !== false;
+
+ for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
+ const item = items[itemIndex];
+ const fields = this.getNodeParameter('fields.field', itemIndex, []) as Array<{
+ name: string;
+ type: string;
+ value: string;
+ }>;
+
+ let newItem: IDataObject = {};
+
+ // Include other fields if specified
+ if (includeOtherFields) {
+ newItem = { ...item.json };
+ }
+
+ // Set/update fields
+ for (const field of fields) {
+ const { name, type, value } = field;
+
+ // Evaluate value (simple implementation - will be enhanced with expression engine)
+ let evaluatedValue: any = value;
+
+ // Simple expression evaluation: {{$json.fieldName}}
+ if (typeof value === 'string' && value.includes('{{$json.')) {
+ const matches = value.match(/\{\{\$json\.([^}]+)\}\}/);
+ if (matches && matches[1]) {
+ evaluatedValue = getNestedValue(item.json, matches[1]);
+ }
+ }
+
+ // Type conversion
+ evaluatedValue = convertValue(evaluatedValue, type);
+
+ // Set field (with dot notation support)
+ if (dotNotation && name.includes('.')) {
+ setNestedValue(newItem, name, evaluatedValue);
+ } else {
+ newItem[name] = evaluatedValue;
+ }
+ }
+
+ returnData.push(newItem);
+ }
+
+ return [this.helpers.returnJsonArray(returnData)];
+ }
+}
+
+/**
+ * Convert value to specified type
+ */
+function convertValue(value: any, type: string): any {
+ if (value === null || value === undefined) {
+ return value;
+ }
+
+ switch (type) {
+ case 'string':
+ return String(value);
+
+ case 'number':
+ const num = Number(value);
+ return isNaN(num) ? 0 : num;
+
+ case 'boolean':
+ if (typeof value === 'string') {
+ return value.toLowerCase() === 'true';
+ }
+ return Boolean(value);
+
+ case 'object':
+ if (typeof value === 'string') {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return {};
+ }
+ }
+ return value;
+
+ case 'array':
+ if (Array.isArray(value)) {
+ return value;
+ }
+ if (typeof value === 'string') {
+ try {
+ const parsed = JSON.parse(value);
+ return Array.isArray(parsed) ? parsed : [value];
+ } catch {
+ return [value];
+ }
+ }
+ return [value];
+
+ default:
+ return value;
+ }
+}
+
+/**
+ * Get nested value from object using dot notation
+ */
+function getNestedValue(obj: IDataObject, path: string): any {
+ const keys = path.split('.');
+ let current: any = obj;
+
+ for (const key of keys) {
+ if (current === null || current === undefined) {
+ return undefined;
+ }
+ current = current[key];
+ }
+
+ return current;
+}
+
+/**
+ * Set nested value in object using dot notation
+ */
+function setNestedValue(obj: IDataObject, path: string, value: any): void {
+ const keys = path.split('.');
+ let current: any = obj;
+
+ for (let i = 0; i < keys.length - 1; i++) {
+ const key = keys[i];
+
+ if (!current[key] || typeof current[key] !== 'object') {
+ current[key] = {};
+ }
+
+ current = current[key];
+ }
+
+ current[keys[keys.length - 1]] = value;
+}
diff --git a/fincept-terminal-desktop/src/nodes/core/Switch.node.ts b/fincept-terminal-desktop/src/nodes/core/Switch.node.ts
new file mode 100644
index 000000000..c9a385451
--- /dev/null
+++ b/fincept-terminal-desktop/src/nodes/core/Switch.node.ts
@@ -0,0 +1,295 @@
+/**
+ * Switch Node
+ * Route items to different outputs based on conditions
+ *
+ * Use cases:
+ * - Route stocks by sector
+ * - Separate buy/sell signals
+ * - Split data by price range
+ * - Classify trades by profitability
+ */
+
+import {
+ INodeType,
+ INodeTypeDescription,
+ IExecuteFunctions,
+ NodeOutput,
+ NodeConnectionType,
+ NodePropertyType,
+ IDataObject,
+ INodeExecutionData,
+} from '../../services/nodeSystem/types';
+
+export class SwitchNode implements INodeType {
+ description: INodeTypeDescription = {
+ displayName: 'Switch',
+ name: 'switch',
+ icon: 'fa:map-signs',
+ iconColor: '#f59e0b',
+ group: ['transform'],
+ version: 1,
+ description: 'Route items to different outputs based on conditions',
+ subtitle: '={{$parameter["mode"]}} Mode',
+ defaults: {
+ name: 'Switch',
+ color: '#f59e0b',
+ },
+ inputs: [NodeConnectionType.Main],
+ outputs: [
+ NodeConnectionType.Main,
+ NodeConnectionType.Main,
+ NodeConnectionType.Main,
+ NodeConnectionType.Main,
+ ],
+ outputNames: ['Output 1', 'Output 2', 'Output 3', 'Fallback'],
+ properties: [
+ {
+ displayName: 'Mode',
+ name: 'mode',
+ type: NodePropertyType.Options,
+ noDataExpression: true,
+ options: [
+ {
+ name: 'Rules',
+ value: 'rules',
+ description: 'Route based on conditional rules',
+ },
+ {
+ name: 'Expression',
+ value: 'expression',
+ description: 'Route based on expression result',
+ },
+ ],
+ default: 'rules',
+ },
+
+ // Rules mode
+ {
+ displayName: 'Routing Rules',
+ name: 'rules',
+ placeholder: 'Add Routing Rule',
+ type: NodePropertyType.FixedCollection,
+ typeOptions: {
+ multipleValues: true,
+ },
+ displayOptions: {
+ show: {
+ mode: ['rules'],
+ },
+ },
+ default: [],
+ description: 'Route items to different outputs based on rules',
+ options: [
+ {
+ name: 'rule',
+ description: 'Routing Rule',
+ values: [
+ {
+ displayName: 'Output',
+ name: 'output',
+ type: NodePropertyType.Number,
+ default: 0,
+ description: 'Output index to route to (0-2, or 3 for fallback)',
+ typeOptions: {
+ minValue: 0,
+ maxValue: 3,
+ },
+ },
+ {
+ displayName: 'Field',
+ name: 'field',
+ type: NodePropertyType.String,
+ default: '',
+ placeholder: 'e.g., price',
+ description: 'Field to check',
+ required: true,
+ },
+ {
+ displayName: 'Operation',
+ name: 'operator',
+ type: NodePropertyType.Options,
+ options: [
+ { name: 'Equal', value: 'equal' },
+ { name: 'Not Equal', value: 'notEqual' },
+ { name: 'Greater Than', value: 'greaterThan' },
+ { name: 'Less Than', value: 'lessThan' },
+ { name: 'Contains', value: 'contains' },
+ { name: 'Starts With', value: 'startsWith' },
+ { name: 'Ends With', value: 'endsWith' },
+ { name: 'Is Empty', value: 'isEmpty' },
+ ],
+ default: 'equal',
+ },
+ {
+ displayName: 'Value',
+ name: 'value',
+ type: NodePropertyType.String,
+ default: '',
+ description: 'Value to compare against',
+ displayOptions: {
+ hide: {
+ operator: ['isEmpty'],
+ },
+ },
+ },
+ ],
+ },
+ ],
+ },
+
+ // Expression mode
+ {
+ displayName: 'Output Expression',
+ name: 'outputExpression',
+ type: NodePropertyType.String,
+ displayOptions: {
+ show: {
+ mode: ['expression'],
+ },
+ },
+ default: '',
+ placeholder: '={{$json.category === "technology" ? 0 : 1}}',
+ description: 'Expression that returns output index (0-3)',
+ },
+
+ {
+ displayName: 'Fallback Output',
+ name: 'fallbackOutput',
+ type: NodePropertyType.Options,
+ options: [
+ {
+ name: 'Output 4 (Default)',
+ value: 3,
+ },
+ {
+ name: 'Discard Item',
+ value: -1,
+ },
+ ],
+ default: 3,
+ description: 'Where to send items that do not match any rule',
+ },
+ ],
+ };
+
+ async execute(this: IExecuteFunctions): Promise<NodeOutput> {
+ const items = this.getInputData();
+ const mode = this.getNodeParameter('mode', 0) as string;
+ const fallbackOutput = this.getNodeParameter('fallbackOutput', 0) as number;
+
+ // Initialize output arrays
+ const outputs: INodeExecutionData[][] = [[], [], [], []];
+
+ for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
+ const item = items[itemIndex];
+ let outputIndex = -1;
+
+ if (mode === 'rules') {
+ // Rules-based routing
+ const rules = this.getNodeParameter('rules.rule', itemIndex, []) as Array<{
+ output: number;
+ field: string;
+ operator: string;
+ value: string;
+ }>;
+
+ // Find first matching rule
+ for (const rule of rules) {
+ if (evaluateRule(item.json, rule)) {
+ outputIndex = rule.output;
+ break;
+ }
+ }
+ } else if (mode === 'expression') {
+ // Expression-based routing
+ const expression = this.getNodeParameter('outputExpression', itemIndex) as string;
+
+ // Simple expression evaluation
+ // TODO: Replace with full expression engine
+ outputIndex = evaluateExpression(expression, item.json);
+ }
+
+ // If no rule matched, use fallback
+ if (outputIndex === -1) {
+ outputIndex = fallbackOutput;
+ }
+
+ // Add item to appropriate output
+ if (outputIndex >= 0 && outputIndex < outputs.length) {
+ outputs[outputIndex].push(item);
+ }
+ // If outputIndex is -1, item is discarded
+ }
+
+ return outputs;
+ }
+}
+
+/**
+ * Evaluate a routing rule
+ */
+function evaluateRule(
+ data: IDataObject,
+ rule: { field: string; operator: string; value: string }
+): boolean {
+ const { field, operator, value } = rule;
+
+ const fieldValue = getNestedValue(data, field);
+
+ switch (operator) {
+ case 'equal':
+ return String(fieldValue) === String(value);
+
+ case 'notEqual':
+ return String(fieldValue) !== String(value);
+
+ case 'greaterThan':
+ return Number(fieldValue) > Number(value);
+
+ case 'lessThan':
+ return Number(fieldValue) < Number(value);
+
+ case 'contains':
+ return String(fieldValue).toLowerCase().includes(String(value).toLowerCase());
+
+ case 'startsWith':
+ return String(fieldValue).toLowerCase().startsWith(String(value).toLowerCase());
+
+ case 'endsWith':
+ return String(fieldValue).toLowerCase().endsWith(String(value).toLowerCase());
+
+ case 'isEmpty':
+ return fieldValue === null || fieldValue === undefined || fieldValue === '';
+
+ default:
+ return false;
+ }
+}
+
+/**
+ * Simple expression evaluation
+ * Returns output index (0-3)
+ */
+function evaluateExpression(expression: string, data: IDataObject): number {
+ // Very basic implementation - will be replaced with full expression engine
+ // For now, just return 0 as default
+ // TODO: Implement proper expression evaluation
+ return 0;
+}
+
+/**
+ * Get nested value from object using dot notation
+ */
+function getNestedValue(obj: IDataObject, path: string): any {
+ const keys = path.split('.');
+ let current: any = obj;
+
+ for (const key of keys) {
+ if (current === null || current === undefined) {
+ return undefined;
+ }
+ current = current[key];
+ }
+
+ return current;
+}
diff --git a/fincept-terminal-desktop/src/nodes/finance/StockData.node.ts b/fincept-terminal-desktop/src/nodes/finance/StockData.node.ts
new file mode 100644
index 000000000..6a8f8b779
--- /dev/null
+++ b/fincept-terminal-desktop/src/nodes/finance/StockData.node.ts
@@ -0,0 +1,257 @@
+/**
+ * Stock Data Node - FIXED VERSION
+ * Fetches stock market data from various sources
+ */
+
+import {
+ INodeType,
+ INodeTypeDescription,
+ IExecuteFunctions,
+ NodeOutput,
+ NodeConnectionType,
+ NodePropertyType,
+ IMarketData,
+ NodeOperationError,
+} from '../../services/nodeSystem/types';
+
+export class StockDataNode implements INodeType {
+ description: INodeTypeDescription = {
+ displayName: 'Stock Data',
+ name: 'stockData',
+ icon: 'fa:chart-line',
+ iconColor: '#10b981',
+ group: ['finance', 'input'],
+ version: 1,
+ description: 'Fetch stock market data from various sources',
+ subtitle: '={{$parameter["source"]}} - {{$parameter["symbol"]}}',
+ defaults: {
+ name: 'Stock Data',
+ color: '#10b981',
+ },
+ inputs: [],
+ outputs: [NodeConnectionType.Main, NodeConnectionType.PriceData],
+ properties: [
+ {
+ displayName: 'Data Source',
+ name: 'source',
+ type: NodePropertyType.Options,
+ options: [
+ {
+ name: 'Yahoo Finance',
+ value: 'yfinance',
+ description: 'Free stock data from Yahoo Finance',
+ },
+ {
+ name: 'Alpha Vantage',
+ value: 'alphavantage',
+ description: 'Professional market data (API key required)',
+ },
+ {
+ name: 'Polygon.io',
+ value: 'polygon',
+ description: 'Real-time and historical market data',
+ },
+ {
+ name: 'Local Database',
+ value: 'database',
+ description: 'Fetch from local SQLite database',
+ },
+ ],
+ default: 'yfinance',
+ },
+ {
+ displayName: 'Symbol',
+ name: 'symbol',
+ type: NodePropertyType.String,
+ default: 'AAPL',
+ required: true,
+ placeholder: 'AAPL',
+ description: 'Stock ticker symbol',
+ },
+ {
+ displayName: 'Interval',
+ name: 'interval',
+ type: NodePropertyType.Options,
+ options: [
+ { name: '1 Minute', value: '1m' },
+ { name: '5 Minutes', value: '5m' },
+ { name: '15 Minutes', value: '15m' },
+ { name: '30 Minutes', value: '30m' },
+ { name: '1 Hour', value: '1h' },
+ { name: '1 Day', value: '1d' },
+ { name: '1 Week', value: '1wk' },
+ { name: '1 Month', value: '1mo' },
+ ],
+ default: '1d',
+ description: 'Data interval/timeframe',
+ },
+ {
+ displayName: 'Period',
+ name: 'period',
+ type: NodePropertyType.Options,
+ options: [
+ { name: '1 Day', value: '1d' },
+ { name: '5 Days', value: '5d' },
+ { name: '1 Month', value: '1mo' },
+ { name: '3 Months', value: '3mo' },
+ { name: '6 Months', value: '6mo' },
+ { name: '1 Year', value: '1y' },
+ { name: '2 Years', value: '2y' },
+ { name: '5 Years', value: '5y' },
+ { name: 'Year to Date', value: 'ytd' },
+ { name: 'Max', value: 'max' },
+ ],
+ default: '1mo',
+ description: 'Historical period to fetch',
+ },
+ {
+ displayName: 'API Key',
+ name: 'apiKey',
+ type: NodePropertyType.String,
+ typeOptions: {
+ password: true,
+ },
+ displayOptions: {
+ show: {
+ source: ['alphavantage', 'polygon'],
+ },
+ },
+ default: '',
+ description: 'API key for the selected data source',
+ },
+ ],
+ };
+
+ async execute(this: IExecuteFunctions): Promise<NodeOutput> {
+ const items = this.getInputData();
+ const returnData: any[] = [];
+
+ // If no input items, create one item to process
+ const processItems = items.length > 0 ? items : [{ json: {} }];
+
+ for (let itemIndex = 0; itemIndex < processItems.length; itemIndex++) {
+ try {
+ // Get parameters
+ const source = this.getNodeParameter('source', itemIndex) as string;
+ const symbol = this.getNodeParameter('symbol', itemIndex) as string;
+ const interval = this.getNodeParameter('interval', itemIndex) as string;
+ const period = this.getNodeParameter('period', itemIndex) as string;
+
+ // Fetch data based on source
+ let marketData: IMarketData[];
+
+ switch (source) {
+ case 'yfinance':
+ marketData = generateSampleData(symbol, 30);
+ break;
+
+ case 'alphavantage':
+ const apiKey = this.getNodeParameter('apiKey', itemIndex) as string;
+ if (!apiKey) {
+ throw new NodeOperationError(
+ this.getNode(),
+ 'API Key is required for Alpha Vantage',
+ undefined,
+ itemIndex
+ );
+ }
+ marketData = generateSampleData(symbol, 30);
+ break;
+
+ case 'polygon':
+ const polygonApiKey = this.getNodeParameter('apiKey', itemIndex) as string;
+ if (!polygonApiKey) {
+ throw new NodeOperationError(
+ this.getNode(),
+ 'API Key is required for Polygon.io',
+ undefined,
+ itemIndex
+ );
+ }
+ marketData = generateSampleData(symbol, 30);
+ break;
+
+ case 'database':
+ marketData = generateSampleData(symbol, 30);
+ break;
+
+ default:
+ throw new NodeOperationError(
+ this.getNode(),
+ `Unknown data source: ${source}`,
+ undefined,
+ itemIndex
+ );
+ }
+
+ returnData.push(...marketData);
+ } catch (error: any) {
+ if (this.continueOnFail()) {
+ returnData.push({
+ symbol: '',
+ timestamp: Date.now(),
+ open: 0,
+ high: 0,
+ low: 0,
+ close: 0,
+ volume: 0,
+ });
+ continue;
+ }
+ throw error;
+ }
+ }
+
+ // Convert to node execution data format
+ return [
+ this.helpers.returnJsonArray(
+ returnData.map((data) => ({
+ symbol: data.symbol,
+ timestamp: data.timestamp,
+ datetime: new Date(data.timestamp).toISOString(),
+ open: data.open,
+ high: data.high,
+ low: data.low,
+ close: data.close,
+ volume: data.volume,
+ vwap: data.vwap,
+ }))
+ ),
+ ];
+ }
+}
+
+/**
+ * Generate sample data for demonstration
+ * Helper function outside the class
+ */
+function generateSampleData(symbol: string, count: number): IMarketData[] {
+ const data: IMarketData[] = [];
+ let basePrice = 100 + Math.random() * 400;
+ const now = Date.now();
+ const dayMs = 24 * 60 * 60 * 1000;
+
+ for (let i = 0; i < count; i++) {
+ const change = (Math.random() - 0.5) * 10;
+ basePrice = Math.max(basePrice + change, 1);
+
+ const open = basePrice;
+ const close = basePrice + (Math.random() - 0.5) * 5;
+ const high = Math.max(open, close) + Math.random() * 3;
+ const low = Math.min(open, close) - Math.random() * 3;
+ const volume = Math.floor(1000000 + Math.random() * 10000000);
+
+ data.push({
+ symbol,
+ timestamp: now - (count - i) * dayMs,
+ open,
+ high,
+ low,
+ close,
+ volume,
+ vwap: (high + low + close) / 3,
+ });
+ }
+
+ return data;
+}
diff --git a/fincept-terminal-desktop/src/services/authApi.tsx b/fincept-terminal-desktop/src/services/authApi.tsx
index 55d4fc5b3..462ed4840 100644
--- a/fincept-terminal-desktop/src/services/authApi.tsx
+++ b/fincept-terminal-desktop/src/services/authApi.tsx
@@ -57,15 +57,25 @@ interface DeviceRegisterRequest {
platform: string;
user_agent: string;
language: string;
+ screen_resolution?: string;
+ cpu_cores?: number;
+ memory_gb?: number;
};
}
// Response Types
interface LoginResponse {
api_key: string;
- username: string;
- email: string;
- credit_balance: number;
+ username?: string;
+ email?: string;
+ credit_balance?: number;
+ user?: {
+ id: number;
+ username: string;
+ email: string;
+ account_type: string;
+ credit_balance: number;
+ };
}
interface UserProfileResponse {
@@ -75,6 +85,7 @@ interface UserProfileResponse {
account_type: string;
credit_balance: number;
is_verified: boolean;
+ is_admin: boolean;
mfa_enabled: boolean;
created_at: string;
last_login_at: string;
@@ -104,9 +115,12 @@ interface AuthStatusResponse {
interface DeviceRegisterResponse {
api_key?: string;
temp_api_key?: string;
+ guest_id?: number;
+ device_id?: string;
expires_at?: string;
daily_limit?: number;
requests_today?: number;
+ credit_balance?: number;
}
// Generic API request function
@@ -123,13 +137,6 @@ const makeApiRequest = async <T = any>(
};
const url = getApiEndpoint(endpoint);
- console.log('🚀 Making auth request:', {
- method,
- url,
- endpoint,
- data,
- headers: { ...defaultHeaders, 'X-API-Key': (defaultHeaders as any)['X-API-Key'] ? '[REDACTED]' : undefined }
- });
const config: RequestInit = {
method,
@@ -143,22 +150,12 @@ const makeApiRequest = async <T = any>(
const response = await fetch(url, config);
- console.log('📡 Auth response received:', {
- status: response.status,
- statusText: response.statusText,
- headers: Object.fromEntries(response.headers.entries()),
- url: response.url
- });
-
const responseText = await response.text();
- console.log('📄 Raw auth response text:', responseText.substring(0, 200));
let responseData;
try {
responseData = JSON.parse(responseText);
- console.log('✅ Parsed auth JSON:', responseData);
} catch (parseError) {
- console.error('❌ Auth JSON parse failed:', parseError);
console.log('📄 Full auth response text:', responseText);
// Provide user-friendly error messages based on status code
@@ -217,7 +214,6 @@ const makeApiRequest = async <T = any>(
};
} catch (error) {
- console.error('💥 Auth request failed completely:', error);
if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
return {
@@ -248,6 +244,10 @@ export class AuthApiService {
// Login user
static async login(request: LoginRequest): Promise<ApiResponse<LoginResponse>> {
+ console.log('=== LOGIN REQUEST DEBUG ===');
+ console.log('Endpoint: /user/login');
+ console.log('Request body:', JSON.stringify(request, null, 2));
+ console.log('========================');
return makeApiRequest<LoginResponse>('POST', '/user/login', request);
}
@@ -460,7 +460,7 @@ export class AuthApiService {
}
}
-// Utility function to generate device ID
+// Utility function to generate device ID (must be 10-255 characters)
export const generateDeviceId = (): string => {
const getNavigatorInfo = () => {
return {
@@ -468,7 +468,9 @@ export const generateDeviceId = (): string => {
userAgent: navigator.userAgent,
language: navigator.language,
cookieEnabled: navigator.cookieEnabled,
- onLine: navigator.onLine
+ onLine: navigator.onLine,
+ screenRes: `${window.screen.width}x${window.screen.height}`,
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
};
};
@@ -482,7 +484,16 @@ export const generateDeviceId = (): string => {
hash = hash & hash;
}
- return `desktop_${Math.abs(hash).toString(16)}`;
+ // Generate a device ID that's between 10-255 characters
+ const hashStr = Math.abs(hash).toString(16);
+ const timestamp = Date.now().toString(36);
+ const random = Math.random().toString(36).substring(2);
+
+ // Format: fincept_desktop_{hash}_{timestamp}_{random}
+ const deviceId = `fincept_desktop_${hashStr}_${timestamp}_${random}`;
+
+ // Ensure it's within the valid range (10-255 characters)
+ return deviceId.length > 255 ? deviceId.substring(0, 255) : deviceId;
};
// Auth utility functions
diff --git a/fincept-terminal-desktop/src/services/dataSourceRegistry.ts b/fincept-terminal-desktop/src/services/dataSourceRegistry.ts
index a1dcaff47..f58baeab3 100644
--- a/fincept-terminal-desktop/src/services/dataSourceRegistry.ts
+++ b/fincept-terminal-desktop/src/services/dataSourceRegistry.ts
@@ -2,7 +2,7 @@
// Central service for managing unified data sources (WebSocket + REST API)
import { sqliteService, DataSource } from './sqliteService';
-import { getWebSocketManager } from './websocket';
+import { getWebSocketManager } from './websocketBridge';
import { mappingEngine } from '../components/tabs/data-mapping/engine/MappingEngine';
import { DataMappingConfig } from '../components/tabs/data-mapping/types';
import { dataSourceLogger } from './loggerService';
@@ -64,18 +64,18 @@ export async function createWebSocketDataSource(input: {
const topic = `${config.provider}.${config.channel}${config.symbol ? '.' + config.symbol : ''}`;
try {
- // Set provider config if not already set
- const existingConfig = wsManager.getProviderConfig(config.provider);
- if (!existingConfig) {
- wsManager.setProviderConfig(config.provider, {
- provider_name: config.provider,
- enabled: true,
- api_key: input.params?.api_key,
- api_secret: input.params?.api_secret,
- endpoint: input.params?.endpoint
- });
- dataSourceLogger.debug(`Provider config set for: ${config.provider}`);
- }
+ // TODO: Re-implement with new Rust WebSocket backend
+ // const existingConfig = wsManager.getProviderConfig(config.provider);
+ // if (!existingConfig) {
+ // wsManager.setProviderConfig(config.provider, {
+ // provider_name: config.provider,
+ // enabled: true,
+ // api_key: input.params?.api_key,
+ // api_secret: input.params?.api_secret,
+ // endpoint: input.params?.endpoint
+ // });
+ // dataSourceLogger.debug(`Provider config set for: ${config.provider}`);
+ // }
// Note: Actual subscription happens when component uses useDataSource
dataSourceLogger.debug(`WebSocket source created: ${input.alias} -> ${topic}`);
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/DirectedGraph.ts b/fincept-terminal-desktop/src/services/nodeSystem/DirectedGraph.ts
new file mode 100644
index 000000000..c4f60861c
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/DirectedGraph.ts
@@ -0,0 +1,490 @@
+/**
+ * Directed Graph Implementation
+ * Based on n8n's DirectedGraph for efficient workflow graph operations
+ *
+ * This provides:
+ * - Graph representation as adjacency list
+ * - Efficient node/connection queries
+ * - Graph manipulation (add/remove nodes, connections)
+ * - Subgraph extraction
+ * - Parent/child traversal
+ */
+
+import {
+ INode,
+ IWorkflow,
+ IConnection,
+ NodeConnectionType,
+ IConnections,
+} from './types';
+
+export interface GraphConnection {
+ from: INode;
+ to: INode;
+ type: NodeConnectionType;
+ outputIndex: number;
+ inputIndex: number;
+}
+
+// Key format: fromName-outputType-outputIndex-inputIndex-toName
+type GraphKey = `${string}-${NodeConnectionType}-${number}-${number}-${string}`;
+
+/**
+ * Directed Graph for efficient workflow operations
+ *
+ * Provides a more flexible graph representation than the nested Workflow format.
+ * Allows for:
+ * - Incremental graph building
+ * - Easy graph manipulation
+ * - Efficient queries
+ * - Subgraph extraction
+ */
+export class DirectedGraph {
+ private nodes: Map<string, INode> = new Map();
+ private connections: Map<GraphKey, GraphConnection> = new Map();
+
+ /**
+ * Create graph from workflow
+ */
+ static fromWorkflow(workflow: IWorkflow): DirectedGraph {
+ const graph = new DirectedGraph();
+
+ // Add all nodes
+ for (const node of workflow.nodes) {
+ graph.addNode(node);
+ }
+
+ // Add all connections
+ for (const [sourceNodeName, nodeConnections] of Object.entries(workflow.connections)) {
+ const sourceNode = workflow.nodes.find((n) => n.name === sourceNodeName);
+ if (!sourceNode) continue;
+
+ for (const [connectionType, outputs] of Object.entries(nodeConnections)) {
+ for (let outputIndex = 0; outputIndex < outputs.length; outputIndex++) {
+ const connections = outputs[outputIndex];
+
+ for (const connection of connections) {
+ const targetNode = workflow.nodes.find((n) => n.name === connection.node);
+ if (!targetNode) continue;
+
+ graph.addConnection({
+ from: sourceNode,
+ to: targetNode,
+ type: connectionType as NodeConnectionType,
+ outputIndex,
+ inputIndex: connection.index,
+ });
+ }
+ }
+ }
+ }
+
+ return graph;
+ }
+
+ /**
+ * Convert graph back to workflow
+ */
+ toWorkflow(baseWorkflow: IWorkflow): IWorkflow {
+ const connections: IConnections = {};
+
+ // Rebuild connections object
+ for (const connection of this.connections.values()) {
+ const sourceName = connection.from.name;
+
+ if (!connections[sourceName]) {
+ connections[sourceName] = {};
+ }
+
+ if (!connections[sourceName][connection.type]) {
+ connections[sourceName][connection.type] = [];
+ }
+
+ // Ensure output array exists
+ while (connections[sourceName][connection.type].length <= connection.outputIndex) {
+ connections[sourceName][connection.type].push([]);
+ }
+
+ connections[sourceName][connection.type][connection.outputIndex].push({
+ node: connection.to.name,
+ type: connection.type,
+ index: connection.inputIndex,
+ });
+ }
+
+ return {
+ ...baseWorkflow,
+ nodes: Array.from(this.nodes.values()),
+ connections,
+ };
+ }
+
+ /**
+ * Check if node exists
+ */
+ hasNode(nodeName: string): boolean {
+ return this.nodes.has(nodeName);
+ }
+
+ /**
+ * Get all nodes
+ */
+ getNodes(): Map<string, INode> {
+ return new Map(this.nodes.entries());
+ }
+
+ /**
+ * Get node by name
+ */
+ getNode(nodeName: string): INode | undefined {
+ return this.nodes.get(nodeName);
+ }
+
+ /**
+ * Get nodes by names
+ */
+ getNodesByNames(names: string[]): Set<INode> {
+ const nodes = new Set<INode>();
+
+ for (const name of names) {
+ const node = this.nodes.get(name);
+ if (node) {
+ nodes.add(node);
+ }
+ }
+
+ return nodes;
+ }
+
+ /**
+ * Add node to graph
+ */
+ addNode(node: INode): this {
+ this.nodes.set(node.name, node);
+ return this;
+ }
+
+ /**
+ * Add multiple nodes
+ */
+ addNodes(...nodes: INode[]): this {
+ for (const node of nodes) {
+ this.addNode(node);
+ }
+ return this;
+ }
+
+ /**
+ * Remove node from graph
+ */
+ removeNode(nodeName: string): this {
+ this.nodes.delete(nodeName);
+
+ // Remove all connections to/from this node
+ const keysToDelete: GraphKey[] = [];
+
+ for (const [key, connection] of this.connections.entries()) {
+ if (connection.from.name === nodeName || connection.to.name === nodeName) {
+ keysToDelete.push(key);
+ }
+ }
+
+ for (const key of keysToDelete) {
+ this.connections.delete(key);
+ }
+
+ return this;
+ }
+
+ /**
+ * Get all connections (optionally filtered)
+ */
+ getConnections(filter: { to?: INode; from?: INode } = {}): GraphConnection[] {
+ const filtered: GraphConnection[] = [];
+
+ for (const connection of this.connections.values()) {
+ const toMatches = filter.to ? connection.to === filter.to : true;
+ const fromMatches = filter.from ? connection.from === filter.from : true;
+
+ if (toMatches && fromMatches) {
+ filtered.push(connection);
+ }
+ }
+
+ return filtered;
+ }
+
+ /**
+ * Add connection between nodes
+ */
+ addConnection(connection: GraphConnection): this {
+ const key = this.makeConnectionKey(connection);
+ this.connections.set(key, connection);
+ return this;
+ }
+
+ /**
+ * Get direct parent nodes (nodes that output to this node)
+ */
+ getDirectParents(node: INode): INode[] {
+ const parents: INode[] = [];
+ const seen = new Set<string>();
+
+ for (const connection of this.connections.values()) {
+ if (connection.to === node && !seen.has(connection.from.name)) {
+ parents.push(connection.from);
+ seen.add(connection.from.name);
+ }
+ }
+
+ return parents;
+ }
+
+ /**
+ * Get direct parent connections
+ */
+ getDirectParentConnections(node: INode): GraphConnection[] {
+ return this.getConnections({ to: node });
+ }
+
+ /**
+ * Get direct child nodes (nodes that receive input from this node)
+ */
+ getDirectChildren(node: INode): INode[] {
+ const children: INode[] = [];
+ const seen = new Set<string>();
+
+ for (const connection of this.connections.values()) {
+ if (connection.from === node && !seen.has(connection.to.name)) {
+ children.push(connection.to);
+ seen.add(connection.to.name);
+ }
+ }
+
+ return children;
+ }
+
+ /**
+ * Get all ancestors (all nodes upstream)
+ */
+ getAncestors(node: INode): Set<INode> {
+ const ancestors = new Set<INode>();
+ const visited = new Set<string>();
+
+ const traverse = (current: INode) => {
+ if (visited.has(current.name)) return;
+ visited.add(current.name);
+
+ const parents = this.getDirectParents(current);
+
+ for (const parent of parents) {
+ ancestors.add(parent);
+ traverse(parent);
+ }
+ };
+
+ traverse(node);
+ return ancestors;
+ }
+
+ /**
+ * Get all descendants (all nodes downstream)
+ */
+ getDescendants(node: INode): Set<INode> {
+ const descendants = new Set<INode>();
+ const visited = new Set<string>();
+
+ const traverse = (current: INode) => {
+ if (visited.has(current.name)) return;
+ visited.add(current.name);
+
+ const children = this.getDirectChildren(current);
+
+ for (const child of children) {
+ descendants.add(child);
+ traverse(child);
+ }
+ };
+
+ traverse(node);
+ return descendants;
+ }
+
+ /**
+ * Find path between two nodes (BFS)
+ */
+ findPath(from: INode, to: INode): INode[] | null {
+ const queue: Array<{ node: INode; path: INode[] }> = [{ node: from, path: [from] }];
+ const visited = new Set<string>();
+
+ while (queue.length > 0) {
+ const { node, path } = queue.shift()!;
+
+ if (node === to) {
+ return path;
+ }
+
+ if (visited.has(node.name)) continue;
+ visited.add(node.name);
+
+ const children = this.getDirectChildren(node);
+
+ for (const child of children) {
+ if (!visited.has(child.name)) {
+ queue.push({
+ node: child,
+ path: [...path, child],
+ });
+ }
+ }
+ }
+
+ return null; // No path found
+ }
+
+ /**
+ * Check if graph has cycles
+ */
+ hasCycles(): boolean {
+ const visited = new Set<string>();
+ const recursionStack = new Set<string>();
+
+ const hasCycleDFS = (node: INode): boolean => {
+ if (recursionStack.has(node.name)) {
+ return true; // Cycle detected
+ }
+
+ if (visited.has(node.name)) {
+ return false;
+ }
+
+ visited.add(node.name);
+ recursionStack.add(node.name);
+
+ const children = this.getDirectChildren(node);
+
+ for (const child of children) {
+ if (hasCycleDFS(child)) {
+ return true;
+ }
+ }
+
+ recursionStack.delete(node.name);
+ return false;
+ };
+
+ for (const node of this.nodes.values()) {
+ if (hasCycleDFS(node)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Get nodes with no incoming connections (start nodes)
+ */
+ getStartNodes(): INode[] {
+ const startNodes: INode[] = [];
+
+ for (const node of this.nodes.values()) {
+ const hasIncoming = this.getDirectParentConnections(node).length > 0;
+
+ if (!hasIncoming) {
+ startNodes.push(node);
+ }
+ }
+
+ return startNodes;
+ }
+
+ /**
+ * Get nodes with no outgoing connections (end nodes)
+ */
+ getEndNodes(): INode[] {
+ const endNodes: INode[] = [];
+
+ for (const node of this.nodes.values()) {
+ const hasOutgoing = this.getConnections({ from: node }).length > 0;
+
+ if (!hasOutgoing) {
+ endNodes.push(node);
+ }
+ }
+
+ return endNodes;
+ }
+
+ /**
+ * Extract subgraph from trigger to destination
+ */
+ extractSubgraph(trigger: INode, destination: INode): DirectedGraph {
+ const subgraph = new DirectedGraph();
+
+ // Find all nodes in path from trigger to destination
+ const nodesToInclude = new Set<string>();
+
+ // Start from destination and work backwards to trigger
+ const queue = [destination];
+ const visited = new Set<string>();
+
+ while (queue.length > 0) {
+ const node = queue.shift()!;
+
+ if (visited.has(node.name)) continue;
+ visited.add(node.name);
+ nodesToInclude.add(node.name);
+
+ // If we reached the trigger, continue to find other paths
+ if (node === trigger) continue;
+
+ const parents = this.getDirectParents(node);
+ queue.push(...parents);
+ }
+
+ // Add nodes to subgraph
+ for (const nodeName of nodesToInclude) {
+ const node = this.nodes.get(nodeName);
+ if (node) {
+ subgraph.addNode(node);
+ }
+ }
+
+ // Add connections within subgraph
+ for (const connection of this.connections.values()) {
+ if (
+ nodesToInclude.has(connection.from.name) &&
+ nodesToInclude.has(connection.to.name)
+ ) {
+ subgraph.addConnection(connection);
+ }
+ }
+
+ return subgraph;
+ }
+
+ /**
+ * Clone the graph
+ */
+ clone(): DirectedGraph {
+ const cloned = new DirectedGraph();
+
+ for (const node of this.nodes.values()) {
+ cloned.addNode({ ...node });
+ }
+
+ for (const connection of this.connections.values()) {
+ cloned.addConnection({ ...connection });
+ }
+
+ return cloned;
+ }
+
+ /**
+ * Make connection key
+ */
+ private makeConnectionKey(connection: GraphConnection): GraphKey {
+ return `${connection.from.name}-${connection.type}-${connection.outputIndex}-${connection.inputIndex}-${connection.to.name}`;
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/ExecutionContext.ts b/fincept-terminal-desktop/src/services/nodeSystem/ExecutionContext.ts
new file mode 100644
index 000000000..93476d09e
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/ExecutionContext.ts
@@ -0,0 +1,544 @@
+/**
+ * Execution Context
+ * Provides runtime context and utilities for node execution
+ *
+ * This is what nodes access via 'this' during execution
+ */
+
+import {
+ IExecuteFunctions,
+ INode,
+ INodeExecutionData,
+ IWorkflowDataProxy,
+ ITaskDataConnections,
+ NodeConnectionType,
+ NodeParameterValue,
+ NodeParameterValueType,
+ IGetNodeParameterOptions,
+ IExecuteContextHelpers,
+ IDataObject,
+ IHttpRequestOptions,
+ IPairedItemData,
+ AINodeConnectionType,
+ NodeExecutionHint,
+ IRunData,
+ INodeProperties,
+} from './types';
+import { ExpressionEngine } from './ExpressionEngine';
+import { extractParameterValue } from './ParameterProcessor';
+
+/**
+ * Base execution context class
+ */
+export class BaseExecuteContext {
+ protected workflow: IWorkflowDataProxy;
+ protected node: INode;
+ protected inputData: ITaskDataConnections;
+ protected runData: IRunData;
+ protected runIndex: number;
+ protected executionId: string;
+ protected workflowId: string;
+
+ constructor(
+ workflow: IWorkflowDataProxy,
+ node: INode,
+ inputData: ITaskDataConnections,
+ runData: IRunData,
+ runIndex: number = 0,
+ executionId: string = '',
+ workflowId: string = ''
+ ) {
+ this.workflow = workflow;
+ this.node = node;
+ this.inputData = inputData;
+ this.runData = runData;
+ this.runIndex = runIndex;
+ this.executionId = executionId;
+ this.workflowId = workflowId;
+ }
+
+ getNode(): INode {
+ return this.node;
+ }
+
+ getWorkflow(): IWorkflowDataProxy {
+ return this.workflow;
+ }
+
+ continueOnFail(): boolean {
+ return this.node.continueOnFail ?? false;
+ }
+
+ /**
+ * Get node parameter value with support for dot notation and expressions
+ */
+ getNodeParameter(
+ parameterName: string,
+ itemIndex: number,
+ fallbackValue?: any,
+ options?: IGetNodeParameterOptions
+ ): NodeParameterValueType | object {
+ const value = getNodeParameter(
+ this.node,
+ this.workflow,
+ this.runData,
+ this.runIndex,
+ parameterName,
+ itemIndex,
+ fallbackValue,
+ options
+ );
+
+ // Resolve expressions automatically
+ const inputData = this.getInputItems() || [];
+ const item = inputData[itemIndex] || { json: {} };
+
+ const context = ExpressionEngine.createContext(
+ item,
+ inputData,
+ itemIndex,
+ this.runIndex,
+ this.node.parameters,
+ this.node.name,
+ this.node.type,
+ 'Workflow' // Workflow name not available in IWorkflowDataProxy
+ );
+
+ return ExpressionEngine.resolveValue(value as NodeParameterValue, context);
+ }
+
+ /**
+ * Evaluate expression with full expression engine support
+ */
+ evaluateExpression(expression: string, itemIndex: number): NodeParameterValueType {
+ const inputData = this.getInputItems() || [];
+ const item = inputData[itemIndex] || { json: {} };
+
+ const context = ExpressionEngine.createContext(
+ item,
+ inputData,
+ itemIndex,
+ this.runIndex,
+ this.node.parameters,
+ this.node.name,
+ this.node.type,
+ 'Workflow' // Workflow name not available in IWorkflowDataProxy
+ );
+
+ return ExpressionEngine.resolveValue(expression, context);
+ }
+
+ /**
+ * Get input items from connected nodes
+ */
+ protected getInputItems(
+ inputIndex: number = 0,
+ connectionType: NodeConnectionType = NodeConnectionType.Main
+ ): INodeExecutionData[] | undefined {
+ if (!this.inputData[connectionType]) {
+ return undefined;
+ }
+
+ if (inputIndex >= this.inputData[connectionType].length) {
+ return undefined;
+ }
+
+ return this.inputData[connectionType][inputIndex] ?? undefined;
+ }
+}
+
+/**
+ * Main execution context - used by most nodes
+ */
+export class ExecutionContext extends BaseExecuteContext implements IExecuteFunctions {
+ private executionHints: NodeExecutionHint[] = [];
+ private abortController: AbortController;
+
+ constructor(
+ workflow: IWorkflowDataProxy,
+ node: INode,
+ inputData: ITaskDataConnections,
+ runData: IRunData,
+ runIndex: number = 0,
+ executionId: string = '',
+ workflowId: string = ''
+ ) {
+ super(workflow, node, inputData, runData, runIndex, executionId, workflowId);
+ this.abortController = new AbortController();
+ }
+
+ /**
+ * Get input data from connected nodes
+ */
+ getInputData(
+ inputIndex: number = 0,
+ connectionType: NodeConnectionType = NodeConnectionType.Main
+ ): INodeExecutionData[] {
+ const items = this.getInputItems(inputIndex, connectionType);
+ return items ?? [];
+ }
+
+ /**
+ * Get execution ID
+ */
+ getExecutionId(): string {
+ return this.executionId;
+ }
+
+ /**
+ * Get workflow ID
+ */
+ getWorkflowId(): string {
+ return this.workflowId;
+ }
+
+ /**
+ * Get credentials
+ */
+ async getCredentials(type: string): Promise<IDataObject> {
+ // TODO: Implement credential retrieval
+ // This will integrate with the credential manager
+ return {};
+ }
+
+ /**
+ * Get execution cancel signal
+ */
+ getExecutionCancelSignal(): AbortSignal {
+ return this.abortController.signal;
+ }
+
+ /**
+ * Get input connection data (for AI nodes)
+ */
+ async getInputConnectionData(
+ connectionType: AINodeConnectionType,
+ itemIndex: number
+ ): Promise<unknown> {
+ const items = this.getInputItems(0, connectionType);
+ if (!items || itemIndex >= items.length) {
+ return undefined;
+ }
+
+ return items[itemIndex].json;
+ }
+
+ /**
+ * Add execution hints
+ */
+ addExecutionHints(...hints: NodeExecutionHint[]): void {
+ this.executionHints.push(...hints);
+ }
+
+ /**
+ * Get execution hints
+ */
+ getExecutionHints(): NodeExecutionHint[] {
+ return this.executionHints;
+ }
+
+ /**
+ * Send chunk (for streaming)
+ */
+ async sendChunk?(type: string, itemIndex: number, content?: IDataObject | string): Promise<void> {
+ // TODO: Implement chunk sending for streaming nodes
+ console.log('[ExecutionContext] Chunk sent:', { type, itemIndex, content });
+ }
+
+ /**
+ * Helper functions
+ */
+ helpers: IExecuteContextHelpers = {
+ /**
+ * Make HTTP request
+ */
+ httpRequest: async (options: IHttpRequestOptions): Promise<any> => {
+ const url = options.url;
+ const method = options.method || 'GET';
+
+ const fetchOptions: RequestInit = {
+ method,
+ headers: options.headers as HeadersInit,
+ signal: this.abortController.signal,
+ };
+
+ if (options.body) {
+ if (options.json !== false) {
+ fetchOptions.headers = {
+ ...fetchOptions.headers,
+ 'Content-Type': 'application/json',
+ };
+ fetchOptions.body = JSON.stringify(options.body);
+ } else {
+ fetchOptions.body = options.body;
+ }
+ }
+
+ // Add authentication
+ if (options.auth) {
+ if ('bearer' in options.auth) {
+ fetchOptions.headers = {
+ ...fetchOptions.headers,
+ Authorization: `Bearer ${options.auth.bearer}`,
+ };
+ } else if ('username' in options.auth) {
+ const credentials = btoa(`${options.auth.username}:${options.auth.password}`);
+ fetchOptions.headers = {
+ ...fetchOptions.headers,
+ Authorization: `Basic ${credentials}`,
+ };
+ }
+ }
+
+ // Add query parameters
+ let fullUrl = url;
+ if (options.qs) {
+ const params = new URLSearchParams(options.qs as any);
+ fullUrl = `${url}?${params.toString()}`;
+ }
+
+ try {
+ const response = await fetch(fullUrl, fetchOptions);
+
+ if (!response.ok && !options.ignoreHttpStatusErrors) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
+
+ if (options.returnFullResponse) {
+ const body = options.json !== false ? await response.json() : await response.text();
+
+ // Convert headers to object
+ const headers: Record<string, string> = {};
+ response.headers.forEach((value, key) => {
+ headers[key] = value;
+ });
+
+ return {
+ statusCode: response.status,
+ statusMessage: response.statusText,
+ headers,
+ body,
+ };
+ }
+
+ return options.json !== false ? await response.json() : await response.text();
+ } catch (error: any) {
+ throw new Error(`HTTP Request failed: ${error.message}`);
+ }
+ },
+
+ /**
+ * Convert data to node execution format
+ */
+ returnJsonArray: (items: IDataObject | IDataObject[]): INodeExecutionData[] => {
+ const itemsArray = Array.isArray(items) ? items : [items];
+ return itemsArray.map((json) => ({ json }));
+ },
+
+ /**
+ * Normalize items to ensure consistent format
+ */
+ normalizeItems: (items: INodeExecutionData[]): INodeExecutionData[] => {
+ return items.map((item) => ({
+ json: item.json || {},
+ binary: item.binary,
+ pairedItem: item.pairedItem,
+ error: item.error,
+ metadata: item.metadata,
+ }));
+ },
+
+ /**
+ * Construct execution metadata with paired item tracking
+ */
+ constructExecutionMetaData: (
+ inputData: INodeExecutionData[],
+ options: { itemData: IPairedItemData | IPairedItemData[] }
+ ): INodeExecutionData[] => {
+ return inputData.map((item, index) => {
+ const pairedItem = Array.isArray(options.itemData)
+ ? options.itemData[index] || options.itemData[0]
+ : options.itemData;
+
+ return {
+ ...item,
+ pairedItem,
+ };
+ });
+ },
+ };
+}
+
+/**
+ * Load options context - for loading dynamic parameter options
+ */
+export class LoadOptionsContext extends BaseExecuteContext {
+ private currentNodeParameters?: IDataObject;
+
+ constructor(
+ workflow: IWorkflowDataProxy,
+ node: INode,
+ inputData: ITaskDataConnections,
+ runData: IRunData,
+ currentNodeParameters?: IDataObject
+ ) {
+ super(workflow, node, inputData, runData);
+ this.currentNodeParameters = currentNodeParameters;
+ }
+
+ /**
+ * Get current node parameter (partial parameters during configuration)
+ */
+ getCurrentNodeParameter(parameterName: string): NodeParameterValueType | object | undefined {
+ if (!this.currentNodeParameters) {
+ return undefined;
+ }
+
+ return getParameterValue(this.currentNodeParameters, parameterName.split('.'));
+ }
+
+ /**
+ * Get all current node parameters
+ */
+ getCurrentNodeParameters(): IDataObject | undefined {
+ return this.currentNodeParameters;
+ }
+}
+
+// ================================
+// HELPER FUNCTIONS
+// ================================
+
+/**
+ * Get node parameter value
+ */
+export function getNodeParameter(
+ node: INode,
+ workflow: IWorkflowDataProxy,
+ runData: IRunData,
+ runIndex: number,
+ parameterName: string,
+ itemIndex: number,
+ fallbackValue?: any,
+ options?: IGetNodeParameterOptions
+): NodeParameterValueType | object {
+ // Parse parameter path (support dot notation)
+ const parameterPath = parameterName.split('.');
+
+ // Get from node parameters
+ let value = getParameterValue(node.parameters, parameterPath);
+
+ // Apply fallback if undefined
+ if (value === undefined) {
+ value = fallbackValue;
+ }
+
+ // Note: Expression evaluation is handled in BaseExecuteContext.getNodeParameter
+ // which calls this function and then applies ExpressionEngine.resolveValue
+
+ // Extract value if configured (for complex objects)
+ if (options?.extractValue && value !== undefined && value !== null) {
+ // Find the parameter definition to get extractValue config
+ const paramDef = findParameterDefinition(node, parameterName);
+ if (paramDef?.extractValue) {
+ value = extractParameterValue(value, paramDef.extractValue);
+ }
+ }
+
+ return value;
+}
+
+/**
+ * Get parameter value from object using path array
+ */
+function getParameterValue(
+ parameters: IDataObject,
+ path: string[]
+): NodeParameterValueType | object | undefined {
+ let current: any = parameters;
+
+ for (const segment of path) {
+ if (current === undefined || current === null) {
+ return undefined;
+ }
+
+ // Handle array indices: values[0]
+ const arrayMatch = segment.match(/^(.+)\[(\d+)\]$/);
+ if (arrayMatch) {
+ const [, key, index] = arrayMatch;
+ current = current[key];
+
+ if (!Array.isArray(current)) {
+ return undefined;
+ }
+
+ current = current[parseInt(index, 10)];
+ } else {
+ current = current[segment];
+ }
+ }
+
+ return current;
+}
+
+/**
+ * Set parameter value in object using path array
+ */
+export function setParameterValue(
+ parameters: IDataObject,
+ path: string[],
+ value: any
+): void {
+ let current: any = parameters;
+
+ for (let i = 0; i < path.length - 1; i++) {
+ const segment = path[i];
+
+ // Handle array indices
+ const arrayMatch = segment.match(/^(.+)\[(\d+)\]$/);
+ if (arrayMatch) {
+ const [, key, index] = arrayMatch;
+
+ if (!current[key]) {
+ current[key] = [];
+ }
+
+ const idx = parseInt(index, 10);
+ if (!current[key][idx]) {
+ current[key][idx] = {};
+ }
+
+ current = current[key][idx];
+ } else {
+ if (!current[segment]) {
+ current[segment] = {};
+ }
+ current = current[segment];
+ }
+ }
+
+ // Set final value
+ const lastSegment = path[path.length - 1];
+ const arrayMatch = lastSegment.match(/^(.+)\[(\d+)\]$/);
+
+ if (arrayMatch) {
+ const [, key, index] = arrayMatch;
+ if (!current[key]) {
+ current[key] = [];
+ }
+ current[key][parseInt(index, 10)] = value;
+ } else {
+ current[lastSegment] = value;
+ }
+}
+
+
+/**
+ * Find parameter definition in node type
+ */
+function findParameterDefinition(node: INode, parameterName: string): INodeProperties | undefined {
+ // This would require access to the node type definition
+ // For now, return undefined - nodes can use extractValue option explicitly
+ // In the future, this could query NodeRegistry.getNodeType(node.type)
+ return undefined;
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/ExecutionHooks.ts b/fincept-terminal-desktop/src/services/nodeSystem/ExecutionHooks.ts
new file mode 100644
index 000000000..dd2aaed5f
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/ExecutionHooks.ts
@@ -0,0 +1,521 @@
+/**
+ * Execution Hooks System
+ * Provides lifecycle hooks and events for node execution
+ *
+ * Hooks allow external code to:
+ * - Monitor workflow and node execution
+ * - Intercept and modify execution flow
+ * - Add custom logging and debugging
+ * - Implement custom error handling
+ * - Track performance metrics
+ * - Implement audit trails
+ *
+ * Based on common event-driven architecture patterns.
+ */
+
+import type {
+ INode,
+ INodeExecutionData,
+ IRunExecutionData,
+ IWorkflow,
+ NodeError,
+} from './types';
+
+/**
+ * Hook event types
+ */
+export enum HookEventType {
+ // Workflow-level events
+ WorkflowExecuteStart = 'workflow.executeStart',
+ WorkflowExecuteEnd = 'workflow.executeEnd',
+ WorkflowExecuteError = 'workflow.executeError',
+
+ // Node-level events
+ NodeExecuteStart = 'node.executeStart',
+ NodeExecuteEnd = 'node.executeEnd',
+ NodeExecuteError = 'node.executeError',
+
+ // Item-level events
+ ItemProcessStart = 'item.processStart',
+ ItemProcessEnd = 'item.processEnd',
+ ItemProcessError = 'item.processError',
+
+ // Data-level events
+ DataReceived = 'data.received',
+ DataSent = 'data.sent',
+
+ // Performance events
+ PerformanceMetric = 'performance.metric',
+
+ // Custom events
+ Custom = 'custom',
+}
+
+/**
+ * Hook event data
+ */
+export interface IHookEvent {
+ type: HookEventType;
+ timestamp: Date;
+ executionId: string;
+ workflowId?: string;
+ nodeName?: string;
+ data?: any;
+ metadata?: Record<string, any>;
+}
+
+/**
+ * Workflow execution start event
+ */
+export interface IWorkflowExecuteStartEvent extends IHookEvent {
+ type: HookEventType.WorkflowExecuteStart;
+ workflow: IWorkflow;
+ startNode?: string;
+}
+
+/**
+ * Workflow execution end event
+ */
+export interface IWorkflowExecuteEndEvent extends IHookEvent {
+ type: HookEventType.WorkflowExecuteEnd;
+ workflow: IWorkflow;
+ executionData: IRunExecutionData;
+ success: boolean;
+ duration: number; // milliseconds
+}
+
+/**
+ * Workflow execution error event
+ */
+export interface IWorkflowExecuteErrorEvent extends IHookEvent {
+ type: HookEventType.WorkflowExecuteError;
+ workflow: IWorkflow;
+ error: Error | NodeError;
+ nodeName?: string;
+}
+
+/**
+ * Node execution start event
+ */
+export interface INodeExecuteStartEvent extends IHookEvent {
+ type: HookEventType.NodeExecuteStart;
+ node: INode;
+ inputData: INodeExecutionData[];
+}
+
+/**
+ * Node execution end event
+ */
+export interface INodeExecuteEndEvent extends IHookEvent {
+ type: HookEventType.NodeExecuteEnd;
+ node: INode;
+ outputData: INodeExecutionData[][];
+ duration: number; // milliseconds
+}
+
+/**
+ * Node execution error event
+ */
+export interface INodeExecuteErrorEvent extends IHookEvent {
+ type: HookEventType.NodeExecuteError;
+ node: INode;
+ error: Error | NodeError;
+ continueOnFail: boolean;
+}
+
+/**
+ * Performance metric event
+ */
+export interface IPerformanceMetricEvent extends IHookEvent {
+ type: HookEventType.PerformanceMetric;
+ metric: {
+ name: string;
+ value: number;
+ unit: string;
+ tags?: Record<string, string>;
+ };
+}
+
+/**
+ * Hook function signature
+ */
+export type HookFunction = (event: IHookEvent) => void | Promise<void>;
+
+/**
+ * Hook options
+ */
+export interface IHookOptions {
+ once?: boolean; // Execute only once
+ priority?: number; // Higher priority = earlier execution
+ filter?: {
+ nodes?: string[]; // Only for specific nodes
+ workflows?: string[]; // Only for specific workflows
+ eventTypes?: HookEventType[]; // Only for specific event types
+ };
+}
+
+/**
+ * Hook registration
+ */
+interface IHookRegistration {
+ id: string;
+ eventType: HookEventType | '*'; // '*' = all events
+ handler: HookFunction;
+ options: IHookOptions;
+ executionCount: number;
+}
+
+/**
+ * Execution Hooks Manager
+ * Central registry for all execution hooks
+ */
+export class ExecutionHooksManager {
+ private hooks: Map<string, IHookRegistration> = new Map();
+ private nextHookId = 1;
+ private enabled = true;
+
+ /**
+ * Register a hook
+ */
+ on(
+ eventType: HookEventType | '*',
+ handler: HookFunction,
+ options: IHookOptions = {}
+ ): string {
+ const hookId = `hook_${this.nextHookId++}`;
+
+ this.hooks.set(hookId, {
+ id: hookId,
+ eventType,
+ handler,
+ options,
+ executionCount: 0,
+ });
+
+ return hookId;
+ }
+
+ /**
+ * Register a one-time hook
+ */
+ once(eventType: HookEventType | '*', handler: HookFunction, options: IHookOptions = {}): string {
+ return this.on(eventType, handler, { ...options, once: true });
+ }
+
+ /**
+ * Remove a hook
+ */
+ off(hookId: string): boolean {
+ return this.hooks.delete(hookId);
+ }
+
+ /**
+ * Remove all hooks for an event type
+ */
+ offAll(eventType?: HookEventType | '*'): void {
+ if (eventType) {
+ for (const [id, hook] of this.hooks.entries()) {
+ if (hook.eventType === eventType) {
+ this.hooks.delete(id);
+ }
+ }
+ } else {
+ this.hooks.clear();
+ }
+ }
+
+ /**
+ * Emit an event to all registered hooks
+ */
+ async emit(event: IHookEvent): Promise<void> {
+ if (!this.enabled) {
+ return;
+ }
+
+ // Get matching hooks
+ const matchingHooks = this.getMatchingHooks(event);
+
+ // Sort by priority (higher first)
+ matchingHooks.sort((a, b) => (b.options.priority || 0) - (a.options.priority || 0));
+
+ // Execute hooks
+ for (const hook of matchingHooks) {
+ try {
+ await hook.handler(event);
+ hook.executionCount++;
+
+ // Remove if once
+ if (hook.options.once) {
+ this.hooks.delete(hook.id);
+ }
+ } catch (error) {
+ console.error(`[ExecutionHooks] Hook ${hook.id} failed:`, error);
+ // Don't throw - hooks shouldn't break execution
+ }
+ }
+ }
+
+ /**
+ * Emit event synchronously (non-blocking)
+ */
+ emitSync(event: IHookEvent): void {
+ // Fire and forget
+ this.emit(event).catch((error) => {
+ console.error('[ExecutionHooks] Async emit failed:', error);
+ });
+ }
+
+ /**
+ * Get matching hooks for an event
+ */
+ private getMatchingHooks(event: IHookEvent): IHookRegistration[] {
+ const matching: IHookRegistration[] = [];
+
+ for (const hook of this.hooks.values()) {
+ // Check event type
+ if (hook.eventType !== '*' && hook.eventType !== event.type) {
+ continue;
+ }
+
+ // Check filters
+ if (hook.options.filter) {
+ const { nodes, workflows, eventTypes } = hook.options.filter;
+
+ if (eventTypes && !eventTypes.includes(event.type)) {
+ continue;
+ }
+
+ if (nodes && event.nodeName && !nodes.includes(event.nodeName)) {
+ continue;
+ }
+
+ if (workflows && event.workflowId && !workflows.includes(event.workflowId)) {
+ continue;
+ }
+ }
+
+ matching.push(hook);
+ }
+
+ return matching;
+ }
+
+ /**
+ * Get all registered hooks
+ */
+ getHooks(): IHookRegistration[] {
+ return Array.from(this.hooks.values());
+ }
+
+ /**
+ * Get hook statistics
+ */
+ getStats(): {
+ totalHooks: number;
+ hooksByType: Record<string, number>;
+ totalExecutions: number;
+ } {
+ const hooksByType: Record<string, number> = {};
+ let totalExecutions = 0;
+
+ for (const hook of this.hooks.values()) {
+ const type = hook.eventType;
+ hooksByType[type] = (hooksByType[type] || 0) + 1;
+ totalExecutions += hook.executionCount;
+ }
+
+ return {
+ totalHooks: this.hooks.size,
+ hooksByType,
+ totalExecutions,
+ };
+ }
+
+ /**
+ * Enable/disable hooks
+ */
+ setEnabled(enabled: boolean): void {
+ this.enabled = enabled;
+ }
+
+ /**
+ * Check if hooks are enabled
+ */
+ isEnabled(): boolean {
+ return this.enabled;
+ }
+
+ /**
+ * Clear all hooks
+ */
+ clear(): void {
+ this.hooks.clear();
+ }
+}
+
+/**
+ * Global hooks manager instance
+ */
+export const globalHooks = new ExecutionHooksManager();
+
+/**
+ * Convenience functions for common hooks
+ */
+export const hooks = {
+ /**
+ * Register workflow start hook
+ */
+ onWorkflowStart(
+ handler: (event: IWorkflowExecuteStartEvent) => void | Promise<void>,
+ options?: IHookOptions
+ ): string {
+ return globalHooks.on(HookEventType.WorkflowExecuteStart, handler as HookFunction, options);
+ },
+
+ /**
+ * Register workflow end hook
+ */
+ onWorkflowEnd(
+ handler: (event: IWorkflowExecuteEndEvent) => void | Promise<void>,
+ options?: IHookOptions
+ ): string {
+ return globalHooks.on(HookEventType.WorkflowExecuteEnd, handler as HookFunction, options);
+ },
+
+ /**
+ * Register workflow error hook
+ */
+ onWorkflowError(
+ handler: (event: IWorkflowExecuteErrorEvent) => void | Promise<void>,
+ options?: IHookOptions
+ ): string {
+ return globalHooks.on(HookEventType.WorkflowExecuteError, handler as HookFunction, options);
+ },
+
+ /**
+ * Register node start hook
+ */
+ onNodeStart(
+ handler: (event: INodeExecuteStartEvent) => void | Promise<void>,
+ options?: IHookOptions
+ ): string {
+ return globalHooks.on(HookEventType.NodeExecuteStart, handler as HookFunction, options);
+ },
+
+ /**
+ * Register node end hook
+ */
+ onNodeEnd(
+ handler: (event: INodeExecuteEndEvent) => void | Promise<void>,
+ options?: IHookOptions
+ ): string {
+ return globalHooks.on(HookEventType.NodeExecuteEnd, handler as HookFunction, options);
+ },
+
+ /**
+ * Register node error hook
+ */
+ onNodeError(
+ handler: (event: INodeExecuteErrorEvent) => void | Promise<void>,
+ options?: IHookOptions
+ ): string {
+ return globalHooks.on(HookEventType.NodeExecuteError, handler as HookFunction, options);
+ },
+
+ /**
+ * Register performance metric hook
+ */
+ onPerformanceMetric(
+ handler: (event: IPerformanceMetricEvent) => void | Promise<void>,
+ options?: IHookOptions
+ ): string {
+ return globalHooks.on(HookEventType.PerformanceMetric, handler as HookFunction, options);
+ },
+
+ /**
+ * Register hook for all events
+ */
+ onAll(handler: HookFunction, options?: IHookOptions): string {
+ return globalHooks.on('*', handler, options);
+ },
+
+ /**
+ * Remove a hook
+ */
+ off(hookId: string): boolean {
+ return globalHooks.off(hookId);
+ },
+
+ /**
+ * Remove all hooks
+ */
+ clear(): void {
+ globalHooks.clear();
+ },
+};
+
+/**
+ * Performance tracker using hooks
+ */
+export class PerformanceTracker {
+ private startTimes: Map<string, number> = new Map();
+
+ /**
+ * Start tracking
+ */
+ start(key: string): void {
+ this.startTimes.set(key, Date.now());
+ }
+
+ /**
+ * End tracking and emit metric
+ */
+ end(key: string, executionId: string, metadata?: Record<string, any>): void {
+ const startTime = this.startTimes.get(key);
+ if (!startTime) {
+ return;
+ }
+
+ const duration = Date.now() - startTime;
+ this.startTimes.delete(key);
+
+ globalHooks.emitSync({
+ type: HookEventType.PerformanceMetric,
+ timestamp: new Date(),
+ executionId,
+ metadata,
+ data: {
+ metric: {
+ name: key,
+ value: duration,
+ unit: 'ms',
+ tags: metadata,
+ },
+ },
+ } as IPerformanceMetricEvent);
+ }
+
+ /**
+ * Measure execution time of a function
+ */
+ async measure<T>(
+ key: string,
+ executionId: string,
+ fn: () => Promise<T>,
+ metadata?: Record<string, any>
+ ): Promise<T> {
+ this.start(key);
+ try {
+ return await fn();
+ } finally {
+ this.end(key, executionId, metadata);
+ }
+ }
+}
+
+/**
+ * Create a performance tracker instance
+ */
+export function createPerformanceTracker(): PerformanceTracker {
+ return new PerformanceTracker();
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/ExpressionEngine.ts b/fincept-terminal-desktop/src/services/nodeSystem/ExpressionEngine.ts
new file mode 100644
index 000000000..19a915821
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/ExpressionEngine.ts
@@ -0,0 +1,384 @@
+/**
+ * Expression Engine
+ * Evaluates expressions in node parameters
+ *
+ * Supports expression syntax like:
+ * - {{$json.fieldName}} - Access JSON fields
+ * - {{$json["field name"]}} - Access fields with special characters
+ * - {{$json.nested.field}} - Nested field access
+ * - {{$input.item.json.field}} - Explicit input access
+ * - {{$parameter.paramName}} - Access other parameters
+ * - {{1 + 2}} - Basic arithmetic
+ * - {{$json.price * 1.1}} - Expressions with data
+ * - {{$now}} - Current datetime
+ * - {{$today}} - Current date
+ *
+ * Based on n8n's expression system but simplified for core functionality.
+ */
+
+import type {
+ IDataObject,
+ INodeExecutionData,
+ INodeParameters,
+ NodeParameterValue,
+} from './types';
+
+/**
+ * Check if a value contains an expression
+ */
+export function isExpression(value: any): boolean {
+ if (typeof value !== 'string') {
+ return false;
+ }
+
+ // Expression starts with = or contains {{...}}
+ return value.startsWith('=') || /\{\{.+?\}\}/.test(value);
+}
+
+/**
+ * Expression evaluation context
+ */
+export interface IExpressionContext {
+ $json: IDataObject; // Current item's JSON data
+ $input: { // Input data
+ item: INodeExecutionData;
+ all: INodeExecutionData[];
+ first: INodeExecutionData;
+ last: INodeExecutionData;
+ };
+ $parameter: INodeParameters; // Node parameters
+ $now: Date; // Current datetime
+ $today: Date; // Today at midnight
+ $itemIndex: number; // Current item index
+ $runIndex: number; // Current run index
+ $node: { // Current node info
+ name: string;
+ type: string;
+ };
+ $workflow: { // Workflow info
+ name: string;
+ active: boolean;
+ id?: string;
+ };
+}
+
+/**
+ * Expression Engine
+ * Evaluates expressions with access to workflow data
+ */
+export class ExpressionEngine {
+ /**
+ * Resolve a parameter value that may contain expressions
+ */
+ static resolveValue(
+ value: NodeParameterValue,
+ context: Partial<IExpressionContext>
+ ): NodeParameterValue {
+ if (!isExpression(value)) {
+ return value;
+ }
+
+ if (typeof value !== 'string') {
+ return value;
+ }
+
+ try {
+ // Handle = prefix (entire value is an expression)
+ if (value.startsWith('=')) {
+ const expression = value.substring(1).trim();
+ return this.evaluateExpression(expression, context);
+ }
+
+ // Handle {{...}} syntax (can have multiple in one string)
+ return this.replaceExpressions(value, context);
+ } catch (error) {
+ console.error('[ExpressionEngine] Error evaluating expression:', error);
+ return value; // Return original value on error
+ }
+ }
+
+ /**
+ * Replace all {{...}} expressions in a string
+ */
+ private static replaceExpressions(
+ str: string,
+ context: Partial<IExpressionContext>
+ ): string {
+ return str.replace(/\{\{(.+?)\}\}/g, (match, expression) => {
+ try {
+ const result = this.evaluateExpression(expression.trim(), context);
+ return String(result ?? '');
+ } catch (error) {
+ console.warn('[ExpressionEngine] Failed to evaluate:', expression, error);
+ return match; // Return original on error
+ }
+ });
+ }
+
+ /**
+ * Evaluate a single expression
+ */
+ private static evaluateExpression(
+ expression: string,
+ context: Partial<IExpressionContext>
+ ): any {
+ // Handle special variables
+ if (expression === '$now') {
+ return context.$now || new Date();
+ }
+ if (expression === '$today') {
+ const today = context.$today || new Date();
+ today.setHours(0, 0, 0, 0);
+ return today;
+ }
+ if (expression === '$itemIndex') {
+ return context.$itemIndex ?? 0;
+ }
+ if (expression === '$runIndex') {
+ return context.$runIndex ?? 0;
+ }
+
+ // Handle object property access
+ if (expression.startsWith('$json.')) {
+ const path = expression.substring(6);
+ return this.getNestedValue(context.$json || {}, path);
+ }
+ if (expression.startsWith('$json[')) {
+ // Handle bracket notation: $json["field name"]
+ const match = expression.match(/\$json\["(.+?)"\]/);
+ if (match) {
+ return (context.$json || {})[match[1]];
+ }
+ }
+ if (expression.startsWith('$input.item.json.')) {
+ const path = expression.substring(17);
+ return this.getNestedValue(context.$input?.item?.json || {}, path);
+ }
+ if (expression.startsWith('$input.first.json.')) {
+ const path = expression.substring(18);
+ return this.getNestedValue(context.$input?.first?.json || {}, path);
+ }
+ if (expression.startsWith('$input.last.json.')) {
+ const path = expression.substring(17);
+ return this.getNestedValue(context.$input?.last?.json || {}, path);
+ }
+ if (expression.startsWith('$parameter.')) {
+ const paramName = expression.substring(11);
+ return (context.$parameter || {})[paramName];
+ }
+ if (expression.startsWith('$node.')) {
+ const prop = expression.substring(6);
+ return (context.$node as any)?.[prop];
+ }
+ if (expression.startsWith('$workflow.')) {
+ const prop = expression.substring(10);
+ return (context.$workflow as any)?.[prop];
+ }
+
+ // Handle complex expressions with JavaScript evaluation
+ // This is where we evaluate arithmetic, comparisons, etc.
+ return this.evaluateJavaScript(expression, context);
+ }
+
+ /**
+ * Evaluate a JavaScript expression
+ * IMPORTANT: Sanitized execution with limited scope
+ */
+ private static evaluateJavaScript(
+ expression: string,
+ context: Partial<IExpressionContext>
+ ): any {
+ try {
+ // Create safe execution context
+ const $json = context.$json || {};
+ const $input = context.$input;
+ const $parameter = context.$parameter || {};
+ const $now = context.$now || new Date();
+ const $today = (() => {
+ const date = new Date();
+ date.setHours(0, 0, 0, 0);
+ return date;
+ })();
+ const $itemIndex = context.$itemIndex ?? 0;
+ const $runIndex = context.$runIndex ?? 0;
+ const $node = context.$node;
+ const $workflow = context.$workflow;
+
+ // Helper functions available in expressions
+ const helpers = {
+ // Date helpers
+ DateTime: Date,
+ now: () => new Date(),
+ today: () => {
+ const d = new Date();
+ d.setHours(0, 0, 0, 0);
+ return d;
+ },
+
+ // String helpers
+ toLowerCase: (str: string) => String(str).toLowerCase(),
+ toUpperCase: (str: string) => String(str).toUpperCase(),
+ trim: (str: string) => String(str).trim(),
+ split: (str: string, separator: string) => String(str).split(separator),
+ substring: (str: string, start: number, end?: number) =>
+ String(str).substring(start, end),
+
+ // Number helpers
+ toNumber: (val: any) => Number(val),
+ toFixed: (num: number, decimals: number) => Number(num).toFixed(decimals),
+ round: (num: number) => Math.round(num),
+ floor: (num: number) => Math.floor(num),
+ ceil: (num: number) => Math.ceil(num),
+ abs: (num: number) => Math.abs(num),
+
+ // Array helpers
+ length: (arr: any) => (Array.isArray(arr) ? arr.length : 0),
+ first: (arr: any[]) => arr[0],
+ last: (arr: any[]) => arr[arr.length - 1],
+ join: (arr: any[], separator: string) => arr.join(separator),
+
+ // Object helpers
+ keys: (obj: object) => Object.keys(obj),
+ values: (obj: object) => Object.values(obj),
+ has: (obj: object, key: string) => key in obj,
+
+ // Conditional helpers
+ isEmpty: (val: any) =>
+ val === null || val === undefined || val === '' || (Array.isArray(val) && val.length === 0),
+ isNotEmpty: (val: any) =>
+ val !== null && val !== undefined && val !== '' && (!Array.isArray(val) || val.length > 0),
+ };
+
+ // Use Function constructor for safe evaluation
+ // This creates a new function scope with only the variables we provide
+ const func = new Function(
+ '$json',
+ '$input',
+ '$parameter',
+ '$now',
+ '$today',
+ '$itemIndex',
+ '$runIndex',
+ '$node',
+ '$workflow',
+ 'helpers',
+ 'Math',
+ 'String',
+ 'Number',
+ 'Array',
+ 'Object',
+ 'Date',
+ `'use strict'; return (${expression});`
+ );
+
+ return func(
+ $json,
+ $input,
+ $parameter,
+ $now,
+ $today,
+ $itemIndex,
+ $runIndex,
+ $node,
+ $workflow,
+ helpers,
+ Math,
+ String,
+ Number,
+ Array,
+ Object,
+ Date
+ );
+ } catch (error) {
+ console.error('[ExpressionEngine] JavaScript evaluation error:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Get nested value from object using dot notation
+ */
+ private static getNestedValue(obj: IDataObject, path: string): any {
+ const keys = path.split('.');
+ let current: any = obj;
+
+ for (const key of keys) {
+ if (current === null || current === undefined) {
+ return undefined;
+ }
+ current = current[key];
+ }
+
+ return current;
+ }
+
+ /**
+ * Create expression context from execution data
+ */
+ static createContext(
+ item: INodeExecutionData,
+ allItems: INodeExecutionData[],
+ itemIndex: number,
+ runIndex: number,
+ parameters: INodeParameters,
+ nodeName: string,
+ nodeType: string,
+ workflowName: string = 'Workflow'
+ ): IExpressionContext {
+ return {
+ $json: item.json,
+ $input: {
+ item: item,
+ all: allItems,
+ first: allItems[0],
+ last: allItems[allItems.length - 1],
+ },
+ $parameter: parameters,
+ $now: new Date(),
+ $today: (() => {
+ const date = new Date();
+ date.setHours(0, 0, 0, 0);
+ return date;
+ })(),
+ $itemIndex: itemIndex,
+ $runIndex: runIndex,
+ $node: {
+ name: nodeName,
+ type: nodeType,
+ },
+ $workflow: {
+ name: workflowName,
+ active: true,
+ },
+ };
+ }
+
+ /**
+ * Resolve all parameters in an object
+ * Recursively resolves nested objects and arrays
+ */
+ static resolveParameters(
+ parameters: INodeParameters,
+ context: Partial<IExpressionContext>
+ ): INodeParameters {
+ const resolved: INodeParameters = {};
+
+ for (const [key, value] of Object.entries(parameters)) {
+ if (value === null || value === undefined) {
+ resolved[key] = value;
+ } else if (Array.isArray(value)) {
+ resolved[key] = value.map((item) =>
+ typeof item === 'object' && item !== null
+ ? this.resolveParameters(item as INodeParameters, context)
+ : this.resolveValue(item, context)
+ );
+ } else if (typeof value === 'object') {
+ resolved[key] = this.resolveParameters(value as INodeParameters, context);
+ } else {
+ resolved[key] = this.resolveValue(value, context);
+ }
+ }
+
+ return resolved;
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts b/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts
new file mode 100644
index 000000000..e1c44c86e
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts
@@ -0,0 +1,183 @@
+/**
+ * Node Loader
+ * Automatically discovers and registers all available nodes
+ *
+ * This module handles:
+ * - Loading node definitions from the nodes directory
+ * - Registering nodes with the Node Registry
+ * - Providing a centralized initialization point
+ */
+
+import { NodeRegistry } from './NodeRegistry';
+import { INodeType } from './types';
+
+// Import finance nodes
+import { StockDataNode } from '../../nodes/finance/StockData.node';
+
+// Import core nodes
+import { FilterNode } from '../../nodes/core/Filter.node';
+import { MergeNode } from '../../nodes/core/Merge.node';
+import { SetNode } from '../../nodes/core/Set.node';
+import { SwitchNode } from '../../nodes/core/Switch.node';
+import { CodeNode } from '../../nodes/core/Code.node';
+
+/**
+ * Node Loader Class
+ */
+class NodeLoaderClass {
+ private loaded: boolean = false;
+ private loadedNodes: Map<string, INodeType> = new Map();
+
+ /**
+ * Load all available nodes
+ */
+ async loadAll(): Promise<void> {
+ if (this.loaded) {
+ console.log('[NodeLoader] Nodes already loaded, skipping...');
+ return;
+ }
+
+ console.log('[NodeLoader] Starting node loading...');
+
+ // Load core nodes
+ await this.loadCoreNodes();
+
+ // Load finance nodes
+ await this.loadFinanceNodes();
+
+ // Load integration nodes (will be added later)
+ // await this.loadIntegrationNodes();
+
+ // Load AI nodes (will be added later)
+ // await this.loadAINodes();
+
+ this.loaded = true;
+
+ // Print statistics
+ const stats = NodeRegistry.getStatistics();
+ console.log('[NodeLoader] Loading complete!');
+ console.log(` - Total node types: ${stats.totalNodeTypes}`);
+ console.log(` - Total versions: ${stats.totalVersions}`);
+ console.log(' - Node types:');
+ stats.nodeTypes.forEach((nt) => {
+ console.log(` • ${nt.name} (${nt.versions} version${nt.versions > 1 ? 's' : ''})`);
+ });
+ }
+
+ /**
+ * Load core nodes (basic workflow nodes)
+ */
+ private async loadCoreNodes(): Promise<void> {
+ console.log('[NodeLoader] Loading core nodes...');
+
+ try {
+ // Filter Node - Remove items based on conditions
+ const filterNode = new FilterNode();
+ NodeRegistry.registerNodeType(filterNode, 'FilterNode');
+ this.loadedNodes.set('filter', filterNode);
+
+ // Merge Node - Combine data from multiple inputs
+ const mergeNode = new MergeNode();
+ NodeRegistry.registerNodeType(mergeNode, 'MergeNode');
+ this.loadedNodes.set('merge', mergeNode);
+
+ // Set Node - Add/edit/remove fields
+ const setNode = new SetNode();
+ NodeRegistry.registerNodeType(setNode, 'SetNode');
+ this.loadedNodes.set('set', setNode);
+
+ // Switch Node - Route items based on conditions
+ const switchNode = new SwitchNode();
+ NodeRegistry.registerNodeType(switchNode, 'SwitchNode');
+ this.loadedNodes.set('switch', switchNode);
+
+ // Code Node - Execute custom JavaScript
+ const codeNode = new CodeNode();
+ NodeRegistry.registerNodeType(codeNode, 'CodeNode');
+ this.loadedNodes.set('code', codeNode);
+
+ console.log('[NodeLoader] Core nodes loaded (5 nodes)');
+ } catch (error) {
+ console.error('[NodeLoader] Error loading core nodes:', error);
+ }
+ }
+
+ /**
+ * Load finance-specific nodes
+ */
+ private async loadFinanceNodes(): Promise<void> {
+ console.log('[NodeLoader] Loading finance nodes...');
+
+ try {
+ // Stock Data Node
+ const stockDataNode = new StockDataNode();
+ NodeRegistry.registerNodeType(stockDataNode, 'StockDataNode');
+ this.loadedNodes.set('stockData', stockDataNode);
+
+ // More finance nodes will be added:
+ // - TechnicalIndicators Node
+ // - PortfolioOptimizer Node
+ // - RiskCalculator Node
+ // - BacktestStrategy Node
+ // - OptionsAnalysis Node
+ // - FundamentalAnalysis Node
+ // - SentimentAnalysis Node
+ // - EconomicData Node
+
+ console.log('[NodeLoader] Finance nodes loaded (1 node)');
+ } catch (error) {
+ console.error('[NodeLoader] Error loading finance nodes:', error);
+ }
+ }
+
+ /**
+ * Get loaded node instance
+ */
+ getNode(nodeTypeName: string): INodeType | undefined {
+ return this.loadedNodes.get(nodeTypeName);
+ }
+
+ /**
+ * Check if loader has been initialized
+ */
+ isLoaded(): boolean {
+ return this.loaded;
+ }
+
+ /**
+ * Reload all nodes (for development)
+ */
+ async reload(): Promise<void> {
+ console.log('[NodeLoader] Reloading all nodes...');
+ this.loaded = false;
+ this.loadedNodes.clear();
+ NodeRegistry.clear();
+ await this.loadAll();
+ }
+
+ /**
+ * Get all loaded node names
+ */
+ getLoadedNodeNames(): string[] {
+ return Array.from(this.loadedNodes.keys());
+ }
+}
+
+// Export singleton instance
+export const NodeLoader = new NodeLoaderClass();
+
+/**
+ * Initialize the node system
+ * Call this once during app startup
+ */
+export async function initializeNodeSystem(): Promise<void> {
+ console.log('[NodeSystem] Initializing...');
+
+ try {
+ await NodeLoader.loadAll();
+ console.log('[NodeSystem] Initialization complete!');
+ } catch (error) {
+ console.error('[NodeSystem] Initialization failed:', error);
+ throw error;
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/NodeRegistry.ts b/fincept-terminal-desktop/src/services/nodeSystem/NodeRegistry.ts
new file mode 100644
index 000000000..11439b49c
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/NodeRegistry.ts
@@ -0,0 +1,331 @@
+/**
+ * Node Registry
+ * Central registry for all node types in the system
+ *
+ * Manages node type registration, versioning, and retrieval
+ */
+
+import { INodeType, INodeTypeDescription, IVersionedNodeType } from './types';
+
+/**
+ * Registry entry for a node type
+ */
+interface INodeTypeRegistry {
+ [nodeType: string]: {
+ versions: {
+ [version: number]: INodeType;
+ };
+ latestVersion: number;
+ className: string;
+ };
+}
+
+/**
+ * Node Registry Class
+ * Singleton pattern for managing node types
+ */
+class NodeRegistryClass {
+ private registry: INodeTypeRegistry = {};
+ private loadedNodeTypes: Set<string> = new Set();
+
+ /**
+ * Register a node type
+ */
+ registerNodeType(nodeType: INodeType, className?: string): void {
+ const description = nodeType.description;
+ const versions = Array.isArray(description.version)
+ ? description.version
+ : [description.version];
+
+ // Get node type name
+ const nodeTypeName = description.name;
+
+ // Initialize registry entry if needed
+ if (!this.registry[nodeTypeName]) {
+ this.registry[nodeTypeName] = {
+ versions: {},
+ latestVersion: Math.max(...versions),
+ className: className || nodeTypeName,
+ };
+ }
+
+ // Register each version
+ for (const version of versions) {
+ this.registry[nodeTypeName].versions[version] = nodeType;
+
+ // Update latest version
+ if (version > this.registry[nodeTypeName].latestVersion) {
+ this.registry[nodeTypeName].latestVersion = version;
+ }
+ }
+
+ this.loadedNodeTypes.add(nodeTypeName);
+
+ console.log(
+ `[NodeRegistry] Registered ${nodeTypeName} versions: ${versions.join(', ')}`
+ );
+ }
+
+ /**
+ * Register a versioned node type
+ */
+ registerVersionedNodeType(versionedNodeType: IVersionedNodeType, className?: string): void {
+ const versions = Object.keys(versionedNodeType.nodeVersions).map(Number);
+ const nodeTypeName = versionedNodeType.nodeVersions[versions[0]].description.name;
+
+ // Initialize registry entry
+ this.registry[nodeTypeName] = {
+ versions: {},
+ latestVersion: Math.max(...versions),
+ className: className || nodeTypeName,
+ };
+
+ // Register each version
+ for (const [version, nodeType] of Object.entries(versionedNodeType.nodeVersions)) {
+ this.registry[nodeTypeName].versions[Number(version)] = nodeType;
+ }
+
+ this.loadedNodeTypes.add(nodeTypeName);
+
+ console.log(
+ `[NodeRegistry] Registered versioned node ${nodeTypeName} versions: ${versions.join(', ')}`
+ );
+ }
+
+ /**
+ * Get a node type by name and version
+ */
+ getNodeType(nodeTypeName: string, version?: number): INodeType {
+ const entry = this.registry[nodeTypeName];
+
+ if (!entry) {
+ throw new Error(`Node type "${nodeTypeName}" not found in registry`);
+ }
+
+ // Use latest version if not specified
+ const targetVersion = version ?? entry.latestVersion;
+
+ const nodeType = entry.versions[targetVersion];
+
+ if (!nodeType) {
+ throw new Error(
+ `Node type "${nodeTypeName}" version ${targetVersion} not found. ` +
+ `Available versions: ${Object.keys(entry.versions).join(', ')}`
+ );
+ }
+
+ return nodeType;
+ }
+
+ /**
+ * Get node type description
+ */
+ getNodeTypeDescription(nodeTypeName: string, version?: number): INodeTypeDescription {
+ const nodeType = this.getNodeType(nodeTypeName, version);
+ return nodeType.description;
+ }
+
+ /**
+ * Get all registered node types
+ */
+ getAllNodeTypes(): Array<{
+ name: string;
+ versions: number[];
+ latestVersion: number;
+ }> {
+ return Object.entries(this.registry).map(([name, entry]) => ({
+ name,
+ versions: Object.keys(entry.versions).map(Number).sort((a, b) => a - b),
+ latestVersion: entry.latestVersion,
+ }));
+ }
+
+ /**
+ * Get all nodes (latest version of each node type with descriptions)
+ */
+ getAllNodes(): INodeTypeDescription[] {
+ return Object.entries(this.registry).map(([name, entry]) => {
+ const latestNodeType = entry.versions[entry.latestVersion];
+ return latestNodeType.description;
+ });
+ }
+
+ /**
+ * Get node types by category
+ */
+ getNodeTypesByCategory(category: string): INodeTypeDescription[] {
+ const nodeTypes: INodeTypeDescription[] = [];
+
+ for (const [name, entry] of Object.entries(this.registry)) {
+ const description = entry.versions[entry.latestVersion].description;
+
+ if (description.group.includes(category)) {
+ nodeTypes.push(description);
+ }
+ }
+
+ return nodeTypes;
+ }
+
+ /**
+ * Check if node type exists
+ */
+ hasNodeType(nodeTypeName: string, version?: number): boolean {
+ const entry = this.registry[nodeTypeName];
+
+ if (!entry) {
+ return false;
+ }
+
+ if (version === undefined) {
+ return true;
+ }
+
+ return entry.versions[version] !== undefined;
+ }
+
+ /**
+ * Get node type versions
+ */
+ getNodeTypeVersions(nodeTypeName: string): number[] {
+ const entry = this.registry[nodeTypeName];
+
+ if (!entry) {
+ return [];
+ }
+
+ return Object.keys(entry.versions).map(Number).sort((a, b) => a - b);
+ }
+
+ /**
+ * Unregister a node type (for testing/development)
+ */
+ unregisterNodeType(nodeTypeName: string): void {
+ delete this.registry[nodeTypeName];
+ this.loadedNodeTypes.delete(nodeTypeName);
+ console.log(`[NodeRegistry] Unregistered ${nodeTypeName}`);
+ }
+
+ /**
+ * Clear all registrations (for testing)
+ */
+ clear(): void {
+ this.registry = {};
+ this.loadedNodeTypes.clear();
+ console.log('[NodeRegistry] Cleared all node types');
+ }
+
+ /**
+ * Get registry statistics
+ */
+ getStatistics(): {
+ totalNodeTypes: number;
+ totalVersions: number;
+ nodeTypes: Array<{
+ name: string;
+ versions: number;
+ latestVersion: number;
+ }>;
+ } {
+ let totalVersions = 0;
+
+ const nodeTypes = Object.entries(this.registry).map(([name, entry]) => {
+ const versions = Object.keys(entry.versions).length;
+ totalVersions += versions;
+
+ return {
+ name,
+ versions,
+ latestVersion: entry.latestVersion,
+ };
+ });
+
+ return {
+ totalNodeTypes: Object.keys(this.registry).length,
+ totalVersions,
+ nodeTypes,
+ };
+ }
+
+ /**
+ * Validate node configuration
+ */
+ validateNode(nodeTypeName: string, version: number, parameters: any): {
+ valid: boolean;
+ errors: string[];
+ } {
+ const errors: string[] = [];
+
+ try {
+ const nodeType = this.getNodeType(nodeTypeName, version);
+ const description = nodeType.description;
+
+ // Validate required parameters
+ for (const property of description.properties) {
+ if (property.required) {
+ if (parameters[property.name] === undefined || parameters[property.name] === null) {
+ errors.push(`Required parameter "${property.name}" is missing`);
+ }
+ }
+ }
+
+ // TODO: Add more validation
+ // - Type validation
+ // - Value range validation
+ // - Dependent parameter validation
+
+ return {
+ valid: errors.length === 0,
+ errors,
+ };
+ } catch (error: any) {
+ return {
+ valid: false,
+ errors: [error.message],
+ };
+ }
+ }
+
+ /**
+ * Get node type categories
+ */
+ getCategories(): string[] {
+ const categories = new Set<string>();
+
+ for (const entry of Object.values(this.registry)) {
+ const description = entry.versions[entry.latestVersion].description;
+ description.group.forEach((group) => categories.add(group));
+ }
+
+ return Array.from(categories).sort();
+ }
+
+ /**
+ * Search node types
+ */
+ searchNodeTypes(query: string): INodeTypeDescription[] {
+ const lowerQuery = query.toLowerCase();
+ const results: INodeTypeDescription[] = [];
+
+ for (const entry of Object.values(this.registry)) {
+ const description = entry.versions[entry.latestVersion].description;
+
+ // Search in name, displayName, and description
+ if (
+ description.name.toLowerCase().includes(lowerQuery) ||
+ description.displayName.toLowerCase().includes(lowerQuery) ||
+ description.description.toLowerCase().includes(lowerQuery)
+ ) {
+ results.push(description);
+ }
+ }
+
+ return results;
+ }
+}
+
+// Export singleton instance
+export const NodeRegistry = new NodeRegistryClass();
+
+// Export class for testing
+export { NodeRegistryClass };
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/ParameterProcessor.ts b/fincept-terminal-desktop/src/services/nodeSystem/ParameterProcessor.ts
new file mode 100644
index 000000000..eab89b273
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/ParameterProcessor.ts
@@ -0,0 +1,433 @@
+/**
+ * Parameter Processor
+ * Handles parameter value extraction, transformation, and routing
+ *
+ * This module provides utilities for:
+ * - Extracting specific values from complex parameter objects
+ * - Routing parameter values to HTTP requests
+ * - Transforming parameter values based on configuration
+ * - Type conversion and validation
+ *
+ * Based on n8n's parameter handling patterns.
+ */
+
+import type {
+ INode,
+ INodeProperties,
+ INodePropertyRouting,
+ NodeParameterValue,
+ NodeParameterValueType,
+ IDataObject,
+ IGetNodeParameterOptions,
+ IHttpRequestOptions,
+} from './types';
+
+/**
+ * Extract a specific value from a parameter based on extractValue configuration
+ *
+ * Example:
+ * If parameter value is: { id: 123, name: "Test", meta: { ... } }
+ * And extractValue is: { type: "id", property: "id" }
+ * Returns: 123
+ */
+export function extractParameterValue(
+ value: NodeParameterValueType | object,
+ extractConfig?: { type: string; property: string }
+): NodeParameterValue {
+ if (!extractConfig || value === null || value === undefined) {
+ return value as NodeParameterValue;
+ }
+
+ // Handle different extraction types
+ switch (extractConfig.type) {
+ case 'id':
+ case 'value':
+ case 'name':
+ // Extract a specific property from an object
+ if (typeof value === 'object' && !Array.isArray(value)) {
+ const obj = value as IDataObject;
+ return obj[extractConfig.property] as NodeParameterValue;
+ }
+ return value as NodeParameterValue;
+
+ case 'list':
+ // Extract from first item in array
+ if (Array.isArray(value) && value.length > 0) {
+ const firstItem = value[0];
+ if (typeof firstItem === 'object' && firstItem !== null) {
+ return (firstItem as IDataObject)[extractConfig.property] as NodeParameterValue;
+ }
+ return firstItem as NodeParameterValue;
+ }
+ return value as NodeParameterValue;
+
+ case 'object':
+ // Extract entire object at property path
+ if (typeof value === 'object' && !Array.isArray(value)) {
+ return getNestedValue(value as IDataObject, extractConfig.property);
+ }
+ return value as NodeParameterValue;
+
+ default:
+ return value as NodeParameterValue;
+ }
+}
+
+/**
+ * Get nested value from object using dot notation
+ */
+function getNestedValue(obj: IDataObject, path: string): any {
+ const keys = path.split('.');
+ let current: any = obj;
+
+ for (const key of keys) {
+ if (current === null || current === undefined) {
+ return undefined;
+ }
+ current = current[key];
+ }
+
+ return current;
+}
+
+/**
+ * Apply routing configuration to transform parameter value for HTTP requests
+ *
+ * Routing allows parameters to automatically configure HTTP request options.
+ * For example, a parameter can specify that it should be sent as a header,
+ * or as part of the request body.
+ */
+export function applyParameterRouting(
+ parameterValue: NodeParameterValue,
+ routing?: INodePropertyRouting,
+ requestOptions?: IHttpRequestOptions
+): IHttpRequestOptions {
+ if (!routing || !requestOptions) {
+ return requestOptions || { url: '', method: 'GET' };
+ }
+
+ const options = { ...requestOptions };
+
+ // Apply request routing (modify request URL, method, headers, body)
+ if (routing.request) {
+ if (routing.request.method) {
+ options.method = routing.request.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
+ }
+
+ if (routing.request.url) {
+ // Replace placeholders in URL with parameter value
+ options.url = routing.request.url.replace('{{value}}', String(parameterValue));
+ }
+
+ if (routing.request.headers) {
+ options.headers = {
+ ...(options.headers || {}),
+ ...routing.request.headers,
+ };
+ }
+
+ if (routing.request.body) {
+ options.body = {
+ ...(typeof options.body === 'object' ? options.body : {}),
+ ...routing.request.body,
+ };
+ }
+ }
+
+ // Apply send routing (specify where to send the parameter value)
+ if (routing.send) {
+ const { type, property, value } = routing.send;
+
+ const valueToSend = value ? value : parameterValue;
+
+ switch (type) {
+ case 'header':
+ // Send as HTTP header
+ options.headers = {
+ ...(options.headers || {}),
+ [property || 'X-Custom-Header']: String(valueToSend),
+ };
+ break;
+
+ case 'query':
+ // Send as query parameter
+ if (!options.qs) {
+ options.qs = {};
+ }
+ options.qs[property || 'param'] = valueToSend;
+ break;
+
+ case 'body':
+ // Send in request body
+ if (options.json !== false) {
+ if (typeof options.body !== 'object') {
+ options.body = {};
+ }
+ (options.body as IDataObject)[property || 'value'] = valueToSend;
+ }
+ break;
+
+ case 'path':
+ // Send as part of URL path
+ if (options.url && property) {
+ options.url = options.url.replace(`{${property}}`, String(valueToSend));
+ }
+ break;
+
+ default:
+ // Default: send in body
+ if (typeof options.body !== 'object') {
+ options.body = {};
+ }
+ (options.body as IDataObject)[property || 'value'] = valueToSend;
+ }
+ }
+
+ return options;
+}
+
+/**
+ * Convert parameter value to specified type
+ *
+ * Handles type conversion with proper error handling and fallbacks.
+ */
+export function convertParameterValue(
+ value: NodeParameterValue,
+ targetType: 'string' | 'number' | 'boolean' | 'array' | 'object'
+): NodeParameterValue {
+ if (value === null || value === undefined) {
+ return value;
+ }
+
+ try {
+ switch (targetType) {
+ case 'string':
+ return String(value);
+
+ case 'number': {
+ if (typeof value === 'number') {
+ return value;
+ }
+ const num = Number(value);
+ return isNaN(num) ? 0 : num;
+ }
+
+ case 'boolean': {
+ if (typeof value === 'boolean') {
+ return value;
+ }
+ if (typeof value === 'string') {
+ const lower = value.toLowerCase();
+ return lower === 'true' || lower === '1' || lower === 'yes';
+ }
+ return Boolean(value);
+ }
+
+ case 'array': {
+ if (Array.isArray(value)) {
+ return value;
+ }
+ if (typeof value === 'string') {
+ try {
+ const parsed = JSON.parse(value);
+ return Array.isArray(parsed) ? parsed : [value];
+ } catch {
+ // Try splitting by comma
+ return value.split(',').map((s) => s.trim());
+ }
+ }
+ return [value];
+ }
+
+ case 'object': {
+ if (typeof value === 'object' && !Array.isArray(value)) {
+ return value;
+ }
+ if (typeof value === 'string') {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return {};
+ }
+ }
+ return {};
+ }
+
+ default:
+ return value;
+ }
+ } catch (error) {
+ console.error('[ParameterProcessor] Type conversion error:', error);
+ return value; // Return original value on error
+ }
+}
+
+/**
+ * Validate parameter value against field type
+ *
+ * Returns true if value is valid, false otherwise.
+ * Used for runtime validation of parameter values.
+ */
+export function validateParameterValue(
+ value: NodeParameterValue,
+ fieldType: string
+): { valid: boolean; error?: string } {
+ if (value === null || value === undefined) {
+ return { valid: true }; // null/undefined are always valid
+ }
+
+ switch (fieldType) {
+ case 'string':
+ if (typeof value !== 'string') {
+ return { valid: false, error: `Expected string, got ${typeof value}` };
+ }
+ return { valid: true };
+
+ case 'number':
+ if (typeof value !== 'number' || isNaN(value)) {
+ return { valid: false, error: 'Expected valid number' };
+ }
+ return { valid: true };
+
+ case 'boolean':
+ if (typeof value !== 'boolean') {
+ return { valid: false, error: `Expected boolean, got ${typeof value}` };
+ }
+ return { valid: true };
+
+ case 'array':
+ if (!Array.isArray(value)) {
+ return { valid: false, error: `Expected array, got ${typeof value}` };
+ }
+ return { valid: true };
+
+ case 'object':
+ if (typeof value !== 'object' || Array.isArray(value)) {
+ return { valid: false, error: 'Expected object' };
+ }
+ return { valid: true };
+
+ case 'dateTime':
+ // Check if valid date
+ const date = new Date(value as string | number);
+ if (isNaN(date.getTime())) {
+ return { valid: false, error: 'Expected valid date/time' };
+ }
+ return { valid: true };
+
+ case 'url':
+ // Basic URL validation
+ if (typeof value !== 'string') {
+ return { valid: false, error: 'Expected string URL' };
+ }
+ try {
+ new URL(value);
+ return { valid: true };
+ } catch {
+ return { valid: false, error: 'Invalid URL format' };
+ }
+
+ case 'email':
+ // Basic email validation
+ if (typeof value !== 'string') {
+ return { valid: false, error: 'Expected string email' };
+ }
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ if (!emailRegex.test(value)) {
+ return { valid: false, error: 'Invalid email format' };
+ }
+ return { valid: true };
+
+ default:
+ return { valid: true }; // Unknown types are considered valid
+ }
+}
+
+/**
+ * Process all parameters for a node
+ *
+ * This is a comprehensive function that:
+ * 1. Extracts values if needed
+ * 2. Applies type conversions
+ * 3. Validates values
+ * 4. Prepares routing information
+ */
+export function processNodeParameters(
+ node: INode,
+ parameterDefinitions: INodeProperties[],
+ options?: {
+ validateTypes?: boolean;
+ convertTypes?: boolean;
+ extractValues?: boolean;
+ }
+): {
+ parameters: IDataObject;
+ routing: Map<string, INodePropertyRouting>;
+ errors: Array<{ parameter: string; error: string }>;
+} {
+ const processed: IDataObject = {};
+ const routing = new Map<string, INodePropertyRouting>();
+ const errors: Array<{ parameter: string; error: string }> = [];
+
+ for (const paramDef of parameterDefinitions) {
+ const paramName = paramDef.name;
+ let value = node.parameters[paramName];
+
+ if (value === undefined) {
+ value = paramDef.default;
+ }
+
+ // Extract value if configured
+ if (options?.extractValues && paramDef.extractValue) {
+ value = extractParameterValue(value, paramDef.extractValue);
+ }
+
+ // Convert type if needed
+ if (options?.convertTypes && paramDef.validateType) {
+ const targetType = paramDef.validateType as any;
+ value = convertParameterValue(value as NodeParameterValue, targetType);
+ }
+
+ // Validate if configured
+ if (options?.validateTypes && paramDef.validateType && !paramDef.ignoreValidationDuringExecution) {
+ const validation = validateParameterValue(value as NodeParameterValue, paramDef.validateType);
+ if (!validation.valid) {
+ errors.push({
+ parameter: paramName,
+ error: validation.error || 'Validation failed',
+ });
+ }
+ }
+
+ // Store routing information
+ if (paramDef.routing) {
+ routing.set(paramName, paramDef.routing);
+ }
+
+ processed[paramName] = value;
+ }
+
+ return { parameters: processed, routing, errors };
+}
+
+/**
+ * Build HTTP request options from parameters with routing
+ *
+ * This function takes node parameters and their routing configurations
+ * and builds a complete HTTP request options object.
+ */
+export function buildRequestFromRouting(
+ parameters: IDataObject,
+ routing: Map<string, INodePropertyRouting>,
+ baseRequest?: IHttpRequestOptions
+): IHttpRequestOptions {
+ let options: IHttpRequestOptions = baseRequest || { url: '', method: 'GET' };
+
+ // Apply routing from each parameter
+ for (const [paramName, paramRouting] of routing.entries()) {
+ const paramValue = parameters[paramName] as NodeParameterValue;
+ options = applyParameterRouting(paramValue, paramRouting, options);
+ }
+
+ return options;
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/PartialExecutionUtils.ts b/fincept-terminal-desktop/src/services/nodeSystem/PartialExecutionUtils.ts
new file mode 100644
index 000000000..bb149deec
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/PartialExecutionUtils.ts
@@ -0,0 +1,441 @@
+/**
+ * Partial Execution Utilities
+ * Optimizations for smart workflow execution based on n8n's execution engine
+ *
+ * Features:
+ * - Dirty node detection (nodes that need re-execution)
+ * - Start node finding (where to begin partial execution)
+ * - Subgraph extraction (only execute necessary nodes)
+ * - Run data cleaning (remove stale execution data)
+ */
+
+import {
+ INode,
+ IRunData,
+ IPinData,
+ NodeConnectionType,
+ INodeExecutionData,
+} from './types';
+import { DirectedGraph, GraphConnection } from './DirectedGraph';
+
+/**
+ * Check if a node is "dirty" and needs re-execution
+ *
+ * A node is dirty if:
+ * - It has no run data and no pinned data
+ * - Its parameters changed (future enhancement)
+ * - One of its parents is disabled (future enhancement)
+ * - It has an error (future enhancement)
+ */
+export function isDirty(
+ node: INode,
+ runData: IRunData = {},
+ pinData: IPinData = {}
+): boolean {
+ // Check for pinned data (always clean if pinned)
+ const hasPinnedData = pinData[node.name] !== undefined;
+ if (hasPinnedData) {
+ return false;
+ }
+
+ // Check for run data
+ const hasRunData = runData[node.name] !== undefined;
+ if (hasRunData) {
+ return false;
+ }
+
+ // Node has neither pinned data nor run data - it's dirty
+ return true;
+}
+
+/**
+ * Find start nodes for partial execution
+ *
+ * Start nodes are the earliest dirty nodes on each branch
+ * from trigger to destination. These are where execution begins.
+ *
+ * Algorithm:
+ * 1. Start from trigger node
+ * 2. If current node is dirty or is destination - it's a start node
+ * 3. If cycle detected - stop following branch
+ * 4. Recurse with all children in subgraph
+ */
+export function findStartNodes(options: {
+ graph: DirectedGraph;
+ trigger: INode;
+ destination: INode;
+ runData: IRunData;
+ pinData: IPinData;
+}): Set<INode> {
+ const { graph, trigger, destination, runData, pinData } = options;
+
+ const startNodes = new Set<INode>();
+ const seen = new Set<string>();
+
+ function findRecursive(current: INode) {
+ const nodeIsDirty = isDirty(current, runData, pinData);
+
+ // If dirty, this is a start node
+ if (nodeIsDirty) {
+ startNodes.add(current);
+ return;
+ }
+
+ // If we reached destination, this is a start node
+ if (current === destination) {
+ startNodes.add(current);
+ return;
+ }
+
+ // Cycle detection
+ if (seen.has(current.name)) {
+ return;
+ }
+
+ seen.add(current.name);
+
+ // Recurse with direct children
+ const children = graph.getDirectChildren(current);
+
+ for (const child of children) {
+ // Only follow branches that have run data
+ const childRunData = runData[child.name];
+ const childPinData = pinData[child.name];
+
+ const hasData = childRunData !== undefined || childPinData !== undefined;
+
+ if (!hasData) {
+ // Skip branches without data
+ continue;
+ }
+
+ findRecursive(child);
+ }
+ }
+
+ findRecursive(trigger);
+ return startNodes;
+}
+
+/**
+ * Extract subgraph from trigger to destination
+ *
+ * Returns only the nodes and connections needed to execute
+ * from trigger to destination, ignoring unrelated branches.
+ */
+export function findSubgraph(options: {
+ graph: DirectedGraph;
+ trigger: INode;
+ destination: INode;
+}): DirectedGraph {
+ const { graph, trigger, destination } = options;
+ return graph.extractSubgraph(trigger, destination);
+}
+
+/**
+ * Clean run data to only include nodes in subgraph
+ *
+ * Removes execution data for nodes not in the current execution path.
+ * This prevents stale data from affecting the execution.
+ */
+export function cleanRunData(
+ runData: IRunData,
+ subgraph: DirectedGraph
+): IRunData {
+ const cleanedData: IRunData = {};
+ const subgraphNodes = subgraph.getNodes();
+
+ for (const [nodeName, nodeData] of Object.entries(runData)) {
+ if (subgraphNodes.has(nodeName)) {
+ cleanedData[nodeName] = nodeData;
+ }
+ }
+
+ return cleanedData;
+}
+
+/**
+ * Handle cycles in workflow graph
+ *
+ * Detects and breaks cycles to prevent infinite loops.
+ * Returns modified graph with cycle-breaking edges removed.
+ */
+export function handleCycles(graph: DirectedGraph): {
+ hasCycles: boolean;
+ cycleNodes: string[];
+} {
+ const hasCycles = graph.hasCycles();
+
+ if (!hasCycles) {
+ return { hasCycles: false, cycleNodes: [] };
+ }
+
+ // Detect cycle nodes
+ const cycleNodes: string[] = [];
+ const visited = new Set<string>();
+ const recursionStack = new Set<string>();
+
+ const detectCycleDFS = (node: INode): boolean => {
+ if (recursionStack.has(node.name)) {
+ cycleNodes.push(node.name);
+ return true;
+ }
+
+ if (visited.has(node.name)) {
+ return false;
+ }
+
+ visited.add(node.name);
+ recursionStack.add(node.name);
+
+ const children = graph.getDirectChildren(node);
+
+ for (const child of children) {
+ if (detectCycleDFS(child)) {
+ return true;
+ }
+ }
+
+ recursionStack.delete(node.name);
+ return false;
+ };
+
+ const nodes = Array.from(graph.getNodes().values());
+ for (const node of nodes) {
+ if (detectCycleDFS(node)) {
+ break;
+ }
+ }
+
+ return { hasCycles: true, cycleNodes };
+}
+
+/**
+ * Filter disabled nodes from graph
+ *
+ * Returns new graph with disabled nodes and their connections removed.
+ */
+export function filterDisabledNodes(graph: DirectedGraph): DirectedGraph {
+ const filtered = graph.clone();
+ const nodes = Array.from(filtered.getNodes().values());
+
+ for (const node of nodes) {
+ if (node.disabled) {
+ filtered.removeNode(node.name);
+ }
+ }
+
+ return filtered;
+}
+
+/**
+ * Recreate node execution stack from start nodes
+ *
+ * Builds execution stack in topological order starting from
+ * the given start nodes, ensuring dependencies execute first.
+ */
+export function recreateNodeExecutionStack(options: {
+ graph: DirectedGraph;
+ startNodes: Set<INode>;
+ runData: IRunData;
+ pinData: IPinData;
+}): INode[] {
+ const { graph, startNodes, runData, pinData } = options;
+
+ const executionStack: INode[] = [];
+ const visited = new Set<string>();
+
+ /**
+ * Topological sort using DFS
+ */
+ function visit(node: INode) {
+ if (visited.has(node.name)) {
+ return;
+ }
+
+ visited.add(node.name);
+
+ // Visit dependencies first (parents)
+ const parents = graph.getDirectParents(node);
+
+ for (const parent of parents) {
+ // Only visit parents that have data (run data or pin data)
+ const hasData = runData[parent.name] || pinData[parent.name];
+
+ if (hasData && !parent.disabled) {
+ visit(parent);
+ }
+ }
+
+ // Add current node to stack
+ if (!node.disabled) {
+ executionStack.push(node);
+ }
+ }
+
+ // Start from each start node
+ for (const startNode of startNodes) {
+ visit(startNode);
+ }
+
+ return executionStack;
+}
+
+/**
+ * Find trigger node for partial execution
+ *
+ * Searches for the appropriate trigger node to start execution from.
+ * Prefers manual trigger nodes, falls back to start nodes.
+ */
+export function findTriggerForPartialExecution(
+ graph: DirectedGraph,
+ destination: INode
+): INode | undefined {
+ // Get all start nodes (nodes with no incoming connections)
+ const startNodes = graph.getStartNodes();
+
+ if (startNodes.length === 0) {
+ return undefined;
+ }
+
+ // If only one start node, use it
+ if (startNodes.length === 1) {
+ return startNodes[0];
+ }
+
+ // Prefer manual trigger nodes
+ const manualTrigger = startNodes.find(
+ (node) => node.type === 'manualTrigger' || node.type.includes('trigger')
+ );
+
+ if (manualTrigger) {
+ return manualTrigger;
+ }
+
+ // Find start node that has path to destination
+ for (const startNode of startNodes) {
+ const path = graph.findPath(startNode, destination);
+ if (path) {
+ return startNode;
+ }
+ }
+
+ // Fallback to first start node
+ return startNodes[0];
+}
+
+/**
+ * Get incoming data for a node from run data
+ */
+export function getIncomingData(
+ runData: IRunData,
+ nodeName: string,
+ runIndex: number,
+ connectionType: NodeConnectionType = NodeConnectionType.Main,
+ outputIndex: number = 0
+): INodeExecutionData[] | null {
+ const nodeRunData = runData[nodeName];
+
+ if (!nodeRunData) {
+ return null;
+ }
+
+ // Get specific run index (-1 = last run)
+ const targetRun = runIndex === -1 ? nodeRunData.length - 1 : runIndex;
+
+ if (targetRun < 0 || targetRun >= nodeRunData.length) {
+ return null;
+ }
+
+ const taskData = nodeRunData[targetRun];
+
+ if (!taskData.data[connectionType]) {
+ return null;
+ }
+
+ const outputData = taskData.data[connectionType][outputIndex];
+
+ return outputData || null;
+}
+
+/**
+ * Check if node has incoming data from any run
+ */
+export function hasIncomingDataFromAnyRun(
+ runData: IRunData,
+ nodeName: string,
+ connectionType: NodeConnectionType = NodeConnectionType.Main,
+ outputIndex: number = 0
+): boolean {
+ const nodeRunData = runData[nodeName];
+
+ if (!nodeRunData || nodeRunData.length === 0) {
+ return false;
+ }
+
+ // Check if any run has data on this connection
+ for (const taskData of nodeRunData) {
+ const data = taskData.data[connectionType]?.[outputIndex];
+
+ if (data && data.length > 0) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Calculate execution order for nodes
+ *
+ * Returns nodes in the order they should be executed,
+ * respecting dependencies and parallel execution opportunities.
+ */
+export function calculateExecutionOrder(graph: DirectedGraph): INode[][] {
+ const levels: INode[][] = [];
+ const visited = new Set<string>();
+ const nodeLevel = new Map<string, number>();
+
+ // Calculate level for each node (distance from start nodes)
+ function calculateLevel(node: INode, level: number) {
+ const currentLevel = nodeLevel.get(node.name) || 0;
+
+ // Update level if deeper path found
+ if (level > currentLevel) {
+ nodeLevel.set(node.name, level);
+ }
+
+ if (visited.has(node.name)) {
+ return;
+ }
+
+ visited.add(node.name);
+
+ // Recurse with children
+ const children = graph.getDirectChildren(node);
+ for (const child of children) {
+ calculateLevel(child, level + 1);
+ }
+ }
+
+ // Calculate levels starting from start nodes
+ const startNodes = graph.getStartNodes();
+ for (const startNode of startNodes) {
+ calculateLevel(startNode, 0);
+ }
+
+ // Group nodes by level
+ const maxLevel = Math.max(...Array.from(nodeLevel.values()));
+
+ for (let i = 0; i <= maxLevel; i++) {
+ levels[i] = [];
+ }
+
+ const allNodes = Array.from(graph.getNodes().values());
+ for (const node of allNodes) {
+ const level = nodeLevel.get(node.name) || 0;
+ levels[level].push(node);
+ }
+
+ return levels;
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/README.md b/fincept-terminal-desktop/src/services/nodeSystem/README.md
new file mode 100644
index 000000000..314abb431
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/README.md
@@ -0,0 +1,483 @@
+# Node System - n8n-Inspired Architecture
+
+**Version**: 1.0 (Phase 1 Complete)
+**Status**: Foundation Ready ✅
+
+This is a professional-grade node-based workflow system for Fincept Terminal, inspired by n8n's proven architecture.
+
+## What's Been Built (Phase 1)
+
+### ✅ Core Type System (`types.ts`)
+
+Complete TypeScript type definitions covering:
+- **Node Execution Data**: Standard format for data flow between nodes
+- **Connection Types**: 15+ connection types including finance-specific ones
+- **Node Properties**: 25+ parameter types for dynamic UI generation
+- **Execution Contexts**: Interfaces for node execution environments
+- **Workflow Definitions**: Complete workflow structure
+- **Finance Types**: Market data, portfolio, technical indicators, backtest results
+
+### ✅ Execution Context (`ExecutionContext.ts`)
+
+Runtime context for nodes:
+- `ExecutionContext`: Main context for standard nodes
+- `LoadOptionsContext`: For dynamic parameter loading
+- **Helper functions**: HTTP requests, data transformation, paired item tracking
+- **Parameter access**: Dot notation support (`rules.values[0].condition`)
+- **Expression evaluation**: Foundation for `{{$json.field}}` syntax
+
+### ✅ Node Registry (`NodeRegistry.ts`)
+
+Centralized node management:
+- Register/unregister node types
+- Version management
+- Category grouping
+- Node search
+- Validation
+- Statistics and debugging
+
+### ✅ Workflow Data Proxy (`WorkflowDataProxy.ts`)
+
+Workflow context provider:
+- Access other nodes
+- Get execution data from previous nodes
+- Workflow-level static data
+- Parent/child node relationships
+- Execution status tracking
+
+### ✅ Node Loader (`NodeLoader.ts`)
+
+Automatic node discovery:
+- Auto-registration on startup
+- Hot reload support (development)
+- Modular loading (core, finance, AI, integrations)
+- Initialization system
+
+### ✅ Workflow Executor (`WorkflowExecutor.ts`)
+
+Simple but functional executor:
+- Sequential execution
+- Error handling
+- Continue on fail
+- Pin data support
+- Execution state tracking
+
+### ✅ Demo Stock Data Node (`StockData.node.ts`)
+
+Production-ready finance node:
+- Multiple data sources (Yahoo Finance, Alpha Vantage, Polygon, Database)
+- Dynamic parameters (show/hide based on source)
+- Options collection
+- Error handling
+- Sample data generation
+
+## Project Structure
+
+```
+src/services/nodeSystem/
+├── types.ts # All TypeScript interfaces (650+ lines)
+├── ExecutionContext.ts # Execution runtime context
+├── NodeRegistry.ts # Node type management
+├── WorkflowDataProxy.ts # Workflow data access
+├── NodeLoader.ts # Auto-discovery and registration
+├── WorkflowExecutor.ts # Workflow execution engine
+├── index.ts # Public API exports
+├── demo.ts # Usage examples
+└── README.md # This file
+
+src/nodes/
+└── finance/
+ └── StockData.node.ts # Example finance node
+```
+
+## How to Use
+
+### 1. Initialize the System
+
+```typescript
+import { initializeNodeSystem } from '@/services/nodeSystem';
+
+// Call once during app startup
+await initializeNodeSystem();
+```
+
+### 2. Create a Node
+
+```typescript
+import { INode } from '@/services/nodeSystem';
+
+const stockNode: INode = {
+ id: 'node-1',
+ name: 'AAPL Data',
+ type: 'stockData',
+ typeVersion: 1,
+ position: [100, 100],
+ parameters: {
+ source: 'yfinance',
+ symbol: 'AAPL',
+ interval: '1d',
+ period: '1mo',
+ },
+};
+```
+
+### 3. Create a Workflow
+
+```typescript
+import { IWorkflow } from '@/services/nodeSystem';
+
+const workflow: IWorkflow = {
+ id: 'workflow-1',
+ name: 'My Workflow',
+ active: true,
+ nodes: [stockNode],
+ connections: {},
+};
+```
+
+### 4. Execute the Workflow
+
+```typescript
+import { WorkflowExecutor } from '@/services/nodeSystem';
+
+const executor = new WorkflowExecutor(workflow);
+const result = await executor.execute();
+
+// Access results
+const nodeResults = result.resultData.runData['AAPL Data'];
+const outputData = nodeResults[0].data.main[0];
+
+console.log('Output items:', outputData.length);
+```
+
+## Creating a New Node
+
+### Example: Simple Calculator Node
+
+```typescript
+import {
+ INodeType,
+ INodeTypeDescription,
+ IExecuteFunctions,
+ NodeOutput,
+ NodeConnectionType,
+ NodePropertyType,
+} from '@/services/nodeSystem';
+
+export class CalculatorNode implements INodeType {
+ description: INodeTypeDescription = {
+ displayName: 'Calculator',
+ name: 'calculator',
+ group: ['transform'],
+ version: 1,
+ description: 'Perform calculations on numeric data',
+ defaults: {
+ name: 'Calculator',
+ color: '#3b82f6',
+ },
+ inputs: [NodeConnectionType.Main],
+ outputs: [NodeConnectionType.Main],
+ properties: [
+ {
+ displayName: 'Operation',
+ name: 'operation',
+ type: NodePropertyType.Options,
+ options: [
+ { name: 'Add', value: 'add' },
+ { name: 'Subtract', value: 'subtract' },
+ { name: 'Multiply', value: 'multiply' },
+ { name: 'Divide', value: 'divide' },
+ ],
+ default: 'add',
+ },
+ {
+ displayName: 'Value A',
+ name: 'valueA',
+ type: NodePropertyType.Number,
+ default: 0,
+ },
+ {
+ displayName: 'Value B',
+ name: 'valueB',
+ type: NodePropertyType.Number,
+ default: 0,
+ },
+ ],
+ };
+
+ async execute(this: IExecuteFunctions): Promise<NodeOutput> {
+ const items = this.getInputData();
+ const returnData = [];
+
+ for (let i = 0; i < items.length; i++) {
+ const operation = this.getNodeParameter('operation', i) as string;
+ const valueA = this.getNodeParameter('valueA', i) as number;
+ const valueB = this.getNodeParameter('valueB', i) as number;
+
+ let result: number;
+
+ switch (operation) {
+ case 'add':
+ result = valueA + valueB;
+ break;
+ case 'subtract':
+ result = valueA - valueB;
+ break;
+ case 'multiply':
+ result = valueA * valueB;
+ break;
+ case 'divide':
+ result = valueA / valueB;
+ break;
+ default:
+ result = 0;
+ }
+
+ returnData.push({
+ json: {
+ operation,
+ valueA,
+ valueB,
+ result,
+ },
+ });
+ }
+
+ return [returnData];
+ }
+}
+```
+
+### Register Your Node
+
+In `NodeLoader.ts`:
+
+```typescript
+import { CalculatorNode } from '../../nodes/core/Calculator.node';
+
+// In loadCoreNodes():
+const calculatorNode = new CalculatorNode();
+NodeRegistry.registerNodeType(calculatorNode);
+```
+
+## Finance-Specific Features
+
+### Connection Types
+
+```typescript
+NodeConnectionType.MarketData // Real-time market data
+NodeConnectionType.PortfolioData // Portfolio holdings
+NodeConnectionType.PriceData // Historical prices
+NodeConnectionType.TechnicalData // Technical indicators
+NodeConnectionType.BacktestData // Backtest results
+```
+
+### Parameter Types
+
+```typescript
+NodePropertyType.StockSymbol // Stock symbol selector
+NodePropertyType.PortfolioSelector // Portfolio picker
+NodePropertyType.DateRange // Date range picker
+NodePropertyType.TimeInterval // Time interval (1d, 1h)
+NodePropertyType.TechnicalIndicator // Indicator selector
+```
+
+### Data Structures
+
+```typescript
+interface IMarketData {
+ symbol: string;
+ timestamp: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+ vwap?: number;
+}
+
+interface IPortfolioHolding {
+ symbol: string;
+ quantity: number;
+ averageCost: number;
+ currentPrice: number;
+ marketValue: number;
+ unrealizedPL: number;
+ unrealizedPLPercent: number;
+ weight: number;
+}
+```
+
+## Next Steps (Phase 2)
+
+### Coming Soon:
+
+1. **Paired Item Tracking** - Data lineage through workflows
+2. **Connection Validation** - Type checking for connections
+3. **Binary Data Support** - Handle files, images, PDFs
+4. **Expression Engine** - Full `{{$json.field}}` support
+5. **More Core Nodes**:
+ - Switch (conditional routing)
+ - Merge (combine data)
+ - Set (modify fields)
+ - Filter (filter items)
+ - Loop (iterate)
+
+6. **More Finance Nodes**:
+ - Technical Indicators
+ - Portfolio Optimizer
+ - Risk Calculator
+ - Backtest Strategy
+ - Options Analysis
+ - Fundamental Analysis
+ - Sentiment Analysis
+
+## Testing
+
+Run the demo:
+
+```typescript
+import { runAllDemos } from '@/services/nodeSystem/demo';
+
+await runAllDemos();
+```
+
+## API Reference
+
+### Key Interfaces
+
+- `INodeType` - Node definition
+- `IExecuteFunctions` - Execution context (available as `this` in nodes)
+- `INode` - Node instance
+- `IWorkflow` - Workflow definition
+- `INodeExecutionData` - Data format between nodes
+
+### Key Classes
+
+- `NodeRegistry` - Manage node types
+- `WorkflowExecutor` - Execute workflows
+- `ExecutionContext` - Runtime context for nodes
+- `WorkflowDataProxy` - Access workflow data
+
+## Debugging
+
+### Enable Verbose Logging
+
+All modules use console logging with prefixes:
+- `[NodeSystem]` - System initialization
+- `[NodeLoader]` - Node loading
+- `[NodeRegistry]` - Node registration
+- `[WorkflowExecutor]` - Execution flow
+- `[NodeName]` - Individual nodes
+
+### Get Registry Statistics
+
+```typescript
+import { NodeRegistry } from '@/services/nodeSystem';
+
+const stats = NodeRegistry.getStatistics();
+console.log('Node types:', stats.totalNodeTypes);
+console.log('Versions:', stats.totalVersions);
+```
+
+### Validate Node Configuration
+
+```typescript
+const validation = NodeRegistry.validateNode(
+ 'stockData',
+ 1,
+ { source: 'yfinance', symbol: 'AAPL' }
+);
+
+if (!validation.valid) {
+ console.error('Validation errors:', validation.errors);
+}
+```
+
+## Migration from Old System
+
+### Old Way
+
+```typescript
+// Old node component
+<DataSourceNode data={{ label: 'Stock Data' }} />
+```
+
+### New Way
+
+```typescript
+// Create node instance
+const node: INode = {
+ type: 'stockData',
+ name: 'Stock Data',
+ parameters: { source: 'yfinance', symbol: 'AAPL' },
+ // ... other properties
+};
+
+// Add to workflow and execute
+```
+
+**Benefits**:
+- Type safety
+- Versioning
+- Testability
+- Reusability
+- Standard interfaces
+
+## Architecture Decisions
+
+### Why n8n's Approach?
+
+1. **Proven at Scale** - Used by 200k+ users
+2. **Type Safe** - Full TypeScript
+3. **Extensible** - Easy to add nodes
+4. **Versionable** - Nodes can evolve
+5. **Testable** - Clear interfaces
+6. **Professional** - Production-ready patterns
+
+### Key Differences from Old System
+
+| Feature | Old System | New System |
+|---------|-----------|------------|
+| Type Safety | ❌ Weak | ✅ Strong |
+| Versioning | ❌ None | ✅ Built-in |
+| Data Lineage | ❌ No | ✅ Paired Items |
+| Parameters | ❌ Manual | ✅ Dynamic |
+| Execution | ❌ Basic | ✅ Professional |
+| Error Handling | ❌ Limited | ✅ Comprehensive |
+| Testing | ❌ Difficult | ✅ Easy |
+
+## Contributing
+
+### Adding a New Node
+
+1. Create node file in `src/nodes/<category>/YourNode.node.ts`
+2. Implement `INodeType` interface
+3. Register in `NodeLoader.ts`
+4. Test with demo workflow
+5. Document parameters and usage
+
+### Code Style
+
+- Use TypeScript strict mode
+- Document all public methods
+- Add JSDoc comments
+- Follow n8n naming conventions
+- Include error handling
+
+## License
+
+Same as Fincept Terminal (MIT License)
+
+## Support
+
+- **Documentation**: This file + inline comments
+- **Examples**: `demo.ts`
+- **Issues**: Report via GitHub
+- **Questions**: Discord community
+
+---
+
+**Last Updated**: 2025-12-29
+**Phase**: 1 Complete ✅
+**Next Phase**: Paired Item Tracking & More Nodes
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/WorkflowCache.ts b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowCache.ts
new file mode 100644
index 000000000..cf768b8e1
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowCache.ts
@@ -0,0 +1,606 @@
+/**
+ * Workflow Cache
+ *
+ * Provides caching and memoization for workflow execution to improve performance.
+ *
+ * Features:
+ * - Cache workflow execution results
+ * - Memoize node execution outputs
+ * - Cache DirectedGraph instances
+ * - Cache parameter evaluations
+ * - LRU eviction policy
+ * - TTL (time-to-live) support
+ * - Cache invalidation
+ * - Memory management
+ *
+ * Based on caching patterns from n8n and general workflow systems.
+ */
+
+import type {
+ IWorkflow,
+ INode,
+ IRunExecutionData,
+ IRunData,
+ NodeParameterValue,
+ INodeExecutionData,
+} from './types';
+import { DirectedGraph } from './DirectedGraph';
+
+/**
+ * Cache entry with metadata
+ */
+interface ICacheEntry<T> {
+ value: T;
+ timestamp: number;
+ hits: number;
+ size: number; // Approximate size in bytes
+}
+
+/**
+ * Cache statistics
+ */
+interface ICacheStats {
+ hits: number;
+ misses: number;
+ size: number;
+ entries: number;
+ hitRate: number;
+}
+
+/**
+ * LRU Cache with TTL support
+ */
+class LRUCache<T> {
+ private cache: Map<string, ICacheEntry<T>>;
+ private maxSize: number;
+ private maxAge: number; // milliseconds
+ private currentSize: number;
+ private hits: number;
+ private misses: number;
+
+ constructor(maxSize: number = 100, maxAge: number = 5 * 60 * 1000) {
+ this.cache = new Map();
+ this.maxSize = maxSize;
+ this.maxAge = maxAge;
+ this.currentSize = 0;
+ this.hits = 0;
+ this.misses = 0;
+ }
+
+ /**
+ * Get value from cache
+ */
+ get(key: string): T | undefined {
+ const entry = this.cache.get(key);
+
+ if (!entry) {
+ this.misses++;
+ return undefined;
+ }
+
+ // Check if expired
+ const age = Date.now() - entry.timestamp;
+ if (age > this.maxAge) {
+ this.cache.delete(key);
+ this.currentSize -= entry.size;
+ this.misses++;
+ return undefined;
+ }
+
+ // Update access metadata
+ entry.hits++;
+ entry.timestamp = Date.now();
+
+ // Move to end (most recently used)
+ this.cache.delete(key);
+ this.cache.set(key, entry);
+
+ this.hits++;
+ return entry.value;
+ }
+
+ /**
+ * Set value in cache
+ */
+ set(key: string, value: T, size: number = 1): void {
+ // Remove existing entry if present
+ const existing = this.cache.get(key);
+ if (existing) {
+ this.currentSize -= existing.size;
+ this.cache.delete(key);
+ }
+
+ // Evict entries if necessary
+ while (this.cache.size >= this.maxSize) {
+ this.evictOldest();
+ }
+
+ // Add new entry
+ const entry: ICacheEntry<T> = {
+ value,
+ timestamp: Date.now(),
+ hits: 0,
+ size,
+ };
+
+ this.cache.set(key, entry);
+ this.currentSize += size;
+ }
+
+ /**
+ * Check if key exists (without updating access)
+ */
+ has(key: string): boolean {
+ const entry = this.cache.get(key);
+ if (!entry) return false;
+
+ // Check expiration
+ const age = Date.now() - entry.timestamp;
+ if (age > this.maxAge) {
+ this.cache.delete(key);
+ this.currentSize -= entry.size;
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Delete entry
+ */
+ delete(key: string): boolean {
+ const entry = this.cache.get(key);
+ if (entry) {
+ this.currentSize -= entry.size;
+ }
+ return this.cache.delete(key);
+ }
+
+ /**
+ * Clear all entries
+ */
+ clear(): void {
+ this.cache.clear();
+ this.currentSize = 0;
+ this.hits = 0;
+ this.misses = 0;
+ }
+
+ /**
+ * Evict oldest (least recently used) entry
+ */
+ private evictOldest(): void {
+ const firstKey = this.cache.keys().next().value;
+ if (firstKey) {
+ const entry = this.cache.get(firstKey);
+ if (entry) {
+ this.currentSize -= entry.size;
+ }
+ this.cache.delete(firstKey);
+ }
+ }
+
+ /**
+ * Get cache statistics
+ */
+ getStats(): ICacheStats {
+ const total = this.hits + this.misses;
+ return {
+ hits: this.hits,
+ misses: this.misses,
+ size: this.currentSize,
+ entries: this.cache.size,
+ hitRate: total > 0 ? this.hits / total : 0,
+ };
+ }
+
+ /**
+ * Get all keys
+ */
+ keys(): string[] {
+ return Array.from(this.cache.keys());
+ }
+
+ /**
+ * Cleanup expired entries
+ */
+ cleanup(): void {
+ const now = Date.now();
+ const keysToDelete: string[] = [];
+
+ for (const [key, entry] of this.cache.entries()) {
+ const age = now - entry.timestamp;
+ if (age > this.maxAge) {
+ keysToDelete.push(key);
+ }
+ }
+
+ for (const key of keysToDelete) {
+ const entry = this.cache.get(key);
+ if (entry) {
+ this.currentSize -= entry.size;
+ }
+ this.cache.delete(key);
+ }
+ }
+}
+
+/**
+ * Workflow Cache Manager
+ */
+export class WorkflowCache {
+ // Caches for different types of data
+ private executionCache: LRUCache<IRunExecutionData>;
+ private nodeOutputCache: LRUCache<INodeExecutionData[][]>;
+ private graphCache: LRUCache<DirectedGraph>;
+ private parameterCache: LRUCache<NodeParameterValue>;
+ private expressionCache: LRUCache<any>;
+
+ // Cache configuration
+ private enabled: boolean = true;
+ private cleanupInterval: NodeJS.Timeout | null = null;
+
+ constructor() {
+ // Initialize caches with different sizes based on typical usage
+ this.executionCache = new LRUCache<IRunExecutionData>(50, 10 * 60 * 1000); // 10 min TTL
+ this.nodeOutputCache = new LRUCache<INodeExecutionData[][]>(200, 5 * 60 * 1000); // 5 min TTL
+ this.graphCache = new LRUCache<DirectedGraph>(100, 30 * 60 * 1000); // 30 min TTL
+ this.parameterCache = new LRUCache<NodeParameterValue>(500, 5 * 60 * 1000); // 5 min TTL
+ this.expressionCache = new LRUCache<any>(1000, 5 * 60 * 1000); // 5 min TTL
+
+ // Start periodic cleanup
+ this.startCleanup();
+ }
+
+ /**
+ * Cache workflow execution result
+ */
+ cacheExecution(workflowId: string, executionId: string, result: IRunExecutionData): void {
+ if (!this.enabled) return;
+
+ const key = `${workflowId}:${executionId}`;
+ const size = this.estimateSize(result);
+ this.executionCache.set(key, result, size);
+ }
+
+ /**
+ * Get cached workflow execution result
+ */
+ getCachedExecution(workflowId: string, executionId: string): IRunExecutionData | undefined {
+ if (!this.enabled) return undefined;
+
+ const key = `${workflowId}:${executionId}`;
+ return this.executionCache.get(key);
+ }
+
+ /**
+ * Cache node execution output
+ */
+ cacheNodeOutput(
+ workflowId: string,
+ nodeId: string,
+ inputHash: string,
+ output: INodeExecutionData[][]
+ ): void {
+ if (!this.enabled) return;
+
+ const key = `${workflowId}:${nodeId}:${inputHash}`;
+ const size = this.estimateSize(output);
+ this.nodeOutputCache.set(key, output, size);
+ }
+
+ /**
+ * Get cached node output
+ */
+ getCachedNodeOutput(
+ workflowId: string,
+ nodeId: string,
+ inputHash: string
+ ): INodeExecutionData[][] | undefined {
+ if (!this.enabled) return undefined;
+
+ const key = `${workflowId}:${nodeId}:${inputHash}`;
+ return this.nodeOutputCache.get(key);
+ }
+
+ /**
+ * Cache DirectedGraph for workflow
+ */
+ cacheGraph(workflowId: string, graph: DirectedGraph): void {
+ if (!this.enabled) return;
+
+ const size = graph.getNodes().size + graph.getDirectChildren.length * 2;
+ this.graphCache.set(workflowId, graph, size);
+ }
+
+ /**
+ * Get cached DirectedGraph
+ */
+ getCachedGraph(workflowId: string): DirectedGraph | undefined {
+ if (!this.enabled) return undefined;
+
+ return this.graphCache.get(workflowId);
+ }
+
+ /**
+ * Cache parameter value
+ */
+ cacheParameter(
+ workflowId: string,
+ nodeId: string,
+ paramName: string,
+ value: NodeParameterValue
+ ): void {
+ if (!this.enabled) return;
+
+ const key = `${workflowId}:${nodeId}:${paramName}`;
+ const size = this.estimateSize(value);
+ this.parameterCache.set(key, value, size);
+ }
+
+ /**
+ * Get cached parameter value
+ */
+ getCachedParameter(
+ workflowId: string,
+ nodeId: string,
+ paramName: string
+ ): NodeParameterValue | undefined {
+ if (!this.enabled) return undefined;
+
+ const key = `${workflowId}:${nodeId}:${paramName}`;
+ return this.parameterCache.get(key);
+ }
+
+ /**
+ * Cache expression evaluation result
+ */
+ cacheExpression(expression: string, contextHash: string, result: any): void {
+ if (!this.enabled) return;
+
+ const key = `${expression}:${contextHash}`;
+ const size = this.estimateSize(result);
+ this.expressionCache.set(key, result, size);
+ }
+
+ /**
+ * Get cached expression result
+ */
+ getCachedExpression(expression: string, contextHash: string): any | undefined {
+ if (!this.enabled) return undefined;
+
+ const key = `${expression}:${contextHash}`;
+ return this.expressionCache.get(key);
+ }
+
+ /**
+ * Invalidate all caches for a workflow
+ */
+ invalidateWorkflow(workflowId: string): void {
+ // Invalidate execution cache
+ for (const key of this.executionCache.keys()) {
+ if (key.startsWith(`${workflowId}:`)) {
+ this.executionCache.delete(key);
+ }
+ }
+
+ // Invalidate node output cache
+ for (const key of this.nodeOutputCache.keys()) {
+ if (key.startsWith(`${workflowId}:`)) {
+ this.nodeOutputCache.delete(key);
+ }
+ }
+
+ // Invalidate graph cache
+ this.graphCache.delete(workflowId);
+
+ // Invalidate parameter cache
+ for (const key of this.parameterCache.keys()) {
+ if (key.startsWith(`${workflowId}:`)) {
+ this.parameterCache.delete(key);
+ }
+ }
+ }
+
+ /**
+ * Invalidate cache for a specific node
+ */
+ invalidateNode(workflowId: string, nodeId: string): void {
+ // Invalidate node output cache
+ for (const key of this.nodeOutputCache.keys()) {
+ if (key.startsWith(`${workflowId}:${nodeId}:`)) {
+ this.nodeOutputCache.delete(key);
+ }
+ }
+
+ // Invalidate parameter cache
+ for (const key of this.parameterCache.keys()) {
+ if (key.startsWith(`${workflowId}:${nodeId}:`)) {
+ this.parameterCache.delete(key);
+ }
+ }
+ }
+
+ /**
+ * Clear all caches
+ */
+ clearAll(): void {
+ this.executionCache.clear();
+ this.nodeOutputCache.clear();
+ this.graphCache.clear();
+ this.parameterCache.clear();
+ this.expressionCache.clear();
+ }
+
+ /**
+ * Enable/disable caching
+ */
+ setEnabled(enabled: boolean): void {
+ this.enabled = enabled;
+ if (!enabled) {
+ this.clearAll();
+ }
+ }
+
+ /**
+ * Check if caching is enabled
+ */
+ isEnabled(): boolean {
+ return this.enabled;
+ }
+
+ /**
+ * Get comprehensive cache statistics
+ */
+ getStats(): {
+ execution: ICacheStats;
+ nodeOutput: ICacheStats;
+ graph: ICacheStats;
+ parameter: ICacheStats;
+ expression: ICacheStats;
+ total: {
+ hits: number;
+ misses: number;
+ hitRate: number;
+ totalSize: number;
+ totalEntries: number;
+ };
+ } {
+ const executionStats = this.executionCache.getStats();
+ const nodeOutputStats = this.nodeOutputCache.getStats();
+ const graphStats = this.graphCache.getStats();
+ const parameterStats = this.parameterCache.getStats();
+ const expressionStats = this.expressionCache.getStats();
+
+ const totalHits =
+ executionStats.hits +
+ nodeOutputStats.hits +
+ graphStats.hits +
+ parameterStats.hits +
+ expressionStats.hits;
+
+ const totalMisses =
+ executionStats.misses +
+ nodeOutputStats.misses +
+ graphStats.misses +
+ parameterStats.misses +
+ expressionStats.misses;
+
+ const total = totalHits + totalMisses;
+
+ return {
+ execution: executionStats,
+ nodeOutput: nodeOutputStats,
+ graph: graphStats,
+ parameter: parameterStats,
+ expression: expressionStats,
+ total: {
+ hits: totalHits,
+ misses: totalMisses,
+ hitRate: total > 0 ? totalHits / total : 0,
+ totalSize:
+ executionStats.size +
+ nodeOutputStats.size +
+ graphStats.size +
+ parameterStats.size +
+ expressionStats.size,
+ totalEntries:
+ executionStats.entries +
+ nodeOutputStats.entries +
+ graphStats.entries +
+ parameterStats.entries +
+ expressionStats.entries,
+ },
+ };
+ }
+
+ /**
+ * Start periodic cleanup of expired entries
+ */
+ private startCleanup(): void {
+ if (this.cleanupInterval) return;
+
+ this.cleanupInterval = setInterval(() => {
+ this.executionCache.cleanup();
+ this.nodeOutputCache.cleanup();
+ this.graphCache.cleanup();
+ this.parameterCache.cleanup();
+ this.expressionCache.cleanup();
+ }, 60 * 1000); // Cleanup every minute
+ }
+
+ /**
+ * Stop periodic cleanup
+ */
+ stopCleanup(): void {
+ if (this.cleanupInterval) {
+ clearInterval(this.cleanupInterval);
+ this.cleanupInterval = null;
+ }
+ }
+
+ /**
+ * Estimate size of data for cache management
+ */
+ private estimateSize(data: any): number {
+ if (data === null || data === undefined) return 1;
+
+ if (typeof data === 'string') return data.length;
+ if (typeof data === 'number') return 8;
+ if (typeof data === 'boolean') return 4;
+
+ if (Array.isArray(data)) {
+ return data.reduce((sum: number, item) => sum + this.estimateSize(item), 10);
+ }
+
+ if (typeof data === 'object') {
+ return Object.values(data).reduce((sum: number, value) => sum + this.estimateSize(value), 10);
+ }
+
+ return 1;
+ }
+}
+
+/**
+ * Global workflow cache instance
+ */
+export const globalWorkflowCache = new WorkflowCache();
+
+/**
+ * Hash function for creating cache keys
+ */
+export function hashData(data: any): string {
+ const str = JSON.stringify(data);
+ let hash = 0;
+
+ for (let i = 0; i < str.length; i++) {
+ const char = str.charCodeAt(i);
+ hash = (hash << 5) - hash + char;
+ hash = hash & hash; // Convert to 32-bit integer
+ }
+
+ return hash.toString(36);
+}
+
+/**
+ * Memoize function results
+ */
+export function memoize<T extends (...args: any[]) => any>(
+ fn: T,
+ keyFn?: (...args: Parameters<T>) => string
+): T {
+ const cache = new Map<string, ReturnType<T>>();
+
+ return ((...args: Parameters<T>): ReturnType<T> => {
+ const key = keyFn ? keyFn(...args) : JSON.stringify(args);
+
+ if (cache.has(key)) {
+ return cache.get(key)!;
+ }
+
+ const result = fn(...args);
+ cache.set(key, result);
+
+ return result;
+ }) as T;
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/WorkflowDataProxy.ts b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowDataProxy.ts
new file mode 100644
index 000000000..590b562c3
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowDataProxy.ts
@@ -0,0 +1,186 @@
+/**
+ * Workflow Data Proxy
+ * Provides access to workflow data during node execution
+ *
+ * This class acts as a context provider for nodes to access:
+ * - Other nodes in the workflow
+ * - Execution data from previous nodes
+ * - Workflow-level static data
+ */
+
+import {
+ IWorkflowDataProxy,
+ INode,
+ INodeExecutionData,
+ IDataObject,
+ IWorkflow,
+ IRunData,
+} from './types';
+
+export class WorkflowDataProxy implements IWorkflowDataProxy {
+ private workflow: IWorkflow;
+ private runData: IRunData;
+ private staticData: IDataObject;
+
+ constructor(workflow: IWorkflow, runData: IRunData = {}, staticData: IDataObject = {}) {
+ this.workflow = workflow;
+ this.runData = runData;
+ this.staticData = staticData;
+ }
+
+ /**
+ * Get a node by name
+ */
+ getNode(nodeName: string): INode | null {
+ const node = this.workflow.nodes.find((n) => n.name === nodeName);
+ return node || null;
+ }
+
+ /**
+ * Get execution data from a specific node
+ */
+ getNodeData(nodeName: string, runIndex: number = 0): INodeExecutionData[] | null {
+ const nodeData = this.runData[nodeName];
+
+ if (!nodeData || !nodeData[runIndex]) {
+ return null;
+ }
+
+ // Return main output data
+ return nodeData[runIndex].data.main?.[0] || null;
+ }
+
+ /**
+ * Get workflow static data
+ * Static data persists across workflow executions
+ */
+ getWorkflowStaticData(type: string): IDataObject {
+ if (!this.staticData[type]) {
+ this.staticData[type] = {};
+ }
+
+ return this.staticData[type] as IDataObject;
+ }
+
+ /**
+ * Get all nodes in workflow
+ */
+ getAllNodes(): INode[] {
+ return this.workflow.nodes;
+ }
+
+ /**
+ * Get workflow metadata
+ */
+ getWorkflowMetadata(): {
+ id?: string;
+ name: string;
+ active: boolean;
+ } {
+ return {
+ id: this.workflow.id,
+ name: this.workflow.name,
+ active: this.workflow.active,
+ };
+ }
+
+ /**
+ * Get nodes connected to a specific node's input
+ */
+ getParentNodes(nodeName: string, inputIndex: number = 0): Array<{
+ node: INode;
+ outputIndex: number;
+ }> {
+ const parents: Array<{ node: INode; outputIndex: number }> = [];
+
+ // Get connections for this node
+ const nodeConnections = this.workflow.connections[nodeName];
+ if (!nodeConnections) {
+ return parents;
+ }
+
+ // Look through all connection types
+ for (const [connectionType, connections] of Object.entries(nodeConnections)) {
+ if (!connections[inputIndex]) continue;
+
+ for (const connection of connections[inputIndex]) {
+ const parentNode = this.getNode(connection.node);
+ if (parentNode) {
+ parents.push({
+ node: parentNode,
+ outputIndex: connection.index,
+ });
+ }
+ }
+ }
+
+ return parents;
+ }
+
+ /**
+ * Get nodes connected to a specific node's output
+ */
+ getChildNodes(nodeName: string, outputIndex: number = 0): Array<{
+ node: INode;
+ inputIndex: number;
+ }> {
+ const children: Array<{ node: INode; inputIndex: number }> = [];
+
+ // Search through all node connections
+ for (const [targetNodeName, nodeConnections] of Object.entries(this.workflow.connections)) {
+ for (const connections of Object.values(nodeConnections)) {
+ for (let inputIndex = 0; inputIndex < connections.length; inputIndex++) {
+ const inputConnections = connections[inputIndex];
+
+ for (const connection of inputConnections) {
+ if (connection.node === nodeName && connection.index === outputIndex) {
+ const childNode = this.getNode(targetNodeName);
+ if (childNode) {
+ children.push({
+ node: childNode,
+ inputIndex,
+ });
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return children;
+ }
+
+ /**
+ * Check if a node has been executed
+ */
+ hasNodeExecuted(nodeName: string): boolean {
+ return this.runData[nodeName] !== undefined && this.runData[nodeName].length > 0;
+ }
+
+ /**
+ * Get execution status of a node
+ */
+ getNodeExecutionStatus(nodeName: string, runIndex: number = 0): string | undefined {
+ const nodeData = this.runData[nodeName];
+
+ if (!nodeData || !nodeData[runIndex]) {
+ return undefined;
+ }
+
+ return nodeData[runIndex].executionStatus;
+ }
+
+ /**
+ * Update run data (used by executor)
+ */
+ updateRunData(runData: IRunData): void {
+ this.runData = runData;
+ }
+
+ /**
+ * Update static data (used by executor)
+ */
+ updateStaticData(staticData: IDataObject): void {
+ this.staticData = staticData;
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/WorkflowExecutor.ts b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowExecutor.ts
new file mode 100644
index 000000000..3e6478a63
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/WorkflowExecutor.ts
@@ -0,0 +1,689 @@
+/**
+ * Workflow Executor - OPTIMIZED VERSION
+ * Executes workflows efficiently using DirectedGraph and partial execution
+ *
+ * Performance Features (from n8n):
+ * - DirectedGraph for efficient workflow analysis
+ * - Partial execution (only run dirty nodes)
+ * - Parallel execution opportunities
+ * - Cycle detection and handling
+ * - Smart start node finding
+ * - Subgraph extraction
+ * - Run data cleaning
+ *
+ * Based on n8n's execution-engine architecture
+ */
+
+import {
+ IWorkflow,
+ INode,
+ IRunExecutionData,
+ IRunData,
+ ITaskData,
+ IExecuteData,
+ ITaskDataConnections,
+ NodeConnectionType,
+ INodeExecutionData,
+ NodeError,
+ IPinData,
+ IExecutionState,
+} from './types';
+import { NodeRegistry } from './NodeRegistry';
+import { ExecutionContext } from './ExecutionContext';
+import { WorkflowDataProxy } from './WorkflowDataProxy';
+import { DirectedGraph } from './DirectedGraph';
+import {
+ isDirty,
+ findStartNodes,
+ findSubgraph,
+ cleanRunData,
+ handleCycles,
+ filterDisabledNodes,
+ recreateNodeExecutionStack,
+ findTriggerForPartialExecution,
+ calculateExecutionOrder,
+} from './PartialExecutionUtils';
+import {
+ globalHooks,
+ HookEventType,
+ type IWorkflowExecuteStartEvent,
+ type IWorkflowExecuteEndEvent,
+ type IWorkflowExecuteErrorEvent,
+ type INodeExecuteStartEvent,
+ type INodeExecuteEndEvent,
+ type INodeExecuteErrorEvent,
+} from './ExecutionHooks';
+import { globalWorkflowCache, hashData } from './WorkflowCache';
+
+export class WorkflowExecutor {
+ private workflow: IWorkflow;
+ private executionId: string;
+ private graph: DirectedGraph;
+ private enablePartialExecution: boolean = true;
+ private enableCaching: boolean = true;
+
+ constructor(workflow: IWorkflow, executionId?: string) {
+ this.workflow = workflow;
+ this.executionId = executionId || this.generateExecutionId();
+
+ // Try to get cached DirectedGraph
+ const workflowId = this.workflow.id || 'default';
+ const cachedGraph = this.enableCaching ? globalWorkflowCache.getCachedGraph(workflowId) : undefined;
+
+ if (cachedGraph) {
+ this.graph = cachedGraph;
+ console.log('[WorkflowExecutor] Using cached DirectedGraph');
+ } else {
+ // Create DirectedGraph from workflow for efficient operations
+ this.graph = DirectedGraph.fromWorkflow(workflow);
+
+ // Cache the graph
+ if (this.enableCaching && workflowId) {
+ globalWorkflowCache.cacheGraph(workflowId, this.graph);
+ }
+
+ console.log('[WorkflowExecutor] Initialized with DirectedGraph');
+ }
+ }
+
+ /**
+ * Execute the workflow with optimizations
+ *
+ * Supports:
+ * - Full execution (all nodes)
+ * - Partial execution (only dirty nodes)
+ * - Pinned data support
+ * - Cycle detection
+ */
+ async execute(
+ startNodeName?: string,
+ pinData?: IPinData,
+ existingRunData?: IRunData
+ ): Promise<IRunExecutionData> {
+ const startTime = Date.now();
+ console.log(`[WorkflowExecutor] Starting execution: ${this.executionId}`);
+
+ // Emit workflow start hook
+ await globalHooks.emit({
+ type: HookEventType.WorkflowExecuteStart,
+ timestamp: new Date(),
+ executionId: this.executionId,
+ workflowId: this.workflow.id,
+ workflow: this.workflow,
+ startNode: startNodeName,
+ } as IWorkflowExecuteStartEvent);
+
+ // Detect cycles
+ const cycleCheck = handleCycles(this.graph);
+ if (cycleCheck.hasCycles) {
+ console.warn('[WorkflowExecutor] Detected cycles in workflow:', cycleCheck.cycleNodes);
+ }
+
+ // Merge existing run data with new execution
+ const baseRunData = existingRunData || {};
+ const mergedPinData = { ...this.workflow.pinData, ...pinData };
+
+ // Initialize execution state
+ const executionState: IExecutionState = {
+ runData: { ...baseRunData },
+ pinData: mergedPinData,
+ nodeExecutionStack: [],
+ waitingExecution: {},
+ };
+
+ // Create workflow data proxy
+ const workflowDataProxy = new WorkflowDataProxy(
+ this.workflow,
+ executionState.runData,
+ this.workflow.staticData || {}
+ );
+
+ // Determine execution strategy
+ let nodesToExecute: INode[];
+
+ if (startNodeName) {
+ // Execute from specific start node
+ const startNode = this.workflow.nodes.find((n) => n.name === startNodeName);
+ if (!startNode) {
+ throw new Error(`Start node not found: ${startNodeName}`);
+ }
+
+ nodesToExecute = [startNode];
+ console.log('[WorkflowExecutor] Executing from specific start node:', startNodeName);
+ } else if (this.enablePartialExecution && Object.keys(baseRunData).length > 0) {
+ // Partial execution - only run dirty nodes
+ nodesToExecute = this.findNodesToExecutePartially(executionState);
+ console.log('[WorkflowExecutor] Partial execution:', nodesToExecute.map((n) => n.name));
+ } else {
+ // Full execution - run all nodes
+ nodesToExecute = this.findNodesToExecuteFully();
+ console.log('[WorkflowExecutor] Full execution:', nodesToExecute.map((n) => n.name));
+ }
+
+ // Filter out disabled nodes
+ const filteredGraph = filterDisabledNodes(this.graph);
+
+ // Build execution stack
+ for (const node of nodesToExecute) {
+ executionState.nodeExecutionStack.push({
+ node,
+ data: { main: [[{ json: {} }]] },
+ source: null,
+ });
+ }
+
+ // Execute nodes in order
+ const executedNodes = new Set<string>();
+
+ while (executionState.nodeExecutionStack.length > 0) {
+ const executeData = executionState.nodeExecutionStack.shift()!;
+
+ try {
+ // Skip if already executed
+ if (executedNodes.has(executeData.node.name)) {
+ continue;
+ }
+
+ // Check if node is disabled
+ if (executeData.node.disabled) {
+ console.log(`[WorkflowExecutor] Skipping disabled node: ${executeData.node.name}`);
+ continue;
+ }
+
+ // Check if pinned
+ if (executionState.pinData[executeData.node.name]) {
+ console.log(`[WorkflowExecutor] Using pinned data for: ${executeData.node.name}`);
+
+ executionState.runData[executeData.node.name] = [
+ {
+ data: { main: [executionState.pinData[executeData.node.name]] },
+ executionTime: 0,
+ executionStatus: 'success',
+ startTime: Date.now(),
+ source: [],
+ },
+ ];
+
+ executedNodes.add(executeData.node.name);
+
+ // Add downstream nodes
+ await this.addDownstreamNodesOptimized(
+ executeData.node,
+ executionState,
+ workflowDataProxy,
+ filteredGraph
+ );
+ continue;
+ }
+
+ // Check if all parent nodes have executed
+ const parents = filteredGraph.getDirectParents(executeData.node);
+ const allParentsExecuted = parents.every(
+ (p) => executedNodes.has(p.name) || executionState.pinData[p.name]
+ );
+
+ if (!allParentsExecuted) {
+ // Re-add to end of stack and continue
+ executionState.nodeExecutionStack.push(executeData);
+ continue;
+ }
+
+ // Execute node
+ console.log(`[WorkflowExecutor] Executing node: ${executeData.node.name}`);
+
+ // Emit node start hook
+ await globalHooks.emit({
+ type: HookEventType.NodeExecuteStart,
+ timestamp: new Date(),
+ executionId: this.executionId,
+ workflowId: this.workflow.id,
+ nodeName: executeData.node.name,
+ node: executeData.node,
+ inputData: executeData.data.main[0] || [],
+ } as INodeExecuteStartEvent);
+
+ const nodeStartTime = Date.now();
+
+ // Try to get cached node output
+ const workflowId = this.workflow.id || 'default';
+ const inputHash = hashData(executeData.data);
+ let taskData: ITaskData;
+
+ const cachedOutput = this.enableCaching
+ ? globalWorkflowCache.getCachedNodeOutput(workflowId, executeData.node.name, inputHash)
+ : undefined;
+
+ if (cachedOutput) {
+ console.log(`[WorkflowExecutor] Using cached output for: ${executeData.node.name}`);
+ taskData = {
+ data: { main: cachedOutput },
+ executionTime: 0,
+ executionStatus: 'success',
+ startTime: nodeStartTime,
+ source: [],
+ };
+ } else {
+ // Execute node
+ taskData = await this.executeNode(
+ executeData.node,
+ executeData.data,
+ workflowDataProxy,
+ executionState.runData
+ );
+
+ // Cache the output
+ if (this.enableCaching && taskData.executionStatus === 'success' && taskData.data.main) {
+ globalWorkflowCache.cacheNodeOutput(
+ workflowId,
+ executeData.node.name,
+ inputHash,
+ taskData.data.main as INodeExecutionData[][]
+ );
+ }
+ }
+
+ // Store result
+ if (!executionState.runData[executeData.node.name]) {
+ executionState.runData[executeData.node.name] = [];
+ }
+ executionState.runData[executeData.node.name].push(taskData);
+
+ executedNodes.add(executeData.node.name);
+
+ // Emit node end hook
+ const nodeDuration = Date.now() - nodeStartTime;
+ await globalHooks.emit({
+ type: HookEventType.NodeExecuteEnd,
+ timestamp: new Date(),
+ executionId: this.executionId,
+ workflowId: this.workflow.id,
+ nodeName: executeData.node.name,
+ node: executeData.node,
+ outputData: taskData.data.main || [],
+ duration: nodeDuration,
+ } as INodeExecuteEndEvent);
+
+ // Update proxy with new run data
+ workflowDataProxy.updateRunData(executionState.runData);
+
+ // Add downstream nodes
+ await this.addDownstreamNodesOptimized(
+ executeData.node,
+ executionState,
+ workflowDataProxy,
+ filteredGraph
+ );
+ } catch (error: any) {
+ console.error(`[WorkflowExecutor] Error executing ${executeData.node.name}:`, error);
+
+ // Emit node error hook
+ await globalHooks.emit({
+ type: HookEventType.NodeExecuteError,
+ timestamp: new Date(),
+ executionId: this.executionId,
+ workflowId: this.workflow.id,
+ nodeName: executeData.node.name,
+ node: executeData.node,
+ error: error as NodeError,
+ continueOnFail: executeData.node.continueOnFail || false,
+ } as INodeExecuteErrorEvent);
+
+ // Store error
+ if (!executionState.runData[executeData.node.name]) {
+ executionState.runData[executeData.node.name] = [];
+ }
+
+ executionState.runData[executeData.node.name].push({
+ data: { main: [] },
+ executionTime: 0,
+ executionStatus: 'error',
+ startTime: Date.now(),
+ error: error as NodeError,
+ source: [],
+ });
+
+ executedNodes.add(executeData.node.name);
+
+ // Check if should continue on fail
+ if (!executeData.node.continueOnFail) {
+ console.log('[WorkflowExecutor] Stopping execution due to error');
+ break;
+ }
+
+ console.log('[WorkflowExecutor] Continuing execution despite error');
+ }
+ }
+
+ console.log('[WorkflowExecutor] Execution complete');
+
+ const executionResult = {
+ resultData: {
+ runData: executionState.runData,
+ pinData: executionState.pinData,
+ },
+ executionData: {
+ contextData: {},
+ nodeExecutionStack: [],
+ waitingExecution: {},
+ metadata: {},
+ },
+ };
+
+ // Emit workflow end hook
+ const duration = Date.now() - startTime;
+ await globalHooks.emit({
+ type: HookEventType.WorkflowExecuteEnd,
+ timestamp: new Date(),
+ executionId: this.executionId,
+ workflowId: this.workflow.id,
+ workflow: this.workflow,
+ executionData: executionResult,
+ success: true,
+ duration,
+ } as IWorkflowExecuteEndEvent);
+
+ return executionResult;
+ }
+
+ /**
+ * Find nodes to execute for partial execution
+ *
+ * Uses DirectedGraph to find dirty nodes and rebuild execution path
+ */
+ private findNodesToExecutePartially(executionState: IExecutionState): INode[] {
+ // Find all dirty nodes
+ const dirtyNodes: INode[] = [];
+ const allNodes = Array.from(this.graph.getNodes().values());
+
+ for (const node of allNodes) {
+ if (isDirty(node, executionState.runData, executionState.pinData)) {
+ dirtyNodes.push(node);
+ }
+ }
+
+ if (dirtyNodes.length === 0) {
+ // No dirty nodes, nothing to execute
+ return [];
+ }
+
+ // For each dirty node, find path from trigger
+ const nodesToExecute = new Set<INode>();
+
+ for (const dirtyNode of dirtyNodes) {
+ // Find trigger for this node
+ const trigger = findTriggerForPartialExecution(this.graph, dirtyNode);
+
+ if (!trigger) {
+ // No trigger found, use the dirty node itself
+ nodesToExecute.add(dirtyNode);
+ continue;
+ }
+
+ // Find start nodes from trigger to dirty node
+ const startNodes = findStartNodes({
+ graph: this.graph,
+ trigger,
+ destination: dirtyNode,
+ runData: executionState.runData,
+ pinData: executionState.pinData,
+ });
+
+ // Add all nodes in execution path
+ for (const startNode of startNodes) {
+ const subgraph = findSubgraph({
+ graph: this.graph,
+ trigger: startNode,
+ destination: dirtyNode,
+ });
+
+ const subgraphNodes = Array.from(subgraph.getNodes().values());
+ subgraphNodes.forEach((n) => nodesToExecute.add(n));
+ }
+ }
+
+ return Array.from(nodesToExecute);
+ }
+
+ /**
+ * Find nodes to execute for full execution
+ *
+ * Returns all nodes in topological order
+ */
+ private findNodesToExecuteFully(): INode[] {
+ // Get execution order (nodes grouped by level)
+ const levels = calculateExecutionOrder(this.graph);
+
+ // Flatten levels into single array
+ const allNodes: INode[] = [];
+ for (const level of levels) {
+ allNodes.push(...level);
+ }
+
+ return allNodes;
+ }
+
+ /**
+ * Execute a single node
+ */
+ private async executeNode(
+ node: INode,
+ inputData: ITaskDataConnections,
+ workflowDataProxy: WorkflowDataProxy,
+ runData: IRunData
+ ): Promise<ITaskData> {
+ const startTime = Date.now();
+
+ try {
+ // Get node type
+ const nodeType = NodeRegistry.getNodeType(node.type, node.typeVersion);
+
+ // Create execution context
+ const context = new ExecutionContext(
+ workflowDataProxy,
+ node,
+ inputData,
+ runData,
+ 0, // runIndex
+ this.executionId,
+ this.workflow.id || ''
+ );
+
+ // Execute node
+ if (!nodeType.execute) {
+ throw new Error(`Node type ${node.type} does not have an execute function`);
+ }
+
+ const result = await nodeType.execute.call(context);
+
+ const executionTime = Date.now() - startTime;
+
+ return {
+ data: { main: result },
+ executionTime,
+ executionStatus: 'success',
+ startTime,
+ source: [],
+ hints: context.getExecutionHints(),
+ };
+ } catch (error: any) {
+ const executionTime = Date.now() - startTime;
+
+ throw {
+ ...error,
+ node,
+ executionTime,
+ };
+ }
+ }
+
+ /**
+ * Add downstream nodes to execution stack (OPTIMIZED)
+ *
+ * Uses DirectedGraph for efficient child node lookups
+ */
+ private async addDownstreamNodesOptimized(
+ node: INode,
+ executionState: IExecutionState,
+ workflowDataProxy: WorkflowDataProxy,
+ graph: DirectedGraph
+ ): Promise<void> {
+ // Get direct children from graph (more efficient than proxy)
+ const children = graph.getDirectChildren(node);
+
+ for (const childNode of children) {
+ // Check if already in stack or executed
+ const alreadyInStack = executionState.nodeExecutionStack.some(
+ (item) => item.node.name === childNode.name
+ );
+
+ if (alreadyInStack) {
+ continue;
+ }
+
+ // Skip if disabled
+ if (childNode.disabled) {
+ continue;
+ }
+
+ // Build input data for child node
+ const inputData = await this.buildInputDataOptimized(
+ childNode,
+ executionState,
+ graph
+ );
+
+ // Add to execution stack
+ executionState.nodeExecutionStack.push({
+ node: childNode,
+ data: inputData,
+ source: {
+ main: [
+ {
+ node: node.name,
+ data: executionState.runData[node.name][0].data,
+ },
+ ],
+ },
+ });
+ }
+ }
+
+ /**
+ * DEPRECATED: Old method - kept for backward compatibility
+ * Use addDownstreamNodesOptimized instead
+ */
+ private async addDownstreamNodes(
+ node: INode,
+ executionState: IExecutionState,
+ workflowDataProxy: WorkflowDataProxy
+ ): Promise<void> {
+ return this.addDownstreamNodesOptimized(
+ node,
+ executionState,
+ workflowDataProxy,
+ this.graph
+ );
+ }
+
+ /**
+ * Build input data for a node from its parent nodes (OPTIMIZED)
+ *
+ * Uses DirectedGraph for parent node lookups
+ */
+ private async buildInputDataOptimized(
+ node: INode,
+ executionState: IExecutionState,
+ graph: DirectedGraph
+ ): Promise<ITaskDataConnections> {
+ const inputData: ITaskDataConnections = {
+ main: [],
+ };
+
+ // Get parent connections from graph
+ const parentConnections = graph.getDirectParentConnections(node);
+
+ // Group connections by input index
+ const connectionsByInput = new Map<number, typeof parentConnections>();
+
+ for (const connection of parentConnections) {
+ if (!connectionsByInput.has(connection.inputIndex)) {
+ connectionsByInput.set(connection.inputIndex, []);
+ }
+ connectionsByInput.get(connection.inputIndex)!.push(connection);
+ }
+
+ // Build input data for each input
+ for (const [inputIndex, connections] of connectionsByInput) {
+ if (!inputData.main[inputIndex]) {
+ inputData.main[inputIndex] = [];
+ }
+
+ for (const connection of connections) {
+ // Get parent's execution data
+ const parentRunData = executionState.runData[connection.from.name];
+
+ if (!parentRunData || parentRunData.length === 0) {
+ // Check for pinned data
+ const pinnedData = executionState.pinData[connection.from.name];
+ if (pinnedData) {
+ inputData.main[inputIndex].push(...pinnedData);
+ }
+ continue;
+ }
+
+ // Get output data from parent
+ const parentOutputData =
+ parentRunData[0].data[connection.type]?.[connection.outputIndex] || [];
+
+ inputData.main[inputIndex].push(...parentOutputData);
+ }
+ }
+
+ return inputData;
+ }
+
+ /**
+ * DEPRECATED: Old method - kept for backward compatibility
+ * Use buildInputDataOptimized instead
+ */
+ private async buildInputData(
+ node: INode,
+ executionState: IExecutionState,
+ workflowDataProxy: WorkflowDataProxy
+ ): Promise<ITaskDataConnections> {
+ return this.buildInputDataOptimized(node, executionState, this.graph);
+ }
+
+ /**
+ * Find the start node (OPTIMIZED)
+ *
+ * Uses DirectedGraph.getStartNodes() for O(1) lookup
+ */
+ private findStartNode(): INode | undefined {
+ const startNodes = this.graph.getStartNodes();
+
+ if (startNodes.length === 0) {
+ // Fallback to first node if no start nodes found
+ return this.workflow.nodes[0];
+ }
+
+ // Prefer manual trigger nodes
+ const manualTrigger = startNodes.find(
+ (node) => node.type === 'manualTrigger' || node.type.includes('trigger')
+ );
+
+ if (manualTrigger) {
+ return manualTrigger;
+ }
+
+ // Return first start node
+ return startNodes[0];
+ }
+
+ /**
+ * Generate execution ID
+ */
+ private generateExecutionId(): string {
+ return `exec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/demo.ts b/fincept-terminal-desktop/src/services/nodeSystem/demo.ts
new file mode 100644
index 000000000..ec06c3665
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/demo.ts
@@ -0,0 +1,139 @@
+/**
+ * Node System Demo
+ * Demonstrates how to use the new node system
+ *
+ * This file shows:
+ * - Creating a workflow
+ * - Adding nodes
+ * - Connecting nodes
+ * - Executing the workflow
+ */
+
+import {
+ IWorkflow,
+ INode,
+ NodeConnectionType,
+} from './types';
+import { initializeNodeSystem } from './NodeLoader';
+import { WorkflowExecutor } from './WorkflowExecutor';
+import { NodeRegistry } from './NodeRegistry';
+
+/**
+ * Demo: Simple Stock Data Workflow
+ */
+export async function demoStockDataWorkflow() {
+ console.log('=== Node System Demo: Stock Data Workflow ===\n');
+
+ // 1. Initialize the node system
+ console.log('Step 1: Initializing node system...');
+ await initializeNodeSystem();
+ console.log('✓ Node system initialized\n');
+
+ // 2. Create nodes
+ console.log('Step 2: Creating nodes...');
+
+ const stockDataNode: INode = {
+ id: 'node-1',
+ name: 'AAPL Stock Data',
+ type: 'stockData',
+ typeVersion: 1,
+ position: [100, 100],
+ parameters: {
+ source: 'yfinance',
+ symbol: 'AAPL',
+ interval: '1d',
+ period: '1mo',
+ options: {
+ maxResults: 10,
+ },
+ },
+ };
+
+ console.log('✓ Created Stock Data node\n');
+
+ // 3. Create workflow
+ console.log('Step 3: Creating workflow...');
+
+ const workflow: IWorkflow = {
+ id: 'demo-workflow-1',
+ name: 'Stock Data Demo',
+ active: true,
+ nodes: [stockDataNode],
+ connections: {},
+ settings: {
+ executionOrder: 'v1',
+ },
+ };
+
+ console.log('✓ Workflow created\n');
+
+ // 4. Execute workflow
+ console.log('Step 4: Executing workflow...');
+
+ const executor = new WorkflowExecutor(workflow);
+ const result = await executor.execute();
+
+ console.log('✓ Workflow executed\n');
+
+ // 5. Display results
+ console.log('Step 5: Results:');
+ console.log('================\n');
+
+ for (const [nodeName, taskDataArray] of Object.entries(result.resultData.runData)) {
+ console.log(`Node: ${nodeName}`);
+ console.log(`Status: ${taskDataArray[0].executionStatus}`);
+ console.log(`Execution time: ${taskDataArray[0].executionTime}ms`);
+
+ const outputData = taskDataArray[0].data.main?.[0] || [];
+ console.log(`Output items: ${outputData.length}`);
+
+ if (outputData.length > 0) {
+ console.log('\nSample data (first 3 items):');
+ outputData.slice(0, 3).forEach((item, i) => {
+ console.log(` Item ${i + 1}:`, {
+ symbol: item.json.symbol,
+ datetime: item.json.datetime,
+ close: item.json.close,
+ volume: item.json.volume,
+ });
+ });
+ }
+
+ console.log('');
+ }
+
+ console.log('=== Demo Complete ===\n');
+
+ return result;
+}
+
+/**
+ * Demo: Multi-Node Workflow
+ * (Will be implemented after more nodes are created)
+ */
+export async function demoMultiNodeWorkflow() {
+ console.log('=== Node System Demo: Multi-Node Workflow ===\n');
+ console.log('Coming soon: This will demonstrate multiple nodes connected together');
+ console.log('Examples:');
+ console.log(' - Stock Data → Technical Indicators → Results Display');
+ console.log(' - Stock Data → Portfolio Optimizer → Backtest → Results');
+ console.log(' - Economic Data → AI Analysis → Report Generator');
+ console.log('\n');
+}
+
+/**
+ * Run all demos
+ */
+export async function runAllDemos() {
+ try {
+ await demoStockDataWorkflow();
+ await demoMultiNodeWorkflow();
+ } catch (error) {
+ console.error('Demo failed:', error);
+ }
+}
+
+// If run directly
+if (require.main === module) {
+ runAllDemos().catch(console.error);
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/index.ts b/fincept-terminal-desktop/src/services/nodeSystem/index.ts
new file mode 100644
index 000000000..3621f8271
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/index.ts
@@ -0,0 +1,93 @@
+/**
+ * Node System - Main Entry Point
+ *
+ * This is the n8n-inspired node execution system for Fincept Terminal.
+ * Import from this file to use the node system in your components.
+ */
+
+// Core Types
+export * from './types';
+
+// Execution Context
+export { ExecutionContext, BaseExecuteContext, LoadOptionsContext } from './ExecutionContext';
+
+// Node Registry
+export { NodeRegistry } from './NodeRegistry';
+
+// Workflow Data Proxy
+export { WorkflowDataProxy } from './WorkflowDataProxy';
+
+// Node Loader
+export { NodeLoader, initializeNodeSystem } from './NodeLoader';
+
+// Workflow Executor
+export { WorkflowExecutor } from './WorkflowExecutor';
+
+// Expression Engine
+export { ExpressionEngine, isExpression } from './ExpressionEngine';
+export type { IExpressionContext } from './ExpressionEngine';
+
+// Parameter Processor (value extraction, routing, validation)
+export {
+ extractParameterValue,
+ applyParameterRouting,
+ convertParameterValue,
+ validateParameterValue,
+ processNodeParameters,
+ buildRequestFromRouting,
+} from './ParameterProcessor';
+
+// Execution Hooks (lifecycle events and monitoring)
+export {
+ ExecutionHooksManager,
+ globalHooks,
+ hooks,
+ PerformanceTracker,
+ createPerformanceTracker,
+ HookEventType,
+} from './ExecutionHooks';
+export type {
+ IHookEvent,
+ IWorkflowExecuteStartEvent,
+ IWorkflowExecuteEndEvent,
+ IWorkflowExecuteErrorEvent,
+ INodeExecuteStartEvent,
+ INodeExecuteEndEvent,
+ INodeExecuteErrorEvent,
+ IPerformanceMetricEvent,
+ HookFunction,
+ IHookOptions,
+} from './ExecutionHooks';
+
+// DirectedGraph (for workflow optimization)
+export { DirectedGraph } from './DirectedGraph';
+export type { GraphConnection } from './DirectedGraph';
+
+// Partial Execution Utilities
+export {
+ isDirty,
+ findStartNodes,
+ findSubgraph,
+ cleanRunData,
+ handleCycles,
+ filterDisabledNodes,
+ recreateNodeExecutionStack,
+ findTriggerForPartialExecution,
+ calculateExecutionOrder,
+ getIncomingData,
+ hasIncomingDataFromAnyRun,
+} from './PartialExecutionUtils';
+
+// Workflow Cache (caching and memoization)
+export { WorkflowCache, globalWorkflowCache, hashData, memoize } from './WorkflowCache';
+
+// Re-export commonly used types with simpler names
+export type {
+ INodeType as NodeType,
+ INode as Node,
+ IWorkflow as Workflow,
+ INodeExecutionData as NodeExecutionData,
+ IExecuteFunctions as ExecuteFunctions,
+ INodeTypeDescription as NodeTypeDescription,
+ INodeProperties as NodeProperties,
+} from './types';
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/types.ts b/fincept-terminal-desktop/src/services/nodeSystem/types.ts
new file mode 100644
index 000000000..f94832d1a
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/nodeSystem/types.ts
@@ -0,0 +1,925 @@
+/**
+ * Core Node System Types
+ * Based on n8n architecture, adapted for Fincept Terminal
+ *
+ * This file contains all fundamental types for the node-based workflow system.
+ * Finance-specific extensions are added while maintaining n8n's proven architecture.
+ */
+
+// ================================
+// BASIC DATA TYPES
+// ================================
+
+// Base parameter value - primitives, arrays, and objects
+// Extended to support Collection/FixedCollection default values (empty arrays)
+export type NodeParameterValue =
+ | string
+ | number
+ | boolean
+ | undefined
+ | null
+ | any[] // For Collection/FixedCollection defaults
+ | IDataObject; // For object-type parameters
+
+export type NodeParameterValueType =
+ | NodeParameterValue
+ | INodeParameters
+ | NodeParameterValue[]
+ | INodeParameters[]
+ | INodeParameters[][];
+
+export interface IDataObject {
+ [key: string]: NodeParameterValueType;
+}
+
+export interface INodeParameters {
+ [key: string]: NodeParameterValueType;
+}
+
+// ================================
+// CONNECTION TYPES
+// ================================
+
+/**
+ * Types of connections between nodes
+ * Extended with finance-specific connection types
+ */
+export enum NodeConnectionType {
+ Main = 'main', // Standard data flow
+
+ // AI Connections (from n8n)
+ AiLanguageModel = 'ai_languageModel',
+ AiMemory = 'ai_memory',
+ AiTool = 'ai_tool',
+ AiDocument = 'ai_document',
+ AiVectorStore = 'ai_vectorStore',
+ AiTextSplitter = 'ai_textSplitter',
+ AiEmbedding = 'ai_embedding',
+ AiOutputParser = 'ai_outputParser',
+
+ // Finance-specific connections
+ MarketData = 'finance_marketData', // Real-time market data
+ PortfolioData = 'finance_portfolio', // Portfolio holdings
+ PriceData = 'finance_priceData', // Historical prices
+ FundamentalData = 'finance_fundamental', // Fundamental data
+ TechnicalData = 'finance_technical', // Technical indicators
+ NewsData = 'finance_news', // News and sentiment
+ EconomicData = 'finance_economic', // Economic indicators
+ OptionsData = 'finance_options', // Options chain data
+ BacktestData = 'finance_backtest', // Backtest results
+}
+
+export type MainConnectionType = NodeConnectionType.Main;
+export type AINodeConnectionType = Exclude<NodeConnectionType, NodeConnectionType.Main>;
+export type FinanceConnectionType =
+ | NodeConnectionType.MarketData
+ | NodeConnectionType.PortfolioData
+ | NodeConnectionType.PriceData
+ | NodeConnectionType.FundamentalData
+ | NodeConnectionType.TechnicalData
+ | NodeConnectionType.NewsData
+ | NodeConnectionType.EconomicData
+ | NodeConnectionType.OptionsData
+ | NodeConnectionType.BacktestData;
+
+// ================================
+// NODE EXECUTION DATA
+// ================================
+
+/**
+ * Paired item data - tracks which output item came from which input item
+ * Essential for data lineage and debugging
+ */
+export interface IPairedItemData {
+ item: number; // Index of the item in the input
+ input?: number; // Which input the data came from (for multiple inputs)
+ sourceOverwrite?: ISourceData;
+}
+
+/**
+ * Source data - tracks where data originated from in the workflow
+ */
+export interface ISourceData {
+ previousNode: string;
+ previousNodeOutput?: number;
+ previousNodeRun?: number;
+}
+
+/**
+ * Binary data interface for handling files, images, etc.
+ */
+export interface IBinaryKeyData {
+ [key: string]: IBinaryData;
+}
+
+export interface IBinaryData {
+ data: string; // base64 encoded data or file path
+ mimeType: string;
+ fileName?: string;
+ fileExtension?: string;
+ fileSize?: string;
+ directory?: string;
+ id?: string; // Storage ID for large files
+}
+
+/**
+ * Core execution data structure - the primary data carrier between nodes
+ */
+export interface INodeExecutionData {
+ json: IDataObject; // Main JSON data
+ binary?: IBinaryKeyData; // Binary file data
+ error?: NodeApiError | NodeOperationError; // Error if execution failed
+ pairedItem?: IPairedItemData | IPairedItemData[] | number; // Data lineage
+ metadata?: {
+ subExecution?: {
+ executionId: string;
+ workflowId: string;
+ };
+ };
+}
+
+/**
+ * Task data connections - how data flows between nodes
+ * Each connection type can have multiple outputs (for branching)
+ */
+export interface ITaskDataConnections {
+ [connectionType: string]: Array<INodeExecutionData[] | null>;
+}
+
+// ================================
+// ERROR TYPES
+// ================================
+
+export class NodeError extends Error {
+ constructor(
+ public node: INode,
+ message: string
+ ) {
+ super(message);
+ this.name = 'NodeError';
+ }
+}
+
+export class NodeOperationError extends NodeError {
+ constructor(
+ node: INode,
+ message: string,
+ public description?: string,
+ public itemIndex?: number
+ ) {
+ super(node, message);
+ this.name = 'NodeOperationError';
+ }
+}
+
+export class NodeApiError extends NodeError {
+ constructor(
+ node: INode,
+ public httpCode: number,
+ message: string,
+ public description?: string
+ ) {
+ super(node, message);
+ this.name = 'NodeApiError';
+ }
+}
+
+// ================================
+// NODE PROPERTY TYPES
+// ================================
+
+/**
+ * All supported parameter types
+ * Extended from n8n's 30+ types
+ */
+export enum NodePropertyType {
+ // Basic types
+ String = 'string',
+ Number = 'number',
+ Boolean = 'boolean',
+
+ // Selection types
+ Options = 'options',
+ MultiOptions = 'multiOptions',
+
+ // Complex types
+ Collection = 'collection',
+ FixedCollection = 'fixedCollection',
+ Json = 'json',
+
+ // UI types
+ Notice = 'notice',
+ Button = 'button',
+ Color = 'color',
+ DateTime = 'dateTime',
+ Hidden = 'hidden',
+
+ // Advanced types
+ Filter = 'filter',
+ ResourceLocator = 'resourceLocator',
+ ResourceMapper = 'resourceMapper',
+ CredentialsSelect = 'credentialsSelect',
+ CurlImport = 'curlImport',
+
+ // Finance-specific types
+ StockSymbol = 'stockSymbol', // Stock symbol selector
+ PortfolioSelector = 'portfolioSelector', // Portfolio picker
+ DateRange = 'dateRange', // Date range picker
+ TimeInterval = 'timeInterval', // Time interval (1d, 1h, etc.)
+ TechnicalIndicator = 'technicalIndicator', // Technical indicator selector
+ AssetClass = 'assetClass', // Asset class picker
+}
+
+/**
+ * Field type for validation
+ */
+export enum FieldType {
+ String = 'string',
+ Number = 'number',
+ Boolean = 'boolean',
+ DateTime = 'dateTime',
+ Time = 'time',
+ Object = 'object',
+ Array = 'array',
+ Url = 'url',
+ Email = 'email',
+}
+
+/**
+ * Options for a parameter
+ * Simple options for Options/MultiOptions types
+ */
+export interface INodePropertyOptions {
+ name: string;
+ value: string | number | boolean;
+ description?: string;
+ action?: string;
+ routing?: INodePropertyRouting;
+}
+
+/**
+ * Collection field option - for FixedCollection types
+ * Contains nested parameter structures via 'values' array
+ */
+export interface INodePropertyCollectionValue {
+ name: string;
+ description?: string;
+ displayName?: string;
+ values: INodeProperties[];
+}
+
+/**
+ * Type options for parameters
+ */
+export interface INodePropertyTypeOptions {
+ multipleValues?: boolean;
+ multipleValueButtonText?: string;
+ sortable?: boolean;
+ minValue?: number;
+ maxValue?: number;
+ numberPrecision?: number;
+ password?: boolean;
+ rows?: number;
+ alwaysOpenEditWindow?: boolean;
+ editor?: 'code' | 'json' | 'html';
+ loadOptionsMethod?: string;
+ loadOptionsDependsOn?: string[];
+
+ // Filter specific
+ filter?: {
+ caseSensitive?: boolean | string;
+ typeValidation?: 'strict' | 'loose';
+ version?: number;
+ };
+
+ // Resource locator specific
+ resourceMapper?: {
+ resourceMapperMethod: string;
+ mode: 'add' | 'update';
+ fieldWords?: {
+ singular: string;
+ plural: string;
+ };
+ };
+}
+
+/**
+ * Display options - control when parameters are shown/hidden
+ */
+export interface IDisplayOptions {
+ show?: {
+ [key: string]: NodeParameterValue[];
+ };
+ hide?: {
+ [key: string]: NodeParameterValue[];
+ };
+}
+
+/**
+ * Routing configuration for parameters
+ */
+export interface INodePropertyRouting {
+ request?: {
+ method?: string;
+ url?: string;
+ headers?: IDataObject;
+ body?: IDataObject;
+ };
+ send?: {
+ type?: string;
+ property?: string;
+ value?: string;
+ };
+}
+
+/**
+ * Node property definition
+ */
+export interface INodeProperties {
+ displayName: string;
+ name: string;
+ type: NodePropertyType;
+ typeOptions?: INodePropertyTypeOptions;
+ default: NodeParameterValue;
+ description?: string;
+ hint?: string;
+ placeholder?: string;
+ required?: boolean;
+ displayOptions?: IDisplayOptions;
+
+ // For Options/MultiOptions: simple key-value options
+ // For Collection: nested INodeProperties (parameters themselves)
+ // For FixedCollection: INodePropertyCollectionValue (with 'values' array)
+ options?: INodePropertyOptions[] | INodeProperties[] | INodePropertyCollectionValue[];
+
+ routing?: INodePropertyRouting;
+ validateType?: FieldType;
+ ignoreValidationDuringExecution?: boolean;
+ noDataExpression?: boolean;
+ extractValue?: {
+ type: string;
+ property: string;
+ };
+}
+
+// ================================
+// NODE DESCRIPTION
+// ================================
+
+/**
+ * Node hints - provide guidance to users
+ */
+export interface NodeHint {
+ message: string;
+ type?: 'info' | 'warning' | 'danger';
+ location?: 'outputPane' | 'inputPane' | 'ndv';
+ displayCondition?: string;
+ whenToDisplay?: 'always' | 'beforeExecution' | 'afterExecution';
+}
+
+/**
+ * Node output definition
+ */
+export interface INodeOutputConfiguration {
+ type: NodeConnectionType | string;
+ displayName?: string;
+}
+
+/**
+ * Credential description for node
+ */
+export interface INodeCredentialDescription {
+ name: string;
+ required?: boolean;
+ displayOptions?: IDisplayOptions;
+ testedBy?: string | ICredentialTestRequest;
+}
+
+export interface ICredentialTestRequest {
+ request: {
+ method: string;
+ url: string;
+ headers?: IDataObject;
+ body?: IDataObject;
+ };
+ rules?: Array<{
+ type: 'responseCode' | 'responseSuccessBody' | 'responseErrorBody';
+ properties: IDataObject;
+ }>;
+}
+
+/**
+ * Base node type description
+ */
+export interface INodeTypeBaseDescription {
+ displayName: string;
+ name: string;
+ icon?: string;
+ iconUrl?: string;
+ iconColor?: string;
+ badgeIconUrl?: string;
+ group: string[];
+ description: string;
+ defaultVersion?: number;
+}
+
+/**
+ * Full node type description
+ */
+export interface INodeTypeDescription extends INodeTypeBaseDescription {
+ version: number | number[];
+ subtitle?: string;
+ defaults: {
+ name: string;
+ color?: string;
+ };
+ inputs: NodeConnectionType[] | string;
+ outputs: NodeConnectionType[] | INodeOutputConfiguration[] | string;
+ properties: INodeProperties[];
+ credentials?: INodeCredentialDescription[];
+ hints?: NodeHint[];
+ outputNames?: string[];
+ usableAsTool?: boolean;
+ maxNodes?: number;
+ keepOnlySet?: boolean;
+}
+
+// ================================
+// NODE INTERFACE
+// ================================
+
+/**
+ * Core node instance
+ */
+export interface INode {
+ id: string;
+ name: string;
+ type: string;
+ typeVersion: number;
+ position: [number, number];
+ parameters: INodeParameters;
+ credentials?: {
+ [key: string]: {
+ id: string;
+ name: string;
+ };
+ };
+ disabled?: boolean;
+ notes?: string;
+ notesInFlow?: boolean;
+ color?: string;
+ continueOnFail?: boolean;
+ alwaysOutputData?: boolean;
+ executeOnce?: boolean;
+ retryOnFail?: boolean;
+ maxTries?: number;
+ waitBetweenTries?: number;
+}
+
+// ================================
+// EXECUTION CONTEXT INTERFACES
+// ================================
+
+/**
+ * Options for getting node parameters
+ */
+export interface IGetNodeParameterOptions {
+ extractValue?: boolean;
+ returnObjectType?: 'json' | 'object';
+ fallbackValue?: any;
+}
+
+/**
+ * Workflow data proxy - provides access to workflow data
+ */
+export interface IWorkflowDataProxy {
+ getNode(nodeName: string): INode | null;
+ getNodeData(nodeName: string, runIndex?: number): INodeExecutionData[] | null;
+ getWorkflowStaticData(type: string): IDataObject;
+}
+
+/**
+ * Execute context helpers
+ */
+export interface IExecuteContextHelpers {
+ httpRequest(options: IHttpRequestOptions): Promise<any>;
+ returnJsonArray(items: IDataObject | IDataObject[]): INodeExecutionData[];
+ normalizeItems(items: INodeExecutionData[]): INodeExecutionData[];
+ constructExecutionMetaData(
+ inputData: INodeExecutionData[],
+ options: { itemData: IPairedItemData | IPairedItemData[] }
+ ): INodeExecutionData[];
+}
+
+/**
+ * HTTP request options
+ */
+export interface IHttpRequestOptions {
+ url: string;
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
+ headers?: IDataObject;
+ body?: any;
+ qs?: IDataObject;
+ auth?: {
+ username: string;
+ password: string;
+ } | {
+ bearer: string;
+ };
+ json?: boolean;
+ timeout?: number;
+ returnFullResponse?: boolean;
+ ignoreHttpStatusErrors?: boolean;
+}
+
+/**
+ * Base execution functions - available in all contexts
+ */
+export interface IExecuteFunctionsBase {
+ getNode(): INode;
+ getWorkflow(): IWorkflowDataProxy;
+ getNodeParameter(
+ parameterName: string,
+ itemIndex: number,
+ fallbackValue?: any,
+ options?: IGetNodeParameterOptions
+ ): NodeParameterValueType | object;
+ continueOnFail(): boolean;
+ evaluateExpression(expression: string, itemIndex: number): NodeParameterValueType;
+}
+
+/**
+ * Main execution functions - for standard nodes
+ */
+export interface IExecuteFunctions extends IExecuteFunctionsBase {
+ getInputData(inputIndex?: number, connectionType?: NodeConnectionType): INodeExecutionData[];
+
+ getExecutionId(): string;
+ getWorkflowId(): string;
+
+ helpers: IExecuteContextHelpers;
+
+ // Get credentials
+ getCredentials(type: string): Promise<IDataObject>;
+
+ // Execution metadata
+ getExecutionCancelSignal(): AbortSignal;
+
+ // AI connection helpers
+ getInputConnectionData(
+ connectionType: AINodeConnectionType,
+ itemIndex: number
+ ): Promise<unknown>;
+
+ // Add execution hints
+ addExecutionHints(...hints: NodeExecutionHint[]): void;
+
+ // Send chunks (for streaming)
+ sendChunk?(type: string, itemIndex: number, content?: IDataObject | string): Promise<void>;
+}
+
+/**
+ * Load options functions - for dynamic parameter options
+ */
+export interface ILoadOptionsFunctions extends IExecuteFunctionsBase {
+ getCurrentNodeParameter(parameterName: string): NodeParameterValueType | object | undefined;
+ getCurrentNodeParameters(): INodeParameters | undefined;
+}
+
+/**
+ * Webhook functions - for webhook nodes
+ */
+export interface IWebhookFunctions extends IExecuteFunctionsBase {
+ getRequestObject(): any;
+ getResponseObject(): any;
+ getBodyData(): IDataObject;
+ getHeaderData(): IDataObject;
+ getParamsData(): IDataObject;
+ getQueryData(): IDataObject;
+ getWebhookName(): string;
+}
+
+// ================================
+// NODE TYPE INTERFACE
+// ================================
+
+/**
+ * Node execution hint
+ */
+export interface NodeExecutionHint {
+ message: string;
+ type?: 'info' | 'warning' | 'error';
+ location?: 'outputPane' | 'inputPane';
+ whenToDisplay?: 'always' | 'beforeExecution' | 'afterExecution';
+}
+
+/**
+ * Node output - result of node execution
+ */
+export type NodeOutput = INodeExecutionData[][];
+
+/**
+ * Core node type interface
+ */
+export interface INodeType {
+ description: INodeTypeDescription;
+
+ // Main execution function
+ execute?(this: IExecuteFunctions): Promise<NodeOutput>;
+
+ // Webhook handler
+ webhook?(this: IWebhookFunctions): Promise<any>;
+
+ // Methods for dynamic behavior
+ methods?: {
+ loadOptions?: {
+ [key: string]: (this: ILoadOptionsFunctions) => Promise<INodePropertyOptions[]>;
+ };
+ credentialTest?: {
+ [key: string]: (
+ this: IExecuteFunctions,
+ credential: IDataObject
+ ) => Promise<{ status: 'OK' | 'Error'; message?: string }>;
+ };
+ listSearch?: {
+ [key: string]: (
+ this: ILoadOptionsFunctions,
+ filter?: string,
+ paginationToken?: string
+ ) => Promise<INodeListSearchResult>;
+ };
+ };
+}
+
+export interface INodeListSearchResult {
+ results: INodePropertyOptions[];
+ paginationToken?: string;
+}
+
+// ================================
+// VERSIONED NODE TYPE
+// ================================
+
+/**
+ * Interface for versioned node types
+ */
+export interface IVersionedNodeType {
+ nodeVersions: {
+ [version: number]: INodeType;
+ };
+ currentVersion: number;
+ getNodeType(version?: number): INodeType;
+}
+
+// ================================
+// WORKFLOW EXECUTION
+// ================================
+
+/**
+ * Connection definition
+ */
+export interface IConnection {
+ node: string;
+ type: NodeConnectionType;
+ index: number;
+}
+
+/**
+ * Node connections
+ */
+export interface INodeConnections {
+ [outputType: string]: Array<IConnection[]>;
+}
+
+/**
+ * Workflow connections
+ */
+export interface IConnections {
+ [nodeName: string]: INodeConnections;
+}
+
+/**
+ * Workflow definition
+ */
+export interface IWorkflow {
+ id?: string;
+ name: string;
+ nodes: INode[];
+ connections: IConnections;
+ active: boolean;
+ settings?: IWorkflowSettings;
+ staticData?: IDataObject;
+ pinData?: IPinData;
+}
+
+export interface IWorkflowSettings {
+ executionOrder?: 'v0' | 'v1';
+ saveManualExecutions?: boolean;
+ callerPolicy?: string;
+ errorWorkflow?: string;
+ timezone?: string;
+ saveExecutionProgress?: boolean;
+ saveDataErrorExecution?: 'all' | 'none';
+ saveDataSuccessExecution?: 'all' | 'none';
+}
+
+/**
+ * Pin data for testing
+ */
+export interface IPinData {
+ [nodeName: string]: INodeExecutionData[];
+}
+
+/**
+ * Task data - result of node execution
+ */
+export interface ITaskData {
+ data: ITaskDataConnections;
+ executionTime: number;
+ executionStatus?: 'success' | 'error' | 'unknown';
+ executionIndex?: number;
+ startTime: number;
+ error?: NodeError;
+ hints?: NodeExecutionHint[];
+ source: Array<ISourceData | null>;
+}
+
+/**
+ * Run data - all execution results
+ */
+export interface IRunData {
+ [nodeName: string]: ITaskData[];
+}
+
+/**
+ * Execution state
+ */
+export interface IExecutionState {
+ runData: IRunData;
+ pinData: IPinData;
+ nodeExecutionStack: IExecuteData[];
+ waitingExecution: IWaitingForExecution;
+}
+
+/**
+ * Execute data - node to be executed
+ */
+export interface IExecuteData {
+ node: INode;
+ data: ITaskDataConnections;
+ source: ITaskDataConnectionsSource | null;
+ runIndex?: number;
+}
+
+export interface ITaskDataConnectionsSource {
+ main?: Array<{
+ node: string;
+ data: ITaskDataConnections;
+ }>;
+}
+
+export interface IWaitingForExecution {
+ [nodeName: string]: {
+ [outputIndex: string]: {
+ [connectionIndex: string]: ITaskDataConnections;
+ };
+ };
+}
+
+/**
+ * Run execution data - complete execution state
+ */
+export interface IRunExecutionData {
+ startData?: {
+ destinationNode?: string;
+ runNodeFilter?: string[];
+ };
+ resultData: {
+ runData: IRunData;
+ pinData?: IPinData;
+ };
+ executionData?: {
+ contextData: IDataObject;
+ nodeExecutionStack: IExecuteData[];
+ waitingExecution: IWaitingForExecution;
+ metadata: { [nodeName: string]: ITaskMetadata[] };
+ };
+}
+
+export interface ITaskMetadata {
+ subExecution?: {
+ executionId: string;
+ workflowId: string;
+ };
+}
+
+// ================================
+// CREDENTIALS
+// ================================
+
+export interface ICredentialType {
+ name: string;
+ displayName: string;
+ documentationUrl?: string;
+ properties: INodeProperties[];
+ authenticate?: {
+ type: string;
+ properties: IDataObject;
+ };
+ test?: ICredentialTestRequest;
+}
+
+export interface ICredentialsDecrypted {
+ id: string;
+ name: string;
+ type: string;
+ data: IDataObject;
+}
+
+export interface ICredentialDataDecryptedObject {
+ [key: string]: string | number | boolean;
+}
+
+// ================================
+// FINANCE-SPECIFIC TYPES
+// ================================
+
+/**
+ * Market data structure
+ */
+export interface IMarketData {
+ symbol: string;
+ timestamp: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+ vwap?: number;
+}
+
+/**
+ * Portfolio holding
+ */
+export interface IPortfolioHolding {
+ symbol: string;
+ quantity: number;
+ averageCost: number;
+ currentPrice: number;
+ marketValue: number;
+ unrealizedPL: number;
+ unrealizedPLPercent: number;
+ weight: number;
+}
+
+/**
+ * Technical indicator result
+ */
+export interface ITechnicalIndicatorResult {
+ indicator: string;
+ symbol: string;
+ timestamp: number;
+ values: {
+ [key: string]: number;
+ };
+}
+
+/**
+ * Backtest result
+ */
+export interface IBacktestResult {
+ strategy: string;
+ period: {
+ start: string;
+ end: string;
+ };
+ metrics: {
+ totalReturn: number;
+ annualizedReturn: number;
+ sharpeRatio: number;
+ maxDrawdown: number;
+ winRate: number;
+ profitFactor: number;
+ };
+ trades: IBacktestTrade[];
+}
+
+export interface IBacktestTrade {
+ symbol: string;
+ action: 'BUY' | 'SELL';
+ quantity: number;
+ price: number;
+ timestamp: number;
+ pnl?: number;
+}
+
+// ================================
+// EXPORTS
+// ================================
+
+export type {
+ INodeExecutionData as NodeExecutionData,
+ INodeType as NodeType,
+ INode as Node,
+ IWorkflow as Workflow,
+};
diff --git a/fincept-terminal-desktop/src/services/paymentApi.tsx b/fincept-terminal-desktop/src/services/paymentApi.tsx
index 7c65fa0f0..6c9cfa9b8 100644
--- a/fincept-terminal-desktop/src/services/paymentApi.tsx
+++ b/fincept-terminal-desktop/src/services/paymentApi.tsx
@@ -23,40 +23,58 @@ interface PaymentApiResponse<T = any> {
// Request Types
interface CheckoutRequest {
- plan_id: string;
- return_url?: string;
+ plan_id: string; // Valid values: free, basic, standard, pro, enterprise
+ currency: string; // USD, EUR, INR, etc.
}
// Response Types
interface SubscriptionPlan {
plan_id: string;
name: string;
- description: string;
- price_usd: number;
- billing_interval: string;
- api_calls_limit: number | string;
- databases_access: string[];
- priority_support: boolean;
- features: {
- api_calls: string;
- databases: string;
- support: string;
+ pricing: {
+ currency: string;
+ amount: number;
+ base_usd: number;
+ symbol: string;
};
+ credits: number;
+ validity_days: number;
+ features: string[];
+ is_free: boolean;
+ // Legacy fields for backward compatibility
+ description?: string;
+ price_usd?: number;
+ price_display?: string;
+ credits_amount?: number;
+ support_type?: string;
+ support_display?: string;
+ validity_display?: string;
+ is_popular?: boolean;
+ display_order?: number;
}
interface PlansResponse {
plans: SubscriptionPlan[];
- total_plans: number;
+ currency: string;
+ total_plans?: number;
}
interface CheckoutResponse {
+ order_id: string;
checkout_url: string;
- session_id: string;
- payment_uuid: string;
+ payment_session_id: string;
+ pricing: {
+ currency: string;
+ amount: number;
+ base_usd: number;
+ symbol: string;
+ };
plan: {
name: string;
- price: number;
+ credits: number;
+ validity_days: number;
};
+ expires_at: string;
}
interface UserSubscriptionResponse {
@@ -109,19 +127,7 @@ interface PaymentHistoryResponse {
};
}
-// Payment Window Manager Interface
-interface PaymentWindowManager {
- openPaymentWindow: (url: string, planName: string, planPrice: number) => Promise<boolean>;
-}
-
-// Global payment window manager - will be set by the main app
-let paymentWindowManager: PaymentWindowManager | null = null;
-
-export const setPaymentWindowManager = (manager: PaymentWindowManager) => {
- paymentWindowManager = manager;
-};
-
-// Generic Payment API request function with enhanced debugging
+// Generic Payment API request function
const makePaymentApiRequest = async <T = any>(
method: string,
endpoint: string,
@@ -136,32 +142,6 @@ const makePaymentApiRequest = async <T = any>(
const url = getPaymentApiEndpoint(endpoint);
- // Enhanced debug logging
- console.log('💳 Making payment request:', {
- method,
- url,
- endpoint,
- data,
- timestamp: new Date().toISOString()
- });
-
- // Debug headers (with API key redacted)
- const debugHeaders: any = { ...defaultHeaders };
- if (debugHeaders['X-API-Key']) {
- debugHeaders['X-API-Key'] = '[REDACTED - Length: ' + debugHeaders['X-API-Key'].length + ']';
- }
- console.log('💳 Request headers:', debugHeaders);
-
- // Check if API key is actually present
- const hasApiKey = !!headers?.['X-API-Key'];
- const apiKeyLength = headers?.['X-API-Key']?.length || 0;
- console.log('💳 API Key debug:', {
- hasApiKey,
- apiKeyLength,
- headerKeys: Object.keys(defaultHeaders),
- originalHeaderKeys: headers ? Object.keys(headers) : 'none'
- });
-
const config: RequestInit = {
method,
headers: defaultHeaders,
@@ -170,44 +150,17 @@ const makePaymentApiRequest = async <T = any>(
if (data && (method === 'POST' || method === 'PUT')) {
config.body = JSON.stringify(data);
- console.log('💳 Request body:', JSON.stringify(data, null, 2));
}
- console.log('💳 Final fetch config:', {
- url,
- method: config.method,
- mode: config.mode,
- hasBody: !!config.body,
- bodyLength: config.body ? (config.body as string).length : 0
- });
-
const response = await fetch(url, config);
- console.log('💰 Payment response received:', {
- status: response.status,
- statusText: response.statusText,
- url: response.url,
- ok: response.ok,
- headers: Object.fromEntries(response.headers.entries())
- });
-
const responseText = await response.text();
- console.log('📄 Payment response text (first 500 chars):', responseText.substring(0, 500));
- console.log('📄 Payment response full length:', responseText.length);
let responseData;
try {
responseData = JSON.parse(responseText);
- console.log('✅ Payment JSON parsed successfully:', {
- success: responseData.success,
- hasData: !!responseData.data,
- message: responseData.message,
- error: responseData.error,
- errorCode: responseData.error_code
- });
} catch (parseError) {
- console.error('❌ Payment JSON parse failed:', parseError);
- console.log('📄 Raw response that failed to parse:', responseText);
+ console.error('Payment JSON parse failed:', parseError);
return {
success: false,
error: `Invalid JSON response: ${responseText.substring(0, 100)}...`,
@@ -215,16 +168,8 @@ const makePaymentApiRequest = async <T = any>(
};
}
- // Enhanced response logging for failures
if (!response.ok) {
- console.error('❌ Payment request failed:', {
- status: response.status,
- statusText: response.statusText,
- responseData,
- requestHeaders: debugHeaders,
- requestUrl: url,
- requestMethod: method
- });
+ console.error('Payment request failed:', response.status, responseData.message || response.statusText);
}
return {
@@ -235,12 +180,7 @@ const makePaymentApiRequest = async <T = any>(
};
} catch (error) {
- console.error('💥 Payment request failed completely:', error);
- console.error('💥 Error details:', {
- name: error instanceof Error ? error.name : 'Unknown',
- message: error instanceof Error ? error.message : 'Unknown error',
- stack: error instanceof Error ? error.stack : 'No stack trace'
- });
+ console.error('Payment request error:', error);
if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
return {
@@ -258,67 +198,51 @@ const makePaymentApiRequest = async <T = any>(
// Payment API Service Class with enhanced debugging
export class PaymentApiService {
- // Get all subscription plans
+ // Get all subscription plans from API
static async getSubscriptionPlans(): Promise<PaymentApiResponse<PlansResponse>> {
- console.log('📋 PaymentApiService: Starting getSubscriptionPlans request');
-
- const result = await makePaymentApiRequest<PlansResponse>('GET', '/payment/plans');
+ const response = await makePaymentApiRequest<PlansResponse>('GET', '/payment/plans');
- console.log('📋 PaymentApiService: getSubscriptionPlans result:', {
- success: result.success,
- hasData: !!result.data,
- statusCode: result.status_code,
- error: result.error
- });
+ // Handle double-wrapped response: response.data might contain {success, data: {plans}}
+ let plansData = response.data;
+ if (plansData && (plansData as any).data && (plansData as any).success) {
+ // Double-wrapped - extract the inner data
+ plansData = (plansData as any).data;
+ }
- if (result.success && result.data) {
- console.log('📋 PaymentApiService: Raw API response structure:', {
- dataKeys: Object.keys(result.data),
- hasPlans: !!(result.data as any).plans,
- hasDataProperty: !!(result.data as any).data,
- plansCount: (result.data as any).plans?.length || 'no plans array'
- });
-
- // Check if the data has the expected structure
- if ((result.data as any).plans) {
- console.log('📋 PaymentApiService: Found plans directly in result.data');
- console.log('📋 PaymentApiService: Number of plans:', (result.data as any).plans.length);
- } else if ((result.data as any).data && (result.data as any).data.plans) {
- console.log('📋 PaymentApiService: Found plans in result.data.data');
- console.log('📋 PaymentApiService: Number of plans:', (result.data as any).data.plans.length);
- } else {
- console.log('📋 PaymentApiService: Plans not found in expected location');
- console.log('📋 PaymentApiService: Available properties:', Object.keys(result.data));
- }
+ // Add backward compatibility fields to each plan
+ if (response.success && plansData?.plans) {
+ plansData.plans = plansData.plans.map((plan: any, index: number) => ({
+ ...plan,
+ // Add backward compatibility fields
+ price_usd: plan.pricing?.base_usd || 0,
+ price_display: `${plan.pricing?.symbol || '$'}${plan.pricing?.amount || 0}`,
+ credits_amount: plan.credits || 0,
+ description: plan.features?.join(', ') || '',
+ support_type: plan.is_free ? 'community' : 'priority',
+ support_display: plan.is_free ? 'Community Support' : 'Priority Support',
+ validity_display: plan.validity_days > 0 ? `${plan.validity_days} days` : 'One-time',
+ is_popular: plan.plan_id === 'standard', // Mark standard as popular
+ display_order: index + 1
+ }));
+
+ plansData.total_plans = plansData.plans.length;
+ response.data = plansData;
}
- return result;
+ return response;
}
// Get specific plan details
static async getPlanDetails(planId: string): Promise<PaymentApiResponse<SubscriptionPlan>> {
- console.log('📋 PaymentApiService: Getting plan details for:', planId);
return makePaymentApiRequest<SubscriptionPlan>('GET', `/payment/plans/${planId}`);
}
- // Create checkout session with enhanced debugging
+ // Create checkout session - Updated to use /payment/create-order endpoint
static async createCheckoutSession(
apiKey: string,
request: CheckoutRequest
): Promise<PaymentApiResponse<CheckoutResponse>> {
- console.log('🔑 PaymentApiService: createCheckoutSession called');
- console.log('🔑 PaymentApiService: API Key debug:', {
- hasApiKey: !!apiKey,
- apiKeyType: typeof apiKey,
- apiKeyLength: apiKey?.length || 0,
- apiKeyPrefix: apiKey ? apiKey.substring(0, 10) + '...' : 'null',
- apiKeyValid: apiKey && apiKey.length > 10
- });
- console.log('🔑 PaymentApiService: Request data:', request);
-
- // Verify API key format
if (!apiKey) {
- console.error('🔑 PaymentApiService: No API key provided!');
return {
success: false,
error: 'No API key provided'
@@ -326,33 +250,18 @@ export class PaymentApiService {
}
if (typeof apiKey !== 'string') {
- console.error('🔑 PaymentApiService: API key is not a string:', typeof apiKey);
return {
success: false,
error: 'Invalid API key format'
};
}
- // Test different header variations to debug the issue
const headers = {
'X-API-Key': apiKey
};
- console.log('🔑 PaymentApiService: Headers being passed:', {
- 'X-API-Key': '[REDACTED - Length: ' + apiKey.length + ']',
- headerCount: Object.keys(headers).length
- });
-
- const result = await makePaymentApiRequest<CheckoutResponse>('POST', '/payment/checkout', request, headers);
-
- console.log('🔑 PaymentApiService: createCheckoutSession result:', {
- success: result.success,
- statusCode: result.status_code,
- error: result.error,
- hasData: !!result.data
- });
-
- return result;
+ console.log('Creating payment order:', { plan_id: request.plan_id, currency: request.currency });
+ return await makePaymentApiRequest<CheckoutResponse>('POST', '/payment/create-order', request, headers);
}
// Handle payment success
@@ -361,12 +270,6 @@ export class PaymentApiService {
sessionId?: string,
paymentId?: string
): Promise<PaymentApiResponse<PaymentSuccessResponse>> {
- console.log('✅ PaymentApiService: handlePaymentSuccess called:', {
- hasApiKey: !!apiKey,
- sessionId,
- paymentId
- });
-
const params = new URLSearchParams();
if (sessionId) params.append('session_id', sessionId);
if (paymentId) params.append('payment_id', paymentId);
@@ -381,27 +284,20 @@ export class PaymentApiService {
// Get user's current subscription
static async getUserSubscription(apiKey: string): Promise<PaymentApiResponse<UserSubscriptionResponse>> {
- console.log('👤 PaymentApiService: getUserSubscription called:', {
- hasApiKey: !!apiKey,
- apiKeyLength: apiKey?.length || 0
- });
-
- return makePaymentApiRequest<UserSubscriptionResponse>('GET', '/payment/subscription', undefined, {
+ return makePaymentApiRequest<UserSubscriptionResponse>('GET', '/user/subscriptions', undefined, {
'X-API-Key': apiKey
});
}
// Get user's usage details
static async getUserUsage(apiKey: string): Promise<PaymentApiResponse<any>> {
- console.log('📊 PaymentApiService: getUserUsage called');
- return makePaymentApiRequest('GET', '/payment/usage', undefined, {
+ return makePaymentApiRequest('GET', '/user/usage', undefined, {
'X-API-Key': apiKey
});
}
// Cancel subscription
static async cancelSubscription(apiKey: string): Promise<PaymentApiResponse<any>> {
- console.log('❌ PaymentApiService: cancelSubscription called');
return makePaymentApiRequest('POST', '/payment/cancel', undefined, {
'X-API-Key': apiKey
});
@@ -409,22 +305,20 @@ export class PaymentApiService {
// Reactivate subscription
static async reactivateSubscription(apiKey: string): Promise<PaymentApiResponse<any>> {
- console.log('🔄 PaymentApiService: reactivateSubscription called');
return makePaymentApiRequest('POST', '/payment/reactivate', undefined, {
'X-API-Key': apiKey
});
}
- // Get payment history
+ // Get payment history (transactions)
static async getPaymentHistory(
apiKey: string,
page: number = 1,
limit: number = 10
): Promise<PaymentApiResponse<PaymentHistoryResponse>> {
- console.log('📜 PaymentApiService: getPaymentHistory called:', { page, limit });
return makePaymentApiRequest<PaymentHistoryResponse>(
'GET',
- `/payment/payments?page=${page}&limit=${limit}`,
+ `/user/transactions?page=${page}&limit=${limit}`,
undefined,
{ 'X-API-Key': apiKey }
);
@@ -435,7 +329,6 @@ export class PaymentApiService {
apiKey: string,
paymentUuid: string
): Promise<PaymentApiResponse<any>> {
- console.log('💳 PaymentApiService: getPaymentDetails called:', paymentUuid);
return makePaymentApiRequest(
'GET',
`/payment/payments/${paymentUuid}`,
@@ -446,31 +339,14 @@ export class PaymentApiService {
// Webhook validation (for future use)
static async validateWebhook(webhookData: any): Promise<PaymentApiResponse<any>> {
- console.log('🔗 PaymentApiService: validateWebhook called');
return makePaymentApiRequest('POST', '/payment/webhook', webhookData);
}
// Debug function to test API key validity
static async testApiKey(apiKey: string): Promise<PaymentApiResponse<any>> {
- console.log('🧪 PaymentApiService: Testing API key validity');
- console.log('🧪 API Key test details:', {
- hasApiKey: !!apiKey,
- apiKeyLength: apiKey?.length || 0,
- apiKeyPrefix: apiKey ? apiKey.substring(0, 15) + '...' : 'null'
- });
-
- // Try a simple GET request first
- const testResult = await makePaymentApiRequest('GET', '/payment/subscription', undefined, {
+ return await makePaymentApiRequest('GET', '/payment/subscription', undefined, {
'X-API-Key': apiKey
});
-
- console.log('🧪 API Key test result:', {
- success: testResult.success,
- statusCode: testResult.status_code,
- error: testResult.error
- });
-
- return testResult;
}
}
@@ -598,37 +474,24 @@ static validatePaymentUrl(url: string): boolean {
}
}
- // Updated: Open payment URL using in-app window
+ // Open payment URL in external browser (Tauri shell)
static async openPaymentUrl(
checkoutUrl: string,
planName: string = 'Subscription',
planPrice: number = 0
): Promise<boolean> {
- console.log('PaymentUtils: Opening payment URL:', checkoutUrl);
-
- // Validate the checkout URL
if (!this.validatePaymentUrl(checkoutUrl)) {
- console.error('PaymentUtils: Invalid checkout URL provided');
+ console.error('Invalid checkout URL provided');
alert('Payment URL is invalid. Please try again or contact support.');
return false;
}
try {
- // Try to use in-app payment window first
- if (paymentWindowManager) {
- console.log('PaymentUtils: Using in-app payment window');
- return await paymentWindowManager.openPaymentWindow(checkoutUrl, planName, planPrice);
- }
-
- // Fallback to external browser if in-app window is not available
- console.log('PaymentUtils: Falling back to external browser');
+ // Always use external browser for Tauri
return this.openPaymentUrlExternal(checkoutUrl);
-
} catch (error) {
- console.error('PaymentUtils: Failed to open payment window:', error);
-
- // Final fallback to external browser
- return this.openPaymentUrlExternal(checkoutUrl);
+ console.error('Failed to open payment window:', error);
+ return false;
}
}
@@ -638,9 +501,8 @@ static validatePaymentUrl(url: string): boolean {
planName: string = 'Subscription',
planPrice: number = 0
): Promise<boolean> {
- // Validate URL first
if (!this.validatePaymentUrl(checkoutUrl)) {
- console.error('PaymentUtils: Invalid or suspicious payment URL');
+ console.error('Invalid or suspicious payment URL');
alert('Invalid payment URL. Please contact support.');
return false;
}
@@ -654,7 +516,6 @@ static validatePaymentUrl(url: string): boolean {
const newWindow = window.open(checkoutUrl, '_blank', 'noopener,noreferrer');
if (!newWindow) {
- console.warn('PaymentUtils: Popup blocked, trying clipboard fallback');
// Try to copy URL to clipboard as fallback
if (navigator.clipboard && checkoutUrl !== 'undefined') {
diff --git a/fincept-terminal-desktop/src/services/websocket/EventBus.ts b/fincept-terminal-desktop/src/services/websocket/EventBus.ts
deleted file mode 100644
index 04a5d226d..000000000
--- a/fincept-terminal-desktop/src/services/websocket/EventBus.ts
+++ /dev/null
@@ -1,343 +0,0 @@
-// File: src/services/websocket/EventBus.ts
-// Lightweight pub/sub event bus for distributing WebSocket messages
-
-import { EventBusEvent, MessageCallback, NormalizedMessage } from './types';
-import { websocketLogger } from '../loggerService';
-
-/**
- * Topic subscription metadata
- */
-interface TopicSubscription {
- id: string;
- topic: string;
- pattern: RegExp;
- callback: MessageCallback;
- subscribedAt: number;
-}
-
-/**
- * EventBus - Centralized message distribution using pub/sub pattern
- *
- * Features:
- * - Topic-based subscriptions with wildcard support
- * - Memory-efficient using WeakMap where possible
- * - Topic pattern matching (exact, wildcard, regex)
- * - Message history (optional, for debugging)
- * - Performance monitoring
- */
-export class EventBus {
- private subscriptions: Map<string, TopicSubscription[]> = new Map();
- private messageHistory: EventBusEvent[] = [];
- private maxHistorySize: number = 100;
- private enableHistory: boolean = false;
- private enableLogging: boolean = false;
-
- // Performance metrics
- private messageCount: number = 0;
- private lastMessageTime: number = 0;
- private messageRate: number = 0;
-
- constructor(options?: {
- enableHistory?: boolean;
- maxHistorySize?: number;
- enableLogging?: boolean;
- }) {
- this.enableHistory = options?.enableHistory ?? false;
- this.maxHistorySize = options?.maxHistorySize ?? 100;
- this.enableLogging = options?.enableLogging ?? false;
-
- if (this.enableLogging) {
- websocketLogger.info('EventBus initialized', { historyEnabled: this.enableHistory });
- }
- }
-
- /**
- * Subscribe to a topic with optional wildcard support
- *
- * Examples:
- * - "kraken.ticker.BTC/USD" - exact match
- * - "kraken.ticker.*" - all tickers from Kraken
- * - "kraken.*" - all messages from Kraken
- * - "*.ticker.BTC/USD" - BTC/USD ticker from any provider
- * - "*" - all messages (use sparingly)
- *
- * @returns Unsubscribe function
- */
- subscribe(topic: string, callback: MessageCallback): () => void {
- const subscriptionId = this.generateSubscriptionId();
- const pattern = this.topicToRegex(topic);
-
- const subscription: TopicSubscription = {
- id: subscriptionId,
- topic,
- pattern,
- callback,
- subscribedAt: Date.now()
- };
-
- // Store by exact topic for efficient lookup
- const key = this.getSubscriptionKey(topic);
- if (!this.subscriptions.has(key)) {
- this.subscriptions.set(key, []);
- }
- this.subscriptions.get(key)!.push(subscription);
-
- if (this.enableLogging) {
- websocketLogger.debug(`Subscribed to topic: ${topic}`, { subscriptionId });
- }
-
- // Return unsubscribe function
- return () => this.unsubscribe(subscriptionId, topic);
- }
-
- /**
- * Unsubscribe from a topic
- */
- private unsubscribe(subscriptionId: string, topic: string): void {
- const key = this.getSubscriptionKey(topic);
- const subs = this.subscriptions.get(key);
-
- if (subs) {
- const index = subs.findIndex(s => s.id === subscriptionId);
- if (index !== -1) {
- subs.splice(index, 1);
-
- // Clean up empty subscription arrays
- if (subs.length === 0) {
- this.subscriptions.delete(key);
- }
-
- if (this.enableLogging) {
- websocketLogger.debug(`Unsubscribed from topic: ${topic}`, { subscriptionId });
- }
- }
- }
- }
-
- /**
- * Publish a message to all matching subscribers
- */
- publish(topic: string, message: NormalizedMessage): void {
- const event: EventBusEvent = {
- topic,
- message,
- timestamp: Date.now()
- };
-
- // Update metrics
- this.updateMetrics();
-
- // Add to history if enabled
- if (this.enableHistory) {
- this.addToHistory(event);
- }
-
- // Find all matching subscriptions
- const matchingSubscriptions = this.findMatchingSubscriptions(topic);
-
- // Only log chart/candle related messages
- if (this.enableLogging && matchingSubscriptions.length > 0 && (topic.includes('ohlc') || topic.includes('candle'))) {
- websocketLogger.debug(`Publishing chart data to ${matchingSubscriptions.length} subscribers: ${topic}`);
- }
-
- // Deliver message to all matching subscribers
- matchingSubscriptions.forEach(sub => {
- try {
- sub.callback(message);
- } catch (error) {
- websocketLogger.error(`Error in subscription callback for ${topic}:`, error);
- }
- });
- }
-
- /**
- * Find all subscriptions matching a topic
- */
- private findMatchingSubscriptions(topic: string): TopicSubscription[] {
- const matches: TopicSubscription[] = [];
-
- // Check all subscription patterns
- this.subscriptions.forEach(subs => {
- subs.forEach(sub => {
- if (sub.pattern.test(topic)) {
- matches.push(sub);
- }
- });
- });
-
- return matches;
- }
-
- /**
- * Convert topic pattern to RegExp
- * Supports wildcards: * (any segment), ** (any number of segments)
- */
- private topicToRegex(topic: string): RegExp {
- // Escape special regex characters except *
- const escaped = topic.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
-
- // Replace wildcards
- const pattern = escaped
- .replace(/\\\*\\\*/g, '.*') // ** matches anything
- .replace(/\\\*/g, '[^.]+'); // * matches one segment
-
- return new RegExp(`^${pattern}$`);
- }
-
- /**
- * Get subscription key for efficient storage
- * Groups similar patterns together
- */
- private getSubscriptionKey(topic: string): string {
- // Use the first non-wildcard segment as key
- const parts = topic.split('.');
- const firstPart = parts[0];
- return firstPart === '*' ? '__wildcard__' : firstPart;
- }
-
- /**
- * Generate unique subscription ID
- */
- private generateSubscriptionId(): string {
- return `sub_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
- }
-
- /**
- * Add event to message history
- */
- private addToHistory(event: EventBusEvent): void {
- this.messageHistory.push(event);
-
- // Trim history if it exceeds max size
- if (this.messageHistory.length > this.maxHistorySize) {
- this.messageHistory = this.messageHistory.slice(-this.maxHistorySize);
- }
- }
-
- /**
- * Update performance metrics
- */
- private updateMetrics(): void {
- this.messageCount++;
- const now = Date.now();
-
- if (this.lastMessageTime > 0) {
- const timeDiff = (now - this.lastMessageTime) / 1000; // seconds
- this.messageRate = 1 / timeDiff;
- }
-
- this.lastMessageTime = now;
- }
-
- /**
- * Get message history
- */
- getHistory(limit?: number): EventBusEvent[] {
- if (!this.enableHistory) {
- websocketLogger.warn('History is disabled');
- return [];
- }
-
- if (limit) {
- return this.messageHistory.slice(-limit);
- }
-
- return [...this.messageHistory];
- }
-
- /**
- * Get history for a specific topic
- */
- getHistoryForTopic(topic: string, limit?: number): EventBusEvent[] {
- const pattern = this.topicToRegex(topic);
- const matching = this.messageHistory.filter(event => pattern.test(event.topic));
-
- if (limit) {
- return matching.slice(-limit);
- }
-
- return matching;
- }
-
- /**
- * Clear message history
- */
- clearHistory(): void {
- this.messageHistory = [];
- if (this.enableLogging) {
- websocketLogger.info('History cleared');
- }
- }
-
- /**
- * Get current subscription count
- */
- getSubscriptionCount(): number {
- let count = 0;
- this.subscriptions.forEach(subs => {
- count += subs.length;
- });
- return count;
- }
-
- /**
- * Get all active subscriptions
- */
- getSubscriptions(): Map<string, TopicSubscription[]> {
- return new Map(this.subscriptions);
- }
-
- /**
- * Get metrics
- */
- getMetrics() {
- return {
- totalMessages: this.messageCount,
- messagesPerSecond: this.messageRate,
- subscriptions: this.getSubscriptionCount(),
- historySize: this.messageHistory.length,
- lastMessageAt: this.lastMessageTime
- };
- }
-
- /**
- * Clear all subscriptions (useful for cleanup)
- */
- clear(): void {
- this.subscriptions.clear();
- this.clearHistory();
- this.messageCount = 0;
- this.lastMessageTime = 0;
- this.messageRate = 0;
-
- if (this.enableLogging) {
- websocketLogger.info('All subscriptions cleared');
- }
- }
-
- /**
- * Enable/disable logging at runtime
- */
- setLogging(enabled: boolean): void {
- this.enableLogging = enabled;
- }
-
- /**
- * Enable/disable history at runtime
- */
- setHistory(enabled: boolean, maxSize?: number): void {
- this.enableHistory = enabled;
- if (maxSize !== undefined) {
- this.maxHistorySize = maxSize;
- }
- if (!enabled) {
- this.clearHistory();
- }
- }
-}
-
-// Singleton instance for global use
-export const globalEventBus = new EventBus({
- enableHistory: false,
- enableLogging: false
-});
diff --git a/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts b/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
deleted file mode 100644
index a12784d6a..000000000
--- a/fincept-terminal-desktop/src/services/websocket/WebSocketManager.ts
+++ /dev/null
@@ -1,509 +0,0 @@
-// File: src/services/websocket/WebSocketManager.ts
-// Central WebSocket manager - orchestrates all WebSocket connections
-
-import {
- IWebSocketAdapter,
- ConnectionStatus,
- ProviderConfig,
- Subscription,
- NormalizedMessage,
- MessageCallback,
- WebSocketManagerConfig,
- DEFAULT_MANAGER_CONFIG,
- parseTopic
-} from './types';
-import { EventBus, globalEventBus } from './EventBus';
-import { WebSocketRegistry } from './WebSocketRegistry';
-import { createAdapter, isProviderAvailable } from './adapters';
-import { generateId } from './utils';
-
-/**
- * WebSocketManager - Central orchestrator for all WebSocket connections
- *
- * Features:
- * - Automatic connection management
- * - Connection pooling (single connection per provider)
- * - Topic-based subscriptions with pub/sub
- * - Metrics and health monitoring
- * - Configuration management
- *
- * Usage:
- * ```typescript
- * const manager = new WebSocketManager();
- *
- * // Subscribe to a topic
- * const subscription = await manager.subscribe('kraken.ticker.BTC/USD', (message) => {
- * console.log('Price update:', message.data);
- * });
- *
- * // Unsubscribe
- * subscription.unsubscribe();
- * ```
- */
-export class WebSocketManager {
- private eventBus: EventBus;
- private registry: WebSocketRegistry;
- private config: WebSocketManagerConfig;
- private providerConfigs: Map<string, ProviderConfig> = new Map();
-
- // Track subscriptions for cleanup
- private activeSubscriptions: Map<string, Subscription> = new Map();
-
- // Track ongoing connections to prevent duplicates
- private connectingProviders: Set<string> = new Set();
-
- constructor(config?: Partial<WebSocketManagerConfig>) {
- this.config = { ...DEFAULT_MANAGER_CONFIG, ...config };
- this.eventBus = globalEventBus;
- this.registry = new WebSocketRegistry(this.eventBus, {
- enableLogging: this.config.enableLogging
- });
-
- // Configure event bus
- this.eventBus.setLogging(this.config.enableLogging);
- this.eventBus.setHistory(this.config.enableMetrics, 100);
-
- this.log('WebSocketManager initialized');
- }
-
- /**
- * Subscribe to a topic
- * @param topic - Format: "provider.channel.symbol" e.g., "kraken.ticker.BTC/USD"
- * @param callback - Message handler callback
- * @param params - Optional subscription parameters
- */
- async subscribe(
- topic: string,
- callback: MessageCallback,
- params?: Record<string, any>
- ): Promise<Subscription> {
- try {
- const parsed = parseTopic(topic);
- const { provider, channel, symbol } = parsed;
-
- // Ensure adapter exists and is connected
- await this.ensureConnection(provider);
-
- // Get adapter
- const adapter = this.registry.get(provider);
- if (!adapter) {
- throw new Error(`Adapter not found for provider: ${provider}`);
- }
-
- // Subscribe via adapter (only if not already subscribed)
- const adapterTopic = symbol ? `${channel}.${symbol}` : channel;
- const existingSubscriptions = adapter.getSubscriptions();
-
- if (!existingSubscriptions.includes(adapterTopic)) {
- await adapter.subscribe(adapterTopic, params);
- }
-
- // Create event bus subscription
- const eventBusUnsubscribe = this.eventBus.subscribe(topic, callback);
-
- // Track reference
- this.registry.addRef(provider);
-
- // Create subscription object
- const subscriptionId = generateId('sub');
- const subscription: Subscription = {
- id: subscriptionId,
- topic,
- callback,
- unsubscribe: () => this.unsubscribe(subscriptionId, topic, provider, adapterTopic, eventBusUnsubscribe),
- params
- };
-
- this.activeSubscriptions.set(subscriptionId, subscription);
-
- this.log(`Subscribed to: ${topic} (ID: ${subscriptionId})`);
-
- return subscription;
- } catch (error) {
- // Only log non-connection errors (connection errors are expected during reconnects)
- const errorMsg = error instanceof Error ? error.message : String(error);
- if (!errorMsg.includes('not connected') && !errorMsg.includes('not open')) {
- console.error(`[WebSocketManager] Subscribe failed for ${topic}:`, error);
- } else {
- console.debug(`[WebSocketManager] Subscribe pending connection for ${topic}`);
- }
- throw error;
- }
- }
-
- /**
- * Unsubscribe from a topic
- */
- private async unsubscribe(
- subscriptionId: string,
- topic: string,
- provider: string,
- adapterTopic: string,
- eventBusUnsubscribe: () => void
- ): Promise<void> {
- try {
- // Remove from active subscriptions first to avoid recursion
- const subscription = this.activeSubscriptions.get(subscriptionId);
- if (!subscription) {
- return; // Already unsubscribed
- }
-
- this.activeSubscriptions.delete(subscriptionId);
-
- // Unsubscribe from event bus
- eventBusUnsubscribe();
-
- // Release reference
- this.registry.release(provider);
-
- // Check if topic has other subscribers
- const hasOtherSubscribers = Array.from(this.activeSubscriptions.values())
- .some(sub => sub.topic === topic);
-
- // Unsubscribe from adapter if no other subscribers
- if (!hasOtherSubscribers) {
- const adapter = this.registry.get(provider);
- if (adapter) {
- await adapter.unsubscribe(adapterTopic);
- }
- }
-
- this.log(`Unsubscribed from: ${topic} (ID: ${subscriptionId})`);
- } catch (error) {
- console.error(`[WebSocketManager] Unsubscribe failed:`, error);
- }
- }
-
- /**
- * Ensure connection to provider exists and is healthy
- */
- private async ensureConnection(provider: string): Promise<void> {
- // Check if adapter exists
- if (!isProviderAvailable(provider)) {
- throw new Error(`Provider not supported: ${provider}`);
- }
-
- // Check if already connected
- if (this.registry.has(provider) && this.registry.isConnected(provider)) {
- return;
- }
-
- // Check if already connecting - PREVENT DUPLICATE CONNECTIONS
- if (this.connectingProviders.has(provider)) {
- this.log(`Already connecting to ${provider}, waiting...`);
- // Wait for existing connection to complete
- while (this.connectingProviders.has(provider)) {
- await new Promise(resolve => setTimeout(resolve, 100));
- }
- return;
- }
-
- // Mark as connecting
- this.connectingProviders.add(provider);
-
- try {
- // Get provider config
- const config = this.providerConfigs.get(provider);
- if (!config) {
- throw new Error(`No configuration found for provider: ${provider}. Use setProviderConfig() first.`);
- }
-
- // Create adapter if doesn't exist
- if (!this.registry.has(provider)) {
- const adapter = createAdapter(provider);
-
- // Setup message handler
- adapter.onMessage((message: NormalizedMessage) => {
- // Publish to event bus with full topic path
- const fullTopic = this.buildFullTopic(message);
- this.eventBus.publish(fullTopic, message);
- });
-
- // Setup error handler
- adapter.onError((error) => {
- this.log(`Error from ${provider}:`, error);
- });
-
- // Setup status change handler
- adapter.onStatusChange((status) => {
- this.log(`${provider} status changed to: ${status}`);
- });
-
- // Register adapter
- this.registry.register(provider, adapter, config);
- }
-
- // Connect
- const adapter = this.registry.get(provider);
- if (adapter && adapter.status !== ConnectionStatus.CONNECTED) {
- await adapter.connect(config);
- }
- } finally {
- // Always remove from connecting set
- this.connectingProviders.delete(provider);
- }
- }
-
- /**
- * Build full topic path from message
- */
- private buildFullTopic(message: NormalizedMessage): string {
- const parts = [message.provider, message.channel];
-
- if (message.symbol) {
- parts.push(message.symbol);
- }
-
- return parts.join('.');
- }
-
- /**
- * Set provider configuration
- */
- setProviderConfig(provider: string, config: ProviderConfig): void {
- this.providerConfigs.set(provider, config);
- this.log(`Configuration set for provider: ${provider}`);
- }
-
- /**
- * Get provider configuration
- */
- getProviderConfig(provider: string): ProviderConfig | undefined {
- return this.providerConfigs.get(provider);
- }
-
- /**
- * Connect to a provider manually
- */
- async connect(provider: string): Promise<void> {
- await this.ensureConnection(provider);
- }
-
- /**
- * Disconnect from a provider
- */
- async disconnect(provider: string): Promise<void> {
- if (this.registry.has(provider)) {
- await this.registry.unregister(provider);
- this.log(`Disconnected from provider: ${provider}`);
- }
- }
-
- /**
- * Get connection status for a provider
- */
- getStatus(provider: string): ConnectionStatus | null {
- return this.registry.getStatus(provider);
- }
-
- /**
- * Get all connection statuses
- */
- getAllStatuses(): Map<string, ConnectionStatus> {
- return this.registry.getAllStatuses();
- }
-
- /**
- * Get metrics for a provider
- */
- getMetrics(provider: string) {
- return this.registry.getMetrics(provider);
- }
-
- /**
- * Get all metrics
- */
- getAllMetrics() {
- return this.registry.getAllMetrics();
- }
-
- /**
- * Get registry statistics
- */
- getStats() {
- return {
- registry: this.registry.getStats(),
- eventBus: this.eventBus.getMetrics(),
- activeSubscriptions: this.activeSubscriptions.size,
- configuredProviders: this.providerConfigs.size
- };
- }
-
- /**
- * Ping a provider
- */
- async ping(provider: string): Promise<number> {
- const adapter = this.registry.get(provider);
-
- if (!adapter) {
- throw new Error(`Provider not connected: ${provider}`);
- }
-
- return adapter.ping();
- }
-
- /**
- * Ping all connected providers
- */
- async pingAll(): Promise<Map<string, number>> {
- return this.registry.pingAll();
- }
-
- /**
- * Reconnect a provider and restore subscriptions
- */
- async reconnect(provider: string): Promise<void> {
- // Get active subscriptions for this provider before reconnection
- const providerSubs = this.getProviderSubscriptions(provider);
-
- // Store subscription details
- const subsToRestore = providerSubs.map(sub => ({
- topic: sub.topic,
- callback: sub.callback,
- // Use stored params from subscription
- params: sub.params
- }));
-
- // Reconnect the adapter
- await this.registry.reconnect(provider);
-
- // Resubscribe to all topics
- const adapter = this.registry.get(provider);
- if (adapter && subsToRestore.length > 0) {
- this.log(`Resubscribing to ${subsToRestore.length} topics for ${provider}`);
-
- for (const subInfo of subsToRestore) {
- try {
- const parsed = parseTopic(subInfo.topic);
- const adapterTopic = parsed.symbol ? `${parsed.channel}.${parsed.symbol}` : parsed.channel;
- await adapter.subscribe(adapterTopic, subInfo.params);
- this.log(`Resubscribed to: ${subInfo.topic}`);
- } catch (error) {
- console.error(`[WebSocketManager] Failed to resubscribe to ${subInfo.topic}:`, error);
- }
- }
- }
- }
-
- /**
- * Reconnect all providers and restore subscriptions
- */
- async reconnectAll(): Promise<void> {
- const providers = this.registry.getProviders();
-
- for (const provider of providers) {
- try {
- await this.reconnect(provider);
- } catch (error) {
- console.error(`[WebSocketManager] Failed to reconnect ${provider}:`, error);
- }
- }
- }
-
- /**
- * Get message history from event bus
- */
- getMessageHistory(topic?: string, limit?: number) {
- if (topic) {
- return this.eventBus.getHistoryForTopic(topic, limit);
- }
- return this.eventBus.getHistory(limit);
- }
-
- /**
- * Clear message history
- */
- clearHistory(): void {
- this.eventBus.clearHistory();
- }
-
- /**
- * Get active subscriptions
- */
- getSubscriptions(): Subscription[] {
- return Array.from(this.activeSubscriptions.values());
- }
-
- /**
- * Get subscriptions for a specific provider
- */
- getProviderSubscriptions(provider: string): Subscription[] {
- return Array.from(this.activeSubscriptions.values())
- .filter(sub => sub.topic.startsWith(`${provider}.`));
- }
-
- /**
- * Enable/disable logging
- */
- setLogging(enabled: boolean): void {
- this.config.enableLogging = enabled;
- this.eventBus.setLogging(enabled);
- this.registry.setLogging(enabled);
- }
-
- /**
- * Update configuration
- */
- updateConfig(config: Partial<WebSocketManagerConfig>): void {
- this.config = { ...this.config, ...config };
- }
-
- /**
- * Cleanup all resources
- */
- async destroy(): Promise<void> {
- this.log('Destroying WebSocketManager...');
-
- // Unsubscribe all
- const subscriptionIds = Array.from(this.activeSubscriptions.keys());
- for (const id of subscriptionIds) {
- const sub = this.activeSubscriptions.get(id);
- if (sub) {
- sub.unsubscribe();
- }
- }
-
- // Cleanup registry
- await this.registry.destroy();
-
- // Clear event bus
- this.eventBus.clear();
-
- this.log('WebSocketManager destroyed');
- }
-
- /**
- * Log helper
- */
- private log(...args: any[]): void {
- if (this.config.enableLogging) {
- console.log('[WebSocketManager]', ...args);
- }
- }
-}
-
-// Global singleton instance
-let globalManagerInstance: WebSocketManager | null = null;
-
-/**
- * Get global WebSocketManager instance (singleton)
- */
-export function getWebSocketManager(): WebSocketManager {
- if (!globalManagerInstance) {
- globalManagerInstance = new WebSocketManager({
- enableLogging: true, // ENABLED FOR DEBUGGING
- enableMetrics: true
- });
- }
- return globalManagerInstance;
-}
-
-/**
- * Reset global instance (useful for testing)
- */
-export function resetWebSocketManager(): void {
- if (globalManagerInstance) {
- globalManagerInstance.destroy();
- globalManagerInstance = null;
- }
-}
diff --git a/fincept-terminal-desktop/src/services/websocket/WebSocketRegistry.ts b/fincept-terminal-desktop/src/services/websocket/WebSocketRegistry.ts
deleted file mode 100644
index df7acfbbf..000000000
--- a/fincept-terminal-desktop/src/services/websocket/WebSocketRegistry.ts
+++ /dev/null
@@ -1,409 +0,0 @@
-// File: src/services/websocket/WebSocketRegistry.ts
-// Connection registry for managing WebSocket adapter instances and lifecycle
-
-import {
- IWebSocketAdapter,
- ConnectionStatus,
- ConnectionMetrics,
- ProviderConfig
-} from './types';
-import { EventBus } from './EventBus';
-import { websocketLogger } from '../loggerService';
-
-/**
- * Registry entry for a WebSocket adapter
- */
-interface RegistryEntry {
- adapter: IWebSocketAdapter;
- config: ProviderConfig;
- createdAt: number;
- refCount: number; // Track number of active subscribers
-}
-
-/**
- * WebSocketRegistry - Manages lifecycle and pooling of WebSocket adapters
- *
- * Features:
- * - Single instance per provider (connection pooling)
- * - Reference counting for automatic cleanup
- * - Health monitoring
- * - Automatic reconnection
- * - Connection metrics tracking
- */
-export class WebSocketRegistry {
- private registry: Map<string, RegistryEntry> = new Map();
- private eventBus: EventBus;
- private enableLogging: boolean = false;
-
- // Cleanup settings
- private cleanupIntervalMs: number = 60000; // 1 minute
- private cleanupTimeoutMs: number = 300000; // 5 minutes of inactivity
- private cleanupTimer: NodeJS.Timeout | null = null;
-
- constructor(eventBus: EventBus, options?: {
- enableLogging?: boolean;
- cleanupIntervalMs?: number;
- cleanupTimeoutMs?: number;
- }) {
- this.eventBus = eventBus;
- this.enableLogging = options?.enableLogging ?? false;
- this.cleanupIntervalMs = options?.cleanupIntervalMs ?? 60000;
- this.cleanupTimeoutMs = options?.cleanupTimeoutMs ?? 300000;
-
- this.startCleanupTimer();
-
- if (this.enableLogging) {
- websocketLogger.info('Registry initialized');
- }
- }
-
- /**
- * Register a new adapter instance
- */
- register(provider: string, adapter: IWebSocketAdapter, config: ProviderConfig): void {
- if (this.registry.has(provider)) {
- throw new Error(`Provider ${provider} is already registered`);
- }
-
- const entry: RegistryEntry = {
- adapter,
- config,
- createdAt: Date.now(),
- refCount: 0
- };
-
- this.registry.set(provider, entry);
-
- if (this.enableLogging) {
- websocketLogger.info(`Registered provider: ${provider}`);
- }
- }
-
- /**
- * Unregister an adapter and cleanup
- */
- async unregister(provider: string): Promise<void> {
- const entry = this.registry.get(provider);
-
- if (!entry) {
- websocketLogger.warn(`Provider not found: ${provider}`);
- return;
- }
-
- // Disconnect and cleanup
- try {
- await entry.adapter.disconnect();
- entry.adapter.destroy();
- } catch (error) {
- websocketLogger.error(`Error cleaning up ${provider}:`, error);
- }
-
- this.registry.delete(provider);
-
- if (this.enableLogging) {
- websocketLogger.info(`Unregistered provider: ${provider}`);
- }
- }
-
- /**
- * Get adapter instance (creates if doesn't exist)
- */
- get(provider: string): IWebSocketAdapter | null {
- const entry = this.registry.get(provider);
- return entry ? entry.adapter : null;
- }
-
- /**
- * Check if provider is registered
- */
- has(provider: string): boolean {
- return this.registry.has(provider);
- }
-
- /**
- * Get all registered providers
- */
- getProviders(): string[] {
- return Array.from(this.registry.keys());
- }
-
- /**
- * Increment reference count (track active subscribers)
- */
- addRef(provider: string): void {
- const entry = this.registry.get(provider);
- if (entry) {
- entry.refCount++;
-
- if (this.enableLogging) {
- websocketLogger.debug(`${provider} refCount: ${entry.refCount}`);
- }
- }
- }
-
- /**
- * Decrement reference count
- */
- release(provider: string): void {
- const entry = this.registry.get(provider);
- if (entry) {
- entry.refCount = Math.max(0, entry.refCount - 1);
-
- if (this.enableLogging) {
- websocketLogger.debug(`${provider} refCount: ${entry.refCount}`);
- }
-
- // Schedule cleanup if no active references
- if (entry.refCount === 0) {
- this.scheduleCleanup(provider);
- }
- }
- }
-
- /**
- * Get reference count for provider
- */
- getRefCount(provider: string): number {
- const entry = this.registry.get(provider);
- return entry ? entry.refCount : 0;
- }
-
- /**
- * Get metrics for a provider
- */
- getMetrics(provider: string): ConnectionMetrics | null {
- const entry = this.registry.get(provider);
- return entry ? entry.adapter.metrics : null;
- }
-
- /**
- * Get metrics for all providers
- */
- getAllMetrics(): Map<string, ConnectionMetrics> {
- const metrics = new Map<string, ConnectionMetrics>();
-
- this.registry.forEach((entry, provider) => {
- metrics.set(provider, entry.adapter.metrics);
- });
-
- return metrics;
- }
-
- /**
- * Get connection status for a provider
- */
- getStatus(provider: string): ConnectionStatus | null {
- const entry = this.registry.get(provider);
- return entry ? entry.adapter.status : null;
- }
-
- /**
- * Check if provider is connected
- */
- isConnected(provider: string): boolean {
- const status = this.getStatus(provider);
- return status === ConnectionStatus.CONNECTED;
- }
-
- /**
- * Get all connection statuses
- */
- getAllStatuses(): Map<string, ConnectionStatus> {
- const statuses = new Map<string, ConnectionStatus>();
-
- this.registry.forEach((entry, provider) => {
- statuses.set(provider, entry.adapter.status);
- });
-
- return statuses;
- }
-
- /**
- * Schedule cleanup for idle connections
- */
- private scheduleCleanup(provider: string): void {
- // Don't cleanup if there are active references
- const entry = this.registry.get(provider);
- if (!entry || entry.refCount > 0) {
- return;
- }
-
- // Cleanup will happen in the cleanup timer if still idle
- }
-
- /**
- * Start periodic cleanup timer
- */
- private startCleanupTimer(): void {
- this.cleanupTimer = setInterval(() => {
- this.performCleanup();
- }, this.cleanupIntervalMs);
- }
-
- /**
- * Perform cleanup of idle connections
- */
- private async performCleanup(): Promise<void> {
- const now = Date.now();
- const toCleanup: string[] = [];
-
- this.registry.forEach((entry, provider) => {
- // Skip if has active references
- if (entry.refCount > 0) {
- return;
- }
-
- // Check if connection has been idle too long
- const metrics = entry.adapter.metrics;
- const lastActivity = metrics.lastMessageAt || entry.createdAt;
- const idleTime = now - lastActivity;
-
- if (idleTime > this.cleanupTimeoutMs) {
- toCleanup.push(provider);
- }
- });
-
- // Cleanup idle connections
- for (const provider of toCleanup) {
- if (this.enableLogging) {
- websocketLogger.info(`Cleaning up idle connection: ${provider}`);
- }
- await this.unregister(provider);
- }
- }
-
- /**
- * Force cleanup of all connections
- */
- async cleanup(): Promise<void> {
- const providers = this.getProviders();
-
- for (const provider of providers) {
- await this.unregister(provider);
- }
-
- if (this.cleanupTimer) {
- clearInterval(this.cleanupTimer);
- this.cleanupTimer = null;
- }
-
- if (this.enableLogging) {
- websocketLogger.info('All connections cleaned up');
- }
- }
-
- /**
- * Get registry statistics
- */
- getStats() {
- const stats = {
- totalProviders: this.registry.size,
- connectedProviders: 0,
- totalSubscriptions: 0,
- totalMessages: 0,
- providers: new Map<string, {
- status: ConnectionStatus;
- refCount: number;
- uptime: number;
- subscriptions: number;
- }>()
- };
-
- this.registry.forEach((entry, provider) => {
- const metrics = entry.adapter.metrics;
-
- if (entry.adapter.status === ConnectionStatus.CONNECTED) {
- stats.connectedProviders++;
- }
-
- stats.totalSubscriptions += metrics.subscriptions;
- stats.totalMessages += metrics.messagesReceived;
-
- stats.providers.set(provider, {
- status: entry.adapter.status,
- refCount: entry.refCount,
- uptime: metrics.uptime || 0,
- subscriptions: metrics.subscriptions
- });
- });
-
- return stats;
- }
-
- /**
- * Reconnect a provider
- */
- async reconnect(provider: string): Promise<void> {
- const entry = this.registry.get(provider);
-
- if (!entry) {
- throw new Error(`Provider not found: ${provider}`);
- }
-
- if (this.enableLogging) {
- websocketLogger.info(`Reconnecting provider: ${provider}`);
- }
-
- try {
- await entry.adapter.disconnect();
- await entry.adapter.connect(entry.config);
- } catch (error) {
- websocketLogger.error(`Failed to reconnect ${provider}:`, error);
- throw error;
- }
- }
-
- /**
- * Reconnect all providers
- */
- async reconnectAll(): Promise<void> {
- const providers = this.getProviders();
-
- for (const provider of providers) {
- try {
- await this.reconnect(provider);
- } catch (error) {
- websocketLogger.error(`Failed to reconnect ${provider}:`, error);
- }
- }
- }
-
- /**
- * Ping all connected providers
- */
- async pingAll(): Promise<Map<string, number>> {
- const results = new Map<string, number>();
-
- for (const [provider, entry] of this.registry.entries()) {
- if (entry.adapter.status === ConnectionStatus.CONNECTED) {
- try {
- const latency = await entry.adapter.ping();
- results.set(provider, latency);
- } catch (error) {
- websocketLogger.error(`Ping failed for ${provider}:`, error);
- results.set(provider, -1);
- }
- }
- }
-
- return results;
- }
-
- /**
- * Enable/disable logging
- */
- setLogging(enabled: boolean): void {
- this.enableLogging = enabled;
- }
-
- /**
- * Destroy registry and cleanup all resources
- */
- async destroy(): Promise<void> {
- await this.cleanup();
-
- if (this.enableLogging) {
- websocketLogger.info('Registry destroyed');
- }
- }
-}
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts b/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts
deleted file mode 100644
index 9773514dc..000000000
--- a/fincept-terminal-desktop/src/services/websocket/adapters/BaseAdapter.ts
+++ /dev/null
@@ -1,574 +0,0 @@
-// File: src/services/websocket/adapters/BaseAdapter.ts
-// Abstract base class for WebSocket adapters - provides common functionality
-
-import {
- IWebSocketAdapter,
- ConnectionStatus,
- ConnectionMetrics,
- ConnectionError,
- ProviderConfig,
- NormalizedMessage,
- DEFAULT_RECONNECTION_POLICY,
- DEFAULT_RATE_LIMIT
-} from '../types';
-import {
- ReconnectionManager,
- RateLimiter,
- CircuitBreaker,
- HeartbeatMonitor,
- PerformanceMetrics,
- generateId
-} from '../utils';
-import { websocketLogger } from '../../loggerService';
-
-/**
- * Base WebSocket Adapter
- * Provides common functionality for all provider adapters:
- * - Connection management
- * - Automatic reconnection
- * - Rate limiting
- * - Health monitoring
- * - Error handling
- * - Metrics collection
- */
-export abstract class BaseAdapter implements IWebSocketAdapter {
- abstract readonly provider: string;
-
- protected ws: WebSocket | null = null;
- protected _status: ConnectionStatus = ConnectionStatus.DISCONNECTED;
- protected config: ProviderConfig | null = null;
-
- // Utilities
- protected reconnectionManager: ReconnectionManager;
- protected rateLimiter: RateLimiter;
- protected circuitBreaker: CircuitBreaker;
- protected heartbeatMonitor: HeartbeatMonitor;
- protected performanceMetrics: PerformanceMetrics;
-
- // Callbacks
- private messageCallbacks: Array<(message: NormalizedMessage) => void> = [];
- private errorCallbacks: Array<(error: ConnectionError) => void> = [];
- private statusCallbacks: Array<(status: ConnectionStatus) => void> = [];
-
- // Subscriptions tracking
- protected subscriptions: Set<string> = new Set();
-
- // Metrics
- protected _metrics: ConnectionMetrics;
-
- // Logging
- protected enableLogging: boolean = false;
-
- constructor() {
- // Initialize metrics with empty provider (will be set by getter)
- this._metrics = {
- provider: '',
- status: ConnectionStatus.DISCONNECTED,
- messagesReceived: 0,
- messagesPerSecond: 0,
- reconnectionAttempts: 0,
- errors: [],
- subscriptions: 0
- };
-
- this.reconnectionManager = new ReconnectionManager(DEFAULT_RECONNECTION_POLICY);
- this.rateLimiter = new RateLimiter(DEFAULT_RATE_LIMIT);
- this.circuitBreaker = new CircuitBreaker(5, 60000, 2);
- this.heartbeatMonitor = new HeartbeatMonitor(30000, 60000);
- this.performanceMetrics = new PerformanceMetrics();
- }
-
- /**
- * Getter for current status
- */
- get status(): ConnectionStatus {
- return this._status;
- }
-
- /**
- * Getter for metrics
- */
- get metrics(): ConnectionMetrics {
- const perfMetrics = this.performanceMetrics.getMetrics();
-
- return {
- ...this._metrics,
- provider: this.provider,
- status: this._status,
- messagesReceived: perfMetrics.messageCount,
- messagesPerSecond: perfMetrics.messagesPerSecond,
- reconnectionAttempts: this.reconnectionManager.getAttempts(),
- subscriptions: this.subscriptions.size
- };
- }
-
- /**
- * Connect to WebSocket
- */
- async connect(config: ProviderConfig): Promise<void> {
- websocketLogger.info(`[${this.provider}] Connecting to WebSocket...`);
-
- if (!this.circuitBreaker.isAllowed()) {
- throw new Error(`Circuit breaker is open for ${this.provider}`);
- }
-
- this.config = config;
- this.setStatus(ConnectionStatus.CONNECTING);
-
- try {
- const url = this.getWebSocketUrl(config);
- websocketLogger.debug(`[${this.provider}] WebSocket URL: ${url}`);
-
- this.ws = new WebSocket(url);
- websocketLogger.debug(`[${this.provider}] WebSocket object created, readyState: ${this.ws.readyState}`);
-
- this.setupWebSocketHandlers();
-
- // Wait for connection
- websocketLogger.debug(`[${this.provider}] Waiting for WebSocket to open...`);
- await this.waitForConnection();
- websocketLogger.debug(`[${this.provider}] WebSocket opened! readyState: ${this.ws?.readyState}`);
-
- this.reconnectionManager.recordSuccess();
- this.circuitBreaker.recordSuccess();
- this.setStatus(ConnectionStatus.CONNECTED);
- this._metrics.connectedAt = Date.now();
-
- // Start heartbeat monitoring
- this.heartbeatMonitor.start(() => this.handleStaleConnection());
- websocketLogger.debug(`[${this.provider}] Heartbeat monitoring started`);
-
- // Perform provider-specific initialization
- await this.onConnected();
-
- websocketLogger.info(`[${this.provider}] Connection complete!`);
- this.log('Connected successfully');
- } catch (error) {
- websocketLogger.error(`[${this.provider}] Connection failed:`, error);
-
- this.circuitBreaker.recordFailure();
- this.reconnectionManager.recordAttempt();
-
- const errorObj: ConnectionError = {
- timestamp: Date.now(),
- error: error instanceof Error ? error.message : String(error)
- };
- this.addError(errorObj);
- this.notifyError(errorObj);
-
- this.setStatus(ConnectionStatus.ERROR);
-
- // Attempt reconnection if policy allows
- if (this.reconnectionManager.shouldAttempt()) {
- websocketLogger.info(`[${this.provider}] Will retry connection...`);
- await this.scheduleReconnection();
- } else {
- throw error;
- }
- }
- }
-
- /**
- * Disconnect from WebSocket
- */
- async disconnect(): Promise<void> {
- this.log('Disconnecting...');
-
- this.heartbeatMonitor.stop();
-
- if (this.ws) {
- // Remove event listeners to prevent reconnection
- this.ws.onclose = null;
- this.ws.onerror = null;
-
- if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
- this.ws.close();
- }
-
- this.ws = null;
- }
-
- this.setStatus(ConnectionStatus.DISCONNECTED);
- this.subscriptions.clear();
-
- await this.onDisconnected();
- }
-
- /**
- * Subscribe to a topic
- */
- async subscribe(topic: string, params?: Record<string, any>): Promise<void> {
- websocketLogger.debug(`[${this.provider}] Subscribe requested: ${topic}`);
- websocketLogger.debug(`[${this.provider}] - WebSocket exists: ${!!this.ws}`);
- websocketLogger.debug(`[${this.provider}] - readyState: ${this.ws?.readyState} (OPEN=${WebSocket.OPEN})`);
- websocketLogger.debug(`[${this.provider}] - Status: ${this._status}`);
-
- // Check WebSocket is actually open FIRST (most accurate check)
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
- throw new Error(`Cannot subscribe: WebSocket is not open (readyState: ${this.ws?.readyState || 'null'})`);
- }
-
- // Then check connection status
- if (this._status !== ConnectionStatus.CONNECTED) {
- throw new Error(`Cannot subscribe: connection status is ${this._status}`);
- }
-
- // Check rate limit
- if (!this.rateLimiter.tryConsume()) {
- const waitTime = this.rateLimiter.getWaitTime();
- this.log(`Rate limited, waiting ${waitTime}ms before subscribing to ${topic}`);
- await new Promise(resolve => setTimeout(resolve, waitTime));
- }
-
- await this.performSubscribe(topic, params);
- this.subscriptions.add(topic);
-
- this.log(`Subscribed to: ${topic}`);
- }
-
- /**
- * Unsubscribe from a topic
- */
- async unsubscribe(topic: string): Promise<void> {
- if (this._status !== ConnectionStatus.CONNECTED) {
- this.log(`Cannot unsubscribe: connection status is ${this._status}`);
- return;
- }
-
- await this.performUnsubscribe(topic);
- this.subscriptions.delete(topic);
-
- this.log(`Unsubscribed from: ${topic}`);
- }
-
- /**
- * Send raw message
- */
- async send(message: any): Promise<void> {
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
- throw new Error('WebSocket is not connected');
- }
-
- const data = typeof message === 'string' ? message : JSON.stringify(message);
- this.ws.send(data);
- }
-
- /**
- * Ping/health check
- */
- async ping(): Promise<number> {
- const start = Date.now();
- await this.performPing();
- const latency = Date.now() - start;
-
- this._metrics.latency = latency;
- this.performanceMetrics.recordLatency(latency);
-
- return latency;
- }
-
- /**
- * Get current subscriptions
- */
- getSubscriptions(): string[] {
- return Array.from(this.subscriptions);
- }
-
- /**
- * Register message callback
- */
- onMessage(callback: (message: NormalizedMessage) => void): void {
- this.messageCallbacks.push(callback);
- }
-
- /**
- * Register error callback
- */
- onError(callback: (error: ConnectionError) => void): void {
- this.errorCallbacks.push(callback);
- }
-
- /**
- * Register status change callback
- */
- onStatusChange(callback: (status: ConnectionStatus) => void): void {
- this.statusCallbacks.push(callback);
- }
-
- /**
- * Cleanup resources
- */
- destroy(): void {
- this.heartbeatMonitor.stop();
- this.messageCallbacks = [];
- this.errorCallbacks = [];
- this.statusCallbacks = [];
- this.subscriptions.clear();
- this.ws = null;
- }
-
- // ==================== Abstract Methods (Provider-Specific) ====================
-
- /**
- * Get WebSocket URL for provider
- */
- protected abstract getWebSocketUrl(config: ProviderConfig): string;
-
- /**
- * Handle incoming message (parse and normalize)
- */
- protected abstract handleMessage(event: MessageEvent): void;
-
- /**
- * Perform subscription (provider-specific)
- */
- protected abstract performSubscribe(topic: string, params?: Record<string, any>): Promise<void>;
-
- /**
- * Perform unsubscription (provider-specific)
- */
- protected abstract performUnsubscribe(topic: string): Promise<void>;
-
- /**
- * Perform ping (provider-specific)
- */
- protected abstract performPing(): Promise<void>;
-
- /**
- * Called after successful connection (optional hook)
- */
- protected async onConnected(): Promise<void> {
- // Override in subclass if needed
- }
-
- /**
- * Called after disconnection (optional hook)
- */
- protected async onDisconnected(): Promise<void> {
- // Override in subclass if needed
- }
-
- // ==================== Protected Helper Methods ====================
-
- /**
- * Setup WebSocket event handlers
- */
- protected setupWebSocketHandlers(): void {
- if (!this.ws) return;
-
- this.ws.onopen = () => {
- this.log('WebSocket connection opened');
- };
-
- this.ws.onmessage = (event: MessageEvent) => {
- this.heartbeatMonitor.beat();
- this._metrics.lastMessageAt = Date.now();
- this.performanceMetrics.recordMessage(event.data?.length);
-
- try {
- this.handleMessage(event);
- } catch (error) {
- websocketLogger.error(`[${this.provider}] Error handling message:`, error);
- this.addError({
- timestamp: Date.now(),
- error: `Message handling error: ${error}`
- });
- }
- };
-
- this.ws.onerror = (event: Event) => {
- this.log('WebSocket error', event);
- this.addError({
- timestamp: Date.now(),
- error: 'WebSocket error occurred'
- });
- this.setStatus(ConnectionStatus.ERROR);
- };
-
- this.ws.onclose = (event: CloseEvent) => {
- this.log(`WebSocket closed: ${event.code} - ${event.reason}`);
-
- if (this._status !== ConnectionStatus.DISCONNECTED) {
- // Unexpected close, attempt reconnection
- this.handleUnexpectedClose(event);
- }
- };
- }
-
- /**
- * Wait for WebSocket connection to open
- */
- protected waitForConnection(timeout: number = 10000): Promise<void> {
- return new Promise((resolve, reject) => {
- if (!this.ws) {
- reject(new Error('WebSocket is null'));
- return;
- }
-
- const timer = setTimeout(() => {
- reject(new Error('Connection timeout'));
- }, timeout);
-
- this.ws.addEventListener('open', () => {
- clearTimeout(timer);
- resolve();
- }, { once: true });
-
- this.ws.addEventListener('error', (error) => {
- clearTimeout(timer);
- reject(error);
- }, { once: true });
- });
- }
-
- /**
- * Handle unexpected connection close
- */
- protected async handleUnexpectedClose(event: CloseEvent): Promise<void> {
- this.log(`Unexpected close: ${event.code} - ${event.reason}`);
-
- if (this.reconnectionManager.shouldAttempt()) {
- await this.scheduleReconnection();
- } else {
- this.setStatus(ConnectionStatus.ERROR);
- this.addError({
- timestamp: Date.now(),
- error: 'Max reconnection attempts reached',
- code: event.code
- });
- }
- }
-
- /**
- * Schedule reconnection attempt
- */
- protected async scheduleReconnection(): Promise<void> {
- const delay = this.reconnectionManager.getNextDelay();
- this.setStatus(ConnectionStatus.RECONNECTING);
-
- this.log(`Scheduling reconnection in ${delay}ms (attempt ${this.reconnectionManager.getAttempts() + 1})`);
-
- await new Promise(resolve => setTimeout(resolve, delay));
-
- if (this.config) {
- try {
- await this.connect(this.config);
-
- // Resubscribe to previous topics
- await this.resubscribe();
- } catch (error) {
- websocketLogger.error(`[${this.provider}] Reconnection failed:`, error);
- }
- }
- }
-
- /**
- * Resubscribe to all topics after reconnection
- */
- protected async resubscribe(): Promise<void> {
- const topics = Array.from(this.subscriptions);
- this.subscriptions.clear();
-
- for (const topic of topics) {
- try {
- await this.subscribe(topic);
- } catch (error) {
- websocketLogger.error(`[${this.provider}] Failed to resubscribe to ${topic}:`, error);
- }
- }
- }
-
- /**
- * Handle stale connection (heartbeat timeout)
- */
- protected async handleStaleConnection(): Promise<void> {
- // Prevent simultaneous reconnection attempts
- if (this._status === ConnectionStatus.RECONNECTING || this._status === ConnectionStatus.CONNECTING) {
- this.log('Already reconnecting, skipping stale connection handler');
- return;
- }
-
- this.log('Connection appears stale, forcing reconnect');
-
- await this.disconnect();
-
- if (this.config && this.reconnectionManager.shouldAttempt()) {
- await this.scheduleReconnection();
- }
- }
-
- /**
- * Notify message to all callbacks
- */
- protected notifyMessage(message: NormalizedMessage): void {
- this.messageCallbacks.forEach(callback => {
- try {
- callback(message);
- } catch (error) {
- websocketLogger.error(`[${this.provider}] Error in message callback:`, error);
- }
- });
- }
-
- /**
- * Notify error to all callbacks
- */
- protected notifyError(error: ConnectionError): void {
- this.errorCallbacks.forEach(callback => {
- try {
- callback(error);
- } catch (err) {
- websocketLogger.error(`[${this.provider}] Error in error callback:`, err);
- }
- });
- }
-
- /**
- * Set connection status and notify listeners
- */
- protected setStatus(status: ConnectionStatus): void {
- if (this._status !== status) {
- this._status = status;
- this._metrics.status = status;
-
- this.statusCallbacks.forEach(callback => {
- try {
- callback(status);
- } catch (error) {
- websocketLogger.error(`[${this.provider}] Error in status callback:`, error);
- }
- });
-
- this.log(`Status changed to: ${status}`);
- }
- }
-
- /**
- * Add error to metrics
- */
- protected addError(error: ConnectionError): void {
- this._metrics.errors.push(error);
- this.performanceMetrics.recordError();
-
- // Keep only last 50 errors
- if (this._metrics.errors.length > 50) {
- this._metrics.errors = this._metrics.errors.slice(-50);
- }
- }
-
- /**
- * Log message (if logging enabled)
- */
- protected log(...args: any[]): void {
- if (this.enableLogging) {
- websocketLogger.debug(`[${this.provider}]`, ...args);
- }
- }
-
- /**
- * Enable/disable logging
- */
- setLogging(enabled: boolean): void {
- this.enableLogging = enabled;
- }
-}
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.ts b/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.ts
deleted file mode 100644
index ef3953f47..000000000
--- a/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.ts
+++ /dev/null
@@ -1,381 +0,0 @@
-// File: src/services/websocket/adapters/HyperLiquidAdapter.ts
-// HyperLiquid WebSocket API adapter
-// Documentation: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket
-
-import { BaseAdapter } from './BaseAdapter';
-import { ProviderConfig, NormalizedMessage } from '../types';
-
-/**
- * HyperLiquid WebSocket message types
- */
-interface HyperLiquidMessage {
- channel?: string;
- data?: any;
-}
-
-interface HyperLiquidSubscription {
- method: 'subscribe' | 'unsubscribe';
- subscription: {
- type: string;
- coin?: string;
- user?: string;
- interval?: string;
- };
-}
-
-/**
- * HyperLiquidAdapter - WebSocket adapter for HyperLiquid DEX
- *
- * Supported channels:
- * - allMids: All mid prices for all coins
- * - l2Book: Level 2 order book for specific coin
- * - trades: Recent trades for specific coin
- * - candle: OHLC candlestick data (intervals: 1m, 5m, 15m, 1h, 4h, 1d)
- * - user: User-specific data (fills, orders - requires authentication)
- *
- * Topic format: "channel.symbol" e.g., "book.BTC", "trades.ETH"
- */
-export class HyperLiquidAdapter extends BaseAdapter {
- readonly provider = 'hyperliquid';
-
- private readonly WS_URL = 'wss://api.hyperliquid.xyz/ws';
-
- /**
- * Get WebSocket URL
- */
- protected getWebSocketUrl(config: ProviderConfig): string {
- return this.WS_URL;
- }
-
- /**
- * Handle incoming messages from HyperLiquid
- */
- protected handleMessage(event: MessageEvent): void {
- try {
- const message: HyperLiquidMessage = JSON.parse(event.data);
-
- this.log('Received message:', message);
-
- // Handle channel messages
- if (message.channel && message.data) {
- this.handleChannelMessage(message);
- }
- } catch (error) {
- console.error('[HyperLiquidAdapter] Failed to parse message:', error);
- }
- }
-
- /**
- * Subscribe to a channel
- * @param topic - Format: "channel.symbol" e.g., "book.BTC", "trades.ETH"
- * @param params - Optional parameters (interval for candles)
- */
- protected async performSubscribe(topic: string, params?: Record<string, any>): Promise<void> {
- const { channel, symbol } = this.parseTopic(topic);
-
- const subscribeMessage: HyperLiquidSubscription = {
- method: 'subscribe',
- subscription: {
- type: this.mapChannelToType(channel)
- }
- };
-
- // Add coin for specific subscriptions
- if (symbol && channel !== 'allMids') {
- subscribeMessage.subscription.coin = symbol;
- }
-
- // Add interval for candles
- if (channel === 'ohlc' && params?.interval) {
- subscribeMessage.subscription.interval = this.normalizeInterval(params.interval);
- }
-
- await this.send(subscribeMessage);
- this.log(`Subscribed to ${channel}${symbol ? ` for ${symbol}` : ''}`);
- }
-
- /**
- * Unsubscribe from a channel
- */
- protected async performUnsubscribe(topic: string): Promise<void> {
- const { channel, symbol } = this.parseTopic(topic);
-
- const unsubscribeMessage: HyperLiquidSubscription = {
- method: 'unsubscribe',
- subscription: {
- type: this.mapChannelToType(channel)
- }
- };
-
- if (symbol && channel !== 'allMids') {
- unsubscribeMessage.subscription.coin = symbol;
- }
-
- await this.send(unsubscribeMessage);
- this.log(`Sent unsubscription request for ${topic}`);
- }
-
- /**
- * Perform ping (HyperLiquid doesn't require explicit ping)
- */
- protected async performPing(): Promise<void> {
- // HyperLiquid WebSocket maintains connection automatically
- // No explicit ping needed
- this.log('Ping not required for HyperLiquid');
- }
-
- /**
- * Called after successful connection
- */
- protected async onConnected(): Promise<void> {
- this.log('WebSocket connected successfully');
- }
-
- /**
- * Handle channel data messages
- */
- private handleChannelMessage(message: HyperLiquidMessage): void {
- if (!message.channel || !message.data) {
- return;
- }
-
- // Normalize message based on channel type
- const normalizedMessages = this.normalizeMessage(message);
-
- // Emit each normalized message
- normalizedMessages.forEach(msg => {
- this.notifyMessage(msg);
- });
- }
-
- /**
- * Normalize HyperLiquid message to standard format
- */
- private normalizeMessage(message: HyperLiquidMessage): NormalizedMessage[] {
- const normalized: NormalizedMessage[] = [];
- const channel = message.channel || 'unknown';
- const data = message.data;
-
- let type: NormalizedMessage['type'] = 'custom';
- let symbol: string | undefined;
-
- // Map channel to normalized type and extract data
- switch (channel) {
- case 'allMids':
- // All mid prices - emit as ticker for each coin
- type = 'ticker';
- if (data.mids && typeof data.mids === 'object') {
- Object.entries(data.mids).forEach(([coin, price]) => {
- normalized.push({
- provider: this.provider,
- channel: 'ticker',
- type: 'ticker',
- symbol: coin,
- timestamp: Date.now(),
- data: {
- last: parseFloat(price as string),
- mid: parseFloat(price as string)
- },
- raw: message
- });
- });
- }
- return normalized;
-
- case 'l2Book':
- // Order book
- type = 'orderbook';
- symbol = data.coin;
- const orderBookData = this.normalizeOrderBookData(data);
- normalized.push({
- provider: this.provider,
- channel: 'book',
- type,
- symbol,
- timestamp: data.time || Date.now(),
- data: orderBookData,
- raw: message
- });
- return normalized;
-
- case 'trades':
- // Trades
- type = 'trade';
- symbol = data.coin;
- if (Array.isArray(data.trades)) {
- data.trades.forEach((trade: any) => {
- normalized.push({
- provider: this.provider,
- channel: 'trades',
- type: 'trade',
- symbol,
- timestamp: trade.time || Date.now(),
- data: {
- price: parseFloat(trade.px),
- size: parseFloat(trade.sz),
- side: trade.side === 'A' ? 'sell' : 'buy', // A = ask (sell), B = bid (buy)
- time: trade.time
- },
- raw: message
- });
- });
- }
- return normalized;
-
- case 'candle':
- // OHLC candles
- type = 'candle';
- symbol = data.coin;
- if (data.candle) {
- const candle = data.candle;
- normalized.push({
- provider: this.provider,
- channel: 'ohlc',
- type: 'candle',
- symbol,
- timestamp: candle.t || Date.now(),
- data: {
- time: candle.t,
- open: parseFloat(candle.o),
- high: parseFloat(candle.h),
- low: parseFloat(candle.l),
- close: parseFloat(candle.c),
- volume: parseFloat(candle.v || 0)
- },
- raw: message
- });
- }
- return normalized;
-
- default:
- type = 'custom';
- }
-
- // Default push for unhandled channels
- normalized.push({
- provider: this.provider,
- channel,
- type,
- symbol,
- timestamp: Date.now(),
- data,
- raw: message
- });
-
- return normalized;
- }
-
- /**
- * Normalize HyperLiquid order book data to standardized format
- */
- private normalizeOrderBookData(data: any): any {
- const normalized: any = {};
-
- // HyperLiquid format: levels: [[bids], [asks]]
- // Each level: { px: price, sz: size, n: number of orders }
- if (data.levels && Array.isArray(data.levels) && data.levels.length === 2) {
- const [bids, asks] = data.levels;
-
- // Transform bids
- if (Array.isArray(bids)) {
- normalized.bids = bids.map((level: any) => ({
- price: parseFloat(level.px),
- size: parseFloat(level.sz),
- numOrders: level.n
- }));
- }
-
- // Transform asks
- if (Array.isArray(asks)) {
- normalized.asks = asks.map((level: any) => ({
- price: parseFloat(level.px),
- size: parseFloat(level.sz),
- numOrders: level.n
- }));
- }
- }
-
- // Add metadata
- if (data.coin) normalized.symbol = data.coin;
- if (data.time) normalized.time = data.time;
-
- return normalized;
- }
-
- /**
- * Map internal channel name to HyperLiquid subscription type
- */
- private mapChannelToType(channel: string): string {
- const channelMap: Record<string, string> = {
- 'ticker': 'allMids',
- 'book': 'l2Book',
- 'trades': 'trades',
- 'ohlc': 'candle',
- 'candle': 'candle',
- 'allMids': 'allMids',
- 'l2Book': 'l2Book'
- };
-
- return channelMap[channel] || channel;
- }
-
- /**
- * Normalize interval to HyperLiquid format
- */
- private normalizeInterval(interval: string | number): string {
- // Convert number (minutes) to HyperLiquid format
- if (typeof interval === 'number') {
- const intervalMap: Record<number, string> = {
- 1: '1m',
- 5: '5m',
- 15: '15m',
- 60: '1h',
- 240: '4h',
- 1440: '1d'
- };
- return intervalMap[interval] || '1m';
- }
-
- // Already in correct format
- return interval;
- }
-
- /**
- * Parse topic into channel and symbol
- */
- private parseTopic(topic: string): { channel: string; symbol?: string } {
- const parts = topic.split('.');
-
- if (parts.length === 1) {
- // Just channel, no symbol
- return { channel: parts[0] };
- } else {
- // channel.symbol format
- return {
- channel: parts[0],
- symbol: parts.slice(1).join('.')
- };
- }
- }
-}
-
-/**
- * HyperLiquid WebSocket Usage Examples:
- *
- * All Mid Prices:
- * subscribe('allMids')
- * subscribe('ticker') // Alias for allMids
- *
- * Order Book Level 2:
- * subscribe('book.BTC')
- * subscribe('book.ETH')
- *
- * Trades:
- * subscribe('trades.BTC')
- *
- * OHLC Candles (intervals: 1m, 5m, 15m, 1h, 4h, 1d):
- * subscribe('ohlc.BTC', { interval: '1m' })
- * subscribe('candle.ETH', { interval: '1h' })
- *
- * Note: HyperLiquid uses coin symbols without pairs (e.g., 'BTC' not 'BTC/USD')
- */
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts b/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts
deleted file mode 100644
index e0f35e3c9..000000000
--- a/fincept-terminal-desktop/src/services/websocket/adapters/KrakenAdapter.ts
+++ /dev/null
@@ -1,410 +0,0 @@
-// File: src/services/websocket/adapters/KrakenAdapter.ts
-// Kraken WebSocket v2 API adapter
-// Documentation: https://docs.kraken.com/api/docs/websocket-v2
-
-import { BaseAdapter } from './BaseAdapter';
-import { ProviderConfig, NormalizedMessage } from '../types';
-
-/**
- * Kraken WebSocket v2 message types
- */
-interface KrakenMessage {
- method?: string;
- result?: any;
- success?: boolean;
- error?: string;
- channel?: string;
- type?: 'snapshot' | 'update';
- data?: any[];
- timestamp?: string;
-}
-
-/**
- * KrakenAdapter - WebSocket v2 adapter for Kraken exchange
- *
- * Supported channels:
- * - ticker: Real-time ticker updates (bid, ask, last, volume, vwap, high, low, change)
- * - book: Level 2 order book (depth: 10, 25, 100, 500, 1000)
- * - trade: Recent trades
- * - ohlc: OHLC/candlestick data (intervals: 1, 5, 15, 30, 60, 240, 1440, 10080, 21600 minutes)
- * - instrument: Reference data for assets and trading pairs
- * - level3: Level 3 order book (requires authentication)
- *
- * Topic format: "channel.symbol" e.g., "ticker.BTC/USD"
- */
-export class KrakenAdapter extends BaseAdapter {
- readonly provider = 'kraken';
-
- private readonly WS_URL = 'wss://ws.kraken.com/v2';
- private readonly WS_AUTH_URL = 'wss://ws-auth.kraken.com/v2';
-
- private reqIdCounter: number = 1;
-
- /**
- * Get WebSocket URL based on config
- */
- protected getWebSocketUrl(config: ProviderConfig): string {
- // Use authenticated endpoint for level3 or if API key provided
- return config.api_key ? this.WS_AUTH_URL : this.WS_URL;
- }
-
- /**
- * Handle incoming messages from Kraken
- */
- protected handleMessage(event: MessageEvent): void {
- try {
- const message: KrakenMessage = JSON.parse(event.data);
-
- this.log('Received message:', message);
-
- // Handle different message types
- if (message.method === 'pong') {
- this.handlePong();
- } else if (message.method === 'subscribe' || message.method === 'unsubscribe') {
- this.handleSubscriptionResponse(message);
- } else if (message.channel) {
- this.handleChannelMessage(message);
- } else if (message.error) {
- this.handleErrorMessage(message);
- }
- } catch (error) {
- console.error('[KrakenAdapter] Failed to parse message:', error);
- }
- }
-
- /**
- * Subscribe to a channel
- * @param topic - Format: "channel.symbol" e.g., "ticker.BTC/USD"
- * @param params - Optional parameters (depth, interval, event_trigger, snapshot, token)
- */
- protected async performSubscribe(topic: string, params?: Record<string, any>): Promise<void> {
- const { channel, symbol } = this.parseTopic(topic);
-
- const subscribeMessage: any = {
- method: 'subscribe',
- params: {
- channel,
- snapshot: params?.snapshot ?? true
- },
- req_id: this.getNextReqId()
- };
-
- // Add symbol array if provided
- if (symbol) {
- // Normalize symbol for Kraken (BTC/USD -> XBT/USD, ensure uppercase)
- const normalizedSymbol = this.normalizeSymbolForKraken(symbol);
- subscribeMessage.params.symbol = [normalizedSymbol];
- }
-
- // Channel-specific parameters
- if (channel === 'book' || channel === 'level3') {
- // Depth: 10, 25, 100, 500, 1000 (default: 10)
- // Validate and round to nearest valid depth
- let depth = params?.depth ?? 10;
- const validDepths = [10, 25, 100, 500, 1000];
-
- // Find the closest valid depth
- if (!validDepths.includes(depth)) {
- depth = validDepths.reduce((prev, curr) =>
- Math.abs(curr - depth) < Math.abs(prev - depth) ? curr : prev
- );
- }
-
- subscribeMessage.params.depth = depth;
- }
-
- if (channel === 'ohlc') {
- // Interval in minutes: 1, 5, 15, 30, 60, 240, 1440, 10080, 21600
- subscribeMessage.params.interval = params?.interval ?? 1;
- }
-
- if (channel === 'ticker' && params?.event_trigger) {
- // Event trigger: 'bbo' or 'trades'
- subscribeMessage.params.event_trigger = params.event_trigger;
- }
-
- if (channel === 'level3' && this.config?.api_key) {
- // Authentication token for level3
- subscribeMessage.params.token = this.config.api_key;
- }
-
- if (channel === 'instrument' && params?.include_tokenized_assets !== undefined) {
- subscribeMessage.params.include_tokenized_assets = params.include_tokenized_assets;
- }
-
- await this.send(subscribeMessage);
- this.log(`Subscribed to ${channel}${symbol ? ` for ${symbol}` : ''}`);
- }
-
- /**
- * Unsubscribe from a channel
- */
- protected async performUnsubscribe(topic: string): Promise<void> {
- const { channel, symbol } = this.parseTopic(topic);
-
- const unsubscribeMessage: any = {
- method: 'unsubscribe',
- params: {
- channel
- },
- req_id: this.getNextReqId()
- };
-
- if (symbol) {
- unsubscribeMessage.params.symbol = [symbol];
- }
-
- await this.send(unsubscribeMessage);
- this.log(`Sent unsubscription request for ${topic}`);
- }
-
- /**
- * Perform ping
- */
- protected async performPing(): Promise<void> {
- const pingMessage = {
- method: 'ping',
- req_id: this.getNextReqId()
- };
-
- await this.send(pingMessage);
- }
-
- /**
- * Called after successful connection
- */
- protected async onConnected(): Promise<void> {
- this.log('WebSocket connected successfully');
- }
-
- /**
- * Handle channel data messages
- */
- private handleChannelMessage(message: KrakenMessage): void {
- if (!message.channel || !message.data) {
- return;
- }
-
- // Normalize message based on channel type
- const normalizedMessages = this.normalizeMessage(message);
-
- // Emit each normalized message
- normalizedMessages.forEach(msg => {
- this.notifyMessage(msg);
- });
- }
-
- /**
- * Normalize Kraken v2 message to standard format
- */
- private normalizeMessage(message: KrakenMessage): NormalizedMessage[] {
- const normalized: NormalizedMessage[] = [];
-
- if (!message.data || message.data.length === 0) {
- return normalized;
- }
-
- const channel = message.channel || 'unknown';
- const messageType = message.type || 'update';
-
- message.data.forEach((dataItem: any) => {
- let type: NormalizedMessage['type'] = 'custom';
- const symbol = dataItem.symbol;
-
- // Map channel to normalized type
- switch (channel) {
- case 'ticker':
- type = 'ticker';
- break;
- case 'trade':
- type = 'trade';
- break;
- case 'ohlc':
- type = 'candle';
- break;
- case 'book':
- case 'level3':
- type = 'orderbook';
- // Transform Kraken order book format to standardized format
- const normalizedData = this.normalizeOrderBookData(dataItem);
- normalized.push({
- provider: this.provider,
- channel,
- type,
- symbol,
- timestamp: message.timestamp ? new Date(message.timestamp).getTime() : Date.now(),
- data: normalizedData,
- raw: message
- });
- return; // Skip the default push below
- case 'instrument':
- type = 'status';
- break;
- default:
- type = 'custom';
- }
-
- normalized.push({
- provider: this.provider,
- channel,
- type,
- symbol,
- timestamp: message.timestamp ? new Date(message.timestamp).getTime() : Date.now(),
- data: {
- ...dataItem,
- messageType // 'snapshot' or 'update'
- },
- raw: message
- });
- });
-
- return normalized;
- }
-
- /**
- * Normalize Kraken order book data to standardized format
- */
- private normalizeOrderBookData(data: any): any {
- const normalized: any = {
- messageType: data.type || 'update'
- };
-
- // Transform bids array to standardized format
- if (data.bids && Array.isArray(data.bids)) {
- normalized.bids = data.bids.map((bid: any) => ({
- price: parseFloat(bid.price || bid[0] || 0),
- size: parseFloat(bid.qty || bid[1] || 0)
- }));
- }
-
- // Transform asks array to standardized format
- if (data.asks && Array.isArray(data.asks)) {
- normalized.asks = data.asks.map((ask: any) => ({
- price: parseFloat(ask.price || ask[0] || 0),
- size: parseFloat(ask.qty || ask[1] || 0)
- }));
- }
-
- // Copy over other fields
- if (data.symbol) normalized.symbol = data.symbol;
- if (data.checksum) normalized.checksum = data.checksum;
-
- return normalized;
- }
-
- /**
- * Handle subscription response
- */
- private handleSubscriptionResponse(message: KrakenMessage): void {
- if (message.success) {
- this.log('Subscription successful:', message);
- } else if (message.error) {
- // Log error but don't add to error queue for common subscription issues
- const errorStr = String(message.error);
-
- // Categorize errors
- const isCommonError =
- errorStr.includes('not Found') ||
- errorStr.includes('invalid') ||
- errorStr.includes('not supported');
-
- // Only log verbose errors in development
- if (isCommonError) {
- console.debug('[KrakenAdapter] Subscription info:', message.error);
- } else {
- console.error('[KrakenAdapter] Subscription error:', message.error);
- this.addError({
- timestamp: Date.now(),
- error: message.error
- });
- }
- }
- }
-
- /**
- * Handle error messages
- */
- private handleErrorMessage(message: KrakenMessage): void {
- const error = {
- timestamp: Date.now(),
- error: message.error || 'Unknown error'
- };
-
- this.addError(error);
- this.notifyError(error);
- this.log('Error message:', message.error);
- }
-
- /**
- * Handle pong response
- */
- private handlePong(): void {
- this.log('Received pong');
- }
-
- /**
- * Parse topic into channel and symbol
- */
- private parseTopic(topic: string): { channel: string; symbol?: string } {
- const parts = topic.split('.');
-
- if (parts.length === 1) {
- // Just channel, no symbol
- return { channel: parts[0] };
- } else {
- // channel.symbol format
- return {
- channel: parts[0],
- symbol: parts.slice(1).join('.')
- };
- }
- }
-
- /**
- * Get next request ID
- */
- private getNextReqId(): number {
- return this.reqIdCounter++;
- }
-
- /**
- * Normalize symbol for Kraken WebSocket API
- * Kraken WebSocket v2 uses different formats than v1
- * Examples: BTC/USD, ETH/USD (not XBT/USD)
- */
- private normalizeSymbolForKraken(symbol: string): string {
- // Ensure uppercase
- let normalized = symbol.toUpperCase();
-
- // Kraken WebSocket v2 actually uses BTC/USD format, not XBT/USD
- // The v1 API used XBT, but v2 standardized on BTC
- // No conversion needed for v2 API
-
- return normalized;
- }
-}
-
-/**
- * Kraken WebSocket v2 Usage Examples:
- *
- * Ticker (bid, ask, last, volume, vwap, high, low, change):
- * subscribe('ticker.BTC/USD')
- * subscribe('ticker.ETH/USD', { event_trigger: 'bbo' })
- *
- * Order Book Level 2 (depth: 10, 25, 100, 500, 1000):
- * subscribe('book.BTC/USD', { depth: 10 })
- * subscribe('book.ETH/USD', { depth: 100, snapshot: true })
- *
- * Trades:
- * subscribe('trade.BTC/USD')
- *
- * OHLC Candles (intervals: 1, 5, 15, 30, 60, 240, 1440, 10080, 21600 minutes):
- * subscribe('ohlc.BTC/USD', { interval: 1 })
- * subscribe('ohlc.ETH/USD', { interval: 60 })
- *
- * Instrument Reference Data:
- * subscribe('instrument', { include_tokenized_assets: false })
- *
- * Level 3 Order Book (requires authentication):
- * subscribe('level3.BTC/USD', { depth: 10 })
- */
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/index.ts b/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
deleted file mode 100644
index 0c5ac000f..000000000
--- a/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-// File: src/services/websocket/adapters/index.ts
-// Export all adapters and adapter registry
-
-import { AdapterRegistry, IWebSocketAdapter } from '../types';
-import { BaseAdapter } from './BaseAdapter';
-import { KrakenAdapter } from './KrakenAdapter';
-import { HyperLiquidAdapter } from './HyperLiquidAdapter';
-
-/**
- * Global registry of available WebSocket adapters
- * Add new adapters here as they are implemented
- */
-export const adapters: AdapterRegistry = {
- kraken: KrakenAdapter,
- hyperliquid: HyperLiquidAdapter,
- // Add more adapters here:
- // fyers: FyersAdapter,
- // polygon: PolygonAdapter,
- // binance: BinanceAdapter,
- // etc.
-};
-
-/**
- * Get list of available provider names
- */
-export function getAvailableProviders(): string[] {
- return Object.keys(adapters);
-}
-
-/**
- * Check if provider is available
- */
-export function isProviderAvailable(provider: string): boolean {
- return provider in adapters;
-}
-
-/**
- * Create adapter instance for a provider
- */
-export function createAdapter(provider: string): IWebSocketAdapter {
- const AdapterClass = adapters[provider];
-
- if (!AdapterClass) {
- throw new Error(`Adapter not found for provider: ${provider}`);
- }
-
- return new AdapterClass();
-}
-
-// Export adapter classes
-export { BaseAdapter } from './BaseAdapter';
-export { KrakenAdapter } from './KrakenAdapter';
-export { HyperLiquidAdapter } from './HyperLiquidAdapter';
diff --git a/fincept-terminal-desktop/src/services/websocket/index.ts b/fincept-terminal-desktop/src/services/websocket/index.ts
deleted file mode 100644
index 47b42a4fe..000000000
--- a/fincept-terminal-desktop/src/services/websocket/index.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-// File: src/services/websocket/index.ts
-// Main entry point for WebSocket management system
-
-// Core Manager
-export { WebSocketManager, getWebSocketManager, resetWebSocketManager } from './WebSocketManager';
-
-// Event Bus
-export { EventBus, globalEventBus } from './EventBus';
-
-// Registry
-export { WebSocketRegistry } from './WebSocketRegistry';
-
-// Types
-export type {
- IWebSocketAdapter,
- ConnectionMetrics,
- ConnectionError,
- ProviderConfig,
- NormalizedMessage,
- Subscription,
- SubscriptionTopic,
- MessageCallback,
- RateLimitConfig,
- ReconnectionPolicy,
- WebSocketManagerConfig,
- EventBusEvent,
- AdapterRegistry,
- HealthCheckResult,
- ParsedTopic,
- QueuedMessage
-} from './types';
-
-export {
- ConnectionStatus, // enum (both type and value)
- DEFAULT_RATE_LIMIT,
- DEFAULT_RECONNECTION_POLICY,
- DEFAULT_MANAGER_CONFIG,
- parseTopic,
- buildTopic
-} from './types';
-
-// Utilities
-export {
- ReconnectionManager,
- RateLimiter,
- CircuitBreaker,
- MessageThrottler,
- HeartbeatMonitor,
- PerformanceMetrics,
- retryWithBackoff,
- generateId,
- safeJsonParse,
- debounce
-} from './utils';
-
-// Adapters
-export { BaseAdapter } from './adapters/BaseAdapter';
-export { KrakenAdapter } from './adapters/KrakenAdapter';
-export {
- adapters,
- getAvailableProviders,
- isProviderAvailable,
- createAdapter
-} from './adapters';
-
-/**
- * Quick start guide:
- *
- * 1. Set up provider configuration:
- * ```typescript
- * import { getWebSocketManager } from '@/services/websocket';
- *
- * const manager = getWebSocketManager();
- *
- * manager.setProviderConfig('kraken', {
- * provider_name: 'kraken',
- * enabled: true,
- * endpoint: 'wss://ws.kraken.com/v2'
- * });
- * ```
- *
- * 2. Subscribe to topics:
- * ```typescript
- * const subscription = await manager.subscribe(
- * 'kraken.ticker.BTC/USD',
- * (message) => {
- * console.log('Price update:', message.data);
- * }
- * );
- * ```
- *
- * 3. Use in React components:
- * ```typescript
- * import { useWebSocket } from '@/hooks/useWebSocket';
- *
- * function PriceDisplay() {
- * const { message, status } = useWebSocket('kraken.ticker.BTC/USD');
- *
- * return (
- * <div>
- * <p>Status: {status}</p>
- * <p>Price: {message?.data.last}</p>
- * </div>
- * );
- * }
- * ```
- *
- * 4. Monitor connections in Settings:
- * See useWebSocketManager hook in hooks/useWebSocket.ts for connection monitoring
- */
diff --git a/fincept-terminal-desktop/src/services/websocket/types.ts b/fincept-terminal-desktop/src/services/websocket/types.ts
deleted file mode 100644
index 6e87a5c68..000000000
--- a/fincept-terminal-desktop/src/services/websocket/types.ts
+++ /dev/null
@@ -1,314 +0,0 @@
-// File: src/services/websocket/types.ts
-// Core TypeScript types and interfaces for WebSocket management system
-
-/**
- * Connection status for WebSocket providers
- */
-export enum ConnectionStatus {
- DISCONNECTED = 'disconnected',
- CONNECTING = 'connecting',
- CONNECTED = 'connected',
- RECONNECTING = 'reconnecting',
- ERROR = 'error',
- RATE_LIMITED = 'rate_limited'
-}
-
-/**
- * Standard message format across all providers
- * Providers normalize their messages to this format
- */
-export interface NormalizedMessage {
- provider: string;
- channel: string;
- type: 'ticker' | 'trade' | 'orderbook' | 'candle' | 'status' | 'error' | 'custom';
- symbol?: string;
- timestamp: number;
- data: any;
- raw?: any; // Original message for debugging
-}
-
-/**
- * Subscription topic structure
- * Example: "kraken.ticker.BTC/USD" or "fyers.orderbook.NSE:RELIANCE-EQ"
- */
-export interface SubscriptionTopic {
- provider: string;
- channel: string;
- symbol?: string;
- params?: Record<string, any>;
-}
-
-/**
- * Callback function for message subscriptions
- */
-export type MessageCallback = (message: NormalizedMessage) => void;
-
-/**
- * Subscription handle returned to subscribers
- */
-export interface Subscription {
- id: string;
- topic: string;
- callback: MessageCallback;
- unsubscribe: () => void;
- params?: Record<string, any>;
-}
-
-/**
- * Provider configuration stored in SQLite
- */
-export interface ProviderConfig {
- id?: number;
- provider_name: string;
- enabled: boolean;
- api_key?: string | null;
- api_secret?: string | null;
- endpoint?: string | null;
- config_data?: string | null; // JSON string for additional config
- created_at?: string;
- updated_at?: string;
-}
-
-/**
- * Connection health metrics
- */
-export interface ConnectionMetrics {
- provider: string;
- status: ConnectionStatus;
- connectedAt?: number;
- lastMessageAt?: number;
- uptime?: number; // milliseconds
- latency?: number; // milliseconds
- messagesReceived: number;
- messagesPerSecond: number;
- reconnectionAttempts: number;
- errors: ConnectionError[];
- subscriptions: number;
-}
-
-/**
- * Connection error tracking
- */
-export interface ConnectionError {
- timestamp: number;
- error: string;
- code?: string | number;
- details?: any;
-}
-
-/**
- * Rate limiting configuration
- */
-export interface RateLimitConfig {
- maxMessagesPerSecond: number;
- maxSubscriptions: number;
- throttleMs: number;
- enabled: boolean;
-}
-
-/**
- * Reconnection policy configuration
- */
-export interface ReconnectionPolicy {
- enabled: boolean;
- maxAttempts: number;
- initialDelayMs: number;
- maxDelayMs: number;
- backoffMultiplier: number;
- resetAfterMs: number; // Reset attempt counter after successful connection
-}
-
-/**
- * Abstract WebSocket adapter interface
- * All provider adapters must implement this
- */
-export interface IWebSocketAdapter {
- readonly provider: string;
- readonly status: ConnectionStatus;
- readonly metrics: ConnectionMetrics;
-
- /**
- * Initialize connection with provider-specific config
- */
- connect(config: ProviderConfig): Promise<void>;
-
- /**
- * Gracefully disconnect
- */
- disconnect(): Promise<void>;
-
- /**
- * Subscribe to a channel/topic
- * @param topic - Topic string (e.g., "ticker.BTC/USD")
- * @param params - Additional subscription parameters
- */
- subscribe(topic: string, params?: Record<string, any>): Promise<void>;
-
- /**
- * Unsubscribe from a channel/topic
- */
- unsubscribe(topic: string): Promise<void>;
-
- /**
- * Send raw message to provider (for advanced use)
- */
- send(message: any): Promise<void>;
-
- /**
- * Register message handler
- */
- onMessage(callback: (message: NormalizedMessage) => void): void;
-
- /**
- * Register error handler
- */
- onError(callback: (error: ConnectionError) => void): void;
-
- /**
- * Register status change handler
- */
- onStatusChange(callback: (status: ConnectionStatus) => void): void;
-
- /**
- * Ping/health check
- */
- ping(): Promise<number>; // Returns latency in ms
-
- /**
- * Get current subscriptions
- */
- getSubscriptions(): string[];
-
- /**
- * Cleanup resources
- */
- destroy(): void;
-}
-
-/**
- * WebSocket Manager configuration
- */
-export interface WebSocketManagerConfig {
- maxConnectionsPerProvider: number;
- globalRateLimit: RateLimitConfig;
- defaultReconnectionPolicy: ReconnectionPolicy;
- enableMetrics: boolean;
- enableLogging: boolean;
- logLevel: 'debug' | 'info' | 'warn' | 'error';
-}
-
-/**
- * Event bus event structure
- */
-export interface EventBusEvent {
- topic: string;
- message: NormalizedMessage;
- timestamp: number;
-}
-
-/**
- * Provider adapter constructor signature
- */
-export type AdapterConstructor = new () => IWebSocketAdapter;
-
-/**
- * Registry of available adapters
- */
-export interface AdapterRegistry {
- [provider: string]: AdapterConstructor;
-}
-
-/**
- * Health check result
- */
-export interface HealthCheckResult {
- provider: string;
- healthy: boolean;
- latency?: number;
- error?: string;
- timestamp: number;
-}
-
-/**
- * Topic parser result
- */
-export interface ParsedTopic {
- provider: string;
- channel: string;
- symbol?: string;
- params?: Record<string, any>;
- raw: string;
-}
-
-/**
- * Message queue item for backpressure handling
- */
-export interface QueuedMessage {
- message: NormalizedMessage;
- timestamp: number;
- retries: number;
-}
-
-/**
- * Default configurations
- */
-export const DEFAULT_RATE_LIMIT: RateLimitConfig = {
- maxMessagesPerSecond: 100,
- maxSubscriptions: 50,
- throttleMs: 10,
- enabled: true
-};
-
-export const DEFAULT_RECONNECTION_POLICY: ReconnectionPolicy = {
- enabled: true,
- maxAttempts: 10,
- initialDelayMs: 1000,
- maxDelayMs: 30000,
- backoffMultiplier: 2,
- resetAfterMs: 60000
-};
-
-export const DEFAULT_MANAGER_CONFIG: WebSocketManagerConfig = {
- maxConnectionsPerProvider: 10,
- globalRateLimit: DEFAULT_RATE_LIMIT,
- defaultReconnectionPolicy: DEFAULT_RECONNECTION_POLICY,
- enableMetrics: true,
- enableLogging: true,
- logLevel: 'info'
-};
-
-/**
- * Topic format: "provider.channel.symbol"
- * Examples:
- * - "kraken.ticker.BTC/USD"
- * - "fyers.orderbook.NSE:RELIANCE-EQ"
- * - "polygon.trades.AAPL"
- * - "binance.candles.BTCUSDT.1m"
- */
-export function parseTopic(topic: string): ParsedTopic {
- const parts = topic.split('.');
-
- if (parts.length < 2) {
- throw new Error(`Invalid topic format: ${topic}. Expected "provider.channel[.symbol]"`);
- }
-
- const [provider, channel, symbol, ...paramParts] = parts;
-
- return {
- provider,
- channel,
- symbol,
- params: paramParts.length > 0 ? { extra: paramParts.join('.') } : undefined,
- raw: topic
- };
-}
-
-/**
- * Build topic string from components
- */
-export function buildTopic(provider: string, channel: string, symbol?: string, params?: string[]): string {
- const parts = [provider, channel];
- if (symbol) parts.push(symbol);
- if (params && params.length > 0) parts.push(...params);
- return parts.join('.');
-}
diff --git a/fincept-terminal-desktop/src/services/websocket/utils.ts b/fincept-terminal-desktop/src/services/websocket/utils.ts
deleted file mode 100644
index bf13fc102..000000000
--- a/fincept-terminal-desktop/src/services/websocket/utils.ts
+++ /dev/null
@@ -1,621 +0,0 @@
-// File: src/services/websocket/utils.ts
-// Utility functions for WebSocket management (reconnection, rate limiting, etc.)
-
-import { ReconnectionPolicy, RateLimitConfig } from './types';
-
-/**
- * Exponential backoff calculator for reconnection delays
- */
-export class ReconnectionManager {
- private attempts: number = 0;
- private lastAttemptTime: number = 0;
- private lastSuccessTime: number = 0;
- private policy: ReconnectionPolicy;
-
- constructor(policy: ReconnectionPolicy) {
- this.policy = policy;
- }
-
- /**
- * Calculate next reconnection delay using exponential backoff
- */
- getNextDelay(): number {
- if (!this.policy.enabled) {
- return 0;
- }
-
- // Reset attempts if enough time has passed since last success
- if (
- this.lastSuccessTime > 0 &&
- Date.now() - this.lastSuccessTime > this.policy.resetAfterMs
- ) {
- this.reset();
- }
-
- const delay = Math.min(
- this.policy.initialDelayMs * Math.pow(this.policy.backoffMultiplier, this.attempts),
- this.policy.maxDelayMs
- );
-
- return delay;
- }
-
- /**
- * Record a reconnection attempt
- */
- recordAttempt(): void {
- this.attempts++;
- this.lastAttemptTime = Date.now();
- }
-
- /**
- * Record successful connection
- */
- recordSuccess(): void {
- this.lastSuccessTime = Date.now();
- this.reset();
- }
-
- /**
- * Check if should attempt reconnection
- */
- shouldAttempt(): boolean {
- return this.policy.enabled && this.attempts < this.policy.maxAttempts;
- }
-
- /**
- * Get current attempt count
- */
- getAttempts(): number {
- return this.attempts;
- }
-
- /**
- * Reset attempt counter
- */
- reset(): void {
- this.attempts = 0;
- }
-
- /**
- * Update policy at runtime
- */
- updatePolicy(policy: Partial<ReconnectionPolicy>): void {
- this.policy = { ...this.policy, ...policy };
- }
-}
-
-/**
- * Rate limiter using token bucket algorithm
- */
-export class RateLimiter {
- private tokens: number;
- private maxTokens: number;
- private refillRate: number; // tokens per second
- private lastRefill: number;
- private config: RateLimitConfig;
- private messageQueue: Array<() => void> = [];
-
- constructor(config: RateLimitConfig) {
- this.config = config;
- this.maxTokens = config.maxMessagesPerSecond;
- this.tokens = this.maxTokens;
- this.refillRate = config.maxMessagesPerSecond;
- this.lastRefill = Date.now();
- }
-
- /**
- * Check if action is allowed (consumes token if available)
- */
- tryConsume(): boolean {
- if (!this.config.enabled) {
- return true;
- }
-
- this.refill();
-
- if (this.tokens >= 1) {
- this.tokens -= 1;
- return true;
- }
-
- return false;
- }
-
- /**
- * Refill tokens based on time elapsed
- */
- private refill(): void {
- const now = Date.now();
- const timePassed = (now - this.lastRefill) / 1000; // seconds
- const tokensToAdd = timePassed * this.refillRate;
-
- this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);
- this.lastRefill = now;
- }
-
- /**
- * Wait for available token (returns delay in ms)
- */
- getWaitTime(): number {
- if (!this.config.enabled) {
- return 0;
- }
-
- this.refill();
-
- if (this.tokens >= 1) {
- return 0;
- }
-
- // Calculate time until next token is available
- const tokensNeeded = 1 - this.tokens;
- const waitTime = (tokensNeeded / this.refillRate) * 1000;
-
- return Math.max(waitTime, this.config.throttleMs);
- }
-
- /**
- * Execute action with rate limiting
- */
- async execute<T>(action: () => Promise<T>): Promise<T> {
- if (!this.config.enabled) {
- return action();
- }
-
- const waitTime = this.getWaitTime();
-
- if (waitTime > 0) {
- await this.sleep(waitTime);
- }
-
- this.tryConsume();
- return action();
- }
-
- /**
- * Queue action for later execution when tokens available
- */
- queue(action: () => void): void {
- this.messageQueue.push(action);
- this.processQueue();
- }
-
- /**
- * Process queued actions
- */
- private async processQueue(): Promise<void> {
- while (this.messageQueue.length > 0) {
- if (this.tryConsume()) {
- const action = this.messageQueue.shift();
- if (action) {
- try {
- action();
- } catch (error) {
- console.error('[RateLimiter] Error executing queued action:', error);
- }
- }
- } else {
- // Wait for next token
- const waitTime = this.getWaitTime();
- await this.sleep(waitTime);
- }
- }
- }
-
- /**
- * Get current token count
- */
- getAvailableTokens(): number {
- this.refill();
- return Math.floor(this.tokens);
- }
-
- /**
- * Reset rate limiter
- */
- reset(): void {
- this.tokens = this.maxTokens;
- this.lastRefill = Date.now();
- this.messageQueue = [];
- }
-
- /**
- * Update configuration at runtime
- */
- updateConfig(config: Partial<RateLimitConfig>): void {
- this.config = { ...this.config, ...config };
- this.maxTokens = this.config.maxMessagesPerSecond;
- this.refillRate = this.config.maxMessagesPerSecond;
- }
-
- private sleep(ms: number): Promise<void> {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
-}
-
-/**
- * Circuit breaker for handling repeated failures
- */
-export class CircuitBreaker {
- private failures: number = 0;
- private lastFailureTime: number = 0;
- private state: 'closed' | 'open' | 'half-open' = 'closed';
- private successCount: number = 0;
-
- constructor(
- private failureThreshold: number = 5,
- private timeout: number = 60000, // 1 minute
- private successThreshold: number = 2
- ) {}
-
- /**
- * Record successful operation
- */
- recordSuccess(): void {
- this.failures = 0;
- this.lastFailureTime = 0;
-
- if (this.state === 'half-open') {
- this.successCount++;
- if (this.successCount >= this.successThreshold) {
- this.state = 'closed';
- this.successCount = 0;
- }
- }
- }
-
- /**
- * Record failed operation
- */
- recordFailure(): void {
- this.failures++;
- this.lastFailureTime = Date.now();
-
- if (this.failures >= this.failureThreshold) {
- this.state = 'open';
- }
-
- if (this.state === 'half-open') {
- this.state = 'open';
- this.successCount = 0;
- }
- }
-
- /**
- * Check if operation is allowed
- */
- isAllowed(): boolean {
- if (this.state === 'closed') {
- return true;
- }
-
- if (this.state === 'open') {
- // Check if timeout has passed
- if (Date.now() - this.lastFailureTime >= this.timeout) {
- this.state = 'half-open';
- this.successCount = 0;
- return true;
- }
- return false;
- }
-
- // half-open state
- return true;
- }
-
- /**
- * Get current state
- */
- getState(): 'closed' | 'open' | 'half-open' {
- return this.state;
- }
-
- /**
- * Reset circuit breaker
- */
- reset(): void {
- this.failures = 0;
- this.lastFailureTime = 0;
- this.state = 'closed';
- this.successCount = 0;
- }
-}
-
-/**
- * Message throttler for preventing UI overload
- */
-export class MessageThrottler {
- private lastExecutionTime: number = 0;
- private pendingMessage: any = null;
- private timeoutId: NodeJS.Timeout | null = null;
-
- constructor(private throttleMs: number = 100) {}
-
- /**
- * Throttle message delivery
- */
- throttle<T>(message: T, callback: (message: T) => void): void {
- const now = Date.now();
- const timeSinceLastExecution = now - this.lastExecutionTime;
-
- if (timeSinceLastExecution >= this.throttleMs) {
- // Execute immediately
- callback(message);
- this.lastExecutionTime = now;
- this.pendingMessage = null;
-
- // Clear any pending timeout
- if (this.timeoutId) {
- clearTimeout(this.timeoutId);
- this.timeoutId = null;
- }
- } else {
- // Store message and schedule execution
- this.pendingMessage = message;
-
- if (!this.timeoutId) {
- const delay = this.throttleMs - timeSinceLastExecution;
- this.timeoutId = setTimeout(() => {
- if (this.pendingMessage) {
- callback(this.pendingMessage);
- this.lastExecutionTime = Date.now();
- this.pendingMessage = null;
- }
- this.timeoutId = null;
- }, delay);
- }
- }
- }
-
- /**
- * Flush any pending message immediately
- */
- flush<T>(callback: (message: T) => void): void {
- if (this.pendingMessage) {
- callback(this.pendingMessage);
- this.pendingMessage = null;
- this.lastExecutionTime = Date.now();
- }
-
- if (this.timeoutId) {
- clearTimeout(this.timeoutId);
- this.timeoutId = null;
- }
- }
-
- /**
- * Clear throttler
- */
- clear(): void {
- this.pendingMessage = null;
- if (this.timeoutId) {
- clearTimeout(this.timeoutId);
- this.timeoutId = null;
- }
- }
-}
-
-/**
- * Heartbeat monitor for detecting stale connections
- */
-export class HeartbeatMonitor {
- private lastHeartbeat: number = Date.now();
- private timeoutId: NodeJS.Timeout | null = null;
- private onTimeout?: () => void;
-
- constructor(
- private intervalMs: number = 30000, // 30 seconds
- private timeoutMs: number = 60000 // 1 minute
- ) {}
-
- /**
- * Start heartbeat monitoring
- */
- start(onTimeout: () => void): void {
- this.onTimeout = onTimeout;
- this.lastHeartbeat = Date.now();
- this.scheduleCheck();
- }
-
- /**
- * Record heartbeat (call this when receiving messages)
- */
- beat(): void {
- this.lastHeartbeat = Date.now();
- }
-
- /**
- * Stop monitoring
- */
- stop(): void {
- if (this.timeoutId) {
- clearTimeout(this.timeoutId);
- this.timeoutId = null;
- }
- this.onTimeout = undefined;
- }
-
- /**
- * Schedule next heartbeat check
- */
- private scheduleCheck(): void {
- if (this.timeoutId) {
- clearTimeout(this.timeoutId);
- }
-
- this.timeoutId = setTimeout(() => {
- const timeSinceLastBeat = Date.now() - this.lastHeartbeat;
-
- if (timeSinceLastBeat > this.timeoutMs) {
- // Connection appears stale
- if (this.onTimeout) {
- this.onTimeout();
- }
- } else {
- // Schedule next check
- this.scheduleCheck();
- }
- }, this.intervalMs);
- }
-
- /**
- * Get time since last heartbeat
- */
- getTimeSinceLastBeat(): number {
- return Date.now() - this.lastHeartbeat;
- }
-
- /**
- * Check if connection appears healthy
- */
- isHealthy(): boolean {
- return this.getTimeSinceLastBeat() < this.timeoutMs;
- }
-}
-
-/**
- * Performance metrics collector
- */
-export class PerformanceMetrics {
- private messageCount: number = 0;
- private errorCount: number = 0;
- private startTime: number = Date.now();
- private messageSizes: number[] = [];
- private latencies: number[] = [];
- private maxSamples: number = 100;
-
- /**
- * Record message received
- */
- recordMessage(size?: number): void {
- this.messageCount++;
-
- if (size !== undefined) {
- this.messageSizes.push(size);
- if (this.messageSizes.length > this.maxSamples) {
- this.messageSizes.shift();
- }
- }
- }
-
- /**
- * Record error
- */
- recordError(): void {
- this.errorCount++;
- }
-
- /**
- * Record latency measurement
- */
- recordLatency(latencyMs: number): void {
- this.latencies.push(latencyMs);
- if (this.latencies.length > this.maxSamples) {
- this.latencies.shift();
- }
- }
-
- /**
- * Get metrics summary
- */
- getMetrics() {
- const uptime = Date.now() - this.startTime;
- const uptimeSeconds = uptime / 1000;
-
- return {
- messageCount: this.messageCount,
- errorCount: this.errorCount,
- messagesPerSecond: uptimeSeconds > 0 ? this.messageCount / uptimeSeconds : 0,
- errorRate: this.messageCount > 0 ? this.errorCount / this.messageCount : 0,
- averageMessageSize: this.average(this.messageSizes),
- averageLatency: this.average(this.latencies),
- uptime,
- uptimeHours: uptime / (1000 * 60 * 60)
- };
- }
-
- /**
- * Reset metrics
- */
- reset(): void {
- this.messageCount = 0;
- this.errorCount = 0;
- this.startTime = Date.now();
- this.messageSizes = [];
- this.latencies = [];
- }
-
- private average(arr: number[]): number {
- if (arr.length === 0) return 0;
- return arr.reduce((a, b) => a + b, 0) / arr.length;
- }
-}
-
-/**
- * Retry helper with exponential backoff
- */
-export async function retryWithBackoff<T>(
- fn: () => Promise<T>,
- maxRetries: number = 3,
- initialDelay: number = 1000,
- maxDelay: number = 10000,
- multiplier: number = 2
-): Promise<T> {
- let lastError: Error | undefined;
-
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
- try {
- return await fn();
- } catch (error) {
- lastError = error instanceof Error ? error : new Error(String(error));
-
- if (attempt < maxRetries) {
- const delay = Math.min(initialDelay * Math.pow(multiplier, attempt), maxDelay);
- await new Promise(resolve => setTimeout(resolve, delay));
- }
- }
- }
-
- throw lastError || new Error('Max retries exceeded');
-}
-
-/**
- * Generate unique ID
- */
-export function generateId(prefix: string = 'ws'): string {
- return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
-}
-
-/**
- * Safe JSON parse with fallback
- */
-export function safeJsonParse<T = any>(json: string, fallback: T): T {
- try {
- return JSON.parse(json);
- } catch {
- return fallback;
- }
-}
-
-/**
- * Debounce function
- */
-export function debounce<T extends (...args: any[]) => any>(
- func: T,
- wait: number
-): (...args: Parameters<T>) => void {
- let timeout: NodeJS.Timeout | null = null;
-
- return function (this: any, ...args: Parameters<T>) {
- const context = this;
-
- if (timeout) {
- clearTimeout(timeout);
- }
-
- timeout = setTimeout(() => {
- func.apply(context, args);
- }, wait);
- };
-}
diff --git a/fincept-terminal-desktop/src/services/websocketBridge.ts b/fincept-terminal-desktop/src/services/websocketBridge.ts
new file mode 100644
index 000000000..e2dc6e70a
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/websocketBridge.ts
@@ -0,0 +1,297 @@
+// WebSocket Bridge - TypeScript wrapper for Rust WebSocket system
+// Provides a clean API for frontend components to use Rust WebSocket backend
+
+import { invoke } from '@tauri-apps/api/core';
+import { listen, UnlistenFn } from '@tauri-apps/api/event';
+
+// ============================================================================
+// TYPES (matching Rust types)
+// ============================================================================
+
+export interface ProviderConfig {
+ name: string;
+ url: string;
+ api_key?: string;
+ api_secret?: string;
+ enabled: boolean;
+ reconnect_delay_ms: number;
+ max_reconnect_attempts: number;
+ heartbeat_interval_ms: number;
+}
+
+export interface TickerData {
+ provider: string;
+ symbol: string;
+ price: number;
+ bid?: number;
+ ask?: number;
+ bid_size?: number;
+ ask_size?: number;
+ volume?: number;
+ high?: number;
+ low?: number;
+ open?: number;
+ close?: number;
+ change?: number;
+ change_percent?: number;
+ timestamp: number;
+}
+
+export interface OrderBookLevel {
+ price: number;
+ quantity: number;
+ count?: number;
+}
+
+export interface OrderBookData {
+ provider: string;
+ symbol: string;
+ bids: OrderBookLevel[];
+ asks: OrderBookLevel[];
+ timestamp: number;
+ is_snapshot: boolean;
+}
+
+export interface TradeData {
+ provider: string;
+ symbol: string;
+ trade_id?: string;
+ price: number;
+ quantity: number;
+ side: 'buy' | 'sell' | 'unknown';
+ timestamp: number;
+}
+
+export interface CandleData {
+ provider: string;
+ symbol: string;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+ timestamp: number;
+ interval: string;
+}
+
+export interface StatusData {
+ provider: string;
+ status: 'connected' | 'connecting' | 'disconnected' | 'reconnecting' | 'error';
+ message?: string;
+ timestamp: number;
+}
+
+export interface ConnectionMetrics {
+ provider: string;
+ status: 'connected' | 'connecting' | 'disconnected' | 'reconnecting' | 'error';
+ connected_at?: number;
+ last_message_at?: number;
+ messages_received: number;
+ messages_sent: number;
+ active_subscriptions: number;
+ reconnect_count: number;
+ latency_ms?: number;
+}
+
+// ============================================================================
+// WEBSOCKET BRIDGE CLASS
+// ============================================================================
+
+export class WebSocketBridge {
+ private eventListeners: Map<string, UnlistenFn> = new Map();
+
+ // ========================================================================
+ // CONFIGURATION
+ // ========================================================================
+
+ async setConfig(config: ProviderConfig): Promise<void> {
+ await invoke('ws_set_config', { config });
+ }
+
+ // ========================================================================
+ // CONNECTION MANAGEMENT
+ // ========================================================================
+
+ async connect(provider: string): Promise<void> {
+ await invoke('ws_connect', { provider });
+ }
+
+ async disconnect(provider: string): Promise<void> {
+ await invoke('ws_disconnect', { provider });
+ }
+
+ async reconnect(provider: string): Promise<void> {
+ await invoke('ws_reconnect', { provider });
+ }
+
+ // ========================================================================
+ // SUBSCRIPTION MANAGEMENT
+ // ========================================================================
+
+ async subscribe(
+ provider: string,
+ symbol: string,
+ channel: string,
+ params?: Record<string, any>
+ ): Promise<void> {
+ await invoke('ws_subscribe', {
+ provider,
+ symbol,
+ channel,
+ params: params ? params : null,
+ });
+ }
+
+ async unsubscribe(provider: string, symbol: string, channel: string): Promise<void> {
+ await invoke('ws_unsubscribe', { provider, symbol, channel });
+ }
+
+ // ========================================================================
+ // EVENT LISTENERS
+ // ========================================================================
+
+ async onTicker(callback: (data: TickerData) => void): Promise<UnlistenFn> {
+ const unlisten = await listen<TickerData>('ws_ticker', (event) => {
+ callback(event.payload);
+ });
+ this.eventListeners.set('ws_ticker', unlisten);
+ return unlisten;
+ }
+
+ async onOrderBook(callback: (data: OrderBookData) => void): Promise<UnlistenFn> {
+ const unlisten = await listen<OrderBookData>('ws_orderbook', (event) => {
+ callback(event.payload);
+ });
+ this.eventListeners.set('ws_orderbook', unlisten);
+ return unlisten;
+ }
+
+ async onTrade(callback: (data: TradeData) => void): Promise<UnlistenFn> {
+ const unlisten = await listen<TradeData>('ws_trade', (event) => {
+ callback(event.payload);
+ });
+ this.eventListeners.set('ws_trade', unlisten);
+ return unlisten;
+ }
+
+ async onCandle(callback: (data: CandleData) => void): Promise<UnlistenFn> {
+ const unlisten = await listen<CandleData>('ws_candle', (event) => {
+ callback(event.payload);
+ });
+ this.eventListeners.set('ws_candle', unlisten);
+ return unlisten;
+ }
+
+ async onStatus(callback: (data: StatusData) => void): Promise<UnlistenFn> {
+ const unlisten = await listen<StatusData>('ws_status', (event) => {
+ callback(event.payload);
+ });
+ this.eventListeners.set('ws_status', unlisten);
+ return unlisten;
+ }
+
+ // ========================================================================
+ // METRICS
+ // ========================================================================
+
+ async getMetrics(provider: string): Promise<ConnectionMetrics | null> {
+ return await invoke('ws_get_metrics', { provider });
+ }
+
+ async getAllMetrics(): Promise<ConnectionMetrics[]> {
+ return await invoke('ws_get_all_metrics');
+ }
+
+ // ========================================================================
+ // CLEANUP
+ // ========================================================================
+
+ async cleanup(): Promise<void> {
+ // Unlisten from all events
+ for (const unlisten of this.eventListeners.values()) {
+ unlisten();
+ }
+ this.eventListeners.clear();
+ }
+}
+
+// ============================================================================
+// SINGLETON INSTANCE
+// ============================================================================
+
+export const websocketBridge = new WebSocketBridge();
+
+// ============================================================================
+// HELPER FUNCTIONS
+// ============================================================================
+
+/**
+ * Configure provider with default settings
+ */
+export async function configureProvider(
+ name: string,
+ url: string,
+ options?: Partial<ProviderConfig>
+): Promise<void> {
+ const config: ProviderConfig = {
+ name,
+ url,
+ enabled: true,
+ reconnect_delay_ms: 5000,
+ max_reconnect_attempts: 10,
+ heartbeat_interval_ms: 30000,
+ ...options,
+ };
+
+ await websocketBridge.setConfig(config);
+}
+
+/**
+ * Quick subscribe helper
+ */
+export async function subscribeToSymbol(
+ provider: string,
+ symbol: string,
+ channels: string[] = ['ticker', 'book', 'trade']
+): Promise<void> {
+ for (const channel of channels) {
+ await websocketBridge.subscribe(provider, symbol, channel);
+ }
+}
+
+/**
+ * Quick unsubscribe helper
+ */
+export async function unsubscribeFromSymbol(
+ provider: string,
+ symbol: string,
+ channels: string[] = ['ticker', 'book', 'trade']
+): Promise<void> {
+ for (const channel of channels) {
+ await websocketBridge.unsubscribe(provider, symbol, channel);
+ }
+}
+
+/**
+ * Get WebSocket manager instance (for backwards compatibility)
+ */
+export function getWebSocketManager() {
+ return websocketBridge;
+}
+
+/**
+ * Get available providers
+ */
+export function getAvailableProviders(): string[] {
+ return ['kraken', 'binance', 'coinbase']; // Add more as needed
+}
+
+/**
+ * Connection status enum (for backwards compatibility)
+ */
+export enum ConnectionStatus {
+ CONNECTED = 'connected',
+ DISCONNECTED = 'disconnected',
+ CONNECTING = 'connecting',
+ ERROR = 'error'
+}
diff --git a/fincept-terminal-desktop/statsmodels_api_scan.txt b/fincept-terminal-desktop/statsmodels_api_scan.txt
deleted file mode 100644
index 321f11ee5..000000000
--- a/fincept-terminal-desktop/statsmodels_api_scan.txt
+++ /dev/null
@@ -1,58 +0,0 @@
-=== STATSMODELS API (via statsmodels.api) ===
-
-Total items: 69
-
-Classes (41):
- BayesGaussMI
- BinomialBayesMixedGLM
- ConditionalLogit
- ConditionalMNLogit
- ConditionalPoisson
- Factor
- GEE
- GLM
- GLMGam
- GLS
- GLSAR
- GeneralizedPoisson
- HurdleCountModel
- Logit
- MANOVA
- MI
- MICE
- MICEData
- MNLogit
- MixedLM
- ... and 21 more
-
-Functions (10):
- add_constant
- categorical
- load
- load_pickle
- qqline
- qqplot
- qqplot_2samples
- show_versions
- test
- webdoc
-
-Modules (18):
- cov_struct
- datasets
- distributions
- duration
- emplike
- families
- formula
- gam
- genmod
- graphics
- iolib
- multivariate
- nonparametric
- regression
- robust
- stats
- tools
- tsa
diff --git a/fincept-terminal-desktop/statsmodels_modules_scan.txt b/fincept-terminal-desktop/statsmodels_modules_scan.txt
deleted file mode 100644
index 4010fa0b2..000000000
--- a/fincept-terminal-desktop/statsmodels_modules_scan.txt
+++ /dev/null
@@ -1,177 +0,0 @@
-============================================================
-MODULE: statsmodels.tsa
-============================================================
-Classes (22):
- AR
- ARDL
- ARIMA
- ArmaProcess
- AutoReg
- DynamicFactor
- DynamicFactorMQ
- ETSModel
- ExponentialSmoothing
- Holt
- MarkovAutoregression
- MarkovRegression
- SARIMAX
- STL
- STLForecast
- ... 7 more
-
-Functions (26):
- acf
- acovf
- add_lag
- add_trend
- adfuller
- ardl_select_order
- arma_generate_sample
- arma_order_select_ic
- bds
- breakvar_heteroskedasticity_test
- ccf
- ccovf
- coint
- detrend
- kpss
- ... 11 more
-
-============================================================
-MODULE: statsmodels.regression
-============================================================
-Classes (1):
- PytestTester
-
-Functions (2):
- test
- yule_walker
-
-============================================================
-MODULE: statsmodels.stats
-============================================================
-Classes (20):
- AnovaRM
- CompareMeans
- DescrStatsW
- Describe
- FTestAnovaPower
- FTestPower
- FactoredPSDMatrix
- GofChisquarePower
- Mediation
- NormalIndPower
- NullDistribution
- OaxacaBlinder
- RegressionFDR
- Runs
- SquareTable
- ... 5 more
-
-Functions (124):
- acorr_breusch_godfrey
- acorr_ljungbox
- acorr_lm
- anova_generic
- anova_lm
- anova_oneway
- binom_test
- binom_test_reject_interval
- binom_tost
- binom_tost_reject_interval
- breaks_cusumolsresid
- breaks_hansen
- chisquare_effectsize
- cochrans_q
- cohens_kappa
- ... 109 more
-
-============================================================
-MODULE: statsmodels.robust
-============================================================
-Classes (3):
- Huber
- HuberScale
- PytestTester
-
-Functions (3):
- hubers_scale
- mad
- test
-
-============================================================
-MODULE: statsmodels.genmod
-============================================================
-Classes (6):
- BinomialBayesMixedGLM
- GEE
- GLM
- NominalGEE
- OrdinalGEE
- PoissonBayesMixedGLM
-
-Functions (0):
-
-============================================================
-MODULE: statsmodels.multivariate
-============================================================
-Classes (5):
- CanCorr
- Factor
- FactorResults
- MANOVA
- PCA
-
-Functions (0):
-
-============================================================
-MODULE: statsmodels.nonparametric
-============================================================
-Classes (6):
- EstimatorSettings
- KDEMultivariate
- KDEMultivariateConditional
- KDEUnivariate
- KernelCensoredReg
- KernelReg
-
-Functions (3):
- cdf_kernel_asym
- lowess
- pdf_kernel_asym
-
-============================================================
-MODULE: statsmodels.duration
-============================================================
-Classes (3):
- CumIncidenceRight
- PHReg
- SurvfuncRight
-
-Functions (1):
- survdiff
-
-============================================================
-MODULE: statsmodels.gam
-============================================================
-Classes (4):
- BSplines
- CyclicCubicSplines
- GLMGam
- MultivariateGAMCVPath
-
-Functions (0):
-
-============================================================
-MODULE: statsmodels.emplike
-============================================================
-Classes (5):
- ANOVA
- DescStatMV
- DescStatUV
- ELOriginRegress
- emplikeAFT
-
-Functions (1):
- DescStat
-
diff --git a/fincept-terminal-desktop/statsmodels_stats_functions.txt b/fincept-terminal-desktop/statsmodels_stats_functions.txt
deleted file mode 100644
index 86849305f..000000000
--- a/fincept-terminal-desktop/statsmodels_stats_functions.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-statsmodels.stats functions (1 total):
-
-Statistical Tests:
- test
-