FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
Trading Tab Update
tilakpatel22034b4d612a68
diff --git a/fincept-terminal-desktop/src/components/settings/LanguageSelector.tsx b/fincept-terminal-desktop/src/components/settings/LanguageSelector.tsxindex 404ee0aea..5fee94a63 100644--- a/fincept-terminal-desktop/src/components/settings/LanguageSelector.tsx+++ b/fincept-terminal-desktop/src/components/settings/LanguageSelector.tsx@@ -1,59 +1,329 @@// File: src/components/settings/LanguageSelector.tsx-// Language selector component for the Settings tab+// Bloomberg Terminal-styled language selectorimport React from 'react';import { useLanguage } from '@/contexts/LanguageContext';import { useTranslation } from 'react-i18next';-import { Globe } from 'lucide-react';+import { Globe, Check } from 'lucide-react';++// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};export const LanguageSelector: React.FC = () => {const { currentLanguage, changeLanguage, availableLanguages } = useLanguage();const { t } = useTranslation('settings');return (- <div className="space-y-4">- <div className="flex items-center gap-2 mb-4">- <Globe className="h-5 w-5 text-blue-400" />- <h3 className="text-lg font-medium text-white">{t('language.title')}</h3>+ <div style={{+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'+ }}>+ {/* Header */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ marginBottom: '24px',+ paddingBottom: '12px',+ borderBottom: `2px solid ${BLOOMBERG.ORANGE}`+ }}>+ <Globe size={20} color={BLOOMBERG.ORANGE} style={{ filter: `drop-shadow(0 0 4px ${BLOOMBERG.ORANGE})` }} />+ <h2 style={{+ color: BLOOMBERG.ORANGE,+ fontSize: '16px',+ fontWeight: 700,+ letterSpacing: '1px',+ margin: 0,+ textShadow: `0 0 10px ${BLOOMBERG.ORANGE}40`+ }}>+ {t('language.title', 'LANGUAGE SETTINGS')}+ </h2>+ </div>++ {/* Description */}+ <div style={{+ marginBottom: '20px',+ padding: '12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderLeft: `3px solid ${BLOOMBERG.CYAN}`+ }}>+ <p style={{+ color: BLOOMBERG.GRAY,+ fontSize: '10px',+ margin: 0,+ lineHeight: '1.6'+ }}>+ {t('language.selectLanguage', 'Select your preferred language for the terminal interface')}+ </p></div>- <div className="space-y-3">- <label className="text-sm text-zinc-400">{t('language.selectLanguage')}</label>+ {/* Language Grid */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',+ gap: '12px',+ marginBottom: '24px'+ }}>+ {availableLanguages.map((lang) => {+ const isActive = currentLanguage === lang.code;- <div className="grid grid-cols-2 gap-3">- {availableLanguages.map((lang) => (+ return (<buttonkey={lang.code}onClick={() => changeLanguage(lang.code)}- className={`- flex items-center gap-3 p-3 rounded-lg border transition-all- ${- currentLanguage === lang.code- ? 'bg-blue-500/20 border-blue-500 text-white'- : 'bg-zinc-800/50 border-zinc-700 text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600'+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ padding: '14px',+ backgroundColor: isActive ? BLOOMBERG.PANEL_BG : BLOOMBERG.HEADER_BG,+ border: `1px solid ${isActive ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,+ borderLeft: `3px solid ${isActive ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,+ cursor: 'pointer',+ transition: 'all 0.2s',+ position: 'relative',+ overflow: 'hidden'+ }}+ onMouseEnter={(e) => {+ if (!isActive) {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ e.currentTarget.style.borderColor = BLOOMBERG.MUTED;}- `}+ }}+ onMouseLeave={(e) => {+ if (!isActive) {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HEADER_BG;+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ }+ }}>- <span className="text-2xl">{lang.flag}</span>- <div className="text-left">- <div className="font-medium text-sm">{lang.nativeName}</div>- <div className="text-xs text-zinc-500">{lang.name}</div>+ {/* Flag */}+ <span style={{+ fontSize: '32px',+ lineHeight: 1,+ filter: isActive ? 'brightness(1.2)' : 'brightness(0.8)'+ }}>+ {lang.flag}+ </span>++ {/* Language Info */}+ <div style={{ flex: 1, textAlign: 'left' }}>+ <div style={{+ color: isActive ? BLOOMBERG.ORANGE : BLOOMBERG.WHITE,+ fontSize: '12px',+ fontWeight: 700,+ marginBottom: '2px',+ letterSpacing: '0.5px'+ }}>+ {lang.nativeName}+ </div>+ <div style={{+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ fontWeight: 500+ }}>+ {lang.name}+ </div></div>- {currentLanguage === lang.code && (- <div className="ml-auto">- <div className="w-2 h-2 bg-blue-500 rounded-full"></div>++ {/* Active Indicator */}+ {isActive && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}>+ <Check size={14} color={BLOOMBERG.GREEN} />+ <div style={{+ width: '8px',+ height: '8px',+ borderRadius: '50%',+ backgroundColor: BLOOMBERG.GREEN,+ boxShadow: `0 0 8px ${BLOOMBERG.GREEN}`+ }} /></div>)}++ {/* Hover Glow Effect */}+ {isActive && (+ <div style={{+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ height: '1px',+ background: `linear-gradient(90deg, transparent, ${BLOOMBERG.ORANGE}, transparent)`,+ opacity: 0.5+ }} />+ )}</button>- ))}+ );+ })}+ </div>++ {/* Current Language Status */}+ <div style={{+ padding: '16px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderTop: `2px solid ${BLOOMBERG.GREEN}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: BLOOMBERG.GREEN,+ boxShadow: `0 0 8px ${BLOOMBERG.GREEN}`+ }} />+ <span style={{+ color: BLOOMBERG.GRAY,+ fontSize: '10px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ {t('language.currentLanguage', 'CURRENT LANGUAGE')}:+ </span>+ </div>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}>+ <span style={{+ fontSize: '18px'+ }}>+ {availableLanguages.find(lang => lang.code === currentLanguage)?.flag || '🌐'}+ </span>+ <span style={{+ color: BLOOMBERG.CYAN,+ fontSize: '12px',+ fontWeight: 700,+ letterSpacing: '0.5px'+ }}>+ {availableLanguages.find(lang => lang.code === currentLanguage)?.nativeName || 'English'}+ </span>+ </div>+ </div>++ {/* Info Panel */}+ <div style={{+ marginTop: '20px',+ padding: '12px 16px',+ backgroundColor: `${BLOOMBERG.CYAN}10`,+ border: `1px solid ${BLOOMBERG.CYAN}40`,+ borderLeft: `3px solid ${BLOOMBERG.CYAN}`+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'flex-start',+ gap: '10px'+ }}>+ <Globe size={14} color={BLOOMBERG.CYAN} style={{ marginTop: '1px', flexShrink: 0 }} />+ <div style={{+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ lineHeight: '1.5'+ }}>+ Language changes will apply immediately across the entire terminal interface.+ All menus, labels, and system messages will be displayed in the selected language.+ </div>+ </div>+ </div>++ {/* Statistics */}+ <div style={{+ marginTop: '20px',+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',+ gap: '12px'+ }}>+ <div style={{+ padding: '12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ textAlign: 'center'+ }}>+ <div style={{+ color: BLOOMBERG.YELLOW,+ fontSize: '20px',+ fontWeight: 700,+ marginBottom: '4px'+ }}>+ {availableLanguages.length}+ </div>+ <div style={{+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ LANGUAGES+ </div></div>- <div className="mt-4 p-3 bg-zinc-800/30 border border-zinc-700 rounded-lg">- <div className="flex items-center gap-2 text-xs text-zinc-400">- <span className="font-medium">{t('language.currentLanguage')}:</span>- <span className="text-white">- {availableLanguages.find(lang => lang.code === currentLanguage)?.nativeName || 'English'}- </span>+ <div style={{+ padding: '12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ textAlign: 'center'+ }}>+ <div style={{+ color: BLOOMBERG.GREEN,+ fontSize: '20px',+ fontWeight: 700,+ marginBottom: '4px'+ }}>+ 100%+ </div>+ <div style={{+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ COVERAGE+ </div>+ </div>++ <div style={{+ padding: '12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ textAlign: 'center'+ }}>+ <div style={{+ color: BLOOMBERG.CYAN,+ fontSize: '20px',+ fontWeight: 700,+ marginBottom: '4px'+ }}>+ RTL+ </div>+ <div style={{+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ SUPPORTED</div></div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsxindex 328b7d339..866515f3f 100644--- a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx@@ -1,10 +1,24 @@// File: src/components/tabs/TradingTab.tsx-// Complete Trading Tab with Paper Trading Integration+// Professional Bloomberg Terminal-Grade Trading Interfaceimport React, { useState, useEffect, useCallback } from 'react';+import {+ TrendingUp, TrendingDown, Activity, DollarSign, BarChart3,+ Settings as SettingsIcon, Globe, Wifi, WifiOff, Bell,+ Zap, Target, AlertCircle, RefreshCw, Maximize2, ChevronDown,+ Clock, TrendingDown as ArrowDown, TrendingUp as ArrowUp, ChevronUp, Minimize2+} from 'lucide-react';import { useBrokerContext } from '../../contexts/BrokerContext';import { useWebSocket } from '../../hooks/useWebSocket';-import { OrderForm } from './trading/OrderForm';+// Import new enhanced order form+import { EnhancedOrderForm } from './trading/core/OrderForm';+import { HyperLiquidVaultManager } from './trading/exchange-specific/hyperliquid';+import { StakingPanel, FuturesPanel } from './trading/exchange-specific/kraken';+import { PositionsTable } from './trading/core/PositionManager';+import { OrdersTable, ClosedOrders } from './trading/core/OrderManager';+import { TradingChart, DepthChart, VolumeProfile } from './trading/charts';+import { AccountStats, FeesDisplay, MarginPanel } from './trading/core/AccountInfo';+import { PortfolioAggregator, ArbitrageDetector } from './trading/cross-exchange';import type { OrderRequest } from '../../types/trading';interface OrderBookLevel {@@ -41,26 +55,41 @@ interface Order {createdAt: string;}+// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};+export function TradingTab() {const {activeBroker,+ availableBrokers,+ setActiveBroker,tradingMode,+ setTradingMode,+ paperPortfolioMode,+ setPaperPortfolioMode,activeAdapter,paperAdapter,defaultSymbols,isConnecting,} = useBrokerContext();- // Debug logging- useEffect(() => {- console.log('[TradingTab] Context updated:');- console.log(' - activeBroker:', activeBroker);- console.log(' - tradingMode:', tradingMode);- console.log(' - paperAdapter:', paperAdapter ? 'EXISTS' : 'NULL');- console.log(' - paperAdapter.isConnected():', paperAdapter?.isConnected());- console.log(' - isConnecting:', isConnecting);- }, [activeBroker, tradingMode, paperAdapter, isConnecting]);-+ const [currentTime, setCurrentTime] = useState(new Date());const [selectedSymbol, setSelectedSymbol] = useState(defaultSymbols[0] || 'BTC/USD');const [tickerData, setTickerData] = useState<any>(null);const [orderBook, setOrderBook] = useState<OrderBook>({ bids: [], asks: [], symbol: '' });@@ -68,11 +97,14 @@ export function TradingTab() {const [isPlacingOrder, setIsPlacingOrder] = useState(false);const [lastOrderBookUpdate, setLastOrderBookUpdate] = useState<number>(0);- // Symbol search state+ // UI Stateconst [searchQuery, setSearchQuery] = useState('');const [availableSymbols, setAvailableSymbols] = useState<string[]>([]);const [isLoadingSymbols, setIsLoadingSymbols] = useState(false);const [showSymbolDropdown, setShowSymbolDropdown] = useState(false);+ const [showBrokerDropdown, setShowBrokerDropdown] = useState(false);+ const [selectedView, setSelectedView] = useState<'chart' | 'depth' | 'trades'>('chart');+ const [rightPanelView, setRightPanelView] = useState<'orderbook' | 'volume'>('orderbook');// Paper trading stateconst [positions, setPositions] = useState<Position[]>([]);@@ -81,51 +113,53 @@ export function TradingTab() {const [balance, setBalance] = useState(0);const [equity, setEquity] = useState(0);const [stats, setStats] = useState<any>(null);- const [activeTab, setActiveTab] = useState<'positions' | 'orders' | 'trades' | 'stats'>('positions');+ const [activeBottomTab, setActiveBottomTab] = useState<'positions' | 'orders' | 'history' | 'trades' | 'stats' | 'features' | 'cross-exchange'>('positions');+ const [isBottomPanelMinimized, setIsBottomPanelMinimized] = useState(false);// Trading settingsconst [slippage, setSlippage] = useState(0);- const [makerFee, setMakerFee] = useState(0.0002); // 0.02% default- const [takerFee, setTakerFee] = useState(0.0005); // 0.05% default+ const [makerFee, setMakerFee] = useState(0.0002);+ const [takerFee, setTakerFee] = useState(0.0005);const [showSettings, setShowSettings] = useState(false);+ // Watchlist+ const [watchlist, setWatchlist] = useState<string[]>(['BTC/USD', 'ETH/USD', 'SOL/USD']);++ // Update time+ useEffect(() => {+ const timer = setInterval(() => {+ setCurrentTime(new Date());+ }, 1000);+ return () => clearInterval(timer);+ }, []);+// Clear data when symbol changesuseEffect(() => {- console.log('[TradingTab] Symbol changed to:', selectedSymbol);- // Clear existing data for new symbolsetTickerData(null);setOrderBook({ bids: [], asks: [], symbol: selectedSymbol });setTradesData([]);setLastOrderBookUpdate(0);}, [selectedSymbol]);- // Subscribe to ticker WebSocket+ // Subscribe to WebSocket feedsconst { message: tickerMessage } = useWebSocket(activeBroker ? `${activeBroker}.ticker.${selectedSymbol}` : null);- // Subscribe to orderbook WebSocketconst { message: orderbookMessage } = useWebSocket(activeBroker ? `${activeBroker}.book.${selectedSymbol}` : null);- // Subscribe to trades WebSocketconst { message: tradesMessage } = useWebSocket(activeBroker ? `${activeBroker}.trade.${selectedSymbol}` : null);-// Update ticker datauseEffect(() => {if (tickerMessage && tickerMessage.data) {const data = tickerMessage.data;-- // Verify the ticker data is for the current selected symbolif (data.symbol === selectedSymbol) {- console.log('[TradingTab] WebSocket ticker update for', selectedSymbol, ':', data);setTickerData(data);-- // Update matching engine with WebSocket price for order monitoringif (tradingMode === 'paper' && paperAdapter) {const matchingEngine = (paperAdapter as any).matchingEngine;if (matchingEngine && typeof matchingEngine.updatePriceFromWebSocket === 'function') {@@ -134,28 +168,20 @@ export function TradingTab() {ask: data.ask,last: data.last,});- console.log('[TradingTab] Price fed to matching engine:', data.last);}}- } else {- console.log('[TradingTab] Ignoring ticker for', data.symbol, '- current symbol is', selectedSymbol);}}}, [tickerMessage, tradingMode, paperAdapter, selectedSymbol]);- // Update orderbook data+ // Update orderbookuseEffect(() => {if (!orderbookMessage || !orderbookMessage.data) return;-const data = orderbookMessage.data;const messageType = data.messageType;const dataSymbol = data.symbol || selectedSymbol;- // Only process if it's for the current selected symbol- if (dataSymbol !== selectedSymbol) {- console.log('[TradingTab] Ignoring orderbook for', dataSymbol, '- current symbol is', selectedSymbol);- return;- }+ if (dataSymbol !== selectedSymbol) return;if (messageType === 'snapshot') {setOrderBook({@@ -168,37 +194,28 @@ export function TradingTab() {} else if (messageType === 'update') {setOrderBook(prevBook => {const newBook = { ...prevBook };-if (data.bids && data.bids.length > 0) {const bidsMap = new Map(prevBook.bids.map(b => [b.price, b.size]));data.bids.forEach((bid: OrderBookLevel) => {- if (bid.size === 0) {- bidsMap.delete(bid.price);- } else {- bidsMap.set(bid.price, bid.size);- }+ if (bid.size === 0) bidsMap.delete(bid.price);+ else bidsMap.set(bid.price, bid.size);});newBook.bids = Array.from(bidsMap.entries()).map(([price, size]) => ({ price, size })).sort((a, b) => b.price - a.price).slice(0, 25);}-if (data.asks && data.asks.length > 0) {const asksMap = new Map(prevBook.asks.map(a => [a.price, a.size]));data.asks.forEach((ask: OrderBookLevel) => {- if (ask.size === 0) {- asksMap.delete(ask.price);- } else {- asksMap.set(ask.price, ask.size);- }+ if (ask.size === 0) asksMap.delete(ask.price);+ else asksMap.set(ask.price, ask.size);});newBook.asks = Array.from(asksMap.entries()).map(([price, size]) => ({ price, size })).sort((a, b) => a.price - b.price).slice(0, 25);}-newBook.checksum = data.checksum;setLastOrderBookUpdate(Date.now());return newBook;@@ -206,126 +223,60 @@ export function TradingTab() {}}, [orderbookMessage, selectedSymbol]);- // Update trades data+ // Update tradesuseEffect(() => {if (tradesMessage && tradesMessage.data) {const data = tradesMessage.data;const dataSymbol = data.symbol || selectedSymbol;-- // Only add trades for current selected symbolif (dataSymbol === selectedSymbol) {setTradesData(prev => [data, ...prev].slice(0, 50));- } else {- console.log('[TradingTab] Ignoring trade for', dataSymbol, '- current symbol is', selectedSymbol);}}}, [tradesMessage, selectedSymbol]);-// Load paper trading datauseEffect(() => {const loadPaperTradingData = async () => {if (tradingMode !== 'paper' || !paperAdapter) return;try {- console.log('[TradingTab] ==========================================');- console.log('[TradingTab] Loading paper trading data...');- console.log('[TradingTab] Portfolio ID:', (paperAdapter as any).paperConfig?.portfolioId);- console.log('[TradingTab] ==========================================');-- // Fetch balanceconst balanceData = await paperAdapter.fetchBalance();- console.log('[TradingTab] Balance:', balanceData);const usdBalance = (balanceData.free as any)?.USD || 0;const totalEquity = (balanceData.total as any)?.USD || 0;setBalance(usdBalance);setEquity(totalEquity);- // Fetch positionsconst positionsData = await paperAdapter.fetchPositions();- console.log('[TradingTab] Positions RAW from adapter:', positionsData);- console.log('[TradingTab] Number of positions:', positionsData.length);-- const mappedPositions: Position[] = positionsData.map((p: any) => {- console.log('[TradingTab] Mapping position:', {- symbol: p.symbol,- side: p.side,- contracts: p.contracts,- entryPrice: p.entryPrice,- markPrice: p.markPrice,- unrealizedPnl: p.unrealizedPnl,- percentage: p.percentage,- positionValue: p.info?.positionValue- });-- return {- symbol: p.symbol,- side: p.side,- quantity: p.contracts,- entryPrice: p.entryPrice,- positionValue: p.info?.positionValue || (p.entryPrice * p.contracts),- currentPrice: p.markPrice,- unrealizedPnl: p.unrealizedPnl,- pnlPercent: p.percentage || 0,- };- });-- console.log('[TradingTab] Mapped positions:', mappedPositions);- console.log('[TradingTab] Setting positions state with', mappedPositions.length, 'positions');+ const mappedPositions: Position[] = positionsData.map((p: any) => ({+ symbol: p.symbol,+ side: p.side,+ quantity: p.contracts,+ entryPrice: p.entryPrice,+ positionValue: p.info?.positionValue || (p.entryPrice * p.contracts),+ currentPrice: p.markPrice,+ unrealizedPnl: p.unrealizedPnl,+ pnlPercent: p.percentage || 0,+ }));setPositions(mappedPositions);- // Fetch open ordersconst ordersData = await paperAdapter.fetchOpenOrders();- console.log('[TradingTab] Orders RAW from adapter:', ordersData);- console.log('[TradingTab] Number of orders:', ordersData.length);-- const mappedOrders: Order[] = ordersData.map((o: any) => {- console.log('[TradingTab] Mapping order:', {- id: o.id,- symbol: o.symbol,- side: o.side,- type: o.type,- amount: o.amount,- price: o.price,- status: o.status- });-- return {- id: o.id,- symbol: o.symbol,- side: o.side,- type: o.type,- quantity: o.amount,- price: o.price,- status: o.status,- createdAt: o.datetime,- };- });-- console.log('[TradingTab] Mapped orders:', mappedOrders);- console.log('[TradingTab] Setting orders state with', mappedOrders.length, 'orders');+ const mappedOrders: Order[] = ordersData.map((o: any) => ({+ id: o.id,+ symbol: o.symbol,+ side: o.side,+ type: o.type,+ quantity: o.amount,+ price: o.price,+ status: o.status,+ createdAt: o.datetime,+ }));setOrders(mappedOrders);- // Fetch tradesconst tradesData = await paperAdapter.fetchMyTrades(undefined, undefined, 50);- console.log('[TradingTab] Trades:', tradesData);- console.log('[TradingTab] Trades details:');- tradesData.forEach((trade: any, idx: number) => {- console.log(` Trade ${idx + 1}:`, {- side: trade.side,- amount: trade.amount,- price: trade.price,- cost: trade.cost,- fee: trade.fee?.cost,- timestamp: trade.datetime- });- });setTrades(tradesData);- // Fetch statisticsif (typeof (paperAdapter as any).getStatistics === 'function') {const statsData = await (paperAdapter as any).getStatistics();- console.log('[TradingTab] Stats:', statsData);setStats(statsData);}} catch (error) {@@ -334,105 +285,49 @@ export function TradingTab() {};loadPaperTradingData();-- // Refresh every 2 seconds (not too spammy)const interval = setInterval(loadPaperTradingData, 2000);return () => clearInterval(interval);}, [tradingMode, paperAdapter]);- // Update slippage when it changes+ // Update slippage & feesuseEffect(() => {if (paperAdapter) {(paperAdapter as any).paperConfig.slippage.market = slippage;- console.log('[TradingTab] Slippage updated to:', slippage);- }- }, [slippage, paperAdapter]);-- // Update fees when they change- useEffect(() => {- if (paperAdapter) {(paperAdapter as any).paperConfig.fees.maker = makerFee;(paperAdapter as any).paperConfig.fees.taker = takerFee;- console.log('[TradingTab] Fees updated - Maker:', makerFee, 'Taker:', takerFee);}- }, [makerFee, takerFee, paperAdapter]);+ }, [slippage, makerFee, takerFee, paperAdapter]);- // Fetch available markets from broker+ // Fetch marketsuseEffect(() => {const fetchMarkets = async () => {if (!activeAdapter) return;-setIsLoadingSymbols(true);try {- console.log('[TradingTab] Fetching markets from adapter...');const markets = await activeAdapter.fetchMarkets();- console.log('[TradingTab] Markets fetched:', markets.length);-- // Extract symbols and filter for spot/USD pairsconst symbols = markets- .filter((m: any) => {- // Filter for active, spot markets- return m.active && m.spot && (m.quote === 'USD' || m.quote === 'USDT' || m.quote === 'USDC');- })+ .filter((m: any) => m.active && m.spot && (m.quote === 'USD' || m.quote === 'USDT' || m.quote === 'USDC')).map((m: any) => m.symbol).sort();-- console.log('[TradingTab] Available symbols:', symbols.length);setAvailableSymbols(symbols);} catch (error) {- console.error('[TradingTab] Failed to fetch markets:', error);- // Fallback to default symbolssetAvailableSymbols(defaultSymbols);} finally {setIsLoadingSymbols(false);}};-fetchMarkets();}, [activeAdapter, defaultSymbols]);- // Close dropdown when clicking outside- useEffect(() => {- const handleClickOutside = (event: MouseEvent) => {- const target = event.target as HTMLElement;- if (showSymbolDropdown && !target.closest('[data-symbol-selector]')) {- setShowSymbolDropdown(false);- setSearchQuery('');- }- };-- document.addEventListener('mousedown', handleClickOutside);- return () => document.removeEventListener('mousedown', handleClickOutside);- }, [showSymbolDropdown]);-// Handle order placementconst handlePlaceOrder = useCallback(async (orderRequest: OrderRequest) => {- console.log('[TradingTab] ========== ORDER PLACEMENT START ==========');- console.log('[TradingTab] Order request:', orderRequest);- console.log('[TradingTab] Slippage:', slippage);- console.log('[TradingTab] Trading mode:', tradingMode);- console.log('[TradingTab] paperAdapter:', paperAdapter ? 'EXISTS' : 'NULL');- console.log('[TradingTab] paperAdapter connected:', paperAdapter?.isConnected());-- if (!paperAdapter) {- const errorMsg = 'Paper trading adapter not available. Please wait for initialization.';- console.error('[TradingTab]', errorMsg);- alert(errorMsg);- throw new Error(errorMsg);- }-- if (!paperAdapter.isConnected()) {- const errorMsg = 'Paper trading adapter not connected. Please wait.';- console.error('[TradingTab]', errorMsg);- alert(errorMsg);- throw new Error(errorMsg);+ if (!paperAdapter || !paperAdapter.isConnected()) {+ alert('Paper trading adapter not available');+ throw new Error('Adapter not available');}setIsPlacingOrder(true);-try {- console.log('[TradingTab] Calling paperAdapter.createOrder...');-const order = await paperAdapter.createOrder(orderRequest.symbol,orderRequest.type,@@ -442,17 +337,7 @@ export function TradingTab() {{ stopPrice: orderRequest.stopPrice });- console.log('[TradingTab] ✓ Order created successfully:', order);- console.log('[TradingTab] Order ID:', order.id);- console.log('[TradingTab] Order status:', order.status);-- // Immediate refresh- console.log('[TradingTab] Refreshing orders and balance...');-const ordersData = await paperAdapter.fetchOpenOrders();- console.log('[TradingTab] fetchOpenOrders returned:', ordersData);- console.log('[TradingTab] Number of orders:', ordersData.length);-const mappedOrders: Order[] = ordersData.map((o: any) => ({id: o.id,symbol: o.symbol,@@ -463,37 +348,26 @@ export function TradingTab() {status: o.status,createdAt: o.datetime,}));-- console.log('[TradingTab] Setting orders state:', mappedOrders);setOrders(mappedOrders);const balanceData = await paperAdapter.fetchBalance();- console.log('[TradingTab] New balance:', balanceData);const usdBalance = (balanceData.free as any)?.USD || 0;setBalance(usdBalance);- alert(`Order placed successfully! ID: ${order.id}`);- console.log('[TradingTab] ========== ORDER PLACEMENT END ==========');+ alert(`✓ Order placed: ${order.id}`);} catch (error) {- console.error('[TradingTab] ✗ Order placement failed:', error);- console.error('[TradingTab] Error details:', error);- alert(`Order failed: ${(error as Error).message}`);+ alert(`✗ Order failed: ${(error as Error).message}`);throw error;} finally {setIsPlacingOrder(false);}- }, [paperAdapter, tradingMode]);+ }, [paperAdapter]);// Handle order cancellationconst handleCancelOrder = useCallback(async (orderId: string, symbol: string) => {if (!paperAdapter) return;-try {- console.log('[TradingTab] Cancelling order:', orderId);await paperAdapter.cancelOrder(orderId, symbol);- console.log('[TradingTab] ✓ Order cancelled');-- // Refresh orders immediatelyconst ordersData = await paperAdapter.fetchOpenOrders();const mappedOrders: Order[] = ordersData.map((o: any) => ({id: o.id,@@ -507,895 +381,1109 @@ export function TradingTab() {}));setOrders(mappedOrders);} catch (error) {- console.error('[TradingTab] ✗ Cancel failed:', error);+ console.error('Cancel failed:', error);}}, [paperAdapter]);- // Handle balance reset- const handleResetBalance = useCallback(async () => {- if (!paperAdapter) return;+ // Handle broker change+ const handleBrokerChange = async (brokerId: string) => {+ setShowBrokerDropdown(false);+ await setActiveBroker(brokerId);+ };- const confirmed = window.confirm(- '⚠️ Reset Paper Trading Account?\n\n' +- 'This will:\n' +- '• Close all open positions\n' +- '• Cancel all pending orders\n' +- '• Reset balance to initial capital\n' +- '• Clear trade history\n\n' +- 'This action cannot be undone!'- );+ const currentPrice = tickerData?.last || orderBook.asks[0]?.price || 0;- if (!confirmed) return;+ // Calculate price change - try multiple field names+ const priceChange = tickerData?.change || tickerData?.price_change || 0;- try {- console.log('[TradingTab] Resetting paper trading account...');-- // Call reset method on paper adapter- if (typeof (paperAdapter as any).resetAccount === 'function') {- await (paperAdapter as any).resetAccount();- console.log('[TradingTab] ✓ Account reset successfully');- alert('✓ Paper trading account has been reset!');- } else {- console.error('[TradingTab] resetAccount method not found on paperAdapter');- alert('❌ Reset method not available');- }- } catch (error) {- console.error('[TradingTab] ✗ Reset failed:', error);- alert(`❌ Reset failed: ${(error as Error).message}`);+ // Calculate percentage change - try from data or calculate manually+ let priceChangePercent = tickerData?.change_percent || tickerData?.percentage || tickerData?.percent_change || 0;++ // If no percentage provided, calculate it from price change and current price+ if (priceChangePercent === 0 && tickerData?.last && tickerData?.open && tickerData.open > 0) {+ priceChangePercent = ((tickerData.last - tickerData.open) / tickerData.open) * 100;+ } else if (priceChangePercent === 0 && priceChange !== 0 && currentPrice > 0) {+ // Calculate from absolute change if we have it+ const previousPrice = currentPrice - priceChange;+ if (previousPrice > 0) {+ priceChangePercent = (priceChange / previousPrice) * 100;}- }, [paperAdapter]);+ }- const currentPrice = tickerData?.last || orderBook.asks[0]?.price || 0;+ // Calculate 24h price range (High - Low)+ const spread24h = (tickerData?.high && tickerData?.low) ? (tickerData.high - tickerData.low) : 0;+ const spread24hPercent = (spread24h > 0 && tickerData?.low && tickerData.low > 0)+ ? ((spread24h / tickerData.low) * 100)+ : 0;return (<div style={{- padding: '20px',- color: 'white',- backgroundColor: '#0d0d0d',height: '100%',- overflow: 'auto'+ backgroundColor: BLOOMBERG.DARK_BG,+ color: BLOOMBERG.WHITE,+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column'}}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px', gap: '16px' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flex: 1 }}>- <h1 style={{ fontSize: '24px', margin: 0 }}>- Trading- </h1>-- {/* Symbol Selector with Search */}- <div style={{ position: 'relative', minWidth: '200px' }} data-symbol-selector>- <div+ <style>{`+ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap');++ *::-webkit-scrollbar { width: 6px; height: 6px; }+ *::-webkit-scrollbar-track { background: ${BLOOMBERG.DARK_BG}; }+ *::-webkit-scrollbar-thumb { background: ${BLOOMBERG.BORDER}; border-radius: 3px; }+ *::-webkit-scrollbar-thumb:hover { background: ${BLOOMBERG.MUTED}; }++ .terminal-glow {+ text-shadow: 0 0 10px ${BLOOMBERG.ORANGE}40;+ }++ .price-flash {+ animation: flash 0.3s ease-out;+ }++ @keyframes flash {+ 0% { background-color: ${BLOOMBERG.YELLOW}40; }+ 100% { background-color: transparent; }+ }+ `}</style>++ {/* ========== TOP NAVIGATION BAR ========== */}+ <div style={{+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderBottom: `2px solid ${BLOOMBERG.ORANGE}`,+ padding: '6px 12px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexShrink: 0,+ boxShadow: `0 2px 8px ${BLOOMBERG.ORANGE}20`+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Activity size={18} color={BLOOMBERG.ORANGE} style={{ filter: 'drop-shadow(0 0 4px ' + BLOOMBERG.ORANGE + ')' }} />+ <span style={{+ color: BLOOMBERG.ORANGE,+ fontWeight: 700,+ fontSize: '14px',+ letterSpacing: '0.5px',+ textShadow: `0 0 10px ${BLOOMBERG.ORANGE}40`+ }}>+ FINCEPT TERMINAL+ </span>+ </div>++ <div style={{ height: '16px', width: '1px', backgroundColor: BLOOMBERG.BORDER }} />++ {/* Broker Selector */}+ <div style={{ position: 'relative' }}>+ <button+ onClick={() => setShowBrokerDropdown(!showBrokerDropdown)}style={{display: 'flex',alignItems: 'center',- gap: '8px',- padding: '8px 12px',- backgroundColor: '#1a1a1a',- border: '1px solid #333',- borderRadius: '6px',- cursor: 'pointer'+ gap: '6px',+ padding: '4px 10px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.CYAN,+ cursor: 'pointer',+ fontSize: '11px',+ fontWeight: 600,+ transition: 'all 0.2s'}}- onClick={() => setShowSymbolDropdown(!showSymbolDropdown)}+ onMouseEnter={(e) => e.currentTarget.style.borderColor = BLOOMBERG.CYAN}+ onMouseLeave={(e) => e.currentTarget.style.borderColor = BLOOMBERG.BORDER}>- <span style={{ fontSize: '14px', fontWeight: 'bold', flex: 1 }}>- {selectedSymbol}- </span>- <span style={{ fontSize: '12px', color: '#666' }}>▼</span>- </div>+ <Globe size={12} />+ {activeBroker?.toUpperCase() || 'SELECT BROKER'}+ <ChevronDown size={10} />+ </button>- {/* Dropdown */}- {showSymbolDropdown && (+ {showBrokerDropdown && (<div style={{position: 'absolute',top: '100%',left: 0,- right: 0,marginTop: '4px',- backgroundColor: '#1a1a1a',- border: '1px solid #333',- borderRadius: '6px',- maxHeight: '400px',- overflow: 'hidden',+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ minWidth: '200px',zIndex: 1000,- boxShadow: '0 4px 12px rgba(0,0,0,0.5)'+ boxShadow: `0 4px 16px ${BLOOMBERG.DARK_BG}80`}}>- {/* Search Input */}- <div style={{ padding: '12px', borderBottom: '1px solid #333' }}>- <input- type="text"- placeholder="Search pairs... (e.g., BTC, ETH)"- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- autoFocus+ {availableBrokers.map((broker) => (+ <div+ key={broker.id}+ onClick={() => handleBrokerChange(broker.id)}style={{- width: '100%',- padding: '8px 12px',- backgroundColor: '#0d0d0d',- color: 'white',- border: '1px solid #333',- borderRadius: '4px',- fontSize: '13px',- outline: 'none'+ padding: '10px 12px',+ cursor: 'pointer',+ fontSize: '11px',+ backgroundColor: activeBroker === broker.id ? `${BLOOMBERG.ORANGE}20` : 'transparent',+ borderLeft: activeBroker === broker.id ? `3px solid ${BLOOMBERG.ORANGE}` : '3px solid transparent',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ transition: 'all 0.2s'}}- />- </div>-- {/* Loading State */}- {isLoadingSymbols ? (- <div style={{ padding: '20px', textAlign: 'center', color: '#666', fontSize: '13px' }}>- Loading markets...- </div>- ) : (- /* Symbol List */- <div style={{ maxHeight: '300px', overflowY: 'auto' }}>- {availableSymbols- .filter(symbol =>- symbol.toLowerCase().includes(searchQuery.toLowerCase())- )- .map(symbol => (- <div- key={symbol}- onClick={() => {- setSelectedSymbol(symbol);- setShowSymbolDropdown(false);- setSearchQuery('');- }}- style={{- padding: '10px 16px',- cursor: 'pointer',- fontSize: '13px',- backgroundColor: symbol === selectedSymbol ? '#f59e0b20' : 'transparent',- color: symbol === selectedSymbol ? '#f59e0b' : 'white',- borderBottom: '1px solid #222',- transition: 'background-color 0.15s'- }}- onMouseEnter={(e) => {- if (symbol !== selectedSymbol) {- e.currentTarget.style.backgroundColor = '#ffffff10';- }- }}- onMouseLeave={(e) => {- if (symbol !== selectedSymbol) {- e.currentTarget.style.backgroundColor = 'transparent';- }- }}- >- {symbol}- </div>- ))- }- {/* No Results */}- {availableSymbols.filter(s => s.toLowerCase().includes(searchQuery.toLowerCase())).length === 0 && (- <div style={{ padding: '20px', textAlign: 'center', color: '#666', fontSize: '13px' }}>- No pairs found matching "{searchQuery}"- </div>+ onMouseEnter={(e) => {+ if (activeBroker !== broker.id) {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ }+ }}+ onMouseLeave={(e) => {+ if (activeBroker !== broker.id) {+ e.currentTarget.style.backgroundColor = 'transparent';+ }+ }}+ >+ <div>+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600 }}>{broker.name}</div>+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px' }}>{broker.type.toUpperCase()}</div>+ </div>+ {activeBroker === broker.id && (+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: BLOOMBERG.GREEN,+ boxShadow: `0 0 6px ${BLOOMBERG.GREEN}`+ }} />)}</div>- )}+ ))}</div>)}</div>- {/* Mode Badge */}- <span style={{- padding: '4px 12px',- backgroundColor: tradingMode === 'paper' ? '#10b98120' : '#dc262620',- color: tradingMode === 'paper' ? '#10b981' : '#dc2626',- border: `1px solid ${tradingMode === 'paper' ? '#10b981' : '#dc2626'}`,- borderRadius: '4px',- fontSize: '12px',- fontWeight: 'bold'- }}>- {tradingMode === 'paper' ? '📝 PAPER' : '🔴 LIVE'}- </span>- </div>-- <button- onClick={() => setShowSettings(!showSettings)}- style={{- padding: '8px 16px',- backgroundColor: '#1a1a1a',- color: 'white',- border: '1px solid #333',- borderRadius: '6px',- cursor: 'pointer',- fontSize: '13px'- }}- >- ⚙️ Settings- </button>- </div>-- {/* Settings Panel */}- {showSettings && (- <div style={{- marginBottom: '20px',- padding: '16px',- backgroundColor: '#1a1a1a',- borderRadius: '6px',- border: '1px solid #333'- }}>- <h3 style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '16px' }}>Trading Settings</h3>-- {/* Slippage Control */}- <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px' }}>- <label style={{ fontSize: '13px', color: '#999', minWidth: '100px' }}>- Slippage (%):- </label>- <input- type="number"- value={slippage * 100}- onChange={(e) => setSlippage(parseFloat(e.target.value) / 100)}- step="0.01"- min="0"- max="5"- style={{- padding: '6px 12px',- backgroundColor: '#0d0d0d',- color: 'white',- border: '1px solid #333',- borderRadius: '4px',- width: '100px',- fontSize: '13px'- }}- />- <span style={{ fontSize: '12px', color: '#666' }}>- (0% = exact price, 0.1% = realistic)- </span>- </div>-- {/* Maker Fee Control */}- <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px' }}>- <label style={{ fontSize: '13px', color: '#999', minWidth: '100px' }}>- Maker Fee (%):- </label>- <input- type="number"- value={makerFee * 100}- onChange={(e) => setMakerFee(parseFloat(e.target.value) / 100)}- step="0.001"- min="0"- max="1"- style={{- padding: '6px 12px',- backgroundColor: '#0d0d0d',- color: 'white',- border: '1px solid #333',- borderRadius: '4px',- width: '100px',- fontSize: '13px'- }}- />- <span style={{ fontSize: '12px', color: '#666' }}>- (0.02% Kraken default)- </span>- </div>+ <div style={{ height: '16px', width: '1px', backgroundColor: BLOOMBERG.BORDER }} />- {/* Taker Fee Control */}- <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '16px' }}>- <label style={{ fontSize: '13px', color: '#999', minWidth: '100px' }}>- Taker Fee (%):- </label>- <input- type="number"- value={takerFee * 100}- onChange={(e) => setTakerFee(parseFloat(e.target.value) / 100)}- step="0.001"- min="0"- max="1"+ {/* Trading Mode Toggle */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <button+ onClick={() => setTradingMode('paper')}style={{- padding: '6px 12px',- backgroundColor: '#0d0d0d',- color: 'white',- border: '1px solid #333',- borderRadius: '4px',- width: '100px',- fontSize: '13px'+ padding: '4px 10px',+ backgroundColor: tradingMode === 'paper' ? BLOOMBERG.GREEN : BLOOMBERG.PANEL_BG,+ border: `1px solid ${tradingMode === 'paper' ? BLOOMBERG.GREEN : BLOOMBERG.BORDER}`,+ color: tradingMode === 'paper' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ cursor: 'pointer',+ fontSize: '10px',+ fontWeight: 700,+ transition: 'all 0.2s'}}- />- <span style={{ fontSize: '12px', color: '#666' }}>- (0.05% Kraken default)- </span>- </div>-- {/* Reset Balance Button */}- <div style={{- borderTop: '1px solid #333',- paddingTop: '16px',- marginTop: '4px'- }}>+ >+ PAPER+ </button><button- onClick={handleResetBalance}+ onClick={() => setTradingMode('live')}style={{- padding: '8px 16px',- backgroundColor: '#dc262620',- color: '#dc2626',- border: '1px solid #dc2626',- borderRadius: '6px',+ padding: '4px 10px',+ backgroundColor: tradingMode === 'live' ? BLOOMBERG.RED : BLOOMBERG.PANEL_BG,+ border: `1px solid ${tradingMode === 'live' ? BLOOMBERG.RED : BLOOMBERG.BORDER}`,+ color: tradingMode === 'live' ? BLOOMBERG.WHITE : BLOOMBERG.GRAY,cursor: 'pointer',- fontSize: '13px',- fontWeight: 'bold',- width: '100%',+ fontSize: '10px',+ fontWeight: 700,transition: 'all 0.2s'}}- onMouseOver={(e) => {- e.currentTarget.style.backgroundColor = '#dc2626';- e.currentTarget.style.color = 'white';- }}- onMouseOut={(e) => {- e.currentTarget.style.backgroundColor = '#dc262620';- e.currentTarget.style.color = '#dc2626';- }}>- 🔄 Reset Paper Trading Account+ LIVE</button>- <div style={{ fontSize: '11px', color: '#666', marginTop: '8px', textAlign: 'center' }}>- Resets balance, closes all positions, and clears history- </div></div></div>- )}- {/* Status Bar */}- <div style={{ marginBottom: '20px', padding: '12px', backgroundColor: '#1a1a1a', borderRadius: '6px' }}>- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '16px', fontSize: '13px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '10px' }}>+ {activeAdapter?.isConnected() ? (+ <>+ <Wifi size={12} color={BLOOMBERG.GREEN} />+ <span style={{ color: BLOOMBERG.GREEN }}>CONNECTED</span>+ </>+ ) : (+ <>+ <WifiOff size={12} color={BLOOMBERG.RED} />+ <span style={{ color: BLOOMBERG.RED }}>DISCONNECTED</span>+ </>+ )}+ </div>++ <div style={{ height: '16px', width: '1px', backgroundColor: BLOOMBERG.BORDER }} />++ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '10px', color: BLOOMBERG.CYAN }}>+ <Clock size={12} />+ {currentTime.toLocaleTimeString('en-US', { hour12: false })}+ </div>++ <button+ onClick={() => setShowSettings(!showSettings)}+ style={{+ padding: '4px 8px',+ backgroundColor: 'transparent',+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.GRAY,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ fontSize: '10px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = BLOOMBERG.ORANGE;+ e.currentTarget.style.color = BLOOMBERG.ORANGE;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ e.currentTarget.style.color = BLOOMBERG.GRAY;+ }}+ >+ <SettingsIcon size={12} />+ </button>+ </div>+ </div>++ {/* ========== TICKER BAR ========== */}+ <div style={{+ backgroundColor: BLOOMBERG.PANEL_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ padding: '10px 12px',+ display: 'flex',+ alignItems: 'center',+ gap: '20px',+ flexShrink: 0+ }}>+ {/* Symbol Selector */}+ <div style={{ position: 'relative', minWidth: '180px' }} data-symbol-selector>+ <div+ onClick={() => setShowSymbolDropdown(!showSymbolDropdown)}+ style={{+ padding: '6px 12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ cursor: 'pointer',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center'+ }}+ >+ <span style={{ fontSize: '13px', fontWeight: 700, color: BLOOMBERG.ORANGE }}>{selectedSymbol}</span>+ <ChevronDown size={12} color={BLOOMBERG.GRAY} />+ </div>++ {showSymbolDropdown && (+ <div style={{+ position: 'absolute',+ top: '100%',+ left: 0,+ right: 0,+ marginTop: '4px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ maxHeight: '400px',+ overflow: 'hidden',+ zIndex: 1000,+ boxShadow: `0 4px 16px ${BLOOMBERG.DARK_BG}80`+ }}>+ <div style={{ padding: '8px', borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>+ <input+ type="text"+ placeholder="Search symbols..."+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ autoFocus+ style={{+ width: '100%',+ padding: '6px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '11px',+ outline: 'none'+ }}+ />+ </div>+ <div style={{ maxHeight: '340px', overflowY: 'auto' }}>+ {availableSymbols+ .filter(symbol => symbol.toLowerCase().includes(searchQuery.toLowerCase()))+ .map(symbol => (+ <div+ key={symbol}+ onClick={() => {+ setSelectedSymbol(symbol);+ setShowSymbolDropdown(false);+ setSearchQuery('');+ }}+ style={{+ padding: '8px 12px',+ cursor: 'pointer',+ fontSize: '11px',+ backgroundColor: symbol === selectedSymbol ? `${BLOOMBERG.ORANGE}20` : 'transparent',+ color: symbol === selectedSymbol ? BLOOMBERG.ORANGE : BLOOMBERG.WHITE,+ borderLeft: symbol === selectedSymbol ? `3px solid ${BLOOMBERG.ORANGE}` : 'none'+ }}+ onMouseEnter={(e) => {+ if (symbol !== selectedSymbol) {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ }+ }}+ onMouseLeave={(e) => {+ if (symbol !== selectedSymbol) {+ e.currentTarget.style.backgroundColor = 'transparent';+ }+ }}+ >+ {symbol}+ </div>+ ))}+ </div>+ </div>+ )}+ </div>++ {/* Price Display */}+ <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px' }}>+ <span style={{ fontSize: '24px', fontWeight: 700, color: BLOOMBERG.YELLOW }}>+ {tickerData ? `$${tickerData.last?.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '0.00'}` : '--'}+ </span>+ {tickerData && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ {priceChange >= 0 ? (+ <ArrowUp size={16} color={BLOOMBERG.GREEN} />+ ) : (+ <ArrowDown size={16} color={BLOOMBERG.RED} />+ )}+ <span style={{+ fontSize: '13px',+ fontWeight: 600,+ color: priceChange >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED+ }}>+ {priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)} ({priceChangePercent >= 0 ? '+' : ''}{priceChangePercent.toFixed(2)}%)+ </span>+ </div>+ )}+ </div>++ <div style={{ height: '24px', width: '1px', backgroundColor: BLOOMBERG.BORDER }} />++ {/* Market Stats */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '24px', fontSize: '11px' }}><div>- <div style={{ color: '#666', marginBottom: '4px' }}>Symbol</div>- <div style={{ fontWeight: 'bold', fontSize: '16px' }}>{selectedSymbol}</div>+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>BID</div>+ <div style={{ color: BLOOMBERG.GREEN, fontWeight: 600 }}>+ {tickerData ? `$${tickerData.bid?.toFixed(2) || '0.00'}` : '--'}+ </div></div><div>- <div style={{ color: '#666', marginBottom: '4px' }}>Last Price</div>- <div style={{ fontWeight: 'bold', fontSize: '16px', color: tickerData ? '#10b981' : '#666' }}>- {tickerData ? `$${tickerData.last?.toFixed(2) || '0.00'}` : 'Loading...'}+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>ASK</div>+ <div style={{ color: BLOOMBERG.RED, fontWeight: 600 }}>+ {tickerData ? `$${tickerData.ask?.toFixed(2) || '0.00'}` : '--'}</div></div><div>- <div style={{ color: '#666', marginBottom: '4px' }}>Bid / Ask</div>- <div style={{ fontWeight: 'bold', fontSize: '13px' }}>- {tickerData ? (+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H RANGE</div>+ <div style={{ color: BLOOMBERG.CYAN, fontWeight: 600 }}>+ {spread24h > 0 ? (<>- <span style={{ color: '#10b981' }}>${tickerData.bid?.toFixed(2) || '0.00'}</span>- {' / '}- <span style={{ color: '#dc2626' }}>${tickerData.ask?.toFixed(2) || '0.00'}</span>+ ${spread24h.toFixed(2)} ({spread24hPercent.toFixed(2)}%)</>) : (- <span style={{ color: '#666' }}>--</span>+ '--')}</div></div>- {tradingMode === 'paper' && (+ {tickerData && (<><div>- <div style={{ color: '#666', marginBottom: '4px' }}>Balance</div>- <div style={{ fontWeight: 'bold' }}>${balance.toFixed(2)}</div>+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H HIGH</div>+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600 }}>${tickerData.high?.toFixed(2) || '--'}</div></div><div>- <div style={{ color: '#666', marginBottom: '4px' }}>Equity</div>- <div style={{ fontWeight: 'bold' }}>${equity.toFixed(2)}</div>+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H LOW</div>+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600 }}>${tickerData.low?.toFixed(2) || '--'}</div>+ </div>+ <div>+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H VOLUME</div>+ <div style={{ color: BLOOMBERG.PURPLE, fontWeight: 600 }}>+ {tickerData.volume ? (+ <>+ {/* Show volume in USD if available */}+ {tickerData.quoteVolume ? (+ `$${tickerData.quoteVolume.toLocaleString(undefined, { maximumFractionDigits: 0 })}`+ ) : tickerData.volumeUsd ? (+ `$${tickerData.volumeUsd.toLocaleString(undefined, { maximumFractionDigits: 0 })}`+ ) : (+ // Calculate USD value from volume * current price+ currentPrice > 0 ? (+ <>+ ${(tickerData.volume * currentPrice).toLocaleString(undefined, { maximumFractionDigits: 0 })}+ <span style={{ fontSize: '8px', color: BLOOMBERG.GRAY, marginLeft: '4px' }}>+ ({tickerData.volume.toLocaleString(undefined, { maximumFractionDigits: 2 })} {selectedSymbol.split('/')[0]})+ </span>+ </>+ ) : (+ <>+ {tickerData.volume.toLocaleString(undefined, { maximumFractionDigits: 2 })}+ <span style={{ fontSize: '8px', color: BLOOMBERG.GRAY, marginLeft: '2px' }}>+ {selectedSymbol.split('/')[0]}+ </span>+ </>+ )+ )}+ </>+ ) : '--'}+ </div></div></>)}- <div>- <div style={{ color: '#666', marginBottom: '4px' }}>Status</div>- <div style={{ fontWeight: 'bold', color: activeAdapter?.isConnected() ? '#10b981' : '#dc2626' }}>- {isConnecting ? 'Connecting...' : activeAdapter?.isConnected() ? 'Connected' : 'Disconnected'}+ </div>++ {tradingMode === 'paper' && (+ <>+ <div style={{ height: '24px', width: '1px', backgroundColor: BLOOMBERG.BORDER }} />+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '11px' }}>+ <div>+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>BALANCE</div>+ <div style={{ color: BLOOMBERG.CYAN, fontWeight: 600 }}>${balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>+ </div>+ <div>+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>EQUITY</div>+ <div style={{ color: BLOOMBERG.YELLOW, fontWeight: 600 }}>${equity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>+ </div></div>+ </>+ )}+ </div>++ {/* ========== MAIN CONTENT ========== */}+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>+ {/* LEFT SIDEBAR - Watchlist */}+ <div style={{+ width: '220px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ borderRight: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden'+ }}>+ <div style={{+ padding: '8px 12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '10px',+ fontWeight: 700,+ color: BLOOMBERG.ORANGE,+ letterSpacing: '0.5px'+ }}>+ WATCHLIST+ </div>+ <div style={{ flex: 1, overflow: 'auto' }}>+ {watchlist.map((symbol, idx) => (+ <div+ key={symbol}+ onClick={() => setSelectedSymbol(symbol)}+ style={{+ padding: '10px 12px',+ cursor: 'pointer',+ backgroundColor: selectedSymbol === symbol ? `${BLOOMBERG.ORANGE}15` : 'transparent',+ borderLeft: selectedSymbol === symbol ? `3px solid ${BLOOMBERG.ORANGE}` : '3px solid transparent',+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ if (selectedSymbol !== symbol) {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ }+ }}+ onMouseLeave={(e) => {+ if (selectedSymbol !== symbol) {+ e.currentTarget.style.backgroundColor = 'transparent';+ }+ }}+ >+ <div style={{ fontSize: '11px', fontWeight: 600, color: selectedSymbol === symbol ? BLOOMBERG.ORANGE : BLOOMBERG.WHITE, marginBottom: '4px' }}>+ {symbol}+ </div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GREEN }}>+2.45%</div>+ </div>+ ))}</div></div>- </div>- {/* Main Grid */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 350px', gap: '20px', marginBottom: '20px' }}>- {/* Left Column: Positions */}- <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>- {/* Trading Activity Tabs (Paper Trading) */}- {tradingMode === 'paper' && (- <div style={{ padding: '16px', backgroundColor: '#1a1a1a', borderRadius: '6px' }}>- {/* Tab Headers */}- <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', borderBottom: '1px solid #333' }}>- {(['positions', 'orders', 'trades', 'stats'] as const).map((tab) => (+ {/* CENTER - Chart & Order Book */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ {/* Chart Area */}+ <div style={{+ height: '55%',+ backgroundColor: BLOOMBERG.PANEL_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden'+ }}>+ <div style={{+ padding: '8px 12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}>+ {['CHART', 'DEPTH', 'TRADES'].map((view) => (+ <button+ key={view}+ onClick={() => setSelectedView(view.toLowerCase() as any)}+ style={{+ padding: '4px 12px',+ backgroundColor: selectedView === view.toLowerCase() ? BLOOMBERG.ORANGE : 'transparent',+ border: 'none',+ color: selectedView === view.toLowerCase() ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ cursor: 'pointer',+ fontSize: '10px',+ fontWeight: 700,+ transition: 'all 0.2s'+ }}+ >+ {view}+ </button>+ ))}+ </div>+ <div style={{+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: BLOOMBERG.GRAY,+ fontSize: '12px',+ overflow: 'hidden'+ }}>+ {selectedView === 'chart' && (+ <div style={{ width: '100%', height: '100%' }}>+ <TradingChart symbol={selectedSymbol} height={isBottomPanelMinimized ? 650 : 450} showVolume={true} />+ </div>+ )}+ {selectedView === 'depth' && (+ <div style={{ width: '100%', height: '100%', padding: '8px' }}>+ <DepthChart symbol={selectedSymbol} height={420} />+ </div>+ )}+ {selectedView === 'trades' && (+ <div style={{ width: '100%', height: '100%', overflow: 'auto', padding: '8px' }}>+ <table style={{ width: '100%', fontSize: '10px', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>+ <th style={{ padding: '6px', textAlign: 'left', color: BLOOMBERG.GRAY }}>TIME</th>+ <th style={{ padding: '6px', textAlign: 'right', color: BLOOMBERG.GRAY }}>PRICE</th>+ <th style={{ padding: '6px', textAlign: 'right', color: BLOOMBERG.GRAY }}>SIZE</th>+ </tr>+ </thead>+ <tbody>+ {tradesData.slice(0, 20).map((trade, idx) => (+ <tr key={idx} style={{ borderBottom: `1px solid ${BLOOMBERG.BORDER}40` }}>+ <td style={{ padding: '4px 6px', color: BLOOMBERG.GRAY, fontSize: '9px' }}>+ {new Date(trade.timestamp).toLocaleTimeString()}+ </td>+ <td style={{+ padding: '4px 6px',+ textAlign: 'right',+ color: trade.side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.RED+ }}>+ ${trade.price?.toFixed(2)}+ </td>+ <td style={{ padding: '4px 6px', textAlign: 'right', color: BLOOMBERG.WHITE }}>+ {trade.amount?.toFixed(4)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </div>+ </div>++ {/* Bottom Panel - Positions/Orders/Trades */}+ <div style={{+ flex: isBottomPanelMinimized ? '0 0 40px' : 1,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ transition: 'flex 0.3s ease'+ }}>+ <div style={{+ padding: '6px 12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center'+ }}>+ <div style={{ display: 'flex', gap: '4px' }}>+ {(['positions', 'orders', 'history', 'trades', 'stats', 'features', 'cross-exchange'] as const).map((tab) => (<buttonkey={tab}- onClick={() => setActiveTab(tab)}+ onClick={() => setActiveBottomTab(tab)}style={{- padding: '10px 16px',- backgroundColor: activeTab === tab ? '#f59e0b20' : 'transparent',- color: activeTab === tab ? '#f59e0b' : '#999',+ padding: '6px 16px',+ backgroundColor: activeBottomTab === tab ? BLOOMBERG.ORANGE : 'transparent',border: 'none',- borderBottom: activeTab === tab ? '2px solid #f59e0b' : '2px solid transparent',+ color: activeBottomTab === tab ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,cursor: 'pointer',- fontSize: '13px',- fontWeight: activeTab === tab ? 'bold' : 'normal',- textTransform: 'capitalize',+ fontSize: '10px',+ fontWeight: 700,+ textTransform: 'uppercase',transition: 'all 0.2s'}}>- {tab}- {tab === 'positions' && ` (${positions.length})`}- {tab === 'orders' && ` (${orders.length})`}- {tab === 'trades' && ` (${trades.length})`}+ {tab} {tab === 'positions' && `(${positions.length})`} {tab === 'orders' && `(${orders.length})`}</button>))}</div>- {/* Positions Tab */}- {activeTab === 'positions' && (- <div>- {positions.length === 0 ? (- <div style={{ padding: '40px', textAlign: 'center', color: '#666', fontSize: '13px' }}>- No open positions- </div>- ) : (- <table style={{ width: '100%', fontSize: '12px', fontFamily: 'monospace', borderCollapse: 'collapse' }}>- <thead>- <tr style={{ borderBottom: '1px solid #333' }}>- <th style={{ textAlign: 'left', padding: '8px', color: '#666' }}>Symbol</th>- <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Side</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Qty</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Value</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Entry</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Current</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>PnL ($)</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>PnL (%)</th>- </tr>- </thead>- <tbody>- {positions.map((pos, idx) => {- // Calculate price difference- const priceDiff = pos.entryPrice - pos.currentPrice;-- // For SHORT: profit when price goes DOWN (priceDiff > 0)- // For LONG: profit when price goes UP (priceDiff < 0)- const totalPnlDollar = pos.side === 'short'- ? priceDiff * pos.quantity- : -priceDiff * pos.quantity;-- // Calculate P&L percentage based on position value- const pnlPercent = pos.positionValue > 0 ? (totalPnlDollar / pos.positionValue) * 100 : 0;-- return (- <tr key={idx} style={{ borderBottom: '1px solid #222' }}>- <td style={{ padding: '8px' }}>{pos.symbol}</td>- <td style={{ padding: '8px', textAlign: 'center' }}>- <span style={{- padding: '4px 8px',- borderRadius: '4px',- backgroundColor: pos.side === 'long' ? '#10b98120' : '#dc262620',- color: pos.side === 'long' ? '#10b981' : '#dc2626',- fontSize: '11px',- fontWeight: 'bold'- }}>- {pos.side.toUpperCase()}- </span>- </td>- <td style={{ padding: '8px', textAlign: 'right' }}>{pos.quantity.toFixed(4)}</td>- <td style={{ padding: '8px', textAlign: 'right', color: '#999' }}>- ${pos.positionValue.toFixed(2)}- </td>- <td style={{ padding: '8px', textAlign: 'right' }}>${pos.entryPrice.toFixed(2)}</td>- <td style={{ padding: '8px', textAlign: 'right', fontWeight: 'bold' }}>- ${pos.currentPrice.toFixed(2)}- </td>- <td style={{- padding: '8px',- textAlign: 'right',- color: totalPnlDollar >= 0 ? '#10b981' : '#dc2626',- fontWeight: 'bold'- }}>- {totalPnlDollar >= 0 ? '+' : '-'}${Math.abs(totalPnlDollar).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}- </td>- <td style={{- padding: '8px',- textAlign: 'right',- color: pnlPercent >= 0 ? '#10b981' : '#dc2626',- fontWeight: 'bold'- }}>- {pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(2)}%- </td>- </tr>- );- })}- </tbody>- </table>- )}- </div>- )}+ {/* Minimize/Maximize Button */}+ <button+ onClick={() => setIsBottomPanelMinimized(!isBottomPanelMinimized)}+ style={{+ padding: '4px 8px',+ backgroundColor: 'transparent',+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.GRAY,+ cursor: 'pointer',+ fontSize: '10px',+ fontWeight: 600,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ borderRadius: '2px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ e.currentTarget.style.borderColor = BLOOMBERG.GRAY;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ }}+ title={isBottomPanelMinimized ? 'Maximize Panel' : 'Minimize Panel'}+ >+ {isBottomPanelMinimized ? (+ <>+ <ChevronUp size={14} />+ <span>MAXIMIZE</span>+ </>+ ) : (+ <>+ <ChevronDown size={14} />+ <span>MINIMIZE</span>+ </>+ )}+ </button>+ </div>++ {!isBottomPanelMinimized && (+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>+ {/* Positions Tab */}+ {activeBottomTab === 'positions' && <PositionsTable />}{/* Orders Tab */}- {activeTab === 'orders' && (- <div>- {orders.length === 0 ? (- <div style={{ padding: '40px', textAlign: 'center', color: '#666', fontSize: '13px' }}>- No open orders- </div>- ) : (- <table style={{ width: '100%', fontSize: '12px', fontFamily: 'monospace', borderCollapse: 'collapse' }}>- <thead>- <tr style={{ borderBottom: '1px solid #333' }}>- <th style={{ textAlign: 'left', padding: '8px', color: '#666' }}>Symbol</th>- <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Type</th>- <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Side</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Qty</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Price</th>- <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Status</th>- <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Action</th>- </tr>- </thead>- <tbody>- {orders.map((order) => (- <tr key={order.id} style={{ borderBottom: '1px solid #222' }}>- <td style={{ padding: '8px' }}>{order.symbol}</td>- <td style={{ padding: '8px', textAlign: 'center', textTransform: 'uppercase', fontSize: '11px' }}>- {order.type}- </td>- <td style={{ padding: '8px', textAlign: 'center' }}>- <span style={{- padding: '4px 8px',- borderRadius: '4px',- backgroundColor: order.side === 'buy' ? '#10b98120' : '#dc262620',- color: order.side === 'buy' ? '#10b981' : '#dc2626',- fontSize: '11px',- fontWeight: 'bold'- }}>- {order.side.toUpperCase()}- </span>- </td>- <td style={{ padding: '8px', textAlign: 'right' }}>{order.quantity.toFixed(4)}</td>- <td style={{ padding: '8px', textAlign: 'right' }}>- {order.price ? `$${order.price.toFixed(2)}` : 'Market'}- </td>- <td style={{ padding: '8px', textAlign: 'center', textTransform: 'uppercase', fontSize: '11px', color: '#f59e0b' }}>- {order.status}- </td>- <td style={{ padding: '8px', textAlign: 'center' }}>- <button- onClick={() => handleCancelOrder(order.id, order.symbol)}- style={{- padding: '4px 12px',- backgroundColor: '#dc262620',- color: '#dc2626',- border: '1px solid #dc2626',- borderRadius: '4px',- cursor: 'pointer',- fontSize: '11px',- fontWeight: 'bold',- transition: 'all 0.2s'- }}- onMouseOver={(e) => {- e.currentTarget.style.backgroundColor = '#dc2626';- e.currentTarget.style.color = 'white';- }}- onMouseOut={(e) => {- e.currentTarget.style.backgroundColor = '#dc262620';- e.currentTarget.style.color = '#dc2626';- }}- >- Cancel- </button>- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- )}+ {activeBottomTab === 'orders' && <OrdersTable />}++ {/* History Tab (Closed Orders) */}+ {activeBottomTab === 'history' && <ClosedOrders />}{/* Trades Tab */}- {activeTab === 'trades' && (- <div>- {trades.length === 0 ? (- <div style={{ padding: '40px', textAlign: 'center', color: '#666', fontSize: '13px' }}>- No trade history- </div>- ) : (- <div style={{ maxHeight: '400px', overflowY: 'auto' }}>- <table style={{ width: '100%', fontSize: '12px', fontFamily: 'monospace', borderCollapse: 'collapse' }}>- <thead style={{ position: 'sticky', top: 0, backgroundColor: '#1a1a1a' }}>- <tr style={{ borderBottom: '1px solid #333' }}>- <th style={{ textAlign: 'left', padding: '8px', color: '#666' }}>Time</th>- <th style={{ textAlign: 'left', padding: '8px', color: '#666' }}>Symbol</th>- <th style={{ textAlign: 'center', padding: '8px', color: '#666' }}>Side</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Qty</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Price</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Value</th>- <th style={{ textAlign: 'right', padding: '8px', color: '#666' }}>Fee</th>- </tr>- </thead>- <tbody>- {trades.map((trade, idx) => (- <tr key={idx} style={{ borderBottom: '1px solid #222' }}>- <td style={{ padding: '8px', fontSize: '11px', color: '#999' }}>- {new Date(trade.timestamp).toLocaleTimeString()}- </td>- <td style={{ padding: '8px' }}>{trade.symbol}</td>- <td style={{ padding: '8px', textAlign: 'center' }}>- <span style={{- padding: '4px 8px',- borderRadius: '4px',- backgroundColor: trade.side === 'buy' ? '#10b98120' : '#dc262620',- color: trade.side === 'buy' ? '#10b981' : '#dc2626',- fontSize: '11px',- fontWeight: 'bold'- }}>- {trade.side.toUpperCase()}- </span>- </td>- <td style={{ padding: '8px', textAlign: 'right' }}>{trade.amount?.toFixed(4) || '0.0000'}</td>- <td style={{ padding: '8px', textAlign: 'right' }}>${trade.price?.toFixed(2) || '0.00'}</td>- <td style={{ padding: '8px', textAlign: 'right' }}>${trade.cost?.toFixed(2) || '0.00'}</td>- <td style={{ padding: '8px', textAlign: 'right', color: '#dc2626' }}>- ${trade.fee?.cost?.toFixed(2) || '0.00'}- </td>- </tr>- ))}- </tbody>- </table>- </div>- )}- </div>+ {activeBottomTab === 'trades' && (+ trades.length === 0 ? (+ <div style={{ padding: '40px', textAlign: 'center', color: BLOOMBERG.GRAY, fontSize: '11px' }}>+ No trade history+ </div>+ ) : (+ <table style={{ width: '100%', fontSize: '10px', borderCollapse: 'collapse' }}>+ <thead>+ <tr style={{ borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>+ <th style={{ padding: '8px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 600 }}>TIME</th>+ <th style={{ padding: '8px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 600 }}>SYMBOL</th>+ <th style={{ padding: '8px', textAlign: 'center', color: BLOOMBERG.GRAY, fontWeight: 600 }}>SIDE</th>+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 600 }}>QTY</th>+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 600 }}>PRICE</th>+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 600 }}>VALUE</th>+ <th style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 600 }}>FEE</th>+ </tr>+ </thead>+ <tbody>+ {trades.map((trade, idx) => (+ <tr key={idx} style={{ borderBottom: `1px solid ${BLOOMBERG.BORDER}40` }}>+ <td style={{ padding: '8px', color: BLOOMBERG.GRAY, fontSize: '9px' }}>+ {new Date(trade.timestamp).toLocaleTimeString()}+ </td>+ <td style={{ padding: '8px', color: BLOOMBERG.WHITE }}>{trade.symbol}</td>+ <td style={{ padding: '8px', textAlign: 'center' }}>+ <span style={{+ padding: '2px 8px',+ backgroundColor: trade.side === 'buy' ? `${BLOOMBERG.GREEN}20` : `${BLOOMBERG.RED}20`,+ color: trade.side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.RED,+ fontSize: '9px',+ fontWeight: 700+ }}>+ {trade.side.toUpperCase()}+ </span>+ </td>+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG.WHITE }}>+ {trade.amount?.toFixed(4) || '0.0000'}+ </td>+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG.YELLOW }}>+ ${trade.price?.toFixed(2) || '0.00'}+ </td>+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG.CYAN }}>+ ${trade.cost?.toFixed(2) || '0.00'}+ </td>+ <td style={{ padding: '8px', textAlign: 'right', color: BLOOMBERG.RED }}>+ ${trade.fee?.cost?.toFixed(2) || '0.00'}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ ))}{/* Stats Tab */}- {activeTab === 'stats' && (- <div>- {!stats ? (- <div style={{ padding: '40px', textAlign: 'center', color: '#666', fontSize: '13px' }}>- Loading statistics...- </div>- ) : (- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px' }}>- {/* Initial Balance */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Initial Balance</div>- <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>- ${stats.initialBalance?.toFixed(2) || '0.00'}- </div>- </div>-- {/* Current Balance */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Current Balance</div>- <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>- ${stats.currentBalance?.toFixed(2) || '0.00'}- </div>- </div>-- {/* Total Value */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Total Value</div>- <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>- ${stats.totalValue?.toFixed(2) || '0.00'}- </div>- </div>-- {/* Total PnL */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Total PnL</div>- <div style={{- fontSize: '20px',- fontWeight: 'bold',- fontFamily: 'monospace',- color: stats.totalPnL >= 0 ? '#10b981' : '#dc2626'- }}>- {stats.totalPnL >= 0 ? '+' : ''}${stats.totalPnL?.toFixed(2) || '0.00'}- </div>- </div>+ {activeBottomTab === 'stats' && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: '12px' }}>+ {/* Left: Account Statistics */}+ <div>+ <AccountStats />+ </div>- {/* Realized PnL */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Realized PnL</div>- <div style={{- fontSize: '20px',- fontWeight: 'bold',- fontFamily: 'monospace',- color: stats.realizedPnL >= 0 ? '#10b981' : '#dc2626'- }}>- {stats.realizedPnL >= 0 ? '+' : ''}${stats.realizedPnL?.toFixed(2) || '0.00'}- </div>- </div>+ {/* Right: Fees & Margin */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ <FeesDisplay />+ <MarginPanel />+ </div>+ </div>+ )}- {/* Unrealized PnL */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Unrealized PnL</div>- <div style={{- fontSize: '20px',- fontWeight: 'bold',- fontFamily: 'monospace',- color: stats.unrealizedPnL >= 0 ? '#10b981' : '#dc2626'- }}>- {stats.unrealizedPnL >= 0 ? '+' : ''}${stats.unrealizedPnL?.toFixed(2) || '0.00'}- </div>- </div>+ {/* Features Tab - Exchange-Specific Features */}+ {activeBottomTab === 'features' && (+ <div style={{ padding: '16px', overflow: 'auto' }}>+ {/* Kraken-Specific Features */}+ {activeBroker === 'kraken' && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>+ <StakingPanel />+ <FuturesPanel />+ </div>+ )}- {/* Return % */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Return</div>- <div style={{- fontSize: '20px',- fontWeight: 'bold',- fontFamily: 'monospace',- color: parseFloat(stats.returnPercent || '0') >= 0 ? '#10b981' : '#dc2626'- }}>- {parseFloat(stats.returnPercent || '0') >= 0 ? '+' : ''}{stats.returnPercent || '0.00'}%- </div>+ {/* HyperLiquid - Already shown in order form area */}+ {activeBroker === 'hyperliquid' && (+ <div style={{+ padding: '40px',+ textAlign: 'center',+ color: BLOOMBERG.GRAY,+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '4px'+ }}>+ <div style={{ fontSize: '14px', fontWeight: 600, marginBottom: '8px' }}>+ HyperLiquid Features</div>-- {/* Total Trades */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Total Trades</div>- <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>- {stats.totalTrades || 0}- </div>+ <div style={{ fontSize: '11px' }}>+ HyperLiquid-specific features (Vault Manager, Leverage Control) are available in the order form panel on the right.</div>+ </div>+ )}- {/* Open Positions */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Open Positions</div>- <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace', color: '#f59e0b' }}>- {stats.openPositions || 0}- </div>+ {/* No exchange-specific features */}+ {activeBroker !== 'kraken' && activeBroker !== 'hyperliquid' && (+ <div style={{+ padding: '40px',+ textAlign: 'center',+ color: BLOOMBERG.GRAY,+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ borderRadius: '4px'+ }}>+ <div style={{ fontSize: '14px', fontWeight: 600, marginBottom: '8px' }}>+ No Exchange-Specific Features</div>-- {/* Closed Positions */}- <div style={{ padding: '16px', backgroundColor: '#0d0d0d', borderRadius: '6px' }}>- <div style={{ fontSize: '11px', color: '#666', marginBottom: '4px' }}>Closed Positions</div>- <div style={{ fontSize: '20px', fontWeight: 'bold', fontFamily: 'monospace' }}>- {stats.closedPositions || 0}- </div>+ <div style={{ fontSize: '11px' }}>+ The selected exchange does not have additional features available in this panel.</div></div>)}</div>)}- </div>- )}++ {/* Cross-Exchange Tab - Multi-Exchange Portfolio & Arbitrage */}+ {activeBottomTab === 'cross-exchange' && (+ <div style={{ padding: '16px', overflow: 'auto' }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>+ <PortfolioAggregator />+ <ArbitrageDetector />+ </div>+ </div>+ )}+ </div>+ )}+ </div></div>- {/* Right Column: Order Form + Order Book */}- <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>- {/* Order Form */}- {tradingMode === 'paper' && (- <div>- {!paperAdapter || !paperAdapter.isConnected() ? (+ {/* RIGHT SIDEBAR - Order Entry & Order Book */}+ <div style={{+ width: '360px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ borderLeft: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden'+ }}>+ {/* Order Entry */}+ <div style={{+ height: '45%',+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden'+ }}>+ <div style={{+ padding: '8px 12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '10px',+ fontWeight: 700,+ color: BLOOMBERG.ORANGE,+ letterSpacing: '0.5px'+ }}>+ ORDER ENTRY+ </div>+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>+ {tradingMode === 'paper' ? (+ !paperAdapter || !paperAdapter.isConnected() ? (+ <div style={{+ padding: '20px',+ textAlign: 'center',+ border: `1px solid ${BLOOMBERG.ORANGE}`,+ backgroundColor: `${BLOOMBERG.ORANGE}10`+ }}>+ <div style={{ color: BLOOMBERG.ORANGE, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>+ ⚠️ INITIALIZING...+ </div>+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '10px' }}>+ {isConnecting ? 'Connecting to broker...' : 'Waiting for adapter...'}+ </div>+ </div>+ ) : (+ <>+ <EnhancedOrderForm+ symbol={selectedSymbol}+ currentPrice={currentPrice}+ balance={balance}+ onOrderPlaced={() => {+ // Reload positions and orders after successful order+ console.log('Order placed successfully');+ }}+ />++ {/* HyperLiquid Vault Manager */}+ <HyperLiquidVaultManager />+ </>+ )+ ) : (<div style={{padding: '20px',- backgroundColor: '#1a1a1a',- borderRadius: '6px',textAlign: 'center',- border: '1px solid #f59e0b'+ border: `1px solid ${BLOOMBERG.RED}`,+ backgroundColor: `${BLOOMBERG.RED}10`,+ color: BLOOMBERG.RED,+ fontSize: '11px'}}>- <div style={{ fontSize: '14px', color: '#f59e0b', marginBottom: '8px', fontWeight: 'bold' }}>- ⚠️ Paper Trading Initializing...- </div>- <div style={{ fontSize: '12px', color: '#999' }}>- {isConnecting ? 'Connecting to broker...' : 'Waiting for adapter...'}- </div>- <div style={{- marginTop: '12px',- width: '100%',- height: '4px',- backgroundColor: '#333',- borderRadius: '2px',- overflow: 'hidden'- }}>- <div style={{- width: '50%',- height: '100%',- backgroundColor: '#f59e0b',- animation: 'loading 1.5s ease-in-out infinite'- }} />- </div>+ Live trading not yet enabled</div>- ) : (- <OrderForm- symbol={selectedSymbol}- currentPrice={currentPrice}- onPlaceOrder={handlePlaceOrder}- isLoading={isPlacingOrder}- />)}</div>- )}+ </div>- {/* Order Book */}- <div style={{ padding: '16px', backgroundColor: '#1a1a1a', borderRadius: '6px' }}>- <h3 style={{ marginBottom: '12px', fontSize: '14px', fontWeight: 'bold' }}>- Order Book - {orderBook.bids.length} bids, {orderBook.asks.length} asks- </h3>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>- {/* Asks */}- <div>- <h4 style={{ color: '#dc2626', fontSize: '12px', marginBottom: '8px', fontWeight: 'bold' }}>ASKS</h4>- <table style={{ width: '100%', fontSize: '11px', fontFamily: 'monospace' }}>+ {/* Order Book / Volume Profile */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ <div style={{+ padding: '8px 12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '10px',+ fontWeight: 700,+ color: BLOOMBERG.ORANGE,+ letterSpacing: '0.5px',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center'+ }}>+ <div style={{ display: 'flex', gap: '8px' }}>+ {['orderbook', 'volume'].map((view) => (+ <button+ key={view}+ onClick={() => setRightPanelView(view as any)}+ style={{+ padding: '4px 8px',+ backgroundColor: rightPanelView === view ? BLOOMBERG.ORANGE : 'transparent',+ border: 'none',+ color: rightPanelView === view ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ cursor: 'pointer',+ fontSize: '9px',+ fontWeight: 700,+ transition: 'all 0.2s'+ }}+ >+ {view.toUpperCase()}+ </button>+ ))}+ </div>+ {rightPanelView === 'orderbook' && (+ <span style={{ fontSize: '8px', color: BLOOMBERG.GRAY }}>+ {orderBook.asks.length + orderBook.bids.length} LEVELS+ </span>+ )}+ </div>+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>+ {rightPanelView === 'orderbook' && (+ <>+ <div style={{ marginBottom: '12px' }}>+ <div style={{ color: BLOOMBERG.RED, fontSize: '9px', fontWeight: 700, marginBottom: '4px' }}>+ ASKS ({orderBook.asks.length})+ </div>+ <table style={{ width: '100%', fontSize: '10px' }}><tbody>- {orderBook.asks.slice(0, 10).map((ask, idx) => (- <tr key={idx}>- <td style={{ padding: '2px 4px', color: '#dc2626' }}>- ${ask.price.toFixed(1)}- </td>- <td style={{ padding: '2px 4px', textAlign: 'right', color: '#999' }}>- {ask.size.toFixed(4)}- </td>- </tr>- ))}+ {orderBook.asks.slice(0, 12).reverse().map((ask, idx) => {+ const depth = (ask.size / Math.max(...orderBook.asks.map(a => a.size))) * 100;+ return (+ <tr key={idx} style={{ position: 'relative' }}>+ <td style={{+ padding: '2px 4px',+ color: BLOOMBERG.RED,+ position: 'relative',+ zIndex: 1+ }}>+ <div style={{+ position: 'absolute',+ right: 0,+ top: 0,+ bottom: 0,+ width: `${depth}%`,+ backgroundColor: `${BLOOMBERG.RED}15`,+ zIndex: -1+ }} />+ ${ask.price.toFixed(2)}+ </td>+ <td style={{ padding: '2px 4px', textAlign: 'right', color: BLOOMBERG.GRAY }}>+ {ask.size.toFixed(4)}+ </td>+ </tr>+ );+ })}</tbody></table></div>- {/* Bids */}+ <div style={{+ height: '1px',+ backgroundColor: BLOOMBERG.BORDER,+ margin: '8px 0',+ position: 'relative'+ }}>+ <div style={{+ position: 'absolute',+ left: '50%',+ top: '50%',+ transform: 'translate(-50%, -50%)',+ backgroundColor: BLOOMBERG.PANEL_BG,+ padding: '0 8px',+ fontSize: '11px',+ fontWeight: 700,+ color: BLOOMBERG.YELLOW+ }}>+ ${currentPrice.toFixed(2)}+ </div>+ </div>+<div>- <h4 style={{ color: '#10b981', fontSize: '12px', marginBottom: '8px', fontWeight: 'bold' }}>BIDS</h4>- <table style={{ width: '100%', fontSize: '11px', fontFamily: 'monospace' }}>+ <div style={{ color: BLOOMBERG.GREEN, fontSize: '9px', fontWeight: 700, marginBottom: '4px' }}>+ BIDS ({orderBook.bids.length})+ </div>+ <table style={{ width: '100%', fontSize: '10px' }}><tbody>- {orderBook.bids.slice(0, 10).map((bid, idx) => (- <tr key={idx}>- <td style={{ padding: '2px 4px', color: '#10b981' }}>- ${bid.price.toFixed(1)}- </td>- <td style={{ padding: '2px 4px', textAlign: 'right', color: '#999' }}>- {bid.size.toFixed(4)}- </td>- </tr>- ))}+ {orderBook.bids.slice(0, 12).map((bid, idx) => {+ const depth = (bid.size / Math.max(...orderBook.bids.map(b => b.size))) * 100;+ return (+ <tr key={idx} style={{ position: 'relative' }}>+ <td style={{+ padding: '2px 4px',+ color: BLOOMBERG.GREEN,+ position: 'relative',+ zIndex: 1+ }}>+ <div style={{+ position: 'absolute',+ right: 0,+ top: 0,+ bottom: 0,+ width: `${depth}%`,+ backgroundColor: `${BLOOMBERG.GREEN}15`,+ zIndex: -1+ }} />+ ${bid.price.toFixed(2)}+ </td>+ <td style={{ padding: '2px 4px', textAlign: 'right', color: BLOOMBERG.GRAY }}>+ {bid.size.toFixed(4)}+ </td>+ </tr>+ );+ })}</tbody></table></div>- </div>- <div style={{ marginTop: '12px', fontSize: '10px', color: '#555' }}>- Last update: {lastOrderBookUpdate > 0 ? new Date(lastOrderBookUpdate).toLocaleTimeString() : 'Never'}+ </>+ )}++ {rightPanelView === 'volume' && (+ <VolumeProfile symbol={selectedSymbol} height={550} />+ )}+ </div>+ <div style={{+ padding: '4px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '8px',+ color: BLOOMBERG.GRAY+ }}>+ Updated: {lastOrderBookUpdate > 0 ? new Date(lastOrderBookUpdate).toLocaleTimeString() : 'Never'}</div></div></div></div>- {/* Footer */}+ {/* ========== STATUS BAR ========== */}<div style={{- marginTop: '20px',- padding: '16px',- backgroundColor: '#1a1a1a',- borderRadius: '6px',- borderTop: '1px solid #333',+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,+ backgroundColor: BLOOMBERG.HEADER_BG,+ padding: '4px 12px',+ fontSize: '9px',+ color: BLOOMBERG.GRAY,display: 'flex',justifyContent: 'space-between',alignItems: 'center',- fontSize: '12px',- color: '#666'+ flexShrink: 0}}>- <div style={{ display: 'flex', gap: '24px', alignItems: 'center' }}>- <div>- <span style={{ color: '#999', marginRight: '8px' }}>Broker:</span>- <span style={{ color: '#f59e0b', fontWeight: 'bold' }}>- {activeBroker || 'None'}- </span>- </div>- <div>- <span style={{ color: '#999', marginRight: '8px' }}>Mode:</span>- <span style={{- color: tradingMode === 'paper' ? '#10b981' : '#dc2626',- fontWeight: 'bold'- }}>- {tradingMode === 'paper' ? 'Paper Trading' : 'Live Trading'}- </span>- </div>- <div>- <span style={{ color: '#999', marginRight: '8px' }}>Connection:</span>- <span style={{- color: activeAdapter?.isConnected() ? '#10b981' : '#dc2626',- fontWeight: 'bold'- }}>- {activeAdapter?.isConnected() ? '● Connected' : '○ Disconnected'}- </span>- </div>- </div>-- <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>- <div style={{ fontSize: '11px', color: '#555' }}>- Fincept Terminal v3.0.12- </div>- <div style={{ fontSize: '11px', color: '#555' }}>- © {new Date().getFullYear()} Fincept Corporation- </div>- </div>+ <span>Fincept Terminal v3.0.12 | Professional Trading Platform</span>+ <span>+ Broker: <span style={{ color: BLOOMBERG.ORANGE }}>{activeBroker?.toUpperCase() || 'NONE'}</span> |+ Mode: <span style={{ color: tradingMode === 'paper' ? BLOOMBERG.GREEN : BLOOMBERG.RED }}>+ {tradingMode.toUpperCase()}+ </span> |+ Status: <span style={{ color: activeAdapter?.isConnected() ? BLOOMBERG.GREEN : BLOOMBERG.RED }}>+ {activeAdapter?.isConnected() ? 'CONNECTED' : 'DISCONNECTED'}+ </span>+ </span></div></div>);diff --git a/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsx b/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsxindex 828b273ca..f156c02c6 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsx@@ -1,5 +1,5 @@// File: src/components/tabs/trading/OrderForm.tsx-// Feature-aware order placement form - adapts to broker capabilities+// Bloomberg Terminal-styled order placement formimport React, { useState } from 'react';import { useBrokerContext } from '../../../contexts/BrokerContext';@@ -12,6 +12,23 @@ interface OrderFormProps {isLoading?: boolean;}+// Bloomberg Professional Color Palette+const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A'+};+export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: OrderFormProps) {const { activeBrokerMetadata, tradingMode } = useBrokerContext();@@ -77,90 +94,207 @@ export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: Ord: '0.00';return (- <div className="bg-[#0d0d0d] border-t border-gray-800 p-4">- <h3 className="text-sm font-bold text-gray-400 mb-3">PLACE ORDER</h3>-- <form onSubmit={handleSubmit} className="space-y-3">+ <div style={{+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ fontSize: '11px'+ }}>+ <form onSubmit={handleSubmit}>{/* Buy/Sell Toggle */}- <div className="flex gap-2">+ <div style={{ display: 'flex', gap: '6px', marginBottom: '12px' }}><buttontype="button"onClick={() => setSide('buy')}- className={`flex-1 py-2 rounded font-semibold text-sm transition-colors ${- side === 'buy'- ? 'bg-green-600 text-white'- : 'bg-gray-800 text-gray-400 hover:bg-gray-700'- }`}+ style={{+ flex: 1,+ padding: '8px',+ backgroundColor: side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.HEADER_BG,+ border: `1px solid ${side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.BORDER}`,+ color: side === 'buy' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ cursor: 'pointer',+ fontWeight: 700,+ fontSize: '10px',+ letterSpacing: '0.5px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ if (side !== 'buy') {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ }+ }}+ onMouseLeave={(e) => {+ if (side !== 'buy') {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HEADER_BG;+ }+ }}>BUY</button><buttontype="button"onClick={() => setSide('sell')}- className={`flex-1 py-2 rounded font-semibold text-sm transition-colors ${- side === 'sell'- ? 'bg-red-600 text-white'- : 'bg-gray-800 text-gray-400 hover:bg-gray-700'- }`}+ style={{+ flex: 1,+ padding: '8px',+ backgroundColor: side === 'sell' ? BLOOMBERG.RED : BLOOMBERG.HEADER_BG,+ border: `1px solid ${side === 'sell' ? BLOOMBERG.RED : BLOOMBERG.BORDER}`,+ color: side === 'sell' ? BLOOMBERG.WHITE : BLOOMBERG.GRAY,+ cursor: 'pointer',+ fontWeight: 700,+ fontSize: '10px',+ letterSpacing: '0.5px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ if (side !== 'sell') {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ }+ }}+ onMouseLeave={(e) => {+ if (side !== 'sell') {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HEADER_BG;+ }+ }}>SELL</button></div>- {/* Order Type - Only show supported types */}- <div>- <label className="block text-xs text-gray-500 mb-1">Order Type</label>+ {/* Order Type */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ marginBottom: '4px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ ORDER TYPE+ </label><selectvalue={orderType}onChange={(e) => setOrderType(e.target.value as OrderType)}- className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"+ style={{+ width: '100%',+ padding: '6px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ color: BLOOMBERG.WHITE,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '10px',+ fontWeight: 600,+ outline: 'none',+ cursor: 'pointer'+ }}>- {supportsMarket && <option value="market">Market</option>}- {supportsLimit && <option value="limit">Limit</option>}- {supportsStop && <option value="stop_market">Stop Market</option>}- {supportsStopLimit && <option value="stop_limit">Stop Limit</option>}+ {supportsMarket && <option value="market">MARKET</option>}+ {supportsLimit && <option value="limit">LIMIT</option>}+ {supportsStop && <option value="stop_market">STOP MARKET</option>}+ {supportsStopLimit && <option value="stop_limit">STOP LIMIT</option>}</select></div>{/* Quantity */}- <div>- <label className="block text-xs text-gray-500 mb-1">Quantity</label>+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ marginBottom: '4px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ QUANTITY+ </label><inputtype="number"step="0.0001"value={quantity}onChange={(e) => setQuantity(e.target.value)}- placeholder="0.00"- className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"+ placeholder="0.0000"+ style={{+ width: '100%',+ padding: '6px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ color: BLOOMBERG.YELLOW,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '11px',+ fontWeight: 600,+ outline: 'none',+ fontFamily: 'monospace'+ }}+ onFocus={(e) => e.currentTarget.style.borderColor = BLOOMBERG.ORANGE}+ onBlur={(e) => e.currentTarget.style.borderColor = BLOOMBERG.BORDER}/></div>{/* Limit Price (for limit and stop_limit) */}{(orderType === 'limit' || orderType === 'stop_limit') && (- <div>- <label className="block text-xs text-gray-500 mb-1">Limit Price</label>+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ marginBottom: '4px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ LIMIT PRICE+ </label><inputtype="number"step="0.01"value={price}onChange={(e) => setPrice(e.target.value)}placeholder={currentPrice?.toFixed(2) || '0.00'}- className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"+ style={{+ width: '100%',+ padding: '6px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ color: BLOOMBERG.CYAN,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '11px',+ fontWeight: 600,+ outline: 'none',+ fontFamily: 'monospace'+ }}+ onFocus={(e) => e.currentTarget.style.borderColor = BLOOMBERG.ORANGE}+ onBlur={(e) => e.currentTarget.style.borderColor = BLOOMBERG.BORDER}/></div>)}{/* Stop Price (for stop_market and stop_limit) */}{(orderType === 'stop_market' || orderType === 'stop_limit') && (- <div>- <label className="block text-xs text-gray-500 mb-1">Stop Price</label>+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ marginBottom: '4px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ STOP PRICE+ </label><inputtype="number"step="0.01"value={stopPrice}onChange={(e) => setStopPrice(e.target.value)}placeholder={currentPrice?.toFixed(2) || '0.00'}- className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"+ style={{+ width: '100%',+ padding: '6px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ color: BLOOMBERG.CYAN,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '11px',+ fontWeight: 600,+ outline: 'none',+ fontFamily: 'monospace'+ }}+ onFocus={(e) => e.currentTarget.style.borderColor = BLOOMBERG.ORANGE}+ onBlur={(e) => e.currentTarget.style.borderColor = BLOOMBERG.BORDER}/></div>)}@@ -169,52 +303,125 @@ export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: Ord<buttontype="button"onClick={() => setEnableAdvanced(!enableAdvanced)}- className="text-xs text-orange-500 hover:text-orange-400 transition-colors"+ style={{+ marginBottom: '12px',+ color: BLOOMBERG.ORANGE,+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ fontSize: '9px',+ fontWeight: 600,+ letterSpacing: '0.5px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => e.currentTarget.style.color = BLOOMBERG.YELLOW}+ onMouseLeave={(e) => e.currentTarget.style.color = BLOOMBERG.ORANGE}>- {enableAdvanced ? '− ' : '+ '}Advanced (SL/TP)+ {enableAdvanced ? '▼' : '▶'} ADVANCED (SL/TP)</button>{/* Advanced Settings: Stop Loss & Take Profit */}{enableAdvanced && (- <div className="space-y-3 border border-gray-700 rounded p-3 bg-gray-900/50">- <div>- <label className="block text-xs text-gray-500 mb-1">Take Profit Price</label>+ <div style={{+ marginBottom: '12px',+ padding: '10px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`+ }}>+ <div style={{ marginBottom: '10px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG.GREEN,+ fontSize: '9px',+ marginBottom: '4px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ TAKE PROFIT+ </label><inputtype="number"step="0.01"value={takeProfitPrice}onChange={(e) => setTakeProfitPrice(e.target.value)}placeholder="Optional"- className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500"+ style={{+ width: '100%',+ padding: '6px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ color: BLOOMBERG.GREEN,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '10px',+ fontWeight: 600,+ outline: 'none',+ fontFamily: 'monospace'+ }}+ onFocus={(e) => e.currentTarget.style.borderColor = BLOOMBERG.GREEN}+ onBlur={(e) => e.currentTarget.style.borderColor = BLOOMBERG.BORDER}/></div><div>- <label className="block text-xs text-gray-500 mb-1">Stop Loss Price</label>+ <label style={{+ display: 'block',+ color: BLOOMBERG.RED,+ fontSize: '9px',+ marginBottom: '4px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ STOP LOSS+ </label><inputtype="number"step="0.01"value={stopLossPrice}onChange={(e) => setStopLossPrice(e.target.value)}placeholder="Optional"- className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-red-500"+ style={{+ width: '100%',+ padding: '6px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ color: BLOOMBERG.RED,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '10px',+ fontWeight: 600,+ outline: 'none',+ fontFamily: 'monospace'+ }}+ onFocus={(e) => e.currentTarget.style.borderColor = BLOOMBERG.RED}+ onBlur={(e) => e.currentTarget.style.borderColor = BLOOMBERG.BORDER}/></div>{currentPrice && (takeProfitPrice || stopLossPrice) && (- <div className="text-xs space-y-1">+ <div style={{+ marginTop: '8px',+ paddingTop: '8px',+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '9px'+ }}>{takeProfitPrice && (- <div className="flex justify-between text-green-400">+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ color: BLOOMBERG.GREEN,+ marginBottom: '4px'+ }}><span>TP R/R:</span>- <span>+ <span style={{ fontWeight: 700 }}>{((Math.abs(parseFloat(takeProfitPrice) - currentPrice) / currentPrice) * 100).toFixed(2)}%</span></div>)}{stopLossPrice && (- <div className="flex justify-between text-red-400">- <span>SL Risk:</span>- <span>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ color: BLOOMBERG.RED+ }}>+ <span>SL RISK:</span>+ <span style={{ fontWeight: 700 }}>{((Math.abs(currentPrice - parseFloat(stopLossPrice)) / currentPrice) * 100).toFixed(2)}%</span></div>@@ -226,23 +433,58 @@ export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: Ord{/* Estimated Cost */}{currentPrice && (- <div className="flex justify-between text-xs">- <span className="text-gray-500">Estimated {side === 'buy' ? 'Cost' : 'Proceeds'}:</span>- <span className="text-white font-mono">${estimatedCost}</span>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '12px',+ padding: '8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '9px'+ }}>+ <span style={{ color: BLOOMBERG.GRAY, fontWeight: 600 }}>+ EST. {side === 'buy' ? 'COST' : 'PROCEEDS'}:+ </span>+ <span style={{+ color: BLOOMBERG.YELLOW,+ fontWeight: 700,+ fontFamily: 'monospace',+ fontSize: '10px'+ }}>+ ${estimatedCost}+ </span></div>)}{/* Error Message */}{error && (- <div className="bg-red-900/20 border border-red-600 rounded p-2 text-xs text-red-400">- {error}+ <div style={{+ marginBottom: '12px',+ padding: '8px',+ backgroundColor: `${BLOOMBERG.RED}20`,+ border: `1px solid ${BLOOMBERG.RED}`,+ color: BLOOMBERG.RED,+ fontSize: '9px',+ fontWeight: 600+ }}>+ ⚠ {error}</div>)}{/* Trading Mode Warning */}{tradingMode === 'live' && (- <div className="bg-red-900/20 border border-red-600 rounded p-2 text-xs text-red-400 font-bold">- ⚠️ LIVE TRADING MODE - Real money will be used!+ <div style={{+ marginBottom: '12px',+ padding: '8px',+ backgroundColor: `${BLOOMBERG.RED}20`,+ border: `2px solid ${BLOOMBERG.RED}`,+ color: BLOOMBERG.RED,+ fontSize: '9px',+ fontWeight: 700,+ textAlign: 'center',+ letterSpacing: '0.5px'+ }}>+ ⚠️ LIVE TRADING MODE - REAL MONEY!</div>)}@@ -250,16 +492,51 @@ export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: Ord<buttontype="submit"disabled={isLoading}- className={`w-full py-2 rounded font-semibold text-sm transition-colors ${- tradingMode === 'live'- ? 'bg-red-600 hover:bg-red-700 text-white border-2 border-red-400'+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: tradingMode === 'live'+ ? BLOOMBERG.RED: side === 'buy'- ? 'bg-green-600 hover:bg-green-700 text-white'- : 'bg-red-600 hover:bg-red-700 text-white'- } ${isLoading ? 'opacity-50 cursor-not-allowed' : ''}`}+ ? BLOOMBERG.GREEN+ : BLOOMBERG.RED,+ border: tradingMode === 'live'+ ? `2px solid ${BLOOMBERG.YELLOW}`+ : `1px solid ${side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.RED}`,+ color: tradingMode === 'live' || side === 'sell' ? BLOOMBERG.WHITE : BLOOMBERG.DARK_BG,+ cursor: isLoading ? 'not-allowed' : 'pointer',+ fontWeight: 700,+ fontSize: '11px',+ letterSpacing: '1px',+ transition: 'all 0.2s',+ opacity: isLoading ? 0.6 : 1,+ boxShadow: tradingMode === 'live' ? `0 0 10px ${BLOOMBERG.RED}40` : 'none'+ }}+ onMouseEnter={(e) => {+ if (!isLoading) {+ if (tradingMode === 'live') {+ e.currentTarget.style.backgroundColor = '#FF1111';+ } else if (side === 'buy') {+ e.currentTarget.style.backgroundColor = '#00FF88';+ } else {+ e.currentTarget.style.backgroundColor = '#FF5555';+ }+ }+ }}+ onMouseLeave={(e) => {+ if (!isLoading) {+ if (tradingMode === 'live') {+ e.currentTarget.style.backgroundColor = BLOOMBERG.RED;+ } else if (side === 'buy') {+ e.currentTarget.style.backgroundColor = BLOOMBERG.GREEN;+ } else {+ e.currentTarget.style.backgroundColor = BLOOMBERG.RED;+ }+ }+ }}>{isLoading- ? 'Placing Order...'+ ? 'PLACING ORDER...': tradingMode === 'live'? `🔴 LIVE ${side.toUpperCase()} ${symbol}`: `${side.toUpperCase()} ${symbol}`}@@ -267,7 +544,13 @@ export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: Ord{/* Paper Trading Info */}{tradingMode === 'paper' && (- <div className="text-xs text-gray-500 text-center italic">+ <div style={{+ marginTop: '8px',+ textAlign: 'center',+ color: BLOOMBERG.GRAY,+ fontSize: '8px',+ fontStyle: 'italic'+ }}>Paper trading - No real money used</div>)}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/DepthChart.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/DepthChart.tsxnew file mode 100644index 000000000..817588d6d--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/DepthChart.tsx@@ -0,0 +1,164 @@+/**+ * DepthChart - Market depth visualization+ * Shows orderbook bid/ask distribution+ */++import React, { useMemo } from 'react';+import { AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';+import { useOrderBook } from '../hooks/useMarketData';++interface DepthChartProps {+ symbol: string;+ height?: number;+ limit?: number;+}++interface DepthDataPoint {+ price: number;+ bidTotal: number;+ askTotal: number;+}++export function DepthChart({ symbol, height = 300, limit = 50 }: DepthChartProps) {+ const { orderBook, isLoading, error } = useOrderBook(symbol, limit, true);++ const depthData = useMemo(() => {+ if (!orderBook) return [];++ const data: DepthDataPoint[] = [];++ // Calculate cumulative bid depth+ let bidTotal = 0;+ const bids = [...orderBook.bids]+ .sort((a, b) => b.price - a.price) // Highest to lowest+ .slice(0, limit);++ bids.forEach((bid) => {+ bidTotal += bid.size;+ data.push({+ price: bid.price,+ bidTotal,+ askTotal: 0,+ });+ });++ // Calculate cumulative ask depth+ let askTotal = 0;+ const asks = [...orderBook.asks]+ .sort((a, b) => a.price - b.price) // Lowest to highest+ .slice(0, limit);++ asks.forEach((ask) => {+ askTotal += ask.size;+ data.push({+ price: ask.price,+ bidTotal: 0,+ askTotal,+ });+ });++ // Sort by price+ return data.sort((a, b) => a.price - b.price);+ }, [orderBook, limit]);++ const midPrice = useMemo(() => {+ if (!orderBook || !orderBook.bids.length || !orderBook.asks.length) return null;+ return (orderBook.bids[0].price + orderBook.asks[0].price) / 2;+ }, [orderBook]);++ if (isLoading) {+ return (+ <div className="flex items-center justify-center bg-black border border-gray-800 rounded" style={{ height }}>+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>+ </div>+ );+ }++ if (error) {+ return (+ <div className="flex items-center justify-center bg-black border border-gray-800 rounded text-red-500 text-sm" style={{ height }}>+ Failed to load depth chart: {error.message}+ </div>+ );+ }++ if (!depthData.length) {+ return (+ <div className="flex items-center justify-center bg-black border border-gray-800 rounded text-gray-500 text-sm" style={{ height }}>+ No orderbook data available+ </div>+ );+ }++ return (+ <div className="bg-black border border-gray-800 rounded p-2">+ <div className="flex items-center justify-between mb-2 px-2">+ <span className="text-xs text-gray-400">MARKET DEPTH</span>+ {midPrice && (+ <span className="text-xs font-mono text-gray-300">+ MID: ${midPrice.toFixed(2)}+ </span>+ )}+ </div>++ <ResponsiveContainer width="100%" height={height}>+ <AreaChart data={depthData} margin={{ top: 5, right: 5, left: 5, bottom: 5 }}>+ <defs>+ <linearGradient id="bidGradient" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="#10b981" stopOpacity={0.4} />+ <stop offset="95%" stopColor="#10b981" stopOpacity={0} />+ </linearGradient>+ <linearGradient id="askGradient" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor="#ef4444" stopOpacity={0.4} />+ <stop offset="95%" stopColor="#ef4444" stopOpacity={0} />+ </linearGradient>+ </defs>++ <XAxis+ dataKey="price"+ stroke="#4b5563"+ tick={{ fill: '#9ca3af', fontSize: 11 }}+ tickFormatter={(value) => `$${value.toFixed(0)}`}+ />++ <YAxis+ stroke="#4b5563"+ tick={{ fill: '#9ca3af', fontSize: 11 }}+ tickFormatter={(value) => value.toFixed(2)}+ />++ <Tooltip+ contentStyle={{+ backgroundColor: '#1f2937',+ border: '1px solid #374151',+ borderRadius: '4px',+ fontSize: '12px',+ }}+ labelStyle={{ color: '#d1d5db' }}+ itemStyle={{ color: '#d1d5db' }}+ formatter={(value: number) => value.toFixed(4)}+ labelFormatter={(label) => `Price: $${label}`}+ />++ <Area+ type="stepAfter"+ dataKey="bidTotal"+ stroke="#10b981"+ fill="url(#bidGradient)"+ strokeWidth={2}+ name="Bid Depth"+ />++ <Area+ type="stepBefore"+ dataKey="askTotal"+ stroke="#ef4444"+ fill="url(#askGradient)"+ strokeWidth={2}+ name="Ask Depth"+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChart.tsxnew file mode 100644index 000000000..f937f26bc--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChart.tsx@@ -0,0 +1,199 @@+/**+ * TradingChart - TradingView-style candlestick chart+ * Uses lightweight-charts library for high-performance rendering+ */++import React, { useEffect, useRef, useState } from 'react';+import { createChart, ColorType, CandlestickSeries, HistogramSeries } from 'lightweight-charts';+import type { IChartApi, CandlestickData, Time } from 'lightweight-charts';+import { useOHLCV } from '../hooks/useMarketData';+import type { Timeframe, OHLCV } from '../types';++interface TradingChartProps {+ symbol: string;+ timeframe?: Timeframe;+ height?: number;+ showVolume?: boolean;+}++export function TradingChart({+ symbol,+ timeframe = '1h',+ height = 500,+ showVolume = true+}: TradingChartProps) {+ const chartContainerRef = useRef<HTMLDivElement>(null);+ const chartRef = useRef<IChartApi | null>(null);+ const candlestickSeriesRef = useRef<any>(null);+ const volumeSeriesRef = useRef<any>(null);++ const { ohlcv, isLoading, error } = useOHLCV(symbol, timeframe, 200);+ const [selectedTimeframe, setSelectedTimeframe] = useState<Timeframe>(timeframe);++ // Initialize chart+ useEffect(() => {+ if (!chartContainerRef.current) return;++ const chart = createChart(chartContainerRef.current, {+ width: chartContainerRef.current.clientWidth,+ height,+ layout: {+ background: { type: ColorType.Solid, color: '#0a0a0a' },+ textColor: '#d1d5db',+ },+ grid: {+ vertLines: { color: '#1f1f1f' },+ horzLines: { color: '#1f1f1f' },+ },+ crosshair: {+ mode: 1,+ },+ rightPriceScale: {+ borderColor: '#2a2a2a',+ },+ timeScale: {+ borderColor: '#2a2a2a',+ timeVisible: true,+ secondsVisible: false,+ },+ });++ chartRef.current = chart;++ // Create candlestick series - v5 API: chart.addSeries(SeriesDefinition, options)+ const candlestickSeries = chart.addSeries(CandlestickSeries, {+ upColor: '#10b981',+ downColor: '#ef4444',+ borderUpColor: '#10b981',+ borderDownColor: '#ef4444',+ wickUpColor: '#10b981',+ wickDownColor: '#ef4444',+ });++ candlestickSeriesRef.current = candlestickSeries;++ // Create volume series+ if (showVolume) {+ const volumeSeries = chart.addSeries(HistogramSeries, {+ color: '#6b7280',+ priceFormat: {+ type: 'volume',+ },+ priceScaleId: '',+ });++ volumeSeries.priceScale().applyOptions({+ scaleMargins: {+ top: 0.8,+ bottom: 0,+ },+ });++ volumeSeriesRef.current = volumeSeries;+ }++ // Handle resize+ const handleResize = () => {+ if (chartContainerRef.current && chartRef.current) {+ chartRef.current.resize(+ chartContainerRef.current.clientWidth,+ height,+ true+ );+ }+ };++ window.addEventListener('resize', handleResize);++ return () => {+ window.removeEventListener('resize', handleResize);+ chart.remove();+ };+ }, [height, showVolume]);++ // Handle height changes+ useEffect(() => {+ if (chartRef.current && chartContainerRef.current) {+ chartRef.current.resize(+ chartContainerRef.current.clientWidth,+ height,+ true+ );+ }+ }, [height]);++ // Update chart data+ useEffect(() => {+ if (!ohlcv.length || !candlestickSeriesRef.current) return;++ // Convert OHLCV to candlestick data+ const candleData: CandlestickData[] = ohlcv.map((candle: OHLCV) => ({+ time: Math.floor(candle.timestamp / 1000) as any,+ open: candle.open,+ high: candle.high,+ low: candle.low,+ close: candle.close,+ }));++ candlestickSeriesRef.current.setData(candleData);++ // Update volume data+ if (showVolume && volumeSeriesRef.current) {+ const volumeData = ohlcv.map((candle: OHLCV) => ({+ time: Math.floor(candle.timestamp / 1000) as any,+ value: candle.volume,+ color: candle.close >= candle.open ? '#10b98144' : '#ef444444',+ }));++ volumeSeriesRef.current.setData(volumeData);+ }++ // Fit content+ chartRef.current?.timeScale().fitContent();+ }, [ohlcv, showVolume]);++ const timeframes: Timeframe[] = ['1m', '5m', '15m', '1h', '4h', '1d'];++ return (+ <div className="flex flex-col gap-2">+ {/* Timeframe selector */}+ <div className="flex items-center gap-2 px-4">+ <span className="text-xs text-gray-400">TIMEFRAME:</span>+ <div className="flex gap-1">+ {timeframes.map((tf) => (+ <button+ key={tf}+ onClick={() => setSelectedTimeframe(tf)}+ className={`px-2 py-1 text-xs font-mono rounded transition-colors ${+ selectedTimeframe === tf+ ? 'bg-blue-600 text-white'+ : 'bg-gray-800 text-gray-400 hover:bg-gray-700'+ }`}+ >+ {tf}+ </button>+ ))}+ </div>+ </div>++ {/* Chart container */}+ <div className="relative">+ {isLoading && (+ <div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10">+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>+ </div>+ )}++ {error && (+ <div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10">+ <div className="text-red-500 text-sm">+ Failed to load chart data: {error.message}+ </div>+ </div>+ )}++ <div ref={chartContainerRef} className="w-full" />+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/VolumeProfile.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/VolumeProfile.tsxnew file mode 100644index 000000000..4a51fe73a--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/VolumeProfile.tsx@@ -0,0 +1,138 @@+/**+ * VolumeProfile - Volume distribution by price level+ * Shows where most trading activity occurred+ */++import React from 'react';+import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts';+import { useVolumeProfile } from '../hooks/useMarketData';+import type { Timeframe } from '../types';++interface VolumeProfileProps {+ symbol: string;+ timeframe?: Timeframe;+ height?: number;+ limit?: number;+}++export function VolumeProfile({+ symbol,+ timeframe = '1h',+ height = 400,+ limit = 100+}: VolumeProfileProps) {+ const { volumeProfile, isLoading } = useVolumeProfile(symbol, timeframe, limit);++ if (isLoading || !volumeProfile.length) {+ return (+ <div className="flex items-center justify-center bg-black border border-gray-800 rounded" style={{ height }}>+ {isLoading ? (+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>+ ) : (+ <div className="text-gray-500 text-sm">No volume data available</div>+ )}+ </div>+ );+ }++ // Find max volume for color scaling+ const maxVolume = Math.max(...volumeProfile.map((p) => p.volume));++ // Find POC (Point of Control) - price level with highest volume+ const poc = volumeProfile.reduce((max, current) =>+ current.volume > max.volume ? current : max+ );++ return (+ <div className="bg-black border border-gray-800 rounded p-2">+ <div className="flex items-center justify-between mb-2 px-2">+ <span className="text-xs text-gray-400">VOLUME PROFILE</span>+ <span className="text-xs font-mono text-blue-400">+ POC: ${poc.price.toFixed(2)}+ </span>+ </div>++ <ResponsiveContainer width="100%" height={height}>+ <BarChart+ data={volumeProfile}+ layout="horizontal"+ margin={{ top: 5, right: 5, left: 50, bottom: 20 }}+ >+ <XAxis+ type="number"+ stroke="#4b5563"+ tick={{ fill: '#9ca3af', fontSize: 11 }}+ tickFormatter={(value) => `${(value / 1000).toFixed(0)}K`}+ />++ <YAxis+ type="number"+ dataKey="price"+ stroke="#4b5563"+ tick={{ fill: '#9ca3af', fontSize: 11 }}+ tickFormatter={(value) => `$${value.toFixed(0)}`}+ domain={['auto', 'auto']}+ />++ <Tooltip+ contentStyle={{+ backgroundColor: '#1f2937',+ border: '1px solid #374151',+ borderRadius: '4px',+ fontSize: '12px',+ }}+ labelStyle={{ color: '#d1d5db' }}+ itemStyle={{ color: '#d1d5db' }}+ formatter={(value: number, name: string) => {+ if (name === 'buyVolume' || name === 'sellVolume') {+ return value.toFixed(2);+ }+ return value.toFixed(2);+ }}+ labelFormatter={(label) => `Price: $${label}`}+ />++ <Bar dataKey="volume" radius={[0, 2, 2, 0]}>+ {volumeProfile.map((entry, index) => {+ // Color based on buy/sell ratio+ const buyRatio = entry.buyVolume / entry.volume;+ const isPOC = entry.price === poc.price;++ let color = '#6b7280'; // Default gray++ if (isPOC) {+ color = '#3b82f6'; // Blue for POC+ } else if (buyRatio > 0.6) {+ color = '#10b981'; // Green for buy-heavy+ } else if (buyRatio < 0.4) {+ color = '#ef4444'; // Red for sell-heavy+ }++ return <Cell key={`cell-${index}`} fill={color} />;+ })}+ </Bar>+ </BarChart>+ </ResponsiveContainer>++ {/* Legend */}+ <div className="flex items-center justify-center gap-4 mt-2 text-xs">+ <div className="flex items-center gap-1">+ <div className="w-3 h-3 bg-blue-500 rounded"></div>+ <span className="text-gray-400">POC</span>+ </div>+ <div className="flex items-center gap-1">+ <div className="w-3 h-3 bg-green-500 rounded"></div>+ <span className="text-gray-400">Buy Heavy</span>+ </div>+ <div className="flex items-center gap-1">+ <div className="w-3 h-3 bg-red-500 rounded"></div>+ <span className="text-gray-400">Sell Heavy</span>+ </div>+ <div className="flex items-center gap-1">+ <div className="w-3 h-3 bg-gray-500 rounded"></div>+ <span className="text-gray-400">Neutral</span>+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/charts/index.tsnew file mode 100644index 000000000..05b941286--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/index.ts@@ -0,0 +1,7 @@+/**+ * Charts Exports+ */++export { TradingChart } from './TradingChart';+export { DepthChart } from './DepthChart';+export { VolumeProfile } from './VolumeProfile';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/AccountStats.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/AccountStats.tsxnew file mode 100644index 000000000..c7a8f9f21--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/AccountStats.tsx@@ -0,0 +1,158 @@+/**+ * AccountStats - Trading statistics dashboard+ * Shows P&L, win rate, trade count, etc.+ */++import React from 'react';+import { TrendingUp, TrendingDown, Target, DollarSign } from 'lucide-react';+import { useTradingStats } from '../../hooks/useAccountInfo';++export function AccountStats() {+ const { stats, isLoading } = useTradingStats();++ if (isLoading || !stats) {+ return (+ <div className="flex items-center justify-center p-8 bg-black border border-gray-800 rounded">+ <div className="text-gray-500 text-sm">+ {isLoading ? (+ <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>+ ) : (+ 'No statistics available'+ )}+ </div>+ </div>+ );+ }++ const statCards = [+ {+ label: 'Total P&L',+ value: `${stats.totalPnL >= 0 ? '+' : ''}$${stats.totalPnL.toFixed(2)}`,+ color: stats.totalPnL >= 0 ? 'text-green-500' : 'text-red-500',+ icon: stats.totalPnL >= 0 ? TrendingUp : TrendingDown,+ bgColor: stats.totalPnL >= 0 ? 'bg-green-500/10' : 'bg-red-500/10',+ },+ {+ label: 'Return',+ value: `${stats.returnPercent >= 0 ? '+' : ''}${stats.returnPercent.toFixed(2)}%`,+ color: stats.returnPercent >= 0 ? 'text-green-500' : 'text-red-500',+ icon: Target,+ bgColor: stats.returnPercent >= 0 ? 'bg-green-500/10' : 'bg-red-500/10',+ },+ {+ label: 'Win Rate',+ value: `${stats.winRate.toFixed(1)}%`,+ color: stats.winRate >= 50 ? 'text-green-500' : 'text-yellow-500',+ icon: Target,+ bgColor: stats.winRate >= 50 ? 'bg-green-500/10' : 'bg-yellow-500/10',+ },+ {+ label: 'Total Trades',+ value: stats.totalTrades.toString(),+ color: 'text-blue-500',+ icon: DollarSign,+ bgColor: 'bg-blue-500/10',+ },+ {+ label: 'Winning Trades',+ value: stats.winningTrades.toString(),+ color: 'text-green-500',+ icon: TrendingUp,+ bgColor: 'bg-green-500/10',+ },+ {+ label: 'Losing Trades',+ value: stats.losingTrades.toString(),+ color: 'text-red-500',+ icon: TrendingDown,+ bgColor: 'bg-red-500/10',+ },+ {+ label: 'Realized P&L',+ value: `${stats.realizedPnL >= 0 ? '+' : ''}$${stats.realizedPnL.toFixed(2)}`,+ color: stats.realizedPnL >= 0 ? 'text-green-500' : 'text-red-500',+ icon: DollarSign,+ bgColor: 'bg-gray-800',+ },+ {+ label: 'Unrealized P&L',+ value: `${stats.unrealizedPnL >= 0 ? '+' : ''}$${stats.unrealizedPnL.toFixed(2)}`,+ color: stats.unrealizedPnL >= 0 ? 'text-green-500' : 'text-red-500',+ icon: DollarSign,+ bgColor: 'bg-gray-800',+ },+ ];++ return (+ <div className="space-y-4">+ {/* Main Stats Grid */}+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ {statCards.map((stat, idx) => {+ const Icon = stat.icon;+ return (+ <div+ key={idx}+ className={`${stat.bgColor} border border-gray-800 rounded p-3 transition-all hover:border-gray-700`}+ >+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs text-gray-400 font-medium">{stat.label}</span>+ <Icon className={`w-4 h-4 ${stat.color}`} />+ </div>+ <div className={`text-lg font-bold font-mono ${stat.color}`}>{stat.value}</div>+ </div>+ );+ })}+ </div>++ {/* Advanced Stats */}+ {stats.averageWin !== undefined && (+ <div className="grid grid-cols-2 md:grid-cols-3 gap-3">+ {stats.averageWin !== undefined && (+ <div className="bg-gray-900 border border-gray-800 rounded p-3">+ <div className="text-xs text-gray-400 mb-1">Avg Win</div>+ <div className="text-sm font-mono text-green-500">${stats.averageWin.toFixed(2)}</div>+ </div>+ )}+ {stats.averageLoss !== undefined && (+ <div className="bg-gray-900 border border-gray-800 rounded p-3">+ <div className="text-xs text-gray-400 mb-1">Avg Loss</div>+ <div className="text-sm font-mono text-red-500">${stats.averageLoss.toFixed(2)}</div>+ </div>+ )}+ {stats.profitFactor !== undefined && (+ <div className="bg-gray-900 border border-gray-800 rounded p-3">+ <div className="text-xs text-gray-400 mb-1">Profit Factor</div>+ <div className="text-sm font-mono text-blue-500">{stats.profitFactor.toFixed(2)}</div>+ </div>+ )}+ {stats.largestWin !== undefined && (+ <div className="bg-gray-900 border border-gray-800 rounded p-3">+ <div className="text-xs text-gray-400 mb-1">Largest Win</div>+ <div className="text-sm font-mono text-green-500">${stats.largestWin.toFixed(2)}</div>+ </div>+ )}+ {stats.largestLoss !== undefined && (+ <div className="bg-gray-900 border border-gray-800 rounded p-3">+ <div className="text-xs text-gray-400 mb-1">Largest Loss</div>+ <div className="text-sm font-mono text-red-500">${stats.largestLoss.toFixed(2)}</div>+ </div>+ )}+ {stats.sharpeRatio !== undefined && (+ <div className="bg-gray-900 border border-gray-800 rounded p-3">+ <div className="text-xs text-gray-400 mb-1">Sharpe Ratio</div>+ <div className="text-sm font-mono text-purple-500">{stats.sharpeRatio.toFixed(2)}</div>+ </div>+ )}+ </div>+ )}++ {/* Total Fees */}+ <div className="bg-gray-900 border border-gray-800 rounded p-3">+ <div className="flex items-center justify-between">+ <span className="text-xs text-gray-400">Total Fees Paid</span>+ <span className="text-sm font-mono text-orange-500">${stats.totalFees.toFixed(2)}</span>+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/FeesDisplay.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/FeesDisplay.tsxnew file mode 100644index 000000000..c672d8084--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/FeesDisplay.tsx@@ -0,0 +1,97 @@+/**+ * FeesDisplay - Shows trading fees for current exchange+ */++import React from 'react';+import { DollarSign, Info } from 'lucide-react';+import { useFees } from '../../hooks/useAccountInfo';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++export function FeesDisplay() {+ const { fees, isLoading } = useFees();+ const { activeBroker } = useBrokerContext();++ if (isLoading || !fees) {+ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-4">+ <div className="flex items-center gap-2 mb-3">+ <DollarSign className="w-4 h-4 text-orange-500" />+ <span className="text-sm font-medium text-gray-300">Trading Fees</span>+ </div>+ {isLoading ? (+ <div className="flex items-center justify-center py-4">+ <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-orange-500"></div>+ </div>+ ) : (+ <div className="text-xs text-gray-500">No fee information available</div>+ )}+ </div>+ );+ }++ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-4">+ {/* Header */}+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-2">+ <DollarSign className="w-4 h-4 text-orange-500" />+ <span className="text-sm font-medium text-gray-300">Trading Fees</span>+ </div>+ <span className="text-xs text-gray-500 uppercase">{activeBroker}</span>+ </div>++ {/* Fee Structure */}+ <div className="space-y-2">+ {/* Maker Fee */}+ <div className="flex items-center justify-between p-2 bg-black/30 rounded">+ <div className="flex items-center gap-2">+ <div className="text-xs text-gray-400">Maker Fee</div>+ <div className="group relative">+ <Info className="w-3 h-3 text-gray-600 cursor-help" />+ <div className="hidden group-hover:block absolute bottom-full left-0 mb-2 w-48 p-2 bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 z-10">+ Fee for adding liquidity to the order book (limit orders that don't immediately execute)+ </div>+ </div>+ </div>+ <div className="text-sm font-mono text-green-500">{fees.makerPercent}</div>+ </div>++ {/* Taker Fee */}+ <div className="flex items-center justify-between p-2 bg-black/30 rounded">+ <div className="flex items-center gap-2">+ <div className="text-xs text-gray-400">Taker Fee</div>+ <div className="group relative">+ <Info className="w-3 h-3 text-gray-600 cursor-help" />+ <div className="hidden group-hover:block absolute bottom-full left-0 mb-2 w-48 p-2 bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 z-10">+ Fee for taking liquidity from the order book (market orders and limit orders that execute immediately)+ </div>+ </div>+ </div>+ <div className="text-sm font-mono text-orange-500">{fees.takerPercent}</div>+ </div>+ </div>++ {/* Example Calculation */}+ <div className="mt-3 pt-3 border-t border-gray-800">+ <div className="text-xs text-gray-500 mb-2">Example: $10,000 trade</div>+ <div className="grid grid-cols-2 gap-2 text-xs">+ <div className="flex justify-between">+ <span className="text-gray-400">Maker:</span>+ <span className="text-green-500 font-mono">${(10000 * fees.maker).toFixed(2)}</span>+ </div>+ <div className="flex justify-between">+ <span className="text-gray-400">Taker:</span>+ <span className="text-orange-500 font-mono">${(10000 * fees.taker).toFixed(2)}</span>+ </div>+ </div>+ </div>++ {/* Savings Tip */}+ <div className="mt-3 p-2 bg-blue-500/10 border border-blue-500/20 rounded">+ <div className="text-xs text-blue-400">+ 💡 Tip: Use limit orders to pay lower maker fees+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/MarginPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/MarginPanel.tsxnew file mode 100644index 000000000..6ff14b831--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/MarginPanel.tsx@@ -0,0 +1,141 @@+/**+ * MarginPanel - Displays margin information and warnings+ */++import React from 'react';+import { AlertTriangle, Shield, TrendingUp } from 'lucide-react';+import { useMarginInfo } from '../../hooks/useAccountInfo';++export function MarginPanel() {+ const { marginInfo, isLoading } = useMarginInfo();++ if (isLoading) {+ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-4">+ <div className="flex items-center justify-center py-4">+ <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-500"></div>+ </div>+ </div>+ );+ }++ if (!marginInfo) {+ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-4">+ <div className="flex items-center gap-2 mb-2">+ <Shield className="w-4 h-4 text-gray-500" />+ <span className="text-sm font-medium text-gray-400">Margin Trading</span>+ </div>+ <div className="text-xs text-gray-500">+ Not available or not enabled on this account+ </div>+ </div>+ );+ }++ // Determine margin level status+ const getMarginStatus = () => {+ if (marginInfo.marginLevel >= 50) {+ return {+ color: 'text-green-500',+ bgColor: 'bg-green-500/10',+ borderColor: 'border-green-500/20',+ label: 'Healthy',+ };+ } else if (marginInfo.marginLevel >= 20) {+ return {+ color: 'text-yellow-500',+ bgColor: 'bg-yellow-500/10',+ borderColor: 'border-yellow-500/20',+ label: 'Warning',+ };+ } else {+ return {+ color: 'text-red-500',+ bgColor: 'bg-red-500/10',+ borderColor: 'border-red-500/20',+ label: 'Critical',+ };+ }+ };++ const status = getMarginStatus();++ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-4">+ {/* Header */}+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-2">+ <Shield className="w-4 h-4 text-blue-500" />+ <span className="text-sm font-medium text-gray-300">Margin Status</span>+ </div>+ <div className={`flex items-center gap-1 px-2 py-0.5 ${status.bgColor} ${status.borderColor} border rounded text-xs ${status.color}`}>+ <div className="w-1.5 h-1.5 rounded-full bg-current"></div>+ {status.label}+ </div>+ </div>++ {/* Margin Call Warning */}+ {marginInfo.isMarginCall && (+ <div className="mb-3 p-2 bg-red-500/10 border border-red-500/20 rounded flex items-start gap-2">+ <AlertTriangle className="w-4 h-4 text-red-500 flex-shrink-0 mt-0.5" />+ <div className="text-xs text-red-400">+ <div className="font-medium mb-1">Margin Call Warning!</div>+ <div>Your margin level is critically low. Add funds or close positions to avoid liquidation.</div>+ </div>+ </div>+ )}++ {/* Margin Level Progress Bar */}+ <div className="mb-4">+ <div className="flex items-center justify-between mb-1">+ <span className="text-xs text-gray-400">Margin Level</span>+ <span className={`text-sm font-mono font-bold ${status.color}`}>+ {marginInfo.marginLevel.toFixed(2)}%+ </span>+ </div>+ <div className="w-full h-2 bg-gray-800 rounded-full overflow-hidden">+ <div+ className={`h-full ${status.bgColor.replace('/10', '')} transition-all`}+ style={{ width: `${Math.min(marginInfo.marginLevel, 100)}%` }}+ ></div>+ </div>+ </div>++ {/* Margin Details */}+ <div className="space-y-2">+ <div className="flex items-center justify-between p-2 bg-black/30 rounded">+ <span className="text-xs text-gray-400">Total Margin</span>+ <span className="text-sm font-mono text-white">${marginInfo.totalMargin.toFixed(2)}</span>+ </div>++ <div className="flex items-center justify-between p-2 bg-black/30 rounded">+ <span className="text-xs text-gray-400">Used Margin</span>+ <span className="text-sm font-mono text-orange-500">${marginInfo.usedMargin.toFixed(2)}</span>+ </div>++ <div className="flex items-center justify-between p-2 bg-black/30 rounded">+ <span className="text-xs text-gray-400">Available Margin</span>+ <span className="text-sm font-mono text-green-500">${marginInfo.availableMargin.toFixed(2)}</span>+ </div>++ {marginInfo.maintenanceMargin > 0 && (+ <div className="flex items-center justify-between p-2 bg-black/30 rounded">+ <span className="text-xs text-gray-400">Maintenance Margin</span>+ <span className="text-sm font-mono text-blue-500">${marginInfo.maintenanceMargin.toFixed(2)}</span>+ </div>+ )}+ </div>++ {/* Info Tip */}+ <div className="mt-3 p-2 bg-blue-500/10 border border-blue-500/20 rounded">+ <div className="flex items-start gap-2">+ <TrendingUp className="w-3 h-3 text-blue-400 flex-shrink-0 mt-0.5" />+ <div className="text-xs text-blue-400">+ Maintain margin level above 50% for safe trading+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/index.tsnew file mode 100644index 000000000..6ab0b52a5--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/index.ts@@ -0,0 +1,7 @@+/**+ * Account Info Exports+ */++export { AccountStats } from './AccountStats';+export { FeesDisplay } from './FeesDisplay';+export { MarginPanel } from './MarginPanel';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/AdvancedOrderForm.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/AdvancedOrderForm.tsxnew file mode 100644index 000000000..fa2d0edf6--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/AdvancedOrderForm.tsx@@ -0,0 +1,264 @@+/**+ * Advanced Order Form+ * Stop-loss, take-profit, trailing stop (capability-based)+ */++import React, { useState } from 'react';+import type { UnifiedOrderRequest } from '../../types';+import { formatCurrency } from '../../utils/formatters';++const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ CYAN: '#00E5FF',+};++interface AdvancedOrderFormProps {+ currentPrice: number;+ supportsStopLoss: boolean;+ supportsTakeProfit: boolean;+ supportsTrailing: boolean;+ onOrderChange: (order: Partial<UnifiedOrderRequest>) => void;+}++export function AdvancedOrderForm({+ currentPrice,+ supportsStopLoss,+ supportsTakeProfit,+ supportsTrailing,+ onOrderChange,+}: AdvancedOrderFormProps) {+ const [showAdvanced, setShowAdvanced] = useState(false);+ const [stopLossPrice, setStopLossPrice] = useState<string>('');+ const [takeProfitPrice, setTakeProfitPrice] = useState<string>('');+ const [trailingPercent, setTrailingPercent] = useState<string>('');++ // Show advanced panel only if at least one feature is supported+ const hasAdvancedFeatures = supportsStopLoss || supportsTakeProfit || supportsTrailing;++ if (!hasAdvancedFeatures) {+ return null;+ }++ // Handle input changes+ const handleStopLossChange = (value: string) => {+ if (/^\d*\.?\d*$/.test(value) || value === '') {+ setStopLossPrice(value);+ onOrderChange({ stopLossPrice: value ? parseFloat(value) : undefined });+ }+ };++ const handleTakeProfitChange = (value: string) => {+ if (/^\d*\.?\d*$/.test(value) || value === '') {+ setTakeProfitPrice(value);+ onOrderChange({ takeProfitPrice: value ? parseFloat(value) : undefined });+ }+ };++ const handleTrailingChange = (value: string) => {+ if (/^\d*\.?\d*$/.test(value) || value === '') {+ setTrailingPercent(value);+ onOrderChange({ trailingPercent: value ? parseFloat(value) : undefined });+ }+ };++ return (+ <div style={{ marginTop: '8px' }}>+ {/* Toggle Button */}+ <button+ onClick={() => setShowAdvanced(!showAdvanced)}+ style={{+ width: '100%',+ padding: '8px',+ backgroundColor: showAdvanced ? `${BLOOMBERG.CYAN}15` : BLOOMBERG.PANEL_BG,+ border: `1px solid ${showAdvanced ? BLOOMBERG.CYAN : BLOOMBERG.BORDER}`,+ color: showAdvanced ? BLOOMBERG.CYAN : BLOOMBERG.GRAY,+ fontSize: '10px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ if (!showAdvanced) {+ e.currentTarget.style.borderColor = BLOOMBERG.CYAN;+ e.currentTarget.style.color = BLOOMBERG.CYAN;+ }+ }}+ onMouseLeave={(e) => {+ if (!showAdvanced) {+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ e.currentTarget.style.color = BLOOMBERG.GRAY;+ }+ }}+ >+ <span>⚡ ADVANCED OPTIONS</span>+ <span>{showAdvanced ? '▼' : '▶'}</span>+ </button>++ {/* Advanced Fields */}+ {showAdvanced && (+ <div+ style={{+ marginTop: '8px',+ padding: '12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ flexDirection: 'column',+ gap: '12px',+ }}+ >+ {/* Stop Loss */}+ {supportsStopLoss && (+ <div>+ <label+ style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ marginBottom: '4px',+ letterSpacing: '0.5px',+ }}+ >+ STOP LOSS+ </label>+ <input+ type="text"+ value={stopLossPrice}+ onChange={(e) => handleStopLossChange(e.target.value)}+ placeholder="Optional"+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.WHITE,+ fontSize: '11px',+ fontFamily: 'inherit',+ outline: 'none',+ }}+ onFocus={(e) => (e.target.style.borderColor = BLOOMBERG.RED)}+ onBlur={(e) => (e.target.style.borderColor = BLOOMBERG.BORDER)}+ />+ {stopLossPrice && (+ <div style={{ fontSize: '8px', color: BLOOMBERG.RED, marginTop: '4px' }}>+ {parseFloat(stopLossPrice) < currentPrice ? '↓' : '↑'}{' '}+ {Math.abs(((parseFloat(stopLossPrice) - currentPrice) / currentPrice) * 100).toFixed(2)}% from current+ </div>+ )}+ </div>+ )}++ {/* Take Profit */}+ {supportsTakeProfit && (+ <div>+ <label+ style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ marginBottom: '4px',+ letterSpacing: '0.5px',+ }}+ >+ TAKE PROFIT+ </label>+ <input+ type="text"+ value={takeProfitPrice}+ onChange={(e) => handleTakeProfitChange(e.target.value)}+ placeholder="Optional"+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.WHITE,+ fontSize: '11px',+ fontFamily: 'inherit',+ outline: 'none',+ }}+ onFocus={(e) => (e.target.style.borderColor = BLOOMBERG.GREEN)}+ onBlur={(e) => (e.target.style.borderColor = BLOOMBERG.BORDER)}+ />+ {takeProfitPrice && (+ <div style={{ fontSize: '8px', color: BLOOMBERG.GREEN, marginTop: '4px' }}>+ {parseFloat(takeProfitPrice) > currentPrice ? '↑' : '↓'}{' '}+ {Math.abs(((parseFloat(takeProfitPrice) - currentPrice) / currentPrice) * 100).toFixed(2)}% from current+ </div>+ )}+ </div>+ )}++ {/* Trailing Stop */}+ {supportsTrailing && (+ <div>+ <label+ style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ marginBottom: '4px',+ letterSpacing: '0.5px',+ }}+ >+ TRAILING STOP (%)+ </label>+ <input+ type="text"+ value={trailingPercent}+ onChange={(e) => handleTrailingChange(e.target.value)}+ placeholder="e.g. 2.5"+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.WHITE,+ fontSize: '11px',+ fontFamily: 'inherit',+ outline: 'none',+ }}+ onFocus={(e) => (e.target.style.borderColor = BLOOMBERG.ORANGE)}+ onBlur={(e) => (e.target.style.borderColor = BLOOMBERG.BORDER)}+ />+ {trailingPercent && (+ <div style={{ fontSize: '8px', color: BLOOMBERG.ORANGE, marginTop: '4px' }}>+ Trailing {trailingPercent}% ({formatCurrency((currentPrice * parseFloat(trailingPercent)) / 100)})+ </div>+ )}+ </div>+ )}++ {/* Info Message */}+ <div+ style={{+ padding: '8px',+ backgroundColor: `${BLOOMBERG.CYAN}10`,+ border: `1px solid ${BLOOMBERG.CYAN}40`,+ fontSize: '9px',+ color: BLOOMBERG.GRAY,+ lineHeight: '1.4',+ }}+ >+ 💡 Advanced orders help manage risk automatically. Stop-loss limits losses, take-profit locks in gains, and+ trailing stop follows price movements.+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/BasicOrderForm.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/BasicOrderForm.tsxnew file mode 100644index 000000000..70210d832--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/BasicOrderForm.tsx@@ -0,0 +1,254 @@+/**+ * Basic Order Form+ * Market and Limit orders (universal for all exchanges)+ */++import React, { useState, useEffect } from 'react';+import type { OrderType, OrderSide } from '../../../../../brokers/crypto/types';+import type { UnifiedOrderRequest } from '../../types';+import { formatPrice, formatCurrency } from '../../utils/formatters';++const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ YELLOW: '#FFD700',+};++interface BasicOrderFormProps {+ symbol: string;+ currentPrice: number;+ orderType: OrderType;+ side: OrderSide;+ onOrderChange: (order: Partial<UnifiedOrderRequest>) => void;+ balance?: number;+}++export function BasicOrderForm({+ symbol,+ currentPrice,+ orderType,+ side,+ onOrderChange,+ balance = 0,+}: BasicOrderFormProps) {+ const [quantity, setQuantity] = useState<string>('');+ const [price, setPrice] = useState<string>('');+ const [total, setTotal] = useState<number>(0);++ // Update price when current price changes+ useEffect(() => {+ if (orderType === 'market' || !price) {+ setPrice(currentPrice.toString());+ }+ }, [currentPrice, orderType]);++ // Calculate total whenever quantity or price changes+ useEffect(() => {+ const qty = parseFloat(quantity) || 0;+ const prc = parseFloat(price) || currentPrice;+ setTotal(qty * prc);++ // Notify parent of order changes+ onOrderChange({+ symbol,+ type: orderType,+ side,+ quantity: qty,+ price: orderType === 'limit' ? prc : undefined,+ });+ }, [quantity, price, symbol, orderType, side, currentPrice, onOrderChange]);++ // Handle quantity change+ const handleQuantityChange = (value: string) => {+ // Allow only numbers and decimal point+ if (/^\d*\.?\d*$/.test(value) || value === '') {+ setQuantity(value);+ }+ };++ // Handle price change+ const handlePriceChange = (value: string) => {+ if (/^\d*\.?\d*$/.test(value) || value === '') {+ setPrice(value);+ }+ };++ // Quick percentage buttons for quantity+ const handlePercentage = (percent: number) => {+ if (balance === 0 || currentPrice === 0) return;++ const prc = parseFloat(price) || currentPrice;+ const availableQty = (balance * percent) / prc;+ setQuantity(availableQty.toFixed(4));+ };++ // Calculate max quantity based on balance+ const maxQuantity = balance > 0 && currentPrice > 0 ? balance / currentPrice : 0;++ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ {/* Price Input (only for limit orders) */}+ {orderType === 'limit' && (+ <div>+ <label+ style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ marginBottom: '4px',+ letterSpacing: '0.5px',+ }}+ >+ PRICE+ </label>+ <input+ type="text"+ value={price}+ onChange={(e) => handlePriceChange(e.target.value)}+ placeholder="0.00"+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.WHITE,+ fontSize: '12px',+ fontFamily: 'inherit',+ outline: 'none',+ }}+ onFocus={(e) => (e.target.style.borderColor = BLOOMBERG.ORANGE)}+ onBlur={(e) => (e.target.style.borderColor = BLOOMBERG.BORDER)}+ />+ <div style={{ fontSize: '8px', color: BLOOMBERG.GRAY, marginTop: '4px' }}>+ Market: {formatCurrency(currentPrice)}+ </div>+ </div>+ )}++ {orderType === 'market' && (+ <div+ style={{+ padding: '8px',+ backgroundColor: `${BLOOMBERG.ORANGE}10`,+ border: `1px solid ${BLOOMBERG.ORANGE}40`,+ fontSize: '10px',+ color: BLOOMBERG.GRAY,+ }}+ >+ Market Price: <span style={{ color: BLOOMBERG.ORANGE, fontWeight: 700 }}>{formatCurrency(currentPrice)}</span>+ </div>+ )}++ {/* Quantity Input */}+ <div>+ <label+ style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ marginBottom: '4px',+ letterSpacing: '0.5px',+ }}+ >+ QUANTITY+ </label>+ <input+ type="text"+ value={quantity}+ onChange={(e) => handleQuantityChange(e.target.value)}+ placeholder="0.0000"+ style={{+ width: '100%',+ padding: '8px 10px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.WHITE,+ fontSize: '12px',+ fontFamily: 'inherit',+ outline: 'none',+ }}+ onFocus={(e) => (e.target.style.borderColor = BLOOMBERG.ORANGE)}+ onBlur={(e) => (e.target.style.borderColor = BLOOMBERG.BORDER)}+ />+ <div style={{ fontSize: '8px', color: BLOOMBERG.GRAY, marginTop: '4px' }}>+ Max: {maxQuantity.toFixed(4)} {symbol.split('/')[0]}+ </div>+ </div>++ {/* Percentage Buttons */}+ <div style={{ display: 'flex', gap: '4px' }}>+ {[0.25, 0.5, 0.75, 1.0].map((percent) => (+ <button+ key={percent}+ onClick={() => handlePercentage(percent)}+ style={{+ flex: 1,+ padding: '6px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ e.currentTarget.style.borderColor = BLOOMBERG.ORANGE;+ e.currentTarget.style.color = BLOOMBERG.ORANGE;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = BLOOMBERG.PANEL_BG;+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ e.currentTarget.style.color = BLOOMBERG.GRAY;+ }}+ >+ {percent * 100}%+ </button>+ ))}+ </div>++ {/* Total */}+ <div+ style={{+ padding: '10px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}+ >+ <span style={{ fontSize: '9px', color: BLOOMBERG.GRAY, fontWeight: 700 }}>TOTAL</span>+ <span style={{ fontSize: '13px', color: BLOOMBERG.YELLOW, fontWeight: 700 }}>+ {formatCurrency(total)}+ </span>+ </div>++ {/* Balance Warning */}+ {side === 'buy' && total > balance && (+ <div+ style={{+ padding: '8px',+ backgroundColor: `${BLOOMBERG.RED}10`,+ border: `1px solid ${BLOOMBERG.RED}40`,+ fontSize: '10px',+ color: BLOOMBERG.RED,+ }}+ >+ ⚠️ Insufficient balance (Available: {formatCurrency(balance)})+ </div>+ )}+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/EnhancedOrderForm.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/EnhancedOrderForm.tsxnew file mode 100644index 000000000..00365ed49--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/EnhancedOrderForm.tsx@@ -0,0 +1,276 @@+/**+ * Enhanced Order Form+ * Main orchestrator - capability-aware, exchange-agnostic+ */++import React, { useState, useCallback, useMemo } from 'react';+import { BasicOrderForm } from './BasicOrderForm';+import { AdvancedOrderForm } from './AdvancedOrderForm';+import { useExchangeCapabilities } from '../../hooks/useExchangeCapabilities';+import { useOrderExecution } from '../../hooks/useOrderExecution';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';+import { HyperLiquidLeverageControl } from '../../exchange-specific/hyperliquid';+import type { UnifiedOrderRequest } from '../../types';+import type { OrderType, OrderSide } from '../../../../../brokers/crypto/types';+import { validateOrder, formatValidationErrors } from '../../utils/orderValidation';++const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+};++interface EnhancedOrderFormProps {+ symbol: string;+ currentPrice: number;+ balance: number;+ onOrderPlaced?: () => void;+}++export function EnhancedOrderForm({ symbol, currentPrice, balance, onOrderPlaced }: EnhancedOrderFormProps) {+ const capabilities = useExchangeCapabilities();+ const { placeOrder, isPlacing, error } = useOrderExecution();+ const { activeBroker } = useBrokerContext();++ // Order state+ const [orderType, setOrderType] = useState<OrderType>('limit');+ const [side, setSide] = useState<OrderSide>('buy');+ const [orderData, setOrderData] = useState<Partial<UnifiedOrderRequest>>({});+ const [validationError, setValidationError] = useState<string>('');++ // Merge order data changes+ const handleOrderChange = useCallback((updates: Partial<UnifiedOrderRequest>) => {+ setOrderData((prev) => ({ ...prev, ...updates }));+ setValidationError(''); // Clear validation errors on change+ }, []);++ // Build complete order+ const completeOrder: UnifiedOrderRequest = useMemo(+ () => ({+ symbol,+ type: orderType,+ side,+ quantity: orderData.quantity || 0,+ price: orderData.price,+ stopLossPrice: orderData.stopLossPrice,+ takeProfitPrice: orderData.takeProfitPrice,+ trailingPercent: orderData.trailingPercent,+ }),+ [symbol, orderType, side, orderData]+ );++ // Handle order submission+ const handleSubmit = async () => {+ // Validate order+ const validation = validateOrder(completeOrder, capabilities, balance, currentPrice);++ if (!validation.valid) {+ setValidationError(formatValidationErrors(validation.errors));+ return;+ }++ try {+ await placeOrder(completeOrder);++ // Reset form on success+ setOrderData({});+ setValidationError('');++ // Notify parent+ if (onOrderPlaced) {+ onOrderPlaced();+ }++ alert(`✓ Order placed: ${side.toUpperCase()} ${orderData.quantity} ${symbol.split('/')[0]}`);+ } catch (err) {+ const error = err as Error;+ setValidationError(error.message);+ }+ };++ // Calculate if order is valid+ const canSubmit =+ orderData.quantity &&+ orderData.quantity > 0 &&+ (orderType !== 'limit' || (orderData.price && orderData.price > 0)) &&+ !isPlacing;++ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ {/* Order Type Selector */}+ <div>+ <label+ style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ marginBottom: '6px',+ letterSpacing: '0.5px',+ }}+ >+ ORDER TYPE+ </label>+ <div style={{ display: 'flex', gap: '4px' }}>+ {capabilities.supportedOrderTypes.map((type) => (+ <button+ key={type}+ onClick={() => setOrderType(type)}+ style={{+ flex: 1,+ padding: '8px 6px',+ backgroundColor: orderType === type ? BLOOMBERG.ORANGE : BLOOMBERG.PANEL_BG,+ border: `1px solid ${orderType === type ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,+ color: orderType === type ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ cursor: 'pointer',+ textTransform: 'uppercase',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ if (orderType !== type) {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ e.currentTarget.style.borderColor = BLOOMBERG.ORANGE;+ e.currentTarget.style.color = BLOOMBERG.ORANGE;+ }+ }}+ onMouseLeave={(e) => {+ if (orderType !== type) {+ e.currentTarget.style.backgroundColor = BLOOMBERG.PANEL_BG;+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;+ e.currentTarget.style.color = BLOOMBERG.GRAY;+ }+ }}+ >+ {type}+ </button>+ ))}+ </div>+ </div>++ {/* Side Selector */}+ <div style={{ display: 'flex', gap: '4px' }}>+ <button+ onClick={() => setSide('buy')}+ style={{+ flex: 1,+ padding: '10px',+ backgroundColor: side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.PANEL_BG,+ border: `2px solid ${side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.BORDER}`,+ color: side === 'buy' ? BLOOMBERG.DARK_BG : BLOOMBERG.GREEN,+ fontSize: '11px',+ fontWeight: 700,+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ >+ BUY+ </button>+ <button+ onClick={() => setSide('sell')}+ style={{+ flex: 1,+ padding: '10px',+ backgroundColor: side === 'sell' ? BLOOMBERG.RED : BLOOMBERG.PANEL_BG,+ border: `2px solid ${side === 'sell' ? BLOOMBERG.RED : BLOOMBERG.BORDER}`,+ color: side === 'sell' ? BLOOMBERG.WHITE : BLOOMBERG.RED,+ fontSize: '11px',+ fontWeight: 700,+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ >+ SELL+ </button>+ </div>++ {/* Basic Order Form */}+ <BasicOrderForm+ symbol={symbol}+ currentPrice={currentPrice}+ orderType={orderType}+ side={side}+ onOrderChange={handleOrderChange}+ balance={balance}+ />++ {/* Advanced Order Form (capability-based) */}+ <AdvancedOrderForm+ currentPrice={currentPrice}+ supportsStopLoss={capabilities.supportsStopLoss}+ supportsTakeProfit={capabilities.supportsTakeProfit}+ supportsTrailing={capabilities.supportsTrailingStop}+ onOrderChange={handleOrderChange}+ />++ {/* HyperLiquid Leverage Control (exchange-specific) */}+ {activeBroker === 'hyperliquid' && capabilities.supportsLeverage && (+ <HyperLiquidLeverageControl+ symbol={symbol}+ onLeverageChange={(lev) => handleOrderChange({ leverage: lev })}+ />+ )}++ {/* Validation Error */}+ {validationError && (+ <div+ style={{+ padding: '10px',+ backgroundColor: `${BLOOMBERG.RED}15`,+ border: `1px solid ${BLOOMBERG.RED}`,+ color: BLOOMBERG.RED,+ fontSize: '10px',+ whiteSpace: 'pre-line',+ }}+ >+ ⚠️ {validationError}+ </div>+ )}++ {/* Execution Error */}+ {error && (+ <div+ style={{+ padding: '10px',+ backgroundColor: `${BLOOMBERG.RED}15`,+ border: `1px solid ${BLOOMBERG.RED}`,+ color: BLOOMBERG.RED,+ fontSize: '10px',+ }}+ >+ ✗ {error.message}+ </div>+ )}++ {/* Submit Button */}+ <button+ onClick={handleSubmit}+ disabled={!canSubmit}+ style={{+ width: '100%',+ padding: '12px',+ backgroundColor: canSubmit ? (side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.RED) : BLOOMBERG.PANEL_BG,+ border: `2px solid ${canSubmit ? (side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.RED) : BLOOMBERG.BORDER}`,+ color: canSubmit ? BLOOMBERG.WHITE : BLOOMBERG.GRAY,+ fontSize: '12px',+ fontWeight: 700,+ cursor: canSubmit ? 'pointer' : 'not-allowed',+ textTransform: 'uppercase',+ letterSpacing: '1px',+ opacity: isPlacing ? 0.6 : 1,+ transition: 'all 0.2s',+ }}+ >+ {isPlacing ? '⟳ PLACING ORDER...' : `${side.toUpperCase()} ${symbol.split('/')[0]}`}+ </button>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/index.tsnew file mode 100644index 000000000..b719ec2ef--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/index.ts@@ -0,0 +1,7 @@+/**+ * OrderForm Module Exports+ */++export { BasicOrderForm } from './BasicOrderForm';+export { AdvancedOrderForm } from './AdvancedOrderForm';+export { EnhancedOrderForm } from './EnhancedOrderForm';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderManager/ClosedOrders.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderManager/ClosedOrders.tsxnew file mode 100644index 000000000..12579a0f9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderManager/ClosedOrders.tsx@@ -0,0 +1,175 @@+/**+ * Closed Orders History+ * Universal component - works with ALL exchanges (if supported)+ */++import React from 'react';+import { useClosedOrders } from '../../hooks/useOrders';+import { formatCurrency, formatDateTime, formatOrderStatus } from '../../utils/formatters';++const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+};++export function ClosedOrders() {+ const { closedOrders, isLoading, error } = useClosedOrders(undefined, 100);++ if (error) {+ return (+ <div+ style={{+ padding: '20px',+ textAlign: 'center',+ color: BLOOMBERG.GRAY,+ fontSize: '11px',+ }}+ >+ This exchange does not support closed orders history+ </div>+ );+ }++ if (isLoading) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: BLOOMBERG.GRAY, fontSize: '11px' }}>+ Loading order history...+ </div>+ );+ }++ if (closedOrders.length === 0) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: BLOOMBERG.GRAY, fontSize: '11px' }}>+ No closed orders+ </div>+ );+ }++ return (+ <div style={{ width: '100%', height: '100%', overflowX: 'auto', overflowY: 'auto' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>+ <thead style={{ position: 'sticky', top: 0, zIndex: 1 }}>+ <tr style={{ backgroundColor: BLOOMBERG.HEADER_BG, borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ SYMBOL+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ TYPE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ SIDE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ SIZE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ PRICE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ AVG FILL+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ COST+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ STATUS+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ TIME+ </th>+ </tr>+ </thead>+ <tbody>+ {closedOrders.map((order, index) => {+ const status = formatOrderStatus(order.status);++ return (+ <tr+ key={order.id}+ style={{+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ backgroundColor: index % 2 === 0 ? BLOOMBERG.DARK_BG : BLOOMBERG.PANEL_BG,+ }}+ >+ {/* Symbol */}+ <td style={{ padding: '10px', color: BLOOMBERG.WHITE, fontWeight: 600 }}>+ {order.symbol}+ </td>++ {/* Type */}+ <td style={{ padding: '10px', color: BLOOMBERG.GRAY, textTransform: 'uppercase', fontSize: '9px' }}>+ {order.type}+ </td>++ {/* Side */}+ <td style={{ padding: '10px' }}>+ <span+ style={{+ padding: '2px 6px',+ backgroundColor: order.side === 'buy' ? `${BLOOMBERG.GREEN}20` : `${BLOOMBERG.RED}20`,+ color: order.side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.RED,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ }}+ >+ {order.side.toUpperCase()}+ </span>+ </td>++ {/* Size */}+ <td style={{ padding: '10px', textAlign: 'right', color: BLOOMBERG.WHITE }}>+ {order.quantity.toFixed(4)}+ </td>++ {/* Price */}+ <td style={{ padding: '10px', textAlign: 'right', color: BLOOMBERG.GRAY }}>+ {order.price ? formatCurrency(order.price) : 'MARKET'}+ </td>++ {/* Average Fill */}+ <td style={{ padding: '10px', textAlign: 'right', color: BLOOMBERG.WHITE }}>+ {order.average ? formatCurrency(order.average) : '--'}+ </td>++ {/* Cost */}+ <td style={{ padding: '10px', textAlign: 'right', color: BLOOMBERG.ORANGE }}>+ {order.cost ? formatCurrency(order.cost) : '--'}+ </td>++ {/* Status */}+ <td style={{ padding: '10px' }}>+ <span+ style={{+ padding: '2px 6px',+ backgroundColor: `${status.color}20`,+ color: status.color,+ fontSize: '8px',+ fontWeight: 700,+ borderRadius: '2px',+ }}+ >+ {status.text}+ </span>+ </td>++ {/* Time */}+ <td style={{ padding: '10px', color: BLOOMBERG.GRAY, fontSize: '9px' }}>+ {formatDateTime(order.timestamp)}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderManager/OrdersTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderManager/OrdersTable.tsxnew file mode 100644index 000000000..cd1a02cb0--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderManager/OrdersTable.tsx@@ -0,0 +1,256 @@+/**+ * Orders Table+ * Universal component - works with ALL exchanges+ */++import React from 'react';+import { useOrders, useCancelOrder } from '../../hooks/useOrders';+import { formatPrice, formatCurrency, formatDateTime, formatOrderStatus } from '../../utils/formatters';+import type { UnifiedOrder } from '../../types';++const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+};++export function OrdersTable() {+ const { openOrders, isLoading, refresh } = useOrders(undefined, true, 2000);+ const { cancelOrder, cancelAllOrders, isCanceling } = useCancelOrder();++ const handleCancelOrder = async (order: UnifiedOrder) => {+ if (!confirm(`Cancel ${order.type} ${order.side} order for ${order.symbol}?`)) {+ return;+ }++ try {+ await cancelOrder(order.id, order.symbol);+ await refresh();+ alert(`✓ Order canceled: ${order.id}`);+ } catch (error) {+ alert(`✗ Failed to cancel order: ${(error as Error).message}`);+ }+ };++ const handleCancelAll = async () => {+ if (!confirm(`Cancel ALL open orders?`)) {+ return;+ }++ try {+ await cancelAllOrders();+ await refresh();+ alert('✓ All orders canceled');+ } catch (error) {+ alert(`✗ Failed to cancel all orders: ${(error as Error).message}`);+ }+ };++ if (isLoading && openOrders.length === 0) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: BLOOMBERG.GRAY, fontSize: '11px' }}>+ Loading orders...+ </div>+ );+ }++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Header with Cancel All button */}+ {openOrders.length > 0 && (+ <div+ style={{+ padding: '8px 12px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}+ >+ <span style={{ fontSize: '10px', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ OPEN ORDERS ({openOrders.length})+ </span>+ <button+ onClick={handleCancelAll}+ disabled={isCanceling}+ style={{+ padding: '4px 10px',+ backgroundColor: `${BLOOMBERG.RED}20`,+ border: `1px solid ${BLOOMBERG.RED}`,+ color: BLOOMBERG.RED,+ fontSize: '9px',+ fontWeight: 700,+ cursor: isCanceling ? 'not-allowed' : 'pointer',+ opacity: isCanceling ? 0.5 : 1,+ }}+ >+ CANCEL ALL+ </button>+ </div>+ )}++ {/* Orders Table */}+ <div style={{ flex: 1, overflowX: 'auto', overflowY: 'auto' }}>+ {openOrders.length === 0 ? (+ <div style={{ padding: '20px', textAlign: 'center', color: BLOOMBERG.GRAY, fontSize: '11px' }}>+ No open orders+ </div>+ ) : (+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>+ <thead style={{ position: 'sticky', top: 0, zIndex: 1 }}>+ <tr style={{ backgroundColor: BLOOMBERG.HEADER_BG, borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ SYMBOL+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ TYPE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ SIDE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ SIZE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ PRICE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ FILLED+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ STATUS+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ TIME+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'center', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ ACTION+ </th>+ </tr>+ </thead>+ <tbody>+ {openOrders.map((order, index) => {+ const status = formatOrderStatus(order.status);+ const fillPercent = (order.filled / order.quantity) * 100;++ return (+ <tr+ key={order.id}+ style={{+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ backgroundColor: index % 2 === 0 ? BLOOMBERG.DARK_BG : BLOOMBERG.PANEL_BG,+ }}+ >+ {/* Symbol */}+ <td style={{ padding: '10px', color: BLOOMBERG.WHITE, fontWeight: 600 }}>+ {order.symbol}+ </td>++ {/* Type */}+ <td style={{ padding: '10px', color: BLOOMBERG.GRAY, textTransform: 'uppercase' }}>+ {order.type}+ </td>++ {/* Side */}+ <td style={{ padding: '10px' }}>+ <span+ style={{+ padding: '2px 6px',+ backgroundColor: order.side === 'buy' ? `${BLOOMBERG.GREEN}20` : `${BLOOMBERG.RED}20`,+ color: order.side === 'buy' ? BLOOMBERG.GREEN : BLOOMBERG.RED,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ }}+ >+ {order.side.toUpperCase()}+ </span>+ </td>++ {/* Size */}+ <td style={{ padding: '10px', textAlign: 'right', color: BLOOMBERG.WHITE }}>+ {order.quantity.toFixed(4)}+ </td>++ {/* Price */}+ <td style={{ padding: '10px', textAlign: 'right', color: BLOOMBERG.GRAY }}>+ {order.price ? formatCurrency(order.price) : 'MARKET'}+ </td>++ {/* Filled */}+ <td style={{ padding: '10px', textAlign: 'right' }}>+ <div style={{ color: BLOOMBERG.WHITE }}>{order.filled.toFixed(4)}</div>+ <div style={{ fontSize: '8px', color: BLOOMBERG.GRAY }}>+ ({fillPercent.toFixed(0)}%)+ </div>+ </td>++ {/* Status */}+ <td style={{ padding: '10px' }}>+ <span+ style={{+ padding: '2px 6px',+ backgroundColor: `${status.color}20`,+ color: status.color,+ fontSize: '8px',+ fontWeight: 700,+ borderRadius: '2px',+ }}+ >+ {status.text}+ </span>+ </td>++ {/* Time */}+ <td style={{ padding: '10px', color: BLOOMBERG.GRAY, fontSize: '9px' }}>+ {formatDateTime(order.timestamp)}+ </td>++ {/* Action */}+ <td style={{ padding: '10px', textAlign: 'center' }}>+ <button+ onClick={() => handleCancelOrder(order)}+ disabled={isCanceling}+ style={{+ padding: '4px 10px',+ backgroundColor: 'transparent',+ border: `1px solid ${BLOOMBERG.RED}`,+ color: BLOOMBERG.RED,+ fontSize: '9px',+ fontWeight: 700,+ cursor: isCanceling ? 'not-allowed' : 'pointer',+ opacity: isCanceling ? 0.5 : 1,+ }}+ onMouseEnter={(e) => {+ if (!isCanceling) {+ e.currentTarget.style.backgroundColor = BLOOMBERG.RED;+ e.currentTarget.style.color = BLOOMBERG.WHITE;+ }+ }}+ onMouseLeave={(e) => {+ if (!isCanceling) {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.color = BLOOMBERG.RED;+ }+ }}+ >+ CANCEL+ </button>+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ )}+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderManager/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderManager/index.tsnew file mode 100644index 000000000..7ace305fc--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderManager/index.ts@@ -0,0 +1,6 @@+/**+ * Order Manager Exports+ */++export { OrdersTable } from './OrdersTable';+export { ClosedOrders } from './ClosedOrders';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsxnew file mode 100644index 000000000..3af43d86c--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx@@ -0,0 +1,190 @@+/**+ * Positions Table+ * Universal component - works with ALL exchanges+ */++import React from 'react';+import { usePositions, useClosePosition } from '../../hooks/usePositions';+import { useExchangeCapabilities } from '../../hooks/useExchangeCapabilities';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';+import { formatPrice, formatCurrency, formatPnL, formatLeverage } from '../../utils/formatters';+import type { UnifiedPosition } from '../../types';++const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+};++export function PositionsTable() {+ const { positions, isLoading, refresh } = usePositions(undefined, true, 2000);+ const { closePosition, isClosing } = useClosePosition();+ const capabilities = useExchangeCapabilities();+ const { activeBroker } = useBrokerContext();++ const handleClosePosition = async (position: UnifiedPosition) => {+ if (!confirm(`Close ${position.side.toUpperCase()} position for ${position.symbol}?`)) {+ return;+ }++ try {+ await closePosition(position);+ await refresh();+ alert(`✓ Position closed: ${position.symbol}`);+ } catch (error) {+ alert(`✗ Failed to close position: ${(error as Error).message}`);+ }+ };++ if (isLoading && positions.length === 0) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: BLOOMBERG.GRAY, fontSize: '11px' }}>+ Loading positions...+ </div>+ );+ }++ if (positions.length === 0) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: BLOOMBERG.GRAY, fontSize: '11px' }}>+ No open positions+ </div>+ );+ }++ return (+ <div style={{ width: '100%', overflowX: 'auto' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>+ <thead>+ <tr style={{ backgroundColor: BLOOMBERG.HEADER_BG, borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ SYMBOL+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ SIDE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ SIZE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ ENTRY+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ CURRENT+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ PNL+ </th>+ {capabilities.supportsLeverage && (+ <th style={{ padding: '8px 10px', textAlign: 'center', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ LEV+ </th>+ )}+ <th style={{ padding: '8px 10px', textAlign: 'center', color: BLOOMBERG.GRAY, fontWeight: 700 }}>+ ACTIONS+ </th>+ </tr>+ </thead>+ <tbody>+ {positions.map((position, index) => {+ const pnl = formatPnL(position.unrealizedPnl);++ return (+ <tr+ key={position.positionId || index}+ style={{+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ backgroundColor: index % 2 === 0 ? BLOOMBERG.DARK_BG : BLOOMBERG.PANEL_BG,+ }}+ >+ {/* Symbol */}+ <td style={{ padding: '10px', color: BLOOMBERG.WHITE, fontWeight: 600 }}>+ {position.symbol}+ </td>++ {/* Side */}+ <td style={{ padding: '10px' }}>+ <span+ style={{+ padding: '2px 6px',+ backgroundColor: position.side === 'long' ? `${BLOOMBERG.GREEN}20` : `${BLOOMBERG.RED}20`,+ color: position.side === 'long' ? BLOOMBERG.GREEN : BLOOMBERG.RED,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ }}+ >+ {position.side.toUpperCase()}+ </span>+ </td>++ {/* Size */}+ <td style={{ padding: '10px', textAlign: 'right', color: BLOOMBERG.WHITE }}>+ {position.quantity.toFixed(4)}+ </td>++ {/* Entry Price */}+ <td style={{ padding: '10px', textAlign: 'right', color: BLOOMBERG.GRAY }}>+ {formatCurrency(position.entryPrice)}+ </td>++ {/* Current Price */}+ <td style={{ padding: '10px', textAlign: 'right', color: BLOOMBERG.WHITE }}>+ {formatCurrency(position.currentPrice)}+ </td>++ {/* PnL */}+ <td style={{ padding: '10px', textAlign: 'right', color: pnl.color, fontWeight: 700 }}>+ {pnl.text}+ <div style={{ fontSize: '8px', color: BLOOMBERG.GRAY }}>+ ({pnl.sign}{position.pnlPercent.toFixed(2)}%)+ </div>+ </td>++ {/* Leverage (if supported) */}+ {capabilities.supportsLeverage && (+ <td style={{ padding: '10px', textAlign: 'center', color: BLOOMBERG.ORANGE, fontWeight: 700 }}>+ {formatLeverage(position.leverage || 1)}+ </td>+ )}++ {/* Actions */}+ <td style={{ padding: '10px', textAlign: 'center' }}>+ <button+ onClick={() => handleClosePosition(position)}+ disabled={isClosing}+ style={{+ padding: '4px 10px',+ backgroundColor: BLOOMBERG.RED,+ border: 'none',+ color: BLOOMBERG.WHITE,+ fontSize: '9px',+ fontWeight: 700,+ cursor: isClosing ? 'not-allowed' : 'pointer',+ opacity: isClosing ? 0.5 : 1,+ }}+ onMouseEnter={(e) => {+ if (!isClosing) e.currentTarget.style.opacity = '0.8';+ }}+ onMouseLeave={(e) => {+ if (!isClosing) e.currentTarget.style.opacity = '1';+ }}+ >+ CLOSE+ </button>+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/index.tsnew file mode 100644index 000000000..9d5caadd2--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/index.ts@@ -0,0 +1,5 @@+/**+ * Position Manager Exports+ */++export { PositionsTable } from './PositionsTable';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/ArbitrageDetector.tsx b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/ArbitrageDetector.tsxnew file mode 100644index 000000000..812f9c923--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/ArbitrageDetector.tsx@@ -0,0 +1,198 @@+/**+ * ArbitrageDetector - Real-time arbitrage opportunity detection across exchanges+ */++import React from 'react';+import { Zap, RefreshCw, Loader, TrendingUp, Clock, AlertTriangle, ExternalLink } from 'lucide-react';+import { useArbitrageDetection } from '../hooks/useCrossExchange';++export function ArbitrageDetector() {+ const { opportunities, isScanning, lastScanTime, scan } = useArbitrageDetection();++ const formatPrice = (price: number): string => {+ return price.toLocaleString('en-US', {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ });+ };++ const formatTime = (timestamp: number): string => {+ const seconds = Math.floor((Date.now() - timestamp) / 1000);+ if (seconds < 60) return `${seconds}s ago`;+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m ago`;+ const hours = Math.floor(minutes / 60);+ return `${hours}h ago`;+ };++ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-6">+ {/* Header */}+ <div className="flex items-center justify-between mb-6">+ <div className="flex items-center gap-2">+ <Zap className="w-5 h-5 text-yellow-500" />+ <span className="text-lg font-semibold text-white">Arbitrage Opportunities</span>+ </div>+ <div className="flex items-center gap-3">+ {lastScanTime && (+ <div className="flex items-center gap-1 text-xs text-gray-500">+ <Clock className="w-3 h-3" />+ {formatTime(lastScanTime)}+ </div>+ )}+ <button+ onClick={scan}+ disabled={isScanning}+ className="px-3 py-1 text-xs text-yellow-400 hover:text-yellow-300 border border-yellow-500/30 hover:border-yellow-400/50 rounded transition flex items-center gap-1 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ <RefreshCw className={`w-3 h-3 ${isScanning ? 'animate-spin' : ''}`} />+ {isScanning ? 'Scanning...' : 'Scan'}+ </button>+ </div>+ </div>++ {/* Risk Warning */}+ <div className="mb-6 p-3 bg-yellow-500/10 border border-yellow-500/20 rounded flex items-start gap-2">+ <AlertTriangle className="w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5" />+ <div className="text-xs text-yellow-400">+ <strong>Risk Warning:</strong> Arbitrage opportunities include trading fees, withdrawal+ fees, and execution risk. Always calculate net profit after all costs. Prices can change+ rapidly.+ </div>+ </div>++ {/* Scanning Status */}+ {isScanning && (+ <div className="mb-4 p-3 bg-blue-500/10 border border-blue-500/20 rounded flex items-center gap-2">+ <Loader className="w-4 h-4 text-blue-500 animate-spin" />+ <span className="text-sm text-blue-400">Scanning for arbitrage opportunities...</span>+ </div>+ )}++ {/* Opportunities List */}+ <div className="space-y-3">+ {opportunities.length === 0 ? (+ <div className="text-center py-8 text-gray-500">+ <Zap className="w-12 h-12 mx-auto mb-3 text-gray-600" />+ <div className="text-sm">No arbitrage opportunities found</div>+ <div className="text-xs mt-1">Spread must be > 0.2% to be considered viable</div>+ </div>+ ) : (+ opportunities.map((opp, idx) => (+ <div+ key={idx}+ className="p-4 bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-2 border-yellow-500/30 rounded hover:border-yellow-400/50 transition"+ >+ {/* Opportunity Header */}+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-3">+ <div className="flex items-center gap-1 text-yellow-500">+ <Zap className="w-5 h-5 fill-current" />+ <span className="text-lg font-bold text-white">{opp.symbol}</span>+ </div>+ <div className="px-2 py-0.5 bg-yellow-500/20 border border-yellow-500/30 rounded text-xs text-yellow-400 font-semibold">+ {opp.spreadPercent.toFixed(2)}% Spread+ </div>+ </div>+ <div className="text-right">+ <div className="text-sm text-gray-400">Potential Profit</div>+ <div className="text-xl font-bold text-green-500">+ ${opp.potentialProfit.toFixed(2)}+ </div>+ </div>+ </div>++ {/* Trade Details */}+ <div className="grid grid-cols-2 gap-4 mb-3">+ {/* Buy Side */}+ <div className="p-3 bg-green-500/10 border border-green-500/20 rounded">+ <div className="text-xs text-gray-400 mb-1">BUY ON</div>+ <div className="text-sm font-semibold text-white capitalize mb-2">+ {opp.buyExchange}+ </div>+ <div className="flex items-center gap-2">+ <TrendingUp className="w-4 h-4 text-green-500" />+ <span className="text-lg font-bold text-green-500">+ ${formatPrice(opp.buyPrice)}+ </span>+ </div>+ </div>++ {/* Sell Side */}+ <div className="p-3 bg-red-500/10 border border-red-500/20 rounded">+ <div className="text-xs text-gray-400 mb-1">SELL ON</div>+ <div className="text-sm font-semibold text-white capitalize mb-2">+ {opp.sellExchange}+ </div>+ <div className="flex items-center gap-2">+ <TrendingUp className="w-4 h-4 text-red-500 rotate-180" />+ <span className="text-lg font-bold text-red-500">+ ${formatPrice(opp.sellPrice)}+ </span>+ </div>+ </div>+ </div>++ {/* Spread Info */}+ <div className="p-2 bg-black/30 rounded mb-3">+ <div className="flex items-center justify-between text-xs">+ <span className="text-gray-400">Price Difference:</span>+ <span className="text-white font-semibold">${opp.spread.toFixed(2)}</span>+ </div>+ </div>++ {/* Action Buttons */}+ <div className="flex gap-2">+ <button className="flex-1 px-3 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold rounded transition flex items-center justify-center gap-1">+ <TrendingUp className="w-4 h-4" />+ Execute Arbitrage+ </button>+ <button className="px-3 py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm rounded transition">+ <ExternalLink className="w-4 h-4" />+ </button>+ </div>++ {/* Timestamp */}+ <div className="mt-2 text-xs text-gray-500 text-center">+ Detected {formatTime(opp.timestamp)}+ </div>+ </div>+ ))+ )}+ </div>++ {/* Info Section */}+ <div className="mt-6 space-y-2">+ <div className="p-3 bg-gray-800/50 border border-gray-700 rounded">+ <div className="text-xs font-semibold text-gray-300 mb-2">How It Works</div>+ <div className="text-xs text-gray-400 space-y-1">+ <div>+ 1. <strong>Buy</strong> the asset on the exchange with the lower price+ </div>+ <div>+ 2. <strong>Transfer</strong> the asset to the exchange with the higher price+ </div>+ <div>+ 3. <strong>Sell</strong> the asset for profit+ </div>+ </div>+ </div>++ <div className="p-3 bg-blue-500/10 border border-blue-500/20 rounded">+ <div className="text-xs text-blue-400">+ <strong>Cost Considerations:</strong> Factor in trading fees (maker/taker), withdrawal+ fees, network fees, and execution time. The spread must exceed total costs for+ profitable arbitrage.+ </div>+ </div>++ <div className="p-3 bg-purple-500/10 border border-purple-500/20 rounded">+ <div className="text-xs text-purple-400">+ <strong>Auto-Scan:</strong> Opportunities are automatically scanned every 10 seconds.+ Click "Scan" to manually refresh.+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsx b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsxnew file mode 100644index 000000000..70ebac531--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsx@@ -0,0 +1,160 @@+/**+ * PortfolioAggregator - Unified view of balances across all exchanges+ */++import React from 'react';+import { Wallet, TrendingUp, RefreshCw, Loader, PieChart } from 'lucide-react';+import { useCrossExchangePortfolio } from '../hooks/useCrossExchange';++export function PortfolioAggregator() {+ const { aggregatedBalances, totalPortfolioValue, isLoading, error, refresh } =+ useCrossExchangePortfolio();++ const formatCurrency = (value: number): string => {+ return value.toLocaleString('en-US', {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ });+ };++ const formatCrypto = (value: number, decimals: number = 4): string => {+ return value.toLocaleString('en-US', {+ minimumFractionDigits: decimals,+ maximumFractionDigits: decimals,+ });+ };++ if (isLoading) {+ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-6">+ <div className="flex items-center justify-center py-8">+ <Loader className="w-6 h-6 text-blue-500 animate-spin" />+ </div>+ </div>+ );+ }++ if (error) {+ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-6">+ <div className="text-center py-8 text-red-500">{error}</div>+ </div>+ );+ }++ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-6">+ {/* Header */}+ <div className="flex items-center justify-between mb-6">+ <div className="flex items-center gap-2">+ <PieChart className="w-5 h-5 text-blue-500" />+ <span className="text-lg font-semibold text-white">Cross-Exchange Portfolio</span>+ </div>+ <div className="flex items-center gap-3">+ <button+ onClick={refresh}+ className="px-3 py-1 text-xs text-blue-400 hover:text-blue-300 border border-blue-500/30 hover:border-blue-400/50 rounded transition flex items-center gap-1"+ >+ <RefreshCw className="w-3 h-3" />+ Refresh+ </button>+ </div>+ </div>++ {/* Total Portfolio Value */}+ <div className="mb-6 p-4 bg-gradient-to-r from-blue-500/10 to-purple-500/10 border border-blue-500/20 rounded">+ <div className="text-xs text-gray-400 mb-1">Total Portfolio Value</div>+ <div className="flex items-center gap-3">+ <div className="text-3xl font-bold text-white">${formatCurrency(totalPortfolioValue)}</div>+ <div className="flex items-center gap-1 text-green-500 text-sm">+ <TrendingUp className="w-4 h-4" />+ <span>+2.45%</span>+ </div>+ </div>+ <div className="text-xs text-gray-500 mt-1">Across {aggregatedBalances.length} assets</div>+ </div>++ {/* Aggregated Balances */}+ <div className="space-y-3">+ <div className="text-sm font-semibold text-gray-400 mb-3">Asset Breakdown</div>++ {aggregatedBalances.length === 0 ? (+ <div className="text-center py-8 text-gray-500">+ <Wallet className="w-12 h-12 mx-auto mb-3 text-gray-600" />+ <div className="text-sm">No balances found</div>+ </div>+ ) : (+ aggregatedBalances+ .sort((a, b) => b.totalUsdValue - a.totalUsdValue)+ .map((balance) => (+ <div+ key={balance.currency}+ className="p-4 bg-gray-800/50 border border-gray-700 rounded hover:border-gray-600 transition"+ >+ {/* Currency Header */}+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-3">+ <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-500 rounded-full flex items-center justify-center text-white font-bold text-sm">+ {balance.currency.substring(0, 2)}+ </div>+ <div>+ <div className="text-white font-semibold">{balance.currency}</div>+ <div className="text-xs text-gray-500">+ {formatCrypto(balance.totalAmount)} {balance.currency}+ </div>+ </div>+ </div>+ <div className="text-right">+ <div className="text-white font-semibold">+ ${formatCurrency(balance.totalUsdValue)}+ </div>+ <div className="text-xs text-gray-500">+ {((balance.totalUsdValue / totalPortfolioValue) * 100).toFixed(2)}%+ </div>+ </div>+ </div>++ {/* Exchange Breakdown */}+ <div className="space-y-2 pl-13">+ {balance.exchanges.map((exch, idx) => (+ <div+ key={idx}+ className="flex items-center justify-between text-xs p-2 bg-black/20 rounded"+ >+ <div className="flex items-center gap-2">+ <span className="px-2 py-0.5 bg-gray-700 rounded text-gray-300 capitalize">+ {exch.exchange}+ </span>+ <span className="text-gray-400">+ {formatCrypto(exch.amount)} {balance.currency}+ </span>+ </div>+ <span className="text-gray-300">${formatCurrency(exch.usdValue)}</span>+ </div>+ ))}+ </div>++ {/* Progress Bar */}+ <div className="mt-3 h-2 bg-gray-700 rounded-full overflow-hidden">+ <div+ className="h-full bg-gradient-to-r from-blue-500 to-purple-500 transition-all"+ style={{+ width: `${(balance.totalUsdValue / totalPortfolioValue) * 100}%`,+ }}+ ></div>+ </div>+ </div>+ ))+ )}+ </div>++ {/* Info Note */}+ <div className="mt-6 p-3 bg-blue-500/10 border border-blue-500/20 rounded">+ <div className="text-xs text-blue-400">+ <strong>Note:</strong> This view aggregates balances from all connected exchanges. Values+ are updated every 30 seconds. Exchange-specific details are shown for each asset.+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/index.tsnew file mode 100644index 000000000..6cd51e697--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/index.ts@@ -0,0 +1,6 @@+/**+ * Cross-Exchange Components Exports+ */++export { PortfolioAggregator } from './PortfolioAggregator';+export { ArbitrageDetector } from './ArbitrageDetector';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/hyperliquid/LeverageControl.tsx b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/hyperliquid/LeverageControl.tsxnew file mode 100644index 000000000..051d6431e--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/hyperliquid/LeverageControl.tsx@@ -0,0 +1,214 @@+/**+ * HyperLiquid Leverage Control+ * Set leverage (1x-50x) and margin mode+ */++import React, { useState } from 'react';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+};++interface LeverageControlProps {+ symbol: string;+ currentLeverage?: number;+ onLeverageChange?: (leverage: number) => void;+}++export function HyperLiquidLeverageControl({ symbol, currentLeverage = 1, onLeverageChange }: LeverageControlProps) {+ const { activeBroker, activeAdapter } = useBrokerContext();+ const [leverage, setLeverage] = useState(currentLeverage);+ const [marginMode, setMarginMode] = useState<'cross' | 'isolated'>('cross');+ const [isUpdating, setIsUpdating] = useState(false);++ if (activeBroker !== 'hyperliquid') {+ return null;+ }++ const handleLeverageChange = async (newLeverage: number) => {+ if (!activeAdapter) return;++ setLeverage(newLeverage);++ // Update on exchange+ setIsUpdating(true);+ try {+ await (activeAdapter as any).setLeverage(symbol, newLeverage);+ if (onLeverageChange) {+ onLeverageChange(newLeverage);+ }+ } catch (error) {+ console.error('Failed to set leverage:', error);+ } finally {+ setIsUpdating(false);+ }+ };++ const handleMarginModeChange = async (mode: 'cross' | 'isolated') => {+ if (!activeAdapter) return;++ setMarginMode(mode);++ setIsUpdating(true);+ try {+ await (activeAdapter as any).setMarginMode(symbol, mode);+ } catch (error) {+ console.error('Failed to set margin mode:', error);+ } finally {+ setIsUpdating(false);+ }+ };++ const quickLeverages = [1, 2, 5, 10, 20, 50];++ return (+ <div style={{ marginTop: '12px' }}>+ {/* Leverage Slider */}+ <div style={{ marginBottom: '12px' }}>+ <div+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '6px',+ }}+ >+ <label+ style={{+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ letterSpacing: '0.5px',+ }}+ >+ LEVERAGE+ </label>+ <span+ style={{+ fontSize: '12px',+ fontWeight: 700,+ color: leverage > 10 ? BLOOMBERG.RED : BLOOMBERG.ORANGE,+ }}+ >+ {leverage}x+ </span>+ </div>++ <input+ type="range"+ min="1"+ max="50"+ value={leverage}+ onChange={(e) => handleLeverageChange(parseInt(e.target.value))}+ disabled={isUpdating}+ style={{+ width: '100%',+ height: '4px',+ backgroundColor: BLOOMBERG.BORDER,+ outline: 'none',+ opacity: isUpdating ? 0.5 : 1,+ }}+ />++ {/* Quick Leverage Buttons */}+ <div style={{ display: 'flex', gap: '4px', marginTop: '6px' }}>+ {quickLeverages.map((lev) => (+ <button+ key={lev}+ onClick={() => handleLeverageChange(lev)}+ disabled={isUpdating}+ style={{+ flex: 1,+ padding: '4px',+ backgroundColor: leverage === lev ? BLOOMBERG.ORANGE : BLOOMBERG.PANEL_BG,+ border: `1px solid ${leverage === lev ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,+ color: leverage === lev ? BLOOMBERG.PANEL_BG : BLOOMBERG.GRAY,+ fontSize: '8px',+ fontWeight: 700,+ cursor: isUpdating ? 'not-allowed' : 'pointer',+ opacity: isUpdating ? 0.5 : 1,+ }}+ >+ {lev}x+ </button>+ ))}+ </div>+ </div>++ {/* Margin Mode */}+ <div>+ <label+ style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ marginBottom: '6px',+ letterSpacing: '0.5px',+ }}+ >+ MARGIN MODE+ </label>+ <div style={{ display: 'flex', gap: '4px' }}>+ <button+ onClick={() => handleMarginModeChange('cross')}+ disabled={isUpdating}+ style={{+ flex: 1,+ padding: '6px',+ backgroundColor: marginMode === 'cross' ? BLOOMBERG.GREEN : BLOOMBERG.PANEL_BG,+ border: `1px solid ${marginMode === 'cross' ? BLOOMBERG.GREEN : BLOOMBERG.BORDER}`,+ color: marginMode === 'cross' ? BLOOMBERG.PANEL_BG : BLOOMBERG.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ cursor: isUpdating ? 'not-allowed' : 'pointer',+ opacity: isUpdating ? 0.5 : 1,+ }}+ >+ CROSS+ </button>+ <button+ onClick={() => handleMarginModeChange('isolated')}+ disabled={isUpdating}+ style={{+ flex: 1,+ padding: '6px',+ backgroundColor: marginMode === 'isolated' ? BLOOMBERG.ORANGE : BLOOMBERG.PANEL_BG,+ border: `1px solid ${marginMode === 'isolated' ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,+ color: marginMode === 'isolated' ? BLOOMBERG.PANEL_BG : BLOOMBERG.GRAY,+ fontSize: '9px',+ fontWeight: 700,+ cursor: isUpdating ? 'not-allowed' : 'pointer',+ opacity: isUpdating ? 0.5 : 1,+ }}+ >+ ISOLATED+ </button>+ </div>+ </div>++ {/* Warning for high leverage */}+ {leverage > 20 && (+ <div+ style={{+ marginTop: '8px',+ padding: '6px 8px',+ backgroundColor: `${BLOOMBERG.RED}15`,+ border: `1px solid ${BLOOMBERG.RED}40`,+ fontSize: '8px',+ color: BLOOMBERG.RED,+ }}+ >+ ⚠️ High leverage ({leverage}x) increases liquidation risk+ </div>+ )}+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/hyperliquid/VaultManager.tsx b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/hyperliquid/VaultManager.tsxnew file mode 100644index 000000000..b0f5062d0--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/hyperliquid/VaultManager.tsx@@ -0,0 +1,203 @@+/**+ * HyperLiquid Vault Manager+ * Manage vault trading and subaccounts+ */++import React, { useState, useEffect } from 'react';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const BLOOMBERG = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ GREEN: '#00D66F',+ GRAY: '#787878',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ CYAN: '#00E5FF',+};++export function HyperLiquidVaultManager() {+ const { activeBroker, activeAdapter } = useBrokerContext();+ const [vaultAddress, setVaultAddress] = useState('');+ const [subAccountAddress, setSubAccountAddress] = useState('');+ const [vaultBalance, setVaultBalance] = useState<any>(null);+ const [isLoading, setIsLoading] = useState(false);++ // Only show for HyperLiquid+ if (activeBroker !== 'hyperliquid') {+ return null;+ }++ const handleSetVault = async () => {+ if (!vaultAddress || !activeAdapter) return;++ setIsLoading(true);+ try {+ (activeAdapter as any).setVaultAddress(vaultAddress);+ const balance = await (activeAdapter as any).fetchVaultBalance(vaultAddress);+ setVaultBalance(balance);+ alert(`✓ Vault connected: ${vaultAddress.slice(0, 8)}...`);+ } catch (error) {+ alert(`✗ Vault connection failed: ${(error as Error).message}`);+ } finally {+ setIsLoading(false);+ }+ };++ const handleSetSubAccount = () => {+ if (!subAccountAddress || !activeAdapter) return;+ (activeAdapter as any).setSubAccountAddress(subAccountAddress);+ alert(`✓ Subaccount set: ${subAccountAddress.slice(0, 8)}...`);+ };++ return (+ <div+ style={{+ padding: '12px',+ backgroundColor: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ marginTop: '12px',+ }}+ >+ {/* Header */}+ <div+ style={{+ fontSize: '10px',+ fontWeight: 700,+ color: BLOOMBERG.ORANGE,+ marginBottom: '12px',+ letterSpacing: '0.5px',+ }}+ >+ ⚡ HYPERLIQUID VAULT & SUBACCOUNTS+ </div>++ {/* Vault Address */}+ <div style={{ marginBottom: '12px' }}>+ <label+ style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ marginBottom: '4px',+ }}+ >+ VAULT ADDRESS+ </label>+ <div style={{ display: 'flex', gap: '4px' }}>+ <input+ type="text"+ value={vaultAddress}+ onChange={(e) => setVaultAddress(e.target.value)}+ placeholder="0x..."+ style={{+ flex: 1,+ padding: '6px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.WHITE,+ fontSize: '10px',+ fontFamily: 'inherit',+ }}+ />+ <button+ onClick={handleSetVault}+ disabled={isLoading || !vaultAddress}+ style={{+ padding: '6px 12px',+ backgroundColor: BLOOMBERG.CYAN,+ border: 'none',+ color: BLOOMBERG.PANEL_BG,+ fontSize: '9px',+ fontWeight: 700,+ cursor: !vaultAddress || isLoading ? 'not-allowed' : 'pointer',+ opacity: !vaultAddress || isLoading ? 0.5 : 1,+ }}+ >+ {isLoading ? '...' : 'CONNECT'}+ </button>+ </div>+ </div>++ {/* Subaccount Address */}+ <div style={{ marginBottom: '12px' }}>+ <label+ style={{+ display: 'block',+ fontSize: '9px',+ fontWeight: 700,+ color: BLOOMBERG.GRAY,+ marginBottom: '4px',+ }}+ >+ SUBACCOUNT ADDRESS+ </label>+ <div style={{ display: 'flex', gap: '4px' }}>+ <input+ type="text"+ value={subAccountAddress}+ onChange={(e) => setSubAccountAddress(e.target.value)}+ placeholder="0x..."+ style={{+ flex: 1,+ padding: '6px 8px',+ backgroundColor: BLOOMBERG.HEADER_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ color: BLOOMBERG.WHITE,+ fontSize: '10px',+ fontFamily: 'inherit',+ }}+ />+ <button+ onClick={handleSetSubAccount}+ disabled={!subAccountAddress}+ style={{+ padding: '6px 12px',+ backgroundColor: BLOOMBERG.GREEN,+ border: 'none',+ color: BLOOMBERG.PANEL_BG,+ fontSize: '9px',+ fontWeight: 700,+ cursor: !subAccountAddress ? 'not-allowed' : 'pointer',+ opacity: !subAccountAddress ? 0.5 : 1,+ }}+ >+ SET+ </button>+ </div>+ </div>++ {/* Vault Balance */}+ {vaultBalance && (+ <div+ style={{+ padding: '8px',+ backgroundColor: `${BLOOMBERG.CYAN}15`,+ border: `1px solid ${BLOOMBERG.CYAN}40`,+ fontSize: '9px',+ color: BLOOMBERG.CYAN,+ }}+ >+ ✓ Vault Balance: ${vaultBalance.total?.USD?.toFixed(2) || '0.00'}+ </div>+ )}++ {/* Info */}+ <div+ style={{+ marginTop: '12px',+ padding: '8px',+ backgroundColor: `${BLOOMBERG.ORANGE}10`,+ border: `1px solid ${BLOOMBERG.ORANGE}40`,+ fontSize: '8px',+ color: BLOOMBERG.GRAY,+ lineHeight: '1.4',+ }}+ >+ 💡 HyperLiquid vaults allow you to trade from a vault address. Subaccounts enable multi-strategy trading.+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/hyperliquid/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/hyperliquid/index.tsnew file mode 100644index 000000000..59692ad18--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/hyperliquid/index.ts@@ -0,0 +1,6 @@+/**+ * HyperLiquid Exchange-Specific Components+ */++export { HyperLiquidVaultManager } from './VaultManager';+export { HyperLiquidLeverageControl } from './LeverageControl';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/FuturesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/FuturesPanel.tsxnew file mode 100644index 000000000..1955482e8--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/FuturesPanel.tsx@@ -0,0 +1,339 @@+/**+ * FuturesPanel - Kraken futures trading interface+ */++import React, { useState, useCallback, useEffect } from 'react';+import { TrendingUp, Activity, AlertTriangle, ExternalLink, Loader } from 'lucide-react';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++interface FuturesMarket {+ symbol: string;+ baseAsset: string;+ quoteAsset: string;+ price: number;+ change24h: number;+ volume24h: number;+ openInterest: number;+ fundingRate: number;+ nextFunding: string;+ maxLeverage: number;+}++export function FuturesPanel() {+ const { activeBroker, activeAdapter } = useBrokerContext();+ const [futuresMarkets, setFuturesMarkets] = useState<FuturesMarket[]>([]);+ const [selectedMarket, setSelectedMarket] = useState<FuturesMarket | null>(null);+ const [isLoading, setIsLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ // Fetch futures markets on mount+ useEffect(() => {+ if (activeBroker === 'kraken') {+ fetchFuturesMarkets();+ }+ }, [activeBroker]);++ const fetchFuturesMarkets = useCallback(async () => {+ setIsLoading(true);+ setError(null);+ try {+ // Mock futures data (in production, fetch from Kraken Futures API)+ const mockMarkets: FuturesMarket[] = [+ {+ symbol: 'PF_BTCUSD',+ baseAsset: 'BTC',+ quoteAsset: 'USD',+ price: 43250.5,+ change24h: 2.35,+ volume24h: 1234567890,+ openInterest: 567890000,+ fundingRate: 0.0001,+ nextFunding: '4h 23m',+ maxLeverage: 50,+ },+ {+ symbol: 'PF_ETHUSD',+ baseAsset: 'ETH',+ quoteAsset: 'USD',+ price: 2345.67,+ change24h: -1.23,+ volume24h: 456789012,+ openInterest: 234567000,+ fundingRate: 0.00005,+ nextFunding: '4h 23m',+ maxLeverage: 50,+ },+ {+ symbol: 'PF_SOLUSD',+ baseAsset: 'SOL',+ quoteAsset: 'USD',+ price: 98.45,+ change24h: 5.67,+ volume24h: 123456789,+ openInterest: 45678900,+ fundingRate: 0.00015,+ nextFunding: '4h 23m',+ maxLeverage: 25,+ },+ {+ symbol: 'PF_XRPUSD',+ baseAsset: 'XRP',+ quoteAsset: 'USD',+ price: 0.5234,+ change24h: 3.45,+ volume24h: 89012345,+ openInterest: 23456789,+ fundingRate: -0.00002,+ nextFunding: '4h 23m',+ maxLeverage: 20,+ },+ ];++ setFuturesMarkets(mockMarkets);+ if (mockMarkets.length > 0 && !selectedMarket) {+ setSelectedMarket(mockMarkets[0]);+ }+ } catch (err) {+ setError('Failed to fetch futures markets');+ console.error('Futures fetch error:', err);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, selectedMarket]);++ const formatNumber = (num: number, decimals: number = 2): string => {+ return num.toLocaleString('en-US', {+ minimumFractionDigits: decimals,+ maximumFractionDigits: decimals,+ });+ };++ const formatLargeNumber = (num: number): string => {+ if (num >= 1e9) return `$${(num / 1e9).toFixed(2)}B`;+ if (num >= 1e6) return `$${(num / 1e6).toFixed(2)}M`;+ if (num >= 1e3) return `$${(num / 1e3).toFixed(2)}K`;+ return `$${num.toFixed(2)}`;+ };++ if (activeBroker !== 'kraken') {+ return null;+ }++ if (isLoading) {+ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-6">+ <div className="flex items-center justify-center py-8">+ <Loader className="w-6 h-6 text-blue-500 animate-spin" />+ </div>+ </div>+ );+ }++ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-6">+ {/* Header */}+ <div className="flex items-center justify-between mb-6">+ <div className="flex items-center gap-2">+ <Activity className="w-5 h-5 text-purple-500" />+ <span className="text-lg font-semibold text-white">Kraken Futures</span>+ </div>+ <div className="flex items-center gap-3">+ <button+ onClick={fetchFuturesMarkets}+ className="px-3 py-1 text-xs text-blue-400 hover:text-blue-300 border border-blue-500/30 hover:border-blue-400/50 rounded transition"+ >+ Refresh+ </button>+ <a+ href="https://futures.kraken.com"+ target="_blank"+ rel="noopener noreferrer"+ className="px-3 py-1 text-xs text-gray-400 hover:text-gray-300 border border-gray-700 hover:border-gray-600 rounded transition flex items-center gap-1"+ >+ <ExternalLink className="w-3 h-3" />+ Kraken Futures+ </a>+ </div>+ </div>++ {/* Warning Banner */}+ <div className="mb-6 p-3 bg-yellow-500/10 border border-yellow-500/20 rounded flex items-start gap-2">+ <AlertTriangle className="w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5" />+ <div className="text-xs text-yellow-400">+ <strong>Futures Trading Risk Warning:</strong> Futures trading involves high risk and+ leverage. Only trade with funds you can afford to lose. Requires separate Kraken Futures+ account.+ </div>+ </div>++ {/* Markets Grid */}+ {futuresMarkets.length === 0 ? (+ <div className="text-center py-8 text-gray-500">+ <Activity className="w-12 h-12 mx-auto mb-3 text-gray-600" />+ <div className="text-sm">No futures markets available</div>+ </div>+ ) : (+ <div className="space-y-4">+ {/* Market Selector */}+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ {futuresMarkets.map((market) => (+ <button+ key={market.symbol}+ onClick={() => setSelectedMarket(market)}+ className={`p-3 rounded border-2 transition ${+ selectedMarket?.symbol === market.symbol+ ? 'border-purple-500 bg-purple-500/10'+ : 'border-gray-700 bg-gray-800/50 hover:border-gray-600'+ }`}+ >+ <div className="text-left">+ <div className="text-white font-semibold mb-1">{market.baseAsset}/USD</div>+ <div className="text-sm text-gray-400">${formatNumber(market.price)}</div>+ <div+ className={`text-xs font-semibold ${+ market.change24h >= 0 ? 'text-green-500' : 'text-red-500'+ }`}+ >+ {market.change24h >= 0 ? '+' : ''}+ {market.change24h.toFixed(2)}%+ </div>+ </div>+ </button>+ ))}+ </div>++ {/* Selected Market Details */}+ {selectedMarket && (+ <div className="border-t border-gray-800 pt-6 space-y-4">+ {/* Market Stats */}+ <div className="grid grid-cols-2 md:grid-cols-3 gap-4">+ {/* Price */}+ <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">+ <div className="text-xs text-gray-400 mb-1">Mark Price</div>+ <div className="text-2xl font-bold text-white">+ ${formatNumber(selectedMarket.price)}+ </div>+ <div+ className={`text-sm font-semibold ${+ selectedMarket.change24h >= 0 ? 'text-green-500' : 'text-red-500'+ }`}+ >+ {selectedMarket.change24h >= 0 ? '+' : ''}+ {selectedMarket.change24h.toFixed(2)}% 24h+ </div>+ </div>++ {/* Volume */}+ <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">+ <div className="text-xs text-gray-400 mb-1">24h Volume</div>+ <div className="text-lg font-bold text-white">+ {formatLargeNumber(selectedMarket.volume24h)}+ </div>+ <div className="text-xs text-gray-500">Trading Volume</div>+ </div>++ {/* Open Interest */}+ <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">+ <div className="text-xs text-gray-400 mb-1">Open Interest</div>+ <div className="text-lg font-bold text-white">+ {formatLargeNumber(selectedMarket.openInterest)}+ </div>+ <div className="text-xs text-gray-500">Total Positions</div>+ </div>++ {/* Funding Rate */}+ <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">+ <div className="text-xs text-gray-400 mb-1">Funding Rate</div>+ <div+ className={`text-lg font-bold ${+ selectedMarket.fundingRate >= 0 ? 'text-green-500' : 'text-red-500'+ }`}+ >+ {(selectedMarket.fundingRate * 100).toFixed(4)}%+ </div>+ <div className="text-xs text-gray-500">Every 8 hours</div>+ </div>++ {/* Next Funding */}+ <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">+ <div className="text-xs text-gray-400 mb-1">Next Funding</div>+ <div className="text-lg font-bold text-white">{selectedMarket.nextFunding}</div>+ <div className="text-xs text-gray-500">Countdown</div>+ </div>++ {/* Max Leverage */}+ <div className="p-4 bg-gray-800/50 border border-gray-700 rounded">+ <div className="text-xs text-gray-400 mb-1">Max Leverage</div>+ <div className="text-lg font-bold text-orange-500">+ {selectedMarket.maxLeverage}x+ </div>+ <div className="text-xs text-gray-500">Available</div>+ </div>+ </div>++ {/* Contract Details */}+ <div className="p-4 bg-blue-500/10 border border-blue-500/20 rounded">+ <div className="text-sm font-semibold text-blue-400 mb-2">Contract Details</div>+ <div className="grid grid-cols-2 gap-3 text-xs">+ <div>+ <span className="text-gray-400">Contract Type:</span>+ <span className="text-white ml-2">Perpetual</span>+ </div>+ <div>+ <span className="text-gray-400">Settlement:</span>+ <span className="text-white ml-2">USD</span>+ </div>+ <div>+ <span className="text-gray-400">Contract Size:</span>+ <span className="text-white ml-2">1 {selectedMarket.baseAsset}</span>+ </div>+ <div>+ <span className="text-gray-400">Min Order:</span>+ <span className="text-white ml-2">0.0001 {selectedMarket.baseAsset}</span>+ </div>+ </div>+ </div>++ {/* Trading Info */}+ <div className="p-4 bg-gray-800/30 border border-gray-700 rounded">+ <div className="text-xs text-gray-400 space-y-2">+ <div>+ <strong className="text-gray-300">How to trade:</strong> Futures trading on+ Kraken requires a separate Kraken Futures account. Visit{' '}+ <a+ href="https://futures.kraken.com"+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-400 hover:text-blue-300 underline"+ >+ futures.kraken.com+ </a>{' '}+ to create an account and start trading.+ </div>+ <div>+ <strong className="text-gray-300">API Integration:</strong> To trade futures+ directly from this terminal, configure Kraken Futures API credentials in+ Settings.+ </div>+ </div>+ </div>++ {/* Action Button */}+ <div className="flex gap-3">+ <a+ href={`https://futures.kraken.com/trade/${selectedMarket.symbol}`}+ target="_blank"+ rel="noopener noreferrer"+ className="flex-1 px-4 py-3 bg-purple-600 hover:bg-purple-700 text-white font-semibold rounded transition flex items-center justify-center gap-2"+ >+ <ExternalLink className="w-4 h-4" />+ Trade on Kraken Futures+ </a>+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/StakingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/StakingPanel.tsxnew file mode 100644index 000000000..f8bc3d232--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/StakingPanel.tsx@@ -0,0 +1,419 @@+/**+ * StakingPanel - Kraken staking management interface+ */++import React, { useState, useCallback, useEffect } from 'react';+import { DollarSign, TrendingUp, Clock, AlertCircle, CheckCircle, Loader } from 'lucide-react';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++interface StakingAsset {+ asset: string;+ balance: number;+ stakedBalance: number;+ availableBalance: number;+ apy: number;+ lockPeriod: string;+ method: string;+}++interface StakingMethod {+ method: string;+ apy: number;+ lockPeriod: string;+ minAmount: number;+}++export function StakingPanel() {+ const { activeBroker, activeAdapter } = useBrokerContext();+ const [stakingAssets, setStakingAssets] = useState<StakingAsset[]>([]);+ const [selectedAsset, setSelectedAsset] = useState<string>('');+ const [stakingMethods, setStakingMethods] = useState<StakingMethod[]>([]);+ const [selectedMethod, setSelectedMethod] = useState<string>('');+ const [amount, setAmount] = useState<string>('');+ const [isLoading, setIsLoading] = useState(true);+ const [isStaking, setIsStaking] = useState(false);+ const [isUnstaking, setIsUnstaking] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [success, setSuccess] = useState<string | null>(null);++ // Fetch staking assets on mount+ useEffect(() => {+ if (activeBroker === 'kraken') {+ fetchStakingAssets();+ }+ }, [activeBroker]);++ const fetchStakingAssets = useCallback(async () => {+ if (!activeAdapter) {+ setIsLoading(false);+ return;+ }++ setIsLoading(true);+ setError(null);+ try {+ // Fetch balance+ const balance = await activeAdapter.fetchBalance();+ const balances = balance as any; // Type assertion for dynamic currency access++ // Mock staking data (in production, fetch from Kraken API)+ const stakableAssets: StakingAsset[] = [+ {+ asset: 'ETH',+ balance: balances['ETH']?.total || 0,+ stakedBalance: 0,+ availableBalance: balances['ETH']?.free || 0,+ apy: 4.5,+ lockPeriod: 'Flexible',+ method: 'ETH2.S',+ },+ {+ asset: 'DOT',+ balance: balances['DOT']?.total || 0,+ stakedBalance: 0,+ availableBalance: balances['DOT']?.free || 0,+ apy: 12.0,+ lockPeriod: '28 days',+ method: 'DOT.S',+ },+ {+ asset: 'SOL',+ balance: balances['SOL']?.total || 0,+ stakedBalance: 0,+ availableBalance: balances['SOL']?.free || 0,+ apy: 6.5,+ lockPeriod: '2 days',+ method: 'SOL.S',+ },+ {+ asset: 'ADA',+ balance: balances['ADA']?.total || 0,+ stakedBalance: 0,+ availableBalance: balances['ADA']?.free || 0,+ apy: 5.0,+ lockPeriod: 'Flexible',+ method: 'ADA.S',+ },+ {+ asset: 'MATIC',+ balance: balances['MATIC']?.total || 0,+ stakedBalance: 0,+ availableBalance: balances['MATIC']?.free || 0,+ apy: 8.0,+ lockPeriod: '3 days',+ method: 'MATIC.S',+ },+ ];++ setStakingAssets(stakableAssets.filter(a => a.balance > 0 || a.stakedBalance > 0));+ } catch (err) {+ setError('Failed to fetch staking assets');+ console.error('Staking fetch error:', err);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter]);++ const handleAssetSelect = (asset: string) => {+ setSelectedAsset(asset);+ setAmount('');+ setError(null);+ setSuccess(null);++ // Set available staking methods for selected asset+ const assetData = stakingAssets.find(a => a.asset === asset);+ if (assetData) {+ setStakingMethods([+ {+ method: assetData.method,+ apy: assetData.apy,+ lockPeriod: assetData.lockPeriod,+ minAmount: 0.01,+ },+ ]);+ setSelectedMethod(assetData.method);+ }+ };++ const handleStake = async () => {+ if (!selectedAsset || !selectedMethod || !amount || parseFloat(amount) <= 0) {+ setError('Please fill all fields');+ return;+ }++ const assetData = stakingAssets.find(a => a.asset === selectedAsset);+ if (!assetData || parseFloat(amount) > assetData.availableBalance) {+ setError('Insufficient balance');+ return;+ }++ setIsStaking(true);+ setError(null);+ setSuccess(null);++ try {+ // Call Kraken adapter's stakeAsset method+ if (typeof (activeAdapter as any).stakeAsset === 'function') {+ await (activeAdapter as any).stakeAsset(selectedAsset, parseFloat(amount), selectedMethod);+ setSuccess(`Successfully staked ${amount} ${selectedAsset}`);+ setAmount('');++ // Refresh staking assets after 2 seconds+ setTimeout(() => {+ fetchStakingAssets();+ }, 2000);+ } else {+ setError('Staking not supported by current adapter');+ }+ } catch (err: any) {+ setError(err?.message || 'Failed to stake asset');+ console.error('Staking error:', err);+ } finally {+ setIsStaking(false);+ }+ };++ const handleUnstake = async () => {+ if (!selectedAsset || !amount || parseFloat(amount) <= 0) {+ setError('Please enter valid amount');+ return;+ }++ const assetData = stakingAssets.find(a => a.asset === selectedAsset);+ if (!assetData || parseFloat(amount) > assetData.stakedBalance) {+ setError('Insufficient staked balance');+ return;+ }++ setIsUnstaking(true);+ setError(null);+ setSuccess(null);++ try {+ // Call Kraken adapter's unstakeAsset method+ if (typeof (activeAdapter as any).unstakeAsset === 'function') {+ await (activeAdapter as any).unstakeAsset(selectedAsset, parseFloat(amount));+ setSuccess(`Successfully unstaked ${amount} ${selectedAsset}`);+ setAmount('');++ // Refresh staking assets after 2 seconds+ setTimeout(() => {+ fetchStakingAssets();+ }, 2000);+ } else {+ setError('Unstaking not supported by current adapter');+ }+ } catch (err: any) {+ setError(err?.message || 'Failed to unstake asset');+ console.error('Unstaking error:', err);+ } finally {+ setIsUnstaking(false);+ }+ };++ const setPercentage = (percentage: number) => {+ if (!selectedAsset) return;+ const assetData = stakingAssets.find(a => a.asset === selectedAsset);+ if (assetData) {+ const calcAmount = (assetData.availableBalance * percentage) / 100;+ setAmount(calcAmount.toFixed(8));+ }+ };++ if (activeBroker !== 'kraken') {+ return null;+ }++ if (isLoading) {+ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-6">+ <div className="flex items-center justify-center py-8">+ <Loader className="w-6 h-6 text-blue-500 animate-spin" />+ </div>+ </div>+ );+ }++ return (+ <div className="bg-gray-900 border border-gray-800 rounded p-6">+ {/* Header */}+ <div className="flex items-center justify-between mb-6">+ <div className="flex items-center gap-2">+ <DollarSign className="w-5 h-5 text-green-500" />+ <span className="text-lg font-semibold text-white">Kraken Staking</span>+ </div>+ <button+ onClick={fetchStakingAssets}+ className="px-3 py-1 text-xs text-blue-400 hover:text-blue-300 border border-blue-500/30 hover:border-blue-400/50 rounded transition"+ >+ Refresh+ </button>+ </div>++ {/* Staking Assets List */}+ {stakingAssets.length === 0 ? (+ <div className="text-center py-8 text-gray-500">+ <AlertCircle className="w-12 h-12 mx-auto mb-3 text-gray-600" />+ <div className="text-sm">No stakable assets found</div>+ <div className="text-xs mt-1">Add funds to your Kraken account to start staking</div>+ </div>+ ) : (+ <>+ {/* Asset Selection Grid */}+ <div className="grid grid-cols-2 gap-3 mb-6">+ {stakingAssets.map((asset) => (+ <button+ key={asset.asset}+ onClick={() => handleAssetSelect(asset.asset)}+ className={`p-4 rounded border-2 transition ${+ selectedAsset === asset.asset+ ? 'border-blue-500 bg-blue-500/10'+ : 'border-gray-700 bg-gray-800/50 hover:border-gray-600'+ }`}+ >+ <div className="flex items-center justify-between mb-2">+ <span className="text-white font-semibold">{asset.asset}</span>+ <div className="flex items-center gap-1 text-green-500 text-xs">+ <TrendingUp className="w-3 h-3" />+ {asset.apy.toFixed(2)}% APY+ </div>+ </div>+ <div className="text-xs text-gray-400">+ <div>Balance: {asset.balance.toFixed(8)}</div>+ {asset.stakedBalance > 0 && (+ <div className="text-green-500">Staked: {asset.stakedBalance.toFixed(8)}</div>+ )}+ </div>+ <div className="flex items-center gap-1 text-xs text-gray-500 mt-2">+ <Clock className="w-3 h-3" />+ {asset.lockPeriod}+ </div>+ </button>+ ))}+ </div>++ {/* Staking Form */}+ {selectedAsset && (+ <div className="border-t border-gray-800 pt-6 space-y-4">+ {/* Amount Input */}+ <div>+ <label className="block text-xs text-gray-400 mb-2">Amount to Stake</label>+ <input+ type="number"+ value={amount}+ onChange={(e) => setAmount(e.target.value)}+ placeholder="0.00"+ className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded text-white focus:outline-none focus:border-blue-500"+ step="0.00000001"+ min="0"+ />+ {/* Quick Percentage Buttons */}+ <div className="flex gap-2 mt-2">+ {[25, 50, 75, 100].map((pct) => (+ <button+ key={pct}+ onClick={() => setPercentage(pct)}+ className="flex-1 px-2 py-1 text-xs bg-gray-800 hover:bg-gray-700 border border-gray-700 rounded transition"+ >+ {pct}%+ </button>+ ))}+ </div>+ </div>++ {/* Info Display */}+ {selectedAsset && amount && parseFloat(amount) > 0 && (+ <div className="p-3 bg-blue-500/10 border border-blue-500/20 rounded">+ <div className="text-xs space-y-1">+ <div className="flex justify-between">+ <span className="text-gray-400">Estimated yearly earnings:</span>+ <span className="text-green-500 font-semibold">+ {(+ parseFloat(amount) *+ (stakingAssets.find((a) => a.asset === selectedAsset)?.apy || 0) /+ 100+ ).toFixed(8)}{' '}+ {selectedAsset}+ </span>+ </div>+ <div className="flex justify-between">+ <span className="text-gray-400">Lock period:</span>+ <span className="text-white">+ {stakingAssets.find((a) => a.asset === selectedAsset)?.lockPeriod}+ </span>+ </div>+ </div>+ </div>+ )}++ {/* Error/Success Messages */}+ {error && (+ <div className="p-3 bg-red-500/10 border border-red-500/20 rounded flex items-start gap-2">+ <AlertCircle className="w-4 h-4 text-red-500 flex-shrink-0 mt-0.5" />+ <span className="text-xs text-red-400">{error}</span>+ </div>+ )}++ {success && (+ <div className="p-3 bg-green-500/10 border border-green-500/20 rounded flex items-start gap-2">+ <CheckCircle className="w-4 h-4 text-green-500 flex-shrink-0 mt-0.5" />+ <span className="text-xs text-green-400">{success}</span>+ </div>+ )}++ {/* Action Buttons */}+ <div className="flex gap-3">+ <button+ onClick={handleStake}+ disabled={isStaking || !amount || parseFloat(amount) <= 0}+ className="flex-1 px-4 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-700 disabled:cursor-not-allowed text-white font-semibold rounded transition flex items-center justify-center gap-2"+ >+ {isStaking ? (+ <>+ <Loader className="w-4 h-4 animate-spin" />+ Staking...+ </>+ ) : (+ <>+ <TrendingUp className="w-4 h-4" />+ Stake+ </>+ )}+ </button>++ <button+ onClick={handleUnstake}+ disabled={+ isUnstaking ||+ !amount ||+ parseFloat(amount) <= 0 ||+ (stakingAssets.find((a) => a.asset === selectedAsset)?.stakedBalance || 0) === 0+ }+ className="flex-1 px-4 py-3 bg-orange-600 hover:bg-orange-700 disabled:bg-gray-700 disabled:cursor-not-allowed text-white font-semibold rounded transition flex items-center justify-center gap-2"+ >+ {isUnstaking ? (+ <>+ <Loader className="w-4 h-4 animate-spin" />+ Unstaking...+ </>+ ) : (+ 'Unstake'+ )}+ </button>+ </div>++ {/* Info Note */}+ <div className="p-3 bg-gray-800/50 border border-gray-700 rounded">+ <div className="text-xs text-gray-400">+ <strong className="text-gray-300">Note:</strong> Staking rewards are+ automatically paid out. Unstaking may take up to the lock period to complete.+ Check Kraken's terms for each asset's specific staking conditions.+ </div>+ </div>+ </div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/index.tsnew file mode 100644index 000000000..557a43112--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/exchange-specific/kraken/index.ts@@ -0,0 +1,6 @@+/**+ * Kraken Exchange-Specific Components Exports+ */++export { StakingPanel } from './StakingPanel';+export { FuturesPanel } from './FuturesPanel';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/index.tsnew file mode 100644index 000000000..3bb53b762--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/index.ts@@ -0,0 +1,15 @@+/**+ * Trading Hooks Exports+ */++export { useExchangeCapabilities, useSupportsFeature, useAvailableOrderTypes, useHasAdvancedOrders, useHasMarginTrading } from './useExchangeCapabilities';+export { useOrderExecution } from './useOrderExecution';+export type { UseOrderExecutionResult } from './useOrderExecution';+export { usePositions, useClosePosition } from './usePositions';+export { useOrders, useCancelOrder, useClosedOrders } from './useOrders';+export { useOHLCV, useOrderBook, useTicker, useVolumeProfile } from './useMarketData';+export type { VolumeProfileLevel } from './useMarketData';+export { useBalance, useFees, useMarginInfo, useTradingStats } from './useAccountInfo';+export type { FeeStructure, MarginInfo } from './useAccountInfo';+export { useCrossExchangePortfolio, useArbitrageDetection, useCrossExchangePositions } from './useCrossExchange';+export type { CrossExchangeBalance, AggregatedBalance, ArbitrageOpportunity, CrossExchangePosition } from './useCrossExchange';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.tsnew file mode 100644index 000000000..3e71f8a50--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.ts@@ -0,0 +1,284 @@+/**+ * Account Information Hooks+ * Fetches balance, fees, margin, and account statistics+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';+import type { UnifiedBalance, UnifiedAccount, TradingStatistics } from '../types';++// ============================================================================+// BALANCE HOOK+// ============================================================================++export function useBalance(autoRefresh: boolean = true, refreshInterval: number = 5000) {+ const { activeAdapter } = useBrokerContext();+ const [balances, setBalances] = useState<UnifiedBalance[]>([]);+ const [totalEquity, setTotalEquity] = useState<number>(0);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchBalance = useCallback(async () => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ setBalances([]);+ setTotalEquity(0);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawBalance = await activeAdapter.fetchBalance();++ // Normalize balances+ const normalizedBalances: UnifiedBalance[] = Object.entries(rawBalance || {})+ .filter(([currency, data]: [string, any]) => data.total > 0)+ .map(([currency, data]: [string, any]) => ({+ currency,+ free: data.free || 0,+ used: data.used || 0,+ total: data.total || 0,+ }));++ setBalances(normalizedBalances);++ // Calculate total equity (simplified - just sum USD/USDC/USDT)+ const equity = normalizedBalances+ .filter((b) => ['USD', 'USDC', 'USDT'].includes(b.currency))+ .reduce((sum, b) => sum + b.total, 0);++ setTotalEquity(equity);+ } catch (err) {+ const error = err as Error;+ console.error('[useBalance] Failed to fetch balance:', error);+ setError(error);+ setBalances([]);+ setTotalEquity(0);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter]);++ useEffect(() => {+ fetchBalance();++ if (!autoRefresh) return;++ const interval = setInterval(fetchBalance, refreshInterval);+ return () => clearInterval(interval);+ }, [fetchBalance, autoRefresh, refreshInterval]);++ return {+ balances,+ totalEquity,+ isLoading,+ error,+ refresh: fetchBalance,+ };+}++// ============================================================================+// FEES HOOK+// ============================================================================++export interface FeeStructure {+ maker: number;+ taker: number;+ makerPercent: string;+ takerPercent: string;+}++export function useFees() {+ const { activeAdapter, activeBroker } = useBrokerContext();+ const [fees, setFees] = useState<FeeStructure | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchFees = useCallback(async () => {+ if (!activeAdapter) {+ setFees(null);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ // Try to fetch trading fees from adapter+ const tradingFees = (activeAdapter as any).getTradingFees?.() || null;++ if (tradingFees) {+ setFees({+ maker: tradingFees.maker || 0,+ taker: tradingFees.taker || 0,+ makerPercent: `${((tradingFees.maker || 0) * 100).toFixed(3)}%`,+ takerPercent: `${((tradingFees.taker || 0) * 100).toFixed(3)}%`,+ });+ } else {+ // Default fees based on exchange+ const defaultFees: Record<string, FeeStructure> = {+ kraken: { maker: 0.0016, taker: 0.0026, makerPercent: '0.160%', takerPercent: '0.260%' },+ hyperliquid: { maker: 0.0002, taker: 0.0005, makerPercent: '0.020%', takerPercent: '0.050%' },+ paper: { maker: 0.0002, taker: 0.0005, makerPercent: '0.020%', takerPercent: '0.050%' },+ };++ setFees(defaultFees[activeBroker || 'paper'] || defaultFees.paper);+ }+ } catch (err) {+ const error = err as Error;+ console.error('[useFees] Failed to fetch fees:', error);+ setError(error);+ setFees(null);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, activeBroker]);++ useEffect(() => {+ fetchFees();+ }, [fetchFees]);++ return {+ fees,+ isLoading,+ error,+ refresh: fetchFees,+ };+}++// ============================================================================+// MARGIN INFO HOOK+// ============================================================================++export interface MarginInfo {+ totalMargin: number;+ usedMargin: number;+ availableMargin: number;+ marginLevel: number; // percentage+ maintenanceMargin: number;+ isMarginCall: boolean;+}++export function useMarginInfo(autoRefresh: boolean = true) {+ const { activeAdapter } = useBrokerContext();+ const [marginInfo, setMarginInfo] = useState<MarginInfo | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchMarginInfo = useCallback(async () => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ setMarginInfo(null);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ // Check if adapter supports margin info+ const balance = await activeAdapter.fetchBalance();++ // Extract margin info if available+ const info = (balance as any).info;++ if (info && info.totalMargin !== undefined) {+ const totalMargin = parseFloat(info.totalMargin || '0');+ const usedMargin = parseFloat(info.usedMargin || '0');+ const availableMargin = totalMargin - usedMargin;+ const marginLevel = totalMargin > 0 ? (availableMargin / totalMargin) * 100 : 100;+ const maintenanceMargin = parseFloat(info.maintenanceMargin || '0');++ setMarginInfo({+ totalMargin,+ usedMargin,+ availableMargin,+ marginLevel,+ maintenanceMargin,+ isMarginCall: marginLevel < 20, // Alert if margin level below 20%+ });+ } else {+ // No margin trading on this account/exchange+ setMarginInfo(null);+ }+ } catch (err) {+ const error = err as Error;+ console.error('[useMarginInfo] Failed to fetch margin info:', error);+ setError(error);+ setMarginInfo(null);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter]);++ useEffect(() => {+ fetchMarginInfo();++ if (!autoRefresh) return;++ const interval = setInterval(fetchMarginInfo, 10000); // Update every 10s+ return () => clearInterval(interval);+ }, [fetchMarginInfo, autoRefresh]);++ return {+ marginInfo,+ isLoading,+ error,+ refresh: fetchMarginInfo,+ };+}++// ============================================================================+// TRADING STATISTICS HOOK+// ============================================================================++export function useTradingStats() {+ const { activeAdapter, tradingMode, paperAdapter } = useBrokerContext();+ const [stats, setStats] = useState<TradingStatistics | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchStats = useCallback(async () => {+ const adapter = tradingMode === 'paper' ? paperAdapter : activeAdapter;++ if (!adapter) {+ setStats(null);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ // Get statistics from paper trading adapter if available+ if (tradingMode === 'paper' && (adapter as any).getStatistics) {+ const paperStats = await (adapter as any).getStatistics();+ setStats(paperStats);+ } else {+ // For live trading, calculate stats from closed orders+ setStats(null); // Not implemented for live yet+ }+ } catch (err) {+ const error = err as Error;+ console.error('[useTradingStats] Failed to fetch stats:', error);+ setError(error);+ setStats(null);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, paperAdapter, tradingMode]);++ useEffect(() => {+ fetchStats();++ const interval = setInterval(fetchStats, 10000);+ return () => clearInterval(interval);+ }, [fetchStats]);++ return {+ stats,+ isLoading,+ error,+ refresh: fetchStats,+ };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useCrossExchange.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useCrossExchange.tsnew file mode 100644index 000000000..2e07d2a2a--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useCrossExchange.ts@@ -0,0 +1,285 @@+/**+ * useCrossExchange - Cross-exchange portfolio aggregation and arbitrage detection+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++// Types+export interface CrossExchangeBalance {+ exchange: string;+ currency: string;+ total: number;+ free: number;+ used: number;+ usdValue: number;+}++export interface AggregatedBalance {+ currency: string;+ totalAmount: number;+ totalUsdValue: number;+ exchanges: {+ exchange: string;+ amount: number;+ usdValue: number;+ }[];+}++export interface ArbitrageOpportunity {+ symbol: string;+ buyExchange: string;+ sellExchange: string;+ buyPrice: number;+ sellPrice: number;+ spread: number;+ spreadPercent: number;+ potentialProfit: number;+ timestamp: number;+}++export interface CrossExchangePosition {+ symbol: string;+ exchange: string;+ side: 'long' | 'short';+ quantity: number;+ entryPrice: number;+ currentPrice: number;+ unrealizedPnl: number;+ pnlPercent: number;+}++/**+ * Hook for cross-exchange portfolio aggregation+ */+export function useCrossExchangePortfolio() {+ const { availableBrokers } = useBrokerContext();+ const [balances, setBalances] = useState<CrossExchangeBalance[]>([]);+ const [aggregatedBalances, setAggregatedBalances] = useState<AggregatedBalance[]>([]);+ const [totalPortfolioValue, setTotalPortfolioValue] = useState<number>(0);+ const [isLoading, setIsLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ const fetchCrossExchangeBalances = useCallback(async () => {+ setIsLoading(true);+ setError(null);++ try {+ const allBalances: CrossExchangeBalance[] = [];++ // Mock data for demonstration (in production, fetch from all connected exchanges)+ const mockBalances: CrossExchangeBalance[] = [+ // Kraken+ { exchange: 'kraken', currency: 'BTC', total: 0.5, free: 0.3, used: 0.2, usdValue: 21625 },+ { exchange: 'kraken', currency: 'ETH', total: 10, free: 8, used: 2, usdValue: 23456 },+ { exchange: 'kraken', currency: 'USDC', total: 5000, free: 4500, used: 500, usdValue: 5000 },++ // HyperLiquid+ { exchange: 'hyperliquid', currency: 'BTC', total: 0.3, free: 0.3, used: 0, usdValue: 12975 },+ { exchange: 'hyperliquid', currency: 'ETH', total: 5, free: 3, used: 2, usdValue: 11728 },+ { exchange: 'hyperliquid', currency: 'USDC', total: 10000, free: 8000, used: 2000, usdValue: 10000 },+ ];++ allBalances.push(...mockBalances);+ setBalances(allBalances);++ // Aggregate by currency+ const aggregated = new Map<string, AggregatedBalance>();++ for (const balance of allBalances) {+ if (!aggregated.has(balance.currency)) {+ aggregated.set(balance.currency, {+ currency: balance.currency,+ totalAmount: 0,+ totalUsdValue: 0,+ exchanges: [],+ });+ }++ const agg = aggregated.get(balance.currency)!;+ agg.totalAmount += balance.total;+ agg.totalUsdValue += balance.usdValue;+ agg.exchanges.push({+ exchange: balance.exchange,+ amount: balance.total,+ usdValue: balance.usdValue,+ });+ }++ const aggregatedArray = Array.from(aggregated.values());+ setAggregatedBalances(aggregatedArray);++ // Calculate total portfolio value+ const totalValue = aggregatedArray.reduce((sum, bal) => sum + bal.totalUsdValue, 0);+ setTotalPortfolioValue(totalValue);++ } catch (err: any) {+ setError(err?.message || 'Failed to fetch cross-exchange balances');+ console.error('Cross-exchange balance error:', err);+ } finally {+ setIsLoading(false);+ }+ }, [availableBrokers]);++ useEffect(() => {+ fetchCrossExchangeBalances();+ // Auto-refresh every 30 seconds+ const interval = setInterval(fetchCrossExchangeBalances, 30000);+ return () => clearInterval(interval);+ }, [fetchCrossExchangeBalances]);++ return {+ balances,+ aggregatedBalances,+ totalPortfolioValue,+ isLoading,+ error,+ refresh: fetchCrossExchangeBalances,+ };+}++/**+ * Hook for arbitrage opportunity detection+ */+export function useArbitrageDetection(symbols: string[] = ['BTC/USDC', 'ETH/USDC']) {+ const { availableBrokers } = useBrokerContext();+ const [opportunities, setOpportunities] = useState<ArbitrageOpportunity[]>([]);+ const [isScanning, setIsScanning] = useState(false);+ const [lastScanTime, setLastScanTime] = useState<number | null>(null);++ const scanArbitrageOpportunities = useCallback(async () => {+ setIsScanning(true);++ try {+ const foundOpportunities: ArbitrageOpportunity[] = [];++ // Mock arbitrage opportunities (in production, fetch real prices from all exchanges)+ const mockOpportunities: ArbitrageOpportunity[] = [+ {+ symbol: 'BTC/USDC',+ buyExchange: 'hyperliquid',+ sellExchange: 'kraken',+ buyPrice: 43150.50,+ sellPrice: 43285.75,+ spread: 135.25,+ spreadPercent: 0.31,+ potentialProfit: 135.25,+ timestamp: Date.now(),+ },+ {+ symbol: 'ETH/USDC',+ buyExchange: 'kraken',+ sellExchange: 'hyperliquid',+ buyPrice: 2340.25,+ sellPrice: 2358.50,+ spread: 18.25,+ spreadPercent: 0.78,+ potentialProfit: 18.25,+ timestamp: Date.now(),+ },+ ];++ // Filter opportunities with spread > 0.2%+ const viableOpportunities = mockOpportunities.filter(+ (opp) => opp.spreadPercent > 0.2+ );++ foundOpportunities.push(...viableOpportunities);+ setOpportunities(foundOpportunities);+ setLastScanTime(Date.now());++ } catch (err) {+ console.error('Arbitrage scan error:', err);+ } finally {+ setIsScanning(false);+ }+ }, [symbols, availableBrokers]);++ useEffect(() => {+ scanArbitrageOpportunities();+ // Auto-scan every 10 seconds+ const interval = setInterval(scanArbitrageOpportunities, 10000);+ return () => clearInterval(interval);+ }, [scanArbitrageOpportunities]);++ return {+ opportunities,+ isScanning,+ lastScanTime,+ scan: scanArbitrageOpportunities,+ };+}++/**+ * Hook for cross-exchange positions aggregation+ */+export function useCrossExchangePositions() {+ const { availableBrokers } = useBrokerContext();+ const [positions, setPositions] = useState<CrossExchangePosition[]>([]);+ const [totalUnrealizedPnl, setTotalUnrealizedPnl] = useState<number>(0);+ const [isLoading, setIsLoading] = useState(true);++ const fetchCrossExchangePositions = useCallback(async () => {+ setIsLoading(true);++ try {+ // Mock positions (in production, fetch from all connected exchanges)+ const mockPositions: CrossExchangePosition[] = [+ {+ symbol: 'BTC/USDC',+ exchange: 'kraken',+ side: 'long',+ quantity: 0.2,+ entryPrice: 42500,+ currentPrice: 43250,+ unrealizedPnl: 150,+ pnlPercent: 1.76,+ },+ {+ symbol: 'ETH/USDC',+ exchange: 'hyperliquid',+ side: 'long',+ quantity: 2,+ entryPrice: 2300,+ currentPrice: 2345,+ unrealizedPnl: 90,+ pnlPercent: 1.96,+ },+ {+ symbol: 'SOL/USDC',+ exchange: 'kraken',+ side: 'short',+ quantity: 10,+ entryPrice: 105,+ currentPrice: 98,+ unrealizedPnl: 70,+ pnlPercent: 6.67,+ },+ ];++ setPositions(mockPositions);++ const totalPnl = mockPositions.reduce((sum, pos) => sum + pos.unrealizedPnl, 0);+ setTotalUnrealizedPnl(totalPnl);++ } catch (err) {+ console.error('Cross-exchange positions error:', err);+ } finally {+ setIsLoading(false);+ }+ }, [availableBrokers]);++ useEffect(() => {+ fetchCrossExchangePositions();+ // Auto-refresh every 5 seconds+ const interval = setInterval(fetchCrossExchangePositions, 5000);+ return () => clearInterval(interval);+ }, [fetchCrossExchangePositions]);++ return {+ positions,+ totalUnrealizedPnl,+ isLoading,+ refresh: fetchCrossExchangePositions,+ };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useExchangeCapabilities.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useExchangeCapabilities.tsnew file mode 100644index 000000000..c90776eb1--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useExchangeCapabilities.ts@@ -0,0 +1,138 @@+/**+ * Exchange Capabilities Hook+ * Detects and returns what features the current exchange supports+ */++import { useMemo } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';+import type { ExchangeOrderCapabilities } from '../types';+import type { OrderType } from '../../../../brokers/crypto/types';++export function useExchangeCapabilities(): ExchangeOrderCapabilities {+ const { features, supports, activeBrokerMetadata } = useBrokerContext();++ return useMemo(() => {+ if (!features || !supports) {+ // Default minimal capabilities when no exchange is connected+ return {+ supportsMarket: true,+ supportsLimit: true,+ supportsStop: false,+ supportsStopLimit: false,+ supportsTrailingStop: false,+ supportsIceberg: false,+ supportsStopLoss: false,+ supportsTakeProfit: false,+ supportsPostOnly: false,+ supportsReduceOnly: false,+ supportsTimeInForce: false,+ supportsMargin: false,+ supportsLeverage: false,+ maxLeverage: undefined,+ supportsOrderEdit: false,+ supportsBatchOrders: false,+ supportsCancelAll: false,+ supportsDeadManSwitch: false,+ supportedOrderTypes: ['market', 'limit'],+ supportedTimeInForce: ['GTC'],+ };+ }++ // Detect supported order types+ const supportedOrderTypes: OrderType[] = ['market', 'limit'];++ // Check for advanced order types+ const supportsStop = activeBrokerMetadata?.tradingFeatures?.stopOrders ?? false;+ const supportsStopLimit = activeBrokerMetadata?.tradingFeatures?.stopLimitOrders ?? false;+ const supportsTrailingStop = activeBrokerMetadata?.tradingFeatures?.trailingStopOrders ?? false;++ if (supportsStop) {+ supportedOrderTypes.push('stop');+ }+ if (supportsStopLimit) {+ supportedOrderTypes.push('stop_limit');+ }+ if (supportsTrailingStop) {+ supportedOrderTypes.push('trailing_stop');+ }++ // Detect leverage support+ const supportsLeverage = activeBrokerMetadata?.advancedFeatures?.leverage ?? false;+ const maxLeverage = activeBrokerMetadata?.advancedFeatures?.maxLeverage;++ // Detect margin support+ const supportsMargin = activeBrokerMetadata?.features?.margin ?? false;++ // Build capabilities object+ const capabilities: ExchangeOrderCapabilities = {+ // Basic order types+ supportsMarket: true,+ supportsLimit: true,+ supportsStop,+ supportsStopLimit,+ supportsTrailingStop,+ supportsIceberg: activeBrokerMetadata?.tradingFeatures?.icebergOrders ?? false,++ // Advanced order features+ supportsStopLoss: supportsStop || supportsStopLimit,+ supportsTakeProfit: supportsStop || supportsStopLimit,+ supportsPostOnly: true, // Most exchanges support this+ supportsReduceOnly: supportsMargin,+ supportsTimeInForce: true, // Most exchanges support this++ // Margin & leverage+ supportsMargin,+ supportsLeverage,+ maxLeverage,++ // Order management+ supportsOrderEdit: supports?.canEditOrder?.() ?? false,+ supportsBatchOrders: supports?.canBatchOrder?.() ?? false,+ supportsCancelAll: supports?.canCancelAll?.() ?? false,+ supportsDeadManSwitch: activeBrokerMetadata?.tradingFeatures?.editOrders ?? false,++ // Available options+ supportedOrderTypes,+ supportedTimeInForce: ['GTC', 'IOC', 'FOK'],+ };++ return capabilities;+ }, [features, supports, activeBrokerMetadata]);+}++/**+ * Hook to check if a specific feature is supported+ */+export function useSupportsFeature(feature: keyof ExchangeOrderCapabilities): boolean {+ const capabilities = useExchangeCapabilities();+ return capabilities[feature] as boolean;+}++/**+ * Hook to get available order types+ */+export function useAvailableOrderTypes(): OrderType[] {+ const capabilities = useExchangeCapabilities();+ return capabilities.supportedOrderTypes;+}++/**+ * Hook to check if advanced orders are available+ */+export function useHasAdvancedOrders(): boolean {+ const capabilities = useExchangeCapabilities();+ return (+ capabilities.supportsStopLoss ||+ capabilities.supportsTakeProfit ||+ capabilities.supportsTrailingStop ||+ capabilities.supportsIceberg+ );+}++/**+ * Hook to check if margin trading is available+ */+export function useHasMarginTrading(): boolean {+ const capabilities = useExchangeCapabilities();+ return capabilities.supportsMargin || capabilities.supportsLeverage;+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useMarketData.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useMarketData.tsnew file mode 100644index 000000000..3424754ac--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useMarketData.ts@@ -0,0 +1,251 @@+/**+ * Market Data Hooks+ * Fetches OHLCV, orderbook, and ticker data across all exchanges+ */++import { useState, useEffect, useCallback, useRef } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';+import type { OHLCV, Timeframe, UnifiedOrderBook, UnifiedTicker } from '../types';++// ============================================================================+// OHLCV / CANDLESTICK DATA+// ============================================================================++export function useOHLCV(symbol?: string, timeframe: Timeframe = '1h', limit: number = 100) {+ const { activeAdapter } = useBrokerContext();+ const [ohlcv, setOhlcv] = useState<OHLCV[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchOHLCV = useCallback(async () => {+ if (!activeAdapter || !symbol) {+ setOhlcv([]);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ // Fetch OHLCV from adapter+ const rawData = await activeAdapter.fetchOHLCV(symbol, timeframe, limit);++ // Normalize to unified format+ const normalized: OHLCV[] = (rawData || []).map((candle: any) => ({+ timestamp: candle[0],+ open: candle[1],+ high: candle[2],+ low: candle[3],+ close: candle[4],+ volume: candle[5],+ }));++ setOhlcv(normalized);+ } catch (err) {+ const error = err as Error;+ console.error('[useOHLCV] Failed to fetch OHLCV:', error);+ setError(error);+ setOhlcv([]);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, timeframe, limit]);++ useEffect(() => {+ fetchOHLCV();+ }, [fetchOHLCV]);++ return {+ ohlcv,+ isLoading,+ error,+ refresh: fetchOHLCV,+ };+}++// ============================================================================+// ORDERBOOK DATA+// ============================================================================++export function useOrderBook(symbol?: string, limit: number = 20, autoRefresh: boolean = true) {+ const { activeAdapter } = useBrokerContext();+ const [orderBook, setOrderBook] = useState<UnifiedOrderBook | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchOrderBook = useCallback(async () => {+ if (!activeAdapter || !symbol) {+ setOrderBook(null);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawBook = await activeAdapter.fetchOrderBook(symbol, limit);++ // Normalize to unified format+ const normalized: UnifiedOrderBook = {+ symbol,+ bids: (rawBook.bids || []).map((level: any) => ({ price: level[0] as number, size: level[1] as number })),+ asks: (rawBook.asks || []).map((level: any) => ({ price: level[0] as number, size: level[1] as number })),+ timestamp: rawBook.timestamp || Date.now(),+ };++ setOrderBook(normalized);+ } catch (err) {+ const error = err as Error;+ console.error('[useOrderBook] Failed to fetch orderbook:', error);+ setError(error);+ setOrderBook(null);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, limit]);++ useEffect(() => {+ fetchOrderBook();++ if (!autoRefresh) return;++ const interval = setInterval(fetchOrderBook, 1000); // Update every 1s+ return () => clearInterval(interval);+ }, [fetchOrderBook, autoRefresh]);++ return {+ orderBook,+ isLoading,+ error,+ refresh: fetchOrderBook,+ };+}++// ============================================================================+// TICKER DATA+// ============================================================================++export function useTicker(symbol?: string, autoRefresh: boolean = true) {+ const { activeAdapter } = useBrokerContext();+ const [ticker, setTicker] = useState<UnifiedTicker | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchTicker = useCallback(async () => {+ if (!activeAdapter || !symbol) {+ setTicker(null);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawTicker = await activeAdapter.fetchTicker(symbol);++ // Normalize to unified format+ const normalized: UnifiedTicker = {+ symbol,+ last: rawTicker.last || 0,+ bid: rawTicker.bid || 0,+ ask: rawTicker.ask || 0,+ high: rawTicker.high || 0,+ low: rawTicker.low || 0,+ open: rawTicker.open,+ close: rawTicker.close,+ volume: rawTicker.baseVolume || 0,+ quoteVolume: rawTicker.quoteVolume,+ change: rawTicker.change || 0,+ changePercent: rawTicker.percentage || 0,+ timestamp: rawTicker.timestamp || Date.now(),+ };++ setTicker(normalized);+ } catch (err) {+ const error = err as Error;+ console.error('[useTicker] Failed to fetch ticker:', error);+ setError(error);+ setTicker(null);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol]);++ useEffect(() => {+ fetchTicker();++ if (!autoRefresh) return;++ const interval = setInterval(fetchTicker, 2000); // Update every 2s+ return () => clearInterval(interval);+ }, [fetchTicker, autoRefresh]);++ return {+ ticker,+ isLoading,+ error,+ refresh: fetchTicker,+ };+}++// ============================================================================+// VOLUME PROFILE DATA+// ============================================================================++export interface VolumeProfileLevel {+ price: number;+ volume: number;+ buyVolume: number;+ sellVolume: number;+}++export function useVolumeProfile(symbol?: string, timeframe: Timeframe = '1h', limit: number = 100) {+ const { ohlcv } = useOHLCV(symbol, timeframe, limit);+ const [volumeProfile, setVolumeProfile] = useState<VolumeProfileLevel[]>([]);++ useEffect(() => {+ if (!ohlcv.length) {+ setVolumeProfile([]);+ return;+ }++ // Calculate volume profile from OHLCV data+ const priceMap = new Map<number, { volume: number; buyVol: number; sellVol: number }>();++ ohlcv.forEach((candle) => {+ // Use close price as reference+ const priceLevel = Math.round(candle.close / 10) * 10; // Round to nearest $10++ const existing = priceMap.get(priceLevel) || { volume: 0, buyVol: 0, sellVol: 0 };++ // Estimate buy/sell volume based on candle close vs open+ const isBullish = candle.close >= candle.open;+ const buyVol = isBullish ? candle.volume : candle.volume * 0.3;+ const sellVol = isBullish ? candle.volume * 0.3 : candle.volume;++ priceMap.set(priceLevel, {+ volume: existing.volume + candle.volume,+ buyVol: existing.buyVol + buyVol,+ sellVol: existing.sellVol + sellVol,+ });+ });++ // Convert to array and sort by price+ const profile: VolumeProfileLevel[] = Array.from(priceMap.entries())+ .map(([price, data]) => ({+ price,+ volume: data.volume,+ buyVolume: data.buyVol,+ sellVolume: data.sellVol,+ }))+ .sort((a, b) => a.price - b.price);++ setVolumeProfile(profile);+ }, [ohlcv]);++ return {+ volumeProfile,+ isLoading: false,+ error: null,+ };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrderExecution.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrderExecution.tsnew file mode 100644index 000000000..8c0122b4f--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrderExecution.ts@@ -0,0 +1,202 @@+/**+ * Order Execution Hook+ * Unified order placement logic for all exchanges+ */++import { useState, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';+import type { UnifiedOrderRequest } from '../types';+import type { OrderParams } from '../../../../brokers/crypto/types';++export interface UseOrderExecutionResult {+ placeOrder: (order: UnifiedOrderRequest) => Promise<any>;+ cancelOrder: (orderId: string, symbol: string) => Promise<void>;+ editOrder: (orderId: string, symbol: string, updates: Partial<UnifiedOrderRequest>) => Promise<any>;+ isPlacing: boolean;+ isCanceling: boolean;+ isEditing: boolean;+ error: Error | null;+}++export function useOrderExecution(): UseOrderExecutionResult {+ const { activeAdapter, tradingMode, paperAdapter } = useBrokerContext();+ const [isPlacing, setIsPlacing] = useState(false);+ const [isCanceling, setIsCanceling] = useState(false);+ const [isEditing, setIsEditing] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ /**+ * Place order on active exchange (real or paper)+ */+ const placeOrder = useCallback(+ async (order: UnifiedOrderRequest) => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ throw new Error('Exchange not connected');+ }++ setIsPlacing(true);+ setError(null);++ try {+ // Build CCXT-compatible params+ const params: OrderParams = {};++ // Stop price+ if (order.stopPrice) {+ params.stopPrice = order.stopPrice;+ }++ // Take profit / stop loss+ if (order.takeProfitPrice) {+ params.takeProfitPrice = order.takeProfitPrice;+ }+ if (order.stopLossPrice) {+ params.stopLossPrice = order.stopLossPrice;+ }++ // Trailing stop+ if (order.trailingPercent) {+ params.trailingPercent = order.trailingPercent;+ }+ if (order.trailingAmount) {+ params.trailingAmount = order.trailingAmount;+ }++ // Leverage+ if (order.leverage) {+ params.leverage = order.leverage;+ }++ // Margin mode+ if (order.marginMode) {+ params.marginMode = order.marginMode;+ }++ // Order flags+ if (order.reduceOnly) {+ params.reduceOnly = order.reduceOnly;+ }+ if (order.postOnly) {+ params.postOnly = order.postOnly;+ }+ if (order.timeInForce) {+ params.timeInForce = order.timeInForce;+ }++ // Iceberg+ if (order.icebergQty) {+ params.icebergQty = order.icebergQty;+ }++ // Client order ID+ if (order.clientOrderId) {+ params.clientOrderId = order.clientOrderId;+ }++ // Execute order+ const result = await activeAdapter.createOrder(+ order.symbol,+ order.type,+ order.side,+ order.quantity,+ order.price,+ params+ );++ console.log('[useOrderExecution] Order placed:', result);+ return result;+ } catch (err) {+ const error = err as Error;+ console.error('[useOrderExecution] Order failed:', error);+ setError(error);+ throw error;+ } finally {+ setIsPlacing(false);+ }+ },+ [activeAdapter]+ );++ /**+ * Cancel order+ */+ const cancelOrder = useCallback(+ async (orderId: string, symbol: string) => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ throw new Error('Exchange not connected');+ }++ setIsCanceling(true);+ setError(null);++ try {+ await activeAdapter.cancelOrder(orderId, symbol);+ console.log('[useOrderExecution] Order canceled:', orderId);+ } catch (err) {+ const error = err as Error;+ console.error('[useOrderExecution] Cancel failed:', error);+ setError(error);+ throw error;+ } finally {+ setIsCanceling(false);+ }+ },+ [activeAdapter]+ );++ /**+ * Edit order (if supported)+ */+ const editOrder = useCallback(+ async (orderId: string, symbol: string, updates: Partial<UnifiedOrderRequest>) => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ throw new Error('Exchange not connected');+ }++ // Check if adapter supports editOrder+ if (typeof (activeAdapter as any).editOrder !== 'function') {+ throw new Error('This exchange does not support order editing');+ }++ setIsEditing(true);+ setError(null);++ try {+ const result = await (activeAdapter as any).editOrder(+ orderId,+ symbol,+ updates.type,+ updates.side,+ updates.quantity,+ updates.price,+ {+ stopPrice: updates.stopPrice,+ takeProfitPrice: updates.takeProfitPrice,+ stopLossPrice: updates.stopLossPrice,+ }+ );++ console.log('[useOrderExecution] Order edited:', result);+ return result;+ } catch (err) {+ const error = err as Error;+ console.error('[useOrderExecution] Edit failed:', error);+ setError(error);+ throw error;+ } finally {+ setIsEditing(false);+ }+ },+ [activeAdapter]+ );++ return {+ placeOrder,+ cancelOrder,+ editOrder,+ isPlacing,+ isCanceling,+ isEditing,+ error,+ };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.tsnew file mode 100644index 000000000..df7f45086--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.ts@@ -0,0 +1,217 @@+/**+ * Order Management Hook+ * Fetches and manages orders across all exchanges+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';+import type { UnifiedOrder } from '../types';++export function useOrders(symbol?: string, autoRefresh: boolean = true, refreshInterval: number = 2000) {+ const { activeAdapter } = useBrokerContext();+ const [openOrders, setOpenOrders] = useState<UnifiedOrder[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchOrders = useCallback(async () => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ setOpenOrders([]);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawOrders = await activeAdapter.fetchOpenOrders(symbol);++ // Normalize to unified format+ const normalized: UnifiedOrder[] = (rawOrders || []).map((order: any) => ({+ id: order.id,+ symbol: order.symbol,+ type: order.type,+ side: order.side,+ quantity: order.amount || 0,+ price: order.price,+ stopPrice: order.stopPrice,+ status: order.status,+ filled: order.filled || 0,+ remaining: order.remaining || order.amount || 0,+ timestamp: order.timestamp || Date.now(),+ createdAt: order.datetime || new Date().toISOString(),+ updatedAt: order.lastUpdateTimestamp ? new Date(order.lastUpdateTimestamp).toISOString() : undefined,+ average: order.average,+ cost: order.cost,+ fee: order.fee+ ? {+ cost: order.fee.cost || 0,+ currency: order.fee.currency || 'USD',+ }+ : undefined,+ clientOrderId: order.clientOrderId,+ timeInForce: order.timeInForce,+ reduceOnly: order.reduceOnly,+ postOnly: order.postOnly,+ }));++ setOpenOrders(normalized);+ } catch (err) {+ const error = err as Error;+ console.error('[useOrders] Failed to fetch orders:', error);+ setError(error);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol]);++ // Auto-refresh+ useEffect(() => {+ fetchOrders();++ if (!autoRefresh) return;++ const interval = setInterval(fetchOrders, refreshInterval);+ return () => clearInterval(interval);+ }, [fetchOrders, autoRefresh, refreshInterval]);++ return {+ openOrders,+ isLoading,+ error,+ refresh: fetchOrders,+ };+}++/**+ * Hook to cancel order(s)+ */+export function useCancelOrder() {+ const { activeAdapter } = useBrokerContext();+ const [isCanceling, setIsCanceling] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const cancelOrder = useCallback(+ async (orderId: string, symbol: string) => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ throw new Error('Exchange not connected');+ }++ setIsCanceling(true);+ setError(null);++ try {+ await activeAdapter.cancelOrder(orderId, symbol);+ return true;+ } catch (err) {+ const error = err as Error;+ setError(error);+ throw error;+ } finally {+ setIsCanceling(false);+ }+ },+ [activeAdapter]+ );++ const cancelAllOrders = useCallback(+ async (symbol?: string) => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ throw new Error('Exchange not connected');+ }++ // Check if exchange supports cancel all+ if (typeof (activeAdapter as any).cancelAllOrders !== 'function') {+ throw new Error('This exchange does not support cancel all orders');+ }++ setIsCanceling(true);+ setError(null);++ try {+ await (activeAdapter as any).cancelAllOrders(symbol);+ return true;+ } catch (err) {+ const error = err as Error;+ setError(error);+ throw error;+ } finally {+ setIsCanceling(false);+ }+ },+ [activeAdapter]+ );++ return { cancelOrder, cancelAllOrders, isCanceling, error };+}++/**+ * Hook to fetch closed orders+ */+export function useClosedOrders(symbol?: string, limit: number = 50) {+ const { activeAdapter } = useBrokerContext();+ const [closedOrders, setClosedOrders] = useState<UnifiedOrder[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchClosedOrders = useCallback(async () => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ setClosedOrders([]);+ return;+ }++ // Check if exchange supports fetching closed orders+ if (typeof (activeAdapter as any).fetchClosedOrders !== 'function') {+ setClosedOrders([]);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawOrders = await (activeAdapter as any).fetchClosedOrders(symbol, undefined, limit);++ const normalized: UnifiedOrder[] = (rawOrders || []).map((order: any) => ({+ id: order.id,+ symbol: order.symbol,+ type: order.type,+ side: order.side,+ quantity: order.amount || 0,+ price: order.price,+ stopPrice: order.stopPrice,+ status: order.status,+ filled: order.filled || 0,+ remaining: 0,+ timestamp: order.timestamp || Date.now(),+ createdAt: order.datetime || new Date().toISOString(),+ average: order.average,+ cost: order.cost,+ fee: order.fee+ ? {+ cost: order.fee.cost || 0,+ currency: order.fee.currency || 'USD',+ }+ : undefined,+ }));++ setClosedOrders(normalized);+ } catch (err) {+ const error = err as Error;+ console.error('[useClosedOrders] Failed to fetch closed orders:', error);+ setError(error);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, limit]);++ useEffect(() => {+ fetchClosedOrders();+ }, [fetchClosedOrders]);++ return {+ closedOrders,+ isLoading,+ error,+ refresh: fetchClosedOrders,+ };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.tsnew file mode 100644index 000000000..1e8d93699--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts@@ -0,0 +1,119 @@+/**+ * Position Management Hook+ * Fetches and manages positions across all exchanges+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';+import type { UnifiedPosition } from '../types';++export function usePositions(symbol?: string, autoRefresh: boolean = true, refreshInterval: number = 2000) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [positions, setPositions] = useState<UnifiedPosition[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchPositions = useCallback(async () => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ setPositions([]);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ // Fetch positions from adapter+ const rawPositions = await activeAdapter.fetchPositions(symbol ? [symbol] : undefined);++ // Normalize to unified format+ const normalized: UnifiedPosition[] = (rawPositions || []).map((pos: any) => ({+ symbol: pos.symbol,+ side: pos.side === 'long' || pos.contracts > 0 ? 'long' : 'short',+ quantity: Math.abs(pos.contracts || pos.amount || 0),+ entryPrice: pos.entryPrice || pos.averagePrice || 0,+ currentPrice: pos.markPrice || pos.currentPrice || 0,+ unrealizedPnl: pos.unrealizedPnl || 0,+ realizedPnl: pos.realizedPnl,+ pnlPercent: pos.percentage || 0,+ leverage: pos.leverage,+ marginMode: pos.marginMode,+ liquidationPrice: pos.liquidationPrice,+ notionalValue: pos.notional || pos.notionalValue || 0,+ marginUsed: pos.collateral || pos.initialMargin,+ openTime: pos.timestamp,+ positionId: pos.id || pos.symbol,+ }));++ setPositions(normalized);+ } catch (err) {+ const error = err as Error;+ console.error('[usePositions] Failed to fetch positions:', error);+ setError(error);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol]);++ // Auto-refresh+ useEffect(() => {+ fetchPositions();++ if (!autoRefresh) return;++ const interval = setInterval(fetchPositions, refreshInterval);+ return () => clearInterval(interval);+ }, [fetchPositions, autoRefresh, refreshInterval]);++ return {+ positions,+ isLoading,+ error,+ refresh: fetchPositions,+ };+}++/**+ * Hook to close a position+ */+export function useClosePosition() {+ const { activeAdapter } = useBrokerContext();+ const [isClosing, setIsClosing] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const closePosition = useCallback(+ async (position: UnifiedPosition) => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ throw new Error('Exchange not connected');+ }++ setIsClosing(true);+ setError(null);++ try {+ // Create opposite order to close position+ const closeSide = position.side === 'long' ? 'sell' : 'buy';++ await activeAdapter.createOrder(+ position.symbol,+ 'market',+ closeSide,+ position.quantity,+ undefined,+ { reduceOnly: true }+ );++ return true;+ } catch (err) {+ const error = err as Error;+ setError(error);+ throw error;+ } finally {+ setIsClosing(false);+ }+ },+ [activeAdapter]+ );++ return { closePosition, isClosing, error };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/types.ts b/fincept-terminal-desktop/src/components/tabs/trading/types.tsnew file mode 100644index 000000000..3bb1b7fbb--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/types.ts@@ -0,0 +1,303 @@+/**+ * Shared Types for Trading UI+ * Exchange-agnostic type definitions+ */++import type { OrderType, OrderSide } from '../../../brokers/crypto/types';++// ============================================================================+// UNIFIED ORDER TYPES+// ============================================================================++export interface UnifiedOrderRequest {+ symbol: string;+ type: OrderType;+ side: OrderSide;+ quantity: number;+ price?: number;++ // Advanced order parameters+ stopPrice?: number;+ takeProfitPrice?: number;+ stopLossPrice?: number;+ trailingPercent?: number;+ trailingAmount?: number;++ // Margin & leverage+ leverage?: number;+ marginMode?: 'cross' | 'isolated';++ // Order options+ reduceOnly?: boolean;+ postOnly?: boolean;+ timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'PO';++ // Iceberg orders+ icebergQty?: number;++ // Client reference+ clientOrderId?: string;+}++// ============================================================================+// EXCHANGE CAPABILITIES+// ============================================================================++export interface ExchangeOrderCapabilities {+ // Order types+ supportsMarket: boolean;+ supportsLimit: boolean;+ supportsStop: boolean;+ supportsStopLimit: boolean;+ supportsTrailingStop: boolean;+ supportsIceberg: boolean;++ // Advanced features+ supportsStopLoss: boolean;+ supportsTakeProfit: boolean;+ supportsPostOnly: boolean;+ supportsReduceOnly: boolean;+ supportsTimeInForce: boolean;++ // Margin & leverage+ supportsMargin: boolean;+ supportsLeverage: boolean;+ maxLeverage?: number;++ // Order management+ supportsOrderEdit: boolean;+ supportsBatchOrders: boolean;+ supportsCancelAll: boolean;+ supportsDeadManSwitch: boolean;++ // Available options+ supportedOrderTypes: OrderType[];+ supportedTimeInForce: string[];+}++// ============================================================================+// POSITION TYPES+// ============================================================================++export interface UnifiedPosition {+ symbol: string;+ side: 'long' | 'short';+ quantity: number;+ entryPrice: number;+ currentPrice: number;++ // P&L+ unrealizedPnl: number;+ realizedPnl?: number;+ pnlPercent: number;++ // Margin info+ leverage?: number;+ marginMode?: 'cross' | 'isolated';+ liquidationPrice?: number;++ // Position value+ notionalValue: number;+ marginUsed?: number;++ // Metadata+ openTime?: number;+ positionId?: string;+}++// ============================================================================+// ORDER TYPES+// ============================================================================++export interface UnifiedOrder {+ id: string;+ symbol: string;+ type: OrderType;+ side: OrderSide;+ quantity: number;+ price?: number;+ stopPrice?: number;++ // Status+ status: 'open' | 'closed' | 'canceled' | 'expired' | 'rejected' | 'pending';+ filled: number;+ remaining: number;++ // Timing+ timestamp: number;+ createdAt: string;+ updatedAt?: string;++ // Execution+ average?: number;+ cost?: number;+ fee?: {+ cost: number;+ currency: string;+ };++ // Metadata+ clientOrderId?: string;+ timeInForce?: string;+ reduceOnly?: boolean;+ postOnly?: boolean;+}++// ============================================================================+// TRADE TYPES+// ============================================================================++export interface UnifiedTrade {+ id: string;+ orderId: string;+ symbol: string;+ side: OrderSide;+ price: number;+ quantity: number;+ cost: number;++ // Fees+ fee: {+ cost: number;+ currency: string;+ rate?: number;+ };++ // Timing+ timestamp: number;+ datetime: string;++ // Trade type+ takerOrMaker: 'taker' | 'maker';++ // Metadata+ info?: any;+}++// ============================================================================+// BALANCE & ACCOUNT+// ============================================================================++export interface UnifiedBalance {+ currency: string;+ free: number;+ used: number;+ total: number;+}++export interface UnifiedAccount {+ balances: UnifiedBalance[];+ totalEquity: number;+ totalMargin?: number;+ availableMargin?: number;+ marginLevel?: number;+}++// ============================================================================+// MARKET DATA+// ============================================================================++export interface UnifiedTicker {+ symbol: string;+ last: number;+ bid: number;+ ask: number;+ high: number;+ low: number;+ open?: number;+ close?: number;+ volume: number;+ quoteVolume?: number;+ change: number;+ changePercent: number;+ timestamp: number;+}++export interface OrderBookLevel {+ price: number;+ size: number;+ count?: number;+}++export interface UnifiedOrderBook {+ symbol: string;+ bids: OrderBookLevel[];+ asks: OrderBookLevel[];+ timestamp: number;+ checksum?: number;+}++// ============================================================================+// CHART DATA+// ============================================================================++export interface OHLCV {+ timestamp: number;+ open: number;+ high: number;+ low: number;+ close: number;+ volume: number;+}++export type Timeframe = '1m' | '3m' | '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d' | '1w' | '1M';++// ============================================================================+// UI STATE TYPES+// ============================================================================++export interface TradingUIState {+ selectedSymbol: string;+ selectedTimeframe: Timeframe;+ chartType: 'candlestick' | 'line' | 'area';+ showDepthChart: boolean;+ showVolumeProfile: boolean;+ activeBottomTab: 'positions' | 'orders' | 'trades' | 'history' | 'stats';+}++// ============================================================================+// ERROR TYPES+// ============================================================================++export interface TradingError {+ code: string;+ message: string;+ userMessage: string;+ exchange?: string;+ timestamp: number;+ details?: any;+}++// ============================================================================+// STATISTICS+// ============================================================================++export interface TradingStatistics {+ // Account+ initialBalance: number;+ currentBalance: number;+ totalEquity: number;++ // P&L+ totalPnL: number;+ realizedPnL: number;+ unrealizedPnL: number;+ returnPercent: number;++ // Trading+ totalTrades: number;+ winningTrades: number;+ losingTrades: number;+ winRate: number;++ // Performance+ largestWin?: number;+ largestLoss?: number;+ averageWin?: number;+ averageLoss?: number;+ profitFactor?: number;+ sharpeRatio?: number;++ // Fees+ totalFees: number;+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/utils/formatters.ts b/fincept-terminal-desktop/src/components/tabs/trading/utils/formatters.tsnew file mode 100644index 000000000..6cca4cac9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/utils/formatters.ts@@ -0,0 +1,193 @@+/**+ * Formatting Utilities+ * Format prices, quantities, and P&L for display+ */++/**+ * Format price with appropriate decimal places+ */+export function formatPrice(price: number, decimals: number = 2): string {+ if (price === 0) return '0.00';+ if (!price || isNaN(price)) return '--';++ // For very small prices, use more decimals+ if (price < 0.01) {+ return price.toFixed(8);+ } else if (price < 1) {+ return price.toFixed(6);+ } else if (price < 100) {+ return price.toFixed(4);+ }++ return price.toFixed(decimals);+}++/**+ * Format price with currency symbol+ */+export function formatCurrency(amount: number, currency: string = 'USD', decimals: number = 2): string {+ if (!amount || isNaN(amount)) return '--';++ const formatted = formatPrice(Math.abs(amount), decimals);++ if (currency === 'USD') {+ return `$${formatted}`;+ }++ return `${formatted} ${currency}`;+}++/**+ * Format quantity/size+ */+export function formatQuantity(quantity: number, decimals: number = 4): string {+ if (!quantity || isNaN(quantity)) return '0.0000';++ if (quantity < 0.0001) {+ return quantity.toFixed(8);+ } else if (quantity < 1) {+ return quantity.toFixed(6);+ }++ return quantity.toFixed(decimals);+}++/**+ * Format percentage+ */+export function formatPercent(percent: number, decimals: number = 2, showSign: boolean = true): string {+ if (!percent || isNaN(percent)) return '0.00%';++ const sign = showSign && percent > 0 ? '+' : '';+ return `${sign}${percent.toFixed(decimals)}%`;+}++/**+ * Format P&L with color and sign+ */+export function formatPnL(pnl: number, decimals: number = 2): { text: string; color: string; sign: string } {+ if (!pnl || isNaN(pnl)) {+ return { text: '$0.00', color: 'gray', sign: '' };+ }++ const sign = pnl >= 0 ? '+' : '';+ const color = pnl >= 0 ? 'green' : 'red';+ const text = `${sign}$${formatPrice(Math.abs(pnl), decimals)}`;++ return { text, color, sign };+}++/**+ * Format volume (abbreviate large numbers)+ */+export function formatVolume(volume: number): string {+ if (!volume || isNaN(volume)) return '0';++ if (volume >= 1_000_000_000) {+ return `${(volume / 1_000_000_000).toFixed(2)}B`;+ } else if (volume >= 1_000_000) {+ return `${(volume / 1_000_000).toFixed(2)}M`;+ } else if (volume >= 1_000) {+ return `${(volume / 1_000).toFixed(2)}K`;+ }++ return volume.toFixed(2);+}++/**+ * Format large numbers with commas+ */+export function formatNumber(num: number, decimals: number = 2): string {+ if (!num || isNaN(num)) return '0';++ return num.toLocaleString(undefined, {+ minimumFractionDigits: decimals,+ maximumFractionDigits: decimals,+ });+}++/**+ * Format timestamp to readable time+ */+export function formatTime(timestamp: number): string {+ if (!timestamp) return '--';++ const date = new Date(timestamp);+ return date.toLocaleTimeString('en-US', {+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit',+ hour12: false,+ });+}++/**+ * Format timestamp to readable date+ */+export function formatDate(timestamp: number): string {+ if (!timestamp) return '--';++ const date = new Date(timestamp);+ return date.toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ });+}++/**+ * Format timestamp to full datetime+ */+export function formatDateTime(timestamp: number): string {+ if (!timestamp) return '--';++ return `${formatDate(timestamp)} ${formatTime(timestamp)}`;+}++/**+ * Format order status+ */+export function formatOrderStatus(status: string): { text: string; color: string } {+ const statusMap: Record<string, { text: string; color: string }> = {+ open: { text: 'OPEN', color: 'blue' },+ closed: { text: 'FILLED', color: 'green' },+ canceled: { text: 'CANCELED', color: 'gray' },+ expired: { text: 'EXPIRED', color: 'orange' },+ rejected: { text: 'REJECTED', color: 'red' },+ pending: { text: 'PENDING', color: 'yellow' },+ };++ return statusMap[status?.toLowerCase()] || { text: status?.toUpperCase() || 'UNKNOWN', color: 'gray' };+}++/**+ * Format order side+ */+export function formatOrderSide(side: string): { text: string; color: string } {+ const sideMap: Record<string, { text: string; color: string }> = {+ buy: { text: 'BUY', color: 'green' },+ sell: { text: 'SELL', color: 'red' },+ long: { text: 'LONG', color: 'green' },+ short: { text: 'SHORT', color: 'red' },+ };++ return sideMap[side?.toLowerCase()] || { text: side?.toUpperCase() || 'UNKNOWN', color: 'gray' };+}++/**+ * Truncate long strings+ */+export function truncate(str: string, maxLength: number = 20): string {+ if (!str) return '';+ if (str.length <= maxLength) return str;++ return `${str.substring(0, maxLength - 3)}...`;+}++/**+ * Format leverage+ */+export function formatLeverage(leverage: number): string {+ if (!leverage || leverage === 1) return '1x';+ return `${leverage}x`;+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/utils/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/utils/index.tsnew file mode 100644index 000000000..b874f03e9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/utils/index.ts@@ -0,0 +1,6 @@+/**+ * Trading Utilities Exports+ */++export * from './orderValidation';+export * from './formatters';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/utils/orderValidation.ts b/fincept-terminal-desktop/src/components/tabs/trading/utils/orderValidation.tsnew file mode 100644index 000000000..c7248fab6--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/utils/orderValidation.ts@@ -0,0 +1,206 @@+/**+ * Order Validation Utilities+ * Validates orders before submission+ */++import type { UnifiedOrderRequest, ExchangeOrderCapabilities } from '../types';++export interface ValidationResult {+ valid: boolean;+ errors: string[];+}++/**+ * Validate order against exchange capabilities+ */+export function validateOrder(+ order: UnifiedOrderRequest,+ capabilities: ExchangeOrderCapabilities,+ balance?: number,+ currentPrice?: number+): ValidationResult {+ const errors: string[] = [];++ // Check basic fields+ if (!order.symbol) {+ errors.push('Symbol is required');+ }++ if (!order.quantity || order.quantity <= 0) {+ errors.push('Quantity must be greater than 0');+ }++ // Validate order type+ if (!capabilities.supportedOrderTypes.includes(order.type)) {+ errors.push(`Order type "${order.type}" is not supported by this exchange`);+ }++ // Validate limit orders+ if (order.type === 'limit' && (!order.price || order.price <= 0)) {+ errors.push('Limit orders require a valid price');+ }++ // Validate stop orders+ if ((order.type === 'stop' || order.type === 'stop_limit') && !order.stopPrice) {+ errors.push('Stop orders require a stop price');+ }++ if (order.type === 'stop_limit' && !order.price) {+ errors.push('Stop-limit orders require both stop price and limit price');+ }++ // Validate trailing stop+ if (order.type === 'trailing_stop') {+ if (!capabilities.supportsTrailingStop) {+ errors.push('This exchange does not support trailing stop orders');+ }+ if (!order.trailingPercent && !order.trailingAmount) {+ errors.push('Trailing stop orders require trailing percent or trailing amount');+ }+ }++ // Validate stop loss / take profit+ if (order.stopLossPrice && !capabilities.supportsStopLoss) {+ errors.push('This exchange does not support stop loss orders');+ }++ if (order.takeProfitPrice && !capabilities.supportsTakeProfit) {+ errors.push('This exchange does not support take profit orders');+ }++ // Validate leverage+ if (order.leverage) {+ if (!capabilities.supportsLeverage) {+ errors.push('This exchange does not support leverage');+ } else if (capabilities.maxLeverage && order.leverage > capabilities.maxLeverage) {+ errors.push(`Maximum leverage for this exchange is ${capabilities.maxLeverage}x`);+ }+ }++ // Validate iceberg+ if (order.icebergQty && !capabilities.supportsIceberg) {+ errors.push('This exchange does not support iceberg orders');+ }++ if (order.icebergQty && order.icebergQty >= order.quantity) {+ errors.push('Iceberg visible quantity must be less than total quantity');+ }++ // Validate post-only+ if (order.postOnly && order.type === 'market') {+ errors.push('Market orders cannot be post-only');+ }++ // Validate reduce-only+ if (order.reduceOnly && !capabilities.supportsReduceOnly) {+ errors.push('This exchange does not support reduce-only orders');+ }++ // Validate balance (if provided)+ if (balance !== undefined && currentPrice) {+ const orderCost = calculateOrderCost(order, currentPrice);+ if (order.side === 'buy' && orderCost > balance) {+ errors.push(`Insufficient balance. Required: $${orderCost.toFixed(2)}, Available: $${balance.toFixed(2)}`);+ }+ }++ return {+ valid: errors.length === 0,+ errors,+ };+}++/**+ * Calculate order cost+ */+export function calculateOrderCost(order: UnifiedOrderRequest, currentPrice: number): number {+ const price = order.price || currentPrice;+ const quantity = order.quantity;++ if (order.leverage && order.leverage > 1) {+ return (price * quantity) / order.leverage;+ }++ return price * quantity;+}++/**+ * Validate order quantity against min/max constraints+ */+export function validateQuantity(+ quantity: number,+ minQty?: number,+ maxQty?: number,+ stepSize?: number+): ValidationResult {+ const errors: string[] = [];++ if (minQty && quantity < minQty) {+ errors.push(`Quantity must be at least ${minQty}`);+ }++ if (maxQty && quantity > maxQty) {+ errors.push(`Quantity cannot exceed ${maxQty}`);+ }++ if (stepSize && quantity % stepSize !== 0) {+ errors.push(`Quantity must be a multiple of ${stepSize}`);+ }++ return {+ valid: errors.length === 0,+ errors,+ };+}++/**+ * Validate price against min/max constraints+ */+export function validatePrice(+ price: number,+ minPrice?: number,+ maxPrice?: number,+ tickSize?: number+): ValidationResult {+ const errors: string[] = [];++ if (minPrice && price < minPrice) {+ errors.push(`Price must be at least ${minPrice}`);+ }++ if (maxPrice && price > maxPrice) {+ errors.push(`Price cannot exceed ${maxPrice}`);+ }++ if (tickSize && !isValidPriceStep(price, tickSize)) {+ errors.push(`Price must be a multiple of ${tickSize}`);+ }++ return {+ valid: errors.length === 0,+ errors,+ };+}++/**+ * Check if price is valid for given tick size+ */+function isValidPriceStep(price: number, tickSize: number): boolean {+ const remainder = price % tickSize;+ return Math.abs(remainder) < 0.0000001 || Math.abs(remainder - tickSize) < 0.0000001;+}++/**+ * Format validation errors for display+ */+export function formatValidationErrors(errors: string[]): string {+ if (errors.length === 0) {+ return '';+ }++ if (errors.length === 1) {+ return errors[0];+ }++ return errors.map((error, index) => `${index + 1}. ${error}`).join('\n');+}diff --git a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx b/fincept-terminal-desktop/src/contexts/BrokerContext.tsxindex 66bf7d099..11a806ba7 100644--- a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx+++ b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx@@ -34,6 +34,10 @@ interface BrokerContextType {tradingMode: 'live' | 'paper';setTradingMode: (mode: 'live' | 'paper') => void;+ // Paper portfolio mode+ paperPortfolioMode: 'separate' | 'unified';+ setPaperPortfolioMode: (mode: 'separate' | 'unified') => void;+// Broker adaptersrealAdapter: IExchangeAdapter | null;paperAdapter: PaperTradingAdapter | null;@@ -64,6 +68,9 @@ interface BrokerProviderProps {export function BrokerProvider({ children }: BrokerProviderProps) {const [activeBroker, setActiveBrokerState] = useState<string>('kraken');const [tradingMode, setTradingModeState] = useState<'live' | 'paper'>('paper');+ const [paperPortfolioMode, setPaperPortfolioModeState] = useState<'separate' | 'unified'>(() => {+ return (localStorage.getItem('paper_portfolio_mode') as 'separate' | 'unified') || 'separate';+ });const [providerConfigs, setProviderConfigs] = useState<Map<string, ProviderConfig>>(new Map());const [isLoading, setIsLoading] = useState(true);const [isConnecting, setIsConnecting] = useState(false);@@ -198,10 +205,12 @@ export function BrokerProvider({ children }: BrokerProviderProps) {setRealAdapter(newRealAdapter);// Create paper adapter (wrapping real adapter)- // Use a stable portfolio ID based on broker name (reuse existing portfolio instead of creating new ones)+ // Portfolio ID depends on mode: separate per broker or unified globalconsole.log(`[BrokerContext] Creating ${activeBroker} paper adapter...`);- const portfolioId = `paper_${activeBroker}`; // Stable ID - no timestamp- console.log(`[BrokerContext] Portfolio ID: ${portfolioId}`);+ const portfolioId = paperPortfolioMode === 'unified'+ ? 'paper_global'+ : `paper_${activeBroker}`;+ console.log(`[BrokerContext] Portfolio ID: ${portfolioId} (mode: ${paperPortfolioMode})`);let newPaperAdapter: PaperTradingAdapter;@@ -209,7 +218,9 @@ export function BrokerProvider({ children }: BrokerProviderProps) {newPaperAdapter = createPaperTradingAdapter({portfolioId,- portfolioName: `${activeBroker.toUpperCase()} Paper Trading`,+ portfolioName: paperPortfolioMode === 'unified'+ ? 'Global Paper Trading Portfolio'+ : `${activeBroker.toUpperCase()} Paper Trading`,provider: activeBroker,assetClass: 'crypto',initialBalance: 100000,@@ -306,7 +317,7 @@ export function BrokerProvider({ children }: BrokerProviderProps) {}}};- }, [isLoading, activeBroker]); // Depend on activeBroker to handle broker switching+ }, [isLoading, activeBroker, paperPortfolioMode]); // Depend on activeBroker and portfolio mode// Set active brokerconst setActiveBroker = useCallback(async (brokerId: string) => {@@ -332,6 +343,15 @@ export function BrokerProvider({ children }: BrokerProviderProps) {localStorage.setItem('trading_mode', mode);}, []);+ // Set paper portfolio mode+ const setPaperPortfolioMode = useCallback((mode: 'separate' | 'unified') => {+ console.log(`[BrokerContext] Switching paper portfolio mode to: ${mode}`);+ setPaperPortfolioModeState(mode);+ localStorage.setItem('paper_portfolio_mode', mode);+ // Reset initialization to recreate adapters with new portfolio ID+ isInitializedRef.current = false;+ }, []);+// Update provider configconst updateProviderConfig = useCallback(async (provider: string,@@ -366,6 +386,8 @@ export function BrokerProvider({ children }: BrokerProviderProps) {availableBrokers,tradingMode,setTradingMode,+ paperPortfolioMode,+ setPaperPortfolioMode,realAdapter,paperAdapter,activeAdapter,