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.

feat: Refactor broker architecture and create universal paper trading module

tilakpatel2240c3dcd9f38f
diff --git a/fincept-terminal-desktop/bun.lock b/fincept-terminal-desktop/bun.lock
index 67b17c0df..9c15d9898 100644
--- a/fincept-terminal-desktop/bun.lock
+++ b/fincept-terminal-desktop/bun.lock
@@ -46,6 +46,7 @@
"@tauri-apps/plugin-updater": "~2.9.0",
"@types/react-grid-layout": "^1.3.5",
"axios": "^1.12.2",
+ "ccxt": "^4.5.24",
"cheerio": "^1.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -696,6 +697,8 @@
"ccount": ["[email protected]", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],
+ "ccxt": ["[email protected]", "", { "dependencies": { "ws": "^8.8.1" } }, "sha512-0ym0t8A4EFpxKpge12yowIkSnimtLF5PYOaANycAT8i+FqSO3KoD5qLfSK0rP69g3nnx7Q38X+9c0Rs0r74a4Q=="],
+
"chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
"character-entities": ["[email protected]", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="],
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.json
index 3b6cfe157..07baadaed 100644
--- a/fincept-terminal-desktop/package.json
+++ b/fincept-terminal-desktop/package.json
@@ -52,6 +52,7 @@
"@tauri-apps/plugin-updater": "~2.9.0",
"@types/react-grid-layout": "^1.3.5",
"axios": "^1.12.2",
+ "ccxt": "^4.5.24",
"cheerio": "^1.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
diff --git a/fincept-terminal-desktop/src/brokers/README.md b/fincept-terminal-desktop/src/brokers/README.md
new file mode 100644
index 000000000..7499bbf06
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/README.md
@@ -0,0 +1,85 @@
+# Brokers Integration
+
+Professional-grade broker and exchange integrations for Fincept Terminal. Bloomberg-quality infrastructure for trading, paper trading, and agentic systems.
+
+## Structure
+
+```
+src/brokers/
+├── index.ts # Main exports and broker registry
+├── exchanges/ # Crypto exchanges (CCXT-based)
+│ ├── types.ts # Unified type definitions
+│ ├── BaseExchangeAdapter.ts # Abstract base class
+│ ├── KrakenAdapter.ts # Kraken implementation
+│ ├── index.ts # Exchange registry & factory
+│ └── README.md # Detailed documentation
+├── zerodha/ # Zerodha Kite (Indian broker)
+│ ├── index.ts # Zerodha exports and metadata
+│ └── kiteAdapter.tsx # Complete Kite Connect API adapter
+└── README.md # This file
+```
+
+## Supported Brokers
+
+### 1. **Kraken** (Crypto Exchange - CEX) - CCXT
+- **Region**: Global
+- **Assets**: 200+ Cryptocurrencies
+- **Features**: Spot, Margin, Futures, Staking, Earn
+- **Technology**: CCXT unified API
+- **WebSocket**: Real-time market data
+- **Advanced Orders**: Stop-loss, Take-profit, Trailing stops, Iceberg
+- **Files**: `src/brokers/exchanges/KrakenAdapter.ts`
+
+### 2. **HyperLiquid** (Crypto DEX) - CCXT
+- **Region**: Global (Arbitrum L2)
+- **Assets**: Perpetual futures on major crypto assets
+- **Features**: Spot, Perpetuals (up to 50x), Vaults, Subaccounts
+- **Technology**: CCXT unified API
+- **WebSocket**: Real-time market data
+- **Special**: 4% fee discount (Builder Code), No market orders (simulated with limits)
+- **Files**: `src/brokers/exchanges/HyperLiquidAdapter.ts`
+
+### 3. **Zerodha Kite** (Stock Broker)
+- **Region**: India
+- **Assets**: Equity, F&O, Commodity, Currency, Mutual Funds
+- **Features**: Trading, Portfolio, GTT, Alerts, Margin Calculator
+- **API Version**: Kite Connect v3
+- **Files**: `src/brokers/zerodha/`
+
+## Adding New Brokers
+
+To add a new broker integration:
+
+1. Create a new directory: `src/brokers/{broker-name}/`
+2. Implement the broker adapter with standard interface
+3. Create `index.ts` with exports and metadata
+4. Update `src/brokers/index.ts` to include the new broker
+5. Add broker to `SUPPORTED_BROKERS` registry
+
+## Usage
+
+```typescript
+import { SUPPORTED_BROKERS } from '@/brokers';
+import { createKiteAdapter } from '@/brokers/zerodha';
+import { KrakenService } from '@/brokers/kraken';
+
+// Check available brokers
+console.log(SUPPORTED_BROKERS);
+
+// Initialize Zerodha
+const kite = createKiteAdapter({
+ apiKey: 'your_api_key',
+ apiSecret: 'your_secret',
+});
+
+// Initialize Kraken
+const kraken = new KrakenService(config);
+```
+
+## Migration Notes
+
+This directory consolidates broker integrations previously scattered across:
+- `src/stockBrokers/` (old)
+- `src/services/stockBrokers/` (old)
+
+All broker code is now unified under `src/brokers/` for better organization.
diff --git a/fincept-terminal-desktop/src/brokers/crypto/BaseExchangeAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/BaseExchangeAdapter.ts
new file mode 100644
index 000000000..ed514bd25
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/crypto/BaseExchangeAdapter.ts
@@ -0,0 +1,721 @@
+/**
+ * Base Exchange Adapter
+ *
+ * Abstract base class for all exchange adapters
+ * Provides common functionality and enforces consistent interface
+ */
+
+import ccxt, { Exchange, Market, Ticker, OrderBook, Trade, OHLCV, Balance, Order, Position } from 'ccxt';
+import {
+ IExchangeAdapter,
+ ExchangeCredentials,
+ ExchangeConfig,
+ OrderType,
+ OrderSide,
+ OrderParams,
+ ExchangeCapabilities,
+ ExchangeError,
+ AuthenticationError,
+ RateLimitError,
+ ExchangeEvent,
+ ExchangeEventData,
+} from './types';
+
+export abstract class BaseExchangeAdapter implements IExchangeAdapter {
+ protected exchange: Exchange;
+ protected _isConnected: boolean = false;
+ protected _isAuthenticated: boolean = false;
+ protected eventListeners: Map<ExchangeEvent, Set<(data: ExchangeEventData) => void>> = new Map();
+
+ public readonly id: string;
+ public readonly name: string;
+
+ constructor(config: ExchangeConfig) {
+ this.id = config.exchange;
+
+ // Initialize CCXT exchange
+ const ExchangeClass = ccxt[config.exchange as keyof typeof ccxt] as typeof Exchange;
+ if (!ExchangeClass) {
+ throw new Error(`Exchange "${config.exchange}" not supported by CCXT`);
+ }
+
+ this.exchange = new ExchangeClass({
+ apiKey: config.credentials?.apiKey,
+ secret: config.credentials?.secret,
+ password: config.credentials?.password,
+ uid: config.credentials?.uid,
+ enableRateLimit: config.enableRateLimit ?? true,
+ timeout: config.timeout ?? 30000,
+ ...(config.sandbox && { sandbox: true }),
+ ...config.options,
+ });
+
+ this.name = this.exchange.name as string;
+ }
+
+ // ============================================================================
+ // CONNECTION MANAGEMENT
+ // ============================================================================
+
+ async connect(): Promise<void> {
+ try {
+ await this.exchange.loadMarkets();
+ this._isConnected = true;
+ this.emit('connected', { exchange: this.id });
+ } catch (error) {
+ this._isConnected = false;
+ throw this.handleError(error);
+ }
+ }
+
+ async disconnect(): Promise<void> {
+ this._isConnected = false;
+ this._isAuthenticated = false;
+ this.emit('disconnected', { exchange: this.id });
+ }
+
+ isConnected(): boolean {
+ return this._isConnected;
+ }
+
+ // ============================================================================
+ // AUTHENTICATION
+ // ============================================================================
+
+ async authenticate(credentials: ExchangeCredentials): Promise<void> {
+ try {
+ this.exchange.apiKey = credentials.apiKey;
+ this.exchange.secret = credentials.secret;
+ if (credentials.password) this.exchange.password = credentials.password;
+ if (credentials.uid) this.exchange.uid = credentials.uid;
+
+ // Test authentication by fetching balance
+ await this.exchange.fetchBalance();
+ this._isAuthenticated = true;
+ this.emit('authenticated', { exchange: this.id });
+ } catch (error) {
+ this._isAuthenticated = false;
+ throw new AuthenticationError(
+ 'Authentication failed',
+ this.id,
+ error
+ );
+ }
+ }
+
+ isAuthenticated(): boolean {
+ return this._isAuthenticated;
+ }
+
+ // ============================================================================
+ // MARKET DATA
+ // ============================================================================
+
+ async fetchMarkets(): Promise<Market[]> {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchMarkets();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchStatus(): Promise<any> {
+ try {
+ await this.ensureConnected();
+ if (!this.exchange.has['fetchStatus']) {
+ return { status: 'ok', updated: Date.now() };
+ }
+ return await this.exchange.fetchStatus();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchCurrencies(): Promise<any> {
+ try {
+ await this.ensureConnected();
+ if (!this.exchange.has['fetchCurrencies']) {
+ return {};
+ }
+ return await this.exchange.fetchCurrencies();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchTime(): Promise<number> {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchTime() as number;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchTicker(symbol: string): Promise<Ticker> {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchTicker(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchTickers(symbols?: string[]): Promise<Record<string, Ticker>> {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchTickers(symbols);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchOrderBook(symbol: string, limit?: number): Promise<OrderBook> {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchOrderBook(symbol, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchTrades(symbol: string, limit?: number): Promise<Trade[]> {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchTrades(symbol, undefined, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchOHLCV(
+ symbol: string,
+ timeframe: string = '1m',
+ limit?: number
+ ): Promise<OHLCV[]> {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchOHLCV(symbol, timeframe, undefined, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // ACCOUNT & BALANCE
+ // ============================================================================
+
+ async fetchBalance(): Promise<Balance> {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchBalance() as unknown as Balance;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchLedger(code?: string, since?: number, limit?: number): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchLedger']) {
+ throw new Error('fetchLedger not supported by this exchange');
+ }
+ return await this.exchange.fetchLedger(code, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchTradingFee(symbol: string): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchTradingFee']) {
+ const fees = await this.exchange.fetchTradingFees();
+ return fees[symbol] || null;
+ }
+ return await this.exchange.fetchTradingFee(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchPositions(symbols?: string[]): Promise<Position[]> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchPositions']) {
+ return [];
+ }
+ return await this.exchange.fetchPositions(symbols);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // TRADING
+ // ============================================================================
+
+ async createOrder(
+ symbol: string,
+ type: OrderType,
+ side: OrderSide,
+ amount: number,
+ price?: number,
+ params?: OrderParams
+ ): Promise<Order> {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.createOrder(symbol, type, side, amount, price, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async createOrders(orders: Array<{
+ symbol: string;
+ type: OrderType;
+ side: OrderSide;
+ amount: number;
+ price?: number;
+ params?: OrderParams;
+ }>): Promise<Order[]> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['createOrders']) {
+ // Fallback: create orders one by one
+ const results: Order[] = [];
+ for (const order of orders) {
+ const result = await this.createOrder(
+ order.symbol,
+ order.type,
+ order.side,
+ order.amount,
+ order.price,
+ order.params
+ );
+ results.push(result);
+ }
+ return results;
+ }
+ return await this.exchange.createOrders(orders);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async createMarketOrderWithCost(
+ symbol: string,
+ side: OrderSide,
+ cost: number,
+ params?: OrderParams
+ ): Promise<Order> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['createMarketOrderWithCost']) {
+ throw new Error('createMarketOrderWithCost not supported');
+ }
+ return await (this.exchange as any).createMarketOrderWithCost(symbol, side, cost, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async createMarketBuyOrderWithCost(
+ symbol: string,
+ cost: number,
+ params?: OrderParams
+ ): Promise<Order> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['createMarketBuyOrderWithCost']) {
+ return await this.createMarketOrderWithCost(symbol, 'buy', cost, params);
+ }
+ return await (this.exchange as any).createMarketBuyOrderWithCost(symbol, cost, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async editOrder(
+ orderId: string,
+ symbol: string,
+ type?: OrderType,
+ side?: OrderSide,
+ amount?: number,
+ price?: number,
+ params?: OrderParams
+ ): Promise<Order> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['editOrder']) {
+ throw new Error('editOrder not supported by this exchange');
+ }
+ return await this.exchange.editOrder(orderId, symbol, type as any, side as any, amount, price, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async cancelOrder(orderId: string, symbol: string): Promise<Order> {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.cancelOrder(orderId, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async cancelOrders(orderIds: string[], symbol?: string): Promise<Order[]> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['cancelOrders']) {
+ // Fallback: cancel orders one by one
+ const results: Order[] = [];
+ for (const orderId of orderIds) {
+ if (!symbol) throw new Error('Symbol required for bulk cancel fallback');
+ const result = await this.cancelOrder(orderId, symbol);
+ results.push(result);
+ }
+ return results;
+ }
+ return await this.exchange.cancelOrders(orderIds, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async cancelAllOrders(symbol?: string): Promise<Order[]> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['cancelAllOrders']) {
+ throw new Error('Exchange does not support cancelAllOrders');
+ }
+ return await this.exchange.cancelAllOrders(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async cancelAllOrdersAfter(timeout: number): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['cancelAllOrdersAfter']) {
+ throw new Error('cancelAllOrdersAfter not supported by this exchange');
+ }
+ return await (this.exchange as any).cancelAllOrdersAfter(timeout);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchOrder(orderId: string, symbol: string): Promise<Order> {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchOrder(orderId, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchOrdersByIds(orderIds: string[], symbol?: string): Promise<Order[]> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchOrdersByIds']) {
+ // Fallback: fetch orders one by one
+ const results: Order[] = [];
+ for (const orderId of orderIds) {
+ if (!symbol) throw new Error('Symbol required for fetchOrdersByIds fallback');
+ const order = await this.fetchOrder(orderId, symbol);
+ results.push(order);
+ }
+ return results;
+ }
+ return await (this.exchange as any).fetchOrdersByIds(orderIds, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchOrderTrades(orderId: string, symbol: string): Promise<Trade[]> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchOrderTrades']) {
+ throw new Error('fetchOrderTrades not supported by this exchange');
+ }
+ return await this.exchange.fetchOrderTrades(orderId, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchMyTrades(symbol?: string, since?: number, limit?: number): Promise<Trade[]> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchMyTrades']) {
+ throw new Error('fetchMyTrades not supported by this exchange');
+ }
+ return await this.exchange.fetchMyTrades(symbol, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchOpenOrders(symbol?: string): Promise<Order[]> {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchOpenOrders(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchClosedOrders(symbol?: string, limit?: number): Promise<Order[]> {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchClosedOrders(symbol, undefined, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // DEPOSITS & WITHDRAWALS
+ // ============================================================================
+
+ async fetchDeposits(code?: string, since?: number, limit?: number): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchDeposits']) {
+ throw new Error('fetchDeposits not supported by this exchange');
+ }
+ return await this.exchange.fetchDeposits(code, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchWithdrawals(code?: string, since?: number, limit?: number): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchWithdrawals']) {
+ throw new Error('fetchWithdrawals not supported by this exchange');
+ }
+ return await this.exchange.fetchWithdrawals(code, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchDepositAddress(code: string, params?: any): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchDepositAddress']) {
+ throw new Error('fetchDepositAddress not supported by this exchange');
+ }
+ return await this.exchange.fetchDepositAddress(code, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async createDepositAddress(code: string, params?: any): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['createDepositAddress']) {
+ throw new Error('createDepositAddress not supported by this exchange');
+ }
+ return await this.exchange.createDepositAddress(code, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async fetchDepositMethods(code?: string): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchDepositMethods']) {
+ throw new Error('fetchDepositMethods not supported by this exchange');
+ }
+ return await (this.exchange as any).fetchDepositMethods(code);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async withdraw(code: string, amount: number, address: string, tag?: string, params?: any): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['withdraw']) {
+ throw new Error('withdraw not supported by this exchange');
+ }
+ return await this.exchange.withdraw(code, amount, address, tag, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // TRANSFERS
+ // ============================================================================
+
+ async transfer(code: string, amount: number, fromAccount: string, toAccount: string, params?: any): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['transfer']) {
+ throw new Error('transfer not supported by this exchange');
+ }
+ return await this.exchange.transfer(code, amount, fromAccount, toAccount, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ async transferOut(code: string, amount: number, params?: any): Promise<any> {
+ try {
+ await this.ensureAuthenticated();
+ // transferOut is typically just a transfer to an external account
+ if (!this.exchange.has['transfer']) {
+ throw new Error('transferOut not supported by this exchange');
+ }
+ return await this.exchange.transfer(code, amount, 'spot', 'external', params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // EXCHANGE INFORMATION
+ // ============================================================================
+
+ getCapabilities(): ExchangeCapabilities {
+ const has = this.exchange.has;
+ return {
+ spot: !!has['spot'],
+ margin: !!has['margin'],
+ futures: !!has['future'],
+ options: !!has['option'],
+ swap: !!has['swap'],
+
+ supportedOrderTypes: this.getSupportedOrderTypes(),
+ supportedTimeInForce: ['GTC', 'IOC', 'FOK', 'PO'],
+
+ leverageTrading: !!has['setLeverage'],
+ stopOrders: !!has['createStopOrder'],
+ conditionalOrders: !!has['createOrder'],
+ algoOrders: false,
+
+ realtimeData: !!has['watchTicker'],
+ historicalData: !!has['fetchOHLCV'],
+ websocketSupport: !!has['watchTicker'],
+
+ multiAccount: false,
+ subAccounts: false,
+ portfolioMargin: false,
+
+ restApi: true,
+ websocketApi: !!has['watchTicker'],
+ fixApi: false,
+
+ rateLimits: {
+ public: 1000,
+ private: 3000,
+ trading: 1000,
+ },
+ };
+ }
+
+ protected getSupportedOrderTypes(): OrderType[] {
+ const types: OrderType[] = ['market', 'limit'];
+ if (this.exchange.has['createStopOrder']) types.push('stop', 'stop_limit');
+ if (this.exchange.has['createTrailingAmountOrder']) types.push('trailing_stop');
+ return types;
+ }
+
+ getMarkets(): Record<string, Market> {
+ return this.exchange.markets;
+ }
+
+ // ============================================================================
+ // EVENT SYSTEM
+ // ============================================================================
+
+ on(event: ExchangeEvent, callback: (data: ExchangeEventData) => void): void {
+ if (!this.eventListeners.has(event)) {
+ this.eventListeners.set(event, new Set());
+ }
+ this.eventListeners.get(event)!.add(callback);
+ }
+
+ off(event: ExchangeEvent, callback: (data: ExchangeEventData) => void): void {
+ this.eventListeners.get(event)?.delete(callback);
+ }
+
+ protected emit(event: ExchangeEvent, data: any): void {
+ const eventData: ExchangeEventData = {
+ event,
+ exchange: this.id,
+ timestamp: Date.now(),
+ data,
+ };
+
+ this.eventListeners.get(event)?.forEach(callback => {
+ try {
+ callback(eventData);
+ } catch (error) {
+ console.error(`Error in event listener for ${event}:`, error);
+ }
+ });
+ }
+
+ // ============================================================================
+ // ERROR HANDLING
+ // ============================================================================
+
+ protected handleError(error: any): ExchangeError {
+ if (error instanceof ExchangeError) {
+ return error;
+ }
+
+ const message = error.message || 'Unknown error';
+
+ if (message.includes('rate limit')) {
+ return new RateLimitError(message, this.id, error);
+ }
+
+ if (message.includes('authentication') || message.includes('Invalid API')) {
+ return new AuthenticationError(message, this.id, error);
+ }
+
+ return new ExchangeError(message, 'UNKNOWN', this.id, error);
+ }
+
+ protected async ensureConnected(): Promise<void> {
+ if (!this._isConnected) {
+ await this.connect();
+ }
+ }
+
+ protected async ensureAuthenticated(): Promise<void> {
+ await this.ensureConnected();
+ if (!this._isAuthenticated && (this.exchange.apiKey && this.exchange.secret)) {
+ throw new AuthenticationError('Not authenticated', this.id);
+ }
+ }
+
+ // ============================================================================
+ // UTILITIES
+ // ============================================================================
+
+ protected parseSymbol(symbol: string): { base: string; quote: string } {
+ const parts = symbol.split('/');
+ if (parts.length !== 2) {
+ throw new Error(`Invalid symbol format: ${symbol}`);
+ }
+ return { base: parts[0], quote: parts[1] };
+ }
+
+ protected formatSymbol(base: string, quote: string): string {
+ return `${base}/${quote}`;
+ }
+}
diff --git a/fincept-terminal-desktop/src/brokers/crypto/README.md b/fincept-terminal-desktop/src/brokers/crypto/README.md
new file mode 100644
index 000000000..021cfdb95
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/crypto/README.md
@@ -0,0 +1,401 @@
+## Exchange Adapters (CCXT)
+
+Professional-grade exchange integrations using CCXT for Fincept Terminal. Bloomberg-quality infrastructure for trading, paper trading, and agentic systems.
+
+## Architecture
+
+```
+src/brokers/exchanges/
+├── types.ts # Unified type definitions
+├── BaseExchangeAdapter.ts # Abstract base class
+├── KrakenAdapter.ts # Kraken implementation
+├── index.ts # Registry & factory
+└── README.md # This file
+```
+
+## Features
+
+### Core Capabilities
+- ✅ **Unified Interface**: Consistent API across all exchanges
+- ✅ **Type-Safe**: Full TypeScript support
+- ✅ **Error Handling**: Professional error types & recovery
+- ✅ **Event System**: Real-time event notifications
+- ✅ **Rate Limiting**: Built-in rate limit management
+- ✅ **Authentication**: Secure credential handling
+
+### Trading Features
+- ✅ Market, Limit, Stop, Stop-Limit orders
+- ✅ Trailing stops, Iceberg orders
+- ✅ Margin trading with leverage
+- ✅ Position management
+- ✅ Balance & portfolio tracking
+
+### Market Data
+- ✅ Real-time tickers
+- ✅ Order book depth
+- ✅ Trade history
+- ✅ OHLCV candles (1m to 1w)
+- ✅ Historical data
+
+### Advanced Features (Kraken)
+- ✅ Staking & Earn
+- ✅ Futures trading
+- ✅ Margin trading
+- ✅ Fund transfers
+- ✅ Deposit/Withdrawal
+
+## Quick Start
+
+### Basic Usage
+
+```typescript
+import { createExchangeAdapter } from '@/brokers/exchanges';
+
+// Create exchange instance
+const kraken = createExchangeAdapter('kraken', {
+ enableRateLimit: true,
+ sandbox: false, // Use testnet
+});
+
+// Connect to exchange
+await kraken.connect();
+
+// Fetch market data
+const ticker = await kraken.fetchTicker('BTC/USD');
+const orderBook = await kraken.fetchOrderBook('BTC/USD', 25);
+const trades = await kraken.fetchTrades('BTC/USD', 100);
+```
+
+### Authentication & Trading
+
+```typescript
+import { createExchangeAdapter } from '@/brokers/exchanges';
+
+const kraken = createExchangeAdapter('kraken');
+
+// Authenticate
+await kraken.authenticate({
+ apiKey: 'YOUR_API_KEY',
+ secret: 'YOUR_SECRET',
+});
+
+// Check balance
+const balance = await kraken.fetchBalance();
+console.log('BTC Balance:', balance.BTC?.free);
+
+// Place order
+const order = await kraken.createOrder(
+ 'BTC/USD', // symbol
+ 'limit', // type
+ 'buy', // side
+ 0.001, // amount
+ 50000 // price
+);
+
+console.log('Order placed:', order.id);
+```
+
+### Advanced Orders (Kraken)
+
+```typescript
+import { KrakenAdapter } from '@/brokers/exchanges';
+
+const kraken = new KrakenAdapter();
+await kraken.authenticate({ ... });
+
+// Stop-loss order
+await kraken.createStopLossOrder(
+ 'BTC/USD',
+ 'sell',
+ 0.001,
+ 48000 // stop price
+);
+
+// Take-profit order
+await kraken.createTakeProfitOrder(
+ 'BTC/USD',
+ 'sell',
+ 0.001,
+ 52000 // take profit price
+);
+
+// Trailing stop
+await kraken.createTrailingStopOrder(
+ 'BTC/USD',
+ 'sell',
+ 0.001,
+ 2 // 2% trailing
+);
+
+// Iceberg order (hidden liquidity)
+await kraken.createIcebergOrder(
+ 'BTC/USD',
+ 'buy',
+ 1.0, // total amount
+ 50000, // price
+ 0.1 // visible amount
+);
+```
+
+### Margin Trading
+
+```typescript
+// Set leverage
+await kraken.setLeverage('BTC/USD', 5);
+
+// Place margin order with leverage
+await kraken.createMarginOrder(
+ 'BTC/USD',
+ 'limit',
+ 'buy',
+ 0.01,
+ 50000,
+ 5 // 5x leverage
+);
+
+// Check margin balance
+const marginBalance = await kraken.fetchMarginBalance();
+```
+
+### Staking (Kraken-specific)
+
+```typescript
+// View staking options
+const stakingAssets = await kraken.fetchStakingAssets();
+
+// Stake ETH
+await kraken.stakeAsset('ETH', 1.0, 'ethereum-staked');
+
+// Unstake
+await kraken.unstakeAsset('ETH', 0.5);
+```
+
+### Historical Data
+
+```typescript
+// Fetch OHLCV candles
+const candles = await kraken.fetchHistoricalOHLCV(
+ 'BTC/USD',
+ '1h', // timeframe
+ undefined, // since (optional)
+ 720 // limit (30 days of hourly data)
+);
+
+candles.forEach(([time, open, high, low, close, volume]) => {
+ console.log({ time, open, high, low, close, volume });
+});
+```
+
+### Event Handling
+
+```typescript
+// Subscribe to events
+kraken.on('connected', (data) => {
+ console.log('Connected to', data.exchange);
+});
+
+kraken.on('error', (data) => {
+ console.error('Exchange error:', data.data);
+});
+
+kraken.on('authenticated', (data) => {
+ console.log('Authenticated successfully');
+});
+
+// Connect
+await kraken.connect();
+```
+
+### Error Handling
+
+```typescript
+import {
+ ExchangeError,
+ AuthenticationError,
+ RateLimitError,
+ InsufficientFunds,
+} from '@/brokers/exchanges';
+
+try {
+ await kraken.createOrder('BTC/USD', 'limit', 'buy', 10, 50000);
+} catch (error) {
+ if (error instanceof AuthenticationError) {
+ console.error('Auth failed:', error.message);
+ } else if (error instanceof RateLimitError) {
+ console.error('Rate limit exceeded, retry after delay');
+ } else if (error instanceof InsufficientFunds) {
+ console.error('Not enough funds');
+ } else if (error instanceof ExchangeError) {
+ console.error('Exchange error:', error.code, error.message);
+ }
+}
+```
+
+## Exchange Capabilities
+
+```typescript
+// Check what exchange supports
+const capabilities = kraken.getCapabilities();
+
+console.log('Spot trading:', capabilities.spot);
+console.log('Margin trading:', capabilities.margin);
+console.log('Futures trading:', capabilities.futures);
+console.log('Supported order types:', capabilities.supportedOrderTypes);
+console.log('WebSocket support:', capabilities.websocketSupport);
+```
+
+## Paper Trading Integration
+
+```typescript
+import { createExchangeAdapter } from '@/brokers/exchanges';
+import { PaperTradingEngine } from '@/services/paperTrading';
+
+// Create exchange adapter for market data
+const kraken = createExchangeAdapter('kraken');
+await kraken.connect();
+
+// Create paper trading engine
+const paperTrading = new PaperTradingEngine({
+ exchange: kraken,
+ initialBalance: 100000,
+ portfolio: 'my-paper-portfolio',
+});
+
+// Use paper trading engine instead of real exchange
+const order = await paperTrading.createOrder(
+ 'BTC/USD',
+ 'limit',
+ 'buy',
+ 0.01,
+ 50000
+);
+```
+
+## Agentic Trading Integration
+
+```typescript
+import { createExchangeAdapter } from '@/brokers/exchanges';
+import { TradingAgent } from '@/services/agenticTrading';
+
+const kraken = createExchangeAdapter('kraken');
+await kraken.authenticate({ ... });
+
+// Create AI trading agent
+const agent = new TradingAgent({
+ exchange: kraken,
+ strategy: 'momentum',
+ riskLevel: 'medium',
+ maxPositionSize: 0.1,
+});
+
+// Start autonomous trading
+await agent.start();
+```
+
+## Adding New Exchanges
+
+To add support for another exchange:
+
+### 1. Create Adapter Class
+
+```typescript
+// src/brokers/exchanges/BinanceAdapter.ts
+import { BaseExchangeAdapter } from './BaseExchangeAdapter';
+import { ExchangeConfig } from './types';
+
+export class BinanceAdapter extends BaseExchangeAdapter {
+ constructor(config?: Partial<ExchangeConfig>) {
+ super({
+ exchange: 'binance',
+ ...config,
+ });
+ }
+
+ // Add Binance-specific methods here
+}
+```
+
+### 2. Register in Index
+
+```typescript
+// src/brokers/exchanges/index.ts
+import { BinanceAdapter } from './BinanceAdapter';
+
+export const SUPPORTED_EXCHANGES = {
+ kraken: { ... },
+ binance: {
+ id: 'binance',
+ name: 'Binance',
+ adapter: BinanceAdapter,
+ type: 'centralized',
+ assetClass: 'crypto',
+ region: 'global',
+ },
+};
+```
+
+### 3. Use It
+
+```typescript
+const binance = createExchangeAdapter('binance');
+await binance.connect();
+```
+
+## Supported Exchanges
+
+Currently implemented:
+- ✅ **Kraken** - Full implementation with advanced features
+
+Coming soon (CCXT supports 100+ exchanges):
+- 🔄 Binance
+- 🔄 Coinbase
+- 🔄 Bybit
+- 🔄 OKX
+- 🔄 Bitfinex
+- 🔄 And many more...
+
+## Performance Tips
+
+1. **Enable Rate Limiting**: Always use `enableRateLimit: true`
+2. **Reuse Connections**: Create one adapter instance and reuse it
+3. **Batch Requests**: Use `fetchTickers()` for multiple symbols
+4. **Use WebSocket**: For real-time data (coming soon with ccxt.pro)
+5. **Cache Markets**: Call `loadMarkets()` once and cache
+
+## Testing
+
+```typescript
+// Use sandbox mode for testing
+const krakenTest = createExchangeAdapter('kraken', {
+ sandbox: true,
+ credentials: {
+ apiKey: 'test_key',
+ secret: 'test_secret',
+ },
+});
+
+await krakenTest.connect();
+// All operations now run on testnet
+```
+
+## Security Best Practices
+
+1. **Never commit API keys** - Use environment variables
+2. **Use read-only keys** for market data
+3. **Restrict IP addresses** in exchange API settings
+4. **Enable 2FA** on exchange accounts
+5. **Monitor API usage** and set alerts
+6. **Use separate keys** for paper vs live trading
+
+## Resources
+
+- **CCXT Documentation**: https://docs.ccxt.com/
+- **Kraken API Docs**: https://docs.kraken.com/
+- **CCXT GitHub**: https://github.com/ccxt/ccxt
+- **Fincept Terminal Docs**: [Internal documentation]
+
+---
+
+**Version**: 1.0.0
+**Last Updated**: 2025-01-29
+**Maintained by**: Fincept Corporation
diff --git a/fincept-terminal-desktop/src/brokers/crypto/hyperliquid/HyperLiquidAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/hyperliquid/HyperLiquidAdapter.ts
new file mode 100644
index 000000000..1d1274217
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/crypto/hyperliquid/HyperLiquidAdapter.ts
@@ -0,0 +1,1108 @@
+/**
+ * HyperLiquid Exchange Adapter
+ *
+ * Professional-grade HyperLiquid DEX integration using CCXT
+ * Features: Perpetual futures, spot, vault trading, subaccounts
+ * Note: Simulates market orders with 5% max slippage limit orders
+ */
+
+import { BaseExchangeAdapter } from './BaseExchangeAdapter';
+import {
+ ExchangeConfig,
+ OrderType,
+ OrderSide,
+ OrderParams,
+ ExchangeCapabilities,
+} from './types';
+
+export class HyperLiquidAdapter extends BaseExchangeAdapter {
+ constructor(config?: Partial<ExchangeConfig>) {
+ super({
+ exchange: 'hyperliquid',
+ enableRateLimit: true,
+ timeout: 30000,
+ ...config,
+ });
+ }
+
+ // ============================================================================
+ // HYPERLIQUID-SPECIFIC FEATURES
+ // ============================================================================
+
+ /**
+ * Get HyperLiquid-specific capabilities
+ */
+ getCapabilities(): ExchangeCapabilities {
+ const base = super.getCapabilities();
+ return {
+ ...base,
+ spot: true,
+ margin: false, // Uses perpetuals instead
+ futures: true, // Perpetual futures
+ swap: true,
+ options: false,
+
+ supportedOrderTypes: [
+ 'limit',
+ 'market', // Simulated with limit orders
+ 'stop',
+ 'stop_limit',
+ ],
+
+ leverageTrading: true, // Up to 50x on perpetuals
+ stopOrders: true,
+ conditionalOrders: true,
+ algoOrders: false,
+
+ realtimeData: true,
+ historicalData: true,
+ websocketSupport: true,
+
+ rateLimits: {
+ public: 100, // Very fast, decentralized
+ private: 200,
+ trading: 100,
+ },
+ };
+ }
+
+ // ============================================================================
+ // VAULT & SUBACCOUNT SUPPORT
+ // ============================================================================
+
+ /**
+ * Set vault address for trading from vault
+ */
+ setVaultAddress(vaultAddress: string) {
+ this.exchange.options = {
+ ...this.exchange.options,
+ vaultAddress,
+ };
+ }
+
+ /**
+ * Set subaccount address
+ */
+ setSubAccountAddress(subAccountAddress: string) {
+ this.exchange.options = {
+ ...this.exchange.options,
+ subAccountAddress,
+ };
+ }
+
+ /**
+ * Get vault balance
+ */
+ async fetchVaultBalance(vaultAddress: string) {
+ try {
+ await this.ensureAuthenticated();
+ this.setVaultAddress(vaultAddress);
+ return await this.fetchBalance();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // ENHANCED ORDER METHODS (HyperLiquid-specific)
+ // ============================================================================
+
+ /**
+ * Create stop-loss order
+ * HyperLiquid uses stop-loss-limit orders
+ */
+ async createStopLossOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ stopPrice: number,
+ limitPrice?: number
+ ) {
+ const price = limitPrice || stopPrice;
+ return await this.createOrder(symbol, 'stop_limit', side, amount, price, {
+ stopPrice,
+ stopLossPrice: stopPrice,
+ });
+ }
+
+ /**
+ * Create take-profit order
+ */
+ async createTakeProfitOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ stopPrice: number,
+ limitPrice?: number
+ ) {
+ const price = limitPrice || stopPrice;
+ return await this.createOrder(symbol, 'stop_limit', side, amount, price, {
+ stopPrice,
+ takeProfitPrice: stopPrice,
+ });
+ }
+
+ /**
+ * Create reduce-only order
+ */
+ async createReduceOnlyOrder(
+ symbol: string,
+ type: OrderType,
+ side: OrderSide,
+ amount: number,
+ price?: number
+ ) {
+ return await this.createOrder(symbol, type, side, amount, price, {
+ reduceOnly: true,
+ });
+ }
+
+ /**
+ * Create post-only order (maker-only)
+ */
+ async createPostOnlyOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ price: number
+ ) {
+ return await this.createOrder(symbol, 'limit', side, amount, price, {
+ postOnly: true,
+ });
+ }
+
+ // ============================================================================
+ // LEVERAGE & MARGIN
+ // ============================================================================
+
+ /**
+ * Set leverage for symbol (1x to 50x)
+ */
+ async setLeverage(symbol: string, leverage: number) {
+ try {
+ await this.ensureAuthenticated();
+ if (leverage < 1 || leverage > 50) {
+ throw new Error('HyperLiquid leverage must be between 1x and 50x');
+ }
+ return await this.exchange.setLeverage(leverage, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Set margin mode (cross or isolated)
+ */
+ async setMarginMode(symbol: string, marginMode: 'cross' | 'isolated') {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.setMarginMode(marginMode, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // TRADING METHODS (Extended)
+ // ============================================================================
+
+ /**
+ * Fetch trading fee for specific symbol
+ */
+ async fetchTradingFee(symbol: string) {
+ try {
+ await this.ensureAuthenticated();
+ const fees = await this.exchange.fetchTradingFees();
+ return fees[symbol] || null;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch funding rates for multiple symbols
+ */
+ async fetchFundingRates(symbols?: string[]) {
+ try {
+ await this.ensureConnected();
+ if (!this.exchange.has['fetchFundingRates']) {
+ if (!symbols) {
+ const markets = await this.fetchMarkets();
+ symbols = markets.filter((m: any) => m.swap).map((m: any) => m.symbol);
+ }
+ const results: any = {};
+ for (const symbol of symbols) {
+ try {
+ results[symbol] = await this.fetchFundingRate(symbol);
+ } catch (e) {
+ // Skip symbols without funding rates
+ }
+ }
+ return results;
+ }
+ return await this.exchange.fetchFundingRates(symbols);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch account ledger
+ */
+ async fetchLedger(code?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchLedger(code, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Edit existing order
+ */
+ async editOrder(
+ orderId: string,
+ symbol: string,
+ type?: string,
+ side?: string,
+ amount?: number,
+ price?: number,
+ params?: any
+ ) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.editOrder(orderId, symbol, type as any, side as any, amount, price, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch specific order
+ */
+ async fetchOrder(orderId: string, symbol: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchOrder(orderId, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch orders by IDs
+ */
+ async fetchOrdersByIds(orderIds: string[], symbol?: string) {
+ try {
+ await this.ensureAuthenticated();
+ const orders = [];
+ for (const orderId of orderIds) {
+ if (!symbol) throw new Error('Symbol required');
+ const order = await this.fetchOrder(orderId, symbol);
+ orders.push(order);
+ }
+ return orders;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch order trades
+ */
+ async fetchOrderTrades(orderId: string, symbol: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchOrderTrades(orderId, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch my trades
+ */
+ async fetchMyTrades(symbol?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchMyTrades(symbol, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Cancel multiple orders
+ */
+ async cancelOrders(orderIds: string[], symbol?: string) {
+ try {
+ await this.ensureAuthenticated();
+ const results = [];
+ for (const orderId of orderIds) {
+ if (!symbol) throw new Error('Symbol required');
+ const result = await this.cancelOrder(orderId, symbol);
+ results.push(result);
+ }
+ return results;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Create market order with cost
+ * Note: HyperLiquid simulates market orders
+ */
+ async createMarketBuyOrderWithCost(symbol: string, cost: number) {
+ try {
+ await this.ensureAuthenticated();
+ // Fetch current price
+ const ticker = await this.fetchTicker(symbol);
+ const price = ticker.ask || ticker.last;
+ if (!price) throw new Error('Cannot determine price');
+
+ // Calculate amount with 5% slippage buffer
+ const amount = cost / (price * 1.05);
+
+ return await this.createOrder(symbol, 'market', 'buy', amount);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // BULK ORDER OPERATIONS (HyperLiquid-specific)
+ // ============================================================================
+
+ /**
+ * Create multiple orders in bulk (REST)
+ */
+ async createOrdersRequest(orders: Array<{
+ symbol: string;
+ type: string;
+ side: string;
+ amount: number;
+ price?: number;
+ params?: any;
+ }>) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['createOrders']) {
+ return await this.createOrders(orders as any);
+ }
+ return await (this.exchange as any).createOrdersRequest(orders);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Edit multiple orders in bulk
+ */
+ async editOrders(orders: Array<{
+ id: string;
+ symbol: string;
+ type?: string;
+ side?: string;
+ amount?: number;
+ price?: number;
+ params?: any;
+ }>) {
+ try {
+ await this.ensureAuthenticated();
+ const results = [];
+ for (const order of orders) {
+ const result = await this.editOrder(
+ order.id,
+ order.symbol,
+ order.type,
+ order.side,
+ order.amount,
+ order.price,
+ order.params
+ );
+ results.push(result);
+ }
+ return results;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Cancel orders request
+ */
+ async cancelOrdersRequest(orderIds: string[], symbol?: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.cancelOrders(orderIds, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Cancel orders for specific symbols
+ */
+ async cancelOrdersForSymbols(symbols: string[]) {
+ try {
+ await this.ensureAuthenticated();
+ const results = [];
+ for (const symbol of symbols) {
+ const canceled = await this.cancelAllOrders(symbol);
+ results.push(...canceled);
+ }
+ return results;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Cancel all orders after timeout (Dead Man's Switch)
+ */
+ async cancelAllOrdersAfter(timeout: number) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['cancelAllOrdersAfter']) {
+ throw new Error('cancelAllOrdersAfter not supported');
+ }
+ return await (this.exchange as any).cancelAllOrdersAfter(timeout);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // ORDER FETCHING (Extended)
+ // ============================================================================
+
+ /**
+ * Fetch single position for a symbol
+ */
+ async fetchPosition(symbol: string) {
+ try {
+ await this.ensureAuthenticated();
+ const positions = await this.fetchPositions([symbol]);
+ return positions.find((p: any) => p.symbol === symbol) || null;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch all orders (all states)
+ */
+ async fetchOrders(symbol?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchOrders']) {
+ const open = await this.fetchOpenOrders(symbol);
+ const closed = await this.fetchClosedOrders(symbol, limit);
+ return [...open, ...closed];
+ }
+ return await this.exchange.fetchOrders(symbol, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch canceled orders
+ */
+ async fetchCanceledOrders(symbol?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchCanceledOrders']) {
+ const orders = await this.fetchOrders(symbol, since, limit);
+ return orders.filter((o: any) => o.status === 'canceled');
+ }
+ return await (this.exchange as any).fetchCanceledOrders(symbol, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch canceled and closed orders
+ */
+ async fetchCanceledAndClosedOrders(symbol?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ const orders = await this.fetchOrders(symbol, since, limit);
+ return orders.filter((o: any) => o.status === 'canceled' || o.status === 'closed');
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // MARGIN OPERATIONS (Isolated margin)
+ // ============================================================================
+
+ /**
+ * Add margin to position
+ */
+ async addMargin(symbol: string, amount: number) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['addMargin']) {
+ throw new Error('addMargin not supported');
+ }
+ return await this.exchange.addMargin(symbol, amount);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Reduce margin from position
+ */
+ async reduceMargin(symbol: string, amount: number) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['reduceMargin']) {
+ throw new Error('reduceMargin not supported');
+ }
+ return await this.exchange.reduceMargin(symbol, amount);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // VAULT OPERATIONS (HyperLiquid-specific)
+ // ============================================================================
+
+ /**
+ * Create a new vault
+ */
+ async createVault(name: string, params?: any) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['createVault']) {
+ throw new Error('createVault not supported - use HyperLiquid web interface');
+ }
+ return await (this.exchange as any).createVault(name, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // MARKET DATA (Extended HyperLiquid methods)
+ // ============================================================================
+
+ /**
+ * Fetch HIP-3 markets (spot markets)
+ */
+ async fetchHip3Markets() {
+ try {
+ await this.ensureConnected();
+ if (!this.exchange.has['fetchHip3Markets']) {
+ return await this.fetchSpotMarkets();
+ }
+ return await (this.exchange as any).fetchHip3Markets();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch swap/perpetual markets
+ */
+ async fetchSwapMarkets() {
+ try {
+ await this.ensureConnected();
+ const markets = await this.fetchMarkets();
+ return markets.filter((m: any) => m.swap || m.type === 'swap');
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch spot markets
+ */
+ async fetchSpotMarkets() {
+ try {
+ await this.ensureConnected();
+ const markets = await this.fetchMarkets();
+ return markets.filter((m: any) => m.spot || m.type === 'spot');
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Calculate price precision for a symbol
+ */
+ calculatePricePrecision(symbol: string): number {
+ const market = this.exchange.markets[symbol];
+ if (!market) return 8;
+ return market.precision?.price || 8;
+ }
+
+ /**
+ * Fetch open interest for symbol
+ */
+ async fetchOpenInterest(symbol: string) {
+ try {
+ await this.ensureConnected();
+ if (!this.exchange.has['fetchOpenInterest']) {
+ throw new Error('fetchOpenInterest not supported');
+ }
+ return await this.exchange.fetchOpenInterest(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch open interests for multiple symbols
+ */
+ async fetchOpenInterests(symbols?: string[]) {
+ try {
+ await this.ensureConnected();
+ if (!this.exchange.has['fetchOpenInterests']) {
+ if (!symbols) throw new Error('Symbols required');
+ const results: any[] = [];
+ for (const symbol of symbols) {
+ const oi = await this.fetchOpenInterest(symbol);
+ results.push(oi);
+ }
+ return results;
+ }
+ return await (this.exchange as any).fetchOpenInterests(symbols);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch funding history
+ */
+ async fetchFundingHistory(symbol?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureConnected();
+ if (!this.exchange.has['fetchFundingHistory']) {
+ return await this.fetchFundingRateHistory(symbol!, since, limit);
+ }
+ return await (this.exchange as any).fetchFundingHistory(symbol, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Reserve request weight for rate limiting
+ */
+ reserveRequestWeight(weight: number) {
+ // HyperLiquid specific rate limit management
+ if ((this.exchange as any).reserveRequestWeight) {
+ return (this.exchange as any).reserveRequestWeight(weight);
+ }
+ return true;
+ }
+
+ // ============================================================================
+ // WEBSOCKET METHODS (Watch functions)
+ // ============================================================================
+
+ /**
+ * Create order via WebSocket
+ */
+ async createOrderWs(
+ symbol: string,
+ type: string,
+ side: string,
+ amount: number,
+ price?: number,
+ params?: any
+ ) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['createOrderWs']) {
+ return await this.createOrder(symbol, type as any, side as any, amount, price, params);
+ }
+ return await (this.exchange as any).createOrderWs(symbol, type, side, amount, price, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Create multiple orders via WebSocket
+ */
+ async createOrdersWs(orders: any[]) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['createOrdersWs']) {
+ return await this.createOrdersRequest(orders);
+ }
+ return await (this.exchange as any).createOrdersWs(orders);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Edit order via WebSocket
+ */
+ async editOrderWs(
+ orderId: string,
+ symbol: string,
+ type?: string,
+ side?: string,
+ amount?: number,
+ price?: number,
+ params?: any
+ ) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['editOrderWs']) {
+ return await this.editOrder(orderId, symbol, type, side, amount, price, params);
+ }
+ return await (this.exchange as any).editOrderWs(orderId, symbol, type, side, amount, price, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Cancel order via WebSocket
+ */
+ async cancelOrderWs(orderId: string, symbol: string, params?: any) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['cancelOrderWs']) {
+ return await this.cancelOrder(orderId, symbol);
+ }
+ return await (this.exchange as any).cancelOrderWs(orderId, symbol, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Cancel multiple orders via WebSocket
+ */
+ async cancelOrdersWs(orderIds: string[], symbol?: string, params?: any) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['cancelOrdersWs']) {
+ return await this.cancelOrders(orderIds, symbol);
+ }
+ return await (this.exchange as any).cancelOrdersWs(orderIds, symbol, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Watch order book (requires ccxt.pro)
+ */
+ async watchOrderBook(symbol: string, limit?: number) {
+ try {
+ if (!this.exchange.has['watchOrderBook']) {
+ throw new Error('watchOrderBook requires ccxt.pro package');
+ }
+ return await (this.exchange as any).watchOrderBook(symbol, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Unwatch order book
+ */
+ async unWatchOrderBook(symbol: string) {
+ try {
+ if (!this.exchange.has['unwatch']) {
+ return;
+ }
+ return await (this.exchange as any).unwatch('orderbook', symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Watch ticker (requires ccxt.pro)
+ */
+ async watchTicker(symbol: string) {
+ try {
+ if (!this.exchange.has['watchTicker']) {
+ throw new Error('watchTicker requires ccxt.pro package');
+ }
+ return await (this.exchange as any).watchTicker(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Watch multiple tickers
+ */
+ async watchTickers(symbols?: string[]) {
+ try {
+ if (!this.exchange.has['watchTickers']) {
+ throw new Error('watchTickers requires ccxt.pro package');
+ }
+ return await (this.exchange as any).watchTickers(symbols);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Unwatch tickers
+ */
+ async unWatchTickers(symbols?: string[]) {
+ try {
+ if (!this.exchange.has['unwatch']) {
+ return;
+ }
+ if (symbols) {
+ for (const symbol of symbols) {
+ await (this.exchange as any).unwatch('ticker', symbol);
+ }
+ }
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Watch my trades
+ */
+ async watchMyTrades(symbol?: string) {
+ try {
+ if (!this.exchange.has['watchMyTrades']) {
+ throw new Error('watchMyTrades requires ccxt.pro package');
+ }
+ return await (this.exchange as any).watchMyTrades(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Watch public trades
+ */
+ async watchTrades(symbol: string) {
+ try {
+ if (!this.exchange.has['watchTrades']) {
+ throw new Error('watchTrades requires ccxt.pro package');
+ }
+ return await (this.exchange as any).watchTrades(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Unwatch trades
+ */
+ async unWatchTrades(symbol: string) {
+ try {
+ if (!this.exchange.has['unwatch']) {
+ return;
+ }
+ return await (this.exchange as any).unwatch('trades', symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Watch OHLCV candles
+ */
+ async watchOHLCV(symbol: string, timeframe: string = '1m', since?: number, limit?: number) {
+ try {
+ if (!this.exchange.has['watchOHLCV']) {
+ throw new Error('watchOHLCV requires ccxt.pro package');
+ }
+ return await (this.exchange as any).watchOHLCV(symbol, timeframe, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Unwatch OHLCV candles
+ */
+ async unWatchOHLCV(symbol: string, timeframe: string = '1m') {
+ try {
+ if (!this.exchange.has['unwatch']) {
+ return;
+ }
+ return await (this.exchange as any).unwatch('ohlcv', symbol, timeframe);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Watch orders (requires ccxt.pro)
+ */
+ async watchOrders(symbol?: string) {
+ try {
+ if (!this.exchange.has['watchOrders']) {
+ throw new Error('watchOrders requires ccxt.pro package');
+ }
+ return await (this.exchange as any).watchOrders(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // DEPOSITS & WITHDRAWALS (L1 Bridge operations)
+ // ============================================================================
+
+ /**
+ * Fetch deposit address (L1 bridge address)
+ */
+ async fetchDepositAddress(currency: string, params?: any) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchDepositAddress(currency, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch deposits from L1
+ */
+ async fetchDeposits(currency?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchDeposits(currency, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch withdrawals to L1
+ */
+ async fetchWithdrawals(currency?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchWithdrawals(currency, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Withdraw to L1 (Arbitrum)
+ */
+ async withdraw(currency: string, amount: number, address: string, tag?: string, params?: any) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.withdraw(currency, amount, address, tag, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // TRANSFERS (Vault/Subaccount)
+ // ============================================================================
+
+ /**
+ * Transfer between accounts
+ */
+ async transfer(currency: string, amount: number, fromAccount: string, toAccount: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.transfer(currency, amount, fromAccount, toAccount);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // FUNDING RATES (Perpetuals)
+ // ============================================================================
+
+ /**
+ * Fetch funding rate
+ */
+ async fetchFundingRate(symbol: string) {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchFundingRate(symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch funding rate history
+ */
+ async fetchFundingRateHistory(symbol: string, since?: number, limit?: number) {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchFundingRateHistory(symbol, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // UTILITIES
+ // ============================================================================
+
+ /**
+ * Get popular HyperLiquid trading pairs
+ */
+ getPopularPairs(): string[] {
+ return [
+ 'BTC/USDC:USDC',
+ 'ETH/USDC:USDC',
+ 'SOL/USDC:USDC',
+ 'ARB/USDC:USDC',
+ 'AVAX/USDC:USDC',
+ 'MATIC/USDC:USDC',
+ 'OP/USDC:USDC',
+ 'DOGE/USDC:USDC',
+ 'LINK/USDC:USDC',
+ 'UNI/USDC:USDC',
+ ];
+ }
+
+ /**
+ * Get system status
+ */
+ async getSystemStatus() {
+ try {
+ return await this.fetchStatus();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Get server time
+ */
+ async getServerTime() {
+ try {
+ return await this.fetchTime();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Check if using Coincurve for faster signing
+ * (45ms -> 0.05ms signing time improvement)
+ */
+ isUsingCoincurve(): boolean {
+ return !!(this.exchange as any).coincurve;
+ }
+}
diff --git a/fincept-terminal-desktop/src/brokers/crypto/index.ts b/fincept-terminal-desktop/src/brokers/crypto/index.ts
new file mode 100644
index 000000000..43a94b0aa
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/crypto/index.ts
@@ -0,0 +1,104 @@
+/**
+ * Exchange Adapters
+ *
+ * Unified CCXT-based exchange integrations for Fincept Terminal
+ * Professional-grade architecture for trading, paper trading, and agentic systems
+ */
+
+// Core exports
+export * from './types';
+export { BaseExchangeAdapter } from './BaseExchangeAdapter';
+export { KrakenAdapter } from './kraken/KrakenAdapter';
+export { HyperLiquidAdapter } from './hyperliquid/HyperLiquidAdapter';
+
+// Paper Trading exports
+export * from './paper-trading';
+
+// Exchange registry
+import { KrakenAdapter } from './kraken/KrakenAdapter';
+import { HyperLiquidAdapter } from './hyperliquid/HyperLiquidAdapter';
+import type { ExchangeConfig } from './types';
+
+export const SUPPORTED_EXCHANGES = {
+ kraken: {
+ id: 'kraken',
+ name: 'Kraken',
+ adapter: KrakenAdapter,
+ type: 'centralized',
+ assetClass: 'crypto',
+ region: 'global',
+ features: {
+ spot: true,
+ margin: true,
+ futures: true,
+ staking: true,
+ earn: true,
+ },
+ },
+ hyperliquid: {
+ id: 'hyperliquid',
+ name: 'HyperLiquid',
+ adapter: HyperLiquidAdapter,
+ type: 'decentralized',
+ assetClass: 'crypto',
+ region: 'global',
+ features: {
+ spot: true,
+ margin: false,
+ futures: true, // Perpetuals
+ swap: true,
+ vault: true,
+ subaccounts: true,
+ },
+ },
+ // Future exchanges will be added here
+ // binance: { ... },
+ // coinbase: { ... },
+ // etc.
+} as const;
+
+export type SupportedExchangeId = keyof typeof SUPPORTED_EXCHANGES;
+
+/**
+ * Factory function to create exchange adapter
+ */
+export function createExchangeAdapter(
+ exchangeId: SupportedExchangeId,
+ config?: Partial<ExchangeConfig>
+) {
+ const exchange = SUPPORTED_EXCHANGES[exchangeId];
+ if (!exchange) {
+ throw new Error(`Exchange "${exchangeId}" is not supported`);
+ }
+
+ return new exchange.adapter({
+ exchange: exchangeId,
+ ...config,
+ });
+}
+
+/**
+ * Get list of all supported exchanges
+ */
+export function getupportedExchanges(): Array<{
+ id: string;
+ name: string;
+ type: string;
+ assetClass: string;
+ region: string;
+}> {
+ return Object.values(SUPPORTED_EXCHANGES).map(exchange => ({
+ id: exchange.id,
+ name: exchange.name,
+ type: exchange.type,
+ assetClass: exchange.assetClass,
+ region: exchange.region,
+ }));
+}
+
+/**
+ * Check if an exchange is supported
+ */
+export function isExchangeSupported(exchangeId: string): exchangeId is SupportedExchangeId {
+ return exchangeId in SUPPORTED_EXCHANGES;
+}
diff --git a/fincept-terminal-desktop/src/brokers/crypto/kraken/KrakenAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/kraken/KrakenAdapter.ts
new file mode 100644
index 000000000..4a24e97d8
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/crypto/kraken/KrakenAdapter.ts
@@ -0,0 +1,630 @@
+/**
+ * Kraken Exchange Adapter
+ *
+ * Professional-grade Kraken integration using CCXT
+ * Supports: Spot, Margin, Futures, Staking, Earn
+ */
+
+import ccxt from 'ccxt';
+import { BaseExchangeAdapter } from './BaseExchangeAdapter';
+import {
+ ExchangeConfig,
+ OrderType,
+ OrderSide,
+ OrderParams,
+ ExchangeCapabilities,
+} from './types';
+
+export class KrakenAdapter extends BaseExchangeAdapter {
+ constructor(config?: Partial<ExchangeConfig>) {
+ super({
+ exchange: 'kraken',
+ enableRateLimit: true,
+ timeout: 30000,
+ ...config,
+ });
+ }
+
+ // ============================================================================
+ // KRAKEN-SPECIFIC FEATURES
+ // ============================================================================
+
+ /**
+ * Get Kraken-specific capabilities
+ */
+ getCapabilities(): ExchangeCapabilities {
+ const base = super.getCapabilities();
+ return {
+ ...base,
+ spot: true,
+ margin: true,
+ futures: true,
+ swap: false,
+ options: false,
+
+ supportedOrderTypes: [
+ 'market',
+ 'limit',
+ 'stop',
+ 'stop_limit',
+ 'trailing_stop',
+ 'iceberg',
+ ],
+
+ leverageTrading: true,
+ stopOrders: true,
+ conditionalOrders: true,
+ algoOrders: true,
+
+ realtimeData: true,
+ historicalData: true,
+ websocketSupport: true,
+
+ rateLimits: {
+ public: 1000, // 1 req/sec
+ private: 3000, // 1 req/3sec
+ trading: 1000, // 1 req/sec
+ },
+ };
+ }
+
+ // ============================================================================
+ // ENHANCED ORDER METHODS
+ // ============================================================================
+
+ /**
+ * Create stop-loss order (Kraken-specific)
+ */
+ async createStopLossOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ stopPrice: number,
+ limitPrice?: number
+ ) {
+ const type: OrderType = limitPrice ? 'stop_limit' : 'stop';
+ return await this.createOrder(symbol, type, side, amount, limitPrice, {
+ stopPrice,
+ });
+ }
+
+ /**
+ * Create take-profit order (Kraken-specific)
+ */
+ async createTakeProfitOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ stopPrice: number,
+ limitPrice?: number
+ ) {
+ const type: OrderType = limitPrice ? 'stop_limit' : 'stop';
+ return await this.createOrder(symbol, type, side, amount, limitPrice, {
+ stopPrice,
+ trigger: 'last',
+ });
+ }
+
+ /**
+ * Create trailing stop order
+ */
+ async createTrailingStopOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ trailingPercent: number
+ ) {
+ return await this.createOrder(symbol, 'trailing_stop', side, amount, undefined, {
+ trailingPercent,
+ });
+ }
+
+ /**
+ * Create iceberg order (hidden liquidity)
+ */
+ async createIcebergOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ price: number,
+ visibleAmount: number
+ ) {
+ return await this.createOrder(symbol, 'iceberg', side, amount, price, {
+ icebergQty: visibleAmount,
+ });
+ }
+
+ // ============================================================================
+ // MARGIN TRADING
+ // ============================================================================
+
+ /**
+ * Set leverage for symbol
+ */
+ async setLeverage(symbol: string, leverage: number) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['setLeverage']) {
+ throw new Error('Leverage not supported');
+ }
+ return await this.exchange.setLeverage(leverage, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Create margin order
+ */
+ async createMarginOrder(
+ symbol: string,
+ type: OrderType,
+ side: OrderSide,
+ amount: number,
+ price?: number,
+ leverage?: number
+ ) {
+ const params: OrderParams = {
+ leverage,
+ marginMode: 'cross',
+ };
+ return await this.createOrder(symbol, type, side, amount, price, params);
+ }
+
+ /**
+ * Fetch margin balance
+ */
+ async fetchMarginBalance() {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchBalance({ type: 'margin' });
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // FUNDING & TRANSFERS
+ // ============================================================================
+
+ /**
+ * Transfer between spot and margin accounts
+ */
+ async transfer(
+ currency: string,
+ amount: number,
+ fromAccount: 'spot' | 'margin' | 'futures',
+ toAccount: 'spot' | 'margin' | 'futures'
+ ) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['transfer']) {
+ throw new Error('Transfers not supported');
+ }
+ return await this.exchange.transfer(currency, amount, fromAccount, toAccount);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch funding history
+ */
+ async fetchFundingHistory(symbol?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ if (!this.exchange.has['fetchFundingHistory']) {
+ throw new Error('Funding history not available');
+ }
+ return await this.exchange.fetchFundingHistory(symbol, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // STAKING & EARN (Kraken-specific)
+ // ============================================================================
+
+ /**
+ * Fetch staking assets
+ */
+ async fetchStakingAssets() {
+ try {
+ await this.ensureAuthenticated();
+ // Use private API endpoint
+ return await (this.exchange as any).privatePostStakingAssets();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Stake asset
+ */
+ async stakeAsset(asset: string, amount: number, method: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await (this.exchange as any).privatePostStakingStake({
+ asset,
+ amount: amount.toString(),
+ method,
+ });
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Unstake asset
+ */
+ async unstakeAsset(asset: string, amount: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await (this.exchange as any).privatePostStakingUnstake({
+ asset,
+ amount: amount.toString(),
+ });
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // KRAKEN FUTURES
+ // ============================================================================
+
+ /**
+ * Fetch futures markets
+ */
+ async fetchFuturesMarkets() {
+ try {
+ // Switch to futures endpoint
+ const futuresExchange = new ccxt.krakenfutures({
+ apiKey: this.exchange.apiKey,
+ secret: this.exchange.secret,
+ enableRateLimit: true,
+ });
+ return await futuresExchange.loadMarkets();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // HISTORICAL DATA (Enhanced)
+ // ============================================================================
+
+ /**
+ * Fetch historical OHLCV with extended options
+ */
+ async fetchHistoricalOHLCV(
+ symbol: string,
+ timeframe: '1m' | '5m' | '15m' | '30m' | '1h' | '4h' | '1d' | '1w',
+ since?: number,
+ limit: number = 720
+ ) {
+ try {
+ await this.ensureConnected();
+ return await this.exchange.fetchOHLCV(symbol, timeframe, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch recent trades with extended data
+ */
+ async fetchRecentTrades(symbol: string, limit: number = 100) {
+ try {
+ await this.ensureConnected();
+ const trades = await this.exchange.fetchTrades(symbol, undefined, limit);
+ return trades.map(trade => ({
+ ...trade,
+ exchange: 'kraken',
+ timestamp: trade.timestamp || Date.now(),
+ }));
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // ACCOUNT INFORMATION & FEES
+ // ============================================================================
+
+ /**
+ * Fetch trading fees
+ */
+ async fetchTradingFees() {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchTradingFees();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch trading fee for specific symbol
+ */
+ async fetchTradingFee(symbol: string) {
+ try {
+ await this.ensureAuthenticated();
+ const fees = await this.exchange.fetchTradingFees();
+ return fees[symbol] || null;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch account ledger
+ */
+ async fetchLedger(code?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchLedger(code, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // DEPOSITS & WITHDRAWALS (Kraken-specific)
+ // ============================================================================
+
+ /**
+ * Fetch deposit address
+ */
+ async fetchDepositAddress(currency: string, network?: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchDepositAddress(currency, { network });
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Create deposit address
+ */
+ async createDepositAddress(currency: string, network?: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.createDepositAddress(currency, { network });
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch deposit methods
+ */
+ async fetchDepositMethods(currency?: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await (this.exchange as any).fetchDepositMethods(currency);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch deposits
+ */
+ async fetchDeposits(currency?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchDeposits(currency, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch withdrawals
+ */
+ async fetchWithdrawals(currency?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchWithdrawals(currency, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Withdraw funds
+ */
+ async withdraw(currency: string, amount: number, address: string, tag?: string, network?: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.withdraw(currency, amount, address, tag, { network });
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // ADVANCED ORDER METHODS (Kraken-specific)
+ // ============================================================================
+
+ /**
+ * Edit existing order
+ */
+ async editOrder(
+ orderId: string,
+ symbol: string,
+ type?: string,
+ side?: string,
+ amount?: number,
+ price?: number,
+ params?: any
+ ) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.editOrder(orderId, symbol, type as any, side as any, amount, price, params);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch specific order
+ */
+ async fetchOrder(orderId: string, symbol: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchOrder(orderId, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch orders by IDs
+ */
+ async fetchOrdersByIds(orderIds: string[], symbol?: string) {
+ try {
+ await this.ensureAuthenticated();
+ const orders = [];
+ for (const orderId of orderIds) {
+ if (!symbol) throw new Error('Symbol required for Kraken fetchOrdersByIds');
+ const order = await this.fetchOrder(orderId, symbol);
+ orders.push(order);
+ }
+ return orders;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch order trades
+ */
+ async fetchOrderTrades(orderId: string, symbol: string) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchOrderTrades(orderId, symbol);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Fetch my trades
+ */
+ async fetchMyTrades(symbol?: string, since?: number, limit?: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await this.exchange.fetchMyTrades(symbol, since, limit);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Cancel multiple orders
+ */
+ async cancelOrders(orderIds: string[], symbol?: string) {
+ try {
+ await this.ensureAuthenticated();
+ const results = [];
+ for (const orderId of orderIds) {
+ if (!symbol) throw new Error('Symbol required for Kraken bulk cancel');
+ const result = await this.cancelOrder(orderId, symbol);
+ results.push(result);
+ }
+ return results;
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Cancel all orders after timeout (Dead Man's Switch)
+ */
+ async cancelAllOrdersAfter(timeout: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await (this.exchange as any).cancelAllOrdersAfter(timeout);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Create market order with cost (buy specific USD amount)
+ */
+ async createMarketBuyOrderWithCost(symbol: string, cost: number) {
+ try {
+ await this.ensureAuthenticated();
+ return await (this.exchange as any).createMarketBuyOrderWithCost(symbol, cost);
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ // ============================================================================
+ // UTILITIES
+ // ============================================================================
+
+ /**
+ * Get Kraken system status
+ */
+ async getSystemStatus() {
+ try {
+ return await (this.exchange as any).publicGetSystemStatus();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Get server time
+ */
+ async getServerTime() {
+ try {
+ return await this.exchange.fetchTime();
+ } catch (error) {
+ throw this.handleError(error);
+ }
+ }
+
+ /**
+ * Convert Kraken pair format to standard format
+ * Example: XXBTZUSD -> BTC/USD
+ */
+ normalizeSymbol(krakenSymbol: string): string {
+ const markets = this.exchange.markets;
+ for (const symbol in markets) {
+ if (markets[symbol].id === krakenSymbol) {
+ return symbol;
+ }
+ }
+ return krakenSymbol;
+ }
+
+ /**
+ * Get popular Kraken trading pairs
+ */
+ getPopularPairs(): string[] {
+ return [
+ 'BTC/USD',
+ 'ETH/USD',
+ 'XRP/USD',
+ 'SOL/USD',
+ 'ADA/USD',
+ 'MATIC/USD',
+ 'AVAX/USD',
+ 'DOT/USD',
+ 'LINK/USD',
+ 'UNI/USD',
+ 'BTC/EUR',
+ 'ETH/EUR',
+ 'BTC/USDT',
+ 'ETH/USDT',
+ ];
+ }
+}
diff --git a/fincept-terminal-desktop/src/brokers/crypto/types.ts b/fincept-terminal-desktop/src/brokers/crypto/types.ts
new file mode 100644
index 000000000..baeff05a6
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/crypto/types.ts
@@ -0,0 +1,298 @@
+/**
+ * Unified Exchange Types
+ *
+ * Professional-grade type definitions for all exchange operations
+ * Used across trading, paper trading, and agentic trading systems
+ */
+
+import type { Exchange, Market, Ticker, OrderBook, Trade, OHLCV, Balance, Order, Position } from 'ccxt';
+
+// ============================================================================
+// CORE EXCHANGE INTERFACE
+// ============================================================================
+
+export interface IExchangeAdapter {
+ // Metadata
+ id: string;
+ name: string;
+
+ // Connection Management
+ connect(): Promise<void>;
+ disconnect(): Promise<void>;
+ isConnected(): boolean;
+
+ // Authentication
+ authenticate(credentials: ExchangeCredentials): Promise<void>;
+ isAuthenticated(): boolean;
+
+ // Market Data
+ fetchMarkets(): Promise<Market[]>;
+ fetchTicker(symbol: string): Promise<Ticker>;
+ fetchTickers(symbols?: string[]): Promise<Record<string, Ticker>>;
+ fetchOrderBook(symbol: string, limit?: number): Promise<OrderBook>;
+ fetchTrades(symbol: string, limit?: number): Promise<Trade[]>;
+ fetchOHLCV(symbol: string, timeframe: string, limit?: number): Promise<OHLCV[]>;
+
+ // Account & Balance
+ fetchBalance(): Promise<Balance>;
+ fetchPositions(symbols?: string[]): Promise<Position[]>;
+
+ // Trading
+ createOrder(symbol: string, type: OrderType, side: OrderSide, amount: number, price?: number, params?: OrderParams): Promise<Order>;
+ cancelOrder(orderId: string, symbol: string): Promise<Order>;
+ cancelAllOrders(symbol?: string): Promise<Order[]>;
+ fetchOrder(orderId: string, symbol: string): Promise<Order>;
+ fetchOpenOrders(symbol?: string): Promise<Order[]>;
+ fetchClosedOrders(symbol?: string, limit?: number): Promise<Order[]>;
+
+ // Real-time (WebSocket)
+ watchTicker?(symbol: string): AsyncGenerator<Ticker>;
+ watchOrderBook?(symbol: string, limit?: number): AsyncGenerator<OrderBook>;
+ watchTrades?(symbol: string): AsyncGenerator<Trade[]>;
+ watchBalance?(): AsyncGenerator<Balance>;
+ watchOrders?(symbol?: string): AsyncGenerator<Order[]>;
+}
+
+// ============================================================================
+// CREDENTIALS & AUTHENTICATION
+// ============================================================================
+
+export interface ExchangeCredentials {
+ apiKey: string;
+ secret: string;
+ password?: string; // Some exchanges require
+ uid?: string; // Some exchanges require
+ privateKey?: string; // For some DEX integrations
+ walletAddress?: string;
+ testnet?: boolean;
+}
+
+export interface ExchangeConfig {
+ exchange: string;
+ credentials?: ExchangeCredentials;
+ sandbox?: boolean;
+ enableRateLimit?: boolean;
+ timeout?: number;
+ proxy?: string;
+ options?: Record<string, any>;
+}
+
+// ============================================================================
+// ORDER TYPES
+// ============================================================================
+
+export type OrderType =
+ | 'market'
+ | 'limit'
+ | 'stop'
+ | 'stop_limit'
+ | 'trailing_stop'
+ | 'iceberg'
+ | 'twap'
+ | 'vwap';
+
+export type OrderSide = 'buy' | 'sell';
+
+export type OrderStatus =
+ | 'open'
+ | 'closed'
+ | 'canceled'
+ | 'expired'
+ | 'rejected'
+ | 'pending';
+
+export type TimeInForce = 'GTC' | 'IOC' | 'FOK' | 'PO';
+
+export interface OrderParams {
+ timeInForce?: TimeInForce;
+ postOnly?: boolean;
+ reduceOnly?: boolean;
+ stopPrice?: number;
+ triggerPrice?: number;
+ trailingAmount?: number;
+ trailingPercent?: number;
+ icebergQty?: number;
+ clientOrderId?: string;
+ leverage?: number;
+ marginMode?: 'cross' | 'isolated';
+ [key: string]: any;
+}
+
+// ============================================================================
+// MARKET DATA TYPES
+// ============================================================================
+
+export interface ExtendedTicker extends Ticker {
+ fundingRate?: number;
+ fundingTimestamp?: number;
+ openInterest?: number;
+ volume24h?: number;
+ volumeQuote?: number;
+}
+
+export interface ExtendedOrderBook {
+ bids: Array<[number, number]>;
+ asks: Array<[number, number]>;
+ symbol?: string;
+ checksum?: number;
+ timestamp?: number;
+ datetime?: string;
+ nonce?: number;
+}
+
+// ============================================================================
+// TRADING SESSION
+// ============================================================================
+
+export interface TradingSession {
+ sessionId: string;
+ exchange: string;
+ mode: 'live' | 'paper' | 'backtest';
+ startTime: number;
+ endTime?: number;
+ initialBalance: number;
+ currentBalance: number;
+ pnl: number;
+ trades: number;
+ winRate: number;
+ sharpeRatio?: number;
+}
+
+// ============================================================================
+// POSITION & RISK MANAGEMENT
+// ============================================================================
+
+export interface ExtendedPosition extends Position {
+ entryPrice: number;
+ markPrice: number;
+ liquidationPrice?: number;
+ leverage: number;
+ marginMode: 'cross' | 'isolated';
+ unrealizedPnl: number;
+ realizedPnl: number;
+ marginRatio?: number;
+ maintenanceMargin?: number;
+ timestamp: number;
+}
+
+export interface RiskMetrics {
+ totalExposure: number;
+ availableMargin: number;
+ marginLevel: number;
+ maxDrawdown: number;
+ positionCount: number;
+ largestPosition: number;
+ concentrationRisk: number;
+}
+
+// ============================================================================
+// EXCHANGE CAPABILITIES
+// ============================================================================
+
+export interface ExchangeCapabilities {
+ // Trading Features
+ spot: boolean;
+ margin: boolean;
+ futures: boolean;
+ options: boolean;
+ swap: boolean;
+
+ // Order Types
+ supportedOrderTypes: OrderType[];
+ supportedTimeInForce: TimeInForce[];
+
+ // Advanced Features
+ leverageTrading: boolean;
+ stopOrders: boolean;
+ conditionalOrders: boolean;
+ algoOrders: boolean;
+
+ // Market Data
+ realtimeData: boolean;
+ historicalData: boolean;
+ websocketSupport: boolean;
+
+ // Account
+ multiAccount: boolean;
+ subAccounts: boolean;
+ portfolioMargin: boolean;
+
+ // API Features
+ restApi: boolean;
+ websocketApi: boolean;
+ fixApi: boolean;
+
+ // Rate Limits
+ rateLimits: {
+ public: number;
+ private: number;
+ trading: number;
+ };
+}
+
+// ============================================================================
+// ERROR HANDLING
+// ============================================================================
+
+export class ExchangeError extends Error {
+ constructor(
+ message: string,
+ public code: string,
+ public exchange: string,
+ public details?: any
+ ) {
+ super(message);
+ this.name = 'ExchangeError';
+ }
+}
+
+export class AuthenticationError extends ExchangeError {
+ constructor(message: string, exchange: string, details?: any) {
+ super(message, 'AUTH_ERROR', exchange, details);
+ this.name = 'AuthenticationError';
+ }
+}
+
+export class RateLimitError extends ExchangeError {
+ constructor(message: string, exchange: string, details?: any) {
+ super(message, 'RATE_LIMIT', exchange, details);
+ this.name = 'RateLimitError';
+ }
+}
+
+export class InsufficientFunds extends ExchangeError {
+ constructor(message: string, exchange: string, details?: any) {
+ super(message, 'INSUFFICIENT_FUNDS', exchange, details);
+ this.name = 'InsufficientFunds';
+ }
+}
+
+export class OrderNotFound extends ExchangeError {
+ constructor(message: string, exchange: string, details?: any) {
+ super(message, 'ORDER_NOT_FOUND', exchange, details);
+ this.name = 'OrderNotFound';
+ }
+}
+
+// ============================================================================
+// EVENTS
+// ============================================================================
+
+export type ExchangeEvent =
+ | 'connected'
+ | 'disconnected'
+ | 'authenticated'
+ | 'error'
+ | 'ticker'
+ | 'orderbook'
+ | 'trade'
+ | 'order'
+ | 'balance'
+ | 'position';
+
+export interface ExchangeEventData {
+ event: ExchangeEvent;
+ exchange: string;
+ timestamp: number;
+ data: any;
+}
diff --git a/fincept-terminal-desktop/src/brokers/index.ts b/fincept-terminal-desktop/src/brokers/index.ts
new file mode 100644
index 000000000..cb4ea4d41
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/index.ts
@@ -0,0 +1,71 @@
+/**
+ * Brokers Integration Module
+ *
+ * Professional-grade broker integrations for Fincept Terminal
+ * Organized by asset class: Crypto exchanges vs Stock brokers
+ */
+
+// ============================================================================
+// CRYPTO EXCHANGES (CCXT-based)
+// ============================================================================
+export * from './crypto';
+
+// ============================================================================
+// STOCK BROKERS
+// ============================================================================
+export * from './stocks';
+
+// ============================================================================
+// UNIFIED BROKER REGISTRY
+// ============================================================================
+import { SUPPORTED_EXCHANGES } from './crypto';
+
+export const SUPPORTED_BROKERS = {
+ // Crypto Exchanges
+ ...Object.fromEntries(
+ Object.entries(SUPPORTED_EXCHANGES).map(([id, exchange]) => [
+ id,
+ {
+ id: exchange.id,
+ name: exchange.name,
+ type: exchange.assetClass,
+ region: exchange.region,
+ supported: true,
+ category: 'crypto',
+ },
+ ])
+ ),
+
+ // Stock Brokers
+ zerodha: {
+ id: 'zerodha',
+ name: 'Zerodha Kite',
+ type: 'stocks',
+ region: 'india',
+ supported: true,
+ category: 'stocks',
+ },
+} as const;
+
+export type BrokerId = keyof typeof SUPPORTED_BROKERS;
+
+/**
+ * Get brokers by category
+ */
+export function getBrokersByCategory(category: 'crypto' | 'stocks') {
+ return Object.values(SUPPORTED_BROKERS).filter(b => b.category === category);
+}
+
+/**
+ * Get all crypto exchanges
+ */
+export function getCryptoExchanges() {
+ return getBrokersByCategory('crypto');
+}
+
+/**
+ * Get all stock brokers
+ */
+export function getStockBrokers() {
+ return getBrokersByCategory('stocks');
+}
diff --git a/fincept-terminal-desktop/src/brokers/stocks/index.ts b/fincept-terminal-desktop/src/brokers/stocks/index.ts
new file mode 100644
index 000000000..55d9c5ef1
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/index.ts
@@ -0,0 +1,84 @@
+/**
+ * Zerodha Kite Connect Integration
+ *
+ * Indian stock broker integration using Kite Connect API v3
+ * Supports equity, F&O, commodity, currency, and mutual funds
+ */
+
+export { KiteConnectAdapter, createKiteAdapter } from './kiteAdapter';
+export type {
+ KiteConfig,
+ SessionData,
+ OrderParams as KiteOrderParams,
+ OrderResponse,
+ Order,
+ Trade,
+ Quote,
+ Holding,
+ Position,
+ HistoricalParams,
+ CandleData,
+ GTTParams,
+ GTTResponse,
+ GTT,
+ AlertParams,
+ Alert,
+ MarginOrder,
+ MarginResponse,
+ MFOrder,
+ MFHolding,
+ MFSip,
+} from './kiteAdapter';
+
+// Re-export utilities
+export {
+ RateLimiter,
+ WebhookHandler,
+ BatchOperations,
+ SessionManager,
+ FileSessionStorage,
+ PortfolioTracker,
+ KiteError,
+ KiteAuthError,
+ KiteRateLimitError,
+} from './kiteAdapter';
+
+// Broker metadata
+export const ZERODHA_BROKER = {
+ id: 'zerodha',
+ name: 'Zerodha Kite',
+ version: '3.0.0',
+ region: 'india',
+ supported: {
+ equity: true,
+ fno: true,
+ commodity: true,
+ currency: true,
+ mutualFunds: true,
+ websocket: true,
+ },
+ features: {
+ restApi: true,
+ websocket: true,
+ streaming: true,
+ historicalData: true,
+ realTimeData: true,
+ advancedOrders: true,
+ gtt: true,
+ alerts: true,
+ marginCalculator: true,
+ },
+ apis: {
+ rest: 'https://api.kite.trade',
+ websocket: 'wss://ws.kite.trade',
+ login: 'https://kite.zerodha.com/connect/login',
+ },
+ rateLimits: {
+ rest: {
+ public: 1000, // 1 request per second
+ private: 3000, // 1 request per 3 seconds
+ },
+ },
+};
+
+export default ZERODHA_BROKER;
diff --git a/fincept-terminal-desktop/src/stockBrokers/india/zerodhaKite/kiteAdapter.tsx b/fincept-terminal-desktop/src/brokers/stocks/kiteAdapter.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/stockBrokers/india/zerodhaKite/kiteAdapter.tsx
rename to fincept-terminal-desktop/src/brokers/stocks/kiteAdapter.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/DocsTab.tsx.old b/fincept-terminal-desktop/src/components/tabs/DocsTab.tsx.old
deleted file mode 100644
index 172d2bc43..000000000
--- a/fincept-terminal-desktop/src/components/tabs/DocsTab.tsx.old
+++ /dev/null
@@ -1,612 +0,0 @@
-import React, { useState } from 'react';
-import { Book, Search, ChevronRight, Code, FileText, Zap, TrendingUp, Database, Terminal } from 'lucide-react';
-
-interface DocSection {
- id: string;
- title: string;
- icon: any;
- subsections: {
- id: string;
- title: string;
- content: string;
- codeExample?: string;
- }[];
-}
-
-export default function DocsTab() {
- const [selectedSection, setSelectedSection] = useState('getting-started');
- const [searchQuery, setSearchQuery] = useState('');
- const [expandedSections, setExpandedSections] = useState<string[]>(['finscript']);
-
- const C = {
- ORANGE: '#FF8C00',
- WHITE: '#FFFFFF',
- GREEN: '#00FF00',
- BLUE: '#4169E1',
- CYAN: '#00FFFF',
- YELLOW: '#FFFF00',
- GRAY: '#787878',
- DARK_BG: '#000000',
- PANEL_BG: '#0a0a0a',
- CODE_BG: '#1a1a1a'
- };
-
- const docs: DocSection[] = [
- {
- id: 'finscript',
- title: 'FinScript Language',
- icon: Code,
- subsections: [
- {
- id: 'getting-started',
- title: 'Getting Started',
- content: `FinScript is a domain-specific language (DSL) designed for financial analysis and algorithmic trading. It provides a simple, intuitive syntax for defining trading strategies, calculating technical indicators, and generating trading signals.
-
-**Key Features:**
-• Simple syntax inspired by Pine Script
-• Built-in technical indicators (EMA, SMA, WMA, RSI, MACD, etc.)
-• Real-time data integration with Yahoo Finance
-• Automatic chart generation
-• Buy/Sell signal generation
-• Backtesting capabilities`,
- codeExample: `// Your first FinScript program
-if ema(AAPL, 21) > wma(AAPL, 50) {
- buy "Bullish crossover signal"
-}
-
-plot ema(AAPL, 21), "EMA 21"
-plot wma(AAPL, 50), "WMA 50"`
- },
- {
- id: 'syntax',
- title: 'Basic Syntax',
- content: `FinScript uses a clean, declarative syntax. Here are the core language constructs:
-
-**Comments:**
-Use // for single-line comments
-
-**Variables:**
-Variables are automatically typed based on indicator functions
-
-**Conditionals:**
-Use if statements to define trading logic
-
-**Functions:**
-Built-in functions for technical analysis`,
- codeExample: `// Comments explain your strategy
-// Variables are created by indicators
-fast_ema = ema(TSLA, 12)
-slow_ema = ema(TSLA, 26)
-
-// Conditionals for signals
-if fast_ema > slow_ema {
- buy "Fast EMA crossed above Slow EMA"
-}
-
-if fast_ema < slow_ema {
- sell "Fast EMA crossed below Slow EMA"
-}`
- },
- {
- id: 'indicators',
- title: 'Technical Indicators',
- content: `FinScript provides a comprehensive suite of technical indicators for market analysis:
-
-**Moving Averages:**
-• ema(symbol, period) - Exponential Moving Average
-• sma(symbol, period) - Simple Moving Average
-• wma(symbol, period) - Weighted Moving Average
-
-**Momentum Indicators:**
-• rsi(symbol, period) - Relative Strength Index
-• macd(symbol, fast, slow, signal) - MACD
-• stochastic(symbol, period) - Stochastic Oscillator
-
-**Volatility:**
-• atr(symbol, period) - Average True Range
-• bollinger(symbol, period, std) - Bollinger Bands
-
-**Volume:**
-• volume(symbol) - Trading Volume
-• obv(symbol) - On-Balance Volume`,
- codeExample: `// Using multiple indicators
-price = close(AAPL)
-ema_fast = ema(AAPL, 12)
-ema_slow = ema(AAPL, 26)
-rsi_value = rsi(AAPL, 14)
-
-// Combine indicators for strategy
-if ema_fast > ema_slow and rsi_value < 30 {
- buy "Oversold with bullish trend"
-}
-
-plot ema_fast, "EMA 12"
-plot ema_slow, "EMA 26"
-plot rsi_value, "RSI 14"`
- },
- {
- id: 'plotting',
- title: 'Visualization & Plotting',
- content: `FinScript provides powerful charting capabilities to visualize your strategies:
-
-**plot** - Plot indicator values
-Syntax: plot indicator, "label"
-
-**plot_candlestick** - Generate OHLC candlestick charts
-Syntax: plot_candlestick symbol, "chart_title"
-
-**plot_line** - Draw custom lines
-Syntax: plot_line value, "label", color
-
-Charts are automatically generated and saved as PNG files in your working directory.`,
- codeExample: `// Visualize your strategy
-symbol = MSFT
-
-// Plot multiple indicators
-plot ema(symbol, 7), "EMA 7"
-plot ema(symbol, 21), "EMA 21"
-plot sma(symbol, 50), "SMA 50"
-
-// Generate candlestick chart
-plot_candlestick symbol, "Microsoft Stock Chart"
-
-// Add support/resistance lines
-plot_line 300.0, "Resistance", "red"
-plot_line 250.0, "Support", "green"`
- },
- {
- id: 'signals',
- title: 'Trading Signals',
- content: `Generate buy and sell signals based on your trading logic:
-
-**buy** - Generate a buy signal
-Syntax: buy "reason for buying"
-
-**sell** - Generate a sell signal
-Syntax: sell "reason for selling"
-
-Signals are logged with timestamps and can trigger automated trading when integrated with brokers.
-
-**Best Practices:**
-• Always include descriptive messages
-• Use multiple confirmation indicators
-• Implement risk management
-• Test thoroughly with historical data`,
- codeExample: `// Crossover strategy with signals
-fast = ema(GOOGL, 12)
-slow = ema(GOOGL, 26)
-momentum = rsi(GOOGL, 14)
-
-// Buy signal with multiple confirmations
-if fast > slow and momentum > 50 {
- buy "EMA crossover with positive momentum"
-}
-
-// Sell signal with risk management
-if fast < slow or momentum > 70 {
- sell "EMA crossover or overbought condition"
-}
-
-// Plot for visual confirmation
-plot fast, "Fast EMA"
-plot slow, "Slow EMA"`
- }
- ]
- },
- {
- id: 'api',
- title: 'API Reference',
- icon: Database,
- subsections: [
- {
- id: 'data-api',
- title: 'Data API',
- content: `Access real-time and historical market data through our unified API:
-
-**Endpoints:**
-• GET /api/v1/quote/{symbol} - Get latest quote
-• GET /api/v1/historical/{symbol} - Historical OHLCV data
-• GET /api/v1/indicators/{symbol} - Calculated indicators
-• POST /api/v1/backtest - Run strategy backtest
-
-**Authentication:**
-Use API keys in the X-API-Key header
-
-**Rate Limits:**
-• Free tier: 100 requests/hour
-• Pro tier: 1000 requests/hour
-• Enterprise: Unlimited`,
- codeExample: `// Example API calls
-// Get real-time quote
-fetch('https://api.fincept.com/v1/quote/AAPL', {
- headers: {
- 'X-API-Key': 'your_api_key_here'
- }
-})
-
-// Get historical data
-fetch('https://api.fincept.com/v1/historical/AAPL?period=1y', {
- headers: {
- 'X-API-Key': 'your_api_key_here'
- }
-})`
- },
- {
- id: 'websocket',
- title: 'WebSocket Streaming',
- content: `Real-time data streaming via WebSocket for live market data:
-
-**Connection:**
-wss://stream.fincept.com/v1/quotes
-
-**Subscribe to symbols:**
-Send JSON: {"action": "subscribe", "symbols": ["AAPL", "TSLA"]}
-
-**Message Format:**
-Receive real-time tick data as JSON
-
-**Features:**
-• Sub-millisecond latency
-• Level 2 order book data
-• Trade execution updates
-• Market depth information`,
- codeExample: `// WebSocket connection example
-const ws = new WebSocket('wss://stream.fincept.com/v1/quotes');
-
-ws.onopen = () => {
- // Subscribe to symbols
- ws.send(JSON.stringify({
- action: 'subscribe',
- symbols: ['AAPL', 'TSLA', 'GOOGL']
- }));
-};
-
-ws.onmessage = (event) => {
- const data = JSON.parse(event.data);
- console.log('Live quote:', data);
-};`
- }
- ]
- },
- {
- id: 'terminal',
- title: 'Terminal Features',
- icon: Terminal,
- subsections: [
- {
- id: 'shortcuts',
- title: 'Keyboard Shortcuts',
- content: `Master the terminal with these keyboard shortcuts:
-
-**Global Shortcuts:**
-• F1 - Help
-• F2 - Markets
-• F3 - News
-• F4 - Portfolio
-• F5 - Analytics
-• F11 - Fullscreen toggle
-• Ctrl+S - Save current file
-• Ctrl+N - New file
-• Ctrl+O - Open file
-
-**Editor Shortcuts:**
-• Ctrl+/ - Comment/Uncomment
-• Ctrl+F - Find
-• Ctrl+R - Run code
-• Ctrl+Shift+K - Clear output
-
-**Navigation:**
-• Ctrl+Tab - Next tab
-• Ctrl+Shift+Tab - Previous tab
-• Ctrl+W - Close tab`,
- codeExample: `// Quick actions in editor
-// Press Ctrl+/ to toggle comments
-// if ema(AAPL, 21) > sma(AAPL, 50) {
-// buy "EMA crosses SMA"
-// }
-
-// Press Ctrl+R to execute code
-plot ema(AAPL, 21), "EMA 21"
-
-// Press Ctrl+S to save file`
- },
- {
- id: 'customization',
- title: 'Customization',
- content: `Customize the terminal to match your workflow:
-
-**Themes:**
-• Bloomberg Classic (default)
-• Dark Mode
-• Light Mode
-• Custom themes via CSS
-
-**Layouts:**
-• Single panel
-• Dual panel (editor + output)
-• Triple panel (editor + output + charts)
-• Customizable panel sizes
-
-**Settings:**
-• Font size and family
-• Tab size (spaces)
-• Auto-save interval
-• Data refresh rate
-• Chart colors and styles`,
- codeExample: `// Example settings.json
-{
- "theme": "bloomberg-classic",
- "editor": {
- "fontSize": 14,
- "fontFamily": "Consolas",
- "tabSize": 4,
- "autoSave": true,
- "autoSaveInterval": 5000
- },
- "terminal": {
- "refreshRate": 1000,
- "enableNotifications": true
- }
-}`
- }
- ]
- },
- {
- id: 'tutorials',
- title: 'Tutorials',
- icon: Book,
- subsections: [
- {
- id: 'first-strategy',
- title: 'Build Your First Strategy',
- content: `Let's build a simple moving average crossover strategy from scratch:
-
-**Step 1:** Define your indicators
-Calculate fast and slow moving averages
-
-**Step 2:** Create trading logic
-Buy when fast MA crosses above slow MA
-Sell when fast MA crosses below slow MA
-
-**Step 3:** Add visualization
-Plot your indicators on a chart
-
-**Step 4:** Run and test
-Execute your strategy and analyze results
-
-This is one of the most popular strategies used by traders worldwide!`,
- codeExample: `// Complete MA Crossover Strategy
-symbol = AAPL
-
-// Step 1: Define indicators
-fast_ma = ema(symbol, 12)
-slow_ma = ema(symbol, 26)
-
-// Step 2: Trading logic
-if fast_ma > slow_ma {
- buy "Bullish crossover - Fast MA above Slow MA"
-}
-
-if fast_ma < slow_ma {
- sell "Bearish crossover - Fast MA below Slow MA"
-}
-
-// Step 3: Visualization
-plot fast_ma, "Fast EMA (12)"
-plot slow_ma, "Slow EMA (26)"
-plot_candlestick symbol, "Apple Stock"
-
-// Done! Press Ctrl+R to run`
- },
- {
- id: 'advanced-strategy',
- title: 'Advanced: Multi-Indicator Strategy',
- content: `Build a sophisticated strategy combining multiple indicators:
-
-**Indicators Used:**
-• EMA (12, 26) for trend
-• RSI (14) for momentum
-• Bollinger Bands for volatility
-• Volume for confirmation
-
-**Strategy Rules:**
-• Buy: Bullish trend + oversold + high volume
-• Sell: Bearish trend + overbought OR stop loss
-
-This demonstrates how to combine multiple signals for robust trading decisions.`,
- codeExample: `// Advanced Multi-Indicator Strategy
-symbol = TSLA
-
-// Indicators
-ema_fast = ema(symbol, 12)
-ema_slow = ema(symbol, 26)
-rsi_val = rsi(symbol, 14)
-vol = volume(symbol)
-avg_vol = sma(vol, 20)
-
-// Buy conditions (all must be true)
-trend_bullish = ema_fast > ema_slow
-oversold = rsi_val < 30
-volume_spike = vol > avg_vol * 1.5
-
-if trend_bullish and oversold and volume_spike {
- buy "Strong buy: Bullish trend + oversold + volume"
-}
-
-// Sell conditions (any can trigger)
-trend_bearish = ema_fast < ema_slow
-overbought = rsi_val > 70
-
-if trend_bearish or overbought {
- sell "Exit: Trend reversal or overbought"
-}
-
-// Visualize everything
-plot ema_fast, "EMA 12"
-plot ema_slow, "EMA 26"
-plot rsi_val, "RSI"`
- }
- ]
- }
- ];
-
- const toggleSection = (sectionId: string) => {
- setExpandedSections(prev =>
- prev.includes(sectionId)
- ? prev.filter(id => id !== sectionId)
- : [...prev, sectionId]
- );
- };
-
- const filteredDocs = docs.map(section => ({
- ...section,
- subsections: section.subsections.filter(sub =>
- searchQuery === '' ||
- sub.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
- sub.content.toLowerCase().includes(searchQuery.toLowerCase())
- )
- })).filter(section => section.subsections.length > 0);
-
- const activeSubsection = docs
- .flatMap(s => s.subsections)
- .find(sub => sub.id === selectedSection);
-
- return (
- <div style={{ width: '100%', height: '100%', backgroundColor: C.DARK_BG, color: C.WHITE, fontFamily: 'Consolas, monospace', display: 'flex', flexDirection: 'column' }}>
- <style>{`
- .docs-scroll::-webkit-scrollbar { width: 8px; }
- .docs-scroll::-webkit-scrollbar-track { background: #1a1a1a; }
- .docs-scroll::-webkit-scrollbar-thumb { background: #404040; border-radius: 4px; }
- .docs-scroll::-webkit-scrollbar-thumb:hover { background: #525252; }
-
- .docs-content h1 { color: ${C.ORANGE}; font-size: 24px; margin: 24px 0 16px 0; }
- .docs-content h2 { color: ${C.CYAN}; font-size: 18px; margin: 20px 0 12px 0; }
- .docs-content p { line-height: 1.8; margin: 12px 0; }
- .docs-content ul { margin: 12px 0; padding-left: 24px; }
- .docs-content li { margin: 6px 0; line-height: 1.6; }
- `}</style>
-
- {/* Header */}
- <div style={{ backgroundColor: C.PANEL_BG, borderBottom: `2px solid ${C.GRAY}`, padding: '8px 16px', flexShrink: 0 }}>
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '12px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
- <Book size={20} style={{ color: C.ORANGE }} />
- <span style={{ color: C.ORANGE, fontWeight: 'bold', fontSize: '16px' }}>DOCUMENTATION</span>
- <span style={{ color: C.GRAY }}>|</span>
- <span style={{ color: C.CYAN, fontSize: '12px' }}>Complete Guide & API Reference</span>
- </div>
- </div>
- </div>
-
- {/* Search Bar */}
- <div style={{ backgroundColor: C.PANEL_BG, borderBottom: `1px solid ${C.GRAY}`, padding: '12px 16px', flexShrink: 0 }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', backgroundColor: C.DARK_BG, border: `1px solid ${C.GRAY}`, padding: '8px 12px' }}>
- <Search size={16} style={{ color: C.GRAY, flexShrink: 0 }} />
- <input
- type="text"
- placeholder="Search documentation..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- style={{ flex: 1, backgroundColor: 'transparent', border: 'none', outline: 'none', color: C.WHITE, fontSize: '13px', fontFamily: 'Consolas, monospace', minWidth: '150px' }}
- />
- </div>
- </div>
-
- {/* Main Content */}
- <div style={{ flex: 1, display: 'flex', minHeight: 0, flexWrap: 'wrap' }}>
- {/* Sidebar Navigation */}
- <div className="docs-scroll" style={{ flex: '0 0 280px', minWidth: '240px', maxWidth: '320px', borderRight: `1px solid ${C.GRAY}`, backgroundColor: C.PANEL_BG, overflowY: 'auto', padding: '12px' }}>
- {filteredDocs.map(section => (
- <div key={section.id} style={{ marginBottom: '8px' }}>
- <div
- onClick={() => toggleSection(section.id)}
- style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '8px', backgroundColor: C.DARK_BG, cursor: 'pointer', border: `1px solid ${C.GRAY}` }}
- >
- <section.icon size={14} style={{ color: C.ORANGE }} />
- <span style={{ flex: 1, fontSize: '12px', fontWeight: 'bold', color: C.WHITE }}>{section.title}</span>
- <ChevronRight
- size={14}
- style={{ color: C.GRAY, transform: expandedSections.includes(section.id) ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform 0.2s' }}
- />
- </div>
- {expandedSections.includes(section.id) && (
- <div style={{ marginTop: '4px', marginLeft: '12px' }}>
- {section.subsections.map(sub => (
- <div
- key={sub.id}
- onClick={() => setSelectedSection(sub.id)}
- style={{ padding: '8px 12px', fontSize: '11px', color: selectedSection === sub.id ? C.ORANGE : C.GRAY, backgroundColor: selectedSection === sub.id ? C.DARK_BG : 'transparent', cursor: 'pointer', borderLeft: `2px solid ${selectedSection === sub.id ? C.ORANGE : 'transparent'}` }}
- >
- {sub.title}
- </div>
- ))}
- </div>
- )}
- </div>
- ))}
- </div>
-
- {/* Content Area */}
- <div className="docs-scroll" style={{ flex: '1 1 500px', minWidth: '400px', overflowY: 'auto', padding: '24px', backgroundColor: '#050505' }}>
- <div style={{ maxWidth: '900px', margin: '0 auto' }}>
- {activeSubsection ? (
- <>
- <h1 style={{ color: C.ORANGE, fontSize: '28px', marginBottom: '16px', borderBottom: `2px solid ${C.ORANGE}`, paddingBottom: '12px' }}>
- {activeSubsection.title}
- </h1>
- <div className="docs-content" style={{ fontSize: '14px', lineHeight: '1.8', color: C.WHITE }}>
- {activeSubsection.content.split('\n\n').map((para, idx) => (
- <p key={idx} style={{ marginBottom: '16px', whiteSpace: 'pre-wrap' }}>
- {para.split('\n').map((line, lineIdx) => {
- if (line.startsWith('**') && line.endsWith('**')) {
- return <div key={lineIdx} style={{ color: C.CYAN, fontWeight: 'bold', marginTop: '16px', marginBottom: '8px' }}>{line.replace(/\*\*/g, '')}</div>;
- }
- if (line.startsWith('•')) {
- return <li key={lineIdx} style={{ marginLeft: '20px', marginBottom: '4px' }}>{line.substring(1).trim()}</li>;
- }
- return <span key={lineIdx}>{line}<br /></span>;
- })}
- </p>
- ))}
- </div>
-
- {activeSubsection.codeExample && (
- <div style={{ marginTop: '24px' }}>
- <div style={{ color: C.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Code size={16} />
- CODE EXAMPLE
- </div>
- <pre style={{ backgroundColor: C.CODE_BG, border: `1px solid ${C.GRAY}`, padding: '16px', borderRadius: '4px', overflowX: 'auto', fontSize: '13px', lineHeight: '1.6', color: C.GREEN }}>
- <code>{activeSubsection.codeExample}</code>
- </pre>
- </div>
- )}
- </>
- ) : (
- <div style={{ textAlign: 'center', paddingTop: '60px', color: C.GRAY }}>
- <Book size={48} style={{ marginBottom: '16px', opacity: 0.5 }} />
- <div style={{ fontSize: '16px' }}>Select a topic from the sidebar</div>
- </div>
- )}
- </div>
- </div>
- </div>
-
- {/* Footer */}
- <div style={{ borderTop: `2px solid ${C.ORANGE}`, backgroundColor: C.PANEL_BG, padding: '8px 16px', fontSize: '11px', flexShrink: 0 }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '12px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flexWrap: 'wrap' }}>
- <span style={{ color: C.ORANGE, fontWeight: 'bold' }}>FINCEPT DOCS v3.0</span>
- <span style={{ color: C.GRAY }}>|</span>
- <span style={{ color: C.CYAN }}>FinScript Language Reference</span>
- <span style={{ color: C.GRAY }}>|</span>
- <span style={{ color: C.BLUE }}>API Documentation</span>
- </div>
- <div style={{ color: C.GRAY }}>
- {activeSubsection ? activeSubsection.title : 'Browse Documentation'}
- </div>
- </div>
- </div>
- </div>
- );
-}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/MarketsTab.old.tsx b/fincept-terminal-desktop/src/components/tabs/MarketsTab.old.tsx
deleted file mode 100644
index 06184ca73..000000000
--- a/fincept-terminal-desktop/src/components/tabs/MarketsTab.old.tsx
+++ /dev/null
@@ -1,524 +0,0 @@
-import React, { useState, useEffect } from 'react';
-
-const MarketsTab: React.FC = () => {
- const [currentTime, setCurrentTime] = useState(new Date());
- const [lastUpdate, setLastUpdate] = useState(new Date());
- const [isUpdating, setIsUpdating] = useState(false);
- const [autoUpdate, setAutoUpdate] = useState(true);
-
- // Bloomberg color scheme (exact from Python)
- const BLOOMBERG_ORANGE = '#FFA500';
- const BLOOMBERG_WHITE = '#FFFFFF';
- const BLOOMBERG_RED = '#FF0000';
- const BLOOMBERG_GREEN = '#00C800';
- const BLOOMBERG_GRAY = '#787878';
- const BLOOMBERG_DARK_BG = '#1a1a1a';
- const BLOOMBERG_PANEL_BG = '#000000';
-
- // Market data (exact structure from Python)
- const marketData: { [key: string]: string[][] } = {
- 'Stock Indices': [
- ['S&P 500', '5232.35', '+23.45', '+0.45%', '+2.1%', '+5.4%'],
- ['Nasdaq 100', '16412.87', '-15.23', '-0.09%', '+1.8%', '+7.2%'],
- ['Dow Jones', '38546.12', '+156.78', '+0.41%', '+1.5%', '+3.9%'],
- ['Russell 2000', '2087.45', '+8.90', '+0.43%', '+2.3%', '+4.1%'],
- ['VIX', '18.23', '-0.45', '-2.41%', '-5.2%', '-8.7%'],
- ['FTSE 100', '7623.98', '+12.34', '+0.16%', '+0.8%', '+2.3%'],
- ['DAX 40', '18245.67', '+89.23', '+0.49%', '+1.2%', '+4.6%'],
- ['Nikkei 225', '35897.45', '-123.45', '-0.34%', '-0.5%', '+1.8%'],
- ['CAC 40', '7890.12', '+45.67', '+0.58%', '+1.8%', '+4.2%'],
- ['Hang Seng', '18654.23', '-89.45', '-0.48%', '-1.2%', '+2.8%']
- ],
- 'Forex': [
- ['EUR/USD', '1.0840', '+0.0023', '+0.21%', '+0.8%', '+2.1%'],
- ['GBP/USD', '1.2567', '-0.0012', '-0.10%', '-0.3%', '+1.5%'],
- ['USD/JPY', '151.45', '+0.35', '+0.23%', '+1.2%', '+3.4%'],
- ['USD/CHF', '0.8923', '-0.0034', '-0.38%', '-0.7%', '-1.2%'],
- ['USD/CAD', '1.3578', '+0.0089', '+0.66%', '+0.4%', '+1.8%'],
- ['AUD/USD', '0.6634', '+0.0067', '+1.02%', '+2.1%', '+4.3%'],
- ['NZD/USD', '0.6089', '-0.0034', '-0.56%', '-0.8%', '+1.2%'],
- ['EUR/GBP', '0.8623', '+0.0012', '+0.14%', '+0.3%', '+0.9%'],
- ['EUR/JPY', '164.23', '+0.89', '+0.54%', '+1.8%', '+5.1%'],
- ['GBP/JPY', '190.45', '-1.23', '-0.64%', '-0.9%', '+2.3%']
- ],
- 'Commodities': [
- ['Gold', '2312.80', '+12.45', '+0.54%', '+1.8%', '+5.2%'],
- ['Silver', '28.45', '-0.67', '-2.30%', '-1.2%', '+3.1%'],
- ['Crude Oil (WTI)', '78.35', '-1.23', '-1.55%', '-2.8%', '-0.5%'],
- ['Brent Crude', '82.10', '-0.89', '-1.07%', '-2.1%', '+1.2%'],
- ['Natural Gas', '3.45', '+0.12', '+3.60%', '+8.2%', '+12.4%'],
- ['Copper', '4.23', '+0.045', '+1.08%', '+2.3%', '+6.7%'],
- ['Platinum', '987.50', '+8.90', '+0.91%', '+2.1%', '+4.8%'],
- ['Palladium', '1045.20', '-12.45', '-1.18%', '-2.3%', '-5.1%'],
- ['Wheat', '567.80', '+5.67', '+1.01%', '+3.2%', '+7.9%'],
- ['Corn', '478.90', '-3.45', '-0.72%', '-1.8%', '+2.4%']
- ],
- 'Bonds': [
- ['US 10Y Treasury', '4.35%', '+0.02', '+0.46%', '+1.2%', '+3.4%'],
- ['US 30Y Treasury', '4.52%', '+0.01', '+0.22%', '+0.8%', '+2.1%'],
- ['US 2Y Treasury', '4.89%', '-0.03', '-0.61%', '-0.5%', '+1.8%'],
- ['Germany 10Y', '2.45%', '+0.01', '+0.41%', '+0.6%', '+1.9%'],
- ['UK 10Y', '4.12%', '-0.02', '-0.48%', '-0.3%', '+2.3%'],
- ['Japan 10Y', '0.78%', '+0.01', '+1.30%', '+2.1%', '+8.7%'],
- ['France 10Y', '2.98%', '+0.02', '+0.67%', '+0.9%', '+2.8%'],
- ['Italy 10Y', '4.23%', '-0.01', '-0.24%', '-0.2%', '+1.5%'],
- ['Spain 10Y', '3.67%', '+0.03', '+0.82%', '+1.1%', '+3.2%'],
- ['Canada 10Y', '3.89%', '+0.01', '+0.26%', '+0.7%', '+2.1%']
- ],
- 'ETFs': [
- ['SPY (S&P 500)', '523.45', '+2.34', '+0.45%', '+2.1%', '+5.4%'],
- ['QQQ (Nasdaq)', '412.67', '-1.23', '-0.30%', '+1.8%', '+7.2%'],
- ['DIA (Dow)', '385.23', '+1.56', '+0.41%', '+1.5%', '+3.9%'],
- ['EEM (Emerging)', '41.78', '+0.34', '+0.82%', '+3.2%', '+6.8%'],
- ['GLD (Gold)', '231.45', '+1.23', '+0.53%', '+1.8%', '+5.1%'],
- ['XLK (Tech)', '198.90', '-0.89', '-0.45%', '+2.3%', '+8.9%'],
- ['XLE (Energy)', '89.34', '+1.45', '+1.65%', '+3.8%', '+7.2%'],
- ['XLF (Finance)', '42.56', '-0.67', '-1.55%', '-1.2%', '+2.1%'],
- ['XLV (Health)', '156.78', '+0.98', '+0.63%', '+1.1%', '+3.7%'],
- ['VNQ (REIT)', '78.90', '-1.12', '-1.40%', '-2.3%', '+1.8%']
- ],
- 'Cryptocurrencies': [
- ['Bitcoin', '67890.45', '+1234.56', '+1.85%', '+8.2%', '+15.7%'],
- ['Ethereum', '3789.23', '-67.89', '-1.76%', '+5.4%', '+12.3%'],
- ['Binance Coin', '567.89', '+12.34', '+2.22%', '+6.8%', '+18.9%'],
- ['Solana', '234.56', '+8.90', '+3.94%', '+12.1%', '+25.6%'],
- ['Dogecoin', '0.1234', '-0.0045', '-3.52%', '-2.1%', '+8.7%'],
- ['Polygon', '1.23', '+0.045', '+3.80%', '+9.8%', '+21.4%'],
- ['Chainlink', '23.45', '+0.89', '+3.94%', '+7.2%', '+14.8%'],
- ['Cardano', '0.67', '-0.023', '-3.32%', '-1.8%', '+5.4%'],
- ['Polkadot', '12.34', '+0.56', '+4.76%', '+8.9%', '+19.2%'],
- ['Avalanche', '45.67', '-1.23', '-2.62%', '-3.1%', '+11.7%']
- ]
- };
-
- // Regional data (exact from Python)
- const regionalData: { [key: string]: string[][] } = {
- 'India': [
- ['RELIANCE.NS', 'Reliance Industries', '2500.45', '+23.45', '+0.95%'],
- ['TCS.NS', 'Tata Consultancy', '3456.78', '-12.34', '-0.36%'],
- ['HDFCBANK.NS', 'HDFC Bank', '1678.90', '+8.90', '+0.53%'],
- ['INFY.NS', 'Infosys', '1234.56', '+15.67', '+1.29%'],
- ['HINDUNILVR.NS', 'Hindustan Unilever', '2345.67', '-5.43', '-0.23%'],
- ['ICICIBANK.NS', 'ICICI Bank', '987.65', '+12.34', '+1.27%'],
- ['SBIN.NS', 'State Bank of India', '678.90', '+3.45', '+0.51%'],
- ['BHARTIARTL.NS', 'Bharti Airtel', '876.54', '-7.89', '-0.89%']
- ],
- 'China': [
- ['BABA', 'Alibaba Group', '85.67', '+2.34', '+2.81%'],
- ['PDD', 'PDD Holdings', '123.45', '-1.23', '-0.99%'],
- ['JD', 'JD.com', '34.56', '+0.89', '+2.64%'],
- ['BIDU', 'Baidu', '145.67', '+3.45', '+2.43%'],
- ['TCEHY', 'Tencent Holdings', '45.78', '-0.67', '-1.44%'],
- ['NIO', 'NIO Inc', '12.34', '+0.45', '+3.78%'],
- ['LI', 'Li Auto', '23.45', '+1.23', '+5.54%'],
- ['XPEV', 'XPeng', '15.67', '-0.89', '-5.38%']
- ],
- 'United States': [
- ['AAPL', 'Apple Inc', '175.43', '+2.34', '+1.35%'],
- ['MSFT', 'Microsoft Corp', '420.67', '+4.12', '+0.99%'],
- ['GOOGL', 'Alphabet Inc', '140.23', '-1.23', '-0.87%'],
- ['AMZN', 'Amazon.com', '145.32', '+1.89', '+1.32%'],
- ['NVDA', 'NVIDIA Corp', '800.45', '+12.45', '+1.58%'],
- ['META', 'Meta Platforms', '345.67', '-2.34', '-0.67%'],
- ['TSLA', 'Tesla Inc', '200.78', '-5.67', '-2.75%'],
- ['JPM', 'JPMorgan Chase', '156.89', '+1.23', '+0.79%']
- ]
- };
-
- useEffect(() => {
- const timer = setInterval(() => {
- setCurrentTime(new Date());
- if (autoUpdate) {
- setIsUpdating(true);
- setLastUpdate(new Date());
- setTimeout(() => setIsUpdating(false), 1000);
- }
- }, 5000);
- return () => clearInterval(timer);
- }, [autoUpdate]);
-
- // Create market panel (responsive layout)
- const createMarketPanel = (title: string, data: string[][]) => (
- <div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- flex: '1 1 calc(33.333% - 16px)',
- minWidth: '300px',
- maxWidth: '600px',
- height: '280px',
- margin: '8px',
- display: 'flex',
- flexDirection: 'column'
- }}>
- {/* Panel Header */}
- <div style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_ORANGE,
- padding: '8px',
- fontSize: '14px',
- fontWeight: 'bold',
- textAlign: 'center',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
- }}>
- {title.toUpperCase()}
- </div>
-
- {/* Table Header */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
- gap: '4px',
- padding: '4px 8px',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontSize: '12px',
- fontWeight: 'bold',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
- }}>
- <div>SYMBOL</div>
- <div style={{ textAlign: 'right' }}>PRICE</div>
- <div style={{ textAlign: 'right' }}>CHANGE</div>
- <div style={{ textAlign: 'right' }}>%CHG</div>
- <div style={{ textAlign: 'right' }}>7D</div>
- <div style={{ textAlign: 'right' }}>30D</div>
- </div>
-
- {/* Data Rows */}
- <div style={{ flex: 1, overflow: 'auto' }}>
- {data.map((row, index) => (
- <div key={index} style={{
- display: 'grid',
- gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
- gap: '4px',
- padding: '2px 8px',
- fontSize: '10px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
- borderBottom: `1px solid rgba(120,120,120,0.3)`,
- minHeight: '18px',
- alignItems: 'center'
- }}>
- <div style={{ color: BLOOMBERG_WHITE }}>{row[0]}</div>
- <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{row[1]}</div>
- <div style={{
- color: row[2].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[2]}</div>
- <div style={{
- color: row[3].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[3]}</div>
- <div style={{
- color: row[4].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[4]}</div>
- <div style={{
- color: row[5].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[5]}</div>
- </div>
- ))}
- </div>
- </div>
- );
-
- // Create regional panel (responsive layout)
- const createRegionalPanel = (title: string, data: string[][]) => (
- <div style={{
- backgroundColor: BLOOMBERG_PANEL_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- flex: '1 1 calc(33.333% - 16px)',
- minWidth: '300px',
- maxWidth: '600px',
- height: '300px',
- margin: '8px',
- display: 'flex',
- flexDirection: 'column'
- }}>
- {/* Panel Header */}
- <div style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_ORANGE,
- padding: '8px',
- fontSize: '14px',
- fontWeight: 'bold',
- textAlign: 'center',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
- }}>
- {title.toUpperCase()} - LIVE DATA
- </div>
-
- {/* Table Header */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
- gap: '4px',
- padding: '4px 8px',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontSize: '12px',
- fontWeight: 'bold',
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`
- }}>
- <div>SYMBOL</div>
- <div>NAME</div>
- <div style={{ textAlign: 'right' }}>PRICE</div>
- <div style={{ textAlign: 'right' }}>CHANGE</div>
- <div style={{ textAlign: 'right' }}>%CHG</div>
- </div>
-
- {/* Data Rows */}
- <div style={{ flex: 1, overflow: 'auto' }}>
- {data.map((row, index) => (
- <div key={index} style={{
- display: 'grid',
- gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
- gap: '4px',
- padding: '2px 8px',
- fontSize: '10px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
- borderBottom: `1px solid rgba(120,120,120,0.3)`,
- minHeight: '18px',
- alignItems: 'center'
- }}>
- <div style={{ color: BLOOMBERG_WHITE }}>{row[0]}</div>
- <div style={{ color: BLOOMBERG_WHITE, overflow: 'hidden', textOverflow: 'ellipsis' }}>{row[1]}</div>
- <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{row[2]}</div>
- <div style={{
- color: row[3].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[3]}</div>
- <div style={{
- color: row[4].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
- textAlign: 'right'
- }}>{row[4]}</div>
- </div>
- ))}
- </div>
- </div>
- );
-
- const categories = Object.keys(marketData);
-
- return (
- <div style={{
- height: '100%',
- backgroundColor: BLOOMBERG_DARK_BG,
- color: BLOOMBERG_WHITE,
- fontFamily: 'Consolas, monospace',
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column'
- }}>
- <style>{`
- /* Custom scrollbar styles */
- *::-webkit-scrollbar {
- width: 8px;
- height: 8px;
- }
- *::-webkit-scrollbar-track {
- background: #1a1a1a;
- }
- *::-webkit-scrollbar-thumb {
- background: #404040;
- border-radius: 4px;
- }
- *::-webkit-scrollbar-thumb:hover {
- background: #525252;
- }
- `}</style>
- {/* Header Bar - Responsive */}
- <div style={{
- display: 'flex',
- alignItems: 'center',
- flexWrap: 'wrap',
- padding: '8px 12px',
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
- fontSize: '13px',
- gap: '8px',
- flexShrink: 0
- }}>
- <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>FINCEPT</span>
- <span style={{ color: BLOOMBERG_WHITE }}>MARKET TERMINAL</span>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <input
- type="text"
- placeholder="Search Symbol"
- style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
- padding: '4px 8px',
- flex: '0 1 200px',
- minWidth: '120px',
- fontSize: '11px'
- }}
- />
- <button style={{
- backgroundColor: BLOOMBERG_ORANGE,
- color: 'black',
- border: 'none',
- padding: '4px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- minWidth: '70px'
- }}>
- SEARCH
- </button>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <span style={{ color: BLOOMBERG_WHITE, fontSize: '11px' }}>
- {currentTime.toISOString().replace('T', ' ').substring(0, 19)}
- </span>
- </div>
-
- {/* Control Panel - Responsive */}
- <div style={{
- display: 'flex',
- alignItems: 'center',
- flexWrap: 'wrap',
- padding: '8px 12px',
- backgroundColor: BLOOMBERG_PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
- fontSize: '12px',
- gap: '8px',
- flexShrink: 0
- }}>
- <button
- onClick={() => { setIsUpdating(true); setLastUpdate(new Date()); setTimeout(() => setIsUpdating(false), 1000); }}
- style={{
- backgroundColor: BLOOMBERG_ORANGE,
- color: 'black',
- border: 'none',
- padding: '4px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- minWidth: '70px'
- }}
- >
- REFRESH
- </button>
- <button
- onClick={() => setAutoUpdate(!autoUpdate)}
- style={{
- backgroundColor: autoUpdate ? BLOOMBERG_GREEN : BLOOMBERG_GRAY,
- color: 'black',
- border: 'none',
- padding: '4px 12px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- minWidth: '70px'
- }}
- >
- AUTO {autoUpdate ? 'ON' : 'OFF'}
- </button>
- <select style={{
- backgroundColor: BLOOMBERG_DARK_BG,
- border: `1px solid ${BLOOMBERG_GRAY}`,
- color: BLOOMBERG_WHITE,
- padding: '4px 8px',
- fontSize: '11px',
- minWidth: '70px',
- cursor: 'pointer'
- }}>
- <option>1 min</option>
- <option>5 min</option>
- <option>10 min</option>
- <option>30 min</option>
- </select>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <span style={{ color: BLOOMBERG_GRAY, fontSize: '11px' }}>LAST UPDATE:</span>
- <span style={{ color: BLOOMBERG_WHITE, fontSize: '11px' }}>
- {lastUpdate.toTimeString().substring(0, 8)}
- </span>
- <span style={{ color: BLOOMBERG_GRAY }}>|</span>
- <span style={{ color: isUpdating ? BLOOMBERG_ORANGE : BLOOMBERG_GREEN, fontSize: '14px' }}>●</span>
- <span style={{ color: isUpdating ? BLOOMBERG_ORANGE : BLOOMBERG_GREEN, fontSize: '11px', fontWeight: 'bold' }}>
- {isUpdating ? 'UPDATING' : 'LIVE'}
- </span>
- </div>
-
- {/* Main Content - Responsive */}
- <div style={{
- flex: 1,
- overflow: 'auto',
- padding: '12px',
- display: 'flex',
- flexDirection: 'column'
- }}>
- {/* Global Markets Section */}
- <div style={{
- color: BLOOMBERG_ORANGE,
- fontSize: '14px',
- fontWeight: 'bold',
- marginBottom: '8px',
- letterSpacing: '0.5px'
- }}>
- GLOBAL MARKETS
- </div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '16px' }}></div>
-
- {/* Responsive Market Grid */}
- <div style={{
- display: 'flex',
- flexWrap: 'wrap',
- gap: '0',
- marginBottom: '24px'
- }}>
- {categories.map(category =>
- createMarketPanel(category, marketData[category])
- )}
- </div>
-
- {/* Regional Markets Section */}
- <div style={{
- color: BLOOMBERG_ORANGE,
- fontSize: '14px',
- fontWeight: 'bold',
- marginBottom: '8px',
- marginTop: '16px',
- letterSpacing: '0.5px'
- }}>
- REGIONAL MARKETS - LIVE DATA
- </div>
- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '16px' }}></div>
-
- {/* Responsive Regional Panels */}
- <div style={{
- display: 'flex',
- flexWrap: 'wrap',
- gap: '0'
- }}>
- {Object.keys(regionalData).map(region =>
- createRegionalPanel(region, regionalData[region])
- )}
- </div>
- </div>
-
- {/* Status Bar - Responsive */}
- <div style={{
- borderTop: `1px solid ${BLOOMBERG_GRAY}`,
- backgroundColor: BLOOMBERG_PANEL_BG,
- padding: '6px 12px',
- fontSize: '10px',
- color: BLOOMBERG_GRAY,
- flexShrink: 0
- }}>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- flexWrap: 'wrap',
- gap: '8px'
- }}>
- <span>Data provided by Bloomberg Terminal API | Updates every 5 seconds</span>
- <span style={{ whiteSpace: 'nowrap' }}>Connected: {Object.keys(regionalData).length} regional markets</span>
- </div>
- </div>
- </div>
- );
-};
-
-export default MarketsTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx.backup b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx.backup
deleted file mode 100644
index d711f18aa..000000000
--- a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx.backup
+++ /dev/null
@@ -1,1793 +0,0 @@
-import React, { useState } from 'react';
-import {
- FileText,
- Download,
- Save,
- Type,
- BarChart3,
- Table,
- Image as ImageIcon,
- Trash2,
- Copy,
- AlignLeft,
- Code,
- Minus,
- FolderOpen,
- Check,
- Plus,
- RefreshCw,
- Edit2,
- Move,
- Columns as ColumnsIcon,
- Layout,
- BookOpen,
- FileX
-} from 'lucide-react';
-import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';
-import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
-import { CSS } from '@dnd-kit/utilities';
-import { reportService, ReportTemplate, ReportComponent } from '@/services/reportService';
-import { save, open } from '@tauri-apps/plugin-dialog';
-import { toast } from 'sonner';
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
-import { Button } from '@/components/ui/button';
-
-// Bloomberg color palette
-const BLOOMBERG_COLORS = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- RED: '#ef4444',
- GREEN: '#10b981',
- YELLOW: '#fbbf24',
- GRAY: '#787878',
- BLUE: '#3b82f6',
- CYAN: '#06b6d4',
- DARK_BG: '#0a0a0a',
- PANEL_BG: '#1a1a1a',
- BORDER: '#333333',
-};
-
-// Sortable component wrapper
-function SortableComponent({ component, onEdit, onDelete, onDuplicate, isSelected }: {
- component: ReportComponent;
- onEdit: (id: string) => void;
- onDelete: (id: string) => void;
- onDuplicate: (id: string) => void;
- isSelected: boolean;
-}) {
- const {
- attributes,
- listeners,
- setNodeRef,
- transform,
- transition,
- } = useSortable({ id: component.id });
-
- const style = {
- transform: CSS.Transform.toString(transform),
- transition,
- };
-
- const getComponentIcon = () => {
- switch (component.type) {
- case 'heading': return <Type size={10} />;
- case 'text': return <AlignLeft size={10} />;
- case 'chart': return <BarChart3 size={10} />;
- case 'table': return <Table size={10} />;
- case 'image': return <ImageIcon size={10} />;
- case 'code': return <Code size={10} />;
- case 'divider': return <Minus size={10} />;
- default: return <FileText size={10} />;
- }
- };
-
- return (
- <div
- ref={setNodeRef}
- style={{
- ...style,
- backgroundColor: isSelected ? '#2a2a2a' : 'transparent',
- borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- padding: '6px 8px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- cursor: 'pointer',
- borderLeft: isSelected ? `2px solid ${BLOOMBERG_COLORS.ORANGE}` : 'none'
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>
- <div {...attributes} {...listeners} style={{ color: BLOOMBERG_COLORS.GRAY, cursor: 'move', display: 'flex' }}>
- <Move size={12} />
- </div>
- <div style={{ color: BLOOMBERG_COLORS.CYAN, display: 'flex' }}>
- {getComponentIcon()}
- </div>
- <span style={{ color: BLOOMBERG_COLORS.ORANGE, fontSize: '9px', fontWeight: 'bold' }}>
- {component.type.toUpperCase()}
- </span>
- <span style={{ color: BLOOMBERG_COLORS.GRAY, fontSize: '9px', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
- {component.content ? component.content.substring(0, 20) : 'Empty'}
- </span>
- </div>
- <div style={{ display: 'flex', gap: '4px' }}>
- <button
- onClick={(e) => { e.stopPropagation(); onEdit(component.id); }}
- style={{
- background: 'transparent',
- border: 'none',
- color: BLOOMBERG_COLORS.BLUE,
- cursor: 'pointer',
- padding: '2px',
- display: 'flex'
- }}
- title="Edit"
- >
- <Edit2 size={10} />
- </button>
- <button
- onClick={(e) => { e.stopPropagation(); onDuplicate(component.id); }}
- style={{
- background: 'transparent',
- border: 'none',
- color: BLOOMBERG_COLORS.GREEN,
- cursor: 'pointer',
- padding: '2px',
- display: 'flex'
- }}
- title="Duplicate"
- >
- <Copy size={10} />
- </button>
- <button
- onClick={(e) => { e.stopPropagation(); onDelete(component.id); }}
- style={{
- background: 'transparent',
- border: 'none',
- color: BLOOMBERG_COLORS.RED,
- cursor: 'pointer',
- padding: '2px',
- display: 'flex'
- }}
- title="Delete"
- >
- <Trash2 size={10} />
- </button>
- </div>
- </div>
- );
-}
-
-const ReportBuilderTab: React.FC = () => {
- const [currentTime, setCurrentTime] = useState(new Date());
- const [template, setTemplate] = useState<ReportTemplate>({
- id: `report-${Date.now()}`,
- name: 'New Financial Report',
- description: 'Professional financial research report',
- components: [],
- metadata: {
- author: '',
- company: '',
- date: new Date().toISOString().split('T')[0],
- title: 'Financial Research Report',
- },
- styles: {
- pageSize: 'A4',
- orientation: 'portrait',
- margins: '20mm',
- headerFooter: true,
- },
- });
-
- const [selectedComponent, setSelectedComponent] = useState<string | null>(null);
- const [isGenerating, setIsGenerating] = useState(false);
- const [isSaving, setIsSaving] = useState(false);
- const [showSuccessDialog, setShowSuccessDialog] = useState(false);
- const [generatedPdfPath, setGeneratedPdfPath] = useState<string>('');
-
- const sensors = useSensors(
- useSensor(PointerSensor),
- useSensor(KeyboardSensor, {
- coordinateGetter: sortableKeyboardCoordinates,
- })
- );
-
- // Update time
- React.useEffect(() => {
- const timer = setInterval(() => setCurrentTime(new Date()), 1000);
- return () => clearInterval(timer);
- }, []);
-
- const addComponent = (type: ReportComponent['type']) => {
- const newComponent: ReportComponent = {
- id: `component-${Date.now()}`,
- type,
- content: type === 'divider' || type === 'pagebreak' || type === 'coverpage' ? null : '',
- config: {
- fontSize: type === 'heading' ? '2xl' : type === 'subheading' ? 'xl' : 'base',
- alignment: 'left',
- ...(type === 'columns' && { columnCount: 2 }),
- ...(type === 'section' && {
- sectionTitle: 'New Section',
- sectionStyle: 'default',
- backgroundColor: '#f8f9fa',
- borderColor: '#FFA500',
- padding: '15px'
- }),
- ...(type === 'coverpage' && {
- subtitle: '',
- backgroundColor: '#0a0a0a',
- color: '#FFA500'
- }),
- },
- ...(type === 'columns' || type === 'section' ? { children: [] } : {}),
- };
-
- setTemplate(prev => ({
- ...prev,
- components: [...prev.components, newComponent],
- }));
- setSelectedComponent(newComponent.id);
- };
-
- const deleteComponent = (id: string) => {
- setTemplate(prev => ({
- ...prev,
- components: prev.components.filter(c => c.id !== id),
- }));
- if (selectedComponent === id) {
- setSelectedComponent(null);
- }
- };
-
- const duplicateComponent = (id: string) => {
- const component = template.components.find(c => c.id === id);
- if (component) {
- const newComponent = {
- ...component,
- id: `component-${Date.now()}`,
- };
- setTemplate(prev => ({
- ...prev,
- components: [...prev.components, newComponent],
- }));
- }
- };
-
- const handleDragEnd = (event: DragEndEvent) => {
- const { active, over } = event;
-
- if (over && active.id !== over.id) {
- setTemplate(prev => {
- const oldIndex = prev.components.findIndex(c => c.id === active.id);
- const newIndex = prev.components.findIndex(c => c.id === over.id);
-
- return {
- ...prev,
- components: arrayMove(prev.components, oldIndex, newIndex),
- };
- });
- }
- };
-
- const updateComponent = (id: string, updates: Partial<ReportComponent>) => {
- setTemplate(prev => ({
- ...prev,
- components: prev.components.map(c =>
- c.id === id ? { ...c, ...updates } : c
- ),
- }));
- };
-
- const handleOpenFolder = async () => {
- try {
- const success = await reportService.openInFolder(generatedPdfPath);
- if (success) {
- toast.success('Folder opened');
- } else {
- toast.error('Failed to open folder');
- }
- } catch (error) {
- console.error('Failed to open folder:', error);
- toast.error('Failed to open folder');
- }
- setShowSuccessDialog(false);
- };
-
- const generatePDF = async () => {
- setIsGenerating(true);
- try {
- const outputPath = await save({
- filters: [{
- name: 'PDF',
- extensions: ['pdf']
- }],
- defaultPath: `${template.name.replace(/\s+/g, '-')}.pdf`
- });
-
- if (!outputPath) {
- setIsGenerating(false);
- return;
- }
-
- console.log('[ReportBuilder] Generating PDF at:', outputPath);
- const result = await reportService.generatePDF(template, outputPath);
- console.log('[ReportBuilder] PDF generation result:', result);
-
- if (result.success) {
- // Use the path returned by the service, or fall back to the selected path
- const finalPath = result.output_path || outputPath;
- console.log('[ReportBuilder] PDF saved to:', finalPath);
- setGeneratedPdfPath(finalPath);
- setShowSuccessDialog(true);
- toast.success('PDF generated successfully');
- } else {
- console.error('[ReportBuilder] PDF generation failed:', result.error);
-
- // Check if it's a missing dependency error
- if (result.error && result.error.includes('reportlab')) {
- toast.error('PDF Library Missing', {
- description: 'Please install: pip install reportlab',
- duration: 10000
- });
- } else {
- toast.error('Failed to generate PDF', {
- description: result.error || 'Unknown error'
- });
- }
- }
- } catch (error) {
- console.error('[ReportBuilder] Exception during PDF generation:', error);
-
- // Check if it's because the Rust command doesn't exist yet
- if (error instanceof Error && error.message.includes('not found')) {
- toast.error('PDF generation not implemented yet', {
- description: 'The backend PDF generation command is not available. Please implement the generate_report_pdf Rust command.'
- });
- } else {
- toast.error('Failed to generate PDF', {
- description: error instanceof Error ? error.message : 'Unknown error'
- });
- }
- } finally {
- setIsGenerating(false);
- }
- };
-
- const saveTemplate = async () => {
- setIsSaving(true);
- try {
- await reportService.saveTemplate(template);
- toast.success('Template saved');
- } catch (error) {
- console.error('Failed to save template:', error);
- toast.error('Failed to save template');
- } finally {
- setIsSaving(false);
- }
- };
-
- const selectedComp = selectedComponent
- ? template.components.find(c => c.id === selectedComponent)
- : null;
-
- return (
- <div style={{
- height: '100%',
- backgroundColor: BLOOMBERG_COLORS.DARK_BG,
- color: BLOOMBERG_COLORS.WHITE,
- fontFamily: 'Consolas, monospace',
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column'
- }}>
- <style>{`
- *::-webkit-scrollbar { width: 8px; height: 8px; }
- *::-webkit-scrollbar-track { background: #1a1a1a; }
- *::-webkit-scrollbar-thumb { background: #404040; border-radius: 4px; }
- *::-webkit-scrollbar-thumb:hover { background: #525252; }
- `}</style>
-
- {/* Success Dialog */}
- <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>
- <DialogContent
- className="bg-gray-900 border-2 border-orange-500 text-white"
- style={{
- backgroundColor: BLOOMBERG_COLORS.PANEL_BG,
- borderColor: BLOOMBERG_COLORS.ORANGE,
- maxWidth: '600px'
- }}
- >
- <DialogHeader>
- <DialogTitle
- className="flex items-center gap-3 text-lg"
- style={{ color: BLOOMBERG_COLORS.ORANGE }}
- >
- <Check className="w-6 h-6" style={{ color: BLOOMBERG_COLORS.GREEN }} />
- PDF GENERATED SUCCESSFULLY
- </DialogTitle>
- <DialogDescription
- className="text-sm mt-2"
- style={{ color: BLOOMBERG_COLORS.GRAY }}
- >
- Your financial report has been exported successfully.
- </DialogDescription>
- </DialogHeader>
- <div className="py-4">
- <div
- className="text-xs mb-2 uppercase font-bold"
- style={{ color: BLOOMBERG_COLORS.CYAN }}
- >
- FILE LOCATION:
- </div>
- <p
- className="text-sm break-all font-mono p-3 rounded"
- style={{
- backgroundColor: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE
- }}
- >
- {generatedPdfPath}
- </p>
- </div>
- <DialogFooter className="flex gap-3 justify-end">
- <button
- onClick={() => setShowSuccessDialog(false)}
- style={{
- background: BLOOMBERG_COLORS.GRAY,
- color: 'black',
- border: 'none',
- padding: '8px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- CLOSE
- </button>
- <button
- onClick={handleOpenFolder}
- style={{
- background: BLOOMBERG_COLORS.ORANGE,
- color: 'black',
- border: 'none',
- padding: '8px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontFamily: 'Consolas, monospace'
- }}
- >
- <FolderOpen className="w-4 h-4" />
- SHOW IN FOLDER
- </button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
-
- {/* Header Bar */}
- <div style={{
- backgroundColor: BLOOMBERG_COLORS.PANEL_BG,
- borderBottom: `1px solid ${BLOOMBERG_COLORS.GRAY}`,
- padding: '8px 12px',
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <span style={{ color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', fontSize: '14px' }}>
- FINCEPT REPORT BUILDER
- </span>
- <span style={{ color: BLOOMBERG_COLORS.WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_COLORS.GREEN, fontSize: '10px' }}>
- ● ACTIVE
- </span>
- <span style={{ color: BLOOMBERG_COLORS.WHITE }}>|</span>
- <span style={{ color: BLOOMBERG_COLORS.CYAN, fontSize: '11px' }}>
- {currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC
- </span>
- </div>
-
- <div style={{ display: 'flex', gap: '8px' }}>
- <button
- onClick={() => {
- const equityTemplate = reportService.getEquityResearchTemplate();
- setTemplate(equityTemplate);
- toast.success('Loaded Equity Research template');
- }}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- color: BLOOMBERG_COLORS.CYAN,
- border: `1px solid ${BLOOMBERG_COLORS.CYAN}`,
- padding: '4px 12px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <FileText size={12} />
- LOAD TEMPLATE
- </button>
- <button
- onClick={saveTemplate}
- disabled={isSaving}
- style={{
- background: isSaving ? BLOOMBERG_COLORS.GRAY : BLOOMBERG_COLORS.CYAN,
- color: 'black',
- border: 'none',
- padding: '4px 12px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: isSaving ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- opacity: isSaving ? 0.5 : 1
- }}
- >
- <Save size={12} />
- {isSaving ? 'SAVING...' : 'SAVE'}
- </button>
- <button
- onClick={generatePDF}
- disabled={isGenerating}
- style={{
- background: isGenerating ? BLOOMBERG_COLORS.GRAY : BLOOMBERG_COLORS.ORANGE,
- color: 'black',
- border: 'none',
- padding: '4px 12px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: isGenerating ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- opacity: isGenerating ? 0.5 : 1
- }}
- >
- <Download size={12} />
- {isGenerating ? 'GENERATING...' : 'EXPORT PDF'}
- </button>
- </div>
- </div>
- </div>
-
- {/* Main Content Area */}
- <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
- {/* Left Panel - Component Palette & List */}
- <div style={{
- width: '280px',
- backgroundColor: BLOOMBERG_COLORS.PANEL_BG,
- borderRight: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- display: 'flex',
- flexDirection: 'column'
- }}>
- {/* Report Metadata */}
- <div style={{
- borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- padding: '12px'
- }}>
- <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px' }}>
- REPORT METADATA
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '2px' }}>
- TITLE
- </label>
- <input
- type="text"
- value={template.metadata.title}
- onChange={(e) => setTemplate(prev => ({
- ...prev,
- metadata: { ...prev.metadata, title: e.target.value }
- }))}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE,
- padding: '4px 6px',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace'
- }}
- />
- </div>
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '2px' }}>
- AUTHOR
- </label>
- <input
- type="text"
- value={template.metadata.author}
- onChange={(e) => setTemplate(prev => ({
- ...prev,
- metadata: { ...prev.metadata, author: e.target.value }
- }))}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE,
- padding: '4px 6px',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace'
- }}
- />
- </div>
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '2px' }}>
- COMPANY
- </label>
- <input
- type="text"
- value={template.metadata.company}
- onChange={(e) => setTemplate(prev => ({
- ...prev,
- metadata: { ...prev.metadata, company: e.target.value }
- }))}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE,
- padding: '4px 6px',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace'
- }}
- />
- </div>
- </div>
- </div>
-
- {/* Component Palette */}
- <div style={{
- borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- padding: '12px'
- }}>
- <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px' }}>
- CONTENT
- </div>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', marginBottom: '12px' }}>
- <button
- onClick={() => addComponent('heading')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.CYAN,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Type size={14} />
- HEADING
- </button>
- <button
- onClick={() => addComponent('subheading')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.CYAN,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Type size={12} />
- SUBHEAD
- </button>
- <button
- onClick={() => addComponent('text')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.CYAN,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <AlignLeft size={14} />
- TEXT
- </button>
- <button
- onClick={() => addComponent('image')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.CYAN,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <ImageIcon size={14} />
- IMAGE
- </button>
- <button
- onClick={() => addComponent('chart')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.CYAN,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <BarChart3 size={14} />
- CHART
- </button>
- <button
- onClick={() => addComponent('table')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.CYAN,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Table size={14} />
- TABLE
- </button>
- <button
- onClick={() => addComponent('code')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.CYAN,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Code size={14} />
- CODE
- </button>
- <button
- onClick={() => addComponent('divider')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.CYAN,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Minus size={14} />
- DIVIDER
- </button>
- </div>
-
- <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px' }}>
- LAYOUT
- </div>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', marginBottom: '12px' }}>
- <button
- onClick={() => addComponent('section')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.ORANGE,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Layout size={14} />
- SECTION
- </button>
- <button
- onClick={() => addComponent('columns')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.ORANGE,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <ColumnsIcon size={14} />
- COLUMNS
- </button>
- <button
- onClick={() => addComponent('coverpage')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.ORANGE,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <BookOpen size={14} />
- COVER
- </button>
- <button
- onClick={() => addComponent('pagebreak')}
- style={{
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.ORANGE,
- padding: '8px 4px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <FileX size={14} />
- PAGE BREAK
- </button>
- </div>
- </div>
-
- {/* Component List */}
- <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
- <div style={{
- padding: '8px 12px',
- borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- fontSize: '10px',
- color: BLOOMBERG_COLORS.ORANGE,
- fontWeight: 'bold'
- }}>
- DOCUMENT STRUCTURE ({template.components.length})
- </div>
- <div style={{ flex: 1, overflow: 'auto' }}>
- {template.components.length === 0 ? (
- <div style={{
- padding: '24px 12px',
- textAlign: 'center',
- fontSize: '9px',
- color: BLOOMBERG_COLORS.GRAY
- }}>
- <FileText size={32} style={{ margin: '0 auto 8px', opacity: 0.3 }} />
- <div>NO COMPONENTS</div>
- <div style={{ marginTop: '4px' }}>Add components above</div>
- </div>
- ) : (
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={template.components.map(c => c.id)}
- strategy={verticalListSortingStrategy}
- >
- {template.components.map((component) => (
- <SortableComponent
- key={component.id}
- component={component}
- onEdit={setSelectedComponent}
- onDelete={deleteComponent}
- onDuplicate={duplicateComponent}
- isSelected={selectedComponent === component.id}
- />
- ))}
- </SortableContext>
- </DndContext>
- )}
- </div>
- </div>
- </div>
-
- {/* Main Panel - Visual Canvas */}
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
- {/* Always show preview mode with inline editing */}
- <div style={{ flex: 1, overflow: 'auto', padding: '24px', backgroundColor: '#0d0d0d' }}>
- <div style={{
- maxWidth: '900px',
- margin: '0 auto',
- backgroundColor: '#ffffff',
- color: '#000000',
- padding: '48px',
- boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
- fontFamily: 'Georgia, serif'
- }}>
- {/* Report Header */}
- <div style={{
- borderBottom: '2px solid #000',
- paddingBottom: '16px',
- marginBottom: '24px'
- }}>
- <h1 style={{ fontSize: '28px', fontWeight: 'bold', marginBottom: '8px' }}>
- {template.metadata.title}
- </h1>
- {template.metadata.company && (
- <div style={{ fontSize: '16px', color: '#333', marginBottom: '8px' }}>
- {template.metadata.company}
- </div>
- )}
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: '#666' }}>
- {template.metadata.author && <span>Author: {template.metadata.author}</span>}
- {template.metadata.date && <span>Date: {template.metadata.date}</span>}
- </div>
- </div>
-
- {/* Components - Click to Edit Inline */}
- {template.components.length === 0 ? (
- <div style={{
- textAlign: 'center',
- padding: '64px 24px',
- color: '#999'
- }}>
- <FileText size={64} style={{ margin: '0 auto 16px', opacity: 0.2 }} />
- <div style={{ fontSize: '14px' }}>No components added yet</div>
- <div style={{ fontSize: '12px', marginTop: '8px' }}>Add components from the left panel</div>
- </div>
- ) : (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {template.components.map((component) => {
- const isEditing = selectedComponent === component.id;
-
- return (
- <div
- key={component.id}
- onClick={() => setSelectedComponent(component.id)}
- style={{
- cursor: 'pointer',
- padding: isEditing ? '16px' : '12px',
- borderRadius: '4px',
- border: isEditing ? `3px solid ${BLOOMBERG_COLORS.ORANGE}` : '2px dashed transparent',
- transition: 'all 0.2s',
- backgroundColor: isEditing ? '#fff8f0' : 'transparent',
- position: 'relative'
- }}
- onMouseEnter={(e) => {
- if (!isEditing) {
- e.currentTarget.style.backgroundColor = '#f9f9f9';
- e.currentTarget.style.borderColor = '#ddd';
- }
- }}
- onMouseLeave={(e) => {
- if (!isEditing) {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = 'transparent';
- }
- }}
- >
- {/* Editing Toolbar */}
- {isEditing && (
- <div style={{
- position: 'absolute',
- top: '-32px',
- right: '0',
- display: 'flex',
- gap: '4px',
- backgroundColor: BLOOMBERG_COLORS.ORANGE,
- padding: '4px 8px',
- borderRadius: '4px 4px 0 0',
- fontSize: '9px',
- fontWeight: 'bold',
- color: 'black'
- }}>
- <span>{component.type.toUpperCase()}</span>
- <span>|</span>
- <button
- onClick={(e) => {
- e.stopPropagation();
- duplicateComponent(component.id);
- }}
- style={{
- background: 'none',
- border: 'none',
- color: 'black',
- cursor: 'pointer',
- padding: '0 4px'
- }}
- >
- COPY
- </button>
- <button
- onClick={(e) => {
- e.stopPropagation();
- deleteComponent(component.id);
- setSelectedComponent(null);
- }}
- style={{
- background: 'none',
- border: 'none',
- color: 'black',
- cursor: 'pointer',
- padding: '0 4px'
- }}
- >
- DELETE
- </button>
- </div>
- )}
-
- {/* Inline Editor for Selected Component */}
- {isEditing ? (
- <div style={{
- backgroundColor: 'white',
- padding: '8px',
- borderRadius: '4px'
- }}>
-
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {(selectedComp.type === 'heading' || selectedComp.type === 'subheading' || selectedComp.type === 'text') && (
- <>
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>
- CONTENT
- </label>
- <textarea
- value={selectedComp.content}
- onChange={(e) => updateComponent(selectedComp.id, { content: e.target.value })}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE,
- padding: '8px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace',
- minHeight: '120px',
- resize: 'vertical'
- }}
- placeholder={`Enter ${selectedComp.type} content...`}
- />
- </div>
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>
- ALIGNMENT
- </label>
- <select
- value={selectedComp.config.alignment}
- onChange={(e) => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, alignment: e.target.value as any }
- })}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE,
- padding: '6px 8px',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace'
- }}
- >
- <option value="left">LEFT</option>
- <option value="center">CENTER</option>
- <option value="right">RIGHT</option>
- </select>
- </div>
- </>
- )}
-
- {selectedComp.type === 'chart' && (
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>
- CHART TYPE
- </label>
- <select
- value={selectedComp.config.chartType || 'line'}
- onChange={(e) => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, chartType: e.target.value }
- })}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE,
- padding: '6px 8px',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace'
- }}
- >
- <option value="line">LINE CHART</option>
- <option value="bar">BAR CHART</option>
- <option value="pie">PIE CHART</option>
- <option value="area">AREA CHART</option>
- </select>
- <div style={{
- marginTop: '16px',
- padding: '48px',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center'
- }}>
- <BarChart3 size={64} style={{ color: BLOOMBERG_COLORS.CYAN, opacity: 0.3 }} />
- </div>
- </div>
- )}
-
- {selectedComp.type === 'code' && (
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>
- CODE BLOCK
- </label>
- <textarea
- value={selectedComp.content}
- onChange={(e) => updateComponent(selectedComp.id, { content: e.target.value })}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.GREEN,
- padding: '12px',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace',
- minHeight: '240px',
- resize: 'vertical'
- }}
- placeholder="Enter code here..."
- />
- </div>
- )}
-
- {selectedComp.type === 'table' && (
- <div style={{
- padding: '32px',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- textAlign: 'center'
- }}>
- <Table size={48} style={{ color: BLOOMBERG_COLORS.CYAN, opacity: 0.3, margin: '0 auto' }} />
- <div style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, marginTop: '12px' }}>
- TABLE EDITOR COMING SOON
- </div>
- </div>
- )}
-
- {selectedComp.type === 'image' && (
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>
- IMAGE FILE
- </label>
- <div style={{
- padding: '24px',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px dashed ${BLOOMBERG_COLORS.BORDER}`,
- textAlign: 'center'
- }}>
- {selectedComp.config.imageUrl ? (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
- <div style={{
- padding: '12px',
- background: BLOOMBERG_COLORS.PANEL_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- borderRadius: '4px'
- }}>
- <div style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, marginBottom: '6px' }}>
- SELECTED FILE:
- </div>
- <div style={{
- fontSize: '10px',
- color: BLOOMBERG_COLORS.WHITE,
- fontFamily: 'Consolas, monospace',
- wordBreak: 'break-all'
- }}>
- {selectedComp.config.imageUrl}
- </div>
- </div>
- {selectedComp.config.imageUrl.match(/\.(jpg|jpeg|png|gif|bmp|webp)$/i) && (
- <div style={{
- maxWidth: '100%',
- maxHeight: '300px',
- overflow: 'hidden',
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- borderRadius: '4px'
- }}>
- <img
- src={`file://${selectedComp.config.imageUrl}`}
- alt="Preview"
- style={{
- maxWidth: '100%',
- maxHeight: '300px',
- objectFit: 'contain'
- }}
- onError={(e) => {
- (e.target as HTMLImageElement).style.display = 'none';
- }}
- />
- </div>
- )}
- <div style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
- <button
- onClick={async () => {
- try {
- const selected = await open({
- multiple: false,
- filters: [{
- name: 'Images',
- extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']
- }]
- });
- if (selected && typeof selected === 'string') {
- updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, imageUrl: selected }
- });
- toast.success('Image updated successfully');
- }
- } catch (error) {
- console.error('Failed to select image:', error);
- toast.error('Failed to select image');
- }
- }}
- style={{
- background: BLOOMBERG_COLORS.CYAN,
- color: 'black',
- border: 'none',
- padding: '6px 12px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- CHANGE IMAGE
- </button>
- <button
- onClick={() => {
- updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, imageUrl: undefined }
- });
- toast.success('Image removed');
- }}
- style={{
- background: BLOOMBERG_COLORS.RED,
- color: 'white',
- border: 'none',
- padding: '6px 12px',
- fontSize: '9px',
- fontWeight: 'bold',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace'
- }}
- >
- REMOVE
- </button>
- </div>
- </div>
- ) : (
- <div>
- <ImageIcon size={48} style={{ color: BLOOMBERG_COLORS.CYAN, opacity: 0.3, margin: '0 auto 12px' }} />
- <div style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, marginBottom: '12px' }}>
- NO IMAGE SELECTED
- </div>
- <button
- onClick={async () => {
- try {
- const selected = await open({
- multiple: false,
- filters: [{
- name: 'Images',
- extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']
- }]
- });
- if (selected && typeof selected === 'string') {
- updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, imageUrl: selected }
- });
- toast.success('Image selected successfully');
- }
- } catch (error) {
- console.error('Failed to select image:', error);
- toast.error('Failed to select image');
- }
- }}
- style={{
- background: BLOOMBERG_COLORS.ORANGE,
- color: 'black',
- border: 'none',
- padding: '8px 16px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- margin: '0 auto',
- fontFamily: 'Consolas, monospace'
- }}
- >
- <Plus size={14} />
- SELECT IMAGE FROM COMPUTER
- </button>
- </div>
- )}
- </div>
- </div>
- )}
-
- {selectedComp.type === 'divider' && (
- <div style={{
- padding: '16px',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`
- }}>
- <hr style={{ border: 'none', borderTop: `1px solid ${BLOOMBERG_COLORS.BORDER}` }} />
- </div>
- )}
-
- {selectedComp.type === 'pagebreak' && (
- <div style={{
- padding: '24px',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px dashed ${BLOOMBERG_COLORS.BORDER}`,
- textAlign: 'center'
- }}>
- <FileX size={48} style={{ color: BLOOMBERG_COLORS.ORANGE, opacity: 0.3, margin: '0 auto 12px' }} />
- <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.GRAY }}>
- PAGE BREAK - Starts new page in PDF
- </div>
- </div>
- )}
-
- {selectedComp.type === 'coverpage' && (
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>
- SUBTITLE
- </label>
- <input
- type="text"
- value={selectedComp.config.subtitle || ''}
- onChange={(e) => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, subtitle: e.target.value }
- })}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE,
- padding: '8px',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace',
- marginBottom: '12px'
- }}
- placeholder="Enter subtitle..."
- />
- <div style={{
- padding: '48px',
- background: selectedComp.config.backgroundColor || '#0a0a0a',
- border: `2px solid ${BLOOMBERG_COLORS.ORANGE}`,
- textAlign: 'center'
- }}>
- <BookOpen size={64} style={{ color: BLOOMBERG_COLORS.ORANGE, opacity: 0.5, margin: '0 auto 24px' }} />
- <div style={{ fontSize: '24px', color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', marginBottom: '12px' }}>
- COVER PAGE
- </div>
- <div style={{ fontSize: '12px', color: BLOOMBERG_COLORS.GRAY }}>
- {selectedComp.config.subtitle || 'Subtitle here'}
- </div>
- </div>
- </div>
- )}
-
- {selectedComp.type === 'section' && (
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>
- SECTION TITLE
- </label>
- <input
- type="text"
- value={selectedComp.config.sectionTitle || ''}
- onChange={(e) => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, sectionTitle: e.target.value }
- })}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE,
- padding: '8px',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace',
- marginBottom: '12px'
- }}
- placeholder="Enter section title..."
- />
- <div style={{
- padding: selectedComp.config.padding || '15px',
- background: selectedComp.config.backgroundColor || '#f8f9fa',
- border: `3px solid ${selectedComp.config.borderColor || BLOOMBERG_COLORS.ORANGE}`
- }}>
- <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px', color: BLOOMBERG_COLORS.ORANGE }}>
- {selectedComp.config.sectionTitle || 'SECTION TITLE'}
- </div>
- <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.GRAY }}>
- Section content goes here. Add child components to populate this section.
- </div>
- </div>
- </div>
- )}
-
- {selectedComp.type === 'columns' && (
- <div>
- <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>
- COLUMN COUNT
- </label>
- <select
- value={selectedComp.config.columnCount || 2}
- onChange={(e) => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, columnCount: parseInt(e.target.value) as 2 | 3 }
- })}
- style={{
- width: '100%',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- color: BLOOMBERG_COLORS.WHITE,
- padding: '8px',
- fontSize: '10px',
- fontFamily: 'Consolas, monospace',
- marginBottom: '12px'
- }}
- >
- <option value="2">2 COLUMNS</option>
- <option value="3">3 COLUMNS</option>
- </select>
- <div style={{
- display: 'grid',
- gridTemplateColumns: selectedComp.config.columnCount === 3 ? '1fr 1fr 1fr' : '1fr 1fr',
- gap: '12px',
- padding: '16px',
- background: BLOOMBERG_COLORS.DARK_BG,
- border: `1px solid ${BLOOMBERG_COLORS.BORDER}`
- }}>
- {[...Array(selectedComp.config.columnCount || 2)].map((_, i) => (
- <div
- key={i}
- style={{
- padding: '24px 12px',
- border: `1px dashed ${BLOOMBERG_COLORS.BORDER}`,
- textAlign: 'center',
- fontSize: '9px',
- color: BLOOMBERG_COLORS.GRAY
- }}
- >
- COLUMN {i + 1}
- </div>
- ))}
- </div>
- <div style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, marginTop: '12px' }}>
- Add child components to populate columns
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
- ) : (
- // Preview Mode
- <div style={{ flex: 1, overflow: 'auto', padding: '24px', backgroundColor: '#0d0d0d' }}>
- <div style={{
- maxWidth: '900px',
- margin: '0 auto',
- backgroundColor: '#ffffff',
- color: '#000000',
- padding: '48px',
- boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
- fontFamily: 'Georgia, serif'
- }}>
- {/* Report Header */}
- <div style={{
- borderBottom: '2px solid #000',
- paddingBottom: '16px',
- marginBottom: '24px'
- }}>
- <h1 style={{ fontSize: '28px', fontWeight: 'bold', marginBottom: '8px' }}>
- {template.metadata.title}
- </h1>
- {template.metadata.company && (
- <div style={{ fontSize: '16px', color: '#333', marginBottom: '8px' }}>
- {template.metadata.company}
- </div>
- )}
- <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: '#666' }}>
- {template.metadata.author && <span>Author: {template.metadata.author}</span>}
- {template.metadata.date && <span>Date: {template.metadata.date}</span>}
- </div>
- </div>
-
- {/* Components */}
- {template.components.length === 0 ? (
- <div style={{
- textAlign: 'center',
- padding: '64px 24px',
- color: '#999'
- }}>
- <FileText size={64} style={{ margin: '0 auto 16px', opacity: 0.2 }} />
- <div style={{ fontSize: '14px' }}>No components added yet</div>
- <div style={{ fontSize: '12px', marginTop: '8px' }}>Add components from the left panel</div>
- </div>
- ) : (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
- {template.components.map((component) => (
- <div
- key={component.id}
- onClick={() => setSelectedComponent(component.id)}
- style={{
- cursor: 'pointer',
- padding: '12px',
- borderRadius: '4px',
- border: '1px solid transparent',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#f9f9f9';
- e.currentTarget.style.borderColor = BLOOMBERG_COLORS.CYAN;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = 'transparent';
- }}
- >
- {component.type === 'coverpage' && (
- <div style={{
- minHeight: '400px',
- backgroundColor: component.config.backgroundColor || '#0a0a0a',
- border: `3px solid ${BLOOMBERG_COLORS.ORANGE}`,
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- justifyContent: 'center',
- padding: '48px',
- textAlign: 'center'
- }}>
- <h1 style={{ fontSize: '32px', fontWeight: 'bold', color: BLOOMBERG_COLORS.ORANGE, marginBottom: '16px' }}>
- {template.metadata.title}
- </h1>
- {component.config.subtitle && (
- <div style={{ fontSize: '16px', color: BLOOMBERG_COLORS.GRAY, marginBottom: '32px' }}>
- {component.config.subtitle}
- </div>
- )}
- <div style={{ fontSize: '12px', color: BLOOMBERG_COLORS.GRAY, marginTop: '32px' }}>
- {template.metadata.company}<br />
- {template.metadata.date}
- </div>
- </div>
- )}
- {component.type === 'pagebreak' && (
- <div style={{
- padding: '24px',
- border: '2px dashed #ddd',
- textAlign: 'center',
- backgroundColor: '#f9f9f9'
- }}>
- <FileX size={32} style={{ color: '#999', margin: '0 auto 8px' }} />
- <div style={{ fontSize: '11px', color: '#999' }}>PAGE BREAK</div>
- </div>
- )}
- {component.type === 'section' && (
- <div style={{
- padding: component.config.padding || '20px',
- backgroundColor: component.config.backgroundColor || '#f8f9fa',
- border: `3px solid ${component.config.borderColor || BLOOMBERG_COLORS.ORANGE}`,
- borderRadius: '4px'
- }}>
- <h3 style={{
- fontSize: '18px',
- fontWeight: 'bold',
- marginBottom: '12px',
- color: component.config.borderColor || BLOOMBERG_COLORS.ORANGE
- }}>
- {component.config.sectionTitle || 'SECTION'}
- </h3>
- <div style={{ fontSize: '12px', color: '#666' }}>
- {component.children && component.children.length > 0 ? (
- <div>Child components: {component.children.length}</div>
- ) : (
- <div>No child components added yet</div>
- )}
- </div>
- </div>
- )}
- {component.type === 'columns' && (
- <div style={{
- display: 'grid',
- gridTemplateColumns: component.config.columnCount === 3 ? '1fr 1fr 1fr' : '1fr 1fr',
- gap: '16px',
- padding: '12px',
- border: '1px solid #ddd',
- borderRadius: '4px',
- backgroundColor: '#fafafa'
- }}>
- {[...Array(component.config.columnCount || 2)].map((_, i) => (
- <div
- key={i}
- style={{
- padding: '16px',
- border: '1px dashed #ccc',
- minHeight: '100px',
- backgroundColor: 'white'
- }}
- >
- <div style={{ fontSize: '10px', color: '#999', textAlign: 'center' }}>
- Column {i + 1}
- </div>
- </div>
- ))}
- </div>
- )}
- {component.type === 'heading' && (
- <h2 style={{ fontSize: '22px', fontWeight: 'bold' }}>
- {component.content || 'Heading'}
- </h2>
- )}
- {component.type === 'subheading' && (
- <h3 style={{ fontSize: '18px', fontWeight: '600', color: '#444' }}>
- {component.content || 'Subheading'}
- </h3>
- )}
- {component.type === 'text' && (
- <p style={{ fontSize: '14px', lineHeight: '1.6' }}>
- {component.content || 'Text content...'}
- </p>
- )}
- {component.type === 'chart' && (
- <div style={{
- border: '1px solid #ddd',
- borderRadius: '4px',
- padding: '24px',
- backgroundColor: '#f5f5f5',
- textAlign: 'center'
- }}>
- <BarChart3 size={80} style={{ margin: '0 auto', color: '#3b82f6' }} />
- <div style={{ fontSize: '12px', color: '#666', marginTop: '8px' }}>
- {component.config.chartType || 'Chart'} Preview
- </div>
- </div>
- )}
- {component.type === 'table' && (
- <div style={{ border: '1px solid #ddd', borderRadius: '4px', overflow: 'hidden' }}>
- <table style={{ width: '100%', fontSize: '12px', borderCollapse: 'collapse' }}>
- <thead style={{ backgroundColor: '#f0f0f0' }}>
- <tr>
- {['Column 1', 'Column 2', 'Column 3'].map((col, i) => (
- <th key={i} style={{ padding: '8px 12px', textAlign: 'left', borderBottom: '1px solid #ddd' }}>
- {col}
- </th>
- ))}
- </tr>
- </thead>
- <tbody>
- <tr>
- <td style={{ padding: '8px 12px' }}>Sample</td>
- <td style={{ padding: '8px 12px' }}>Sample</td>
- <td style={{ padding: '8px 12px' }}>Sample</td>
- </tr>
- </tbody>
- </table>
- </div>
- )}
- {component.type === 'image' && (
- <div style={{
- border: '1px solid #ddd',
- borderRadius: '4px',
- padding: component.config.imageUrl ? '12px' : '48px',
- backgroundColor: '#f5f5f5',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center'
- }}>
- {component.config.imageUrl ? (
- <img
- src={`file://${component.config.imageUrl}`}
- alt="Report Image"
- style={{
- maxWidth: '100%',
- maxHeight: '400px',
- objectFit: 'contain'
- }}
- onError={(e) => {
- const target = e.target as HTMLImageElement;
- target.style.display = 'none';
- const parent = target.parentElement;
- if (parent) {
- parent.innerHTML = '<div style="color: #999; text-align: center; padding: 24px;"><svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg><div style="margin-top: 12px; font-size: 14px;">Image not found</div></div>';
- }
- }}
- />
- ) : (
- <ImageIcon size={64} style={{ color: '#999' }} />
- )}
- </div>
- )}
- {component.type === 'code' && (
- <pre style={{
- backgroundColor: '#1a1a1a',
- border: '1px solid #333',
- borderRadius: '4px',
- padding: '16px',
- overflow: 'auto',
- fontSize: '11px',
- color: '#10b981',
- fontFamily: 'Consolas, monospace'
- }}>
- <code>{component.content || '# Code block'}</code>
- </pre>
- )}
- {component.type === 'divider' && (
- <hr style={{ border: 'none', borderTop: '1px solid #ddd' }} />
- )}
- </div>
- ))}
- </div>
- )}
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
- );
-};
-
-export default ReportBuilderTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab_new.tsx.bak b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab_new.tsx.bak
deleted file mode 100644
index 594a5c7af..000000000
--- a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab_new.tsx.bak
+++ /dev/null
@@ -1,200 +0,0 @@
-import React, { useState } from 'react';
-import {
- FileText,
- Download,
- Save,
- Type,
- BarChart3,
- Table,
- Image as ImageIcon,
- Trash2,
- Copy,
- AlignLeft,
- Code,
- Minus,
- FolderOpen,
- Check,
- Plus,
- RefreshCw,
- Edit2,
- Move,
- Columns as ColumnsIcon,
- Layout,
- BookOpen,
- FileX
-} from 'lucide-react';
-import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';
-import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
-import { CSS } from '@dnd-kit/utilities';
-import { reportService, ReportTemplate, ReportComponent } from '@/services/reportService';
-import { save, open } from '@tauri-apps/plugin-dialog';
-import { toast } from 'sonner';
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
-import { Button } from '@/components/ui/button';
-
-// Bloomberg color palette
-const BLOOMBERG_COLORS = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- RED: '#ef4444',
- GREEN: '#10b981',
- YELLOW: '#fbbf24',
- GRAY: '#787878',
- BLUE: '#3b82f6',
- CYAN: '#06b6d4',
- DARK_BG: '#0a0a0a',
- PANEL_BG: '#1a1a1a',
- BORDER: '#333333',
-};
-
-// Sortable component wrapper
-function SortableComponent({ component, onEdit, onDelete, onDuplicate, isSelected }: {
- component: ReportComponent;
- onEdit: (id: string) => void;
- onDelete: (id: string) => void;
- onDuplicate: (id: string) => void;
- isSelected: boolean;
-}) {
- const {
- attributes,
- listeners,
- setNodeRef,
- transform,
- transition,
- } = useSortable({ id: component.id });
-
- const style = {
- transform: CSS.Transform.toString(transform),
- transition,
- };
-
- const getComponentIcon = () => {
- switch (component.type) {
- case 'heading': return <Type size={10} />;
- case 'text': return <AlignLeft size={10} />;
- case 'chart': return <BarChart3 size={10} />;
- case 'table': return <Table size={10} />;
- case 'image': return <ImageIcon size={10} />;
- case 'code': return <Code size={10} />;
- case 'divider': return <Minus size={10} />;
- default: return <FileText size={10} />;
- }
- };
-
- return (
- <div
- ref={setNodeRef}
- style={{
- ...style,
- backgroundColor: isSelected ? '#2a2a2a' : 'transparent',
- borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,
- padding: '6px 8px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- cursor: 'pointer',
- borderLeft: isSelected ? `2px solid ${BLOOMBERG_COLORS.ORANGE}` : 'none'
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>
- <div {...attributes} {...listeners} style={{ color: BLOOMBERG_COLORS.GRAY, cursor: 'move', display: 'flex' }}>
- <Move size={12} />
- </div>
- <div style={{ color: BLOOMBERG_COLORS.CYAN, display: 'flex' }}>
- {getComponentIcon()}
- </div>
- <span style={{ color: BLOOMBERG_COLORS.ORANGE, fontSize: '9px', fontWeight: 'bold' }}>
- {component.type.toUpperCase()}
- </span>
- <span style={{ color: BLOOMBERG_COLORS.GRAY, fontSize: '9px', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
- {component.content ? component.content.substring(0, 20) : 'Empty'}
- </span>
- </div>
- <div style={{ display: 'flex', gap: '4px' }}>
- <button
- onClick={(e) => { e.stopPropagation(); onEdit(component.id); }}
- style={{
- background: 'transparent',
- border: 'none',
- color: BLOOMBERG_COLORS.BLUE,
- cursor: 'pointer',
- padding: '2px',
- display: 'flex'
- }}
- title="Edit"
- >
- <Edit2 size={10} />
- </button>
- <button
- onClick={(e) => { e.stopPropagation(); onDuplicate(component.id); }}
- style={{
- background: 'transparent',
- border: 'none',
- color: BLOOMBERG_COLORS.GREEN,
- cursor: 'pointer',
- padding: '2px',
- display: 'flex'
- }}
- title="Duplicate"
- >
- <Copy size={10} />
- </button>
- <button
- onClick={(e) => { e.stopPropagation(); onDelete(component.id); }}
- style={{
- background: 'transparent',
- border: 'none',
- color: BLOOMBERG_COLORS.RED,
- cursor: 'pointer',
- padding: '2px',
- display: 'flex'
- }}
- title="Delete"
- >
- <Trash2 size={10} />
- </button>
- </div>
- </div>
- );
-}
-
-const ReportBuilderTab: React.FC = () => {
- const [currentTime, setCurrentTime] = useState(new Date());
- const [template, setTemplate] = useState<ReportTemplate>({
- id: `report-${Date.now()}`,
- name: 'New Financial Report',
- description: 'Professional financial research report',
- components: [],
- metadata: {
- author: '',
- company: '',
- date: new Date().toISOString().split('T')[0],
- title: 'Financial Research Report',
- },
- styles: {
- pageSize: 'A4',
- orientation: 'portrait',
- margins: '20mm',
- headerFooter: true,
- },
- });
-
- const [selectedComponent, setSelectedComponent] = useState<string | null>(null);
- const [isGenerating, setIsGenerating] = useState(false);
- const [isSaving, setIsSaving] = useState(false);
- const [showSuccessDialog, setShowSuccessDialog] = useState(false);
- const [generatedPdfPath, setGeneratedPdfPath] = useState<string>('');
-
- const sensors = useSensors(
- useSensor(PointerSensor),
- useSensor(KeyboardSensor, {
- coordinateGetter: sortableKeyboardCoordinates,
- })
- );
-
- // Update time
- React.useEffect(() => {
- const timer = setInterval(() => setCurrentTime(new Date()), 1000);
- return () => clearInterval(timer);
- }, []);
-
diff --git a/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
new file mode 100644
index 000000000..8708aa47e
--- /dev/null
+++ b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
@@ -0,0 +1,728 @@
+/**
+ * Order Matching Engine
+ *
+ * Realistic order execution simulation using real market data
+ * Supports all order types: market, limit, stop, stop-limit, trailing stop, iceberg, post-only, reduce-only
+ */
+
+import type { Ticker, OrderBook } from 'ccxt';
+import type { IExchangeAdapter, OrderType, OrderSide, OrderParams, Order } from '../types';
+import type {
+ PaperTradingConfig,
+ PaperTradingOrder,
+ PaperTradingTrade,
+ OrderMatchResult,
+ PriceSnapshot,
+} from './types';
+import { paperTradingDatabase } from './PaperTradingDatabase';
+import { PaperTradingBalance } from './PaperTradingBalance';
+import { InsufficientFunds } from '../types';
+
+export class OrderMatchingEngine {
+ private balanceManager: PaperTradingBalance;
+ private monitoringInterval: NodeJS.Timeout | null = null;
+ private priceCache: Map<string, PriceSnapshot> = new Map();
+
+ constructor(
+ private config: PaperTradingConfig,
+ private realExchangeAdapter: IExchangeAdapter
+ ) {
+ this.balanceManager = new PaperTradingBalance(config);
+ }
+
+ // ============================================================================
+ // ORDER PLACEMENT
+ // ============================================================================
+
+ /**
+ * Place a new order
+ */
+ async placeOrder(
+ symbol: string,
+ type: OrderType,
+ side: OrderSide,
+ amount: number,
+ price?: number,
+ params?: OrderParams
+ ): Promise<OrderMatchResult> {
+ const orderId = `order_${Date.now()}_${Math.random().toString(36).substring(7)}`;
+
+ // Get current price for validation
+ const priceSnapshot = await this.fetchPriceSnapshot(symbol);
+ const executionPrice = price || (side === 'buy' ? priceSnapshot.ask : priceSnapshot.bid);
+
+ // Check sufficient funds
+ const leverage = params?.leverage || this.config.defaultLeverage || 1;
+ const fundsCheck = await this.balanceManager.checkSufficientFunds(
+ this.config.portfolioId,
+ symbol,
+ side,
+ amount,
+ executionPrice,
+ leverage
+ );
+
+ if (!fundsCheck.sufficient) {
+ return {
+ success: false,
+ order: this.createOrderObject(orderId, symbol, type, side, amount, price, params, 'rejected'),
+ trades: [],
+ balance: fundsCheck.available,
+ error: fundsCheck.error,
+ };
+ }
+
+ // Create order in database
+ await paperTradingDatabase.createOrder({
+ id: orderId,
+ portfolioId: this.config.portfolioId,
+ symbol,
+ side,
+ type,
+ quantity: amount,
+ price: price || null,
+ stopPrice: params?.stopPrice || null,
+ timeInForce: params?.timeInForce,
+ postOnly: params?.postOnly,
+ reduceOnly: params?.reduceOnly,
+ trailingPercent: params?.trailingPercent || null,
+ trailingAmount: params?.trailingAmount || null,
+ icebergQty: params?.icebergQty || null,
+ leverage: params?.leverage,
+ marginMode: params?.marginMode,
+ });
+
+ // Handle different order types
+ switch (type) {
+ case 'market':
+ return await this.executeMarketOrder(orderId, symbol, side, amount, params);
+
+ case 'limit':
+ return await this.handleLimitOrder(orderId, symbol, side, amount, price!, params);
+
+ case 'stop':
+ case 'stop_limit':
+ return await this.handleStopOrder(orderId, symbol, type, side, amount, price, params);
+
+ case 'trailing_stop':
+ return await this.handleTrailingStopOrder(orderId, symbol, side, amount, params);
+
+ case 'iceberg':
+ return await this.handleIcebergOrder(orderId, symbol, side, amount, price!, params);
+
+ default:
+ return {
+ success: false,
+ order: this.createOrderObject(orderId, symbol, type, side, amount, price, params, 'rejected'),
+ trades: [],
+ balance: fundsCheck.available,
+ error: `Unsupported order type: ${type}`,
+ };
+ }
+ }
+
+ // ============================================================================
+ // MARKET ORDERS
+ // ============================================================================
+
+ private async executeMarketOrder(
+ orderId: string,
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ params?: OrderParams
+ ): Promise<OrderMatchResult> {
+ const priceSnapshot = await this.fetchPriceSnapshot(symbol);
+
+ // Apply slippage for market orders
+ const basePrice = side === 'buy' ? priceSnapshot.ask : priceSnapshot.bid;
+ const slippage = this.config.slippage.market;
+ const executionPrice = side === 'buy'
+ ? basePrice * (1 + slippage)
+ : basePrice * (1 - slippage);
+
+ // Simulate latency if configured
+ if (this.config.simulatedLatency && this.config.simulatedLatency > 0) {
+ await this.sleep(this.config.simulatedLatency);
+ }
+
+ // Check Time-In-Force
+ if (params?.timeInForce === 'PO') {
+ // Post-only not valid for market orders
+ await paperTradingDatabase.updateOrder(orderId, { status: 'rejected' });
+ return {
+ success: false,
+ order: this.createOrderObject(orderId, symbol, 'market', side, amount, undefined, params, 'rejected'),
+ trades: [],
+ balance: 0,
+ error: 'Post-only (PO) time-in-force not valid for market orders',
+ };
+ }
+
+ // Execute trade
+ const tradeResult = await this.executeTrade(orderId, symbol, side, executionPrice, amount, false, params);
+
+ if (!tradeResult.success) {
+ return tradeResult;
+ }
+
+ // Update order status
+ await paperTradingDatabase.updateOrder(orderId, {
+ filledQuantity: amount,
+ avgFillPrice: executionPrice,
+ status: 'filled',
+ filledAt: new Date().toISOString(),
+ });
+
+ const order = await paperTradingDatabase.getOrder(orderId);
+ return {
+ success: true,
+ order: order!,
+ trades: tradeResult.trades,
+ position: tradeResult.position,
+ balance: tradeResult.balance,
+ };
+ }
+
+ // ============================================================================
+ // LIMIT ORDERS
+ // ============================================================================
+
+ private async handleLimitOrder(
+ orderId: string,
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ limitPrice: number,
+ params?: OrderParams
+ ): Promise<OrderMatchResult> {
+ const priceSnapshot = await this.fetchPriceSnapshot(symbol);
+
+ // Check if order can be immediately filled
+ const canFillImmediately = side === 'buy'
+ ? priceSnapshot.ask <= limitPrice
+ : priceSnapshot.bid >= limitPrice;
+
+ // Handle Post-Only
+ if (params?.postOnly && canFillImmediately) {
+ await paperTradingDatabase.updateOrder(orderId, { status: 'rejected' });
+ return {
+ success: false,
+ order: this.createOrderObject(orderId, symbol, 'limit', side, amount, limitPrice, params, 'rejected'),
+ trades: [],
+ balance: 0,
+ error: 'Post-only order would take liquidity',
+ };
+ }
+
+ // Handle IOC (Immediate-Or-Cancel)
+ if (params?.timeInForce === 'IOC') {
+ if (canFillImmediately) {
+ return await this.executeLimitOrder(orderId, symbol, side, amount, limitPrice, params);
+ } else {
+ await paperTradingDatabase.updateOrder(orderId, { status: 'canceled' });
+ return {
+ success: false,
+ order: this.createOrderObject(orderId, symbol, 'limit', side, amount, limitPrice, params, 'canceled'),
+ trades: [],
+ balance: 0,
+ error: 'IOC order could not be filled immediately',
+ };
+ }
+ }
+
+ // Handle FOK (Fill-Or-Kill)
+ if (params?.timeInForce === 'FOK') {
+ if (canFillImmediately) {
+ return await this.executeLimitOrder(orderId, symbol, side, amount, limitPrice, params);
+ } else {
+ await paperTradingDatabase.updateOrder(orderId, { status: 'canceled' });
+ return {
+ success: false,
+ order: this.createOrderObject(orderId, symbol, 'limit', side, amount, limitPrice, params, 'canceled'),
+ trades: [],
+ balance: 0,
+ error: 'FOK order could not be fully filled',
+ };
+ }
+ }
+
+ // GTC (Good-Till-Canceled) - default
+ if (canFillImmediately) {
+ return await this.executeLimitOrder(orderId, symbol, side, amount, limitPrice, params);
+ } else {
+ // Store as pending order
+ const order = await paperTradingDatabase.getOrder(orderId);
+ return {
+ success: true,
+ order: order!,
+ trades: [],
+ balance: 0,
+ };
+ }
+ }
+
+ private async executeLimitOrder(
+ orderId: string,
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ limitPrice: number,
+ params?: OrderParams
+ ): Promise<OrderMatchResult> {
+ const executionPrice = limitPrice; // Limit orders fill at limit price (optimistic)
+ const isMaker = true; // Limit orders that wait are makers
+
+ // Execute trade
+ const tradeResult = await this.executeTrade(orderId, symbol, side, executionPrice, amount, isMaker, params);
+
+ if (!tradeResult.success) {
+ return tradeResult;
+ }
+
+ // Update order status
+ await paperTradingDatabase.updateOrder(orderId, {
+ filledQuantity: amount,
+ avgFillPrice: executionPrice,
+ status: 'filled',
+ filledAt: new Date().toISOString(),
+ });
+
+ const order = await paperTradingDatabase.getOrder(orderId);
+ return {
+ success: true,
+ order: order!,
+ trades: tradeResult.trades,
+ position: tradeResult.position,
+ balance: tradeResult.balance,
+ };
+ }
+
+ // ============================================================================
+ // STOP ORDERS
+ // ============================================================================
+
+ private async handleStopOrder(
+ orderId: string,
+ symbol: string,
+ type: 'stop' | 'stop_limit',
+ side: OrderSide,
+ amount: number,
+ limitPrice: number | undefined,
+ params?: OrderParams
+ ): Promise<OrderMatchResult> {
+ if (!params?.stopPrice) {
+ await paperTradingDatabase.updateOrder(orderId, { status: 'rejected' });
+ return {
+ success: false,
+ order: this.createOrderObject(orderId, symbol, type, side, amount, limitPrice, params, 'rejected'),
+ trades: [],
+ balance: 0,
+ error: 'Stop orders require stopPrice parameter',
+ };
+ }
+
+ // Store as pending order - will be monitored
+ const order = await paperTradingDatabase.getOrder(orderId);
+ return {
+ success: true,
+ order: order!,
+ trades: [],
+ balance: 0,
+ };
+ }
+
+ private async checkStopOrderTrigger(order: PaperTradingOrder, currentPrice: number): Promise<boolean> {
+ if (!order.stopPrice) return false;
+
+ // Buy stop: trigger when price rises above stop price
+ // Sell stop: trigger when price falls below stop price
+ const triggered = order.side === 'buy'
+ ? currentPrice >= order.stopPrice
+ : currentPrice <= order.stopPrice;
+
+ return triggered;
+ }
+
+ private async executeTriggeredStopOrder(order: PaperTradingOrder, currentPrice: number): Promise<void> {
+ // Update order status to triggered
+ await paperTradingDatabase.updateOrder(order.id, { status: 'triggered' });
+
+ if (order.type === 'stop') {
+ // Stop market order - execute immediately
+ const priceSnapshot = await this.fetchPriceSnapshot(order.symbol);
+ const executionPrice = order.side === 'buy' ? priceSnapshot.ask : priceSnapshot.bid;
+
+ await this.executeTrade(order.id, order.symbol, order.side, executionPrice, order.amount, false);
+
+ await paperTradingDatabase.updateOrder(order.id, {
+ filledQuantity: order.amount,
+ avgFillPrice: executionPrice,
+ status: 'filled',
+ filledAt: new Date().toISOString(),
+ });
+ } else if (order.type === 'stop_limit' && order.price) {
+ // Stop limit order - convert to limit order
+ // Will be filled if price reaches limit price
+ // For simplicity, we'll try to fill immediately if conditions are met
+ const canFill = order.side === 'buy'
+ ? currentPrice <= order.price
+ : currentPrice >= order.price;
+
+ if (canFill) {
+ await this.executeTrade(order.id, order.symbol, order.side, order.price, order.amount, true);
+
+ await paperTradingDatabase.updateOrder(order.id, {
+ filledQuantity: order.amount,
+ avgFillPrice: order.price,
+ status: 'filled',
+ filledAt: new Date().toISOString(),
+ });
+ }
+ // else remains in triggered state, waiting for limit price
+ }
+ }
+
+ // ============================================================================
+ // TRAILING STOP ORDERS
+ // ============================================================================
+
+ private async handleTrailingStopOrder(
+ orderId: string,
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ params?: OrderParams
+ ): Promise<OrderMatchResult> {
+ if (!params?.trailingPercent && !params?.trailingAmount) {
+ await paperTradingDatabase.updateOrder(orderId, { status: 'rejected' });
+ return {
+ success: false,
+ order: this.createOrderObject(orderId, symbol, 'trailing_stop', side, amount, undefined, params, 'rejected'),
+ trades: [],
+ balance: 0,
+ error: 'Trailing stop orders require trailingPercent or trailingAmount',
+ };
+ }
+
+ // Store as pending order - will be monitored
+ const order = await paperTradingDatabase.getOrder(orderId);
+ return {
+ success: true,
+ order: order!,
+ trades: [],
+ balance: 0,
+ };
+ }
+
+ // ============================================================================
+ // ICEBERG ORDERS
+ // ============================================================================
+
+ private async handleIcebergOrder(
+ orderId: string,
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ limitPrice: number,
+ params?: OrderParams
+ ): Promise<OrderMatchResult> {
+ if (!params?.icebergQty) {
+ await paperTradingDatabase.updateOrder(orderId, { status: 'rejected' });
+ return {
+ success: false,
+ order: this.createOrderObject(orderId, symbol, 'iceberg', side, amount, limitPrice, params, 'rejected'),
+ trades: [],
+ balance: 0,
+ error: 'Iceberg orders require icebergQty parameter',
+ };
+ }
+
+ // For paper trading, we'll simplify and treat as a regular limit order
+ // In real exchanges, only icebergQty is visible in order book
+ return await this.handleLimitOrder(orderId, symbol, side, amount, limitPrice, params);
+ }
+
+ // ============================================================================
+ // TRADE EXECUTION
+ // ============================================================================
+
+ private async executeTrade(
+ orderId: string,
+ symbol: string,
+ side: OrderSide,
+ price: number,
+ quantity: number,
+ isMaker: boolean,
+ params?: OrderParams
+ ): Promise<OrderMatchResult & { success: boolean }> {
+ const feeRate = isMaker ? this.config.fees.maker : this.config.fees.taker;
+ const orderValue = price * quantity;
+ const fee = orderValue * feeRate;
+
+ // Create trade record
+ const tradeId = `trade_${Date.now()}_${Math.random().toString(36).substring(7)}`;
+ const trade: PaperTradingTrade = {
+ id: tradeId,
+ portfolioId: this.config.portfolioId,
+ orderId,
+ symbol,
+ side,
+ price,
+ quantity,
+ fee,
+ feeRate,
+ isMaker,
+ timestamp: new Date().toISOString(),
+ };
+
+ await paperTradingDatabase.createTrade(trade);
+
+ // Update position
+ const leverage = params?.leverage || this.config.defaultLeverage || 1;
+ const marginMode = params?.marginMode || this.config.marginMode || 'cross';
+
+ const position = await this.balanceManager.updatePositionAfterFill(
+ this.config.portfolioId,
+ symbol,
+ side,
+ price,
+ quantity,
+ leverage,
+ marginMode
+ );
+
+ // Update portfolio balance (deduct fees)
+ const portfolio = await paperTradingDatabase.getPortfolio(this.config.portfolioId);
+ if (portfolio) {
+ const newBalance = portfolio.currentBalance - fee;
+ await paperTradingDatabase.updatePortfolioBalance(this.config.portfolioId, newBalance);
+ }
+
+ const balance = await this.balanceManager.getBalance(this.config.portfolioId);
+ const currency = this.config.currency || 'USD';
+
+ return {
+ success: true,
+ order: this.createOrderObject(orderId, symbol, 'market', side, quantity, price, params, 'filled'),
+ trades: [trade],
+ position,
+ balance: balance.free[currency] || 0,
+ };
+ }
+
+ // ============================================================================
+ // ORDER MONITORING
+ // ============================================================================
+
+ /**
+ * Start monitoring pending orders
+ */
+ startMonitoring(intervalMs: number = 500): void {
+ if (this.monitoringInterval) {
+ return; // Already monitoring
+ }
+
+ this.monitoringInterval = setInterval(async () => {
+ await this.checkPendingOrders();
+ }, intervalMs);
+ }
+
+ /**
+ * Stop monitoring pending orders
+ */
+ stopMonitoring(): void {
+ if (this.monitoringInterval) {
+ clearInterval(this.monitoringInterval);
+ this.monitoringInterval = null;
+ }
+ }
+
+ /**
+ * Check all pending orders for execution conditions
+ */
+ private async checkPendingOrders(): Promise<void> {
+ try {
+ const pendingOrders = await paperTradingDatabase.getPendingOrders(this.config.portfolioId);
+
+ for (const order of pendingOrders) {
+ try {
+ const priceSnapshot = await this.fetchPriceSnapshot(order.symbol);
+
+ // Check liquidations first
+ await this.checkPositionLiquidations(order.symbol, priceSnapshot.last);
+
+ // Check limit orders
+ if (order.type === 'limit' && order.status === 'pending') {
+ const canFill = order.side === 'buy'
+ ? priceSnapshot.ask <= (order.price || 0)
+ : priceSnapshot.bid >= (order.price || 0);
+
+ if (canFill) {
+ await this.executeLimitOrder(order.id, order.symbol, order.side, order.amount, order.price!, {
+ leverage: order.leverage,
+ marginMode: order.marginMode as any,
+ });
+ }
+ }
+
+ // Check stop orders
+ if ((order.type === 'stop' || order.type === 'stop_limit') && order.status === 'pending') {
+ const triggered = await this.checkStopOrderTrigger(order, priceSnapshot.last);
+ if (triggered) {
+ await this.executeTriggeredStopOrder(order, priceSnapshot.last);
+ }
+ }
+
+ // Update position prices
+ await this.balanceManager.updatePositionPrices(this.config.portfolioId, order.symbol, priceSnapshot.last);
+ } catch (error) {
+ console.error(`Error checking order ${order.id}:`, error);
+ }
+ }
+ } catch (error) {
+ console.error('Error checking pending orders:', error);
+ }
+ }
+
+ /**
+ * Check for position liquidations
+ */
+ private async checkPositionLiquidations(symbol: string, currentPrice: number): Promise<void> {
+ const position = await paperTradingDatabase.getPositionBySymbol(this.config.portfolioId, symbol, 'open');
+ if (!position || !position.liquidationPrice) return;
+
+ const liquidationCheck = await this.balanceManager.checkLiquidation(position, currentPrice);
+ if (liquidationCheck.shouldLiquidate) {
+ await this.balanceManager.executeLiquidation(position, currentPrice);
+ }
+ }
+
+ // ============================================================================
+ // ORDER CANCELLATION
+ // ============================================================================
+
+ /**
+ * Cancel an order
+ */
+ async cancelOrder(orderId: string): Promise<PaperTradingOrder> {
+ const order = await paperTradingDatabase.getOrder(orderId);
+ if (!order) {
+ throw new Error(`Order ${orderId} not found`);
+ }
+
+ if (order.status === 'filled') {
+ throw new Error(`Cannot cancel filled order ${orderId}`);
+ }
+
+ await paperTradingDatabase.updateOrder(orderId, { status: 'canceled' });
+
+ const updatedOrder = await paperTradingDatabase.getOrder(orderId);
+ return updatedOrder!;
+ }
+
+ /**
+ * Cancel all orders for a symbol or all symbols
+ */
+ async cancelAllOrders(symbol?: string): Promise<PaperTradingOrder[]> {
+ const pendingOrders = await paperTradingDatabase.getPendingOrders(this.config.portfolioId);
+
+ const ordersToCancel = symbol
+ ? pendingOrders.filter(o => o.symbol === symbol)
+ : pendingOrders;
+
+ const canceledOrders: PaperTradingOrder[] = [];
+ for (const order of ordersToCancel) {
+ await paperTradingDatabase.updateOrder(order.id, { status: 'canceled' });
+ const updated = await paperTradingDatabase.getOrder(order.id);
+ if (updated) canceledOrders.push(updated);
+ }
+
+ return canceledOrders;
+ }
+
+ // ============================================================================
+ // PRICE DATA
+ // ============================================================================
+
+ /**
+ * Fetch price snapshot from real exchange
+ */
+ private async fetchPriceSnapshot(symbol: string): Promise<PriceSnapshot> {
+ const cached = this.priceCache.get(symbol);
+ const now = Date.now();
+
+ // Use cache if fresh (within 1 second)
+ if (cached && now - cached.timestamp < 1000) {
+ return cached;
+ }
+
+ // Fetch fresh price
+ const ticker = await this.realExchangeAdapter.fetchTicker(symbol);
+
+ const snapshot: PriceSnapshot = {
+ symbol,
+ bid: ticker.bid || ticker.last || 0,
+ ask: ticker.ask || ticker.last || 0,
+ last: ticker.last || 0,
+ timestamp: now,
+ };
+
+ this.priceCache.set(symbol, snapshot);
+ return snapshot;
+ }
+
+ // ============================================================================
+ // UTILITIES
+ // ============================================================================
+
+ private createOrderObject(
+ id: string,
+ symbol: string,
+ type: OrderType,
+ side: OrderSide,
+ amount: number,
+ price?: number,
+ params?: OrderParams,
+ status: string = 'pending'
+ ): PaperTradingOrder {
+ return {
+ id,
+ portfolioId: this.config.portfolioId,
+ symbol,
+ type,
+ side,
+ amount,
+ price,
+ stopPrice: params?.stopPrice,
+ filled: 0,
+ remaining: amount,
+ average: undefined,
+ status: status as any,
+ timestamp: Date.now(),
+ datetime: new Date().toISOString(),
+ timeInForce: params?.timeInForce,
+ postOnly: params?.postOnly,
+ reduceOnly: params?.reduceOnly,
+ trailingPercent: params?.trailingPercent,
+ trailingAmount: params?.trailingAmount,
+ icebergQty: params?.icebergQty,
+ leverage: params?.leverage,
+ marginMode: params?.marginMode,
+ cost: 0,
+ info: {},
+ } as PaperTradingOrder;
+ }
+
+ private sleep(ms: number): Promise<void> {
+ return new Promise(resolve => setTimeout(resolve, ms));
+ }
+
+ /**
+ * Cleanup resources
+ */
+ destroy(): void {
+ this.stopMonitoring();
+ this.priceCache.clear();
+ }
+}
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
new file mode 100644
index 000000000..3f41364b6
--- /dev/null
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
@@ -0,0 +1,703 @@
+/**
+ * Universal Paper Trading Adapter
+ *
+ * Full IExchangeAdapter implementation for realistic paper trading
+ * Works with ANY broker: crypto, stocks, forex, commodities, etc.
+ * Uses real market data from underlying broker adapter for execution simulation
+ */
+
+import type { Market, Ticker, OrderBook, Trade, OHLCV, Balance, Order, Position } from 'ccxt';
+import { BaseExchangeAdapter } from '../brokers/crypto/BaseExchangeAdapter';
+import type {
+ IExchangeAdapter,
+ ExchangeCredentials,
+ ExchangeConfig,
+ ExchangeCapabilities,
+} from '../brokers/crypto/types';
+import type { PaperTradingConfig, OrderType, OrderSide, OrderParams } from './types';
+import { paperTradingDatabase } from './PaperTradingDatabase';
+import { PaperTradingBalance } from './PaperTradingBalance';
+import { OrderMatchingEngine } from './OrderMatchingEngine';
+
+export class PaperTradingAdapter extends BaseExchangeAdapter {
+ private paperConfig: PaperTradingConfig;
+ private realAdapter: IExchangeAdapter;
+ private balanceManager: PaperTradingBalance;
+ private matchingEngine: OrderMatchingEngine;
+ private initialized: boolean = false;
+
+ constructor(config: ExchangeConfig & { paperTradingConfig: PaperTradingConfig; realAdapter: IExchangeAdapter }) {
+ // Initialize base with paper trading exchange ID
+ super({ ...config, exchange: `${config.paperTradingConfig.provider}_paper` });
+
+ this.paperConfig = config.paperTradingConfig;
+ this.realAdapter = config.realAdapter;
+ this.balanceManager = new PaperTradingBalance(this.paperConfig);
+ this.matchingEngine = new OrderMatchingEngine(this.paperConfig, this.realAdapter);
+
+ // Override name
+ this.name = `${this.realAdapter.name} (Paper Trading)`;
+ }
+
+ // ============================================================================
+ // INITIALIZATION
+ // ============================================================================
+
+ async connect(): Promise<void> {
+ try {
+ // Connect to real exchange for market data
+ if (!this.realAdapter.isConnected()) {
+ await this.realAdapter.connect();
+ }
+
+ // Initialize or load portfolio
+ await this.initializePortfolio();
+
+ // Start order monitoring
+ if (this.paperConfig.enableRealtimeUpdates !== false) {
+ this.matchingEngine.startMonitoring(this.paperConfig.priceUpdateInterval || 1000);
+ }
+
+ this._isConnected = true;
+ this._isAuthenticated = true; // Paper trading doesn't require real auth
+ this.initialized = true;
+
+ this.emit('connected', { exchange: this.id });
+ this.emit('authenticated', { exchange: this.id });
+ } catch (error) {
+ this._isConnected = false;
+ throw this.handleError(error);
+ }
+ }
+
+ async disconnect(): Promise<void> {
+ this.matchingEngine.stopMonitoring();
+ this._isConnected = false;
+ this._isAuthenticated = false;
+ this.emit('disconnected', { exchange: this.id });
+ }
+
+ async authenticate(credentials: ExchangeCredentials): Promise<void> {
+ // Paper trading doesn't require authentication
+ // but we'll mark as authenticated for consistency
+ this._isAuthenticated = true;
+ this.emit('authenticated', { exchange: this.id });
+ }
+
+ private async initializePortfolio(): Promise<void> {
+ const existing = await paperTradingDatabase.getPortfolio(this.paperConfig.portfolioId);
+
+ if (!existing) {
+ // Create new portfolio
+ await paperTradingDatabase.createPortfolio({
+ id: this.paperConfig.portfolioId,
+ name: this.paperConfig.portfolioName,
+ provider: this.paperConfig.realExchange,
+ initialBalance: this.paperConfig.initialBalance,
+ currency: this.paperConfig.currency,
+ marginMode: this.paperConfig.marginMode,
+ leverage: this.paperConfig.defaultLeverage,
+ });
+ }
+ }
+
+ // ============================================================================
+ // MARKET DATA (Delegate to real exchange)
+ // ============================================================================
+
+ async fetchMarkets(): Promise<Market[]> {
+ return await this.realAdapter.fetchMarkets();
+ }
+
+ async fetchTicker(symbol: string): Promise<Ticker> {
+ return await this.realAdapter.fetchTicker(symbol);
+ }
+
+ async fetchTickers(symbols?: string[]): Promise<Record<string, Ticker>> {
+ return await this.realAdapter.fetchTickers(symbols);
+ }
+
+ async fetchOrderBook(symbol: string, limit?: number): Promise<OrderBook> {
+ return await this.realAdapter.fetchOrderBook(symbol, limit);
+ }
+
+ async fetchTrades(symbol: string, limit?: number): Promise<Trade[]> {
+ return await this.realAdapter.fetchTrades(symbol, limit);
+ }
+
+ async fetchOHLCV(symbol: string, timeframe: string, limit?: number): Promise<OHLCV[]> {
+ return await this.realAdapter.fetchOHLCV(symbol, timeframe, limit);
+ }
+
+ getMarkets(): Record<string, Market> {
+ return this.exchange.markets || {};
+ }
+
+ async fetchStatus(): Promise<any> {
+ return await this.realAdapter.fetchStatus?.();
+ }
+
+ async fetchCurrencies(): Promise<any> {
+ return await this.realAdapter.fetchCurrencies?.();
+ }
+
+ async fetchTime(): Promise<number> {
+ return await this.realAdapter.fetchTime?.() || Date.now();
+ }
+
+ // ============================================================================
+ // ACCOUNT & BALANCE (Paper trading specific)
+ // ============================================================================
+
+ async fetchBalance(): Promise<Balance> {
+ if (!this.initialized) {
+ throw new Error('Paper trading adapter not initialized. Call connect() first.');
+ }
+
+ const balance = await this.balanceManager.getBalance(this.paperConfig.portfolioId);
+ this.emit('balance', { exchange: this.id, data: balance });
+ return balance;
+ }
+
+ async fetchPositions(symbols?: string[]): Promise<Position[]> {
+ if (!this.initialized) {
+ throw new Error('Paper trading adapter not initialized. Call connect() first.');
+ }
+
+ const positions = await paperTradingDatabase.getPortfolioPositions(this.paperConfig.portfolioId, 'open');
+
+ // Convert to CCXT Position format
+ const ccxtPositions: Position[] = positions
+ .filter(p => !symbols || symbols.includes(p.symbol))
+ .map(p => ({
+ info: p,
+ id: p.id,
+ symbol: p.symbol,
+ timestamp: new Date(p.openedAt).getTime(),
+ datetime: p.openedAt,
+ initialMargin: (p.quantity * p.entryPrice) / p.leverage,
+ initialMarginPercentage: 1 / p.leverage,
+ maintenanceMargin: ((p.quantity * p.entryPrice) / p.leverage) * 0.5,
+ maintenanceMarginPercentage: 0.5 / p.leverage,
+ entryPrice: p.entryPrice,
+ notional: p.quantity * (p.currentPrice || p.entryPrice),
+ leverage: p.leverage,
+ unrealizedPnl: p.unrealizedPnl || 0,
+ contracts: p.quantity,
+ contractSize: 1,
+ marginRatio: null,
+ liquidationPrice: p.liquidationPrice || 0,
+ markPrice: p.currentPrice || p.entryPrice,
+ collateral: (p.quantity * p.entryPrice) / p.leverage,
+ marginMode: p.marginMode,
+ side: p.side === 'long' ? 'long' : 'short',
+ percentage: p.unrealizedPnl ? (p.unrealizedPnl / ((p.quantity * p.entryPrice) / p.leverage)) * 100 : 0,
+ } as Position));
+
+ this.emit('position', { exchange: this.id, data: ccxtPositions });
+ return ccxtPositions;
+ }
+
+ async fetchLedger(code?: string, since?: number, limit?: number): Promise<any> {
+ // Return trades as ledger entries
+ const trades = await paperTradingDatabase.getPortfolioTrades(this.paperConfig.portfolioId, limit);
+ return trades.map(t => ({
+ id: t.id,
+ timestamp: new Date(t.timestamp).getTime(),
+ datetime: t.timestamp,
+ direction: t.side === 'buy' ? 'in' : 'out',
+ account: this.paperConfig.portfolioId,
+ referenceId: t.orderId,
+ referenceAccount: t.symbol,
+ type: 'trade',
+ currency: code || this.paperConfig.currency || 'USD',
+ amount: t.quantity,
+ before: null,
+ after: null,
+ status: 'ok',
+ fee: { cost: t.fee, currency: this.paperConfig.currency || 'USD' },
+ info: t,
+ }));
+ }
+
+ async fetchTradingFee(symbol: string): Promise<any> {
+ return {
+ info: {},
+ symbol,
+ maker: this.paperConfig.fees.maker,
+ taker: this.paperConfig.fees.taker,
+ percentage: true,
+ tierBased: false,
+ };
+ }
+
+ // ============================================================================
+ // TRADING OPERATIONS (Paper trading specific)
+ // ============================================================================
+
+ async createOrder(
+ symbol: string,
+ type: OrderType,
+ side: OrderSide,
+ amount: number,
+ price?: number,
+ params?: OrderParams
+ ): Promise<Order> {
+ if (!this.initialized) {
+ throw new Error('Paper trading adapter not initialized. Call connect() first.');
+ }
+
+ const result = await this.matchingEngine.placeOrder(symbol, type, side, amount, price, params);
+
+ if (!result.success) {
+ throw new Error(result.error || 'Order placement failed');
+ }
+
+ this.emit('order', { exchange: this.id, data: result.order });
+ if (result.position) {
+ this.emit('position', { exchange: this.id, data: result.position });
+ }
+
+ return result.order as Order;
+ }
+
+ async editOrder(
+ orderId: string,
+ symbol: string,
+ type?: OrderType,
+ side?: OrderSide,
+ amount?: number,
+ price?: number,
+ params?: OrderParams
+ ): Promise<Order> {
+ // For paper trading, we'll cancel and recreate the order
+ await this.cancelOrder(orderId, symbol);
+
+ if (!type || !side || !amount) {
+ throw new Error('Edit order requires type, side, and amount');
+ }
+
+ return await this.createOrder(symbol, type, side, amount, price, params);
+ }
+
+ async cancelOrder(orderId: string, symbol: string): Promise<Order> {
+ if (!this.initialized) {
+ throw new Error('Paper trading adapter not initialized. Call connect() first.');
+ }
+
+ const canceledOrder = await this.matchingEngine.cancelOrder(orderId);
+ this.emit('order', { exchange: this.id, data: canceledOrder });
+ return canceledOrder as Order;
+ }
+
+ async cancelOrders(orderIds: string[], symbol?: string): Promise<Order[]> {
+ const canceled: Order[] = [];
+ for (const orderId of orderIds) {
+ const order = await this.cancelOrder(orderId, symbol || '');
+ canceled.push(order);
+ }
+ return canceled;
+ }
+
+ async cancelAllOrders(symbol?: string): Promise<Order[]> {
+ if (!this.initialized) {
+ throw new Error('Paper trading adapter not initialized. Call connect() first.');
+ }
+
+ const canceledOrders = await this.matchingEngine.cancelAllOrders(symbol);
+ for (const order of canceledOrders) {
+ this.emit('order', { exchange: this.id, data: order });
+ }
+ return canceledOrders as Order[];
+ }
+
+ async cancelAllOrdersAfter(timeout: number): Promise<any> {
+ // Implement dead man's switch
+ setTimeout(async () => {
+ await this.cancelAllOrders();
+ }, timeout);
+
+ return { timeout, status: 'scheduled' };
+ }
+
+ async fetchOrder(orderId: string, symbol: string): Promise<Order> {
+ const order = await paperTradingDatabase.getOrder(orderId);
+ if (!order) {
+ throw new Error(`Order ${orderId} not found`);
+ }
+ return order as Order;
+ }
+
+ async fetchOrdersByIds(orderIds: string[], symbol?: string): Promise<Order[]> {
+ const orders: Order[] = [];
+ for (const orderId of orderIds) {
+ const order = await paperTradingDatabase.getOrder(orderId);
+ if (order) orders.push(order as Order);
+ }
+ return orders;
+ }
+
+ async fetchOrderTrades(orderId: string, symbol: string): Promise<Trade[]> {
+ const trades = await paperTradingDatabase.getOrderTrades(orderId);
+
+ return trades.map(t => ({
+ id: t.id,
+ order: orderId,
+ info: t,
+ timestamp: new Date(t.timestamp).getTime(),
+ datetime: t.timestamp,
+ symbol: t.symbol,
+ type: 'limit',
+ side: t.side,
+ takerOrMaker: t.isMaker ? 'maker' : 'taker',
+ price: t.price,
+ amount: t.quantity,
+ cost: t.price * t.quantity,
+ fee: {
+ cost: t.fee,
+ currency: this.paperConfig.currency || 'USD',
+ rate: t.feeRate,
+ },
+ } as Trade));
+ }
+
+ async fetchOpenOrders(symbol?: string): Promise<Order[]> {
+ const orders = await paperTradingDatabase.getPortfolioOrders(this.paperConfig.portfolioId);
+
+ const openOrders = orders.filter(o => ['pending', 'triggered', 'partial'].includes(o.status));
+
+ if (symbol) {
+ return openOrders.filter(o => o.symbol === symbol) as Order[];
+ }
+
+ return openOrders as Order[];
+ }
+
+ async fetchClosedOrders(symbol?: string, limit?: number): Promise<Order[]> {
+ const orders = await paperTradingDatabase.getPortfolioOrders(this.paperConfig.portfolioId);
+
+ let closedOrders = orders.filter(o => ['filled', 'canceled', 'rejected'].includes(o.status));
+
+ if (symbol) {
+ closedOrders = closedOrders.filter(o => o.symbol === symbol);
+ }
+
+ if (limit) {
+ closedOrders = closedOrders.slice(0, limit);
+ }
+
+ return closedOrders as Order[];
+ }
+
+ async fetchMyTrades(symbol?: string, since?: number, limit?: number): Promise<Trade[]> {
+ const trades = await paperTradingDatabase.getPortfolioTrades(this.paperConfig.portfolioId, limit);
+
+ let filteredTrades = trades;
+
+ if (symbol) {
+ filteredTrades = filteredTrades.filter(t => t.symbol === symbol);
+ }
+
+ if (since) {
+ filteredTrades = filteredTrades.filter(t => new Date(t.timestamp).getTime() >= since);
+ }
+
+ return filteredTrades.map(t => ({
+ id: t.id,
+ order: t.orderId,
+ info: t,
+ timestamp: new Date(t.timestamp).getTime(),
+ datetime: t.timestamp,
+ symbol: t.symbol,
+ type: 'limit',
+ side: t.side,
+ takerOrMaker: t.isMaker ? 'maker' : 'taker',
+ price: t.price,
+ amount: t.quantity,
+ cost: t.price * t.quantity,
+ fee: {
+ cost: t.fee,
+ currency: this.paperConfig.currency || 'USD',
+ rate: t.feeRate,
+ },
+ } as Trade));
+ }
+
+ // ============================================================================
+ // ADVANCED ORDER TYPES
+ // ============================================================================
+
+ async createStopLossOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ stopPrice: number,
+ limitPrice?: number
+ ): Promise<Order> {
+ return await this.createOrder(
+ symbol,
+ limitPrice ? 'stop_limit' : 'stop',
+ side,
+ amount,
+ limitPrice,
+ { stopPrice }
+ );
+ }
+
+ async createTakeProfitOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ stopPrice: number,
+ limitPrice?: number
+ ): Promise<Order> {
+ return await this.createOrder(
+ symbol,
+ limitPrice ? 'stop_limit' : 'stop',
+ side,
+ amount,
+ limitPrice,
+ { stopPrice }
+ );
+ }
+
+ async createTrailingStopOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ trailingPercent: number
+ ): Promise<Order> {
+ return await this.createOrder(symbol, 'trailing_stop', side, amount, undefined, { trailingPercent });
+ }
+
+ async createIcebergOrder(
+ symbol: string,
+ side: OrderSide,
+ amount: number,
+ price: number,
+ visibleAmount: number
+ ): Promise<Order> {
+ return await this.createOrder(symbol, 'iceberg', side, amount, price, { icebergQty: visibleAmount });
+ }
+
+ async createMarketOrderWithCost(symbol: string, side: OrderSide, cost: number): Promise<Order> {
+ const ticker = await this.fetchTicker(symbol);
+ const price = side === 'buy' ? ticker.ask || ticker.last || 0 : ticker.bid || ticker.last || 0;
+ const amount = cost / price;
+
+ return await this.createOrder(symbol, 'market', side, amount);
+ }
+
+ async createPostOnlyOrder(symbol: string, side: OrderSide, amount: number, price: number): Promise<Order> {
+ return await this.createOrder(symbol, 'limit', side, amount, price, { postOnly: true });
+ }
+
+ async createReduceOnlyOrder(
+ symbol: string,
+ type: OrderType,
+ side: OrderSide,
+ amount: number,
+ price?: number
+ ): Promise<Order> {
+ return await this.createOrder(symbol, type, side, amount, price, { reduceOnly: true });
+ }
+
+ // ============================================================================
+ // MARGIN & LEVERAGE (Paper trading specific)
+ // ============================================================================
+
+ async setLeverage(symbol: string, leverage: number): Promise<any> {
+ // Update portfolio default leverage
+ const portfolio = await paperTradingDatabase.getPortfolio(this.paperConfig.portfolioId);
+ if (portfolio) {
+ this.paperConfig.defaultLeverage = leverage;
+ }
+
+ return { symbol, leverage };
+ }
+
+ async setMarginMode(symbol: string, marginMode: 'cross' | 'isolated'): Promise<any> {
+ this.paperConfig.marginMode = marginMode;
+ return { symbol, marginMode };
+ }
+
+ // ============================================================================
+ // DEPOSITS & WITHDRAWALS (Not applicable for paper trading)
+ // ============================================================================
+
+ async fetchDeposits(code?: string, since?: number, limit?: number): Promise<any> {
+ return []; // No deposits in paper trading
+ }
+
+ async fetchWithdrawals(code?: string, since?: number, limit?: number): Promise<any> {
+ return []; // No withdrawals in paper trading
+ }
+
+ async fetchDepositAddress(code: string, params?: any): Promise<any> {
+ throw new Error('Deposits not supported in paper trading');
+ }
+
+ async createDepositAddress(code: string, params?: any): Promise<any> {
+ throw new Error('Deposits not supported in paper trading');
+ }
+
+ async fetchDepositMethods(code?: string): Promise<any> {
+ return [];
+ }
+
+ async withdraw(code: string, amount: number, address: string, tag?: string, params?: any): Promise<any> {
+ throw new Error('Withdrawals not supported in paper trading');
+ }
+
+ // ============================================================================
+ // TRANSFERS
+ // ============================================================================
+
+ async transfer(code: string, amount: number, fromAccount: string, toAccount: string): Promise<any> {
+ // Paper trading doesn't have sub-accounts, but we'll return success for compatibility
+ return {
+ info: {},
+ id: `transfer_${Date.now()}`,
+ timestamp: Date.now(),
+ datetime: new Date().toISOString(),
+ currency: code,
+ amount,
+ fromAccount,
+ toAccount,
+ status: 'ok',
+ };
+ }
+
+ async transferOut(code: string, amount: number, params?: any): Promise<any> {
+ return await this.transfer(code, amount, 'main', 'external');
+ }
+
+ // ============================================================================
+ // CAPABILITIES
+ // ============================================================================
+
+ getCapabilities(): ExchangeCapabilities {
+ const realCapabilities = this.realAdapter.getCapabilities?.() || {} as ExchangeCapabilities;
+
+ return {
+ ...realCapabilities,
+ // Paper trading specific overrides
+ spot: this.paperConfig.enableMarginTrading ? true : realCapabilities.spot,
+ margin: this.paperConfig.enableMarginTrading || false,
+ futures: this.paperConfig.enableMarginTrading || false,
+ leverageTrading: this.paperConfig.enableMarginTrading || false,
+ multiAccount: false,
+ subAccounts: false,
+ };
+ }
+
+ // ============================================================================
+ // WEBSOCKET (Optional - delegate to real adapter if available)
+ // ============================================================================
+
+ async *watchTicker(symbol: string): AsyncGenerator<Ticker> {
+ if (this.realAdapter.watchTicker) {
+ yield* this.realAdapter.watchTicker(symbol);
+ } else {
+ throw new Error('WebSocket not supported by underlying adapter');
+ }
+ }
+
+ async *watchOrderBook(symbol: string, limit?: number): AsyncGenerator<OrderBook> {
+ if (this.realAdapter.watchOrderBook) {
+ yield* this.realAdapter.watchOrderBook(symbol, limit);
+ } else {
+ throw new Error('WebSocket not supported by underlying adapter');
+ }
+ }
+
+ async *watchTrades(symbol: string): AsyncGenerator<Trade[]> {
+ if (this.realAdapter.watchTrades) {
+ yield* this.realAdapter.watchTrades(symbol);
+ } else {
+ throw new Error('WebSocket not supported by underlying adapter');
+ }
+ }
+
+ async *watchBalance(): AsyncGenerator<Balance> {
+ // Emit paper trading balance periodically
+ while (true) {
+ const balance = await this.fetchBalance();
+ yield balance;
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ }
+ }
+
+ async *watchOrders(symbol?: string): AsyncGenerator<Order[]> {
+ // Emit paper trading orders periodically
+ while (true) {
+ const orders = await this.fetchOpenOrders(symbol);
+ yield orders;
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ }
+ }
+
+ // ============================================================================
+ // UTILITIES
+ // ============================================================================
+
+ /**
+ * Reset portfolio to initial state
+ */
+ async resetPortfolio(): Promise<void> {
+ // Cancel all orders
+ await this.cancelAllOrders();
+
+ // Close all positions
+ const positions = await paperTradingDatabase.getPortfolioPositions(this.paperConfig.portfolioId, 'open');
+ for (const position of positions) {
+ const closeSide = position.side === 'long' ? 'sell' : 'buy';
+ await this.createOrder(position.symbol, 'market', closeSide, position.quantity, undefined, { reduceOnly: true });
+ }
+
+ // Reset balance
+ await paperTradingDatabase.updatePortfolioBalance(
+ this.paperConfig.portfolioId,
+ this.paperConfig.initialBalance
+ );
+ }
+
+ /**
+ * Get paper trading statistics
+ */
+ async getStatistics(): Promise<any> {
+ const portfolio = await paperTradingDatabase.getPortfolio(this.paperConfig.portfolioId);
+ const positions = await paperTradingDatabase.getPortfolioPositions(this.paperConfig.portfolioId);
+ const trades = await paperTradingDatabase.getPortfolioTrades(this.paperConfig.portfolioId);
+ const pnl = await this.balanceManager.calculatePortfolioPnL(this.paperConfig.portfolioId);
+ const totalValue = await this.balanceManager.calculateTotalValue(this.paperConfig.portfolioId);
+
+ const winningTrades = trades.filter(t => {
+ // Calculate P&L for each trade (simplified)
+ return t.side === 'sell'; // Assume sells close positions
+ });
+
+ return {
+ portfolioId: this.paperConfig.portfolioId,
+ portfolioName: this.paperConfig.portfolioName,
+ initialBalance: this.paperConfig.initialBalance,
+ currentBalance: portfolio?.currentBalance || 0,
+ totalValue,
+ totalPnL: pnl.totalPnL,
+ realizedPnL: pnl.realizedPnL,
+ unrealizedPnL: pnl.unrealizedPnL,
+ totalTrades: trades.length,
+ openPositions: positions.filter(p => p.status === 'open').length,
+ closedPositions: positions.filter(p => p.status === 'closed').length,
+ returnPercent: ((pnl.totalPnL / this.paperConfig.initialBalance) * 100).toFixed(2),
+ };
+ }
+
+ /**
+ * Cleanup resources
+ */
+ async destroy(): Promise<void> {
+ this.matchingEngine.destroy();
+ await this.disconnect();
+ }
+}
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
new file mode 100644
index 000000000..58042eafe
--- /dev/null
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
@@ -0,0 +1,495 @@
+/**
+ * Paper Trading Balance & Position Management
+ *
+ * Handles balance tracking, position management, margin calculations, and liquidation checks
+ */
+
+import type { Balance } from 'ccxt';
+import type {
+ PaperTradingConfig,
+ PaperTradingPortfolio,
+ PaperTradingPosition,
+ MarginRequirement,
+ LiquidationCheck,
+} from './types';
+import type { OrderSide } from '../types';
+import { InsufficientFunds } from '../types';
+import { paperTradingDatabase } from './PaperTradingDatabase';
+
+export class PaperTradingBalance {
+ constructor(private config: PaperTradingConfig) {}
+
+ // ============================================================================
+ // BALANCE OPERATIONS
+ // ============================================================================
+
+ /**
+ * Get current balance in CCXT format
+ */
+ async getBalance(portfolioId: string): Promise<Balance> {
+ const portfolio = await paperTradingDatabase.getPortfolio(portfolioId);
+ if (!portfolio) {
+ throw new Error(`Portfolio ${portfolioId} not found`);
+ }
+
+ const positions = await paperTradingDatabase.getPortfolioPositions(portfolioId, 'open');
+ const marginUsed = this.calculateTotalMarginUsed(positions);
+
+ const currency = portfolio.currency || 'USD';
+ const free = Math.max(0, portfolio.currentBalance - marginUsed);
+ const used = marginUsed;
+ const total = portfolio.currentBalance;
+
+ return {
+ free: { [currency]: free },
+ used: { [currency]: used },
+ total: { [currency]: total },
+ info: {
+ portfolio_id: portfolioId,
+ margin_mode: portfolio.marginMode,
+ leverage: portfolio.leverage,
+ },
+ } as Balance;
+ }
+
+ /**
+ * Check if sufficient funds for an order
+ */
+ async checkSufficientFunds(
+ portfolioId: string,
+ symbol: string,
+ side: OrderSide,
+ quantity: number,
+ price: number,
+ leverage?: number
+ ): Promise<{ sufficient: boolean; required: number; available: number; error?: string }> {
+ const portfolio = await paperTradingDatabase.getPortfolio(portfolioId);
+ if (!portfolio) {
+ return { sufficient: false, required: 0, available: 0, error: 'Portfolio not found' };
+ }
+
+ const effectiveLeverage = leverage || portfolio.leverage || 1;
+ const orderValue = quantity * price;
+ const marginRequired = orderValue / effectiveLeverage;
+
+ // Add fees to required amount
+ const feeRate = side === 'buy' ? this.config.fees.taker : this.config.fees.maker;
+ const fee = orderValue * feeRate;
+ const totalRequired = marginRequired + fee;
+
+ const balance = await this.getBalance(portfolioId);
+ const currency = portfolio.currency || 'USD';
+ const available = balance.free[currency] || 0;
+
+ const sufficient = available >= totalRequired;
+
+ return {
+ sufficient,
+ required: totalRequired,
+ available,
+ error: sufficient ? undefined : `Insufficient funds: ${available.toFixed(2)} ${currency} available, ${totalRequired.toFixed(2)} ${currency} required`,
+ };
+ }
+
+ /**
+ * Lock funds when placing an order
+ */
+ async lockFunds(portfolioId: string, amount: number): Promise<void> {
+ // Funds are implicitly locked by creating positions with margin requirements
+ // No explicit locking needed as we check available funds on each order
+ }
+
+ /**
+ * Release funds when canceling an order
+ */
+ async releaseFunds(portfolioId: string, amount: number): Promise<void> {
+ // No explicit release needed, funds become available when positions close
+ }
+
+ // ============================================================================
+ // POSITION MANAGEMENT
+ // ============================================================================
+
+ /**
+ * Create or update position after order fill
+ */
+ async updatePositionAfterFill(
+ portfolioId: string,
+ symbol: string,
+ side: OrderSide,
+ fillPrice: number,
+ fillQuantity: number,
+ leverage: number,
+ marginMode: 'cross' | 'isolated'
+ ): Promise<PaperTradingPosition> {
+ const existingPosition = await paperTradingDatabase.getPositionBySymbol(portfolioId, symbol, 'open');
+
+ if (!existingPosition) {
+ // Create new position
+ const positionSide = side === 'buy' ? 'long' : 'short';
+ const positionId = `pos_${Date.now()}_${Math.random().toString(36).substring(7)}`;
+
+ const liquidationPrice = this.calculateLiquidationPrice(
+ positionSide,
+ fillPrice,
+ leverage,
+ fillQuantity
+ );
+
+ await paperTradingDatabase.createPosition({
+ id: positionId,
+ portfolioId,
+ symbol,
+ side: positionSide,
+ entryPrice: fillPrice,
+ quantity: fillQuantity,
+ leverage,
+ marginMode,
+ });
+
+ const position = await paperTradingDatabase.getPosition(positionId);
+ if (!position) throw new Error('Failed to create position');
+
+ // Update liquidation price
+ await paperTradingDatabase.updatePosition(positionId, { liquidationPrice });
+
+ return position;
+ } else {
+ // Update existing position
+ const positionSide = existingPosition.side;
+ const orderDirection = side === 'buy' ? 'long' : 'short';
+
+ if (positionSide === orderDirection) {
+ // Adding to position - calculate new average entry price (VWAP)
+ const totalValue = existingPosition.entryPrice * existingPosition.quantity + fillPrice * fillQuantity;
+ const totalQuantity = existingPosition.quantity + fillQuantity;
+ const newEntryPrice = totalValue / totalQuantity;
+
+ const liquidationPrice = this.calculateLiquidationPrice(
+ positionSide,
+ newEntryPrice,
+ leverage,
+ totalQuantity
+ );
+
+ await paperTradingDatabase.updatePosition(existingPosition.id, {
+ quantity: totalQuantity,
+ entryPrice: newEntryPrice,
+ liquidationPrice,
+ });
+ } else {
+ // Reducing or closing position
+ const remainingQuantity = existingPosition.quantity - fillQuantity;
+
+ if (remainingQuantity <= 0) {
+ // Position fully closed - calculate realized P&L
+ const realizedPnl = this.calculateRealizedPnL(
+ existingPosition.side,
+ existingPosition.entryPrice,
+ fillPrice,
+ existingPosition.quantity
+ );
+
+ await paperTradingDatabase.updatePosition(existingPosition.id, {
+ quantity: 0,
+ realizedPnl: existingPosition.realizedPnl + realizedPnl,
+ status: 'closed',
+ closedAt: new Date().toISOString(),
+ });
+
+ // If overfilled, create new position in opposite direction
+ if (remainingQuantity < 0) {
+ const reversalQuantity = Math.abs(remainingQuantity);
+ const newPositionSide = positionSide === 'long' ? 'short' : 'long';
+ const newPositionId = `pos_${Date.now()}_${Math.random().toString(36).substring(7)}`;
+
+ const liquidationPrice = this.calculateLiquidationPrice(
+ newPositionSide,
+ fillPrice,
+ leverage,
+ reversalQuantity
+ );
+
+ await paperTradingDatabase.createPosition({
+ id: newPositionId,
+ portfolioId,
+ symbol,
+ side: newPositionSide,
+ entryPrice: fillPrice,
+ quantity: reversalQuantity,
+ leverage,
+ marginMode,
+ });
+
+ await paperTradingDatabase.updatePosition(newPositionId, { liquidationPrice });
+ }
+ } else {
+ // Position partially closed
+ const closedQuantity = fillQuantity;
+ const realizedPnl = this.calculateRealizedPnL(
+ existingPosition.side,
+ existingPosition.entryPrice,
+ fillPrice,
+ closedQuantity
+ );
+
+ const liquidationPrice = this.calculateLiquidationPrice(
+ existingPosition.side,
+ existingPosition.entryPrice,
+ leverage,
+ remainingQuantity
+ );
+
+ await paperTradingDatabase.updatePosition(existingPosition.id, {
+ quantity: remainingQuantity,
+ realizedPnl: existingPosition.realizedPnl + realizedPnl,
+ liquidationPrice,
+ });
+ }
+ }
+
+ const updatedPosition = await paperTradingDatabase.getPositionBySymbol(portfolioId, symbol, 'open');
+ return updatedPosition!;
+ }
+ }
+
+ /**
+ * Update position prices and unrealized P&L
+ */
+ async updatePositionPrices(portfolioId: string, symbol: string, currentPrice: number): Promise<void> {
+ const position = await paperTradingDatabase.getPositionBySymbol(portfolioId, symbol, 'open');
+ if (!position) return;
+
+ const unrealizedPnl = this.calculateUnrealizedPnL(
+ position.side,
+ position.entryPrice,
+ currentPrice,
+ position.quantity
+ );
+
+ await paperTradingDatabase.updatePosition(position.id, {
+ currentPrice,
+ unrealizedPnl,
+ });
+ }
+
+ /**
+ * Check if position should be liquidated
+ */
+ async checkLiquidation(position: PaperTradingPosition, currentPrice: number): Promise<LiquidationCheck> {
+ if (!position.liquidationPrice) {
+ return { shouldLiquidate: false, position, currentPrice, liquidationPrice: 0, marginRatio: 0 };
+ }
+
+ const shouldLiquidate =
+ (position.side === 'long' && currentPrice <= position.liquidationPrice) ||
+ (position.side === 'short' && currentPrice >= position.liquidationPrice);
+
+ if (!shouldLiquidate) {
+ const marginValue = (position.quantity * position.entryPrice) / position.leverage;
+ const positionValue = position.quantity * currentPrice;
+ const pnl = position.side === 'long'
+ ? positionValue - position.quantity * position.entryPrice
+ : position.quantity * position.entryPrice - positionValue;
+ const equity = marginValue + pnl;
+ const marginRatio = (equity / positionValue) * 100;
+
+ return {
+ shouldLiquidate: false,
+ position,
+ currentPrice,
+ liquidationPrice: position.liquidationPrice,
+ marginRatio,
+ };
+ }
+
+ return {
+ shouldLiquidate: true,
+ position,
+ currentPrice,
+ liquidationPrice: position.liquidationPrice,
+ marginRatio: 0,
+ reason: `Price ${currentPrice} ${position.side === 'long' ? '<=' : '>='} liquidation price ${position.liquidationPrice}`,
+ };
+ }
+
+ /**
+ * Execute liquidation
+ */
+ async executeLiquidation(position: PaperTradingPosition, liquidationPrice: number): Promise<void> {
+ // Calculate final realized P&L at liquidation
+ const realizedPnl = this.calculateRealizedPnL(
+ position.side,
+ position.entryPrice,
+ liquidationPrice,
+ position.quantity
+ );
+
+ await paperTradingDatabase.updatePosition(position.id, {
+ quantity: 0,
+ currentPrice: liquidationPrice,
+ unrealizedPnl: 0,
+ realizedPnl: position.realizedPnl + realizedPnl,
+ status: 'closed',
+ closedAt: new Date().toISOString(),
+ });
+
+ // Update portfolio balance
+ const portfolio = await paperTradingDatabase.getPortfolio(position.portfolioId);
+ if (portfolio) {
+ const newBalance = portfolio.currentBalance + realizedPnl;
+ await paperTradingDatabase.updatePortfolioBalance(position.portfolioId, newBalance);
+ }
+ }
+
+ // ============================================================================
+ // P&L CALCULATIONS
+ // ============================================================================
+
+ /**
+ * Calculate unrealized P&L for a position
+ */
+ calculateUnrealizedPnL(
+ side: 'long' | 'short',
+ entryPrice: number,
+ currentPrice: number,
+ quantity: number
+ ): number {
+ if (side === 'long') {
+ return (currentPrice - entryPrice) * quantity;
+ } else {
+ return (entryPrice - currentPrice) * quantity;
+ }
+ }
+
+ /**
+ * Calculate realized P&L when closing a position
+ */
+ calculateRealizedPnL(
+ side: 'long' | 'short',
+ entryPrice: number,
+ exitPrice: number,
+ quantity: number
+ ): number {
+ if (side === 'long') {
+ return (exitPrice - entryPrice) * quantity;
+ } else {
+ return (entryPrice - exitPrice) * quantity;
+ }
+ }
+
+ /**
+ * Calculate total margin used across all positions
+ */
+ private calculateTotalMarginUsed(positions: PaperTradingPosition[]): number {
+ return positions.reduce((total, position) => {
+ const positionValue = position.quantity * position.entryPrice;
+ const marginUsed = positionValue / position.leverage;
+ return total + marginUsed;
+ }, 0);
+ }
+
+ // ============================================================================
+ // MARGIN & LIQUIDATION CALCULATIONS
+ // ============================================================================
+
+ /**
+ * Calculate margin requirement for a trade
+ */
+ calculateMarginRequirement(
+ symbol: string,
+ side: 'long' | 'short',
+ price: number,
+ quantity: number,
+ leverage: number,
+ marginMode: 'cross' | 'isolated'
+ ): MarginRequirement {
+ const positionValue = price * quantity;
+ const initialMargin = positionValue / leverage;
+
+ // Maintenance margin is typically 50% of initial margin for simplicity
+ const maintenanceMargin = initialMargin * 0.5;
+
+ const liquidationPrice = this.calculateLiquidationPrice(side, price, leverage, quantity);
+
+ return {
+ symbol,
+ side,
+ quantity,
+ price,
+ leverage,
+ marginMode,
+ initialMargin,
+ maintenanceMargin,
+ liquidationPrice,
+ };
+ }
+
+ /**
+ * Calculate liquidation price
+ */
+ private calculateLiquidationPrice(
+ side: 'long' | 'short',
+ entryPrice: number,
+ leverage: number,
+ quantity: number
+ ): number | null {
+ if (leverage <= 1) return null; // No liquidation for unleveraged positions
+
+ // Simplified liquidation calculation
+ // Liquidation occurs when loss equals initial margin (100% of margin lost)
+ // For more accuracy, should consider maintenance margin requirements
+
+ const maintenanceMarginRate = 0.5 / leverage; // 50% of initial margin
+
+ if (side === 'long') {
+ // Long liquidation: price drops by (1 / leverage) * (1 - maintenance margin rate)
+ return entryPrice * (1 - (1 / leverage) + maintenanceMarginRate);
+ } else {
+ // Short liquidation: price rises by (1 / leverage) * (1 - maintenance margin rate)
+ return entryPrice * (1 + (1 / leverage) - maintenanceMarginRate);
+ }
+ }
+
+ // ============================================================================
+ // PORTFOLIO STATISTICS
+ // ============================================================================
+
+ /**
+ * Calculate portfolio total P&L
+ */
+ async calculatePortfolioPnL(portfolioId: string): Promise<{
+ unrealizedPnL: number;
+ realizedPnL: number;
+ totalPnL: number;
+ }> {
+ const positions = await paperTradingDatabase.getPortfolioPositions(portfolioId);
+
+ let unrealizedPnL = 0;
+ let realizedPnL = 0;
+
+ for (const position of positions) {
+ realizedPnL += position.realizedPnl;
+ if (position.status === 'open' && position.unrealizedPnl !== null) {
+ unrealizedPnL += position.unrealizedPnl;
+ }
+ }
+
+ return {
+ unrealizedPnL,
+ realizedPnL,
+ totalPnL: unrealizedPnL + realizedPnL,
+ };
+ }
+
+ /**
+ * Calculate total portfolio value (balance + unrealized P&L)
+ */
+ async calculateTotalValue(portfolioId: string): Promise<number> {
+ const portfolio = await paperTradingDatabase.getPortfolio(portfolioId);
+ if (!portfolio) return 0;
+
+ const { unrealizedPnL } = await this.calculatePortfolioPnL(portfolioId);
+ return portfolio.currentBalance + unrealizedPnL;
+ }
+}
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts
new file mode 100644
index 000000000..dcd8ca0c7
--- /dev/null
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts
@@ -0,0 +1,577 @@
+/**
+ * Paper Trading Database Operations
+ *
+ * Thin wrapper over SQLite service for paper trading data persistence
+ * Uses existing paper_trading_* tables from sqliteService
+ */
+
+import { sqliteService } from '../../../services/sqliteService';
+import type {
+ PaperTradingPortfolio,
+ PaperTradingPosition,
+ PaperTradingOrder,
+ PaperTradingTrade,
+ DBPortfolio,
+ DBPosition,
+ DBOrder,
+ DBTrade,
+} from './types';
+import type { Order, OrderSide } from '../types';
+
+export class PaperTradingDatabase {
+ // ============================================================================
+ // PORTFOLIO OPERATIONS
+ // ============================================================================
+
+ async createPortfolio(portfolio: {
+ id: string;
+ name: string;
+ provider: string;
+ initialBalance: number;
+ currency?: string;
+ marginMode?: 'cross' | 'isolated';
+ leverage?: number;
+ }): Promise<void> {
+ const sql = `
+ INSERT INTO paper_trading_portfolios
+ (id, name, provider, initial_balance, current_balance, currency, margin_mode, leverage)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ `;
+
+ await sqliteService.execute(sql, [
+ portfolio.id,
+ portfolio.name,
+ portfolio.provider,
+ portfolio.initialBalance,
+ portfolio.initialBalance,
+ portfolio.currency || 'USD',
+ portfolio.marginMode || 'cross',
+ portfolio.leverage || 1,
+ ]);
+ }
+
+ async getPortfolio(portfolioId: string): Promise<PaperTradingPortfolio | null> {
+ const sql = `
+ SELECT id, name, provider, initial_balance, current_balance, currency,
+ margin_mode, leverage, created_at, updated_at
+ FROM paper_trading_portfolios
+ WHERE id = $1
+ `;
+
+ const result = await sqliteService.select<DBPortfolio[]>(sql, [portfolioId]);
+
+ if (!result || result.length === 0) {
+ return null;
+ }
+
+ const row = result[0];
+ return this.mapDBPortfolio(row);
+ }
+
+ async updatePortfolioBalance(portfolioId: string, newBalance: number): Promise<void> {
+ const sql = `
+ UPDATE paper_trading_portfolios
+ SET current_balance = $1, updated_at = CURRENT_TIMESTAMP
+ WHERE id = $2
+ `;
+
+ await sqliteService.execute(sql, [newBalance, portfolioId]);
+ }
+
+ async deletePortfolio(portfolioId: string): Promise<void> {
+ // Cascading deletes will remove positions, orders, and trades
+ const sql = `DELETE FROM paper_trading_portfolios WHERE id = $1`;
+ await sqliteService.execute(sql, [portfolioId]);
+ }
+
+ async listPortfolios(): Promise<PaperTradingPortfolio[]> {
+ const sql = `
+ SELECT id, name, provider, initial_balance, current_balance, currency,
+ margin_mode, leverage, created_at, updated_at
+ FROM paper_trading_portfolios
+ ORDER BY created_at DESC
+ `;
+
+ const result = await sqliteService.select<DBPortfolio[]>(sql, []);
+ return result.map(row => this.mapDBPortfolio(row));
+ }
+
+ // ============================================================================
+ // POSITION OPERATIONS
+ // ============================================================================
+
+ async createPosition(position: {
+ id: string;
+ portfolioId: string;
+ symbol: string;
+ side: 'long' | 'short';
+ entryPrice: number;
+ quantity: number;
+ leverage?: number;
+ marginMode?: 'cross' | 'isolated';
+ }): Promise<void> {
+ const sql = `
+ INSERT INTO paper_trading_positions
+ (id, portfolio_id, symbol, side, entry_price, quantity, leverage, margin_mode, status)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'open')
+ `;
+
+ await sqliteService.execute(sql, [
+ position.id,
+ position.portfolioId,
+ position.symbol,
+ position.side,
+ position.entryPrice,
+ position.quantity,
+ position.leverage || 1,
+ position.marginMode || 'cross',
+ ]);
+ }
+
+ async getPosition(positionId: string): Promise<PaperTradingPosition | null> {
+ const sql = `
+ SELECT id, portfolio_id, symbol, side, entry_price, quantity,
+ current_price, unrealized_pnl, realized_pnl, leverage, margin_mode,
+ liquidation_price, opened_at, closed_at, status
+ FROM paper_trading_positions
+ WHERE id = $1
+ `;
+
+ const result = await sqliteService.select<DBPosition[]>(sql, [positionId]);
+
+ if (!result || result.length === 0) {
+ return null;
+ }
+
+ return this.mapDBPosition(result[0]);
+ }
+
+ async getPositionBySymbol(portfolioId: string, symbol: string, status: 'open' | 'closed' = 'open'): Promise<PaperTradingPosition | null> {
+ const sql = `
+ SELECT id, portfolio_id, symbol, side, entry_price, quantity,
+ current_price, unrealized_pnl, realized_pnl, leverage, margin_mode,
+ liquidation_price, opened_at, closed_at, status
+ FROM paper_trading_positions
+ WHERE portfolio_id = $1 AND symbol = $2 AND status = $3
+ ORDER BY opened_at DESC
+ LIMIT 1
+ `;
+
+ const result = await sqliteService.select<DBPosition[]>(sql, [portfolioId, symbol, status]);
+
+ if (!result || result.length === 0) {
+ return null;
+ }
+
+ return this.mapDBPosition(result[0]);
+ }
+
+ async getPortfolioPositions(portfolioId: string, status?: 'open' | 'closed'): Promise<PaperTradingPosition[]> {
+ let sql = `
+ SELECT id, portfolio_id, symbol, side, entry_price, quantity,
+ current_price, unrealized_pnl, realized_pnl, leverage, margin_mode,
+ liquidation_price, opened_at, closed_at, status
+ FROM paper_trading_positions
+ WHERE portfolio_id = $1
+ `;
+
+ const params: any[] = [portfolioId];
+
+ if (status) {
+ sql += ` AND status = $2`;
+ params.push(status);
+ }
+
+ sql += ` ORDER BY opened_at DESC`;
+
+ const result = await sqliteService.select<DBPosition[]>(sql, params);
+ return result.map(row => this.mapDBPosition(row));
+ }
+
+ async updatePosition(positionId: string, updates: {
+ quantity?: number;
+ entryPrice?: number;
+ currentPrice?: number;
+ unrealizedPnl?: number;
+ realizedPnl?: number;
+ liquidationPrice?: number | null;
+ status?: 'open' | 'closed';
+ closedAt?: string | null;
+ }): Promise<void> {
+ const fields: string[] = [];
+ const values: any[] = [];
+ let paramIndex = 1;
+
+ if (updates.quantity !== undefined) {
+ fields.push(`quantity = $${paramIndex++}`);
+ values.push(updates.quantity);
+ }
+ if (updates.entryPrice !== undefined) {
+ fields.push(`entry_price = $${paramIndex++}`);
+ values.push(updates.entryPrice);
+ }
+ if (updates.currentPrice !== undefined) {
+ fields.push(`current_price = $${paramIndex++}`);
+ values.push(updates.currentPrice);
+ }
+ if (updates.unrealizedPnl !== undefined) {
+ fields.push(`unrealized_pnl = $${paramIndex++}`);
+ values.push(updates.unrealizedPnl);
+ }
+ if (updates.realizedPnl !== undefined) {
+ fields.push(`realized_pnl = $${paramIndex++}`);
+ values.push(updates.realizedPnl);
+ }
+ if (updates.liquidationPrice !== undefined) {
+ fields.push(`liquidation_price = $${paramIndex++}`);
+ values.push(updates.liquidationPrice);
+ }
+ if (updates.status !== undefined) {
+ fields.push(`status = $${paramIndex++}`);
+ values.push(updates.status);
+ }
+ if (updates.closedAt !== undefined) {
+ fields.push(`closed_at = $${paramIndex++}`);
+ values.push(updates.closedAt);
+ }
+
+ if (fields.length === 0) return;
+
+ values.push(positionId);
+ const sql = `UPDATE paper_trading_positions SET ${fields.join(', ')} WHERE id = $${paramIndex}`;
+
+ await sqliteService.execute(sql, values);
+ }
+
+ async deletePosition(positionId: string): Promise<void> {
+ const sql = `DELETE FROM paper_trading_positions WHERE id = $1`;
+ await sqliteService.execute(sql, [positionId]);
+ }
+
+ // ============================================================================
+ // ORDER OPERATIONS
+ // ============================================================================
+
+ async createOrder(order: {
+ id: string;
+ portfolioId: string;
+ symbol: string;
+ side: OrderSide;
+ type: string;
+ quantity: number;
+ price?: number | null;
+ stopPrice?: number | null;
+ timeInForce?: string;
+ postOnly?: boolean;
+ reduceOnly?: boolean;
+ trailingPercent?: number | null;
+ trailingAmount?: number | null;
+ icebergQty?: number | null;
+ leverage?: number;
+ marginMode?: string;
+ }): Promise<void> {
+ const sql = `
+ INSERT INTO paper_trading_orders
+ (id, portfolio_id, symbol, side, type, quantity, price, stop_price, status,
+ time_in_force, post_only, reduce_only, trailing_percent, trailing_amount,
+ iceberg_qty, leverage, margin_mode, filled_quantity, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', $9, $10, $11, $12, $13, $14, $15, $16, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
+ `;
+
+ await sqliteService.execute(sql, [
+ order.id,
+ order.portfolioId,
+ order.symbol,
+ order.side,
+ order.type,
+ order.quantity,
+ order.price || null,
+ order.stopPrice || null,
+ order.timeInForce || 'GTC',
+ order.postOnly ? 1 : 0,
+ order.reduceOnly ? 1 : 0,
+ order.trailingPercent || null,
+ order.trailingAmount || null,
+ order.icebergQty || null,
+ order.leverage || null,
+ order.marginMode || null,
+ ]);
+ }
+
+ async getOrder(orderId: string): Promise<PaperTradingOrder | null> {
+ const sql = `
+ SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price,
+ filled_quantity, avg_fill_price, status, time_in_force, post_only,
+ reduce_only, trailing_percent, trailing_amount, iceberg_qty, leverage,
+ margin_mode, created_at, filled_at, updated_at
+ FROM paper_trading_orders
+ WHERE id = $1
+ `;
+
+ const result = await sqliteService.select<DBOrder[]>(sql, [orderId]);
+
+ if (!result || result.length === 0) {
+ return null;
+ }
+
+ return this.mapDBOrder(result[0]);
+ }
+
+ async getPortfolioOrders(portfolioId: string, status?: string): Promise<PaperTradingOrder[]> {
+ let sql = `
+ SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price,
+ filled_quantity, avg_fill_price, status, time_in_force, post_only,
+ reduce_only, trailing_percent, trailing_amount, iceberg_qty, leverage,
+ margin_mode, created_at, filled_at, updated_at
+ FROM paper_trading_orders
+ WHERE portfolio_id = $1
+ `;
+
+ const params: any[] = [portfolioId];
+
+ if (status) {
+ sql += ` AND status = $2`;
+ params.push(status);
+ }
+
+ sql += ` ORDER BY created_at DESC`;
+
+ const result = await sqliteService.select<DBOrder[]>(sql, params);
+ return result.map(row => this.mapDBOrder(row));
+ }
+
+ async getPendingOrders(portfolioId?: string): Promise<PaperTradingOrder[]> {
+ let sql = `
+ SELECT id, portfolio_id, symbol, side, type, quantity, price, stop_price,
+ filled_quantity, avg_fill_price, status, time_in_force, post_only,
+ reduce_only, trailing_percent, trailing_amount, iceberg_qty, leverage,
+ margin_mode, created_at, filled_at, updated_at
+ FROM paper_trading_orders
+ WHERE status IN ('pending', 'triggered', 'partial')
+ `;
+
+ const params: any[] = [];
+
+ if (portfolioId) {
+ sql += ` AND portfolio_id = $1`;
+ params.push(portfolioId);
+ }
+
+ sql += ` ORDER BY created_at ASC`;
+
+ const result = await sqliteService.select<DBOrder[]>(sql, params);
+ return result.map(row => this.mapDBOrder(row));
+ }
+
+ async updateOrder(orderId: string, updates: {
+ filledQuantity?: number;
+ avgFillPrice?: number;
+ status?: string;
+ filledAt?: string | null;
+ }): Promise<void> {
+ const fields: string[] = ['updated_at = CURRENT_TIMESTAMP'];
+ const values: any[] = [];
+ let paramIndex = 1;
+
+ if (updates.filledQuantity !== undefined) {
+ fields.push(`filled_quantity = $${paramIndex++}`);
+ values.push(updates.filledQuantity);
+ }
+ if (updates.avgFillPrice !== undefined) {
+ fields.push(`avg_fill_price = $${paramIndex++}`);
+ values.push(updates.avgFillPrice);
+ }
+ if (updates.status !== undefined) {
+ fields.push(`status = $${paramIndex++}`);
+ values.push(updates.status);
+ }
+ if (updates.filledAt !== undefined) {
+ fields.push(`filled_at = $${paramIndex++}`);
+ values.push(updates.filledAt);
+ }
+
+ values.push(orderId);
+ const sql = `UPDATE paper_trading_orders SET ${fields.join(', ')} WHERE id = $${paramIndex}`;
+
+ await sqliteService.execute(sql, values);
+ }
+
+ async deleteOrder(orderId: string): Promise<void> {
+ const sql = `DELETE FROM paper_trading_orders WHERE id = $1`;
+ await sqliteService.execute(sql, [orderId]);
+ }
+
+ // ============================================================================
+ // TRADE OPERATIONS
+ // ============================================================================
+
+ async createTrade(trade: {
+ id: string;
+ portfolioId: string;
+ orderId: string;
+ symbol: string;
+ side: OrderSide;
+ price: number;
+ quantity: number;
+ fee: number;
+ feeRate: number;
+ isMaker: boolean;
+ }): Promise<void> {
+ const sql = `
+ INSERT INTO paper_trading_trades
+ (id, portfolio_id, order_id, symbol, side, price, quantity, fee, fee_rate, is_maker, timestamp)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, CURRENT_TIMESTAMP)
+ `;
+
+ await sqliteService.execute(sql, [
+ trade.id,
+ trade.portfolioId,
+ trade.orderId,
+ trade.symbol,
+ trade.side,
+ trade.price,
+ trade.quantity,
+ trade.fee,
+ trade.feeRate,
+ trade.isMaker ? 1 : 0,
+ ]);
+ }
+
+ async getTrade(tradeId: string): Promise<PaperTradingTrade | null> {
+ const sql = `
+ SELECT id, portfolio_id, order_id, symbol, side, price, quantity,
+ fee, fee_rate, is_maker, timestamp
+ FROM paper_trading_trades
+ WHERE id = $1
+ `;
+
+ const result = await sqliteService.select<DBTrade[]>(sql, [tradeId]);
+
+ if (!result || result.length === 0) {
+ return null;
+ }
+
+ return this.mapDBTrade(result[0]);
+ }
+
+ async getPortfolioTrades(portfolioId: string, limit?: number): Promise<PaperTradingTrade[]> {
+ let sql = `
+ SELECT id, portfolio_id, order_id, symbol, side, price, quantity,
+ fee, fee_rate, is_maker, timestamp
+ FROM paper_trading_trades
+ WHERE portfolio_id = $1
+ ORDER BY timestamp DESC
+ `;
+
+ const params: any[] = [portfolioId];
+
+ if (limit) {
+ sql += ` LIMIT $2`;
+ params.push(limit);
+ }
+
+ const result = await sqliteService.select<DBTrade[]>(sql, params);
+ return result.map(row => this.mapDBTrade(row));
+ }
+
+ async getOrderTrades(orderId: string): Promise<PaperTradingTrade[]> {
+ const sql = `
+ SELECT id, portfolio_id, order_id, symbol, side, price, quantity,
+ fee, fee_rate, is_maker, timestamp
+ FROM paper_trading_trades
+ WHERE order_id = $1
+ ORDER BY timestamp ASC
+ `;
+
+ const result = await sqliteService.select<DBTrade[]>(sql, [orderId]);
+ return result.map(row => this.mapDBTrade(row));
+ }
+
+ // ============================================================================
+ // MAPPING FUNCTIONS
+ // ============================================================================
+
+ private mapDBPortfolio(row: DBPortfolio): PaperTradingPortfolio {
+ return {
+ id: row.id,
+ name: row.name,
+ provider: row.provider,
+ initialBalance: row.initial_balance,
+ currentBalance: row.current_balance,
+ currency: row.currency || 'USD',
+ marginMode: row.margin_mode || 'cross',
+ leverage: row.leverage || 1,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+ }
+
+ private mapDBPosition(row: DBPosition): PaperTradingPosition {
+ return {
+ id: row.id,
+ portfolioId: row.portfolio_id,
+ symbol: row.symbol,
+ side: row.side,
+ entryPrice: row.entry_price,
+ quantity: row.quantity,
+ currentPrice: row.current_price,
+ unrealizedPnl: row.unrealized_pnl,
+ realizedPnl: row.realized_pnl,
+ leverage: row.leverage,
+ marginMode: row.margin_mode,
+ liquidationPrice: row.liquidation_price,
+ openedAt: row.opened_at,
+ closedAt: row.closed_at,
+ status: row.status,
+ };
+ }
+
+ private mapDBOrder(row: DBOrder): PaperTradingOrder {
+ return {
+ id: row.id,
+ portfolioId: row.portfolio_id,
+ symbol: row.symbol,
+ side: row.side,
+ type: row.type as any,
+ amount: row.quantity,
+ price: row.price || undefined,
+ stopPrice: row.stop_price || undefined,
+ filled: row.filled_quantity,
+ average: row.avg_fill_price || undefined,
+ status: row.status as any,
+ timestamp: new Date(row.created_at).getTime(),
+ datetime: row.created_at,
+ timeInForce: row.time_in_force || undefined,
+ postOnly: row.post_only === 1,
+ reduceOnly: row.reduce_only === 1,
+ trailingPercent: row.trailing_percent || undefined,
+ trailingAmount: row.trailing_amount || undefined,
+ icebergQty: row.iceberg_qty || undefined,
+ leverage: row.leverage || undefined,
+ marginMode: row.margin_mode as any,
+ lastTradeTimestamp: row.filled_at ? new Date(row.filled_at).getTime() : undefined,
+ remaining: row.quantity - row.filled_quantity,
+ cost: (row.avg_fill_price || 0) * row.filled_quantity,
+ info: {}, // Raw exchange response (not applicable for paper trading)
+ } as PaperTradingOrder;
+ }
+
+ private mapDBTrade(row: DBTrade): PaperTradingTrade {
+ return {
+ id: row.id,
+ portfolioId: row.portfolio_id,
+ orderId: row.order_id,
+ symbol: row.symbol,
+ side: row.side,
+ price: row.price,
+ quantity: row.quantity,
+ fee: row.fee,
+ feeRate: row.fee_rate,
+ isMaker: row.is_maker === 1,
+ timestamp: row.timestamp,
+ };
+ }
+}
+
+// Singleton instance
+export const paperTradingDatabase = new PaperTradingDatabase();
diff --git a/fincept-terminal-desktop/src/paper-trading/README.md b/fincept-terminal-desktop/src/paper-trading/README.md
new file mode 100644
index 000000000..81f02482d
--- /dev/null
+++ b/fincept-terminal-desktop/src/paper-trading/README.md
@@ -0,0 +1,51 @@
+# Universal Paper Trading Module
+
+**Professional-grade paper trading system for ANY asset class and broker.**
+
+This standalone module provides realistic trading simulation with support for:
+- ✅ **Crypto** (Kraken, HyperLiquid, Binance, etc.)
+- ✅ **Stocks** (Zerodha, Interactive Brokers, etc.)
+- ✅ **Forex** (any FX broker)
+- ✅ **Commodities** (any commodity broker)
+- ✅ **Options, Futures** (any derivatives broker)
+
+## Features
+
+### Core Capabilities
+- ✅ **Universal Adapter**: Works with ANY broker via unified interface
+- ✅ **Real-Time Market Data**: Uses live prices from actual exchanges
+- ✅ **All Order Types**: Market, Limit, Stop, Stop-Limit, Trailing Stop, Iceberg
+- ✅ **Margin Trading**: Full spot & leveraged trading (up to 50x)
+- ✅ **Position Management**: Long/short positions with real-time P&L
+- ✅ **Realistic Execution**: Order matching based on real order books
+- ✅ **Fees & Slippage**: Configurable maker/taker fees and slippage
+- ✅ **Risk Management**: Margin requirements, liquidation simulation
+- ✅ **Database Persistence**: SQLite for reliability across sessions
+- ✅ **Event System**: Real-time events for UI updates
+
+## Quick Start
+
+```typescript
+import { createPaperTradingAdapter } from '@/paper-trading';
+
+const adapter = createPaperTradingAdapter({
+ portfolioId: 'my-portfolio',
+ portfolioName: 'Test Strategy',
+ provider: 'kraken', // or any other broker
+ initialBalance: 100000,
+ fees: { maker: 0.0002, taker: 0.0005 },
+ slippage: { market: 0.001, limit: 0 },
+ realAdapter: realBrokerAdapter, // Actual broker adapter for market data
+});
+
+await adapter.connect();
+await adapter.createOrder('BTC/USD', 'market', 'buy', 0.1);
+```
+
+See full documentation in the file for advanced usage, configuration, and examples.
+
+---
+
+**Version**: 2.0.0
+**Location**: `src/paper-trading/`
+**Universal**: Works with any broker (crypto, stocks, forex, commodities)
diff --git a/fincept-terminal-desktop/src/paper-trading/index.ts b/fincept-terminal-desktop/src/paper-trading/index.ts
new file mode 100644
index 000000000..ece038dd9
--- /dev/null
+++ b/fincept-terminal-desktop/src/paper-trading/index.ts
@@ -0,0 +1,87 @@
+/**
+ * Universal Paper Trading Module
+ *
+ * Professional-grade paper trading system for ANY broker/exchange
+ * Works with crypto, stocks, forex, commodities, options, futures, etc.
+ * Drop-in replacement for real trading adapters
+ */
+
+export * from './types';
+export { PaperTradingAdapter } from './PaperTradingAdapter';
+export { PaperTradingDatabase, paperTradingDatabase } from './PaperTradingDatabase';
+export { PaperTradingBalance } from './PaperTradingBalance';
+export { OrderMatchingEngine } from './OrderMatchingEngine';
+
+// Helper function to create paper trading adapter
+import type { ExchangeConfig } from '../brokers/crypto/types';
+import type { PaperTradingConfig } from './types';
+import { PaperTradingAdapter } from './PaperTradingAdapter';
+import type { IExchangeAdapter } from '../brokers/crypto/types';
+
+/**
+ * Create a universal paper trading adapter for ANY broker
+ *
+ * This function creates a paper trading adapter that wraps a real broker adapter,
+ * allowing you to simulate trading with virtual money while using real market data.
+ *
+ * @param config - Paper trading configuration
+ * @param realAdapter - The actual broker adapter to use for market data
+ *
+ * @example Crypto (Kraken)
+ * ```typescript
+ * import { createPaperTradingAdapter } from '@/paper-trading';
+ * import { createExchangeAdapter } from '@/brokers/crypto';
+ *
+ * const krakenAdapter = createExchangeAdapter('kraken');
+ * const paperAdapter = createPaperTradingAdapter({
+ * portfolioId: 'my-crypto-portfolio',
+ * portfolioName: 'BTC Strategy',
+ * provider: 'kraken',
+ * assetClass: 'crypto',
+ * initialBalance: 100000,
+ * fees: { maker: 0.0002, taker: 0.0005 },
+ * slippage: { market: 0.001, limit: 0 },
+ * }, krakenAdapter);
+ *
+ * await paperAdapter.connect();
+ * const order = await paperAdapter.createOrder('BTC/USD', 'market', 'buy', 0.1);
+ * ```
+ *
+ * @example Stocks (Zerodha)
+ * ```typescript
+ * import { createPaperTradingAdapter } from '@/paper-trading';
+ * import { createKiteAdapter } from '@/brokers/stocks';
+ *
+ * const kiteAdapter = createKiteAdapter({ apiKey: 'xxx', apiSecret: 'yyy' });
+ * const paperAdapter = createPaperTradingAdapter({
+ * portfolioId: 'my-stock-portfolio',
+ * portfolioName: 'NIFTY Strategy',
+ * provider: 'zerodha',
+ * assetClass: 'stocks',
+ * initialBalance: 1000000, // ₹10L
+ * currency: 'INR',
+ * fees: { maker: 0.0003, taker: 0.0003 },
+ * slippage: { market: 0.0005, limit: 0 },
+ * }, kiteAdapter);
+ *
+ * await paperAdapter.connect();
+ * const order = await paperAdapter.createOrder('RELIANCE', 'limit', 'buy', 10, 2500);
+ * ```
+ */
+export function createPaperTradingAdapter(
+ config: PaperTradingConfig,
+ realAdapter: IExchangeAdapter
+): PaperTradingAdapter {
+ // Create paper trading adapter with real broker adapter
+ const exchangeConfig: ExchangeConfig & {
+ paperTradingConfig: PaperTradingConfig;
+ realAdapter: IExchangeAdapter;
+ } = {
+ exchange: `${config.provider}_paper`,
+ enableRateLimit: true,
+ paperTradingConfig: config,
+ realAdapter,
+ };
+
+ return new PaperTradingAdapter(exchangeConfig);
+}
diff --git a/fincept-terminal-desktop/src/paper-trading/types.ts b/fincept-terminal-desktop/src/paper-trading/types.ts
new file mode 100644
index 000000000..bb7bb43c5
--- /dev/null
+++ b/fincept-terminal-desktop/src/paper-trading/types.ts
@@ -0,0 +1,291 @@
+/**
+ * Paper Trading Module - Standalone Types
+ *
+ * Universal paper trading system that works with any broker/exchange
+ * Supports crypto, stocks, forex, commodities, etc.
+ */
+
+import type { Order, Balance, Position } from 'ccxt';
+
+// Re-export common types for convenience
+export type OrderType =
+ | 'market'
+ | 'limit'
+ | 'stop'
+ | 'stop_limit'
+ | 'trailing_stop'
+ | 'iceberg'
+ | 'twap'
+ | 'vwap';
+
+export type OrderSide = 'buy' | 'sell';
+
+export interface OrderParams {
+ timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'PO';
+ postOnly?: boolean;
+ reduceOnly?: boolean;
+ stopPrice?: number;
+ triggerPrice?: number;
+ trailingAmount?: number;
+ trailingPercent?: number;
+ icebergQty?: number;
+ clientOrderId?: string;
+ leverage?: number;
+ marginMode?: 'cross' | 'isolated';
+ [key: string]: any;
+}
+
+// ============================================================================
+// PAPER TRADING CONFIG
+// ============================================================================
+
+export interface PaperTradingConfig {
+ // Core settings
+ portfolioId: string;
+ portfolioName: string;
+ provider: string; // Any provider: 'kraken', 'hyperliquid', 'zerodha', 'binance', etc.
+ assetClass?: 'crypto' | 'stocks' | 'forex' | 'commodities'; // Optional classification
+ initialBalance: number;
+ currency?: string; // Default: 'USD'
+
+ // Execution settings
+ fees: {
+ maker: number; // e.g., 0.0002 (0.02%)
+ taker: number; // e.g., 0.0005 (0.05%)
+ };
+
+ slippage: {
+ market: number; // e.g., 0.001 (0.1%)
+ limit: number; // Usually 0
+ };
+
+ // Risk settings (optional)
+ maxPositionSize?: number;
+ maxLeverage?: number;
+ defaultLeverage?: number; // Default: 1
+ marginMode?: 'cross' | 'isolated'; // Default: 'cross'
+
+ // Simulation settings (optional)
+ simulatedLatency?: number; // ms delay (default: 0)
+ partialFills?: boolean; // Enable partial order fills (default: false)
+ enableMarginTrading?: boolean; // Enable leverage trading (default: false)
+
+ // WebSocket settings
+ enableRealtimeUpdates?: boolean; // Use real-time prices (default: true)
+ priceUpdateInterval?: number; // Fallback polling interval in ms (default: 1000)
+}
+
+// ============================================================================
+// PAPER TRADING STATE
+// ============================================================================
+
+export interface PaperTradingPortfolio {
+ id: string;
+ name: string;
+ provider: string;
+ initialBalance: number;
+ currentBalance: number;
+ currency: string;
+ marginMode: 'cross' | 'isolated';
+ leverage: number;
+ createdAt: string;
+ updatedAt: string;
+
+ // Runtime state (not persisted)
+ totalPnL?: number;
+ unrealizedPnL?: number;
+ realizedPnL?: number;
+ totalValue?: number; // balance + unrealized PnL
+ marginUsed?: number;
+ marginAvailable?: number;
+}
+
+export interface PaperTradingPosition {
+ id: string;
+ portfolioId: string;
+ symbol: string;
+ side: 'long' | 'short';
+ entryPrice: number;
+ quantity: number;
+ currentPrice: number | null;
+ unrealizedPnl: number | null;
+ realizedPnl: number;
+ leverage: number;
+ marginMode: 'cross' | 'isolated';
+ liquidationPrice: number | null;
+ openedAt: string;
+ closedAt: string | null;
+ status: 'open' | 'closed';
+}
+
+export interface PaperTradingOrder extends Order {
+ portfolioId: string;
+ stopPrice?: number | null;
+ trailingAmount?: number | null;
+ trailingPercent?: number | null;
+ icebergQty?: number | null;
+ triggerPrice?: number | null;
+ timeInForce?: string;
+ postOnly?: boolean;
+ reduceOnly?: boolean;
+ leverage?: number;
+ marginMode?: 'cross' | 'isolated';
+}
+
+export interface PaperTradingTrade {
+ id: string;
+ portfolioId: string;
+ orderId: string;
+ symbol: string;
+ side: OrderSide;
+ price: number;
+ quantity: number;
+ fee: number;
+ feeRate: number;
+ isMaker: boolean;
+ timestamp: string;
+}
+
+// ============================================================================
+// ORDER MATCHING
+// ============================================================================
+
+export interface OrderMatchResult {
+ success: boolean;
+ order: PaperTradingOrder;
+ trades: PaperTradingTrade[];
+ position?: PaperTradingPosition;
+ balance: number;
+ error?: string;
+}
+
+export interface PriceSnapshot {
+ symbol: string;
+ bid: number;
+ ask: number;
+ last: number;
+ timestamp: number;
+}
+
+// ============================================================================
+// MARGIN & LIQUIDATION
+// ============================================================================
+
+export interface MarginRequirement {
+ symbol: string;
+ side: 'long' | 'short';
+ quantity: number;
+ price: number;
+ leverage: number;
+ marginMode: 'cross' | 'isolated';
+ initialMargin: number;
+ maintenanceMargin: number;
+ liquidationPrice: number | null;
+}
+
+export interface LiquidationCheck {
+ shouldLiquidate: boolean;
+ position: PaperTradingPosition;
+ currentPrice: number;
+ liquidationPrice: number;
+ marginRatio: number;
+ reason?: string;
+}
+
+// ============================================================================
+// STATISTICS
+// ============================================================================
+
+export interface PaperTradingStats {
+ portfolioId: string;
+ totalTrades: number;
+ winningTrades: number;
+ losingTrades: number;
+ winRate: number;
+ totalPnL: number;
+ realizedPnL: number;
+ unrealizedPnL: number;
+ totalFees: number;
+ averageWin: number;
+ averageLoss: number;
+ largestWin: number;
+ largestLoss: number;
+ profitFactor: number;
+ sharpeRatio: number | null;
+ maxDrawdown: number | null;
+ avgHoldingPeriod: number | null; // in minutes
+}
+
+// ============================================================================
+// DATABASE TYPES
+// ============================================================================
+
+export interface DBPortfolio {
+ id: string;
+ name: string;
+ provider: string;
+ initial_balance: number;
+ current_balance: number;
+ currency: string;
+ margin_mode: 'cross' | 'isolated';
+ leverage: number;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface DBPosition {
+ id: string;
+ portfolio_id: string;
+ symbol: string;
+ side: 'long' | 'short';
+ entry_price: number;
+ quantity: number;
+ current_price: number | null;
+ unrealized_pnl: number | null;
+ realized_pnl: number;
+ leverage: number;
+ margin_mode: 'cross' | 'isolated';
+ liquidation_price: number | null;
+ opened_at: string;
+ closed_at: string | null;
+ status: 'open' | 'closed';
+}
+
+export interface DBOrder {
+ id: string;
+ portfolio_id: string;
+ symbol: string;
+ side: 'buy' | 'sell';
+ type: string;
+ quantity: number;
+ price: number | null;
+ stop_price: number | null;
+ filled_quantity: number;
+ avg_fill_price: number | null;
+ status: string;
+ time_in_force: string | null;
+ post_only: number; // SQLite boolean (0/1)
+ reduce_only: number;
+ trailing_percent: number | null;
+ trailing_amount: number | null;
+ iceberg_qty: number | null;
+ leverage: number | null;
+ margin_mode: string | null;
+ created_at: string;
+ filled_at: string | null;
+ updated_at: string;
+}
+
+export interface DBTrade {
+ id: string;
+ portfolio_id: string;
+ order_id: string;
+ symbol: string;
+ side: 'buy' | 'sell';
+ price: number;
+ quantity: number;
+ fee: number;
+ fee_rate: number;
+ is_maker: number; // SQLite boolean (0/1)
+ timestamp: string;
+}
diff --git a/fincept-terminal-desktop/src/services/hyperliquid/hyperliquidApi.ts b/fincept-terminal-desktop/src/services/hyperliquid/hyperliquidApi.ts
deleted file mode 100644
index 3fc21b6ea..000000000
--- a/fincept-terminal-desktop/src/services/hyperliquid/hyperliquidApi.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-// File: src/services/hyperliquid/hyperliquidApi.ts
-// HyperLiquid REST API service
-// Documentation: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint
-
-import type {
- HyperLiquidCandle,
- HyperLiquidCandleInterval,
- HyperLiquidAssetInfo,
- HyperLiquidL2BookData,
- HyperLiquidClearinghouseState
-} from '../../types/hyperliquid';
-
-/**
- * HyperLiquid REST API Client
- * Provides methods for fetching historical data and account information
- */
-export class HyperLiquidApi {
- private readonly baseUrl: string;
- private readonly testnet: boolean;
-
- constructor(testnet: boolean = false) {
- this.testnet = testnet;
- this.baseUrl = testnet
- ? 'https://api.hyperliquid-testnet.xyz'
- : 'https://api.hyperliquid.xyz';
- }
-
- /**
- * Make POST request to /info endpoint
- */
- private async request<T>(body: any): Promise<T> {
- const response = await fetch(`${this.baseUrl}/info`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(body)
- });
-
- if (!response.ok) {
- throw new Error(`HyperLiquid API error: ${response.status} ${response.statusText}`);
- }
-
- return response.json();
- }
-
- /**
- * Get candlestick/OHLC data
- * @param coin - Symbol (e.g., 'BTC', 'ETH')
- * @param interval - Candle interval (1m, 5m, 15m, 30m, 1h, 4h, 1d, etc.)
- * @param startTime - Start timestamp in milliseconds
- * @param endTime - End timestamp in milliseconds (optional, defaults to now)
- * @returns Array of candles (max 5000)
- */
- async getCandles(
- coin: string,
- interval: HyperLiquidCandleInterval,
- startTime: number,
- endTime?: number
- ): Promise<HyperLiquidCandle[]> {
- const body = {
- type: 'candleSnapshot',
- req: {
- coin,
- interval,
- startTime,
- ...(endTime && { endTime })
- }
- };
-
- const response = await this.request<HyperLiquidCandle[]>(body);
- return response;
- }
-
- /**
- * Get mid-prices for all coins
- * @returns Record of coin -> mid price
- */
- async getAllMids(): Promise<Record<string, string>> {
- const body = {
- type: 'allMids'
- };
-
- const response = await this.request<Record<string, string>>(body);
- return response;
- }
-
- /**
- * Get L2 order book snapshot
- * @param coin - Symbol (e.g., 'BTC', 'ETH')
- * @param nSigFigs - Number of significant figures (2-5, default: 5)
- * @param mantissa - Mantissa value (1, 2, or 5, only with nSigFigs=5)
- * @returns Order book with bids and asks
- */
- async getL2Book(
- coin: string,
- nSigFigs: number = 5,
- mantissa?: 1 | 2 | 5
- ): Promise<HyperLiquidL2BookData> {
- const body: any = {
- type: 'l2Book',
- coin,
- nSigFigs
- };
-
- if (mantissa && nSigFigs === 5) {
- body.mantissa = mantissa;
- }
-
- const response = await this.request<HyperLiquidL2BookData>(body);
- return response;
- }
-
- /**
- * Get user's clearinghouse state (positions, balances, etc.)
- * @param userAddress - User's wallet address
- * @returns User state including positions and account value
- */
- async getUserState(userAddress: string): Promise<HyperLiquidClearinghouseState> {
- const body = {
- type: 'clearinghouseState',
- user: userAddress
- };
-
- const response = await this.request<HyperLiquidClearinghouseState>(body);
- return response;
- }
-
- /**
- * Get user's open orders
- * @param userAddress - User's wallet address
- * @returns Array of open orders
- */
- async getOpenOrders(userAddress: string): Promise<any[]> {
- const body = {
- type: 'openOrders',
- user: userAddress
- };
-
- const response = await this.request<any[]>(body);
- return response;
- }
-
- /**
- * Get user's fill history
- * @param userAddress - User's wallet address
- * @param aggregateByTime - Whether to aggregate fills by time (default: false)
- * @returns Array of fills (max 2000 most recent)
- */
- async getUserFills(userAddress: string, aggregateByTime: boolean = false): Promise<any[]> {
- const body = {
- type: 'userFills',
- user: userAddress,
- aggregateByTime
- };
-
- const response = await this.request<any[]>(body);
- return response;
- }
-
- /**
- * Get user's fills by time range
- * @param userAddress - User's wallet address
- * @param startTime - Start timestamp in milliseconds
- * @param endTime - End timestamp in milliseconds (optional, defaults to now)
- * @returns Array of fills (max 2000)
- */
- async getUserFillsByTime(
- userAddress: string,
- startTime: number,
- endTime?: number
- ): Promise<any[]> {
- const body = {
- type: 'userFillsByTime',
- user: userAddress,
- startTime,
- ...(endTime && { endTime })
- };
-
- const response = await this.request<any[]>(body);
- return response;
- }
-
- /**
- * Get metadata about available assets
- * @returns Universe of tradeable assets with their properties
- */
- async getMeta(): Promise<{ universe: HyperLiquidAssetInfo[] }> {
- const body = {
- type: 'meta'
- };
-
- const response = await this.request<{ universe: HyperLiquidAssetInfo[] }>(body);
- return response;
- }
-
- /**
- * Get funding rate history for a coin
- * @param coin - Symbol (e.g., 'BTC', 'ETH')
- * @param startTime - Start timestamp in milliseconds
- * @param endTime - End timestamp in milliseconds (optional)
- * @returns Array of funding rate data
- */
- async getFundingHistory(
- coin: string,
- startTime: number,
- endTime?: number
- ): Promise<any[]> {
- const body = {
- type: 'fundingHistory',
- coin,
- startTime,
- ...(endTime && { endTime })
- };
-
- const response = await this.request<any[]>(body);
- return response;
- }
-
- /**
- * Convenience method: Get latest price for a coin
- * @param coin - Symbol (e.g., 'BTC', 'ETH')
- * @returns Current mid-price as number
- */
- async getCurrentPrice(coin: string): Promise<number> {
- const allMids = await this.getAllMids();
- const price = allMids[coin];
-
- if (!price) {
- throw new Error(`No price found for ${coin}`);
- }
-
- return parseFloat(price);
- }
-
- /**
- * Convenience method: Get recent candles (last N periods)
- * @param coin - Symbol (e.g., 'BTC', 'ETH')
- * @param interval - Candle interval
- * @param count - Number of candles to fetch (max 5000)
- * @returns Array of recent candles
- */
- async getRecentCandles(
- coin: string,
- interval: HyperLiquidCandleInterval,
- count: number = 100
- ): Promise<HyperLiquidCandle[]> {
- // Calculate time range based on interval
- const intervalMs = this.intervalToMs(interval);
- const endTime = Date.now();
- const startTime = endTime - (intervalMs * count);
-
- return this.getCandles(coin, interval, startTime, endTime);
- }
-
- /**
- * Convert interval string to milliseconds
- */
- private intervalToMs(interval: HyperLiquidCandleInterval): number {
- const map: Record<string, number> = {
- '1m': 60 * 1000,
- '3m': 3 * 60 * 1000,
- '5m': 5 * 60 * 1000,
- '15m': 15 * 60 * 1000,
- '30m': 30 * 60 * 1000,
- '1h': 60 * 60 * 1000,
- '2h': 2 * 60 * 60 * 1000,
- '4h': 4 * 60 * 60 * 1000,
- '8h': 8 * 60 * 60 * 1000,
- '12h': 12 * 60 * 60 * 1000,
- '1d': 24 * 60 * 60 * 1000,
- '3d': 3 * 24 * 60 * 60 * 1000,
- '1w': 7 * 24 * 60 * 60 * 1000,
- '1M': 30 * 24 * 60 * 60 * 1000
- };
-
- return map[interval] || 60 * 1000;
- }
-}
-
-/**
- * Create API instance
- * @param testnet - Whether to use testnet (default: false)
- */
-export function createHyperLiquidApi(testnet: boolean = false): HyperLiquidApi {
- return new HyperLiquidApi(testnet);
-}
-
-/**
- * Usage Examples:
- *
- * // Create API instance
- * const api = createHyperLiquidApi();
- *
- * // Get candles
- * const candles = await api.getCandles('BTC', '1h', startTime, endTime);
- *
- * // Get current price
- * const price = await api.getCurrentPrice('BTC');
- *
- * // Get order book
- * const book = await api.getL2Book('ETH', 5);
- *
- * // Get user state
- * const state = await api.getUserState('0x...');
- *
- * // Get metadata
- * const meta = await api.getMeta();
- */
diff --git a/fincept-terminal-desktop/src/services/hyperliquid/index.ts b/fincept-terminal-desktop/src/services/hyperliquid/index.ts
deleted file mode 100644
index 8e248e064..000000000
--- a/fincept-terminal-desktop/src/services/hyperliquid/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-// File: src/services/hyperliquid/index.ts
-// HyperLiquid services exports
-
-export { HyperLiquidApi, createHyperLiquidApi } from './hyperliquidApi';
-export type * from '../../types/hyperliquid';
diff --git a/fincept-terminal-desktop/src/services/stockBrokers/kraken/index.ts b/fincept-terminal-desktop/src/services/stockBrokers/kraken/index.ts
deleted file mode 100644
index ac4af63d6..000000000
--- a/fincept-terminal-desktop/src/services/stockBrokers/kraken/index.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Kraken Broker Integration
- *
- * Complete Kraken API integration for Fincept Terminal
- * Supports spot, margin, futures trading and all WebSocket channels
- */
-
-export { default as KrakenService } from './krakenService';
-export { default as KrakenWebSocket } from './krakenWebSocket';
-export { default as KrakenAuth } from './krakenAuth';
-export { default as KrakenConfig } from './krakenConfig';
-export * from '../krakenTypes';
-
-// Export factory function for easy initialization
-export function createKrakenService(config?: any) {
- const KrakenServiceClass = require('./krakenService').default;
- return new KrakenServiceClass(config);
-}
-
-// Export WebSocket factory
-export function createKrakenWebSocket(config?: any) {
- const KrakenWebSocketClass = require('./krakenWebSocket').default;
- return new KrakenWebSocketClass(config);
-}
-
-// Broker metadata for registry
-export const KRAKEN_BROKER = {
- id: 'kraken',
- name: 'Kraken',
- version: '1.0.0',
- supported: {
- spot: true,
- margin: true,
- futures: true,
- options: false,
- staking: true,
- lending: true,
- websocket: true,
- },
- features: {
- restApi: true,
- websocket: true,
- streaming: true,
- historicalData: true,
- realTimeData: true,
- advancedOrders: true,
- batchOperations: true,
- multiAccount: true,
- },
- apis: {
- rest: {
- spot: 'https://api.kraken.com',
- futures: 'https://futures.kraken.com',
- auth: 'https://api.kraken.com',
- },
- websocket: {
- public: 'wss://ws.kraken.com/v2',
- private: 'wss://ws-auth.kraken.com/v2',
- futures: 'wss://futures.kraken.com/ws/v1',
- testnet: 'wss://demo-futures.kraken.com/ws/v1',
- },
- },
- rateLimits: {
- rest: {
- public: 1000, // 1 request per second
- private: 3000, // 1 request per 3 seconds
- },
- websocket: {
- connections: 10, // Max concurrent connections
- subscriptions: 100, // Max subscriptions per connection
- },
- },
-};
-
-export default KRAKEN_BROKER;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/services/stockBrokers/kraken/krakenAuth.ts b/fincept-terminal-desktop/src/services/stockBrokers/kraken/krakenAuth.ts
deleted file mode 100644
index 6808c255e..000000000
--- a/fincept-terminal-desktop/src/services/stockBrokers/kraken/krakenAuth.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-/**
- * Kraken Authentication Management
- */
-
-import crypto from 'crypto';
-import { KRAKEN_CONFIG } from './krakenConfig';
-
-export interface KrakenCredentials {
- apiKey: string;
- secret: string;
- passphrase?: string; // Not used by Kraken but kept for compatibility
- sandbox?: boolean;
-}
-
-export interface AuthTokens {
- apiToken?: string;
- wsToken?: string;
- expiresAt?: number;
-}
-
-export class KrakenAuth {
- private credentials: KrakenCredentials | null = null;
- private tokens: AuthTokens = {};
-
- constructor(credentials?: KrakenCredentials) {
- if (credentials) {
- this.setCredentials(credentials);
- }
- }
-
- /**
- * Set API credentials
- */
- setCredentials(credentials: KrakenCredentials): void {
- this.validateCredentials(credentials);
- this.credentials = { ...credentials };
- this.tokens = {}; // Clear existing tokens
- }
-
- /**
- * Get current credentials
- */
- getCredentials(): KrakenCredentials | null {
- return this.credentials ? { ...this.credentials } : null;
- }
-
- /**
- * Clear all credentials and tokens
- */
- clearCredentials(): void {
- this.credentials = null;
- this.tokens = {};
- }
-
- /**
- * Check if authenticated
- */
- isAuthenticated(): boolean {
- return this.credentials !== null;
- }
-
- /**
- * Validate credentials format
- */
- private validateCredentials(credentials: KrakenCredentials): void {
- if (!credentials.apiKey || typeof credentials.apiKey !== 'string') {
- throw new Error('Invalid API key format');
- }
-
- if (!credentials.secret || typeof credentials.secret !== 'string') {
- throw new Error('Invalid secret format');
- }
-
- if (credentials.apiKey.length < 20) {
- throw new Error('API key too short');
- }
-
- if (credentials.secret.length < 32) {
- throw new Error('Secret too short');
- }
- }
-
- /**
- * Generate API signature for REST requests
- */
- generateSignature(
- endpoint: string,
- params: Record<string, any>,
- nonce: string | number
- ): string {
- if (!this.credentials) {
- throw new Error('No credentials set');
- }
-
- // Create the message to sign
- const message = nonce + JSON.stringify(params);
-
- // Decode the secret from base64
- const secretBuffer = Buffer.from(this.credentials.secret, 'base64');
-
- // Create HMAC-SHA256 signature
- const hmac = crypto.createHmac('sha512', secretBuffer);
- hmac.update(message);
- const signature = hmac.digest('base64');
-
- return signature;
- }
-
- /**
- * Generate WebSocket authentication token
- */
- async generateWebSocketToken(): Promise<string> {
- if (!this.credentials) {
- throw new Error('No credentials set');
- }
-
- // Check if existing token is still valid
- if (this.tokens.wsToken && this.tokens.expiresAt && Date.now() < this.tokens.expiresAt) {
- return this.tokens.wsToken;
- }
-
- // Generate new token using API-Sign method
- const nonce = Date.now().toString();
- const endpoint = '/ws/auth';
-
- const params = {
- event: 'subscribe',
- subscription: {
- name: 'authenticate',
- token: this.credentials.apiKey
- }
- };
-
- const signature = this.generateSignature(endpoint, params, nonce);
-
- // For Kraken WebSocket, we use the API key directly in the subscription message
- // The signature is used for REST API authentication
- this.tokens.wsToken = this.credentials.apiKey;
- this.tokens.expiresAt = Date.now() + (24 * 60 * 60 * 1000); // 24 hours
-
- return this.tokens.wsToken;
- }
-
- /**
- * Get authentication headers for REST requests
- */
- getAuthHeaders(
- endpoint: string,
- params: Record<string, any> = {}
- ): Record<string, string> {
- if (!this.credentials) {
- throw new Error('No credentials set');
- }
-
- const nonce = Date.now().toString();
- const signature = this.generateSignature(endpoint, params, nonce);
-
- return {
- 'API-Key': this.credentials.apiKey,
- 'API-Sign': signature,
- 'API-Nonce': nonce,
- 'Content-Type': 'application/x-www-form-urlencoded',
- };
- }
-
- /**
- * Add authentication to request parameters
- */
- addAuthToParams(params: Record<string, any> = {}): Record<string, any> {
- if (!this.credentials) {
- return params;
- }
-
- return {
- ...params,
- nonce: Date.now().toString(),
- };
- }
-
- /**
- * Validate API key permissions
- */
- async validatePermissions(): Promise<{
- canTrade: boolean;
- canDeposit: boolean;
- canWithdraw: boolean;
- queryTime: number;
- }> {
- if (!this.credentials) {
- throw new Error('No credentials set');
- }
-
- try {
- // This would typically make a test API call to validate permissions
- // For now, return a default response
- return {
- canTrade: true,
- canDeposit: true,
- canWithdraw: true,
- queryTime: Date.now(),
- };
- } catch (error) {
- throw new Error(`Failed to validate permissions: ${error}`);
- }
- }
-
- /**
- * Test connection with current credentials
- */
- async testConnection(): Promise<boolean> {
- if (!this.credentials) {
- throw new Error('No credentials set');
- }
-
- try {
- // This would typically make a test API call
- // For now, just validate the credentials format
- this.validateCredentials(this.credentials);
- return true;
- } catch (error) {
- return false;
- }
- }
-
- /**
- * Encrypt credentials for storage
- */
- encryptCredentials(credentials: KrakenCredentials): string {
- const secret = process.env.ENCRYPTION_SECRET || 'default-secret';
- const cipher = crypto.createCipher('aes-256-cbc', secret);
-
- let encrypted = cipher.update(JSON.stringify(credentials), 'utf8', 'hex');
- encrypted += cipher.final('hex');
-
- return encrypted;
- }
-
- /**
- * Decrypt credentials from storage
- */
- decryptCredentials(encrypted: string): KrakenCredentials {
- const secret = process.env.ENCRYPTION_SECRET || 'default-secret';
- const decipher = crypto.createDecipher('aes-256-cbc', secret);
-
- let decrypted = decipher.update(encrypted, 'hex', 'utf8');
- decrypted += decipher.final('utf8');
-
- return JSON.parse(decrypted);
- }
-
- /**
- * Get rate limit information
- */
- getRateLimitInfo(): {
- publicApi: { callsPerSecond: number; lastCall: number };
- privateApi: { callsPerSecond: number; lastCall: number };
- tradingApi: { callsPerSecond: number; lastCall: number };
- } {
- const now = Date.now();
- return {
- publicApi: {
- callsPerSecond: 1000 / KRAKEN_CONFIG.REST.PUBLIC,
- lastCall: now,
- },
- privateApi: {
- callsPerSecond: 1000 / KRAKEN_CONFIG.REST.PRIVATE,
- lastCall: now,
- },
- tradingApi: {
- callsPerSecond: 1000 / KRAKEN_CONFIG.REST.TRADING,
- lastCall: now,
- },
- };
- }
-
- /**
- * Check if rate limit allows making a request
- */
- canMakeRequest(apiType: 'public' | 'private' | 'trading'): boolean {
- const rateLimitInfo = this.getRateLimitInfo();
- const timeSinceLastCall = Date.now() - rateLimitInfo[`${apiType}Api`].lastCall;
- const minInterval = rateLimitInfo[`${apiType}Api`].callsPerSecond;
-
- return timeSinceLastCall >= minInterval;
- }
-
- /**
- * Wait for rate limit if necessary
- */
- async waitForRateLimit(apiType: 'public' | 'private' | 'trading'): Promise<void> {
- if (this.canMakeRequest(apiType)) {
- return;
- }
-
- const rateLimitInfo = this.getRateLimitInfo();
- const timeSinceLastCall = Date.now() - rateLimitInfo[`${apiType}Api`].lastCall;
- const minInterval = rateLimitInfo[`${apiType}Api`].callsPerSecond;
- const waitTime = minInterval - timeSinceLastCall;
-
- if (waitTime > 0) {
- await new Promise(resolve => setTimeout(resolve, waitTime));
- }
- }
-}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/services/stockBrokers/kraken/krakenConfig.ts b/fincept-terminal-desktop/src/services/stockBrokers/kraken/krakenConfig.ts
deleted file mode 100644
index cb9b97f23..000000000
--- a/fincept-terminal-desktop/src/services/stockBrokers/kraken/krakenConfig.ts
+++ /dev/null
@@ -1,232 +0,0 @@
-/**
- * Kraken Configuration and Constants
- */
-
-// API Endpoints
-export const KRAKEN_ENDPOINTS = {
- REST: {
- PRODUCTION: 'https://api.kraken.com',
- TESTNET: 'https://api.kraken.com', // Kraken doesn't have a public testnet
- FUTURES: 'https://futures.kraken.com',
- FUTURES_TESTNET: 'https://demo-futures.kraken.com',
- },
- WEBSOCKET: {
- PUBLIC: 'wss://ws.kraken.com/v2',
- PRIVATE: 'wss://ws-auth.kraken.com/v2',
- FUTURES: 'wss://futures.kraken.com/ws/v1',
- FUTURES_TESTNET: 'wss://demo-futures.kraken.com/ws/v1',
- BETA_PUBLIC: 'wss://beta-ws.kraken.com/v2',
- BETA_PRIVATE: 'wss://beta-ws-auth.kraken.com/v2',
- },
-};
-
-// API Versions
-export const KRAKEN_API_VERSIONS = {
- REST: '0',
- WEBSOCKET: '2',
- FUTURES: 'v1',
-};
-
-// Rate Limits (milliseconds)
-export const KRAKEN_RATE_LIMITS = {
- REST: {
- PUBLIC: 1000, // 1 request per second
- PRIVATE: 3000, // 1 request per 3 seconds
- TRADING: 1000, // 1 request per second for trading
- },
- WEBSOCKET: {
- CONNECTION_LIMIT: 10,
- SUBSCRIPTION_LIMIT: 100,
- MESSAGE_RATE: 100, // Max messages per second
- },
-};
-
-// Order Types
-export const KRAKEN_ORDER_TYPES = {
- MARKET: 'market',
- LIMIT: 'limit',
- STOP_LOSS: 'stop-loss',
- TAKE_PROFIT: 'take-profit',
- STOP_LOSS_LIMIT: 'stop-loss-limit',
- TAKE_PROFIT_LIMIT: 'take-profit-limit',
- SETTLE_POSITION: 'settle-position',
-} as const;
-
-// Order Sides
-export const KRAKEN_ORDER_SIDES = {
- BUY: 'buy',
- SELL: 'sell',
-} as const;
-
-// Time in Force
-export const KRAKEN_TIME_IN_FORCE = {
- GTC: 'GTC', // Good Till Cancelled
- IOC: 'IOC', // Immediate Or Cancel
- FOK: 'FOK', // Fill Or Kill
-} as const;
-
-// Asset Classes
-export const KRAKEN_ASSET_CLASSES = {
- CURRENCY: 'currency',
- SPOT: 'spot',
- MARGIN: 'margin',
- FUTURES: 'futures',
- OPTION: 'option',
-} as const;
-
-// WebSocket Channels
-export const KRAKEN_WEBSOCKET_CHANNELS = {
- // Public Channels
- TICKER: 'ticker',
- TRADES: 'trade',
- BOOK: 'book',
- SPREAD: 'spread',
- OHLC: 'ohlc',
- INSTRUMENT: 'instrument',
-
- // Private Channels
- OPEN_ORDERS: 'openOrders',
- OWN_TRADES: 'ownTrades',
- BALANCE: 'balance',
- POSITIONS: 'positions',
- MARGIN: 'margin',
- LEDGERS: 'ledgers',
-} as const;
-
-// WebSocket Statuses
-export const KRAKEN_WEBSOCKET_STATUS = {
- CONNECTED: 'connected',
- CONNECTING: 'connecting',
- DISCONNECTED: 'disconnected',
- ERROR: 'error',
- RECONNECTING: 'reconnecting',
-} as const;
-
-// Error Codes
-export const KRAKEN_ERROR_CODES = {
- // General Errors
- INVALID_API_KEY: 'EAPI:Invalid key',
- INVALID_SIGNATURE: 'EAPI:Invalid signature',
- INVALID_NONCE: 'EAPI:Invalid nonce',
-
- // Trading Errors
- INSUFFICIENT_FUNDS: 'EGeneral:Insufficient funds',
- INVALID_ORDER: 'EGeneral:Invalid arguments',
- ORDER_LIMIT_EXCEEDED: 'EGeneral:Too many requests',
- MARKET_CLOSED: 'EGeneral:Market in cancel only mode',
-
- // Account Errors
- ACCOUNT_SUSPENDED: 'EGeneral:Account suspended',
- PERMISSION_DENIED: 'EGeneral:Permission denied',
-
- // Network Errors
- RATE_LIMIT: 'EOrder:Rate limit exceeded',
- SERVICE_UNAVAILABLE: 'EGeneral:Service unavailable',
-} as const;
-
-// Default Configuration
-export const KRAKEN_DEFAULT_CONFIG = {
- // Connection settings
- timeout: 30000, // 30 seconds
- retryAttempts: 3,
- retryDelay: 1000, // 1 second
-
- // WebSocket settings
- websocketTimeout: 60000, // 1 minute
- reconnectInterval: 5000, // 5 seconds
- maxReconnectAttempts: 10,
-
- // Rate limiting
- enableRateLimiting: true,
- rateLimitBuffer: 100, // 100ms buffer between requests
-
- // Data settings
- defaultOrderBookDepth: 100,
- defaultOHLCVLimit: 720, // 720 candles (default)
-
- // Trading settings
- defaultTimeInForce: 'GTC',
- validateOrders: true,
-
- // WebSocket settings
- enableWebSocketCompression: true,
- websocketPingInterval: 30000, // 30 seconds
- maxSubscriptionsPerConnection: 50,
-};
-
-// Environment Detection
-export const isDevelopment = process.env.NODE_ENV === 'development';
-export const isProduction = process.env.NODE_ENV === 'production';
-
-// Feature Flags
-export const KRAKEN_FEATURES = {
- // API Features
- SPOT_TRADING: true,
- MARGIN_TRADING: true,
- FUTURES_TRADING: true,
- STAKING: true,
- LENDING: true,
-
- // WebSocket Features
- REAL_TIME_DATA: true,
- WEBSOCKET_TRADING: true,
-
- // Advanced Features
- BATCH_ORDERS: true,
- CONDITIONAL_ORDERS: true,
- ICEBERG_ORDERS: true,
- TRAILING_STOPS: false, // Not supported by Kraken
-
- // UI Features
- ADVANCED_CHARTING: true,
- PORTFOLIO_TRACKING: true,
- TAX_REPORTING: true,
-} as const;
-
-// Validation Rules
-export const KRAKEN_VALIDATION = {
- // API Key format
- API_KEY_REGEX: /^[A-Za-z0-9]{20,}$/,
- SECRET_MIN_LENGTH: 32,
-
- // Symbol format
- SYMBOL_REGEX: /^[A-Z]{3,4}\/[A-Z]{3,4}$/,
-
- // Order validation
- MIN_ORDER_AMOUNT: 0.0001,
- MAX_ORDER_PRECISION: 8,
-
- // WebSocket validation
- MAX_SYMBOLS_PER_SUBSCRIPTION: 100,
- MAX_MESSAGE_SIZE: 1024 * 1024, // 1MB
-} as const;
-
-// Currency Pairs (Major Pairs)
-export const KRAKEN_MAJOR_PAIRS = [
- 'BTC/USD',
- 'ETH/USD',
- 'BTC/EUR',
- 'ETH/EUR',
- 'BTC/USDT',
- 'ETH/USDT',
- 'LTC/USD',
- 'XRP/USD',
- 'ADA/USD',
- 'DOT/USD',
-];
-
-// Trading Hours
-export const KRAKEN_TRADING_HOURS = {
- SPOT: '24/7',
- MARGIN: '24/7',
- FUTURES: '24/7',
-} as const;
-
-// Fee Tiers
-export const KRAKEN_FEE_TIERS = {
- MAKER: [0.26, 0.24, 0.22, 0.20, 0.18, 0.16, 0.14, 0.12, 0.10, 0.08],
- TAKER: [0.26, 0.24, 0.22, 0.20, 0.18, 0.16, 0.14, 0.12, 0.10, 0.08],
- VOLUME_THRESHOLDS: [
- 0, 50000, 100000, 250000, 500000, 1000000, 2500000, 5000000, 10000000, Infinity
- ],
-} as const;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/services/trading/index.ts b/fincept-terminal-desktop/src/services/trading/index.ts
index 8e3c0defe..107748585 100644
--- a/fincept-terminal-desktop/src/services/trading/index.ts
+++ b/fincept-terminal-desktop/src/services/trading/index.ts
@@ -1,5 +1,20 @@
// File: src/services/trading/index.ts
// Trading services exports
-export { PaperTradingService, createPaperTradingService } from './paperTradingService';
+// DEPRECATED: Old paper trading service replaced by new adapter-based system
+// The old service has been moved to paperTradingService.ts.deprecated
+//
+// Use the new institutional-grade paper trading adapter instead:
+// import { createPaperTradingAdapter } from '../../brokers/crypto/paper-trading';
+//
+// Example:
+// const adapter = createPaperTradingAdapter({
+// portfolioId: 'my-portfolio',
+// portfolioName: 'Test Strategy',
+// realExchange: 'kraken',
+// initialBalance: 100000,
+// fees: { maker: 0.0002, taker: 0.0005 },
+// slippage: { market: 0.001, limit: 0 },
+// });
+
export type * from '../../types/trading';
diff --git a/fincept-terminal-desktop/src/services/trading/paperTradingService.ts b/fincept-terminal-desktop/src/services/trading/paperTradingService.ts
deleted file mode 100644
index 80c3d5f63..000000000
--- a/fincept-terminal-desktop/src/services/trading/paperTradingService.ts
+++ /dev/null
@@ -1,712 +0,0 @@
-// File: src/services/trading/paperTradingService.ts
-// Paper trading engine - simulates trading with virtual money
-
-import Database from '@tauri-apps/plugin-sql';
-import type {
- VirtualPortfolio,
- Position,
- Order,
- Trade,
- OrderRequest,
- OrderResult,
- PaperTradingConfig,
- DbPortfolio,
- DbPosition,
- DbOrder,
- DbTrade
-} from '../../types/trading';
-import { getWebSocketManager } from '../websocket';
-import type { NormalizedMessage, Subscription } from '../websocket/types';
-
-/**
- * Paper Trading Service
- * Manages virtual portfolios, positions, orders, and trades
- */
-export class PaperTradingService {
- private db: Database | null = null;
- private config: PaperTradingConfig;
- private marketPrices = new Map<string, number>(); // symbol -> current price
- private priceSubscriptions = new Map<string, Subscription>(); // symbol -> subscription
- private orderMonitorInterval: NodeJS.Timeout | null = null;
-
- constructor(config?: Partial<PaperTradingConfig>) {
- this.config = {
- portfolioId: config?.portfolioId || '',
- feeRate: config?.feeRate || 0.0002, // 0.02% fee
- slippage: config?.slippage || 0.0001 // 0.01% slippage
- };
- }
-
- /**
- * Initialize database connection
- */
- async initialize(): Promise<void> {
- if (!this.db) {
- this.db = await Database.load('sqlite:fincept_terminal.db');
- }
- }
-
- /**
- * Create a new paper trading portfolio
- */
- async createPortfolio(
- name: string,
- provider: string,
- initialBalance: number = 100000
- ): Promise<string> {
- await this.initialize();
-
- const id = crypto.randomUUID();
-
- await this.db!.execute(
- `INSERT INTO paper_trading_portfolios (id, name, provider, initial_balance, current_balance)
- VALUES ($1, $2, $3, $4, $5)`,
- [id, name, provider, initialBalance, initialBalance]
- );
-
- this.config.portfolioId = id;
-
- return id;
- }
-
- /**
- * Get portfolio by ID
- */
- async getPortfolio(portfolioId: string): Promise<VirtualPortfolio | null> {
- await this.initialize();
-
- const results = await this.db!.select<DbPortfolio[]>(
- 'SELECT * FROM paper_trading_portfolios WHERE id = $1',
- [portfolioId]
- );
-
- if (results.length === 0) return null;
-
- const dbPortfolio = results[0];
- const positions = await this.getPositions(portfolioId);
-
- // Calculate total P&L
- const totalPnL = positions.reduce((sum, pos) => {
- return sum + (pos.unrealizedPnL || 0) + pos.realizedPnL;
- }, 0);
-
- return {
- id: dbPortfolio.id,
- name: dbPortfolio.name,
- provider: dbPortfolio.provider,
- initialBalance: dbPortfolio.initial_balance,
- balance: dbPortfolio.current_balance,
- totalPnL,
- positions,
- createdAt: dbPortfolio.created_at,
- updatedAt: dbPortfolio.updated_at
- };
- }
-
- /**
- * Get all open positions for a portfolio
- */
- async getPositions(portfolioId: string, status: 'open' | 'closed' | 'all' = 'open'): Promise<Position[]> {
- await this.initialize();
-
- let query = 'SELECT * FROM paper_trading_positions WHERE portfolio_id = $1';
- const params: any[] = [portfolioId];
-
- if (status !== 'all') {
- query += ' AND status = $2';
- params.push(status);
- }
-
- query += ' ORDER BY opened_at DESC';
-
- const results = await this.db!.select<DbPosition[]>(query, params);
-
- return results.map(dbPos => this.mapDbPosition(dbPos));
- }
-
- /**
- * Get all orders for a portfolio
- */
- async getOrders(portfolioId: string): Promise<Order[]> {
- await this.initialize();
-
- const results = await this.db!.select<DbOrder[]>(
- 'SELECT * FROM paper_trading_orders WHERE portfolio_id = $1 ORDER BY created_at DESC',
- [portfolioId]
- );
-
- return results.map(dbOrder => this.mapDbOrder(dbOrder));
- }
-
- /**
- * Place an order
- */
- async placeOrder(portfolioId: string, order: OrderRequest): Promise<OrderResult> {
- await this.initialize();
-
- const portfolio = await this.getPortfolio(portfolioId);
-
- if (!portfolio) {
- return { success: false, error: 'Portfolio not found' };
- }
-
- // Validate balance for buy orders
- if (order.side === 'buy') {
- const estimatedPrice = order.price || await this.getCurrentPrice(order.symbol);
- const requiredBalance = order.quantity * estimatedPrice;
-
- if (portfolio.balance < requiredBalance) {
- return { success: false, error: 'Insufficient balance' };
- }
- }
-
- // Validate order parameters
- if ((order.type === 'limit' || order.type === 'stop_limit') && !order.price) {
- return { success: false, error: 'Limit orders require a price' };
- }
-
- if ((order.type === 'stop_market' || order.type === 'stop_limit') && !order.stopPrice) {
- return { success: false, error: 'Stop orders require a stop price' };
- }
-
- // Create order record
- const orderId = crypto.randomUUID();
-
- await this.db!.execute(
- `INSERT INTO paper_trading_orders
- (id, portfolio_id, symbol, side, type, quantity, price, stop_price, status)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending')`,
- [
- orderId,
- portfolioId,
- order.symbol,
- order.side,
- order.type,
- order.quantity,
- order.price || null,
- order.stopPrice || null
- ]
- );
-
- // Execute market orders immediately
- if (order.type === 'market') {
- await this.executeMarketOrder(portfolioId, orderId, order);
- }
-
- // Subscribe to price updates for this symbol
- await this.subscribeToPriceUpdates(order.symbol, portfolio.provider);
-
- return { success: true, orderId };
- }
-
- /**
- * Execute a market order
- */
- private async executeMarketOrder(
- portfolioId: string,
- orderId: string,
- order: OrderRequest
- ): Promise<void> {
- const currentPrice = await this.getCurrentPrice(order.symbol);
-
- // Apply slippage
- const executionPrice = order.side === 'buy'
- ? currentPrice * (1 + this.config.slippage)
- : currentPrice * (1 - this.config.slippage);
-
- // Calculate fee
- const fee = executionPrice * order.quantity * this.config.feeRate;
-
- // Total cost/proceeds
- const totalCost = order.side === 'buy'
- ? (executionPrice * order.quantity) + fee
- : (executionPrice * order.quantity) - fee;
-
- // Update order status
- await this.db!.execute(
- `UPDATE paper_trading_orders
- SET status = 'filled', filled_quantity = $1, avg_fill_price = $2, filled_at = CURRENT_TIMESTAMP
- WHERE id = $3`,
- [order.quantity, executionPrice, orderId]
- );
-
- // Create trade record
- await this.createTrade(portfolioId, orderId, order, executionPrice, fee);
-
- // Update position
- await this.updatePosition(portfolioId, order, executionPrice);
-
- // Update balance
- const balanceChange = order.side === 'buy' ? -totalCost : totalCost;
- await this.updateBalance(portfolioId, balanceChange);
- }
-
- /**
- * Execute a limit order (called by order monitor)
- */
- private async executeLimitOrder(
- portfolioId: string,
- orderId: string,
- order: DbOrder,
- currentPrice: number
- ): Promise<void> {
- const fee = currentPrice * order.quantity * this.config.feeRate;
-
- // Update order status
- await this.db!.execute(
- `UPDATE paper_trading_orders
- SET status = 'filled', filled_quantity = $1, avg_fill_price = $2, filled_at = CURRENT_TIMESTAMP
- WHERE id = $3`,
- [order.quantity, currentPrice, order.id]
- );
-
- // Create trade record
- const tradeRequest: OrderRequest = {
- symbol: order.symbol,
- side: order.side,
- type: order.type,
- quantity: order.quantity
- };
-
- await this.createTrade(portfolioId, orderId, tradeRequest, currentPrice, fee);
-
- // Update position
- await this.updatePosition(portfolioId, tradeRequest, currentPrice);
-
- // Update balance
- const totalCost = order.side === 'buy'
- ? (currentPrice * order.quantity) + fee
- : (currentPrice * order.quantity) - fee;
-
- const balanceChange = order.side === 'buy' ? -totalCost : totalCost;
- await this.updateBalance(portfolioId, balanceChange);
- }
-
- /**
- * Create trade record
- */
- private async createTrade(
- portfolioId: string,
- orderId: string,
- order: OrderRequest,
- price: number,
- fee: number
- ): Promise<void> {
- const tradeId = crypto.randomUUID();
-
- await this.db!.execute(
- `INSERT INTO paper_trading_trades
- (id, portfolio_id, order_id, symbol, side, price, quantity, fee)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
- [tradeId, portfolioId, orderId, order.symbol, order.side, price, order.quantity, fee]
- );
- }
-
- /**
- * Update or create position
- */
- private async updatePosition(
- portfolioId: string,
- order: OrderRequest,
- price: number
- ): Promise<void> {
- // Check if position exists
- const existing = await this.db!.select<DbPosition[]>(
- `SELECT * FROM paper_trading_positions
- WHERE portfolio_id = $1 AND symbol = $2 AND status = 'open'`,
- [portfolioId, order.symbol]
- );
-
- if (existing.length > 0) {
- const position = existing[0];
-
- // Determine if we're adding to or closing position
- const isSameSide = (order.side === 'buy' && position.side === 'long') ||
- (order.side === 'sell' && position.side === 'short');
-
- if (isSameSide) {
- // Add to position
- const newQuantity = position.quantity + order.quantity;
- const newAvgPrice = ((position.entry_price * position.quantity) + (price * order.quantity)) / newQuantity;
-
- await this.db!.execute(
- `UPDATE paper_trading_positions
- SET quantity = $1, entry_price = $2, updated_at = CURRENT_TIMESTAMP
- WHERE id = $3`,
- [newQuantity, newAvgPrice, position.id]
- );
- } else {
- // Opposite side - reduce or close position
- if (order.quantity >= position.quantity) {
- // Close entire position
- const pnl = (price - position.entry_price) * position.quantity *
- (position.side === 'long' ? 1 : -1);
-
- await this.db!.execute(
- `UPDATE paper_trading_positions
- SET status = 'closed', realized_pnl = $1, closed_at = CURRENT_TIMESTAMP
- WHERE id = $2`,
- [pnl, position.id]
- );
-
- // If order quantity exceeds position, create new opposite position
- if (order.quantity > position.quantity) {
- await this.createPosition(
- portfolioId,
- order.symbol,
- order.side === 'buy' ? 'long' : 'short',
- price,
- order.quantity - position.quantity
- );
- }
- } else {
- // Reduce position
- const newQuantity = position.quantity - order.quantity;
- const partialPnl = (price - position.entry_price) * order.quantity *
- (position.side === 'long' ? 1 : -1);
-
- await this.db!.execute(
- `UPDATE paper_trading_positions
- SET quantity = $1, realized_pnl = realized_pnl + $2, updated_at = CURRENT_TIMESTAMP
- WHERE id = $3`,
- [newQuantity, partialPnl, position.id]
- );
- }
- }
- } else {
- // Create new position
- await this.createPosition(
- portfolioId,
- order.symbol,
- order.side === 'buy' ? 'long' : 'short',
- price,
- order.quantity
- );
- }
- }
-
- /**
- * Create new position
- */
- private async createPosition(
- portfolioId: string,
- symbol: string,
- side: 'long' | 'short',
- entryPrice: number,
- quantity: number
- ): Promise<void> {
- const positionId = crypto.randomUUID();
-
- await this.db!.execute(
- `INSERT INTO paper_trading_positions
- (id, portfolio_id, symbol, side, entry_price, quantity, status)
- VALUES ($1, $2, $3, $4, $5, $6, 'open')`,
- [positionId, portfolioId, symbol, side, entryPrice, quantity]
- );
- }
-
- /**
- * Update portfolio balance
- */
- private async updateBalance(portfolioId: string, amount: number): Promise<void> {
- await this.db!.execute(
- `UPDATE paper_trading_portfolios
- SET current_balance = current_balance + $1, updated_at = CURRENT_TIMESTAMP
- WHERE id = $2`,
- [amount, portfolioId]
- );
- }
-
- /**
- * Subscribe to market price updates for a symbol
- */
- private async subscribeToPriceUpdates(symbol: string, provider: string): Promise<void> {
- // Avoid duplicate subscriptions
- if (this.priceSubscriptions.has(symbol)) {
- return;
- }
-
- const manager = getWebSocketManager();
- const topic = `${provider}.ticker.${symbol}`;
-
- const subscription = await manager.subscribe(topic, (message: NormalizedMessage) => {
- this.handlePriceUpdate(message);
- });
-
- this.priceSubscriptions.set(symbol, subscription);
-
- // Start order monitor if not already running
- if (!this.orderMonitorInterval) {
- this.startOrderMonitor();
- }
- }
-
- /**
- * Handle incoming price updates
- */
- private handlePriceUpdate(message: NormalizedMessage): void {
- const symbol = message.symbol;
- if (!symbol) return;
-
- let price: number | undefined;
-
- // Extract price from different message types
- if (message.type === 'ticker') {
- price = message.data.last || message.data.close || message.data.mid;
- } else if (message.type === 'trade') {
- price = message.data.price || message.data.last;
- }
-
- if (price) {
- this.marketPrices.set(symbol, price);
-
- // Update unrealized P&L for open positions
- this.updateUnrealizedPnL(symbol, price);
- }
- }
-
- /**
- * Get current market price for a symbol
- */
- private async getCurrentPrice(symbol: string): Promise<number> {
- const price = this.marketPrices.get(symbol);
-
- if (!price) {
- throw new Error(`No market price available for ${symbol}`);
- }
-
- return price;
- }
-
- /**
- * Update unrealized P&L for all positions of a symbol
- */
- private async updateUnrealizedPnL(symbol: string, currentPrice: number): Promise<void> {
- await this.initialize();
-
- const positions = await this.db!.select<DbPosition[]>(
- `SELECT * FROM paper_trading_positions WHERE symbol = $1 AND status = 'open'`,
- [symbol]
- );
-
- for (const position of positions) {
- const pnl = (currentPrice - position.entry_price) * position.quantity *
- (position.side === 'long' ? 1 : -1);
-
- await this.db!.execute(
- `UPDATE paper_trading_positions
- SET current_price = $1, unrealized_pnl = $2, updated_at = CURRENT_TIMESTAMP
- WHERE id = $3`,
- [currentPrice, pnl, position.id]
- );
- }
- }
-
- /**
- * Monitor pending orders and execute when conditions are met
- */
- private startOrderMonitor(): void {
- // Check every 500ms
- this.orderMonitorInterval = setInterval(async () => {
- await this.checkPendingOrders();
- }, 500);
- }
-
- /**
- * Check all pending orders and execute if conditions are met
- */
- private async checkPendingOrders(): Promise<void> {
- await this.initialize();
-
- const pendingOrders = await this.db!.select<DbOrder[]>(
- `SELECT * FROM paper_trading_orders WHERE status IN ('pending', 'triggered')`
- );
-
- for (const order of pendingOrders) {
- const currentPrice = this.marketPrices.get(order.symbol);
- if (!currentPrice) continue;
-
- if (order.type === 'limit' && order.price) {
- // Buy limit: execute if market <= limit
- // Sell limit: execute if market >= limit
- const shouldExecute = order.side === 'buy'
- ? currentPrice <= order.price
- : currentPrice >= order.price;
-
- if (shouldExecute) {
- await this.executeLimitOrder(order.portfolio_id, order.id, order, currentPrice);
- }
- } else if (order.type === 'stop_market' && order.stop_price) {
- // Buy stop: trigger if market >= stop
- // Sell stop: trigger if market <= stop
- const triggered = order.side === 'buy'
- ? currentPrice >= order.stop_price
- : currentPrice <= order.stop_price;
-
- if (triggered) {
- // Execute as market order
- const orderRequest: OrderRequest = {
- symbol: order.symbol,
- side: order.side,
- type: 'market',
- quantity: order.quantity
- };
-
- await this.executeMarketOrder(order.portfolio_id, order.id, orderRequest);
- }
- } else if (order.type === 'stop_limit' && order.stop_price && order.price) {
- // Two-step: first trigger, then wait for limit
- if (order.status === 'pending') {
- // Check if stop triggered
- const triggered = order.side === 'buy'
- ? currentPrice >= order.stop_price
- : currentPrice <= order.stop_price;
-
- if (triggered) {
- await this.db!.execute(
- `UPDATE paper_trading_orders SET status = 'triggered' WHERE id = $1`,
- [order.id]
- );
- }
- } else if (order.status === 'triggered') {
- // Now check limit condition
- const shouldExecute = order.side === 'buy'
- ? currentPrice <= order.price
- : currentPrice >= order.price;
-
- if (shouldExecute) {
- await this.executeLimitOrder(order.portfolio_id, order.id, order, currentPrice);
- }
- }
- }
- }
- }
-
- /**
- * Cancel an order
- */
- async cancelOrder(orderId: string): Promise<boolean> {
- await this.initialize();
-
- await this.db!.execute(
- `UPDATE paper_trading_orders SET status = 'cancelled' WHERE id = $1 AND status IN ('pending', 'triggered')`,
- [orderId]
- );
-
- return true;
- }
-
- /**
- * Close a position
- */
- async closePosition(positionId: string): Promise<boolean> {
- await this.initialize();
-
- const results = await this.db!.select<DbPosition[]>(
- `SELECT * FROM paper_trading_positions WHERE id = $1 AND status = 'open'`,
- [positionId]
- );
-
- if (results.length === 0) return false;
-
- const position = results[0];
- const currentPrice = this.marketPrices.get(position.symbol);
-
- if (!currentPrice) {
- throw new Error(`No current price for ${position.symbol}`);
- }
-
- // Create closing order
- const orderRequest: OrderRequest = {
- symbol: position.symbol,
- side: position.side === 'long' ? 'sell' : 'buy',
- type: 'market',
- quantity: position.quantity
- };
-
- await this.placeOrder(position.portfolio_id, orderRequest);
-
- return true;
- }
-
- /**
- * Reset portfolio to initial state
- */
- async resetPortfolio(portfolioId: string): Promise<boolean> {
- await this.initialize();
-
- const portfolio = await this.getPortfolio(portfolioId);
- if (!portfolio) return false;
-
- // Delete all positions, orders, and trades
- await this.db!.execute(`DELETE FROM paper_trading_trades WHERE portfolio_id = $1`, [portfolioId]);
- await this.db!.execute(`DELETE FROM paper_trading_orders WHERE portfolio_id = $1`, [portfolioId]);
- await this.db!.execute(`DELETE FROM paper_trading_positions WHERE portfolio_id = $1`, [portfolioId]);
-
- // Reset balance
- await this.db!.execute(
- `UPDATE paper_trading_portfolios SET current_balance = initial_balance, updated_at = CURRENT_TIMESTAMP WHERE id = $1`,
- [portfolioId]
- );
-
- return true;
- }
-
- /**
- * Cleanup - unsubscribe from price updates and stop monitoring
- */
- cleanup(): void {
- // Unsubscribe from all price updates
- this.priceSubscriptions.forEach(sub => sub.unsubscribe());
- this.priceSubscriptions.clear();
-
- // Stop order monitor
- if (this.orderMonitorInterval) {
- clearInterval(this.orderMonitorInterval);
- this.orderMonitorInterval = null;
- }
- }
-
- // Helper mappers
- private mapDbPosition(dbPos: DbPosition): Position {
- return {
- id: dbPos.id,
- portfolioId: dbPos.portfolio_id,
- symbol: dbPos.symbol,
- side: dbPos.side,
- entryPrice: dbPos.entry_price,
- quantity: dbPos.quantity,
- currentPrice: dbPos.current_price || undefined,
- unrealizedPnL: dbPos.unrealized_pnl || undefined,
- realizedPnL: dbPos.realized_pnl,
- openedAt: dbPos.opened_at,
- closedAt: dbPos.closed_at || undefined,
- status: dbPos.status
- };
- }
-
- private mapDbOrder(dbOrder: DbOrder): Order {
- return {
- id: dbOrder.id,
- portfolioId: dbOrder.portfolio_id,
- symbol: dbOrder.symbol,
- side: dbOrder.side,
- type: dbOrder.type,
- quantity: dbOrder.quantity,
- price: dbOrder.price || undefined,
- stopPrice: dbOrder.stop_price || undefined,
- filledQuantity: dbOrder.filled_quantity,
- avgFillPrice: dbOrder.avg_fill_price || undefined,
- status: dbOrder.status,
- createdAt: dbOrder.created_at,
- filledAt: dbOrder.filled_at || undefined
- };
- }
-}
-
-/**
- * Create a new paper trading service instance
- */
-export function createPaperTradingService(config?: Partial<PaperTradingConfig>): PaperTradingService {
- return new PaperTradingService(config);
-}
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 cbec9fb60..000000000
--- a/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.ts
+++ /dev/null
@@ -1,619 +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';
-import type {
- HyperLiquidMessage,
- HyperLiquidSubscriptionRequest,
- HyperLiquidSubscriptionType,
- HyperLiquidAllMidsData,
- HyperLiquidL2BookData,
- HyperLiquidTradesData,
- HyperLiquidCandleData,
- HyperLiquidBBOData,
- HyperLiquidUserFillsData,
- HyperLiquidOpenOrdersData,
- HyperLiquidUserFundingsData,
- HyperLiquidCandleInterval
-} from '../../../types/hyperliquid';
-
-/**
- * HyperLiquidAdapter - WebSocket adapter for HyperLiquid exchange
- *
- * Supported channels:
- * - allMids: Mid-prices for all coins
- * - l2Book: Level 2 order book (nSigFigs: 2-5, depth configurable)
- * - trades: Recent trades
- * - candle: OHLC candlestick data (intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, 1d, 3d, 1w, 1M)
- * - bbo: Best bid/offer updates
- * - userFills: User-specific fill history (requires user address)
- * - openOrders: User open orders (requires user address)
- * - userFundings: User funding payments (requires user address)
- * - clearinghouseState: User position state (requires user address)
- *
- * Topic format: "channel.symbol" e.g., "l2Book.BTC" or "trades.ETH"
- * User-specific: "userFills" (no symbol, requires config.api_key as user address)
- */
-export class HyperLiquidAdapter extends BaseAdapter {
- readonly provider = 'hyperliquid';
-
- private readonly WS_URL = 'wss://api.hyperliquid.xyz/ws';
- private readonly WS_TESTNET_URL = 'wss://api.hyperliquid-testnet.xyz/ws';
-
- // Track pending subscriptions for response matching
- private pendingSubscriptions = new Map<string, { channel: string; symbol?: string }>();
-
- /**
- * Get WebSocket URL based on config
- */
- protected getWebSocketUrl(config: ProviderConfig): string {
- // Check if testnet mode is enabled in config_data
- const useTestnet = config.config_data
- ? JSON.parse(config.config_data).testnet === true
- : false;
-
- return useTestnet ? this.WS_TESTNET_URL : 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 subscription responses
- if (message.channel === 'subscriptionResponse') {
- this.handleSubscriptionResponse(message);
- return;
- }
-
- // Handle channel data messages
- if (message.channel && message.data) {
- this.handleChannelMessage(message);
- }
- } catch (error) {
- console.error('[HyperLiquidAdapter] Failed to parse message:', error);
- }
- }
-
- /**
- * Channel aliasing map: Generic channel names → HyperLiquid-specific channels
- * This allows components to use generic names like "ticker" and "book"
- */
- private readonly CHANNEL_ALIAS_MAP: Record<string, string> = {
- 'ticker': 'bbo', // ticker → bbo (best bid/offer - per symbol ticker data)
- 'book': 'l2Book', // book → l2Book (level 2 order book)
- 'trade': 'trades', // trade → trades (recent trades)
- 'ohlc': 'candle', // ohlc → candle (candlestick data)
- };
-
- /**
- * Reverse alias map for normalization: HyperLiquid channels → Generic names
- */
- private readonly REVERSE_ALIAS_MAP: Record<string, string> = {
- 'bbo': 'ticker',
- 'l2Book': 'book',
- 'trades': 'trade',
- 'candle': 'ohlc',
- };
-
- /**
- * Subscribe to a channel
- * @param topic - Format: "channel.symbol" e.g., "ticker.BTC" or "book.ETH"
- * @param params - Optional parameters (nSigFigs, mantissa, interval, aggregateByTime)
- */
- protected async performSubscribe(topic: string, params?: Record<string, any>): Promise<void> {
- const { channel, symbol } = this.parseTopic(topic);
-
- // Map generic channel name to HyperLiquid-specific channel
- const hlChannel = this.CHANNEL_ALIAS_MAP[channel] || channel;
-
- this.log(`Subscribing to topic: ${topic} → HyperLiquid channel: ${hlChannel}${symbol ? ` (${symbol})` : ''}`);
-
- // Build subscription request
- const subscription: any = {
- type: hlChannel as HyperLiquidSubscriptionType
- };
-
- // Add symbol if provided (coin parameter in HyperLiquid)
- if (symbol) {
- subscription.coin = symbol;
- }
-
- // Add user address for user-specific channels
- if (this.isUserSpecificChannel(channel)) {
- if (!this.config?.api_key) {
- throw new Error(`Channel ${channel} requires user address (set api_key in config)`);
- }
- subscription.user = this.config.api_key;
- }
-
- // Channel-specific parameters (use HyperLiquid channel name)
- if (hlChannel === 'l2Book') {
- subscription.nSigFigs = params?.nSigFigs ?? 5;
- if (params?.mantissa) {
- subscription.mantissa = params.mantissa;
- }
- }
-
- if (hlChannel === 'candle') {
- subscription.interval = params?.interval ?? '1m';
- }
-
- if (hlChannel === 'userFills' && params?.aggregateByTime !== undefined) {
- subscription.aggregateByTime = params.aggregateByTime;
- }
-
- const subscribeMessage: HyperLiquidSubscriptionRequest = {
- method: 'subscribe',
- subscription
- };
-
- // Track pending subscription (store original generic channel for proper routing)
- const subscriptionKey = this.buildSubscriptionKey(subscribeMessage.subscription);
- this.pendingSubscriptions.set(subscriptionKey, { channel, symbol });
-
- await this.send(subscribeMessage);
- this.log(`✅ Subscription sent: ${topic} → ${hlChannel}${symbol ? ` (${symbol})` : ''}`);
- }
-
- /**
- * Unsubscribe from a channel
- */
- protected async performUnsubscribe(topic: string): Promise<void> {
- const { channel, symbol } = this.parseTopic(topic);
-
- // Map generic channel name to HyperLiquid-specific channel
- const hlChannel = this.CHANNEL_ALIAS_MAP[channel] || channel;
-
- this.log(`Unsubscribing from topic: ${topic} → HyperLiquid channel: ${hlChannel}${symbol ? ` (${symbol})` : ''}`);
-
- // Build unsubscribe request (must match original subscription)
- const subscription: any = {
- type: hlChannel as HyperLiquidSubscriptionType
- };
-
- if (symbol) {
- subscription.coin = symbol;
- }
-
- if (this.isUserSpecificChannel(channel)) {
- if (!this.config?.api_key) {
- this.log(`Cannot unsubscribe from ${channel}: no user address`);
- return;
- }
- subscription.user = this.config.api_key;
- }
-
- const unsubscribeMessage: HyperLiquidSubscriptionRequest = {
- method: 'unsubscribe',
- subscription
- };
-
- await this.send(unsubscribeMessage);
- this.log(`Sent unsubscription request for ${topic}`);
- }
-
- /**
- * Perform ping (HyperLiquid uses message activity for heartbeat)
- */
- protected async performPing(): Promise<void> {
- // HyperLiquid doesn't have explicit ping/pong
- // Heartbeat is maintained by message activity
- // We can send a subscription status check or just log
- this.log('Heartbeat check (no explicit ping for HyperLiquid)');
- }
-
- /**
- * Called after successful connection
- */
- protected async onConnected(): Promise<void> {
- this.log('WebSocket connected successfully to HyperLiquid');
- }
-
- /**
- * Handle subscription response
- */
- private handleSubscriptionResponse(message: any): void {
- this.log('Subscription response:', message);
-
- if (message.data) {
- const { method, subscription } = message.data;
-
- if (method === 'subscribe') {
- this.log('Subscription confirmed:', subscription);
- } else if (method === 'unsubscribe') {
- this.log('Unsubscription confirmed:', subscription);
- }
- }
- }
-
- /**
- * Handle channel data messages
- */
- private handleChannelMessage(message: HyperLiquidMessage): void {
- const channel = message.channel;
-
- // Normalize 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;
-
- if (!message.data) {
- return normalized;
- }
-
- try {
- switch (channel) {
- case 'allMids':
- normalized.push(...this.normalizeAllMids(message.data as HyperLiquidAllMidsData));
- break;
-
- case 'l2Book':
- normalized.push(this.normalizeL2Book(message.data as HyperLiquidL2BookData));
- break;
-
- case 'trades':
- normalized.push(this.normalizeTrades(message.data as HyperLiquidTradesData));
- break;
-
- case 'candle':
- normalized.push(this.normalizeCandle(message.data as HyperLiquidCandleData));
- break;
-
- case 'bbo':
- normalized.push(this.normalizeBBO(message.data as HyperLiquidBBOData));
- break;
-
- case 'userFills':
- normalized.push(this.normalizeUserFills(message.data as HyperLiquidUserFillsData));
- break;
-
- case 'openOrders':
- normalized.push(this.normalizeOpenOrders(message.data as HyperLiquidOpenOrdersData));
- break;
-
- case 'userFundings':
- normalized.push(this.normalizeUserFundings(message.data as HyperLiquidUserFundingsData));
- break;
-
- default:
- // Generic normalization for other channels
- normalized.push({
- provider: this.provider,
- channel,
- type: 'custom',
- timestamp: Date.now(),
- data: message.data,
- raw: message
- });
- }
- } catch (error) {
- console.error(`[HyperLiquidAdapter] Error normalizing ${channel} message:`, error);
- }
-
- return normalized;
- }
-
- /**
- * Normalize allMids (ticker data for all coins)
- */
- private normalizeAllMids(data: HyperLiquidAllMidsData): NormalizedMessage[] {
- const messages: NormalizedMessage[] = [];
-
- if (data.mids) {
- Object.entries(data.mids).forEach(([coin, midPrice]) => {
- messages.push({
- provider: this.provider,
- channel: 'allMids',
- type: 'ticker',
- symbol: coin,
- timestamp: Date.now(),
- data: {
- mid: parseFloat(midPrice),
- coin
- },
- raw: data
- });
- });
- }
-
- return messages;
- }
-
- /**
- * Normalize L2 order book
- */
- private normalizeL2Book(data: HyperLiquidL2BookData): NormalizedMessage {
- const [bids, asks] = data.levels;
-
- return {
- provider: this.provider,
- channel: this.REVERSE_ALIAS_MAP['l2Book'] || 'l2Book', // Use generic 'book' channel name
- type: 'orderbook',
- symbol: data.coin,
- timestamp: data.time,
- data: {
- coin: data.coin,
- bids: bids.map(level => ({
- price: parseFloat(level.px),
- size: parseFloat(level.sz),
- count: level.n
- })),
- asks: asks.map(level => ({
- price: parseFloat(level.px),
- size: parseFloat(level.sz),
- count: level.n
- })),
- time: data.time
- },
- raw: data
- };
- }
-
- /**
- * Normalize trades
- */
- private normalizeTrades(data: HyperLiquidTradesData): NormalizedMessage {
- return {
- provider: this.provider,
- channel: this.REVERSE_ALIAS_MAP['trades'] || 'trades', // Use generic 'trade' channel name
- type: 'trade',
- symbol: data.coin,
- timestamp: Date.now(),
- data: {
- coin: data.coin,
- trades: data.trades.map(trade => ({
- price: parseFloat(trade.px),
- size: parseFloat(trade.sz),
- side: trade.side === 'A' ? 'sell' : 'buy', // A = Ask (sell), B = Bid (buy)
- time: trade.time,
- tradeId: trade.tid,
- hash: trade.hash
- }))
- },
- raw: data
- };
- }
-
- /**
- * Normalize candle data
- */
- private normalizeCandle(data: HyperLiquidCandleData): NormalizedMessage {
- const candle = data.candle;
-
- if (!candle) {
- throw new Error('No candle data in message');
- }
-
- return {
- provider: this.provider,
- channel: this.REVERSE_ALIAS_MAP['candle'] || 'candle', // Use generic 'ohlc' channel name
- type: 'candle',
- symbol: candle.s,
- timestamp: candle.t,
- data: {
- symbol: candle.s,
- interval: candle.i,
- openTime: candle.t,
- closeTime: candle.T,
- open: parseFloat(candle.o),
- high: parseFloat(candle.h),
- low: parseFloat(candle.l),
- close: parseFloat(candle.c),
- volume: parseFloat(candle.v),
- trades: candle.n
- },
- raw: data
- };
- }
-
- /**
- * Normalize BBO (best bid/offer) - This is HyperLiquid's ticker data
- */
- private normalizeBBO(data: HyperLiquidBBOData): NormalizedMessage {
- const bbo = data.bbo;
-
- if (!bbo) {
- throw new Error('No BBO data in message');
- }
-
- const bid = parseFloat(bbo.bid);
- const ask = parseFloat(bbo.ask);
- const mid = (bid + ask) / 2;
-
- return {
- provider: this.provider,
- channel: this.REVERSE_ALIAS_MAP['bbo'] || 'bbo', // Use generic 'ticker' channel name
- type: 'ticker',
- symbol: bbo.coin,
- timestamp: bbo.time,
- data: {
- coin: bbo.coin,
- symbol: bbo.coin,
- bid: bid,
- ask: ask,
- mid: mid,
- last: mid, // Use mid as last price approximation
- spread: ask - bid,
- time: bbo.time
- },
- raw: data
- };
- }
-
- /**
- * Normalize user fills
- */
- private normalizeUserFills(data: HyperLiquidUserFillsData): NormalizedMessage {
- return {
- provider: this.provider,
- channel: 'userFills',
- type: 'trade',
- timestamp: Date.now(),
- data: {
- user: data.user,
- isSnapshot: data.isSnapshot,
- fills: data.fills.map(fill => ({
- coin: fill.coin,
- price: parseFloat(fill.px),
- size: parseFloat(fill.sz),
- side: fill.side === 'A' ? 'sell' : 'buy',
- time: fill.time,
- closedPnl: parseFloat(fill.closedPnl),
- fee: parseFloat(fill.fee),
- orderId: fill.oid,
- tradeId: fill.tid,
- hash: fill.hash
- }))
- },
- raw: data
- };
- }
-
- /**
- * Normalize open orders
- */
- private normalizeOpenOrders(data: HyperLiquidOpenOrdersData): NormalizedMessage {
- return {
- provider: this.provider,
- channel: 'openOrders',
- type: 'status',
- timestamp: Date.now(),
- data: {
- user: data.user,
- orders: data.orders?.map(order => ({
- coin: order.coin,
- side: order.side === 'A' ? 'sell' : 'buy',
- price: parseFloat(order.limitPx),
- size: parseFloat(order.sz),
- origSize: parseFloat(order.origSz),
- orderId: order.oid,
- clientOrderId: order.cloid,
- timestamp: order.timestamp
- })) || []
- },
- raw: data
- };
- }
-
- /**
- * Normalize user fundings
- */
- private normalizeUserFundings(data: HyperLiquidUserFundingsData): NormalizedMessage {
- return {
- provider: this.provider,
- channel: 'userFundings',
- type: 'custom',
- timestamp: Date.now(),
- data: {
- user: data.user,
- isSnapshot: data.isSnapshot,
- fundings: data.fundings.map(funding => ({
- time: funding.time,
- coin: funding.coin,
- usdc: parseFloat(funding.usdc),
- szi: parseFloat(funding.szi),
- fundingRate: parseFloat(funding.fundingRate)
- }))
- },
- raw: data
- };
- }
-
- /**
- * Check if channel requires user address
- */
- private isUserSpecificChannel(channel: string): boolean {
- const userChannels = [
- 'userFills',
- 'openOrders',
- 'userFundings',
- 'clearinghouseState',
- 'userEvents',
- 'orderUpdates',
- 'userNonFundingLedgerUpdates',
- 'userTwapSliceFills',
- 'userTwapHistory',
- 'activeAssetData',
- 'twapStates',
- 'notification',
- 'webData2',
- 'webData3'
- ];
-
- return userChannels.includes(channel);
- }
-
- /**
- * 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('.')
- };
- }
- }
-
- /**
- * Build subscription key for tracking
- */
- private buildSubscriptionKey(subscription: any): string {
- const parts = [subscription.type];
- if (subscription.coin) parts.push(subscription.coin);
- if (subscription.user) parts.push(subscription.user);
- if (subscription.interval) parts.push(subscription.interval);
- return parts.join(':');
- }
-}
-
-/**
- * HyperLiquid WebSocket Usage Examples:
- *
- * All Mids (mid-prices for all coins):
- * subscribe('allMids')
- *
- * Level 2 Order Book (nSigFigs: 2-5):
- * subscribe('l2Book.BTC', { nSigFigs: 5 })
- * subscribe('l2Book.ETH', { nSigFigs: 5, mantissa: 1 })
- *
- * Trades:
- * subscribe('trades.BTC')
- *
- * Candles (intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, 1d, 3d, 1w, 1M):
- * subscribe('candle.BTC', { interval: '1m' })
- * subscribe('candle.ETH', { interval: '1h' })
- *
- * Best Bid/Offer:
- * subscribe('bbo.BTC')
- *
- * User Fills (requires api_key set to wallet address):
- * subscribe('userFills', { aggregateByTime: true })
- *
- * Open Orders (requires api_key set to wallet address):
- * subscribe('openOrders')
- */
diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/index.ts b/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
index 0c5ac000f..249faa8b5 100644
--- a/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
+++ b/fincept-terminal-desktop/src/services/websocket/adapters/index.ts
@@ -4,15 +4,15 @@
import { AdapterRegistry, IWebSocketAdapter } from '../types';
import { BaseAdapter } from './BaseAdapter';
import { KrakenAdapter } from './KrakenAdapter';
-import { HyperLiquidAdapter } from './HyperLiquidAdapter';
/**
* Global registry of available WebSocket adapters
* Add new adapters here as they are implemented
+ *
+ * Note: HyperLiquid now uses CCXT adapter in src/brokers/exchanges/HyperLiquidAdapter.ts
*/
export const adapters: AdapterRegistry = {
kraken: KrakenAdapter,
- hyperliquid: HyperLiquidAdapter,
// Add more adapters here:
// fyers: FyersAdapter,
// polygon: PolygonAdapter,
@@ -50,4 +50,3 @@ export function createAdapter(provider: string): IWebSocketAdapter {
// Export adapter classes
export { BaseAdapter } from './BaseAdapter';
export { KrakenAdapter } from './KrakenAdapter';
-export { HyperLiquidAdapter } from './HyperLiquidAdapter';
diff --git a/fincept-terminal-desktop/src/types/hyperliquid.d.ts b/fincept-terminal-desktop/src/types/hyperliquid.d.ts
deleted file mode 100644
index d949a5127..000000000
--- a/fincept-terminal-desktop/src/types/hyperliquid.d.ts
+++ /dev/null
@@ -1,321 +0,0 @@
-// File: src/types/hyperliquid.d.ts
-// HyperLiquid exchange TypeScript type definitions
-// Documentation: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api
-
-/**
- * HyperLiquid WebSocket subscription types
- */
-export type HyperLiquidSubscriptionType =
- | 'allMids'
- | 'notification'
- | 'webData2'
- | 'webData3'
- | 'candle'
- | 'l2Book'
- | 'trades'
- | 'orderUpdates'
- | 'userEvents'
- | 'userFills'
- | 'userFundings'
- | 'userNonFundingLedgerUpdates'
- | 'userTwapSliceFills'
- | 'userTwapHistory'
- | 'activeAssetCtx'
- | 'activeAssetData'
- | 'twapStates'
- | 'clearinghouseState'
- | 'openOrders'
- | 'bbo';
-
-/**
- * Candle intervals supported by HyperLiquid
- */
-export type HyperLiquidCandleInterval =
- | '1m' | '3m' | '5m' | '15m' | '30m'
- | '1h' | '2h' | '4h' | '8h' | '12h'
- | '1d' | '3d' | '1w' | '1M';
-
-/**
- * HyperLiquid WebSocket base message structure
- */
-export interface HyperLiquidMessage {
- channel: string;
- data: any;
-}
-
-/**
- * HyperLiquid subscription request
- */
-export interface HyperLiquidSubscriptionRequest {
- method: 'subscribe' | 'unsubscribe';
- subscription: {
- type: HyperLiquidSubscriptionType;
- coin?: string;
- user?: string;
- interval?: HyperLiquidCandleInterval;
- nSigFigs?: number; // 2-5 for l2Book
- mantissa?: 1 | 2 | 5; // Only with nSigFigs=5
- aggregateByTime?: boolean; // For userFills
- };
-}
-
-/**
- * HyperLiquid subscription response
- */
-export interface HyperLiquidSubscriptionResponse {
- channel: 'subscriptionResponse';
- data: {
- method: 'subscribe' | 'unsubscribe';
- subscription: any;
- };
-}
-
-/**
- * All Mids (mid-price for all coins)
- */
-export interface HyperLiquidAllMidsData {
- mids: Record<string, string>; // Coin -> mid price
-}
-
-/**
- * Level 2 Order Book
- */
-export interface HyperLiquidL2BookLevel {
- px: string; // Price
- sz: string; // Size
- n: number; // Number of orders
-}
-
-export interface HyperLiquidL2BookData {
- coin: string;
- time: number;
- levels: [HyperLiquidL2BookLevel[], HyperLiquidL2BookLevel[]]; // [bids, asks]
-}
-
-/**
- * Trade data
- */
-export interface HyperLiquidTrade {
- coin: string;
- side: 'A' | 'B'; // Ask (sell) or Bid (buy)
- px: string; // Price
- sz: string; // Size
- time: number; // Timestamp
- tid: number; // Trade ID
- hash?: string; // Transaction hash
-}
-
-export interface HyperLiquidTradesData {
- coin?: string;
- trades: HyperLiquidTrade[];
-}
-
-/**
- * Candle (OHLCV) data
- */
-export interface HyperLiquidCandle {
- t: number; // Timestamp (open time)
- T: number; // Close timestamp
- s: string; // Symbol
- i: HyperLiquidCandleInterval; // Interval
- o: string; // Open
- c: string; // Close
- h: string; // High
- l: string; // Low
- v: string; // Volume
- n: number; // Number of trades
-}
-
-export interface HyperLiquidCandleData {
- candle?: HyperLiquidCandle;
-}
-
-/**
- * BBO (Best Bid Offer)
- */
-export interface HyperLiquidBBO {
- coin: string;
- bid: string; // Best bid price
- ask: string; // Best ask price
- time: number; // Timestamp
-}
-
-export interface HyperLiquidBBOData {
- bbo?: HyperLiquidBBO;
-}
-
-/**
- * User Fills
- */
-export interface HyperLiquidUserFill {
- coin: string;
- px: string; // Fill price
- sz: string; // Fill size
- side: 'A' | 'B'; // Ask or Bid
- time: number; // Timestamp
- startPosition: string;
- dir: string; // Direction
- closedPnl: string;
- hash: string;
- oid: number; // Order ID
- crossed: boolean;
- fee: string;
- tid: number; // Trade ID
- builderFee?: string;
-}
-
-export interface HyperLiquidUserFillsData {
- isSnapshot: boolean;
- user: string;
- fills: HyperLiquidUserFill[];
-}
-
-/**
- * Open Orders
- */
-export interface HyperLiquidOpenOrder {
- coin: string;
- side: 'A' | 'B';
- limitPx: string;
- sz: string;
- oid: number;
- timestamp: number;
- origSz: string;
- cloid?: string; // Client order ID
-}
-
-export interface HyperLiquidOpenOrdersData {
- user?: string;
- orders?: HyperLiquidOpenOrder[];
-}
-
-/**
- * User Fundings
- */
-export interface HyperLiquidUserFunding {
- time: number;
- coin: string;
- usdc: string;
- szi: string;
- fundingRate: string;
-}
-
-export interface HyperLiquidUserFundingsData {
- isSnapshot: boolean;
- user: string;
- fundings: HyperLiquidUserFunding[];
-}
-
-/**
- * Clearinghouse State (User Position State)
- */
-export interface HyperLiquidAssetPosition {
- type: 'oneWay';
- position: {
- coin: string;
- szi: string; // Signed position size
- leverage: {
- type: 'cross' | 'isolated';
- value: number;
- rawUsd?: string;
- };
- entryPx: string | null;
- positionValue: string;
- unrealizedPnl: string;
- returnOnEquity: string;
- liquidationPx: string | null;
- marginUsed: string;
- maxTrade: string;
- cumFunding: {
- allTime: string;
- sinceOpen: string;
- sinceChange: string;
- };
- };
-}
-
-export interface HyperLiquidClearinghouseState {
- assetPositions: HyperLiquidAssetPosition[];
- crossMarginSummary: {
- accountValue: string;
- totalNtlPos: string;
- totalRawUsd: string;
- totalMarginUsed: string;
- withdrawable: string;
- };
- marginSummary: {
- accountValue: string;
- totalNtlPos: string;
- totalRawUsd: string;
- totalMarginUsed: string;
- };
- time: number;
-}
-
-/**
- * REST API Response Types
- */
-
-export interface HyperLiquidCandleSnapshotRequest {
- type: 'candleSnapshot';
- req: {
- coin: string;
- interval: HyperLiquidCandleInterval;
- startTime: number; // Milliseconds
- endTime?: number; // Milliseconds
- };
-}
-
-export interface HyperLiquidAllMidsRequest {
- type: 'allMids';
- dex?: string; // Optional, defaults to first perp dex
-}
-
-export interface HyperLiquidL2BookSnapshotRequest {
- type: 'l2Book';
- coin: string;
- nSigFigs?: number; // 2-5
- mantissa?: 1 | 2 | 5;
-}
-
-export interface HyperLiquidUserStateRequest {
- type: 'clearinghouseState';
- user: string; // Wallet address
-}
-
-export interface HyperLiquidOpenOrdersRequest {
- type: 'openOrders';
- user: string;
- dex?: string;
-}
-
-export interface HyperLiquidUserFillsRequest {
- type: 'userFills';
- user: string;
- aggregateByTime?: boolean;
-}
-
-export interface HyperLiquidUserFillsByTimeRequest {
- type: 'userFillsByTime';
- user: string;
- startTime: number;
- endTime?: number;
-}
-
-/**
- * Meta info for available assets
- */
-export interface HyperLiquidAssetInfo {
- name: string;
- szDecimals: number;
- maxLeverage: number;
- onlyIsolated: boolean;
-}
-
-export interface HyperLiquidMetaRequest {
- type: 'meta';
-}
-
-export interface HyperLiquidMetaResponse {
- universe: HyperLiquidAssetInfo[];
-}