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.

auth update

tilakpatel220a6ee0b23bb5
diff --git a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
index e4df3feda..cb14b13bb 100644
--- a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
+++ b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
@@ -24,7 +24,7 @@ const AUTH_TIMEOUT_MS = 30000;
// State Machine
// ============================================================================
-type AuthStatus = 'idle' | 'loading' | 'guest_loading' | 'mfa_required' | 'success' | 'error';
+type AuthStatus = 'idle' | 'loading' | 'guest_loading' | 'mfa_required' | 'active_session' | 'success' | 'error';
interface State {
status: AuthStatus;
@@ -43,6 +43,7 @@ type Action =
| { type: 'START_LOGIN' }
| { type: 'START_GUEST' }
| { type: 'MFA_REQUIRED' }
+ | { type: 'ACTIVE_SESSION'; payload: string }
| { type: 'SUCCESS' }
| { type: 'ERROR'; payload: string }
| { type: 'CLEAR_ERROR' }
@@ -73,6 +74,8 @@ function reducer(state: State, action: Action): State {
return { ...state, status: 'guest_loading', error: null };
case 'MFA_REQUIRED':
return { ...state, status: 'mfa_required', error: null };
+ case 'ACTIVE_SESSION':
+ return { ...state, status: 'active_session', error: action.payload };
case 'SUCCESS':
return { ...state, status: 'success', error: null };
case 'ERROR':
@@ -174,6 +177,8 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
if (result.success) {
dispatch({ type: 'SUCCESS' });
+ } else if (result.active_session) {
+ dispatch({ type: 'ACTIVE_SESSION', payload: result.error || 'You are already logged in on another device.' });
} else if (result.mfa_required) {
dispatch({ type: 'MFA_REQUIRED' });
} else {
@@ -187,6 +192,37 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
}
}, [state.status, state.email, state.password, login, t, mapErrorMessage]);
+ const handleForceLogin = useCallback(async () => {
+ if (state.status === 'loading') return;
+
+ dispatch({ type: 'START_LOGIN' });
+
+ try {
+ const sanitizedEmail = sanitizeInput(state.email.trim().toLowerCase());
+
+ const result = await withTimeout(
+ login(sanitizedEmail, state.password, true),
+ AUTH_TIMEOUT_MS,
+ 'Login request timed out'
+ );
+
+ if (!mountedRef.current) return;
+
+ if (result.success) {
+ dispatch({ type: 'SUCCESS' });
+ } else if (result.mfa_required) {
+ dispatch({ type: 'MFA_REQUIRED' });
+ } else {
+ const errorMessage = mapErrorMessage(result.error || 'Force login failed.');
+ dispatch({ type: 'ERROR', payload: errorMessage });
+ }
+ } catch (err) {
+ if (!mountedRef.current) return;
+ const message = err instanceof Error ? err.message : t('login.errors.unexpectedError');
+ dispatch({ type: 'ERROR', payload: mapErrorMessage(message) });
+ }
+ }, [state.status, state.email, state.password, login, t, mapErrorMessage]);
+
const handleMfaVerify = useCallback(async (e: React.FormEvent) => {
e.preventDefault();
@@ -257,6 +293,38 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
}
}, [state.status, setupGuestAccess, t]);
+ // Active Session Conflict Screen
+ if (state.status === 'active_session') {
+ return (
+ <div className="bg-zinc-900/90 backdrop-blur-sm border border-zinc-700 rounded-lg p-6 w-full max-w-sm mx-4 shadow-2xl">
+ <div className="mb-4">
+ <CompactLanguageSelector />
+ </div>
+ <div className="text-center mb-4">
+ <h2 className="text-lg font-bold text-white">{t('login.activeSession', 'Active Session Detected')}</h2>
+ <p className="text-zinc-400 text-xs mt-1">
+ {state.error || t('login.activeSessionMessage', 'You are already logged in on another device. Would you like to log out the other session and continue here?')}
+ </p>
+ </div>
+
+ <div className="space-y-3">
+ <button
+ onClick={handleForceLogin}
+ className="w-full h-9 bg-amber-600 hover:bg-amber-700 text-white text-sm font-medium rounded transition-colors disabled:opacity-50"
+ >
+ {t('login.forceLogin', 'Log Out Other Session & Continue')}
+ </button>
+ <button
+ onClick={() => dispatch({ type: 'BACK_TO_LOGIN' })}
+ className="w-full h-9 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 text-sm rounded transition-colors border border-zinc-600"
+ >
+ {t('login.cancel', 'Cancel')}
+ </button>
+ </div>
+ </div>
+ );
+ }
+
// MFA Verification Screen
if (state.status === 'mfa_required' || (state.status === 'loading' && state.mfaCode)) {
return (
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodePalette.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodePalette.tsx
index 9a7b699d0..ede516241 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodePalette.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/components/NodePalette.tsx
@@ -12,16 +12,12 @@ import { BUILTIN_NODE_CONFIGS, CATEGORY_CONFIG } from '../constants';
import type { NodePaletteProps, PaletteNodeItem } from '../types';
// Non-functional nodes to hide from the palette.
-// These nodes have stub implementations (credentials not wired, binary pipeline missing,
-// trigger infrastructure absent, or call non-existent helpers).
-// The code is kept for future implementation — we just hide them from the UI.
-const HIDDEN_NODES = new Set([
- // Notifications — credential retrieval not implemented
- 'Discord', 'Email', 'Slack', 'SMS', 'Telegram', 'Webhook',
- // Files — no binary pipeline in the executor
- 'BinaryFile', 'Compress', 'ConvertToFile', 'FileOperations', 'SpreadsheetFile',
- // Control flow — calls non-existent ExecuteWorkflow helper
- 'ExecuteWorkflow',
+// Nodes that were previously hidden have been reviewed and most are functional:
+// - Notifications (Discord, Slack, Telegram, Webhook, SMS, Email): use direct fetch()/provider APIs
+// - Files (BinaryFile, Compress, ConvertToFile, FileOperations, SpreadsheetFile): use Tauri fs plugin
+// - ExecuteWorkflow: wired to workflowService + nodeExecutionManager
+const HIDDEN_NODES = new Set<string>([
+ // All previously hidden nodes have been verified as functional and un-hidden.
]);
const NodePalette: React.FC<NodePaletteProps> = ({
diff --git a/fincept-terminal-desktop/src/contexts/AuthContext.tsx b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
index c5bec5eb4..8fbb45571 100644
--- a/fincept-terminal-desktop/src/contexts/AuthContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
@@ -143,7 +143,7 @@ interface AuthContextType {
isFirstTimeUser: boolean;
availablePlans: SubscriptionPlan[];
isLoadingPlans: boolean;
- login: (email: string, password: string) => Promise<{ success: boolean; error?: string; mfa_required?: boolean }>;
+ login: (email: string, password: string, forceLogin?: boolean) => Promise<{ success: boolean; error?: string; mfa_required?: boolean; active_session?: boolean }>;
signup: (
username: string,
email: string,
@@ -539,9 +539,9 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
// Login function
- const login = async (email: string, password: string): Promise<{ success: boolean; error?: string; mfa_required?: boolean }> => {
+ const login = async (email: string, password: string, forceLogin?: boolean): Promise<{ success: boolean; error?: string; mfa_required?: boolean; active_session?: boolean }> => {
try {
- const result = await AuthApiService.login({ email, password }) as ApiResponse;
+ const result = await AuthApiService.login({ email, password, force_login: forceLogin }) as ApiResponse;
console.log('=== LOGIN RESPONSE DEBUG ===');
console.log('Full result:', JSON.stringify(result, null, 2));
@@ -553,6 +553,15 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
// But makeApiRequest wraps it again, so we need to check result.data.data
const apiData = (result.data as any)?.data || result.data;
+ // Check if there's an active session on another device
+ if (!result.success && apiData && apiData.active_session) {
+ return {
+ success: false,
+ active_session: true,
+ error: apiData.message || 'You are already logged in on another device. Use force login to continue.'
+ };
+ }
+
// Check if MFA is required
if (result.success && apiData && apiData.mfa_required) {
return {
@@ -633,7 +642,7 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
password,
phone: phone || null,
country: country || null,
- country_code: country_code || null,
+ country_code: country_code || '',
preferred_currency: 'USD'
}) as ApiResponse;
@@ -881,6 +890,15 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
setIsLoggingOut(true);
console.log('[AuthContext] Starting logout process...');
+ // Notify server of logout (best-effort, don't block on failure)
+ if (session?.api_key) {
+ try {
+ await AuthApiService.logout(session.api_key);
+ } catch (e) {
+ console.warn('[AuthContext] Server-side logout failed (non-blocking):', e);
+ }
+ }
+
// Clear session data first (async operations)
await clearSession();
diff --git a/fincept-terminal-desktop/src/services/auth/authApi.tsx b/fincept-terminal-desktop/src/services/auth/authApi.tsx
index 7f9dd5167..4ed56488a 100644
--- a/fincept-terminal-desktop/src/services/auth/authApi.tsx
+++ b/fincept-terminal-desktop/src/services/auth/authApi.tsx
@@ -26,6 +26,7 @@ interface ApiResponse<T = any> {
interface LoginRequest {
email: string;
password: string;
+ force_login?: boolean;
}
interface RegisterRequest {
@@ -34,7 +35,7 @@ interface RegisterRequest {
password: string;
phone?: string | null;
country?: string | null;
- country_code?: string | null;
+ country_code: string;
preferred_currency?: string | null;
}
@@ -244,6 +245,13 @@ export class AuthApiService {
}
}
+ // Validate API key
+ static async validateApiKey(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('GET', '/auth/validate', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
// Login user
static async login(request: LoginRequest): Promise<ApiResponse<LoginResponse>> {
return makeApiRequest<LoginResponse>('POST', '/user/login', request);
@@ -309,8 +317,21 @@ export class AuthApiService {
}
// Get user usage statistics
- static async getUserUsage(apiKey: string): Promise<ApiResponse<any>> {
- return makeApiRequest('GET', '/user/usage', undefined, {
+ static async getUserUsage(apiKey: string, options?: {
+ days?: number;
+ page?: number;
+ page_size?: number;
+ endpoint_filter?: string;
+ method_filter?: string;
+ }): Promise<ApiResponse<any>> {
+ const params = new URLSearchParams();
+ if (options?.days) params.append('days', String(options.days));
+ if (options?.page) params.append('page', String(options.page));
+ if (options?.page_size) params.append('page_size', String(options.page_size));
+ if (options?.endpoint_filter) params.append('endpoint_filter', options.endpoint_filter);
+ if (options?.method_filter) params.append('method_filter', options.method_filter);
+ const query = params.toString();
+ return makeApiRequest('GET', `/user/usage${query ? `?${query}` : ''}`, undefined, {
'X-API-Key': apiKey
});
}
@@ -336,6 +357,95 @@ export class AuthApiService {
});
}
+ // Logout user
+ static async logout(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('POST', '/user/logout', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Validate session (server-side session check)
+ static async validateSessionServer(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('POST', '/user/validate-session', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Get login history
+ static async getLoginHistory(apiKey: string, limit: number = 20, offset: number = 0): Promise<ApiResponse<any>> {
+ return makeApiRequest('GET', `/user/login-history?limit=${limit}&offset=${offset}`, undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Get notifications
+ static async getNotifications(apiKey: string, limit: number = 20, offset: number = 0, unreadOnly: boolean = false): Promise<ApiResponse<any>> {
+ return makeApiRequest('GET', `/user/notifications?limit=${limit}&offset=${offset}&unread_only=${unreadOnly}`, undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Mark notification as read
+ static async markNotificationRead(apiKey: string, notificationId: number): Promise<ApiResponse> {
+ return makeApiRequest('PUT', `/user/notifications/${notificationId}/read`, undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Mark all notifications as read
+ static async markAllNotificationsRead(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('PUT', '/user/notifications/read-all', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Delete notification
+ static async deleteNotification(apiKey: string, notificationId: number): Promise<ApiResponse> {
+ return makeApiRequest('DELETE', `/user/notifications/${notificationId}`, undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Get notification preferences
+ static async getNotificationPreferences(apiKey: string): Promise<ApiResponse<any>> {
+ return makeApiRequest('GET', '/user/notifications/preferences', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Update notification preferences
+ static async updateNotificationPreferences(apiKey: string, preferences: Record<string, any>): Promise<ApiResponse> {
+ return makeApiRequest('PUT', '/user/notifications/preferences', preferences, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Test Telegram notification
+ static async testTelegramNotification(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('POST', '/user/notifications/telegram/test', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Enable MFA
+ static async enableMFA(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('POST', '/user/mfa/enable', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Disable MFA
+ static async disableMFA(apiKey: string, password: string): Promise<ApiResponse> {
+ return makeApiRequest('POST', '/user/mfa/disable', { password }, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Verify MFA login
+ static async verifyMFA(email: string, otp: string): Promise<ApiResponse<LoginResponse>> {
+ return makeApiRequest<LoginResponse>('POST', '/user/verify-mfa', { email, otp });
+ }
+
// Delete user account
static async deleteAccount(apiKey: string, password: string): Promise<ApiResponse> {
return makeApiRequest('DELETE', '/user/account', { password }, {
diff --git a/fincept-terminal-desktop/src/services/auth/userApi.tsx b/fincept-terminal-desktop/src/services/auth/userApi.tsx
index 4f9a86e4e..bd95d89a4 100644
--- a/fincept-terminal-desktop/src/services/auth/userApi.tsx
+++ b/fincept-terminal-desktop/src/services/auth/userApi.tsx
@@ -91,8 +91,21 @@ export class UserApiService {
return makeApiRequest('/user/regenerate-api-key', 'POST', apiKey);
}
- static async getUserUsage(apiKey: string): Promise<ApiResponse> {
- return makeApiRequest('/user/usage', 'GET', apiKey);
+ static async getUserUsage(apiKey: string, options?: {
+ days?: number;
+ page?: number;
+ page_size?: number;
+ endpoint_filter?: string;
+ method_filter?: string;
+ }): Promise<ApiResponse> {
+ const params = new URLSearchParams();
+ if (options?.days) params.append('days', String(options.days));
+ if (options?.page) params.append('page', String(options.page));
+ if (options?.page_size) params.append('page_size', String(options.page_size));
+ if (options?.endpoint_filter) params.append('endpoint_filter', options.endpoint_filter);
+ if (options?.method_filter) params.append('method_filter', options.method_filter);
+ const query = params.toString();
+ return makeApiRequest(`/user/usage${query ? `?${query}` : ''}`, 'GET', apiKey);
}
static async getUserCredits(apiKey: string): Promise<ApiResponse> {
@@ -103,6 +116,58 @@ export class UserApiService {
return makeApiRequest('/user/account', 'DELETE', apiKey, confirmationData);
}
+ // ========================
+ // SESSION MANAGEMENT
+ // ========================
+
+ static async logout(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('/user/logout', 'POST', apiKey);
+ }
+
+ static async validateSession(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('/user/validate-session', 'POST', apiKey);
+ }
+
+ // ========================
+ // LOGIN HISTORY
+ // ========================
+
+ static async getLoginHistory(apiKey: string, limit: number = 20, offset: number = 0): Promise<ApiResponse> {
+ return makeApiRequest(`/user/login-history?limit=${limit}&offset=${offset}`, 'GET', apiKey);
+ }
+
+ // ========================
+ // NOTIFICATIONS
+ // ========================
+
+ static async getNotifications(apiKey: string, limit: number = 20, offset: number = 0, unreadOnly: boolean = false): Promise<ApiResponse> {
+ return makeApiRequest(`/user/notifications?limit=${limit}&offset=${offset}&unread_only=${unreadOnly}`, 'GET', apiKey);
+ }
+
+ static async markNotificationRead(apiKey: string, notificationId: number): Promise<ApiResponse> {
+ return makeApiRequest(`/user/notifications/${notificationId}/read`, 'PUT', apiKey);
+ }
+
+ static async markAllNotificationsRead(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('/user/notifications/read-all', 'PUT', apiKey);
+ }
+
+ static async deleteNotification(apiKey: string, notificationId: number): Promise<ApiResponse> {
+ return makeApiRequest(`/user/notifications/${notificationId}`, 'DELETE', apiKey);
+ }
+
+ static async getNotificationPreferences(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('/user/notifications/preferences', 'GET', apiKey);
+ }
+
+ static async updateNotificationPreferences(apiKey: string, preferences: Record<string, any>): Promise<ApiResponse> {
+ return makeApiRequest('/user/notifications/preferences', 'PUT', apiKey, preferences);
+ }
+
+ static async testTelegramNotification(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('/user/notifications/telegram/test', 'POST', apiKey);
+ }
+
// ========================
// SUBSCRIPTIONS & DATABASES
// ========================
@@ -256,4 +321,35 @@ export class UserApiService {
};
}
}
+
+ // ========================
+ // ADMIN USER MANAGEMENT
+ // ========================
+
+ static async adminListUsers(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('/user/admin/users', 'GET', apiKey);
+ }
+
+ static async adminGetUserDetails(apiKey: string, userId: number): Promise<ApiResponse> {
+ return makeApiRequest(`/user/admin/user/${userId}`, 'GET', apiKey);
+ }
+
+ static async adminManageUserCredits(apiKey: string, userId: number, creditData: {
+ amount: number;
+ reason?: string;
+ }): Promise<ApiResponse> {
+ return makeApiRequest(`/user/admin/user/${userId}/credits`, 'POST', apiKey, creditData);
+ }
+
+ static async adminGetStats(apiKey: string): Promise<ApiResponse> {
+ return makeApiRequest('/user/admin/stats', 'GET', apiKey);
+ }
+
+ static async adminBroadcastNotification(apiKey: string, notification: {
+ title: string;
+ message: string;
+ type?: string;
+ }): Promise<ApiResponse> {
+ return makeApiRequest('/user/admin/notifications/broadcast', 'POST', apiKey, notification);
+ }
}
diff --git a/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts b/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts
index 4ca9c26af..f3d4d0141 100644
--- a/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts
+++ b/fincept-terminal-desktop/src/services/data-sources/chatModeApi.ts
@@ -539,6 +539,42 @@ class ChatModeApiService {
}
}
+ /**
+ * Optimize a prompt using AI
+ */
+ async optimizePrompt(prompt: string): Promise<ChatModeResponse> {
+ try {
+ await this.initialize();
+
+ const response = await fetch(`${this.baseUrl}/chat/optimize-prompt`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(this.apiKey && { 'X-API-Key': this.apiKey })
+ },
+ body: JSON.stringify({ prompt })
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to optimize prompt: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+
+ throw new Error(result.message || 'Unknown error');
+ } catch (error) {
+ console.error('Optimize prompt error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to optimize prompt'
+ };
+ }
+ }
+
/**
* Start session from template
*/
diff --git a/fincept-terminal-desktop/src/services/markets/marketApi.ts b/fincept-terminal-desktop/src/services/markets/marketApi.ts
new file mode 100644
index 000000000..8fd6e201c
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/markets/marketApi.ts
@@ -0,0 +1,137 @@
+// Market Data API Service - Direct HTTP calls to Fincept API
+// Endpoints: /market/*
+// Complements marketDataService.ts (which uses Tauri invoke/Rust bridge)
+
+import { fetch as tauriFetch } from '@tauri-apps/plugin-http';
+
+const API_CONFIG = {
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
+};
+
+const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;
+const safeFetch = import.meta.env.DEV ? window.fetch.bind(window) : tauriFetch;
+
+interface ApiResponse<T = any> {
+ success: boolean;
+ data?: T;
+ error?: string;
+ status_code: number;
+}
+
+async function makeApiRequest<T = any>(
+ endpoint: string,
+ apiKey?: string
+): Promise<ApiResponse<T>> {
+ try {
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ };
+ if (apiKey) headers['X-API-Key'] = apiKey;
+
+ const response = await safeFetch(getApiEndpoint(endpoint), { method: 'GET', headers });
+ const data = await response.json();
+
+ return {
+ success: response.ok,
+ data,
+ error: response.ok ? undefined : data.detail || data.error || 'Request failed',
+ status_code: response.status,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Network error',
+ status_code: 500,
+ };
+ }
+}
+
+export class MarketApiService {
+ // Search tickers
+ static async searchTickers(
+ q: string,
+ apiKey?: string,
+ options?: { limit?: number; type?: string; exchange?: string; country?: string }
+ ): Promise<ApiResponse> {
+ const params = new URLSearchParams({ q });
+ if (options?.limit) params.append('limit', String(options.limit));
+ if (options?.type) params.append('type', options.type);
+ if (options?.exchange) params.append('exchange', options.exchange);
+ if (options?.country) params.append('country', options.country);
+ return makeApiRequest(`/market/search?${params}`, apiKey);
+ }
+
+ // Get ticker price
+ static async getTickerPrice(symbol: string, apiKey?: string, exchange?: string): Promise<ApiResponse> {
+ const params = exchange ? `?exchange=${encodeURIComponent(exchange)}` : '';
+ return makeApiRequest(`/market/price/${encodeURIComponent(symbol)}${params}`, apiKey);
+ }
+
+ // Get ticker info
+ static async getTickerInfo(symbol: string, apiKey?: string, exchange?: string): Promise<ApiResponse> {
+ const params = exchange ? `?exchange=${encodeURIComponent(exchange)}` : '';
+ return makeApiRequest(`/market/info/${encodeURIComponent(symbol)}${params}`, apiKey);
+ }
+
+ // Get ticker snapshot
+ static async getTickerSnapshot(symbol: string, apiKey?: string, exchange?: string): Promise<ApiResponse> {
+ const params = exchange ? `?exchange=${encodeURIComponent(exchange)}` : '';
+ return makeApiRequest(`/market/snapshot/${encodeURIComponent(symbol)}${params}`, apiKey);
+ }
+
+ // Get ticker history
+ static async getTickerHistory(
+ symbol: string,
+ apiKey?: string,
+ options?: { interval?: string; period?: string; start_date?: string; end_date?: string; date?: string; exchange?: string }
+ ): Promise<ApiResponse> {
+ const params = new URLSearchParams();
+ if (options?.interval) params.append('interval', options.interval);
+ if (options?.period) params.append('period', options.period);
+ if (options?.start_date) params.append('start_date', options.start_date);
+ if (options?.end_date) params.append('end_date', options.end_date);
+ if (options?.date) params.append('date', options.date);
+ if (options?.exchange) params.append('exchange', options.exchange);
+ const query = params.toString();
+ return makeApiRequest(`/market/history/${encodeURIComponent(symbol)}${query ? `?${query}` : ''}`, apiKey);
+ }
+
+ // Get ticker financials
+ static async getTickerFinancials(
+ symbol: string,
+ apiKey?: string,
+ options?: { quarterly?: boolean; exchange?: string }
+ ): Promise<ApiResponse> {
+ const params = new URLSearchParams();
+ if (options?.quarterly !== undefined) params.append('quarterly', String(options.quarterly));
+ if (options?.exchange) params.append('exchange', options.exchange);
+ const query = params.toString();
+ return makeApiRequest(`/market/financials/${encodeURIComponent(symbol)}${query ? `?${query}` : ''}`, apiKey);
+ }
+
+ // Get ticker news
+ static async getTickerNews(symbol: string, apiKey?: string, maxResults?: number): Promise<ApiResponse> {
+ const params = maxResults ? `?max_results=${maxResults}` : '';
+ return makeApiRequest(`/market/news/${encodeURIComponent(symbol)}${params}`, apiKey);
+ }
+
+ // Batch prices for multiple symbols
+ static async getBatchPrices(symbols: string[], apiKey?: string, exchange?: string): Promise<ApiResponse> {
+ const params = new URLSearchParams({ symbols: symbols.join(',') });
+ if (exchange) params.append('exchange', exchange);
+ return makeApiRequest(`/market/batch/prices?${params}`, apiKey);
+ }
+
+ // Batch history for multiple symbols
+ static async getBatchHistory(
+ symbols: string[],
+ apiKey?: string,
+ options?: { period?: string; interval?: string; exchange?: string }
+ ): Promise<ApiResponse> {
+ const params = new URLSearchParams({ symbols: symbols.join(',') });
+ if (options?.period) params.append('period', options.period);
+ if (options?.interval) params.append('interval', options.interval);
+ if (options?.exchange) params.append('exchange', options.exchange);
+ return makeApiRequest(`/market/batch/history?${params}`, apiKey);
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/files/SpreadsheetFileNode.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/files/SpreadsheetFileNode.ts
index 935ee8956..ebe6da380 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/files/SpreadsheetFileNode.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/files/SpreadsheetFileNode.ts
@@ -7,6 +7,66 @@ import {
NodePropertyType,
} from '../../types';
+async function readFileContent(path: string): Promise<string> {
+ try {
+ const { readTextFile } = await import('@tauri-apps/plugin-fs');
+ return await readTextFile(path);
+ } catch (e) {
+ throw new Error(`Failed to read file: ${e}`);
+ }
+}
+
+async function writeFileContent(path: string, content: string): Promise<void> {
+ try {
+ const { writeTextFile } = await import('@tauri-apps/plugin-fs');
+ await writeTextFile(path, content);
+ } catch (e) {
+ throw new Error(`Failed to write file: ${e}`);
+ }
+}
+
+function parseCSV(content: string, delimiter: string, hasHeaders: boolean): any[] {
+ const lines = content.trim().split('\n');
+ if (lines.length === 0) return [];
+
+ const headers = hasHeaders ? lines[0].split(delimiter).map(h => h.trim()) : null;
+ const dataLines = hasHeaders ? lines.slice(1) : lines;
+
+ return dataLines.map(line => {
+ const values = line.split(delimiter).map(v => v.trim());
+ if (headers) {
+ const obj: any = {};
+ headers.forEach((header, i) => {
+ obj[header] = values[i] || '';
+ });
+ return obj;
+ } else {
+ return { data: values };
+ }
+ });
+}
+
+function generateCSV(data: any[], delimiter: string, includeHeaders: boolean): string {
+ if (data.length === 0) return '';
+
+ const headers = Object.keys(data[0]);
+ const rows: string[] = [];
+
+ if (includeHeaders) {
+ rows.push(headers.join(delimiter));
+ }
+
+ data.forEach(item => {
+ const values = headers.map(h => {
+ const val = item[h];
+ return val !== undefined && val !== null ? String(val) : '';
+ });
+ rows.push(values.join(delimiter));
+ });
+
+ return rows.join('\n');
+}
+
export class SpreadsheetFileNode implements INodeType {
description: INodeTypeDescription = {
displayName: 'Excel/CSV File',
@@ -90,22 +150,20 @@ export class SpreadsheetFileNode implements INodeType {
try {
if (operation === 'read') {
- // Read file
- const content = await this.readFile(filePath);
+ const content = await readFileContent(filePath);
if (fileFormat === 'csv') {
- const rows = this.parseCSV(content, delimiter, hasHeaders);
- rows.forEach((row, index) => {
+ const rows = parseCSV(content, delimiter, hasHeaders);
+ rows.forEach((row) => {
returnData.push({
json: row,
pairedItem: 0,
});
});
} else {
- // JSON
const data = JSON.parse(content);
const array = Array.isArray(data) ? data : [data];
- array.forEach((item, index) => {
+ array.forEach((item) => {
returnData.push({
json: item,
pairedItem: 0,
@@ -115,17 +173,15 @@ export class SpreadsheetFileNode implements INodeType {
console.log(`[SpreadsheetFileNode] Read ${returnData.length} rows from ${filePath}`);
} else {
- // Write file
let content = '';
if (fileFormat === 'csv') {
- content = this.generateCSV(items.map(i => i.json), delimiter, includeHeaders);
+ content = generateCSV(items.map(i => i.json), delimiter, includeHeaders);
} else {
- // JSON
content = JSON.stringify(items.map(i => i.json), null, 2);
}
- await this.writeFile(filePath, content);
+ await writeFileContent(filePath, content);
console.log(`[SpreadsheetFileNode] Wrote ${items.length} rows to ${filePath}`);
returnData.push({
@@ -154,66 +210,4 @@ export class SpreadsheetFileNode implements INodeType {
return [returnData];
}
-
- private parseCSV(content: string, delimiter: string, hasHeaders: boolean): any[] {
- const lines = content.trim().split('\n');
- if (lines.length === 0) return [];
-
- const headers = hasHeaders ? lines[0].split(delimiter).map(h => h.trim()) : null;
- const dataLines = hasHeaders ? lines.slice(1) : lines;
-
- return dataLines.map(line => {
- const values = line.split(delimiter).map(v => v.trim());
- if (headers) {
- const obj: any = {};
- headers.forEach((header, i) => {
- obj[header] = values[i] || '';
- });
- return obj;
- } else {
- return { data: values };
- }
- });
- }
-
- private generateCSV(data: any[], delimiter: string, includeHeaders: boolean): string {
- if (data.length === 0) return '';
-
- const headers = Object.keys(data[0]);
- const rows: string[] = [];
-
- if (includeHeaders) {
- rows.push(headers.join(delimiter));
- }
-
- data.forEach(item => {
- const values = headers.map(h => {
- const val = item[h];
- return val !== undefined && val !== null ? String(val) : '';
- });
- rows.push(values.join(delimiter));
- });
-
- return rows.join('\n');
- }
-
- private async readFile(path: string): Promise<string> {
- // Use Tauri fs plugin
- try {
- const { readTextFile } = await import('@tauri-apps/plugin-fs');
- return await readTextFile(path);
- } catch (e) {
- throw new Error(`Failed to read file: ${e}`);
- }
- }
-
- private async writeFile(path: string, content: string): Promise<void> {
- // Use Tauri fs plugin
- try {
- const { writeTextFile } = await import('@tauri-apps/plugin-fs');
- await writeTextFile(path, content);
- } catch (e) {
- throw new Error(`Failed to write file: ${e}`);
- }
- }
}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetFundamentalsNode.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetFundamentalsNode.ts
index efc5d206b..54bad0a92 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetFundamentalsNode.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetFundamentalsNode.ts
@@ -180,17 +180,75 @@ export class GetFundamentalsNode implements INodeType {
}
}
+ /**
+ * Compare company metrics against sector peers using real data.
+ * Fetches fundamentals for well-known sector peers and computes
+ * the company's percentile rank for key ratios.
+ */
private static async getIndustryComparison(symbol: string, data: any): Promise<Record<string, any>> {
- // Mock industry comparison - would call actual API in production
+ // Select a set of sector peers to build a comparison baseline
+ const sectorPeers: Record<string, string[]> = {
+ 'Technology': ['AAPL', 'MSFT', 'GOOGL', 'META', 'NVDA', 'CRM', 'ADBE', 'INTC', 'ORCL'],
+ 'Healthcare': ['JNJ', 'UNH', 'PFE', 'ABBV', 'MRK', 'TMO', 'ABT', 'LLY'],
+ 'Financial Services': ['JPM', 'BAC', 'WFC', 'GS', 'MS', 'C', 'BLK', 'SCHW'],
+ 'Consumer Cyclical': ['AMZN', 'TSLA', 'HD', 'NKE', 'MCD', 'SBUX', 'TGT', 'LOW'],
+ 'Energy': ['XOM', 'CVX', 'COP', 'SLB', 'EOG', 'OXY', 'PSX', 'VLO'],
+ };
+
+ const sector = data.sector || 'Technology';
+ const peers = (sectorPeers[sector] || sectorPeers['Technology']).filter(s => s !== symbol.toUpperCase());
+
+ // Fetch peer fundamentals in parallel (best-effort)
+ const peerResults = await Promise.allSettled(
+ peers.slice(0, 6).map(p => MarketDataBridge.getFundamentals(p))
+ );
+
+ const peerData = peerResults
+ .filter((r): r is PromiseFulfilledResult<any> => r.status === 'fulfilled')
+ .map(r => r.value);
+
+ // Helper: compute percentile rank of value in an array
+ const percentile = (value: number | undefined, arr: (number | undefined)[]): number | null => {
+ if (value == null) return null;
+ const valid = arr.filter((v): v is number => v != null);
+ if (valid.length === 0) return null;
+ const below = valid.filter(v => v < value).length;
+ return Math.round((below / valid.length) * 100);
+ };
+
+ const peerPEs = peerData.map(p => p.peRatio);
+ const peerDivYields = peerData.map(p => p.dividendYield);
+ const peerBetas = peerData.map(p => p.beta);
+
+ const avg = (arr: (number | undefined)[]): number | null => {
+ const valid = arr.filter((v): v is number => v != null);
+ return valid.length > 0 ? valid.reduce((a, b) => a + b, 0) / valid.length : null;
+ };
+
return {
- industry: data.industry || 'Technology',
- sector: data.sector || 'Technology',
+ industry: data.industry || 'Unknown',
+ sector,
+ peerCount: peerData.length,
+ peers: peerData.map(p => p.symbol),
metrics: {
- peRatio: { company: data.peRatio || 25, industry: 22.5, percentile: 65 },
- pbRatio: { company: data.pbRatio || 8, industry: 5.2, percentile: 78 },
- roe: { company: data.roe || 0.35, industry: 0.18, percentile: 85 },
- debtToEquity: { company: data.debtToEquity || 1.2, industry: 0.8, percentile: 40 },
- profitMargin: { company: data.profitMargin || 0.25, industry: 0.15, percentile: 80 },
+ peRatio: {
+ company: data.peRatio ?? null,
+ sectorAvg: avg(peerPEs),
+ percentile: percentile(data.peRatio, peerPEs),
+ },
+ dividendYield: {
+ company: data.dividendYield ?? null,
+ sectorAvg: avg(peerDivYields),
+ percentile: percentile(data.dividendYield, peerDivYields),
+ },
+ beta: {
+ company: data.beta ?? null,
+ sectorAvg: avg(peerBetas),
+ percentile: percentile(data.beta, peerBetas),
+ },
+ marketCap: {
+ company: data.marketCap ?? null,
+ },
},
};
}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetTickerStatsNode.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetTickerStatsNode.ts
index dc14129eb..88b46292b 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetTickerStatsNode.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/marketData/GetTickerStatsNode.ts
@@ -190,53 +190,107 @@ export class GetTickerStatsNode implements INodeType {
const periods = this.getNodeParameter('performancePeriods', 0) as string[];
result.performance = {};
for (const period of periods) {
- (result.performance as Record<string, any>)[period] = GetTickerStatsNode.calculatePerformance(stats, period);
+ (result.performance as Record<string, any>)[period] = await GetTickerStatsNode.calculatePerformance(stats, period, symbol);
}
break;
}
- case 'ath':
- result.allTimeHigh = null;
- result.allTimeLow = null;
- result.athDate = null;
- result.atlDate = null;
- result.fromAth = null;
- result.fromAtl = null;
+ case 'ath': {
+ // Use max available history (5y) for ATH/ATL
+ try {
+ const history = await MarketDataBridge.getHistoricalData({ symbol, period: '5y' });
+ if (history.length > 0) {
+ let athVal = -Infinity, atlVal = Infinity, athDate = '', atlDate = '';
+ for (const bar of history) {
+ if (bar.high > athVal) { athVal = bar.high; athDate = bar.timestamp; }
+ if (bar.low < atlVal) { atlVal = bar.low; atlDate = bar.timestamp; }
+ }
+ result.allTimeHigh = athVal;
+ result.allTimeLow = atlVal;
+ result.athDate = athDate;
+ result.atlDate = atlDate;
+ result.fromAth = stats.lastPrice ? parseFloat(((stats.lastPrice - athVal) / athVal * 100).toFixed(2)) + '%' : null;
+ result.fromAtl = stats.lastPrice ? parseFloat(((stats.lastPrice - atlVal) / atlVal * 100).toFixed(2)) + '%' : null;
+ }
+ } catch {
+ result.allTimeHigh = null;
+ result.allTimeLow = null;
+ result.note = 'Historical data unavailable';
+ }
break;
+ }
- case '52week':
- result.week52 = {
- high: null,
- low: null,
- range: null,
- percentFromHigh: null,
- percentFromLow: null,
- };
+ case '52week': {
+ try {
+ const history = await MarketDataBridge.getHistoricalData({ symbol, period: '1y' });
+ if (history.length > 0) {
+ const high52 = Math.max(...history.map(b => b.high));
+ const low52 = Math.min(...history.map(b => b.low));
+ result.week52 = {
+ high: high52,
+ low: low52,
+ range: parseFloat((high52 - low52).toFixed(2)),
+ percentFromHigh: stats.lastPrice ? parseFloat(((stats.lastPrice - high52) / high52 * 100).toFixed(2)) + '%' : null,
+ percentFromLow: stats.lastPrice ? parseFloat(((stats.lastPrice - low52) / low52 * 100).toFixed(2)) + '%' : null,
+ };
+ }
+ } catch {
+ result.week52 = { high: null, low: null, note: 'Historical data unavailable' };
+ }
break;
+ }
+
+ case 'volatility': {
+ // Compute real volatility from historical daily returns
+ let dailyVol = GetTickerStatsNode.estimateVolatility(stats, 'daily');
+ try {
+ const history = await MarketDataBridge.getHistoricalData({ symbol, period: '3mo' });
+ if (history.length >= 5) {
+ const returns: number[] = [];
+ for (let i = 1; i < history.length; i++) {
+ if (history[i - 1].close > 0) {
+ returns.push((history[i].close - history[i - 1].close) / history[i - 1].close);
+ }
+ }
+ if (returns.length > 1) {
+ const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
+ const variance = returns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / (returns.length - 1);
+ dailyVol = parseFloat((Math.sqrt(variance) * 100).toFixed(2));
+ }
+ }
+ } catch { /* use estimate */ }
- case 'volatility':
result.volatility = {
- daily: GetTickerStatsNode.estimateVolatility(stats, 'daily'),
- weekly: GetTickerStatsNode.estimateVolatility(stats, 'weekly'),
- monthly: GetTickerStatsNode.estimateVolatility(stats, 'monthly'),
- annual: GetTickerStatsNode.estimateVolatility(stats, 'annual'),
- atr: null,
- atrPercent: null,
+ daily: dailyVol,
+ weekly: parseFloat((dailyVol * Math.sqrt(5)).toFixed(2)),
+ monthly: parseFloat((dailyVol * Math.sqrt(21)).toFixed(2)),
+ annual: parseFloat((dailyVol * Math.sqrt(252)).toFixed(2)),
};
break;
+ }
+
+ case 'volume': {
+ let avgVol: number | null = null;
+ try {
+ const history = await MarketDataBridge.getHistoricalData({ symbol, period: '1mo' });
+ if (history.length > 0) {
+ avgVol = Math.round(history.reduce((sum, b) => sum + b.volume, 0) / history.length);
+ }
+ } catch { /* leave null */ }
- case 'volume':
+ const currentVol = stats.volume24h || 0;
result.volumeProfile = {
- current: stats.volume24h,
- average: null,
- ratio: null,
- dollarVolume: stats.lastPrice && stats.volume24h ? stats.lastPrice * stats.volume24h : null,
- avgDollarVolume: null,
+ current: currentVol,
+ average: avgVol,
+ ratio: avgVol ? parseFloat((currentVol / avgVol).toFixed(2)) : null,
+ dollarVolume: stats.lastPrice && currentVol ? parseFloat((stats.lastPrice * currentVol).toFixed(0)) : null,
+ avgDollarVolume: stats.lastPrice && avgVol ? parseFloat((stats.lastPrice * avgVol).toFixed(0)) : null,
};
break;
+ }
case 'all':
- default:
+ default: {
result.stats24h = {
lastPrice: stats.lastPrice,
high: stats.highPrice24h,
@@ -245,16 +299,31 @@ export class GetTickerStatsNode implements INodeType {
change: stats.change24h,
changePercent: stats.changePercent24h,
};
- result.week52 = {
- high: null,
- low: null,
- };
- result.averages = {
- volume: null,
- price50: null,
- price200: null,
- };
+
+ // Fetch 52-week range and averages from real historical data
+ try {
+ const history = await MarketDataBridge.getHistoricalData({ symbol, period: '1y' });
+ if (history.length > 0) {
+ result.week52 = {
+ high: Math.max(...history.map(b => b.high)),
+ low: Math.min(...history.map(b => b.low)),
+ };
+ const avgVol = Math.round(history.reduce((s, b) => s + b.volume, 0) / history.length);
+ const closes = history.map(b => b.close);
+ const sma50 = closes.length >= 50
+ ? parseFloat((closes.slice(-50).reduce((a, b) => a + b, 0) / 50).toFixed(2))
+ : null;
+ const sma200 = closes.length >= 200
+ ? parseFloat((closes.slice(-200).reduce((a, b) => a + b, 0) / 200).toFixed(2))
+ : null;
+ result.averages = { volume: avgVol, price50: sma50, price200: sma200 };
+ }
+ } catch {
+ result.week52 = { high: null, low: null };
+ result.averages = { volume: null, price50: null, price200: null };
+ }
break;
+ }
}
// Add technical levels if requested
@@ -262,11 +331,47 @@ export class GetTickerStatsNode implements INodeType {
result.technicalLevels = GetTickerStatsNode.calculateTechnicalLevels(stats);
}
- // Add beta if requested
+ // Calculate real beta from historical data
if (includeBeta) {
const benchmark = this.getNodeParameter('benchmark', 0) as string;
- result.beta = 1.0;
result.benchmark = benchmark;
+ try {
+ const [symHistory, benchHistory] = await Promise.all([
+ MarketDataBridge.getHistoricalData({ symbol, period: '1y' }),
+ MarketDataBridge.getHistoricalData({ symbol: benchmark, period: '1y' }),
+ ]);
+
+ if (symHistory.length >= 20 && benchHistory.length >= 20) {
+ // Align by date (use shorter length)
+ const len = Math.min(symHistory.length, benchHistory.length);
+ const symReturns: number[] = [];
+ const benchReturns: number[] = [];
+ for (let i = 1; i < len; i++) {
+ if (symHistory[i - 1].close > 0 && benchHistory[i - 1].close > 0) {
+ symReturns.push((symHistory[i].close - symHistory[i - 1].close) / symHistory[i - 1].close);
+ benchReturns.push((benchHistory[i].close - benchHistory[i - 1].close) / benchHistory[i - 1].close);
+ }
+ }
+ if (symReturns.length > 5) {
+ const meanB = benchReturns.reduce((a, b) => a + b, 0) / benchReturns.length;
+ const meanS = symReturns.reduce((a, b) => a + b, 0) / symReturns.length;
+ let cov = 0, varB = 0;
+ for (let i = 0; i < symReturns.length; i++) {
+ cov += (symReturns[i] - meanS) * (benchReturns[i] - meanB);
+ varB += Math.pow(benchReturns[i] - meanB, 2);
+ }
+ result.beta = varB > 0 ? parseFloat((cov / varB).toFixed(3)) : 1.0;
+ } else {
+ result.beta = null;
+ }
+ } else {
+ result.beta = null;
+ result.betaNote = 'Insufficient historical data';
+ }
+ } catch {
+ result.beta = null;
+ result.betaNote = 'Failed to calculate beta';
+ }
}
results.push({ json: result });
@@ -284,23 +389,49 @@ export class GetTickerStatsNode implements INodeType {
return [results];
}
- private static calculatePerformance(stats: any, period: string): Record<string, any> {
- // Mock performance calculation - would use historical data in production
- const mockReturns: Record<string, number> = {
- '1d': -0.5,
- '1w': 2.3,
- '1m': 5.1,
- '3m': 12.4,
- '6m': 18.7,
- 'ytd': 22.1,
- '1y': 35.2,
- '3y': 89.5,
- '5y': 156.3,
+ /**
+ * Calculate real performance by fetching historical data from MarketDataBridge.
+ * Falls back to the 24h stats if historical fetch fails.
+ */
+ private static async calculatePerformance(stats: any, period: string, symbol: string): Promise<Record<string, any>> {
+ // Map UI period codes to MarketDataBridge period strings
+ const periodMap: Record<string, string> = {
+ '1d': '1d', '1w': '5d', '1m': '1mo', '3m': '3mo',
+ '6m': '6mo', 'ytd': '6mo', '1y': '1y', '3y': '2y', '5y': '5y',
};
+ const bridgePeriod = periodMap[period] || '1mo';
+
+ try {
+ const history = await MarketDataBridge.getHistoricalData({
+ symbol,
+ period: bridgePeriod,
+ });
+
+ if (history.length >= 2) {
+ const startPrice = history[0].close;
+ const endPrice = history[history.length - 1].close;
+ const returnPct = ((endPrice - startPrice) / startPrice) * 100;
+
+ return {
+ startPrice: parseFloat(startPrice.toFixed(2)),
+ endPrice: parseFloat(endPrice.toFixed(2)),
+ return: parseFloat((endPrice - startPrice).toFixed(2)),
+ returnPercent: parseFloat(returnPct.toFixed(2)) + '%',
+ dataPoints: history.length,
+ period,
+ };
+ }
+ } catch {
+ // Fall through to fallback
+ }
+
+ // Fallback: use 24h change from stats
return {
- return: mockReturns[period] || 0,
- returnPercent: (mockReturns[period] || 0) + '%',
+ return: stats.change24h || 0,
+ returnPercent: (stats.changePercent24h || 0) + '%',
+ period,
+ note: 'Fallback to 24h data',
};
}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/GetHoldingsNode.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/GetHoldingsNode.ts
index 58a868671..43bff9d06 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/GetHoldingsNode.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/GetHoldingsNode.ts
@@ -12,6 +12,7 @@ import {
NodePropertyType,
} from '../../types';
import { TradingBridge } from '../../adapters/TradingBridge';
+import { MarketDataBridge } from '../../adapters/MarketDataBridge';
export class GetHoldingsNode implements INodeType {
description: INodeTypeDescription = {
@@ -133,31 +134,38 @@ export class GetHoldingsNode implements INodeType {
}
}
- // Add mock sector data if requested
- if (includeSector) {
- const sectorMap: Record<string, { sector: string; industry: string }> = {
- AAPL: { sector: 'Technology', industry: 'Consumer Electronics' },
- MSFT: { sector: 'Technology', industry: 'Software' },
- GOOGL: { sector: 'Technology', industry: 'Internet Content' },
- AMZN: { sector: 'Consumer Cyclical', industry: 'E-Commerce' },
- TSLA: { sector: 'Consumer Cyclical', industry: 'Auto Manufacturers' },
- JPM: { sector: 'Financial Services', industry: 'Banks' },
- JNJ: { sector: 'Healthcare', industry: 'Drug Manufacturers' },
- };
+ // Fetch real sector and dividend data from MarketDataBridge if requested
+ if (includeSector || includeDividends) {
+ const fundamentalsResults = await Promise.allSettled(
+ holdings.map(h => MarketDataBridge.getFundamentals(h.symbol))
+ );
- for (const holding of holdings) {
- const sectorInfo = sectorMap[holding.symbol] || { sector: 'Unknown', industry: 'Unknown' };
- (holding as any).sector = sectorInfo.sector;
- (holding as any).industry = sectorInfo.industry;
- }
- }
-
- // Add mock dividend data if requested
- if (includeDividends) {
- for (const holding of holdings) {
- (holding as any).annualDividend = ((holding.currentPrice || holding.averagePrice) * 0.02).toFixed(2); // Mock 2% yield
- (holding as any).dividendYield = '2.00%';
- (holding as any).exDividendDate = null;
+ for (let i = 0; i < holdings.length; i++) {
+ const result = fundamentalsResults[i];
+ if (result.status === 'fulfilled') {
+ const data = result.value;
+ if (includeSector) {
+ (holdings[i] as any).sector = data.sector || 'Unknown';
+ (holdings[i] as any).industry = data.industry || 'Unknown';
+ }
+ if (includeDividends) {
+ (holdings[i] as any).dividendYield = data.dividendYield != null
+ ? (data.dividendYield * 100).toFixed(2) + '%'
+ : 'N/A';
+ (holdings[i] as any).annualDividend = data.dividendYield != null
+ ? ((holdings[i].currentPrice || holdings[i].averagePrice) * data.dividendYield).toFixed(2)
+ : 'N/A';
+ }
+ } else {
+ if (includeSector) {
+ (holdings[i] as any).sector = 'Unknown';
+ (holdings[i] as any).industry = 'Unknown';
+ }
+ if (includeDividends) {
+ (holdings[i] as any).dividendYield = 'N/A';
+ (holdings[i] as any).annualDividend = 'N/A';
+ }
+ }
}
}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/GetOrdersNode.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/GetOrdersNode.ts
index 378bf0551..832209ab7 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/GetOrdersNode.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/GetOrdersNode.ts
@@ -134,13 +134,25 @@ export class GetOrdersNode implements INodeType {
const isPaper = broker === 'paper';
try {
- // Mock order data - would come from actual broker API
- let orders: any[] = GetOrdersNode.getMockOrders(broker, isPaper);
-
- // Filter by status
- if (orderStatus !== 'all') {
- orders = orders.filter((o: any) => o.status.toLowerCase() === orderStatus.toLowerCase());
- }
+ // Fetch real orders from TradingBridge
+ const statusFilter = orderStatus !== 'all' ? orderStatus.toUpperCase() : undefined;
+ let orders: any[] = (await TradingBridge.getOrders(broker as any, statusFilter as any)).map(o => ({
+ orderId: o.orderId,
+ symbol: o.symbol,
+ exchange: o.exchange,
+ side: o.side,
+ orderType: o.type,
+ quantity: o.quantity,
+ filledQuantity: o.filledQuantity,
+ price: o.price,
+ averagePrice: o.filledPrice,
+ triggerPrice: o.triggerPrice,
+ status: o.status?.toLowerCase() || 'unknown',
+ product: o.product,
+ validity: o.validity,
+ tag: o.tag,
+ timestamp: o.timestamp,
+ }));
// Filter by symbol
if (filterSymbol) {
@@ -224,72 +236,4 @@ export class GetOrdersNode implements INodeType {
}
}
- private static getMockOrders(broker: string, isPaper: boolean): any[] {
- const now = new Date();
-
- return [
- {
- orderId: 'ORD001',
- symbol: 'AAPL',
- side: 'BUY',
- orderType: 'MARKET',
- quantity: 10,
- filledQuantity: 10,
- price: 175.50,
- averagePrice: 175.45,
- status: 'filled',
- timestamp: new Date(now.getTime() - 1 * 60 * 60 * 1000).toISOString(),
- filledAt: new Date(now.getTime() - 1 * 60 * 60 * 1000 + 500).toISOString(),
- },
- {
- orderId: 'ORD002',
- symbol: 'MSFT',
- side: 'BUY',
- orderType: 'LIMIT',
- quantity: 5,
- filledQuantity: 0,
- price: 400.00,
- status: 'open',
- timestamp: new Date(now.getTime() - 2 * 60 * 60 * 1000).toISOString(),
- },
- {
- orderId: 'ORD003',
- symbol: 'GOOGL',
- side: 'SELL',
- orderType: 'MARKET',
- quantity: 3,
- filledQuantity: 3,
- price: 140.25,
- averagePrice: 140.30,
- status: 'filled',
- timestamp: new Date(now.getTime() - 5 * 60 * 60 * 1000).toISOString(),
- filledAt: new Date(now.getTime() - 5 * 60 * 60 * 1000 + 300).toISOString(),
- },
- {
- orderId: 'ORD004',
- symbol: 'TSLA',
- side: 'BUY',
- orderType: 'LIMIT',
- quantity: 2,
- filledQuantity: 0,
- price: 200.00,
- status: 'cancelled',
- timestamp: new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),
- cancelledAt: new Date(now.getTime() - 20 * 60 * 60 * 1000).toISOString(),
- },
- {
- orderId: 'ORD005',
- symbol: 'AMZN',
- side: 'BUY',
- orderType: 'MARKET',
- quantity: 4,
- filledQuantity: 4,
- price: 185.00,
- averagePrice: 185.12,
- status: 'filled',
- timestamp: new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000).toISOString(),
- filledAt: new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000 + 800).toISOString(),
- },
- ];
- }
}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/PlaceOrderNode.ts b/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/PlaceOrderNode.ts
index 3db8ff1f5..a555dabde 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/PlaceOrderNode.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/nodes/trading/PlaceOrderNode.ts
@@ -12,6 +12,7 @@ import {
NodePropertyType,
} from '../../types';
import { TradingBridge, OrderSide, OrderType, ProductType, OrderValidity } from '../../adapters/TradingBridge';
+import { MarketDataBridge } from '../../adapters/MarketDataBridge';
import { RiskManager } from '../../safety/RiskManager';
import { AuditLogger } from '../../safety/AuditLogger';
import { ConfirmationService } from '../../safety/ConfirmationService';
@@ -268,19 +269,71 @@ export class PlaceOrderNode implements INodeType {
}]];
}
+ // Get prices for limit/stop orders
+ let limitPrice: number | undefined;
+ let stopPrice: number | undefined;
+
+ if (orderType === 'LIMIT') {
+ limitPrice = this.getNodeParameter('limitPrice', 0) as number;
+ }
+ if (orderType === 'STOP_LOSS' || orderType === 'STOP_LOSS_MARKET') {
+ stopPrice = this.getNodeParameter('stopPrice', 0) as number;
+ }
+
+ // Fetch current market price for accurate sizing and estimation
+ let currentPrice: number = limitPrice || 0;
+ if (!currentPrice) {
+ try {
+ const quote = await MarketDataBridge.getQuote(symbol);
+ currentPrice = quote.price;
+ } catch {
+ // Fallback: check input data for a price field
+ const inputData = this.getInputData();
+ currentPrice = Number(inputData[0]?.json?.price) || 0;
+ }
+ }
+
+ if (!currentPrice && (quantityType === 'dollars' || quantityType === 'percent')) {
+ return [[{
+ json: {
+ success: false,
+ error: `Cannot calculate quantity: unable to fetch current price for ${symbol}`,
+ timestamp: new Date().toISOString(),
+ },
+ }]];
+ }
+
// Calculate quantity
let quantity: number;
switch (quantityType) {
case 'dollars': {
const dollarAmount = this.getNodeParameter('dollarAmount', 0) as number;
- // Would need current price to calculate shares
- quantity = Math.floor(dollarAmount / 100); // Placeholder
+ quantity = Math.floor(dollarAmount / currentPrice);
+ if (quantity <= 0) {
+ return [[{
+ json: {
+ success: false,
+ error: `Dollar amount $${dollarAmount} is insufficient for ${symbol} at $${currentPrice.toFixed(2)}`,
+ timestamp: new Date().toISOString(),
+ },
+ }]];
+ }
break;
}
case 'percent': {
const percentage = this.getNodeParameter('percentage', 0) as number;
- // Would need balance to calculate
- quantity = 10; // Placeholder
+ const balance = await TradingBridge.getBalance(broker as any);
+ const dollarAmount = balance.available * (percentage / 100);
+ quantity = Math.floor(dollarAmount / currentPrice);
+ if (quantity <= 0) {
+ return [[{
+ json: {
+ success: false,
+ error: `${percentage}% of available balance ($${balance.available.toFixed(2)}) is insufficient for ${symbol} at $${currentPrice.toFixed(2)}`,
+ timestamp: new Date().toISOString(),
+ },
+ }]];
+ }
break;
}
case 'input': {
@@ -294,19 +347,7 @@ export class PlaceOrderNode implements INodeType {
quantity = this.getNodeParameter('quantity', 0) as number;
}
- // Get prices for limit/stop orders
- let limitPrice: number | undefined;
- let stopPrice: number | undefined;
-
- if (orderType === 'LIMIT') {
- limitPrice = this.getNodeParameter('limitPrice', 0) as number;
- }
- if (orderType === 'STOP_LOSS' || orderType === 'STOP_LOSS_MARKET') {
- stopPrice = this.getNodeParameter('stopPrice', 0) as number;
- }
-
- // Estimate order value (would use real price in production)
- const estimatedPrice = limitPrice || 100; // Placeholder
+ const estimatedPrice = currentPrice || limitPrice || 0;
const estimatedValue = estimatedPrice * quantity;
// Build order request
@@ -327,10 +368,15 @@ export class PlaceOrderNode implements INodeType {
// Validate against risk limits if enabled
if (validateRisk) {
+ const [currentBalance, currentPositions] = await Promise.all([
+ TradingBridge.getBalance(broker as any),
+ TradingBridge.getPositions(broker as any),
+ ]);
+
const validation = await RiskManager.validateOrder(
orderRequest as any,
- [],
- { currency: 'USD', available: 100000, used: 0, total: 100000 },
+ currentPositions,
+ currentBalance,
estimatedPrice
);
diff --git a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx
index b765443ef..207575785 100644
--- a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx
+++ b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx
@@ -187,6 +187,11 @@ const makePaymentApiRequest = async <T = any>(
// Payment API Service Class with enhanced debugging
export class PaymentApiService {
+ // Get payment gateway configuration
+ static async getPaymentConfig(): Promise<PaymentApiResponse<any>> {
+ return makePaymentApiRequest('GET', '/cashfree/config');
+ }
+
// Get all subscription plans from API
static async getSubscriptionPlans(): Promise<PaymentApiResponse<SubscriptionPlan[]>> {
const response = await makePaymentApiRequest<PlansResponse>('GET', '/cashfree/plans');
diff --git a/fincept-terminal-desktop/src/services/sentinels/sentinelApi.ts b/fincept-terminal-desktop/src/services/sentinels/sentinelApi.ts
new file mode 100644
index 000000000..c88cf1705
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/sentinels/sentinelApi.ts
@@ -0,0 +1,126 @@
+// Sentinel API Service - AI-powered monitoring sentinels
+// Endpoints: /sentinels/*
+
+import { fetch as tauriFetch } from '@tauri-apps/plugin-http';
+
+const API_CONFIG = {
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',
+};
+
+const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;
+const safeFetch = import.meta.env.DEV ? window.fetch.bind(window) : tauriFetch;
+
+interface ApiResponse<T = any> {
+ success: boolean;
+ data?: T;
+ error?: string;
+ status_code: number;
+}
+
+async function makeApiRequest<T = any>(
+ endpoint: string,
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',
+ apiKey: string,
+ body?: any
+): Promise<ApiResponse<T>> {
+ try {
+ const options: RequestInit = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-API-Key': apiKey,
+ },
+ };
+
+ if (body && (method === 'POST' || method === 'PUT')) {
+ options.body = JSON.stringify(body);
+ }
+
+ const response = await safeFetch(getApiEndpoint(endpoint), options);
+ const data = await response.json();
+
+ return {
+ success: response.ok,
+ data,
+ error: response.ok ? undefined : data.detail || data.error || 'Request failed',
+ status_code: response.status,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Network error',
+ status_code: 500,
+ };
+ }
+}
+
+export interface Sentinel {
+ id: string;
+ domain: string;
+ status: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface SentinelFinding {
+ id: string;
+ sentinel_id: string;
+ content: string;
+ created_at: string;
+}
+
+export interface DeployRequest {
+ domain: string;
+ config?: Record<string, any>;
+}
+
+export class SentinelApiService {
+ // Deploy a new sentinel
+ static async deploy(apiKey: string, request: DeployRequest): Promise<ApiResponse> {
+ return makeApiRequest('/sentinels/deploy', 'POST', apiKey, request);
+ }
+
+ // List all sentinels
+ static async listSentinels(apiKey: string, domain?: string, status?: string): Promise<ApiResponse<Sentinel[]>> {
+ const params = new URLSearchParams();
+ if (domain) params.append('domain', domain);
+ if (status) params.append('status', status);
+ const query = params.toString();
+ return makeApiRequest(`/sentinels/${query ? `?${query}` : ''}`, 'GET', apiKey);
+ }
+
+ // Get sentinel details
+ static async getSentinel(apiKey: string, sentinelId: string): Promise<ApiResponse<Sentinel>> {
+ return makeApiRequest(`/sentinels/${sentinelId}`, 'GET', apiKey);
+ }
+
+ // Stop/delete a sentinel
+ static async stopSentinel(apiKey: string, sentinelId: string): Promise<ApiResponse> {
+ return makeApiRequest(`/sentinels/${sentinelId}`, 'DELETE', apiKey);
+ }
+
+ // Get sentinel findings
+ static async getFindings(
+ apiKey: string,
+ sentinelId: string,
+ limit: number = 20,
+ offset: number = 0
+ ): Promise<ApiResponse<SentinelFinding[]>> {
+ return makeApiRequest(`/sentinels/${sentinelId}/findings?limit=${limit}&offset=${offset}`, 'GET', apiKey);
+ }
+
+ // Pause a sentinel
+ static async pauseSentinel(apiKey: string, sentinelId: string): Promise<ApiResponse> {
+ return makeApiRequest(`/sentinels/${sentinelId}/pause`, 'PUT', apiKey);
+ }
+
+ // Resume a sentinel
+ static async resumeSentinel(apiKey: string, sentinelId: string): Promise<ApiResponse> {
+ return makeApiRequest(`/sentinels/${sentinelId}/resume`, 'PUT', apiKey);
+ }
+
+ // Ask a sentinel a question
+ static async askSentinel(apiKey: string, query: string): Promise<ApiResponse> {
+ return makeApiRequest('/sentinels/ask', 'POST', apiKey, { query });
+ }
+}