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: Complete TypeScript migration to new broker adapter architecture

tilakpatel2280be639f0e53
diff --git a/fincept-terminal-desktop/src/brokers/crypto/index.ts b/fincept-terminal-desktop/src/brokers/crypto/index.ts
index aea950628..5b2431994 100644
--- a/fincept-terminal-desktop/src/brokers/crypto/index.ts
+++ b/fincept-terminal-desktop/src/brokers/crypto/index.ts
@@ -11,8 +11,7 @@ export { BaseExchangeAdapter } from './BaseExchangeAdapter';
export { KrakenAdapter } from './kraken/KrakenAdapter';
export { HyperLiquidAdapter } from './hyperliquid/HyperLiquidAdapter';
-// Paper Trading exports
-export * ;
+// Note: Paper Trading now in standalone src/paper-trading/ module
// Exchange registry
import { KrakenAdapter } from './kraken/KrakenAdapter';
diff --git a/fincept-terminal-desktop/src/brokers/crypto/types.ts b/fincept-terminal-desktop/src/brokers/crypto/types.ts
index baeff05a6..45e236170 100644
--- a/fincept-terminal-desktop/src/brokers/crypto/types.ts
+++ b/fincept-terminal-desktop/src/brokers/crypto/types.ts
@@ -7,6 +7,9 @@
import type { Exchange, Market, Ticker, OrderBook, Trade, OHLCV, Balance, Order, Position } from 'ccxt';
+// Re-export CCXT types for convenience
+export type { Order, Position, Balance, Market, Ticker, OrderBook, Trade, OHLCV };
+
// ============================================================================
// CORE EXCHANGE INTERFACE
// ============================================================================
diff --git a/fincept-terminal-desktop/src/brokers/index.ts b/fincept-terminal-desktop/src/brokers/index.ts
index cb4ea4d41..c05699fd0 100644
--- a/fincept-terminal-desktop/src/brokers/index.ts
+++ b/fincept-terminal-desktop/src/brokers/index.ts
@@ -8,12 +8,27 @@
// ============================================================================
// CRYPTO EXCHANGES (CCXT-based)
// ============================================================================
-export * from './crypto';
+export {
+ BaseExchangeAdapter,
+ KrakenAdapter,
+ HyperLiquidAdapter,
+ createExchangeAdapter,
+ SUPPORTED_EXCHANGES,
+ isExchangeSupported,
+ type IExchangeAdapter,
+ type ExchangeConfig,
+ type ExchangeCredentials,
+ type ExchangeCapabilities,
+ type OrderType,
+ type OrderSide,
+ type OrderParams,
+ type SupportedExchangeId,
+} from './crypto';
// ============================================================================
// STOCK BROKERS
// ============================================================================
-export * from './stocks';
+export { KiteConnectAdapter, createKiteAdapter } from './stocks';
// ============================================================================
// UNIFIED BROKER REGISTRY
diff --git a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
index b82d702ec..ee8c18096 100644
--- a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
@@ -17,7 +17,7 @@ import { getWebSocketManager } from '../../services/websocket';
import { createExchangeAdapter } from '../../brokers/crypto';
import { createPaperTradingAdapter } from '../../paper-trading';
import type { IExchangeAdapter } from '../../brokers/crypto/types';
-import type { Position } from 'ccxt';
+import type { Position as CCXTPosition } from 'ccxt';
// Symbol configurations per provider
const KRAKEN_PAIRS = ['BTC/USD', 'ETH/USD', 'SOL/USD', 'AVAX/USD', 'MATIC/USD'];
@@ -42,7 +42,7 @@ export function TradingTab() {
const [isResetting, setIsResetting] = useState(false);
const [currentTime, setCurrentTime] = useState(new Date());
const [isConnected, setIsConnected] = useState(false);
- const [positions, setPositions] = useState<Position[]>([]);
+ const [positions, setPositions] = useState<CCXTPosition[]>([]);
const [balance, setBalance] = useState<number>(0);
const [totalPnL, setTotalPnL] = useState<number>(0);
const [isLoading, setIsLoading] = useState(false);
@@ -114,8 +114,8 @@ export function TradingTab() {
}
// Create new adapter
- realAdapterRef.current = createExchangeAdapter(activeProvider);
- await realAdapterRef.current.connect();
+ realAdapterRef.current = createExchangeAdapter(activeProvider as 'kraken' | 'hyperliquid') as IExchangeAdapter;
+ await realAdapterRef.current?.connect();
console.log(`[TradingTab] ${activeProvider} adapter connected`);
} catch (error) {
console.error(`[TradingTab] Failed to initialize ${activeProvider} adapter:`, error);
@@ -204,7 +204,7 @@ export function TradingTab() {
]);
// Calculate balance and P&L
- const usdBalance = balanceData.free?.['USD'] || balanceData.free?.['USDC'] || 100000;
+ const usdBalance = (balanceData.free as any)?.['USD'] || (balanceData.free as any)?.['USDC'] || 100000;
const unrealizedPnL = positionsData.reduce((sum, p) => sum + (p.unrealizedPnl || 0), 0);
setBalance(usdBalance);
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx
index 1569af9cd..154b9ccfa 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx
@@ -2,7 +2,7 @@
// Display open and closed positions
import React from 'react';
-import type { Position } from '../../../types/trading';
+import type { Position } from 'ccxt';
interface PositionsTableProps {
positions: Position[];
@@ -11,8 +11,8 @@ interface PositionsTableProps {
}
export function PositionsTable({ positions, onClosePosition, isLoading }: PositionsTableProps) {
- const openPositions = positions.filter(p => p.status === 'open');
- const closedPositions = positions.filter(p => p.status === 'closed');
+ const openPositions = positions.filter((p: any) => p.side); // CCXT positions don't have status
+ const closedPositions: Position[] = []; // Closed positions not tracked in CCXT format
return (
<div className="bg-[#0d0d0d] border-t border-gray-800">
@@ -91,7 +91,7 @@ interface PositionRowProps {
}
function PositionRow({ position, onClose, isLoading }: PositionRowProps) {
- const pnl = position.unrealizedPnL || 0;
+ const pnl = position.unrealizedPnl || 0;
const pnlColor = pnl >= 0 ? 'text-green-400' : 'text-red-400';
return (
@@ -101,13 +101,13 @@ function PositionRow({ position, onClose, isLoading }: PositionRowProps) {
<span className={`px-2 py-0.5 rounded text-[10px] font-semibold ${
position.side === 'long' ? 'bg-green-900/30 text-green-400' : 'bg-red-900/30 text-red-400'
}`}>
- {position.side.toUpperCase()}
+ {(position.side || 'unknown').toUpperCase()}
</span>
</td>
- <td className="px-3 py-2 text-right text-gray-300">{position.quantity.toFixed(4)}</td>
- <td className="px-3 py-2 text-right text-gray-300">${position.entryPrice.toFixed(2)}</td>
+ <td className="px-3 py-2 text-right text-gray-300">{(position.contracts || 0).toFixed(4)}</td>
+ <td className="px-3 py-2 text-right text-gray-300">${(position.entryPrice || 0).toFixed(2)}</td>
<td className="px-3 py-2 text-right text-white">
- ${position.currentPrice?.toFixed(2) || '-'}
+ ${(position.markPrice || position.entryPrice || 0).toFixed(2)}
</td>
<td className={`px-3 py-2 text-right font-semibold ${pnlColor}`}>
{pnl >= 0 ? '+' : ''}{pnl.toFixed(2)}
@@ -115,7 +115,7 @@ function PositionRow({ position, onClose, isLoading }: PositionRowProps) {
<td className="px-3 py-2 text-center">
{onClose && (
<button
- onClick={() => onClose(position.id)}
+ onClick={() => onClose(position.id || '')}
disabled={isLoading}
className="px-2 py-1 bg-red-600 hover:bg-red-700 text-white rounded text-[10px] font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
>
@@ -128,10 +128,10 @@ function PositionRow({ position, onClose, isLoading }: PositionRowProps) {
}
function ClosedPositionRow({ position }: { position: Position }) {
- const pnl = position.realizedPnL;
+ const pnl = position.realizedPnl || 0;
const pnlColor = pnl >= 0 ? 'text-green-400' : 'text-red-400';
- const closedDate = position.closedAt
- ? new Date(position.closedAt).toLocaleDateString()
+ const closedDate = position.datetime
+ ? new Date(position.datetime).toLocaleDateString()
: '-';
return (
@@ -141,11 +141,11 @@ function ClosedPositionRow({ position }: { position: Position }) {
<span className={`px-2 py-0.5 rounded text-[10px] ${
position.side === 'long' ? 'bg-green-900/20 text-green-600' : 'bg-red-900/20 text-red-600'
}`}>
- {position.side.toUpperCase()}
+ {(position.side || 'unknown').toUpperCase()}
</span>
</td>
- <td className="px-3 py-2 text-right">{position.quantity.toFixed(4)}</td>
- <td className="px-3 py-2 text-right">${position.entryPrice.toFixed(2)}</td>
+ <td className="px-3 py-2 text-right">{(position.contracts || 0).toFixed(4)}</td>
+ <td className="px-3 py-2 text-right">${(position.entryPrice || 0).toFixed(2)}</td>
<td className={`px-3 py-2 text-right font-semibold ${pnlColor}`}>
{pnl >= 0 ? '+' : ''}{pnl.toFixed(2)}
</td>
diff --git a/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
index d4561c47c..a903ae622 100644
--- a/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
+++ b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
@@ -353,7 +353,7 @@ export class OrderMatchingEngine {
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 this.executeTrade(order.id, order.symbol, order.side as OrderSide, executionPrice, order.amount, false);
await paperTradingDatabase.updateOrder(order.id, {
filledQuantity: order.amount,
@@ -370,7 +370,7 @@ export class OrderMatchingEngine {
: currentPrice >= order.price;
if (canFill) {
- await this.executeTrade(order.id, order.symbol, order.side, order.price, order.amount, true);
+ await this.executeTrade(order.id, order.symbol, order.side as OrderSide, order.price, order.amount, true);
await paperTradingDatabase.updateOrder(order.id, {
filledQuantity: order.amount,
@@ -507,7 +507,7 @@ export class OrderMatchingEngine {
order: this.createOrderObject(orderId, symbol, 'market', side, quantity, price, params, 'filled'),
trades: [trade],
position,
- balance: balance.free[currency] || 0,
+ balance: (balance.free as any)?.[currency] || 0,
};
}
@@ -559,7 +559,7 @@ export class OrderMatchingEngine {
: priceSnapshot.bid >= (order.price || 0);
if (canFill) {
- await this.executeLimitOrder(order.id, order.symbol, order.side, order.amount, order.price!, {
+ await this.executeLimitOrder(order.id, order.symbol, order.side as OrderSide, order.amount, order.price!, {
leverage: order.leverage,
marginMode: order.marginMode as any,
});
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
index 3f41364b6..a8c1a3497 100644
--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
@@ -35,8 +35,12 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
this.balanceManager = new PaperTradingBalance(this.paperConfig);
this.matchingEngine = new OrderMatchingEngine(this.paperConfig, this.realAdapter);
- // Override name
- this.name = `${this.realAdapter.name} (Paper Trading)`;
+ // Set name (using Object.defineProperty to override readonly)
+ Object.defineProperty(this, 'name', {
+ value: `${this.realAdapter.name} (Paper Trading)`,
+ writable: false,
+ configurable: true
+ });
}
// ============================================================================
@@ -92,7 +96,7 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
await paperTradingDatabase.createPortfolio({
id: this.paperConfig.portfolioId,
name: this.paperConfig.portfolioName,
- provider: this.paperConfig.realExchange,
+ provider: this.paperConfig.provider,
initialBalance: this.paperConfig.initialBalance,
currency: this.paperConfig.currency,
marginMode: this.paperConfig.marginMode,
@@ -134,15 +138,24 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
}
async fetchStatus(): Promise<any> {
- return await this.realAdapter.fetchStatus?.();
+ if ('fetchStatus' in this.realAdapter && typeof this.realAdapter.fetchStatus === 'function') {
+ return await this.realAdapter.fetchStatus();
+ }
+ return { status: 'ok', updated: Date.now() };
}
async fetchCurrencies(): Promise<any> {
- return await this.realAdapter.fetchCurrencies?.();
+ if ('fetchCurrencies' in this.realAdapter && typeof this.realAdapter.fetchCurrencies === 'function') {
+ return await this.realAdapter.fetchCurrencies();
+ }
+ return {};
}
async fetchTime(): Promise<number> {
- return await this.realAdapter.fetchTime?.() || Date.now();
+ if ('fetchTime' in this.realAdapter && typeof this.realAdapter.fetchTime === 'function') {
+ return await this.realAdapter.fetchTime();
+ }
+ return Date.now();
}
// ============================================================================
@@ -185,7 +198,7 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
unrealizedPnl: p.unrealizedPnl || 0,
contracts: p.quantity,
contractSize: 1,
- marginRatio: null,
+ marginRatio: undefined,
liquidationPrice: p.liquidationPrice || 0,
markPrice: p.currentPrice || p.entryPrice,
collateral: (p.quantity * p.entryPrice) / p.leverage,
@@ -355,7 +368,7 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
cost: t.price * t.quantity,
fee: {
cost: t.fee,
- currency: this.paperConfig.currency || 'USD',
+ currency: (this.paperConfig.currency || 'USD') as string,
rate: t.feeRate,
},
} as Trade));
@@ -417,7 +430,7 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
cost: t.price * t.quantity,
fee: {
cost: t.fee,
- currency: this.paperConfig.currency || 'USD',
+ currency: (this.paperConfig.currency || 'USD') as string,
rate: t.feeRate,
},
} as Trade));
@@ -577,7 +590,9 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
// ============================================================================
getCapabilities(): ExchangeCapabilities {
- const realCapabilities = this.realAdapter.getCapabilities?.() || {} as ExchangeCapabilities;
+ const realCapabilities = ('getCapabilities' in this.realAdapter && typeof this.realAdapter.getCapabilities === 'function')
+ ? this.realAdapter.getCapabilities()
+ : {} as ExchangeCapabilities;
return {
...realCapabilities,
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
index c509c1649..bb2722daa 100644
--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
@@ -40,7 +40,7 @@ export class PaperTradingBalance {
const used = marginUsed;
const total = portfolio.currentBalance;
- return {
+ const balanceObj: any = {
free: { [currency]: free },
used: { [currency]: used },
total: { [currency]: total },
@@ -49,7 +49,9 @@ export class PaperTradingBalance {
margin_mode: portfolio.marginMode,
leverage: portfolio.leverage,
},
- } as Balance;
+ };
+
+ return balanceObj as Balance;
}
/**
@@ -79,7 +81,7 @@ export class PaperTradingBalance {
const balance = await this.getBalance(portfolioId);
const currency = portfolio.currency || 'USD';
- const available = balance.free[currency] || 0;
+ const available = (balance.free as any)?.[currency] || 0;
const sufficient = available >= totalRequired;
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts
index 2e10f2e6a..f33e874b4 100644
--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingDatabase.ts
@@ -93,7 +93,7 @@ export class PaperTradingDatabase {
`;
const result = await sqliteService.select<DBPortfolio[]>(sql, []);
- return result.map(row => this.mapDBPortfolio(row));
+ return result.map((row: any) => this.mapDBPortfolio(row));
}
// ============================================================================
@@ -185,7 +185,7 @@ export class PaperTradingDatabase {
sql += ` ORDER BY opened_at DESC`;
const result = await sqliteService.select<DBPosition[]>(sql, params);
- return result.map(row => this.mapDBPosition(row));
+ return result.map((row: any) => this.mapDBPosition(row));
}
async updatePosition(positionId: string, updates: {
diff --git a/fincept-terminal-desktop/src/paper-trading/types.ts b/fincept-terminal-desktop/src/paper-trading/types.ts
index bb7bb43c5..554bf2d59 100644
--- a/fincept-terminal-desktop/src/paper-trading/types.ts
+++ b/fincept-terminal-desktop/src/paper-trading/types.ts
@@ -118,9 +118,29 @@ export interface PaperTradingPosition {
status: 'open' | 'closed';
}
-export interface PaperTradingOrder extends Order {
+// Paper trading order (compatible with CCXT Order)
+export interface PaperTradingOrder {
+ id: string;
portfolioId: string;
- stopPrice?: number | null;
+ clientOrderId?: string;
+ timestamp: number;
+ datetime: string;
+ lastTradeTimestamp?: number;
+ symbol: string;
+ type: string;
+ side: string;
+ price?: number;
+ amount: number;
+ cost?: number;
+ average?: number;
+ filled: number;
+ remaining: number;
+ status: string;
+ fee?: any;
+ trades?: any[];
+ info: any;
+ // Paper trading specific
+ stopPrice?: number;
trailingAmount?: number | null;
trailingPercent?: number | null;
icebergQty?: number | null;