Skip to content

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

node editor and equity trading tab update

tilakpatel225d93dac80449
diff --git a/docs/BROKER_INTEGRATION_GUIDE.md b/docs/BROKER_INTEGRATION_GUIDE.md
index 453764cd9..6f1c641b4 100644
--- a/docs/BROKER_INTEGRATION_GUIDE.md
+++ b/docs/BROKER_INTEGRATION_GUIDE.md
@@ -1,230 +1,241 @@
-# Broker Integration Guide
+# Indian Stock Broker Integration Guide
-Guide for integrating new brokers into Fincept Terminal with paper trading support.
+Guide for integrating new Indian stock brokers (Zerodha, Fyers, Angel, Dhan, Upstox, etc.) into Fincept Terminal.
## Architecture Overview
```
-┌─────────────────────────────────────────────────────────────────┐
-│ MARKET DATA LAYER │
-│ Rust WebSocket (useRustTicker, useRustOrderBook, useRustTrades)│
-│ Feeds into UnifiedMarketDataService │
-└─────────────────────────────────┬───────────────────────────────┘
- │
- ┌───────────────────┴───────────────────┐
- ▼ ▼
-┌─────────────────────────────┐ ┌─────────────────────────────┐
-│ PAPER TRADING │ │ LIVE TRADING │
-│ PaperTradingAdapter │ │ BrokerAdapter (CCXT) │
-│ - Uses MarketDataService│ │ - Direct exchange API │
-│ - Simulated orders │ │ - Real order execution │
-│ - Rust backend storage │ │ │
-└─────────────────────────────┘ └─────────────────────────────┘
+src/brokers/stocks/
+├── types.ts # IStockBrokerAdapter interface
+├── BaseStockBrokerAdapter.ts # Abstract base class
+├── registry.ts # Broker metadata & registration
+├── init.ts # Adapter initialization at startup
+└── india/
+ ├── fyers/
+ │ ├── FyersAdapter.ts # ~1287 lines
+ │ ├── constants.ts
+ │ └── mapper.ts
+ └── zerodha/
+ ├── ZerodhaAdapter.ts # ~1295 lines
+ ├── constants.ts
+ └── mapper.ts
```
-## Key Principle: Separation of Concerns
+## Step 1: Add Broker Metadata
-- **Market Data**: Always from real exchange (WebSocket + REST)
-- **Paper Trading**: Only simulates orders/positions, NOT market data
-- **`realAdapter`**: Used for market data in BOTH live and paper modes
-- **`activeAdapter`**: Paper adapter in paper mode, real adapter in live mode
+Update `src/brokers/stocks/registry.ts`:
-## Step 1: Create Broker Adapter
+```typescript
+mybroker: {
+ id: 'mybroker',
+ name: 'mybroker',
+ displayName: 'My Broker',
+ website: 'https://mybroker.com',
+ region: 'india',
+ country: 'IN',
+ currency: 'INR',
+ exchanges: ['NSE', 'BSE', 'NFO', 'MCX'],
+ marketHours: { open: '09:15', close: '15:30', timezone: 'Asia/Kolkata' },
+ features: {
+ webSocket: true, amo: true, gtt: false, bracketOrder: true,
+ coverOrder: true, marginCalculator: false, optionsChain: true, paperTrading: false,
+ },
+ tradingFeatures: {
+ marketOrders: true, limitOrders: true, stopOrders: true,
+ stopLimitOrders: true, trailingStopOrders: false,
+ },
+ productTypes: ['CASH', 'INTRADAY', 'MARGIN'],
+ authType: 'oauth', // 'oauth' | 'totp' | 'password'
+ rateLimit: { ordersPerSecond: 10, quotesPerSecond: 5 },
+ defaultSymbols: ['RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK'],
+},
+```
-Create `src/stockBrokers/adapters/{broker}Adapter.ts`:
+## Step 2: Create Adapter
-```typescript
-import { IExchangeAdapter, BrokerConfig } from '../types';
+Create `src/brokers/stocks/india/mybroker/MyBrokerAdapter.ts`:
-export class MyBrokerAdapter implements IExchangeAdapter {
- private exchange: any; // CCXT instance or custom client
- private connected = false;
- private config: BrokerConfig;
+```typescript
+import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';
+import type { StockBrokerMetadata, BrokerCredentials, AuthResponse, OrderParams, OrderResponse,
+ ModifyOrderParams, Order, Trade, Position, Holding, Funds, Quote, OHLCV, MarketDepth,
+ TimeFrame, StockExchange, Instrument } from '../../types';
+import { STOCK_BROKER_REGISTRY } from '../../registry';
+
+export class MyBrokerAdapter extends BaseStockBrokerAdapter {
+ readonly brokerId = 'mybroker';
+ readonly brokerName = 'My Broker';
+ readonly region = 'india' as const;
+ readonly metadata: StockBrokerMetadata = STOCK_BROKER_REGISTRY.mybroker;
+
+ private apiKey = '';
+ private apiSecret = '';
+ private readonly BASE_URL = 'https://api.mybroker.com/v1';
+
+ // === AUTHENTICATION ===
+ setCredentials(apiKey: string, apiSecret: string): void {
+ this.apiKey = apiKey;
+ this.apiSecret = apiSecret;
+ }
- constructor(config: BrokerConfig) {
- this.config = config;
+ getAuthUrl(): string {
+ return `https://api.mybroker.com/authorize?client_id=${this.apiKey}&redirect_uri=${encodeURIComponent('http://127.0.0.1/')}&response_type=code`;
}
- async connect(): Promise<void> {
- // Initialize exchange connection
- this.exchange = new ccxt.mybroker({
- apiKey: this.config.apiKey,
- secret: this.config.apiSecret,
+ async authenticate(credentials: BrokerCredentials): Promise<AuthResponse> {
+ const res = await fetch(`${this.BASE_URL}/token`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ grant_type: 'authorization_code',
+ client_id: this.apiKey,
+ client_secret: this.apiSecret,
+ code: credentials.accessToken,
+ }),
});
- await this.exchange.loadMarkets();
- this.connected = true;
+ const data = await res.json();
+ if (data.access_token) {
+ this.accessToken = data.access_token;
+ this._isConnected = true;
+ await this.storeCredentials({ apiKey: this.apiKey, apiSecret: this.apiSecret, accessToken: data.access_token });
+ return { success: true, accessToken: data.access_token };
+ }
+ return { success: false, message: data.message || 'Auth failed' };
}
- async disconnect(): Promise<void> {
- this.connected = false;
+ // === REQUIRED INTERNAL IMPLEMENTATIONS ===
+ protected async placeOrderInternal(params: OrderParams): Promise<OrderResponse> {
+ const res = await this.apiCall('POST', '/orders', { symbol: params.symbol, exchange: params.exchange,
+ side: params.side, qty: params.quantity, type: params.orderType, product: params.productType, price: params.price });
+ return { success: res.status === 'ok', orderId: res.data?.order_id, message: res.message };
}
- isConnected(): boolean {
- return this.connected;
+ protected async modifyOrderInternal(params: ModifyOrderParams): Promise<OrderResponse> {
+ const res = await this.apiCall('PUT', `/orders/${params.orderId}`, params);
+ return { success: res.status === 'ok', orderId: params.orderId };
}
- // Required methods
- async fetchTicker(symbol: string): Promise<Ticker> { /* ... */ }
- async fetchOrderBook(symbol: string, limit?: number): Promise<OrderBook> { /* ... */ }
- async fetchOHLCV(symbol: string, timeframe: string, limit?: number): Promise<OHLCV[]> { /* ... */ }
- async fetchBalance(): Promise<Balance> { /* ... */ }
- async fetchPositions(symbols?: string[]): Promise<Position[]> { /* ... */ }
- async fetchOpenOrders(symbol?: string): Promise<Order[]> { /* ... */ }
- async createOrder(symbol: string, type: string, side: string, amount: number, price?: number, params?: any): Promise<Order> { /* ... */ }
- async cancelOrder(orderId: string, symbol?: string): Promise<void> { /* ... */ }
-}
-```
-
-## Step 2: Register in Broker Registry
+ protected async cancelOrderInternal(orderId: string): Promise<OrderResponse> {
+ const res = await this.apiCall('DELETE', `/orders/${orderId}`);
+ return { success: res.status === 'ok', orderId };
+ }
-Update `src/stockBrokers/registry.ts`:
+ protected async getOrdersInternal(): Promise<Order[]> {
+ const res = await this.apiCall('GET', '/orders');
+ return res.data?.orders?.map((o: any) => this.mapOrder(o)) || [];
+ }
-```typescript
-import { MyBrokerAdapter } from './adapters/myBrokerAdapter';
-
-export const BROKER_REGISTRY: BrokerMetadata[] = [
- // ... existing brokers
- {
- id: 'mybroker',
- name: 'My Broker',
- type: 'crypto', // or 'stock', 'forex'
- features: ['spot', 'margin', 'futures'],
- requiredCredentials: ['apiKey', 'apiSecret'],
- testnet: true,
- defaultSymbols: ['BTC/USD', 'ETH/USD'],
- },
-];
+ protected async getTradeBookInternal(): Promise<Trade[]> {
+ const res = await this.apiCall('GET', '/trades');
+ return res.data?.trades?.map((t: any) => this.mapTrade(t)) || [];
+ }
-export function createAdapter(brokerId: string, config: BrokerConfig): IExchangeAdapter {
- switch (brokerId) {
- case 'mybroker':
- return new MyBrokerAdapter(config);
- // ... other brokers
+ protected async getPositionsInternal(): Promise<Position[]> {
+ const res = await this.apiCall('GET', '/positions');
+ return res.data?.positions?.map((p: any) => this.mapPosition(p)) || [];
}
-}
-```
-## Step 3: Add WebSocket Support (Rust Backend)
+ protected async getHoldingsInternal(): Promise<Holding[]> {
+ const res = await this.apiCall('GET', '/holdings');
+ return res.data?.holdings?.map((h: any) => this.mapHolding(h)) || [];
+ }
-Add provider config in `src-tauri/src/websocket/providers/`:
+ protected async getFundsInternal(): Promise<Funds> {
+ const res = await this.apiCall('GET', '/funds');
+ return { availableCash: res.data.available, usedMargin: res.data.used, availableMargin: res.data.available,
+ totalBalance: res.data.total, currency: 'INR' };
+ }
-```rust
-// mybroker.rs
-pub fn get_mybroker_config() -> ProviderConfig {
- ProviderConfig {
- name: "mybroker".to_string(),
- url: "wss://ws.mybroker.com".to_string(),
- // ... config
- }
-}
-```
+ protected async getQuoteInternal(symbol: string, exchange: StockExchange): Promise<Quote> {
+ const res = await this.apiCall('GET', `/quote?symbol=${symbol}&exchange=${exchange}`);
+ return res.data;
+ }
-## Step 4: Paper Trading Integration
+ protected async getQuotesInternal(instruments: Array<{ symbol: string; exchange: StockExchange }>): Promise<Quote[]> {
+ const symbols = instruments.map(i => `${i.exchange}:${i.symbol}`).join(',');
+ const res = await this.apiCall('GET', `/quotes?symbols=${symbols}`);
+ return res.data || [];
+ }
-Paper trading works automatically if your adapter implements `IExchangeAdapter`. The system:
+ protected async getOHLCVInternal(symbol: string, exchange: StockExchange, tf: TimeFrame, from: Date, to: Date): Promise<OHLCV[]> {
+ const res = await this.apiCall('GET', `/historical?symbol=${symbol}&exchange=${exchange}&tf=${tf}&from=${from.getTime()}&to=${to.getTime()}`);
+ return res.data?.candles || [];
+ }
-1. Creates `PaperTradingAdapter` wrapping market data service
-2. Uses `realAdapter` for all market data (ticker, OHLCV, orderbook)
-3. Simulates orders/positions in Rust backend
+ protected async getMarketDepthInternal(symbol: string, exchange: StockExchange): Promise<MarketDepth> {
+ const res = await this.apiCall('GET', `/depth?symbol=${symbol}&exchange=${exchange}`);
+ return { bids: res.data.bids, asks: res.data.asks };
+ }
-### How Paper Trading Gets Prices
+ protected async searchSymbolsInternal(query: string, exchange?: StockExchange): Promise<Instrument[]> {
+ const res = await this.apiCall('GET', `/search?q=${query}${exchange ? `&exchange=${exchange}` : ''}`);
+ return res.data || [];
+ }
-```typescript
-// In TradingTab.tsx - feeds WebSocket data to market data service
-useEffect(() => {
- if (tickerData && activeBroker) {
- const marketDataService = getMarketDataService();
- marketDataService.updatePrice(activeBroker, selectedSymbol, {
- price: tickerData.price,
- bid: tickerData.bid,
- ask: tickerData.ask,
- // ...
+ // === HELPERS ===
+ private async apiCall(method: string, endpoint: string, body?: any): Promise<any> {
+ const res = await fetch(`${this.BASE_URL}${endpoint}`, {
+ method, headers: { 'Authorization': `Bearer ${this.accessToken}`, 'Content-Type': 'application/json' },
+ body: body ? JSON.stringify(body) : undefined,
});
+ return res.json();
}
-}, [tickerData]);
-```
-
-### Paper Order Matching (Touch-Based)
-Orders fill when price touches limit:
-- **Buy Limit**: Fills when `ask <= limit_price`
-- **Sell Limit**: Fills when `bid >= limit_price`
-- **Buy Stop**: Fills when `price >= stop_price`
-- **Sell Stop**: Fills when `price <= stop_price`
+ private mapOrder(o: any): Order {
+ return { orderId: o.order_id, symbol: o.symbol, exchange: o.exchange, side: o.side, quantity: o.qty,
+ filledQuantity: o.filled_qty, pendingQuantity: o.pending_qty, price: o.price, averagePrice: o.avg_price,
+ orderType: o.type, productType: o.product, validity: 'DAY', status: o.status, placedAt: new Date(o.placed_at) };
+ }
+ private mapTrade(t: any): Trade {
+ return { tradeId: t.trade_id, orderId: t.order_id, symbol: t.symbol, exchange: t.exchange, side: t.side,
+ quantity: t.qty, price: t.price, productType: t.product, tradedAt: new Date(t.traded_at) };
+ }
+ private mapPosition(p: any): Position {
+ return { symbol: p.symbol, exchange: p.exchange, productType: p.product, quantity: p.qty, buyQuantity: p.buy_qty,
+ sellQuantity: p.sell_qty, buyValue: p.buy_value, sellValue: p.sell_value, averagePrice: p.avg_price,
+ lastPrice: p.ltp, pnl: p.pnl, pnlPercent: p.pnl_percent, dayPnl: p.day_pnl };
+ }
+ private mapHolding(h: any): Holding {
+ return { symbol: h.symbol, exchange: h.exchange, quantity: h.qty, averagePrice: h.avg_price, lastPrice: h.ltp,
+ investedValue: h.invested, currentValue: h.current, pnl: h.pnl, pnlPercent: h.pnl_percent };
+ }
+}
+```
-## Step 5: Market Data Hooks
+## Step 3: Register Adapter
-The hooks in `src/components/tabs/trading/hooks/useMarketData.ts` use `realAdapter`:
+Update `src/brokers/stocks/init.ts`:
```typescript
-// useOHLCV - fetches chart data
-const { realAdapter } = useBrokerContext();
-const rawData = await realAdapter.fetchOHLCV(symbol, timeframe, limit);
+import { MyBrokerAdapter } from './india/mybroker/MyBrokerAdapter';
+registerBrokerAdapter('mybroker', MyBrokerAdapter);
+```
-// useTicker - gets live prices from MarketDataService
-const marketDataService = getMarketDataService();
-const cachedPrice = marketDataService.getCurrentPrice(symbol, activeBroker);
+## Paper Trading
-// useOrderBook - fetches depth from realAdapter
-const rawBook = await realAdapter.fetchOrderBook(symbol, limit);
-```
+Paper trading is separate from adapters - handled by `StockBrokerContext.tsx` which routes to:
+- **Live mode**: `adapter.getPositions()`, `adapter.getFunds()`, etc.
+- **Paper mode**: `unifiedTradingService.ts` → Rust backend (SQLite)
-## Key Files Reference
+## Key Files
| File | Purpose |
|------|---------|
-| `src/stockBrokers/adapters/` | Broker adapter implementations |
-| `src/stockBrokers/registry.ts` | Broker registration and metadata |
-| `src/contexts/BrokerContext.tsx` | Adapter lifecycle, mode switching |
-| `src/paper-trading/index.ts` | PaperTradingAdapter implementation |
-| `src/paper-trading/OrderMatcher.ts` | Order fill logic |
-| `src/services/trading/UnifiedMarketDataService.ts` | Price cache and subscriptions |
-| `src/hooks/useRustWebSocket.ts` | WebSocket data hooks |
-| `src/components/tabs/trading/hooks/useMarketData.ts` | Market data hooks (OHLCV, ticker, orderbook) |
-
-## IExchangeAdapter Interface
-
-```typescript
-interface IExchangeAdapter {
- connect(): Promise<void>;
- disconnect(): Promise<void>;
- isConnected(): boolean;
-
- // Market Data
- fetchTicker(symbol: string): Promise<Ticker>;
- fetchOrderBook(symbol: string, limit?: number): Promise<OrderBook>;
- fetchOHLCV(symbol: string, timeframe: string, limit?: number): Promise<OHLCV[]>;
- fetchTickers(symbols?: string[]): Promise<Record<string, Ticker>>;
- fetchMarkets(): Promise<Market[]>;
-
- // Account
- fetchBalance(): Promise<Balance>;
- fetchPositions(symbols?: string[]): Promise<Position[]>;
- fetchOpenOrders(symbol?: string): Promise<Order[]>;
- fetchClosedOrders(symbol?: string, since?: number, limit?: number): Promise<Order[]>;
-
- // Trading
- createOrder(symbol: string, type: string, side: string, amount: number, price?: number, params?: any): Promise<Order>;
- cancelOrder(orderId: string, symbol?: string): Promise<void>;
- cancelAllOrders(symbol?: string): Promise<void>;
-}
-```
+| `src/brokers/stocks/types.ts` | `IStockBrokerAdapter` interface |
+| `src/brokers/stocks/BaseStockBrokerAdapter.ts` | Abstract base class |
+| `src/brokers/stocks/registry.ts` | Broker metadata |
+| `src/contexts/StockBrokerContext.tsx` | State management, paper/live routing |
+| `src/services/unifiedTradingService.ts` | Paper trading backend bridge |
## Testing Checklist
-- [ ] Adapter connects successfully with API credentials
-- [ ] `fetchTicker` returns valid price data
-- [ ] `fetchOHLCV` returns chart data (100+ candles)
-- [ ] `fetchOrderBook` returns 20+ levels for bids/asks
-- [ ] `fetchBalance` returns account balances
-- [ ] `createOrder` places orders correctly
-- [ ] Paper trading shows live P&L with your broker's prices
-- [ ] WebSocket streams real-time ticker data
-- [ ] Symbol format matches (e.g., `BTC/USD` vs `BTCUSD`)
-
-## Common Issues
-
-1. **Empty orderbook in paper mode**: Ensure WebSocket is connected and streaming
-2. **Chart not loading**: Check `realAdapter.fetchOHLCV()` returns data
-3. **Prices showing 0**: Verify `marketDataService.updatePrice()` is being called
-4. **Symbol mismatch**: Normalize symbols (remove `/`, `-`, uppercase)
+- [ ] Metadata added to `registry.ts`
+- [ ] Adapter registered in `init.ts`
+- [ ] OAuth: `getAuthUrl()` → `authenticate()` flow works
+- [ ] Credentials persist via `storeCredentials()`/`loadCredentials()`
+- [ ] `getPositions()`, `getHoldings()`, `getOrders()`, `getFunds()` return correct data
+- [ ] `placeOrder()` executes successfully
+- [ ] Paper mode shows paper data, Live mode shows broker data
+
+---
+**Last Updated**: January 2025
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lock
index 31386fb25..fa41883d1 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.lock
+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock
@@ -1735,6 +1735,7 @@ dependencies = [
"barter-integration 0.8.0",
"base64 0.22.1",
"chrono",
+ "csv",
"dashmap",
"flate2",
"fnv",
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.toml
index 35d8a9d18..c651e7c94 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.toml
+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml
@@ -84,6 +84,7 @@ quick-xml = "0.37" # Fast XML/RSS parsing
rand = "0.8" # Random number generation for paper trading
aes-gcm = "0.10" # AES-256-GCM encryption for secure credential storage
base64 = "0.22" # Base64 encoding/decoding for encrypted data
+csv = "1.3" # CSV parsing for master contract data
[target.'cfg(target_os = "windows")'.dependencies]
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
index 175b10b7f..805211c02 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
@@ -147,9 +147,98 @@ pub async fn execute_python_agent(
}
}
+/// Struct for parsing agent definitions from JSON config files
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct AgentDefinition {
+ id: String,
+ name: String,
+ role: Option<String>,
+ goal: Option<String>,
+ description: String,
+ #[serde(default)]
+ llm_config: Option<serde_json::Value>,
+ #[serde(default)]
+ tools: Vec<String>,
+ #[serde(default)]
+ instructions: Option<String>,
+ #[serde(default)]
+ enable_memory: bool,
+ #[serde(default)]
+ enable_agentic_memory: bool,
+}
+
+#[derive(Debug, Deserialize)]
+struct AgentConfigFile {
+ agents: Vec<AgentDefinition>,
+}
+
+/// List all available agents from config files
#[tauri::command]
-pub async fn list_available_agents() -> Result<Vec<AgentMetadata>, String> {
- Ok(Vec::new())
+pub async fn list_available_agents(app: tauri::AppHandle) -> Result<Vec<AgentMetadata>, String> {
+ let mut all_agents = Vec::new();
+
+ // Define agent categories and their config files
+ let categories = vec![
+ ("TraderInvestorsAgent", "agent_definitions.json", "trader", "📈", "#22c55e"),
+ ("hedgeFundAgents", "team_config.json", "hedge-fund", "🏦", "#6366f1"),
+ ("EconomicAgents", "agent_definitions.json", "economic", "💹", "#eab308"),
+ ("GeopoliticsAgents", "agent_definitions.json", "geopolitics", "🌍", "#ef4444"),
+ ];
+
+ for (folder, config_file, category_id, icon, color) in categories {
+ let config_path = format!("resources/scripts/agents/{}/configs/{}", folder, config_file);
+
+ let full_path = if cfg!(debug_assertions) {
+ let current_dir = std::env::current_dir()
+ .map_err(|e| format!("Failed to get current directory: {}", e))?;
+ let base_dir = if current_dir.ends_with("src-tauri") {
+ current_dir
+ } else {
+ current_dir.join("src-tauri")
+ };
+ base_dir.join(&config_path)
+ } else {
+ let resource_dir = app.path().resource_dir()
+ .map_err(|e| format!("Failed to get resource directory: {}", e))?;
+ resource_dir.join(&config_path)
+ };
+
+ // Read and parse the config file
+ if let Ok(content) = std::fs::read_to_string(&full_path) {
+ if let Ok(config) = serde_json::from_str::<AgentConfigFile>(&content) {
+ for agent_def in config.agents {
+ all_agents.push(AgentMetadata {
+ id: agent_def.id.clone(),
+ name: agent_def.name,
+ agent_type: "python-agent".to_string(),
+ category: category_id.to_string(),
+ description: agent_def.description,
+ script_path: format!("agents/{}/", folder),
+ parameters: vec![
+ AgentParameter {
+ name: "query".to_string(),
+ label: "Query".to_string(),
+ param_type: "string".to_string(),
+ required: true,
+ default_value: None,
+ description: Some("The analysis query or question".to_string()),
+ },
+ ],
+ required_inputs: vec![],
+ outputs: vec!["analysis".to_string()],
+ icon: icon.to_string(),
+ color: color.to_string(),
+ });
+ }
+ } else {
+ eprintln!("Failed to parse agent config: {}", full_path.display());
+ }
+ } else {
+ eprintln!("Agent config file not found: {}", full_path.display());
+ }
+ }
+
+ Ok(all_agents)
}
#[tauri::command]
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/common.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common.rs
new file mode 100644
index 000000000..0270b7b46
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common.rs
@@ -0,0 +1,45 @@
+// Common types and utilities for Indian broker integrations
+
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+// ============================================================================
+// Common Response Types
+// ============================================================================
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct ApiResponse<T> {
+ pub success: bool,
+ pub data: Option<T>,
+ pub error: Option<String>,
+ pub timestamp: i64,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct TokenExchangeResponse {
+ pub success: bool,
+ pub access_token: Option<String>,
+ pub user_id: Option<String>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct OrderPlaceResponse {
+ pub success: bool,
+ pub order_id: Option<String>,
+ pub error: Option<String>,
+}
+
+// ============================================================================
+// Helper Functions
+// ============================================================================
+
+/// Create common HTTP headers for API requests
+pub fn create_common_headers() -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Content-Type",
+ HeaderValue::from_static("application/json"),
+ );
+ headers
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rs
new file mode 100644
index 000000000..7c1b4b8a3
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rs
@@ -0,0 +1,179 @@
+//! Common broker utility functions
+//!
+//! Shared credential management functions for all Indian brokers
+
+use serde_json::{json, Value};
+use super::common::ApiResponse;
+
+#[tauri::command]
+pub async fn store_indian_broker_credentials(
+ broker_id: String,
+ credentials: Value,
+) -> Result<ApiResponse<bool>, String> {
+ eprintln!("[store_indian_broker_credentials] Storing credentials for: {}", broker_id);
+ eprintln!("[store_indian_broker_credentials] Received JSON: {}", credentials);
+
+ // This wraps the existing broker_credentials functionality
+ // with Indian broker specific handling
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ // Extract fields from credentials JSON
+ // IMPORTANT: Handle BOTH camelCase (from TypeScript) and snake_case (from Rust)
+ // Tauri may or may not convert camelCase to snake_case depending on serialization
+ let api_key = credentials.get("apiKey")
+ .or_else(|| credentials.get("api_key"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ eprintln!("[store_indian_broker_credentials] Extracted api_key: {:?} (len: {})",
+ api_key.as_ref().map(|s| if s.len() > 0 { "***PRESENT***" } else { "EMPTY" }),
+ api_key.as_ref().map(|s| s.len()).unwrap_or(0));
+
+ let api_secret = credentials.get("apiSecret")
+ .or_else(|| credentials.get("api_secret"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ eprintln!("[store_indian_broker_credentials] Extracted api_secret: {:?} (len: {})",
+ api_secret.as_ref().map(|s| if s.len() > 0 { "***PRESENT***" } else { "EMPTY" }),
+ api_secret.as_ref().map(|s| s.len()).unwrap_or(0));
+
+ let access_token = credentials.get("accessToken")
+ .or_else(|| credentials.get("access_token"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ eprintln!("[store_indian_broker_credentials] Extracted access_token: {:?}",
+ access_token.as_ref().map(|s| if s.len() > 0 { "***PRESENT***" } else { "EMPTY" }));
+
+ let user_id = credentials.get("userId")
+ .or_else(|| credentials.get("user_id"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ // Store additional data as JSON
+ let additional_data = json!({
+ "userId": user_id,
+ "expiresAt": credentials.get("expiresAt").or_else(|| credentials.get("expires_at")),
+ }).to_string();
+
+ // Use the existing save_broker_credentials command
+ use crate::commands::broker_credentials::save_broker_credentials;
+
+ save_broker_credentials(
+ broker_id.clone(),
+ api_key,
+ api_secret,
+ access_token,
+ None, // refresh_token
+ Some(additional_data),
+ ).await.map_err(|e| format!("Failed to save credentials: {}", e))?;
+
+ eprintln!("[store_indian_broker_credentials] ✓ Successfully stored credentials for: {}", broker_id);
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+}
+
+/// Get broker credentials
+#[tauri::command]
+pub async fn get_indian_broker_credentials(
+ broker_id: String,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[get_indian_broker_credentials] Getting credentials for: {}", broker_id);
+
+ use crate::commands::broker_credentials::get_broker_credentials;
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ match get_broker_credentials(broker_id.clone()).await {
+ Ok(creds) => {
+ // Debug: Print actual credential values before JSON serialization
+ eprintln!("[get_indian_broker_credentials] Retrieved credentials:");
+ eprintln!(" - broker_id: {}", creds.broker_id);
+ eprintln!(" - api_key: {:?} (len: {})",
+ creds.api_key.as_ref().map(|s| if s.len() > 0 { "***PRESENT***" } else { "EMPTY" }),
+ creds.api_key.as_ref().map(|s| s.len()).unwrap_or(0));
+ eprintln!(" - api_secret: {:?} (len: {})",
+ creds.api_secret.as_ref().map(|s| if s.len() > 0 { "***PRESENT***" } else { "EMPTY" }),
+ creds.api_secret.as_ref().map(|s| s.len()).unwrap_or(0));
+ eprintln!(" - access_token: {:?}",
+ creds.access_token.as_ref().map(|s| if s.len() > 0 { "***PRESENT***" } else { "EMPTY" }));
+
+ // Parse additional_data JSON to extract userId
+ let additional_data: Option<Value> = creds.additional_data.as_ref()
+ .and_then(|data| serde_json::from_str(data).ok());
+
+ let user_id = additional_data.as_ref()
+ .and_then(|data| data.get("userId"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ eprintln!("[get_indian_broker_credentials] Extracted user_id: {:?}", user_id);
+
+ // Return camelCase JSON for TypeScript
+ let creds_json = json!({
+ "brokerId": creds.broker_id,
+ "apiKey": creds.api_key,
+ "apiSecret": creds.api_secret,
+ "accessToken": creds.access_token,
+ "userId": user_id,
+ "additionalData": creds.additional_data,
+ });
+
+ // Debug: Print the JSON that will be returned
+ eprintln!("[get_indian_broker_credentials] Returning JSON with {} keys", creds_json.as_object().map(|o| o.len()).unwrap_or(0));
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(creds_json),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ eprintln!("[get_indian_broker_credentials] ❌ Error: {}", e);
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(e),
+ timestamp,
+ })
+ }
+ }
+}
+
+/// Delete broker credentials
+#[tauri::command]
+pub async fn delete_indian_broker_credentials(
+ broker_id: String,
+) -> Result<ApiResponse<bool>, String> {
+ eprintln!("[delete_indian_broker_credentials] Deleting credentials for: {}", broker_id);
+
+ use crate::commands::broker_credentials::delete_broker_credentials;
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ match delete_broker_credentials(broker_id).await {
+ Ok(_) => {
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some(e),
+ timestamp,
+ })
+ }
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs
new file mode 100644
index 000000000..b2f4b766f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs
@@ -0,0 +1,1334 @@
+//! Fyers Broker Integration
+//!
+//! Complete API implementation for Fyers broker including:
+//! - Authentication (OAuth with SHA256)
+//! - Order Management (place, modify, cancel)
+//! - Portfolio (positions, holdings, funds)
+//! - Market Data (quotes, history, depth, margin calculator)
+//! - Master Contract (symbol database)
+//! - WebSocket (real-time data streaming)
+
+use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
+use serde_json::{json, Value};
+use sha2::{Sha256, Digest};
+use std::sync::Arc;
+use tokio::sync::RwLock;
+use once_cell::sync::Lazy;
+use tauri::Emitter;
+use chrono::Datelike;
+
+use crate::websocket::types::MarketMessage;
+use crate::websocket::types::ProviderConfig;
+use crate::websocket::adapters::WebSocketAdapter;
+use super::common::{ApiResponse, TokenExchangeResponse, OrderPlaceResponse};
+
+// Fyers API Configuration
+// ============================================================================
+
+const FYERS_API_BASE: &str = "https://api-t1.fyers.in";
+
+fn create_fyers_headers(api_key: &str, access_token: &str) -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ let auth_value = format!("{}:{}", api_key, access_token);
+ if let Ok(header_value) = HeaderValue::from_str(&auth_value) {
+ headers.insert(AUTHORIZATION, header_value);
+ }
+ headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
+ headers
+}
+
+// ============================================================================
+// Fyers Authentication Commands
+// ============================================================================
+
+/// Exchange authorization code for access token
+#[tauri::command]
+pub async fn fyers_exchange_token(
+ api_key: String,
+ api_secret: String,
+ auth_code: String,
+) -> Result<TokenExchangeResponse, String> {
+ eprintln!("[fyers_exchange_token] Exchanging authorization code");
+
+ // Create app_id_hash: SHA256(api_key:api_secret)
+ let checksum_input = format!("{}:{}", api_key, api_secret);
+ let mut hasher = Sha256::new();
+ hasher.update(checksum_input.as_bytes());
+ let app_id_hash = format!("{:x}", hasher.finalize());
+
+ let client = reqwest::Client::new();
+
+ let payload = json!({
+ "grant_type": "authorization_code",
+ "appIdHash": app_id_hash,
+ "code": auth_code
+ });
+
+ let response = client
+ .post(format!("{}/api/v3/validate-authcode", FYERS_API_BASE))
+ .header(CONTENT_TYPE, "application/json")
+ .header("Accept", "application/json")
+ .json(&payload)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ Ok(TokenExchangeResponse {
+ success: true,
+ access_token: body.get("access_token").and_then(|v| v.as_str()).map(String::from),
+ user_id: body.get("user_id").and_then(|v| v.as_str()).map(String::from),
+ error: None,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Token exchange failed")
+ .to_string();
+ Ok(TokenExchangeResponse {
+ success: false,
+ access_token: None,
+ user_id: None,
+ error: Some(error_msg),
+ })
+ }
+}
+
+// ============================================================================
+// Fyers Order Management Commands
+// ============================================================================
+
+/// Place a new order
+#[tauri::command]
+pub async fn fyers_place_order(
+ api_key: String,
+ access_token: String,
+ symbol: String,
+ qty: i32,
+ r#type: i32, // 1=Limit, 2=Market, 3=Stop Loss Limit, 4=Stop Loss Market
+ side: i32, // 1=Buy, -1=Sell
+ product_type: String, // "CNC", "INTRADAY", "MARGIN", "CO", "BO"
+ limit_price: Option<f64>,
+ stop_price: Option<f64>,
+ disclosed_qty: Option<i32>,
+ validity: Option<String>, // "DAY", "IOC"
+ offline_order: Option<bool>,
+ stop_loss: Option<f64>,
+ take_profit: Option<f64>,
+) -> Result<OrderPlaceResponse, String> {
+ eprintln!("[fyers_place_order] Placing order for {}", symbol);
+
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ let mut payload = json!({
+ "symbol": symbol,
+ "qty": qty,
+ "type": r#type,
+ "side": side,
+ "productType": product_type,
+ "validity": validity.unwrap_or_else(|| "DAY".to_string()),
+ "offlineOrder": offline_order.unwrap_or(false)
+ });
+
+ if let Some(price) = limit_price {
+ payload["limitPrice"] = json!(price);
+ }
+ if let Some(price) = stop_price {
+ payload["stopPrice"] = json!(price);
+ }
+ if let Some(qty) = disclosed_qty {
+ payload["disclosedQty"] = json!(qty);
+ }
+ if let Some(sl) = stop_loss {
+ payload["stopLoss"] = json!(sl);
+ }
+ if let Some(tp) = take_profit {
+ payload["takeProfit"] = json!(tp);
+ }
+
+ let response = client
+ .post(format!("{}/api/v3/orders", FYERS_API_BASE))
+ .headers(headers)
+ .json(&payload)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ Ok(OrderPlaceResponse {
+ success: true,
+ order_id: body.get("id").and_then(|v| v.as_str()).map(String::from),
+ error: None,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Order placement failed")
+ .to_string();
+ Ok(OrderPlaceResponse {
+ success: false,
+ order_id: None,
+ error: Some(error_msg),
+ })
+ }
+}
+
+/// Modify an existing order
+#[tauri::command]
+pub async fn fyers_modify_order(
+ api_key: String,
+ access_token: String,
+ order_id: String,
+ qty: Option<i32>,
+ r#type: Option<i32>,
+ limit_price: Option<f64>,
+ stop_price: Option<f64>,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ eprintln!("[fyers_modify_order] Modifying order {}", order_id);
+
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ let mut payload = json!({
+ "id": order_id
+ });
+
+ if let Some(q) = qty {
+ payload["qty"] = json!(q);
+ }
+ if let Some(t) = r#type {
+ payload["type"] = json!(t);
+ }
+ if let Some(price) = limit_price {
+ payload["limitPrice"] = json!(price);
+ }
+ if let Some(price) = stop_price {
+ payload["stopPrice"] = json!(price);
+ }
+
+ let response = client
+ .put(format!("{}/api/v3/orders", FYERS_API_BASE))
+ .headers(headers)
+ .json(&payload)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ Ok(ApiResponse {
+ success: true,
+ data: Some(body),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Order modification failed")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Cancel an order
+#[tauri::command]
+pub async fn fyers_cancel_order(
+ api_key: String,
+ access_token: String,
+ order_id: String,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ eprintln!("[fyers_cancel_order] Cancelling order {}", order_id);
+
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ let response = client
+ .delete(format!("{}/api/v3/orders", FYERS_API_BASE))
+ .headers(headers)
+ .json(&json!({"id": order_id}))
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ Ok(ApiResponse {
+ success: true,
+ data: Some(body),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Order cancellation failed")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get order book
+#[tauri::command]
+pub async fn fyers_get_orders(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ let response = client
+ .get(format!("{}/api/v3/orders", FYERS_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ Ok(ApiResponse {
+ success: true,
+ data: body.get("orderBook").cloned(),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch orders")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get trade book
+#[tauri::command]
+pub async fn fyers_get_trade_book(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ let response = client
+ .get(format!("{}/api/v3/tradebook", FYERS_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ Ok(ApiResponse {
+ success: true,
+ data: body.get("tradeBook").cloned(),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch trade book")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get positions
+#[tauri::command]
+pub async fn fyers_get_positions(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ let response = client
+ .get(format!("{}/api/v3/positions", FYERS_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ Ok(ApiResponse {
+ success: true,
+ data: body.get("netPositions").cloned(),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch positions")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get holdings
+#[tauri::command]
+pub async fn fyers_get_holdings(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ let response = client
+ .get(format!("{}/api/v3/holdings", FYERS_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ Ok(ApiResponse {
+ success: true,
+ data: body.get("holdings").cloned(),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch holdings")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get margin/funds data
+#[tauri::command]
+pub async fn fyers_get_funds(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ let response = client
+ .get(format!("{}/api/v3/funds", FYERS_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ Ok(ApiResponse {
+ success: true,
+ data: body.get("fund_limit").cloned(),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch funds")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get quotes for symbols using Fyers v2 API depth endpoint
+#[tauri::command]
+pub async fn fyers_get_quotes(
+ api_key: String,
+ access_token: String,
+ symbols: Vec<String>,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ // Use quotes endpoint to get OHLCV data
+ // Symbols should be in broker format (e.g., NSE:SBIN-EQ)
+ let symbols_param = symbols.join(",");
+ let url = format!("{}/data/quotes?symbols={}", FYERS_API_BASE, symbols_param);
+
+ eprintln!("[fyers_get_quotes] Requesting: {}", url);
+
+ let response = client
+ .get(&url)
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let text = response.text().await.map_err(|e| format!("Failed to read response: {}", e))?;
+
+ eprintln!("[fyers_get_quotes] Response status: {}", status);
+ eprintln!("[fyers_get_quotes] Response body: {}", text);
+
+ let body: Value = serde_json::from_str(&text).map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ // Fyers /data/quotes returns array format:
+ // { "s": "ok", "d": [{ "n": "NSE:SBIN-EQ", "s": "ok", "v": {...} }] }
+ let data_array = body.get("d").and_then(|d| d.as_array());
+
+ if let Some(arr) = data_array {
+ // Extract the "v" (value) objects from each quote
+ let quotes: Vec<Value> = arr.iter().filter_map(|item| {
+ // Each item has: "n" (name/symbol), "s" (status), "v" (values)
+ if item.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ item.get("v").cloned()
+ } else {
+ None
+ }
+ }).collect();
+
+ eprintln!("[fyers_get_quotes] Extracted {} quotes", quotes.len());
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(json!(quotes)),
+ error: None,
+ timestamp,
+ })
+ } else {
+ eprintln!("[fyers_get_quotes] No array found in response");
+ Ok(ApiResponse {
+ success: true,
+ data: body.get("d").cloned(),
+ error: None,
+ timestamp,
+ })
+ }
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch quotes")
+ .to_string();
+ eprintln!("[fyers_get_quotes] Error: {}", error_msg);
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get historical OHLCV data for a symbol using Fyers v3 API
+#[tauri::command]
+pub async fn fyers_get_history(
+ api_key: String,
+ access_token: String,
+ symbol: String,
+ resolution: String,
+ from_date: String,
+ to_date: String,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ // Fyers API expects dates in YYYY-MM-DD format
+ // Resolution: 1, 2, 3, 5, 10, 15, 20, 30, 60, 120, 240, 1D
+ // Note: Fyers history API endpoint is /data/history (NOT /data-rest/v3/history)
+ let url = format!(
+ "{}/data/history",
+ FYERS_API_BASE
+ );
+
+ // Log current system time for debugging
+ let now = chrono::Utc::now();
+ eprintln!("[fyers_get_history] Current system time: {}", now);
+
+ // Parse date strings and convert to Unix timestamps
+ // Fyers API requires epoch timestamps when date_format=0
+ let from_timestamp = chrono::NaiveDate::parse_from_str(&from_date, "%Y-%m-%d")
+ .map_err(|e| format!("Invalid from_date format: {}", e))?
+ .and_hms_opt(0, 0, 0)
+ .ok_or("Invalid time")?
+ .and_utc()
+ .timestamp();
+
+ let to_timestamp = chrono::NaiveDate::parse_from_str(&to_date, "%Y-%m-%d")
+ .map_err(|e| format!("Invalid to_date format: {}", e))?
+ .and_hms_opt(23, 59, 59)
+ .ok_or("Invalid time")?
+ .and_utc()
+ .timestamp();
+
+ let params = serde_json::json!({
+ "symbol": symbol,
+ "resolution": resolution,
+ "date_format": "0", // Unix timestamp format
+ "range_from": from_timestamp.to_string(),
+ "range_to": to_timestamp.to_string(),
+ "cont_flag": "1"
+ });
+
+ eprintln!("[fyers_get_history] ========================================");
+ eprintln!("[fyers_get_history] Symbol: {}", symbol);
+ eprintln!("[fyers_get_history] Resolution: {}", resolution);
+ eprintln!("[fyers_get_history] Date range: {} ({}) to {} ({})", from_date, from_timestamp, to_date, to_timestamp);
+ eprintln!("[fyers_get_history] Full URL: {}", url);
+ eprintln!("[fyers_get_history] Query params: {:?}", params);
+ eprintln!("[fyers_get_history] ========================================");
+
+ let response = client
+ .get(&url)
+ .headers(headers)
+ .query(&params)
+ .send()
+ .await
+ .map_err(|e| {
+ eprintln!("[fyers_get_history] ❌ Request failed: {}", e);
+ format!("Request failed: {}", e)
+ })?;
+
+ let status = response.status();
+ let text = response.text().await.map_err(|e| format!("Failed to read response: {}", e))?;
+
+ eprintln!("[fyers_get_history] Response status: {}", status);
+ eprintln!("[fyers_get_history] Response body length: {}", text.len());
+
+ if text.is_empty() {
+ eprintln!("[fyers_get_history] ❌ Empty response from Fyers API");
+ return Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some("Empty response from Fyers API. Check your API credentials and symbol format.".to_string()),
+ timestamp,
+ });
+ }
+
+ eprintln!("[fyers_get_history] Response body preview: {}...", &text[..text.len().min(200)]);
+
+ let body: Value = serde_json::from_str(&text).map_err(|e| {
+ eprintln!("[fyers_get_history] ❌ Parse error. Response was: {}", text);
+ format!("Failed to parse response: {}. Response: {}", e, text)
+ })?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ // Fyers history API returns:
+ // { "s": "ok", "candles": [[timestamp, O, H, L, C, V], ...] }
+ Ok(ApiResponse {
+ success: true,
+ data: Some(body.get("candles").unwrap_or(&serde_json::json!([])).clone()),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch historical data")
+ .to_string();
+ eprintln!("[fyers_get_history] Error: {}", error_msg);
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get market depth (orderbook) for a symbol using Fyers v3 API
+#[tauri::command]
+pub async fn fyers_get_depth(
+ api_key: String,
+ access_token: String,
+ symbol: String,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ // Fyers depth endpoint provides 5-level bid/ask orderbook
+ // Note: Fyers depth endpoint is /data/depth (NOT /data-rest/v3/depth)
+ let url = format!("{}/data/depth?symbol={}&ohlcv_flag=1", FYERS_API_BASE, symbol);
+
+ eprintln!("[fyers_get_depth] Requesting: {}", url);
+
+ let response = client
+ .get(&url)
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let text = response.text().await.map_err(|e| format!("Failed to read response: {}", e))?;
+
+ eprintln!("[fyers_get_depth] Response status: {}", status);
+ eprintln!("[fyers_get_depth] Response body: {}", text);
+
+ let body: Value = serde_json::from_str(&text).map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ // Fyers depth API returns:
+ // { "s": "ok", "d": { "totalbuyqty": N, "totalsellqty": N, "bids": [...], "ask": [...] } }
+ Ok(ApiResponse {
+ success: true,
+ data: body.get("d").cloned(),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch market depth")
+ .to_string();
+ eprintln!("[fyers_get_depth] Error: {}", error_msg);
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Calculate margin required for orders using Fyers v3 API
+#[tauri::command]
+pub async fn fyers_calculate_margin(
+ api_key: String,
+ access_token: String,
+ orders: Value,
+) -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ // Fyers multiorder margin endpoint
+ let url = format!("{}/api/v3/multiorder/margin", FYERS_API_BASE);
+
+ eprintln!("[fyers_calculate_margin] Requesting: {}", url);
+ eprintln!("[fyers_calculate_margin] Orders: {}", orders);
+
+ let response = client
+ .post(&url)
+ .headers(headers)
+ .json(&orders)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let text = response.text().await.map_err(|e| format!("Failed to read response: {}", e))?;
+
+ eprintln!("[fyers_calculate_margin] Response status: {}", status);
+ eprintln!("[fyers_calculate_margin] Response body: {}", text);
+
+ let body: Value = serde_json::from_str(&text).map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {
+ // Fyers margin API returns:
+ // { "s": "ok", "data": { "margin_avail": N, "margin_total": N, "margin_new_order": N } }
+ Ok(ApiResponse {
+ success: true,
+ data: body.get("data").cloned(),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to calculate margin")
+ .to_string();
+ eprintln!("[fyers_calculate_margin] Error: {}", error_msg);
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+// ============================================================================
+// Fyers Master Contract Commands
+// ============================================================================
+
+use crate::database::fyers_symbols::{self, FyersSymbol};
+
+/// Download and cache Fyers master contract (symbol master)
+/// This provides symbol-to-token mapping required for WebSocket subscriptions
+#[tauri::command]
+pub async fn fyers_download_master_contract(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[fyers_download_master_contract] Downloading master contract");
+
+ let timestamp = chrono::Utc::now().timestamp();
+ let headers = create_fyers_headers(&api_key, &access_token);
+ let client = reqwest::Client::new();
+
+ // Fyers provides symbol master as CSV download
+ // Note: Fyers symbol master endpoint is /data/symbol-master (NOT /data-rest/v3/symbol-master)
+ let url = format!("{}/data/symbol-master", FYERS_API_BASE);
+
+ let response = client
+ .get(&url)
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+
+ if status.is_success() {
+ // Get response body as text (CSV format)
+ let csv_data = response.text().await.map_err(|e| format!("Failed to read response: {}", e))?;
+
+ eprintln!("[fyers_download_master_contract] Downloaded CSV with {} lines", csv_data.lines().count());
+
+ // Parse CSV and populate database
+ let symbols = parse_fyers_csv(&csv_data).map_err(|e| format!("Failed to parse CSV: {}", e))?;
+
+ eprintln!("[fyers_download_master_contract] Parsed {} symbols", symbols.len());
+
+ // Save to database in bulk
+ fyers_symbols::save_symbols_bulk(&symbols).map_err(|e| format!("Failed to save symbols: {}", e))?;
+
+ eprintln!("[fyers_download_master_contract] Saved {} symbols to database", symbols.len());
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(json!({
+ "symbol_count": symbols.len(),
+ "message": "Master contract downloaded and cached successfully"
+ })),
+ error: None,
+ timestamp,
+ })
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some("Failed to download master contract".to_string()),
+ timestamp,
+ })
+ }
+}
+
+/// Parse Fyers CSV format into symbol structures
+fn parse_fyers_csv(csv_data: &str) -> Result<Vec<FyersSymbol>, String> {
+ let mut symbols = Vec::new();
+ let mut lines = csv_data.lines();
+
+ // Skip header line
+ lines.next();
+
+ for line in lines {
+ if line.trim().is_empty() {
+ continue;
+ }
+
+ let fields: Vec<&str> = line.split(',').collect();
+
+ // Fyers CSV format (typical):
+ // Token,Symbol,Name,Exchange,Segment,InstrumentType,ISIN,TickSize,LotSize
+ // Example: 11536,RELIANCE-EQ,Reliance Industries Ltd,NSE,CM,EQ,INE002A01018,0.05,1
+
+ if fields.len() >= 6 {
+ // Parse token safely
+ let token = fields[0].trim().parse::<i32>().unwrap_or(0);
+
+ if token == 0 {
+ continue; // Skip invalid tokens
+ }
+
+ let symbol = fields.get(1).unwrap_or(&"").trim().to_string();
+ let name = fields.get(2).unwrap_or(&"").trim().to_string();
+ let exchange = fields.get(3).unwrap_or(&"NSE").trim().to_string();
+ let segment = fields.get(4).unwrap_or(&"").trim().to_string();
+ let instrument_type = fields.get(5).unwrap_or(&"").trim().to_string();
+ let isin = fields.get(6).and_then(|s| {
+ let trimmed = s.trim();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed.to_string())
+ }
+ });
+ let tick_size = fields.get(7)
+ .and_then(|s| s.trim().parse::<f64>().ok())
+ .unwrap_or(0.05);
+ let lot_size = fields.get(8)
+ .and_then(|s| s.trim().parse::<i32>().ok())
+ .unwrap_or(1);
+
+ symbols.push(FyersSymbol {
+ token,
+ symbol,
+ name,
+ exchange,
+ segment,
+ instrument_type,
+ isin,
+ tick_size,
+ lot_size,
+ });
+ }
+ }
+
+ Ok(symbols)
+}
+
+/// Search for symbols in master contract
+#[tauri::command]
+pub async fn fyers_search_symbol(
+ keyword: String,
+ exchange: Option<String>,
+ limit: Option<i32>,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[fyers_search_symbol] Searching for: {} on exchange: {:?}", keyword, exchange);
+
+ let timestamp = chrono::Utc::now().timestamp();
+ let search_limit = limit.unwrap_or(20);
+
+ match fyers_symbols::search_symbols(&keyword, exchange.as_deref(), search_limit) {
+ Ok(results) => {
+ eprintln!("[fyers_search_symbol] Found {} results", results.len());
+ Ok(ApiResponse {
+ success: true,
+ data: Some(json!({
+ "results": results,
+ "count": results.len()
+ })),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ eprintln!("[fyers_search_symbol] Error: {}", e);
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(format!("Search failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+}
+
+/// Get token for symbol (required for WebSocket subscription)
+#[tauri::command]
+pub async fn fyers_get_token_for_symbol(
+ symbol: String,
+ exchange: String,
+) -> Result<ApiResponse<i32>, String> {
+ eprintln!("[fyers_get_token_for_symbol] Getting token for: {}:{}", exchange, symbol);
+
+ let timestamp = chrono::Utc::now().timestamp();
+
+ match fyers_symbols::get_token_by_symbol(&symbol, &exchange) {
+ Ok(Some(token)) => {
+ eprintln!("[fyers_get_token_for_symbol] Found token: {}", token);
+ Ok(ApiResponse {
+ success: true,
+ data: Some(token),
+ error: None,
+ timestamp,
+ })
+ }
+ Ok(None) => {
+ eprintln!("[fyers_get_token_for_symbol] Symbol not found");
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(format!("Symbol {}:{} not found in master contract", exchange, symbol)),
+ timestamp,
+ })
+ }
+ Err(e) => {
+ eprintln!("[fyers_get_token_for_symbol] Error: {}", e);
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(format!("Lookup failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+}
+
+/// Get symbol info by token
+#[tauri::command]
+pub async fn fyers_get_symbol_by_token(
+ token: i32,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[fyers_get_symbol_by_token] Getting symbol for token: {}", token);
+
+ let timestamp = chrono::Utc::now().timestamp();
+
+ match fyers_symbols::get_symbol_by_token(token) {
+ Ok(Some(symbol_info)) => {
+ Ok(ApiResponse {
+ success: true,
+ data: Some(json!(symbol_info)),
+ error: None,
+ timestamp,
+ })
+ }
+ Ok(None) => {
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(format!("Token {} not found", token)),
+ timestamp,
+ })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(format!("Lookup failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+}
+
+/// Get master contract metadata (last updated, count)
+#[tauri::command]
+pub async fn fyers_get_master_contract_metadata() -> Result<ApiResponse<Value>, String> {
+ let timestamp = chrono::Utc::now().timestamp();
+
+ match fyers_symbols::get_metadata() {
+ Ok(Some((last_updated, count))) => {
+ Ok(ApiResponse {
+ success: true,
+ data: Some(json!({
+ "last_updated": last_updated,
+ "symbol_count": count,
+ "age_seconds": timestamp - last_updated
+ })),
+ error: None,
+ timestamp,
+ })
+ }
+ Ok(None) => {
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some("Master contract not downloaded yet".to_string()),
+ timestamp,
+ })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(format!("Failed to get metadata: {}", e)),
+ timestamp,
+ })
+ }
+ }
+}
+
+// ============================================================================
+// Fyers WebSocket Commands
+// ============================================================================
+
+// Global Fyers WebSocket adapter instance
+static FYERS_WS: Lazy<Arc<RwLock<Option<crate::websocket::adapters::FyersAdapter>>>> =
+ Lazy::new(|| Arc::new(RwLock::new(None)));
+
+/// Connect to Fyers WebSocket with Tauri event emission
+#[tauri::command]
+pub async fn fyers_ws_connect(
+ app: tauri::AppHandle,
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<bool>, String> {
+ eprintln!("[fyers_ws_connect] WebSocket connection request");
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ // Create adapter with credentials
+ let config = ProviderConfig {
+ name: "fyers".to_string(),
+ url: "wss://socket.fyers.in/hsm/v1-5/prod".to_string(),
+ api_key: Some(access_token.clone()),
+ api_secret: None,
+ enabled: true,
+ reconnect_delay_ms: 5000,
+ max_reconnect_attempts: 10,
+ heartbeat_interval_ms: 30000,
+ };
+
+ let mut adapter = crate::websocket::adapters::FyersAdapter::new(config);
+
+ // Set up message callback to emit Tauri events
+ let app_handle = app.clone();
+ adapter.set_message_callback(Box::new(move |msg: MarketMessage| {
+ match &msg {
+ MarketMessage::Ticker(data) => {
+ let _ = app_handle.emit("fyers_ticker", data);
+ }
+ MarketMessage::OrderBook(data) => {
+ let _ = app_handle.emit("fyers_orderbook", data);
+ }
+ MarketMessage::Trade(data) => {
+ let _ = app_handle.emit("fyers_trade", data);
+ }
+ MarketMessage::Status(data) => {
+ let _ = app_handle.emit("fyers_status", data);
+ }
+ MarketMessage::Candle(data) => {
+ let _ = app_handle.emit("fyers_candle", data);
+ }
+ }
+ }));
+
+ // Connect to WebSocket
+ match adapter.connect().await {
+ Ok(_) => {
+ // Store the adapter
+ let mut ws_guard = FYERS_WS.write().await;
+ *ws_guard = Some(adapter);
+
+ eprintln!("[fyers_ws_connect] WebSocket connected successfully");
+
+ // Emit connection success event
+ let _ = app.emit("fyers_status", json!({
+ "provider": "fyers",
+ "status": "connected",
+ "message": "Connected to Fyers WebSocket",
+ "timestamp": chrono::Utc::now().timestamp_millis()
+ }));
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ eprintln!("[fyers_ws_connect] WebSocket connection failed: {}", e);
+
+ // Emit connection failure event
+ let _ = app.emit("fyers_status", json!({
+ "provider": "fyers",
+ "status": "error",
+ "message": format!("Connection failed: {}", e),
+ "timestamp": chrono::Utc::now().timestamp_millis()
+ }));
+
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some(format!("WebSocket connection failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+}
+
+/// Disconnect from Fyers WebSocket
+#[tauri::command]
+pub async fn fyers_ws_disconnect() -> Result<ApiResponse<bool>, String> {
+ eprintln!("[fyers_ws_disconnect] WebSocket disconnect request");
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ let mut ws_guard = FYERS_WS.write().await;
+
+ if let Some(ref mut adapter) = *ws_guard {
+ match adapter.disconnect().await {
+ Ok(_) => {
+ *ws_guard = None;
+ eprintln!("[fyers_ws_disconnect] WebSocket disconnected successfully");
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some(format!("Disconnect failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some("WebSocket not connected".to_string()),
+ timestamp,
+ })
+ }
+}
+
+/// Subscribe to symbol via Fyers WebSocket
+#[tauri::command]
+pub async fn fyers_ws_subscribe(
+ symbol: String,
+ mode: String,
+) -> Result<ApiResponse<bool>, String> {
+ eprintln!("[fyers_ws_subscribe] Subscribing to {} in {} mode", symbol, mode);
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ let mut ws_guard = FYERS_WS.write().await;
+
+ if let Some(ref mut adapter) = *ws_guard {
+ // Map mode to channel
+ let channel = match mode.as_str() {
+ "ltp" => "ltp",
+ "quotes" | "quote" => "quotes",
+ "depth" | "market_depth" => "depth",
+ _ => "ltp",
+ };
+
+ match adapter.subscribe(&symbol, channel, None).await {
+ Ok(_) => {
+ eprintln!("[fyers_ws_subscribe] Successfully subscribed to {}", symbol);
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some(format!("Subscription failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some("WebSocket not connected. Call fyers_ws_connect first.".to_string()),
+ timestamp,
+ })
+ }
+}
+
+/// Unsubscribe from symbol via Fyers WebSocket
+#[tauri::command]
+pub async fn fyers_ws_unsubscribe(
+ symbol: String,
+) -> Result<ApiResponse<bool>, String> {
+ eprintln!("[fyers_ws_unsubscribe] Unsubscribing from {}", symbol);
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ let mut ws_guard = FYERS_WS.write().await;
+
+ if let Some(ref mut adapter) = *ws_guard {
+ match adapter.unsubscribe(&symbol, "").await {
+ Ok(_) => {
+ eprintln!("[fyers_ws_unsubscribe] Successfully unsubscribed from {}", symbol);
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some(format!("Unsubscription failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some("WebSocket not connected".to_string()),
+ timestamp,
+ })
+ }
+}
+
+/// Check Fyers WebSocket connection status
+#[tauri::command]
+pub async fn fyers_ws_is_connected() -> Result<bool, String> {
+ let ws_guard = FYERS_WS.read().await;
+
+ if let Some(ref adapter) = *ws_guard {
+ Ok(adapter.is_connected())
+ } else {
+ Ok(false)
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/mod.rs
new file mode 100644
index 000000000..e7368cd85
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/mod.rs
@@ -0,0 +1,31 @@
+//! Indian Stock Brokers Module
+//!
+//! This module contains broker-specific integrations for Indian stock brokers.
+//! Each broker has its own file with complete API implementation.
+//!
+//! ## Available Brokers:
+//! - **Fyers**: Full-featured broker with OAuth, orders, positions, WebSocket
+//! - **Zerodha**: Kite Connect API with smart orders, bulk operations
+//!
+//! ## Module Structure:
+//! ```
+//! brokers/
+//! ├── common.rs - Shared types and utilities
+//! ├── fyers.rs - Fyers broker (23 commands)
+//! ├── zerodha.rs - Zerodha broker (24 commands)
+//! └── mod.rs - This file (re-exports)
+//! ```
+
+pub mod common;
+pub mod common_commands;
+pub mod fyers;
+pub mod zerodha;
+
+// Re-export everything from fyers (includes tauri command wrappers)
+pub use fyers::*;
+
+// Re-export everything from zerodha (includes tauri command wrappers)
+pub use zerodha::*;
+
+// Re-export common utility commands
+pub use common_commands::*;
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs
new file mode 100644
index 000000000..e7ce647f9
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/zerodha.rs
@@ -0,0 +1,1493 @@
+//! Zerodha (Kite) Broker Integration
+//!
+//! Complete API implementation for Zerodha/Kite broker including:
+//! - Authentication (OAuth with SHA256 checksum)
+//! - Order Management (place, modify, cancel, smart orders)
+//! - Portfolio (positions, holdings, margins)
+//! - Market Data (quotes, historical, depth)
+//! - Bulk Operations (cancel all, close all positions)
+//! - WebSocket (real-time data streaming)
+
+use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
+use serde_json::{json, Value};
+use sha2::{Sha256, Digest};
+use std::sync::Arc;
+use std::collections::HashMap;
+use tokio::sync::RwLock;
+use once_cell::sync::Lazy;
+use tauri::Emitter;
+
+use crate::websocket::adapters::WebSocketAdapter;
+use crate::websocket::types::MarketMessage;
+use super::common::{ApiResponse, TokenExchangeResponse, OrderPlaceResponse};
+
+// Zerodha API Configuration
+// ============================================================================
+
+const ZERODHA_API_BASE: &str = "https://api.kite.trade";
+const ZERODHA_API_VERSION: &str = "3";
+
+fn create_zerodha_headers(api_key: &str, access_token: &str) -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ headers.insert("X-Kite-Version", HeaderValue::from_static(ZERODHA_API_VERSION));
+
+ let auth_value = format!("token {}:{}", api_key, access_token);
+ if let Ok(header_value) = HeaderValue::from_str(&auth_value) {
+ headers.insert(AUTHORIZATION, header_value);
+ }
+
+ headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/x-www-form-urlencoded"));
+ headers
+}
+
+// ============================================================================
+// Zerodha Authentication Commands
+// ============================================================================
+
+/// Exchange request token for access token
+#[tauri::command]
+pub async fn zerodha_exchange_token(
+ api_key: String,
+ api_secret: String,
+ request_token: String,
+) -> Result<TokenExchangeResponse, String> {
+ eprintln!("[zerodha_exchange_token] Exchanging request token");
+
+ // Create checksum: SHA256(api_key + request_token + api_secret)
+ let checksum_input = format!("{}{}{}", api_key, request_token, api_secret);
+ let mut hasher = Sha256::new();
+ hasher.update(checksum_input.as_bytes());
+ let checksum = format!("{:x}", hasher.finalize());
+
+ let client = reqwest::Client::new();
+
+ let params = [
+ ("api_key", api_key.as_str()),
+ ("request_token", request_token.as_str()),
+ ("checksum", checksum.as_str()),
+ ];
+
+ let response = client
+ .post(format!("{}/session/token", ZERODHA_API_BASE))
+ .header("X-Kite-Version", ZERODHA_API_VERSION)
+ .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
+ .form(&params)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data").ok_or("No data in response")?;
+ Ok(TokenExchangeResponse {
+ success: true,
+ access_token: data.get("access_token").and_then(|v| v.as_str()).map(String::from),
+ user_id: data.get("user_id").and_then(|v| v.as_str()).map(String::from),
+ error: None,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Token exchange failed")
+ .to_string();
+ Ok(TokenExchangeResponse {
+ success: false,
+ access_token: None,
+ user_id: None,
+ error: Some(error_msg),
+ })
+ }
+}
+
+/// Validate access token by fetching user profile
+#[tauri::command]
+pub async fn zerodha_validate_token(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<bool>, String> {
+ eprintln!("[zerodha_validate_token] Validating access token");
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let response = client
+ .get(format!("{}/user/profile", ZERODHA_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if status.is_success() {
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some("Token validation failed".to_string()),
+ timestamp,
+ })
+ }
+}
+
+// ============================================================================
+// Zerodha Order Commands
+// ============================================================================
+
+/// Place an order
+#[tauri::command]
+pub async fn zerodha_place_order(
+ api_key: String,
+ access_token: String,
+ params: HashMap<String, Value>,
+ variety: String,
+) -> Result<OrderPlaceResponse, String> {
+ eprintln!("[zerodha_place_order] Placing {} order", variety);
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ // Convert params to form data
+ let form_params: Vec<(String, String)> = params
+ .iter()
+ .map(|(k, v)| {
+ let value = match v {
+ Value::String(s) => s.clone(),
+ Value::Number(n) => n.to_string(),
+ _ => v.to_string(),
+ };
+ (k.clone(), value)
+ })
+ .collect();
+
+ let url = format!("{}/orders/{}", ZERODHA_API_BASE, variety);
+
+ let response = client
+ .post(&url)
+ .headers(headers)
+ .form(&form_params)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data").ok_or("No data in response")?;
+ Ok(OrderPlaceResponse {
+ success: true,
+ order_id: data.get("order_id").and_then(|v| v.as_str()).map(String::from),
+ error: None,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Order placement failed")
+ .to_string();
+ Ok(OrderPlaceResponse {
+ success: false,
+ order_id: None,
+ error: Some(error_msg),
+ })
+ }
+}
+
+/// Modify an order
+#[tauri::command]
+pub async fn zerodha_modify_order(
+ api_key: String,
+ access_token: String,
+ order_id: String,
+ params: HashMap<String, Value>,
+) -> Result<OrderPlaceResponse, String> {
+ eprintln!("[zerodha_modify_order] Modifying order: {}", order_id);
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let form_params: Vec<(String, String)> = params
+ .iter()
+ .map(|(k, v)| {
+ let value = match v {
+ Value::String(s) => s.clone(),
+ Value::Number(n) => n.to_string(),
+ _ => v.to_string(),
+ };
+ (k.clone(), value)
+ })
+ .collect();
+
+ let url = format!("{}/orders/regular/{}", ZERODHA_API_BASE, order_id);
+
+ let response = client
+ .put(&url)
+ .headers(headers)
+ .form(&form_params)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data").ok_or("No data in response")?;
+ Ok(OrderPlaceResponse {
+ success: true,
+ order_id: data.get("order_id").and_then(|v| v.as_str()).map(String::from),
+ error: None,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Order modification failed")
+ .to_string();
+ Ok(OrderPlaceResponse {
+ success: false,
+ order_id: None,
+ error: Some(error_msg),
+ })
+ }
+}
+
+/// Cancel an order
+#[tauri::command]
+pub async fn zerodha_cancel_order(
+ api_key: String,
+ access_token: String,
+ order_id: String,
+) -> Result<OrderPlaceResponse, String> {
+ eprintln!("[zerodha_cancel_order] Cancelling order: {}", order_id);
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let url = format!("{}/orders/regular/{}", ZERODHA_API_BASE, order_id);
+
+ let response = client
+ .delete(&url)
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data").ok_or("No data in response")?;
+ Ok(OrderPlaceResponse {
+ success: true,
+ order_id: data.get("order_id").and_then(|v| v.as_str()).map(String::from),
+ error: None,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Order cancellation failed")
+ .to_string();
+ Ok(OrderPlaceResponse {
+ success: false,
+ order_id: None,
+ error: Some(error_msg),
+ })
+ }
+}
+
+/// Get all orders
+#[tauri::command]
+pub async fn zerodha_get_orders(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Vec<Value>>, String> {
+ eprintln!("[zerodha_get_orders] Fetching orders");
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let response = client
+ .get(format!("{}/orders", ZERODHA_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data")
+ .and_then(|d| d.as_array())
+ .map(|arr| arr.clone())
+ .unwrap_or_default();
+ Ok(ApiResponse {
+ success: true,
+ data: Some(data),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch orders")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+// ============================================================================
+// Zerodha Position & Holdings Commands
+// ============================================================================
+
+/// Get positions
+#[tauri::command]
+pub async fn zerodha_get_positions(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[zerodha_get_positions] Fetching positions");
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let response = client
+ .get(format!("{}/portfolio/positions", ZERODHA_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data").cloned().unwrap_or(json!({}));
+ Ok(ApiResponse {
+ success: true,
+ data: Some(data),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch positions")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get holdings
+#[tauri::command]
+pub async fn zerodha_get_holdings(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Vec<Value>>, String> {
+ eprintln!("[zerodha_get_holdings] Fetching holdings");
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let response = client
+ .get(format!("{}/portfolio/holdings", ZERODHA_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data")
+ .and_then(|d| d.as_array())
+ .map(|arr| arr.clone())
+ .unwrap_or_default();
+ Ok(ApiResponse {
+ success: true,
+ data: Some(data),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch holdings")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get margins/funds
+#[tauri::command]
+pub async fn zerodha_get_margins(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[zerodha_get_margins] Fetching margins");
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let response = client
+ .get(format!("{}/user/margins", ZERODHA_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data").cloned().unwrap_or(json!({}));
+ Ok(ApiResponse {
+ success: true,
+ data: Some(data),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch margins")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+// ============================================================================
+// Zerodha Market Data Commands
+// ============================================================================
+
+/// Get quotes for instruments
+#[tauri::command]
+pub async fn zerodha_get_quote(
+ api_key: String,
+ access_token: String,
+ instruments: Vec<String>,
+) -> Result<ApiResponse<HashMap<String, Value>>, String> {
+ eprintln!("[zerodha_get_quote] Fetching quotes for {} instruments", instruments.len());
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ // Build query params
+ let instruments_param = instruments.join("&i=");
+ let url = format!("{}/quote?i={}", ZERODHA_API_BASE, instruments_param);
+
+ let response = client
+ .get(&url)
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data")
+ .and_then(|d| d.as_object())
+ .map(|obj| obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
+ .unwrap_or_default();
+ Ok(ApiResponse {
+ success: true,
+ data: Some(data),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch quotes")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get historical data (OHLCV)
+#[tauri::command]
+pub async fn zerodha_get_historical(
+ api_key: String,
+ access_token: String,
+ instrument_token: String,
+ interval: String,
+ from: String,
+ to: String,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[zerodha_get_historical] Fetching historical data for {}", instrument_token);
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let url = format!(
+ "{}/instruments/historical/{}/{}?from={}&to={}",
+ ZERODHA_API_BASE, instrument_token, interval, from, to
+ );
+
+ let response = client
+ .get(&url)
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data").cloned().unwrap_or(json!({}));
+ Ok(ApiResponse {
+ success: true,
+ data: Some(data),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch historical data")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Download master contract (instruments list)
+#[tauri::command]
+pub async fn zerodha_download_master_contract(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Vec<Value>>, String> {
+ eprintln!("[zerodha_download_master_contract] Downloading instruments");
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let response = client
+ .get(format!("{}/instruments", ZERODHA_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if status.is_success() {
+ // Instruments endpoint returns CSV
+ let csv_data = response.text().await.map_err(|e| format!("Failed to read response: {}", e))?;
+
+ // Parse CSV to JSON
+ let mut instruments: Vec<Value> = Vec::new();
+ let mut lines = csv_data.lines();
+
+ // Get headers
+ let headers: Vec<&str> = if let Some(header_line) = lines.next() {
+ header_line.split(',').collect()
+ } else {
+ return Err("Empty CSV response".to_string());
+ };
+
+ // Parse each row
+ for line in lines {
+ let values: Vec<&str> = line.split(',').collect();
+ if values.len() == headers.len() {
+ let mut obj = serde_json::Map::new();
+ for (i, header) in headers.iter().enumerate() {
+ obj.insert(header.to_string(), json!(values[i]));
+ }
+ instruments.push(Value::Object(obj));
+ }
+ }
+
+ eprintln!("[zerodha_download_master_contract] Downloaded {} instruments", instruments.len());
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(instruments),
+ error: None,
+ timestamp,
+ })
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some("Failed to download instruments".to_string()),
+ timestamp,
+ })
+ }
+}
+
+// ============================================================================
+// Zerodha WebSocket Commands
+// ============================================================================
+
+// Global Zerodha WebSocket adapter instance
+static ZERODHA_WS: Lazy<Arc<RwLock<Option<crate::websocket::adapters::ZerodhaAdapter>>>> =
+ Lazy::new(|| Arc::new(RwLock::new(None)));
+
+/// Connect to Zerodha WebSocket with Tauri event emission
+#[tauri::command]
+pub async fn zerodha_ws_connect(
+ app: tauri::AppHandle,
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<bool>, String> {
+ eprintln!("[zerodha_ws_connect] WebSocket connection request");
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ // Validate token first
+ let validate_result = zerodha_validate_token(api_key.clone(), access_token.clone()).await?;
+
+ if !validate_result.success {
+ return Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some("Invalid credentials for WebSocket".to_string()),
+ timestamp,
+ });
+ }
+
+ // Create adapter with credentials
+ let mut adapter = crate::websocket::adapters::ZerodhaAdapter::new_with_credentials(
+ api_key,
+ access_token,
+ );
+
+ // Set up message callback to emit Tauri events
+ let app_handle = app.clone();
+ adapter.set_message_callback(Box::new(move |msg: MarketMessage| {
+ match &msg {
+ MarketMessage::Ticker(data) => {
+ let _ = app_handle.emit("zerodha_ticker", data);
+ }
+ MarketMessage::OrderBook(data) => {
+ let _ = app_handle.emit("zerodha_orderbook", data);
+ }
+ MarketMessage::Trade(data) => {
+ let _ = app_handle.emit("zerodha_trade", data);
+ }
+ MarketMessage::Status(data) => {
+ let _ = app_handle.emit("zerodha_status", data);
+ }
+ MarketMessage::Candle(data) => {
+ let _ = app_handle.emit("zerodha_candle", data);
+ }
+ }
+ }));
+
+ // Connect to WebSocket
+ match adapter.connect().await {
+ Ok(_) => {
+ // Store the adapter
+ let mut ws_guard = ZERODHA_WS.write().await;
+ *ws_guard = Some(adapter);
+
+ eprintln!("[zerodha_ws_connect] WebSocket connected successfully");
+
+ // Emit connection success event
+ let _ = app.emit("zerodha_status", json!({
+ "provider": "zerodha",
+ "status": "connected",
+ "message": "Connected to Zerodha KiteTicker",
+ "timestamp": chrono::Utc::now().timestamp_millis()
+ }));
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ eprintln!("[zerodha_ws_connect] WebSocket connection failed: {}", e);
+
+ // Emit connection failure event
+ let _ = app.emit("zerodha_status", json!({
+ "provider": "zerodha",
+ "status": "error",
+ "message": format!("Connection failed: {}", e),
+ "timestamp": chrono::Utc::now().timestamp_millis()
+ }));
+
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some(format!("WebSocket connection failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+}
+
+/// Disconnect from Zerodha WebSocket
+#[tauri::command]
+pub async fn zerodha_ws_disconnect() -> Result<ApiResponse<bool>, String> {
+ eprintln!("[zerodha_ws_disconnect] WebSocket disconnect request");
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ let mut ws_guard = ZERODHA_WS.write().await;
+
+ if let Some(ref mut adapter) = *ws_guard {
+ match adapter.disconnect().await {
+ Ok(_) => {
+ *ws_guard = None;
+ eprintln!("[zerodha_ws_disconnect] WebSocket disconnected successfully");
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some(format!("Disconnect failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some("WebSocket not connected".to_string()),
+ timestamp,
+ })
+ }
+}
+
+/// Subscribe to symbols via WebSocket
+#[tauri::command]
+pub async fn zerodha_ws_subscribe(
+ tokens: Vec<i64>,
+ mode: String,
+) -> Result<ApiResponse<bool>, String> {
+ eprintln!("[zerodha_ws_subscribe] Subscribing to {} tokens in {} mode", tokens.len(), mode);
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ let ws_guard = ZERODHA_WS.read().await;
+
+ if let Some(ref adapter) = *ws_guard {
+ match adapter.subscribe_tokens(tokens.clone(), &mode).await {
+ Ok(_) => {
+ eprintln!("[zerodha_ws_subscribe] Successfully subscribed to {} tokens", tokens.len());
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some(format!("Subscription failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some("WebSocket not connected. Call zerodha_ws_connect first.".to_string()),
+ timestamp,
+ })
+ }
+}
+
+/// Unsubscribe from symbols via WebSocket
+#[tauri::command]
+pub async fn zerodha_ws_unsubscribe(
+ tokens: Vec<i64>,
+) -> Result<ApiResponse<bool>, String> {
+ eprintln!("[zerodha_ws_unsubscribe] Unsubscribing from {} tokens", tokens.len());
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ let ws_guard = ZERODHA_WS.read().await;
+
+ if let Some(ref adapter) = *ws_guard {
+ match adapter.unsubscribe_tokens(tokens.clone()).await {
+ Ok(_) => {
+ eprintln!("[zerodha_ws_unsubscribe] Successfully unsubscribed from {} tokens", tokens.len());
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ }
+ Err(e) => {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some(format!("Unsubscription failed: {}", e)),
+ timestamp,
+ })
+ }
+ }
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some("WebSocket not connected".to_string()),
+ timestamp,
+ })
+ }
+}
+
+/// Set token-to-symbol mapping for tick data resolution
+#[tauri::command]
+pub async fn zerodha_ws_set_token_map(
+ token: i64,
+ symbol: String,
+ exchange: String,
+) -> Result<ApiResponse<bool>, String> {
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ let ws_guard = ZERODHA_WS.read().await;
+
+ if let Some(ref adapter) = *ws_guard {
+ adapter.set_token_symbol_map(token, symbol.clone(), exchange.clone());
+ Ok(ApiResponse {
+ success: true,
+ data: Some(true),
+ error: None,
+ timestamp,
+ })
+ } else {
+ Ok(ApiResponse {
+ success: false,
+ data: Some(false),
+ error: Some("WebSocket not connected".to_string()),
+ timestamp,
+ })
+ }
+}
+
+/// Check WebSocket connection status
+#[tauri::command]
+pub async fn zerodha_ws_is_connected() -> Result<bool, String> {
+ let ws_guard = ZERODHA_WS.read().await;
+
+ if let Some(ref adapter) = *ws_guard {
+ Ok(adapter.is_connected())
+ } else {
+ Ok(false)
+ }
+}
+
+/// Search symbols in master contract
+#[tauri::command]
+pub async fn search_indian_symbols(
+ broker_id: String,
+ query: String,
+ exchange: Option<String>,
+) -> Result<Vec<Value>, String> {
+ eprintln!("[search_indian_symbols] Searching for '{}' in {} broker", query, broker_id);
+
+ use crate::commands::master_contract::get_master_contract_cache;
+
+ // Get cached master contract
+ let cache_data = get_master_contract_cache(broker_id.clone()).await?;
+
+ // Parse the cached data
+ let instruments: Vec<Value> = serde_json::from_str(&cache_data)
+ .map_err(|e| format!("Failed to parse master contract: {}", e))?;
+
+ // Filter instruments
+ let query_lower = query.to_lowercase();
+ let results: Vec<Value> = instruments
+ .into_iter()
+ .filter(|inst| {
+ let symbol = inst.get("symbol")
+ .or(inst.get("tradingsymbol"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_lowercase();
+
+ let name = inst.get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_lowercase();
+
+ let inst_exchange = inst.get("exchange")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ let matches_query = symbol.contains(&query_lower) || name.contains(&query_lower);
+ let matches_exchange = exchange.as_ref()
+ .map(|e| inst_exchange.eq_ignore_ascii_case(e))
+ .unwrap_or(true);
+
+ matches_query && matches_exchange
+ })
+ .take(50) // Limit results
+ .collect();
+
+ Ok(results)
+}
+
+/// Get symbol token from master contract
+#[tauri::command]
+pub async fn get_indian_symbol_token(
+ broker_id: String,
+ symbol: String,
+ exchange: String,
+) -> Result<Option<Value>, String> {
+ eprintln!("[get_indian_symbol_token] Getting token for {}:{}", exchange, symbol);
+
+ use crate::commands::master_contract::get_master_contract_cache;
+
+ // Get cached master contract
+ let cache_data = get_master_contract_cache(broker_id.clone()).await?;
+
+ // Parse the cached data
+ let instruments: Vec<Value> = serde_json::from_str(&cache_data)
+ .map_err(|e| format!("Failed to parse master contract: {}", e))?;
+
+ // Find matching instrument
+ let symbol_upper = symbol.to_uppercase();
+ let exchange_upper = exchange.to_uppercase();
+
+ let result = instruments
+ .into_iter()
+ .find(|inst| {
+ let inst_symbol = inst.get("symbol")
+ .or(inst.get("tradingsymbol"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_uppercase();
+
+ let inst_exchange = inst.get("exchange")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_uppercase();
+
+ inst_symbol == symbol_upper && inst_exchange == exchange_upper
+ });
+
+ Ok(result)
+}
+
+/// Get master contract last updated timestamp
+#[tauri::command]
+pub async fn get_master_contract_timestamp(
+ broker_id: String,
+) -> Result<Option<i64>, String> {
+ eprintln!("[get_master_contract_timestamp] Getting timestamp for: {}", broker_id);
+
+ use crate::commands::master_contract::get_master_contract_cache_info;
+
+ match get_master_contract_cache_info(broker_id).await {
+ Ok(info) => Ok(Some(info.last_updated)),
+ Err(_) => Ok(None),
+ }
+}
+
+// ============================================================================
+// Zerodha Trade Book & Position Commands
+// ============================================================================
+
+/// Get trade book (executed trades)
+#[tauri::command]
+pub async fn zerodha_get_trade_book(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Vec<Value>>, String> {
+ eprintln!("[zerodha_get_trade_book] Fetching trade book");
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+
+ let response = client
+ .get(format!("{}/trades", ZERODHA_API_BASE))
+ .headers(headers)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data")
+ .and_then(|d| d.as_array())
+ .map(|arr| arr.clone())
+ .unwrap_or_default();
+ Ok(ApiResponse {
+ success: true,
+ data: Some(data),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to fetch trade book")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+/// Get open position for a specific symbol
+#[tauri::command]
+pub async fn zerodha_get_open_position(
+ api_key: String,
+ access_token: String,
+ tradingsymbol: String,
+ exchange: String,
+ product: String,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[zerodha_get_open_position] Fetching position for {}:{}", exchange, tradingsymbol);
+
+ // Get all positions first
+ let positions_response = zerodha_get_positions(api_key, access_token).await?;
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ if !positions_response.success {
+ return Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: positions_response.error,
+ timestamp,
+ });
+ }
+
+ // Find the matching position
+ if let Some(positions_data) = positions_response.data {
+ // Check net positions
+ if let Some(net) = positions_data.get("net").and_then(|n| n.as_array()) {
+ for position in net {
+ let pos_symbol = position.get("tradingsymbol").and_then(|s| s.as_str()).unwrap_or("");
+ let pos_exchange = position.get("exchange").and_then(|s| s.as_str()).unwrap_or("");
+ let pos_product = position.get("product").and_then(|s| s.as_str()).unwrap_or("");
+
+ if pos_symbol == tradingsymbol && pos_exchange == exchange && pos_product == product {
+ let quantity = position.get("quantity").and_then(|q| q.as_i64()).unwrap_or(0);
+ return Ok(ApiResponse {
+ success: true,
+ data: Some(json!({
+ "tradingsymbol": pos_symbol,
+ "exchange": pos_exchange,
+ "product": pos_product,
+ "quantity": quantity,
+ "position": position.clone()
+ })),
+ error: None,
+ timestamp,
+ });
+ }
+ }
+ }
+ }
+
+ // Position not found - return with quantity 0
+ Ok(ApiResponse {
+ success: true,
+ data: Some(json!({
+ "tradingsymbol": tradingsymbol,
+ "exchange": exchange,
+ "product": product,
+ "quantity": 0,
+ "position": null
+ })),
+ error: None,
+ timestamp,
+ })
+}
+
+// ============================================================================
+// Zerodha Smart Order Commands
+// ============================================================================
+
+/// Place smart order (checks position and adjusts action)
+#[tauri::command]
+pub async fn zerodha_place_smart_order(
+ api_key: String,
+ access_token: String,
+ tradingsymbol: String,
+ exchange: String,
+ product: String,
+ action: String,
+ quantity: i64,
+ order_type: String,
+ price: Option<f64>,
+ trigger_price: Option<f64>,
+ position_size: i64,
+) -> Result<OrderPlaceResponse, String> {
+ eprintln!("[zerodha_place_smart_order] Smart order for {}:{}", exchange, tradingsymbol);
+
+ // Determine actual action based on position
+ let (final_action, final_quantity) = if action.to_uppercase() == "BUY" {
+ if position_size == 0 {
+ // No position, buy
+ ("BUY".to_string(), quantity)
+ } else if position_size > 0 {
+ // Already long, add to position
+ ("BUY".to_string(), quantity)
+ } else {
+ // Short position, close first then buy
+ let close_qty = position_size.abs();
+ if quantity <= close_qty {
+ ("BUY".to_string(), quantity)
+ } else {
+ ("BUY".to_string(), quantity)
+ }
+ }
+ } else {
+ // SELL action
+ if position_size == 0 {
+ // No position, sell (short)
+ ("SELL".to_string(), quantity)
+ } else if position_size < 0 {
+ // Already short, add to position
+ ("SELL".to_string(), quantity)
+ } else {
+ // Long position, close
+ ("SELL".to_string(), quantity)
+ }
+ };
+
+ // Build order params
+ let mut params = HashMap::new();
+ params.insert("tradingsymbol".to_string(), json!(tradingsymbol));
+ params.insert("exchange".to_string(), json!(exchange));
+ params.insert("transaction_type".to_string(), json!(final_action));
+ params.insert("quantity".to_string(), json!(final_quantity));
+ params.insert("product".to_string(), json!(product));
+ params.insert("order_type".to_string(), json!(order_type));
+
+ if let Some(p) = price {
+ if p > 0.0 {
+ params.insert("price".to_string(), json!(p));
+ }
+ }
+
+ if let Some(tp) = trigger_price {
+ if tp > 0.0 {
+ params.insert("trigger_price".to_string(), json!(tp));
+ }
+ }
+
+ zerodha_place_order(api_key, access_token, params, "regular".to_string()).await
+}
+
+// ============================================================================
+// Zerodha Bulk Operations
+// ============================================================================
+
+/// Close all open positions
+#[tauri::command]
+pub async fn zerodha_close_all_positions(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Vec<OrderPlaceResponse>>, String> {
+ eprintln!("[zerodha_close_all_positions] Closing all positions");
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ // Get all positions
+ let positions_response = zerodha_get_positions(api_key.clone(), access_token.clone()).await?;
+
+ if !positions_response.success {
+ return Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: positions_response.error,
+ timestamp,
+ });
+ }
+
+ let mut results: Vec<OrderPlaceResponse> = Vec::new();
+
+ if let Some(positions_data) = positions_response.data {
+ if let Some(net) = positions_data.get("net").and_then(|n| n.as_array()) {
+ for position in net {
+ let quantity = position.get("quantity").and_then(|q| q.as_i64()).unwrap_or(0);
+
+ // Skip if no open position
+ if quantity == 0 {
+ continue;
+ }
+
+ let tradingsymbol = position.get("tradingsymbol").and_then(|s| s.as_str()).unwrap_or("").to_string();
+ let exchange = position.get("exchange").and_then(|s| s.as_str()).unwrap_or("").to_string();
+ let product = position.get("product").and_then(|s| s.as_str()).unwrap_or("").to_string();
+
+ // Determine action to close position
+ let action = if quantity > 0 { "SELL" } else { "BUY" };
+ let close_quantity = quantity.abs();
+
+ // Build order params
+ let mut params = HashMap::new();
+ params.insert("tradingsymbol".to_string(), json!(tradingsymbol));
+ params.insert("exchange".to_string(), json!(exchange));
+ params.insert("transaction_type".to_string(), json!(action));
+ params.insert("quantity".to_string(), json!(close_quantity));
+ params.insert("product".to_string(), json!(product));
+ params.insert("order_type".to_string(), json!("MARKET"));
+
+ // Place closing order
+ let order_result = zerodha_place_order(
+ api_key.clone(),
+ access_token.clone(),
+ params,
+ "regular".to_string(),
+ ).await;
+
+ match order_result {
+ Ok(response) => results.push(response),
+ Err(e) => results.push(OrderPlaceResponse {
+ success: false,
+ order_id: None,
+ error: Some(e),
+ }),
+ }
+ }
+ }
+ }
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(results),
+ error: None,
+ timestamp,
+ })
+}
+
+/// Cancel all open orders
+#[tauri::command]
+pub async fn zerodha_cancel_all_orders(
+ api_key: String,
+ access_token: String,
+) -> Result<ApiResponse<Vec<OrderPlaceResponse>>, String> {
+ eprintln!("[zerodha_cancel_all_orders] Cancelling all open orders");
+
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ // Get all orders
+ let orders_response = zerodha_get_orders(api_key.clone(), access_token.clone()).await?;
+
+ if !orders_response.success {
+ return Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: orders_response.error,
+ timestamp,
+ });
+ }
+
+ let mut results: Vec<OrderPlaceResponse> = Vec::new();
+
+ if let Some(orders) = orders_response.data {
+ for order in orders {
+ let status = order.get("status").and_then(|s| s.as_str()).unwrap_or("");
+
+ // Only cancel OPEN or TRIGGER PENDING orders
+ if status == "OPEN" || status == "TRIGGER PENDING" {
+ let order_id = order.get("order_id").and_then(|s| s.as_str()).unwrap_or("").to_string();
+
+ if order_id.is_empty() {
+ continue;
+ }
+
+ let cancel_result = zerodha_cancel_order(
+ api_key.clone(),
+ access_token.clone(),
+ order_id,
+ ).await;
+
+ match cancel_result {
+ Ok(response) => results.push(response),
+ Err(e) => results.push(OrderPlaceResponse {
+ success: false,
+ order_id: None,
+ error: Some(e),
+ }),
+ }
+ }
+ }
+ }
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(results),
+ error: None,
+ timestamp,
+ })
+}
+
+// ============================================================================
+// Zerodha Margin Calculator
+// ============================================================================
+
+/// Calculate margin for orders
+#[tauri::command]
+pub async fn zerodha_calculate_margin(
+ api_key: String,
+ access_token: String,
+ orders: Vec<Value>,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[zerodha_calculate_margin] Calculating margin for {} orders", orders.len());
+
+ let client = reqwest::Client::new();
+ let headers = create_zerodha_headers(&api_key, &access_token);
+ let timestamp = chrono::Utc::now().timestamp_millis();
+
+ // Use basket margin endpoint for multiple orders
+ let url = if orders.len() > 1 {
+ format!("{}/margins/basket", ZERODHA_API_BASE)
+ } else {
+ format!("{}/margins/orders", ZERODHA_API_BASE)
+ };
+
+ let response = client
+ .post(&url)
+ .headers(headers)
+ .json(&orders)
+ .send()
+ .await
+ .map_err(|e| format!("Request failed: {}", e))?;
+
+ let status = response.status();
+ let body: Value = response.json().await.map_err(|e| format!("Failed to parse response: {}", e))?;
+
+ if status.is_success() && body.get("status").and_then(|s| s.as_str()) == Some("success") {
+ let data = body.get("data").cloned().unwrap_or(json!({}));
+ Ok(ApiResponse {
+ success: true,
+ data: Some(data),
+ error: None,
+ timestamp,
+ })
+ } else {
+ let error_msg = body.get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("Failed to calculate margin")
+ .to_string();
+ Ok(ApiResponse {
+ success: false,
+ data: None,
+ error: Some(error_msg),
+ timestamp,
+ })
+ }
+}
+
+// ============================================================================
+// Symbol Search & Instrument Lookup
+// ============================================================================
+
+/// Search symbols in master contract database
+#[tauri::command]
+pub async fn zerodha_search_symbols(
+ query: String,
+ exchange: Option<String>,
+) -> Result<ApiResponse<Vec<Value>>, String> {
+ eprintln!("[zerodha_search_symbols] Searching for: {}", query);
+
+ // TODO: Implement proper database search when master contract DB is set up
+ // For now, return empty results
+ let timestamp = chrono::Utc::now().timestamp();
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(vec![]),
+ error: Some("Master contract database not yet implemented. Use zerodha_download_master_contract first.".to_string()),
+ timestamp,
+ })
+}
+
+/// Get instrument details from master contract
+#[tauri::command]
+pub async fn zerodha_get_instrument(
+ symbol: String,
+ exchange: String,
+) -> Result<ApiResponse<Value>, String> {
+ eprintln!("[zerodha_get_instrument] Looking up: {} on {}", symbol, exchange);
+
+ // TODO: Implement proper database lookup when master contract DB is set up
+ // For now, return basic instrument info
+ let timestamp = chrono::Utc::now().timestamp();
+
+ let instrument = json!({
+ "symbol": symbol,
+ "exchange": exchange,
+ "name": symbol.clone(),
+ "token": "0",
+ "instrument_token": "0",
+ "lot_size": 1,
+ "tick_size": 0.05,
+ "instrument_type": "EQ"
+ });
+
+ Ok(ApiResponse {
+ success: true,
+ data: Some(instrument),
+ error: Some("Master contract database not yet implemented. Returning fallback data.".to_string()),
+ timestamp,
+ })
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/database.rs b/fincept-terminal-desktop/src-tauri/src/commands/database.rs
index a73e3a0a0..5cdca4ae2 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/database.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/database.rs
@@ -88,6 +88,36 @@ pub async fn db_save_llm_global_settings(settings: LLMGlobalSettings) -> Result<
Ok("LLM global settings saved successfully".to_string())
}
+#[tauri::command]
+pub async fn db_set_active_llm_provider(provider: String) -> Result<String, String> {
+ operations::set_active_llm_provider(&provider).map_err(|e| e.to_string())?;
+ Ok("Active LLM provider updated".to_string())
+}
+
+// ============================================================================
+// LLM Model Config Commands
+// ============================================================================
+
+#[tauri::command]
+pub async fn db_get_llm_model_configs() -> Result<Vec<LLMModelConfig>, String> {
+ operations::get_llm_model_configs().map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+pub async fn db_save_llm_model_config(config: LLMModelConfig) -> Result<OperationResult, String> {
+ operations::save_llm_model_config(&config).map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+pub async fn db_delete_llm_model_config(id: String) -> Result<OperationResult, String> {
+ operations::delete_llm_model_config(&id).map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+pub async fn db_toggle_llm_model_config_enabled(id: String) -> Result<OperationResult, String> {
+ operations::toggle_llm_model_config_enabled(&id).map_err(|e| e.to_string())
+}
+
// ============================================================================
// Chat Commands
// ============================================================================
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/master_contract.rs b/fincept-terminal-desktop/src-tauri/src/commands/master_contract.rs
index c05fad25e..6c8b895d4 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/master_contract.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/master_contract.rs
@@ -1,9 +1,13 @@
-// Master Contract Cache Commands
-// Tauri commands for broker symbol data caching
+// Master Contract Commands
+// Tauri commands for broker symbol data management and search
-use crate::database::master_contract;
+use crate::database::master_contract::{self, SearchResult, Symbol};
use serde::{Deserialize, Serialize};
+// ============================================================================
+// Data Structures
+// ============================================================================
+
#[derive(Debug, Serialize, Deserialize)]
pub struct MasterContractInfo {
pub broker_id: String,
@@ -13,7 +17,380 @@ pub struct MasterContractInfo {
pub cache_age_seconds: i64,
}
-/// Save master contract cache
+#[derive(Debug, Serialize, Deserialize)]
+pub struct DownloadResult {
+ pub success: bool,
+ pub broker_id: String,
+ pub symbol_count: i64,
+ pub message: String,
+}
+
+/// Angel One symbol from their JSON API
+#[derive(Debug, Deserialize)]
+struct AngelOneSymbol {
+ token: String,
+ symbol: String,
+ name: String,
+ expiry: Option<String>,
+ strike: Option<String>,
+ lotsize: Option<String>,
+ instrumenttype: Option<String>,
+ exch_seg: String,
+ tick_size: Option<String>,
+}
+
+/// Fyers symbol from their CSV
+#[derive(Debug, Deserialize)]
+struct FyersSymbol {
+ #[serde(rename = "Fytoken")]
+ fytoken: String,
+ #[serde(rename = "Symbol Details")]
+ symbol_details: Option<String>,
+ #[serde(rename = "Exchange Instrument type")]
+ exchange_instrument_type: Option<i32>,
+ #[serde(rename = "Minimum lot size")]
+ minimum_lot_size: Option<i32>,
+ #[serde(rename = "Tick size")]
+ tick_size: Option<f64>,
+ #[serde(rename = "ISIN")]
+ isin: Option<String>,
+ #[serde(rename = "Trading Session")]
+ trading_session: Option<String>,
+ #[serde(rename = "Last update date")]
+ last_update_date: Option<String>,
+ #[serde(rename = "Expiry date")]
+ expiry_date: Option<String>,
+ #[serde(rename = "Symbol ticker")]
+ symbol_ticker: String,
+ #[serde(rename = "Exchange")]
+ exchange: Option<i32>,
+ #[serde(rename = "Segment")]
+ segment: Option<i32>,
+ #[serde(rename = "Scrip code")]
+ scrip_code: Option<i32>,
+ #[serde(rename = "Underlying symbol")]
+ underlying_symbol: Option<String>,
+ #[serde(rename = "Underlying scrip code")]
+ underlying_scrip_code: Option<i64>,
+ #[serde(rename = "Strike price")]
+ strike_price: Option<f64>,
+ #[serde(rename = "Option type")]
+ option_type: Option<String>,
+}
+
+// ============================================================================
+// Download Commands
+// ============================================================================
+
+/// Download master contract for Angel One
+#[tauri::command]
+pub async fn download_angelone_master_contract() -> Result<DownloadResult, String> {
+ eprintln!("[MasterContract] Downloading Angel One master contract...");
+
+ let url = "https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json";
+
+ let response = reqwest::get(url)
+ .await
+ .map_err(|e| format!("Failed to download: {}", e))?;
+
+ if !response.status().is_success() {
+ return Err(format!("HTTP error: {}", response.status()));
+ }
+
+ let json_data: Vec<AngelOneSymbol> = response
+ .json()
+ .await
+ .map_err(|e| format!("Failed to parse JSON: {}", e))?;
+
+ eprintln!("[MasterContract] Downloaded {} symbols from Angel One", json_data.len());
+
+ // Transform to our schema
+ let symbols: Vec<Symbol> = json_data
+ .into_iter()
+ .map(|s| {
+ // Normalize exchange
+ let exchange = normalize_angelone_exchange(&s.exch_seg, s.instrumenttype.as_deref());
+
+ // Normalize symbol (remove suffixes like -EQ, -BE, etc.)
+ let symbol = s.symbol
+ .replace("-EQ", "")
+ .replace("-BE", "")
+ .replace("-MF", "")
+ .replace("-SG", "");
+
+ // Parse strike price
+ let strike = s.strike
+ .as_ref()
+ .and_then(|st| st.parse::<f64>().ok())
+ .map(|st| st / 100.0);
+
+ // Parse lot size
+ let lot_size = s.lotsize
+ .as_ref()
+ .and_then(|ls| ls.parse::<i32>().ok());
+
+ // Parse tick size
+ let tick_size = s.tick_size
+ .as_ref()
+ .and_then(|ts| ts.parse::<f64>().ok())
+ .map(|ts| ts / 100.0);
+
+ // Normalize instrument type
+ let instrument_type = normalize_instrument_type(s.instrumenttype.as_deref());
+
+ // Format expiry
+ let expiry = s.expiry.as_ref().map(|e| format_angelone_expiry(e));
+
+ Symbol {
+ id: None,
+ broker_id: "angelone".to_string(),
+ symbol,
+ br_symbol: s.symbol.clone(),
+ name: Some(s.name),
+ exchange,
+ br_exchange: Some(s.exch_seg.clone()),
+ token: s.token,
+ expiry,
+ strike,
+ lot_size,
+ instrument_type,
+ tick_size,
+ segment: Some(s.exch_seg),
+ }
+ })
+ .collect();
+
+ let symbol_count = symbols.len() as i64;
+
+ // Delete old symbols and insert new ones
+ master_contract::delete_symbols_for_broker("angelone")
+ .map_err(|e| format!("Failed to delete old symbols: {}", e))?;
+
+ master_contract::bulk_insert_symbols(&symbols)
+ .map_err(|e| format!("Failed to insert symbols: {}", e))?;
+
+ // Update cache metadata
+ master_contract::save_master_contract("angelone", "{}", symbol_count)
+ .map_err(|e| format!("Failed to save cache metadata: {}", e))?;
+
+ eprintln!("[MasterContract] ✓ Angel One master contract saved ({} symbols)", symbol_count);
+
+ Ok(DownloadResult {
+ success: true,
+ broker_id: "angelone".to_string(),
+ symbol_count,
+ message: format!("Successfully downloaded {} symbols", symbol_count),
+ })
+}
+
+/// Download master contract for Fyers
+#[tauri::command]
+pub async fn download_fyers_master_contract() -> Result<DownloadResult, String> {
+ eprintln!("[MasterContract] Downloading Fyers master contract...");
+
+ let segments = vec![
+ ("NSE_CM", "https://public.fyers.in/sym_details/NSE_CM.csv"),
+ ("NSE_FO", "https://public.fyers.in/sym_details/NSE_FO.csv"),
+ ("NSE_CD", "https://public.fyers.in/sym_details/NSE_CD.csv"),
+ ("BSE_CM", "https://public.fyers.in/sym_details/BSE_CM.csv"),
+ ("BSE_FO", "https://public.fyers.in/sym_details/BSE_FO.csv"),
+ ("MCX_COM", "https://public.fyers.in/sym_details/MCX_COM.csv"),
+ ];
+
+ let mut all_symbols: Vec<Symbol> = Vec::new();
+
+ for (segment_name, url) in segments {
+ eprintln!("[MasterContract] Downloading Fyers {} segment...", segment_name);
+
+ let response = match reqwest::get(url).await {
+ Ok(r) => r,
+ Err(e) => {
+ eprintln!("[MasterContract] Warning: Failed to download {}: {}", segment_name, e);
+ continue;
+ }
+ };
+
+ if !response.status().is_success() {
+ eprintln!("[MasterContract] Warning: HTTP error for {}: {}", segment_name, response.status());
+ continue;
+ }
+
+ let csv_text = response
+ .text()
+ .await
+ .map_err(|e| format!("Failed to read CSV: {}", e))?;
+
+ // Parse CSV with flexible reader
+ let mut reader = csv::ReaderBuilder::new()
+ .has_headers(false)
+ .flexible(true)
+ .from_reader(csv_text.as_bytes());
+
+ for result in reader.records() {
+ let record: csv::StringRecord = match result {
+ Ok(r) => r,
+ Err(_) => continue,
+ };
+
+ // Fyers CSV format: Fytoken, Symbol Details, Exchange Instrument type, Lot size, Tick size, ISIN, Trading Session, Last update, Expiry, Symbol ticker, Exchange, Segment, Scrip code, Underlying, Underlying code, Strike, Option type, Underlying FyToken, Reserved...
+ if record.len() < 10 {
+ continue;
+ }
+
+ let fytoken = record.get(0).unwrap_or("").to_string();
+ let symbol_ticker = record.get(9).unwrap_or("").to_string();
+
+ if fytoken.is_empty() || symbol_ticker.is_empty() {
+ continue;
+ }
+
+ let exchange = map_fyers_exchange(record.get(10).and_then(|s| s.parse::<i32>().ok()));
+ let lot_size = record.get(3).and_then(|s| s.parse::<i32>().ok());
+ let tick_size = record.get(4).and_then(|s| s.parse::<f64>().ok());
+ let expiry = record.get(8).map(|s| s.to_string()).filter(|s| !s.is_empty());
+ let underlying = record.get(13).map(|s| s.to_string()).filter(|s| !s.is_empty());
+ let strike = record.get(15).and_then(|s| s.parse::<f64>().ok());
+ let option_type = record.get(16).map(|s| s.to_string()).filter(|s| !s.is_empty());
+
+ // Determine instrument type
+ let instrument_type = determine_fyers_instrument_type(&symbol_ticker, option_type.as_deref());
+
+ // Extract base symbol
+ let symbol = extract_fyers_symbol(&symbol_ticker);
+
+ all_symbols.push(Symbol {
+ id: None,
+ broker_id: "fyers".to_string(),
+ symbol,
+ br_symbol: symbol_ticker.clone(),
+ name: underlying,
+ exchange,
+ br_exchange: Some(segment_name.to_string()),
+ token: fytoken,
+ expiry,
+ strike,
+ lot_size,
+ instrument_type,
+ tick_size,
+ segment: Some(segment_name.to_string()),
+ });
+ }
+ }
+
+ let symbol_count = all_symbols.len() as i64;
+
+ if symbol_count == 0 {
+ return Err("No symbols downloaded from Fyers".to_string());
+ }
+
+ // Delete old symbols and insert new ones
+ master_contract::delete_symbols_for_broker("fyers")
+ .map_err(|e| format!("Failed to delete old symbols: {}", e))?;
+
+ master_contract::bulk_insert_symbols(&all_symbols)
+ .map_err(|e| format!("Failed to insert symbols: {}", e))?;
+
+ // Update cache metadata
+ master_contract::save_master_contract("fyers", "{}", symbol_count)
+ .map_err(|e| format!("Failed to save cache metadata: {}", e))?;
+
+ eprintln!("[MasterContract] ✓ Fyers master contract saved ({} symbols)", symbol_count);
+
+ Ok(DownloadResult {
+ success: true,
+ broker_id: "fyers".to_string(),
+ symbol_count,
+ message: format!("Successfully downloaded {} symbols", symbol_count),
+ })
+}
+
+/// Download master contract for any broker
+#[tauri::command]
+pub async fn download_master_contract(broker_id: String) -> Result<DownloadResult, String> {
+ match broker_id.as_str() {
+ "angelone" => download_angelone_master_contract().await,
+ "fyers" => download_fyers_master_contract().await,
+ "zerodha" => Err("Zerodha master contract requires authentication. Use zerodha_download_instruments command.".to_string()),
+ _ => Err(format!("Unknown broker: {}", broker_id)),
+ }
+}
+
+// ============================================================================
+// Search Commands
+// ============================================================================
+
+/// Search symbols
+#[tauri::command]
+pub async fn search_symbols(
+ broker_id: String,
+ query: String,
+ exchange: Option<String>,
+ instrument_type: Option<String>,
+ limit: Option<i32>,
+) -> Result<Vec<SearchResult>, String> {
+ let limit = limit.unwrap_or(50);
+
+ master_contract::search_symbols(
+ &broker_id,
+ &query,
+ exchange.as_deref(),
+ instrument_type.as_deref(),
+ limit,
+ )
+ .map_err(|e| format!("Search failed: {}", e))
+}
+
+/// Get symbol by exact match
+#[tauri::command]
+pub async fn get_symbol(
+ broker_id: String,
+ symbol: String,
+ exchange: String,
+) -> Result<Option<SearchResult>, String> {
+ master_contract::get_symbol(&broker_id, &symbol, &exchange)
+ .map_err(|e| format!("Failed to get symbol: {}", e))
+}
+
+/// Get symbol by token
+#[tauri::command]
+pub async fn get_symbol_by_token(
+ broker_id: String,
+ token: String,
+) -> Result<Option<SearchResult>, String> {
+ master_contract::get_symbol_by_token(&broker_id, &token)
+ .map_err(|e| format!("Failed to get symbol: {}", e))
+}
+
+/// Get symbol count for a broker
+#[tauri::command]
+pub async fn get_symbol_count(broker_id: String) -> Result<i64, String> {
+ master_contract::get_symbol_count(&broker_id)
+ .map_err(|e| format!("Failed to get symbol count: {}", e))
+}
+
+/// Get available exchanges for a broker
+#[tauri::command]
+pub async fn get_exchanges(broker_id: String) -> Result<Vec<String>, String> {
+ master_contract::get_exchanges(&broker_id)
+ .map_err(|e| format!("Failed to get exchanges: {}", e))
+}
+
+/// Get available expiries
+#[tauri::command]
+pub async fn get_expiries(
+ broker_id: String,
+ exchange: Option<String>,
+ underlying: Option<String>,
+) -> Result<Vec<String>, String> {
+ master_contract::get_expiries(&broker_id, exchange.as_deref(), underlying.as_deref())
+ .map_err(|e| format!("Failed to get expiries: {}", e))
+}
+
+// ============================================================================
+// Cache Management Commands
+// ============================================================================
+
+/// Save master contract cache (legacy)
#[tauri::command]
pub async fn save_master_contract_cache(
broker_id: String,
@@ -29,7 +406,7 @@ pub async fn save_master_contract_cache(
))
}
-/// Get master contract cache
+/// Get master contract cache (legacy)
#[tauri::command]
pub async fn get_master_contract_cache(broker_id: String) -> Result<String, String> {
let cache = master_contract::get_master_contract(&broker_id)
@@ -44,13 +421,17 @@ pub async fn get_master_contract_cache(broker_id: String) -> Result<String, Stri
/// Delete master contract cache
#[tauri::command]
pub async fn delete_master_contract_cache(broker_id: String) -> Result<String, String> {
+ // Delete both cache and symbols
+ master_contract::delete_symbols_for_broker(&broker_id)
+ .map_err(|e| format!("Failed to delete symbols: {}", e))?;
+
master_contract::delete_master_contract(&broker_id)
.map_err(|e| format!("Failed to delete master contract: {}", e))?;
Ok(format!("Master contract deleted for {}", broker_id))
}
-/// Check if cache is valid (not expired)
+/// Check if cache is valid
#[tauri::command]
pub async fn is_master_contract_cache_valid(
broker_id: String,
@@ -85,3 +466,83 @@ pub async fn get_master_contract_cache_info(
None => Err(format!("No master contract found for {}", broker_id)),
}
}
+
+// ============================================================================
+// Helper Functions
+// ============================================================================
+
+fn normalize_angelone_exchange(exch_seg: &str, instrument_type: Option<&str>) -> String {
+ match (exch_seg, instrument_type) {
+ ("NSE", Some("AMXIDX")) => "NSE_INDEX".to_string(),
+ ("BSE", Some("AMXIDX")) => "BSE_INDEX".to_string(),
+ ("MCX", Some("AMXIDX")) => "MCX_INDEX".to_string(),
+ _ => exch_seg.to_string(),
+ }
+}
+
+fn normalize_instrument_type(inst_type: Option<&str>) -> Option<String> {
+ match inst_type {
+ Some("OPTIDX") | Some("OPTSTK") => {
+ // Will be determined by symbol suffix (CE/PE)
+ None
+ }
+ Some("FUTIDX") | Some("FUTSTK") | Some("FUTCOM") | Some("FUTCUR") | Some("FUTIRC") => {
+ Some("FUT".to_string())
+ }
+ Some("OPTFUT") | Some("OPTCUR") | Some("OPTIRC") => None,
+ Some(t) => Some(t.to_string()),
+ None => None,
+ }
+}
+
+fn format_angelone_expiry(expiry: &str) -> String {
+ // Convert from '19MAR2024' to '19-MAR-24'
+ if expiry.len() >= 9 {
+ let day = &expiry[0..2];
+ let month = &expiry[2..5];
+ let year = &expiry[7..9];
+ format!("{}-{}-{}", day, month.to_uppercase(), year)
+ } else {
+ expiry.to_uppercase()
+ }
+}
+
+fn map_fyers_exchange(exchange_code: Option<i32>) -> String {
+ match exchange_code {
+ Some(10) => "NSE".to_string(),
+ Some(11) => "MCX".to_string(),
+ Some(12) => "BSE".to_string(),
+ _ => "NSE".to_string(),
+ }
+}
+
+fn determine_fyers_instrument_type(symbol: &str, option_type: Option<&str>) -> Option<String> {
+ if let Some(opt) = option_type {
+ if opt == "CE" || opt == "PE" {
+ return Some(opt.to_string());
+ }
+ }
+
+ if symbol.ends_with("FUT") {
+ Some("FUT".to_string())
+ } else if symbol.ends_with("CE") {
+ Some("CE".to_string())
+ } else if symbol.ends_with("PE") {
+ Some("PE".to_string())
+ } else if symbol.contains("-EQ") || !symbol.contains('-') {
+ Some("EQ".to_string())
+ } else {
+ None
+ }
+}
+
+fn extract_fyers_symbol(symbol_ticker: &str) -> String {
+ // Fyers symbols are like "NSE:RELIANCE-EQ" or "NSE:NIFTY24JAN25000CE"
+ if let Some(pos) = symbol_ticker.find(':') {
+ let after_colon = &symbol_ticker[pos + 1..];
+ // Remove -EQ suffix for equity
+ after_colon.replace("-EQ", "").replace("-BE", "")
+ } else {
+ symbol_ticker.replace("-EQ", "").replace("-BE", "")
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
index 7fd9959f3..54d083be3 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
@@ -134,6 +134,9 @@ pub mod screener_commands;
// Geocoding - Location search and reverse geocoding
pub mod geocoding;
+// Indian Stock Brokers - Modular broker integrations
+pub mod brokers;
+
// Paper Trading moved to src-tauri/src/paper_trading.rs (universal module)
// Broker Credentials - Secure encrypted storage for broker API credentials
@@ -144,3 +147,6 @@ pub mod master_contract;
// Generic Storage - localStorage replacement with SQLite
pub mod storage;
+
+// Unified Trading - Live/Paper mode switching for all brokers
+pub mod unified_trading;
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs b/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs
new file mode 100644
index 000000000..5219e5083
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/unified_trading.rs
@@ -0,0 +1,549 @@
+// Unified Trading Module
+// Handles both LIVE and PAPER trading modes for all brokers
+// Routes orders to either real broker API or paper trading engine
+
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use tokio::sync::RwLock;
+use once_cell::sync::Lazy;
+
+use crate::paper_trading;
+
+// ============================================================================
+// Types
+// ============================================================================
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum TradingMode {
+ Live,
+ Paper,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TradingSession {
+ pub broker: String,
+ pub mode: TradingMode,
+ pub paper_portfolio_id: Option<String>,
+ pub is_connected: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UnifiedOrder {
+ pub symbol: String,
+ pub exchange: String,
+ pub side: String, // "buy" | "sell"
+ pub order_type: String, // "market" | "limit" | "stop" | "stop_limit"
+ pub quantity: f64,
+ pub price: Option<f64>,
+ pub stop_price: Option<f64>,
+ pub product_type: Option<String>, // "CNC" | "MIS" | "NRML"
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UnifiedOrderResponse {
+ pub success: bool,
+ pub order_id: Option<String>,
+ pub message: Option<String>,
+ pub mode: TradingMode,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UnifiedPosition {
+ pub symbol: String,
+ pub exchange: String,
+ pub side: String,
+ pub quantity: f64,
+ pub entry_price: f64,
+ pub current_price: f64,
+ pub unrealized_pnl: f64,
+ pub realized_pnl: f64,
+ pub mode: TradingMode,
+}
+
+// ============================================================================
+// Global State
+// ============================================================================
+
+static TRADING_SESSION: Lazy<Arc<RwLock<Option<TradingSession>>>> =
+ Lazy::new(|| Arc::new(RwLock::new(None)));
+
+// ============================================================================
+// Session Management
+// ============================================================================
+
+/// Initialize trading session
+#[tauri::command]
+pub async fn init_trading_session(
+ broker: String,
+ mode: String,
+ paper_portfolio_id: Option<String>,
+) -> Result<TradingSession, String> {
+ let trading_mode = match mode.to_lowercase().as_str() {
+ "live" => TradingMode::Live,
+ "paper" | "sandbox" => TradingMode::Paper,
+ _ => return Err("Invalid mode. Use 'live' or 'paper'".to_string()),
+ };
+
+ // For paper mode, ensure portfolio exists or create one
+ let portfolio_id = if trading_mode == TradingMode::Paper {
+ match paper_portfolio_id {
+ Some(id) => {
+ // Verify portfolio exists
+ paper_trading::get_portfolio(&id).map_err(|e| e.to_string())?;
+ Some(id)
+ }
+ None => {
+ // Create default paper portfolio for this broker
+ let portfolio = paper_trading::create_portfolio(
+ &format!("{} Paper Trading", broker),
+ 1000000.0, // 10 lakh INR default
+ "INR",
+ 1.0,
+ "cross",
+ 0.0003, // 0.03% fee (typical for Zerodha)
+ ).map_err(|e| e.to_string())?;
+ Some(portfolio.id)
+ }
+ }
+ } else {
+ None
+ };
+
+ let session = TradingSession {
+ broker: broker.clone(),
+ mode: trading_mode,
+ paper_portfolio_id: portfolio_id,
+ is_connected: false,
+ };
+
+ let mut session_guard = TRADING_SESSION.write().await;
+ *session_guard = Some(session.clone());
+
+ eprintln!("[UnifiedTrading] Session initialized: {:?} mode for {}", trading_mode, broker);
+
+ Ok(session)
+}
+
+/// Get current trading session
+#[tauri::command]
+pub async fn get_trading_session() -> Result<Option<TradingSession>, String> {
+ let session_guard = TRADING_SESSION.read().await;
+ Ok(session_guard.clone())
+}
+
+/// Switch trading mode
+#[tauri::command]
+pub async fn switch_trading_mode(mode: String) -> Result<TradingSession, String> {
+ let trading_mode = match mode.to_lowercase().as_str() {
+ "live" => TradingMode::Live,
+ "paper" | "sandbox" => TradingMode::Paper,
+ _ => return Err("Invalid mode".to_string()),
+ };
+
+ let mut session_guard = TRADING_SESSION.write().await;
+
+ if let Some(ref mut session) = *session_guard {
+ session.mode = trading_mode;
+
+ // Create paper portfolio if switching to paper and none exists
+ if trading_mode == TradingMode::Paper && session.paper_portfolio_id.is_none() {
+ let portfolio = paper_trading::create_portfolio(
+ &format!("{} Paper Trading", session.broker),
+ 1000000.0,
+ "INR",
+ 1.0,
+ "cross",
+ 0.0003,
+ ).map_err(|e| e.to_string())?;
+ session.paper_portfolio_id = Some(portfolio.id);
+ }
+
+ eprintln!("[UnifiedTrading] Switched to {:?} mode", trading_mode);
+ Ok(session.clone())
+ } else {
+ Err("No active trading session".to_string())
+ }
+}
+
+// ============================================================================
+// Order Placement
+// ============================================================================
+
+/// Place order - routes to live broker or paper trading based on mode
+#[tauri::command]
+pub async fn unified_place_order(
+ order: UnifiedOrder,
+) -> Result<UnifiedOrderResponse, String> {
+ let session_guard = TRADING_SESSION.read().await;
+
+ let session = session_guard.as_ref()
+ .ok_or("No active trading session. Call init_trading_session first.")?;
+
+ match session.mode {
+ TradingMode::Paper => {
+ place_paper_order(&session, &order).await
+ }
+ TradingMode::Live => {
+ place_live_order(&session, &order).await
+ }
+ }
+}
+
+/// Place order in paper trading
+async fn place_paper_order(
+ session: &TradingSession,
+ order: &UnifiedOrder,
+) -> Result<UnifiedOrderResponse, String> {
+ let portfolio_id = session.paper_portfolio_id.as_ref()
+ .ok_or("No paper portfolio configured")?;
+
+ let symbol = format!("{}:{}", order.exchange, order.symbol);
+
+ let paper_order = paper_trading::place_order(
+ portfolio_id,
+ &symbol,
+ &order.side,
+ &order.order_type,
+ order.quantity,
+ order.price,
+ order.stop_price,
+ false, // reduce_only
+ ).map_err(|e| e.to_string())?;
+
+ // For market orders, auto-fill immediately if we have a price
+ if order.order_type == "market" {
+ if let Some(price) = order.price {
+ let _ = paper_trading::fill_order(&paper_order.id, price, None);
+ }
+ // Otherwise, the order will be filled when we receive a tick
+ }
+
+ Ok(UnifiedOrderResponse {
+ success: true,
+ order_id: Some(paper_order.id),
+ message: Some("Paper order placed".to_string()),
+ mode: TradingMode::Paper,
+ })
+}
+
+/// Place order with live broker
+async fn place_live_order(
+ session: &TradingSession,
+ order: &UnifiedOrder,
+) -> Result<UnifiedOrderResponse, String> {
+ // Route to appropriate broker
+ match session.broker.to_lowercase().as_str() {
+ "zerodha" => {
+ place_zerodha_order(order).await
+ }
+ _ => Err(format!("Live trading not implemented for {}", session.broker))
+ }
+}
+
+/// Place order via Zerodha API
+async fn place_zerodha_order(order: &UnifiedOrder) -> Result<UnifiedOrderResponse, String> {
+ use crate::commands::brokers;
+ use std::collections::HashMap;
+ use serde_json::Value;
+
+ // Get stored credentials
+ let creds = brokers::get_indian_broker_credentials("zerodha".to_string())
+ .await
+ .map_err(|e| e.to_string())?;
+
+ if !creds.success || creds.data.is_none() {
+ return Err("Zerodha credentials not found. Please authenticate first.".to_string());
+ }
+
+ let cred_data = creds.data.unwrap();
+ let api_key = cred_data.get("apiKey")
+ .and_then(|v| v.as_str())
+ .ok_or("API key not found")?
+ .to_string();
+ let access_token = cred_data.get("accessToken")
+ .and_then(|v| v.as_str())
+ .ok_or("Access token not found. Please re-authenticate.")?
+ .to_string();
+
+ // Map order type
+ let zerodha_order_type = match order.order_type.as_str() {
+ "market" => "MARKET",
+ "limit" => "LIMIT",
+ "stop" => "SL-M",
+ "stop_limit" => "SL",
+ _ => "MARKET",
+ };
+
+ // Map transaction type
+ let transaction_type = order.side.to_uppercase();
+
+ // Map product type
+ let product = order.product_type.as_deref().unwrap_or("CNC");
+
+ // Build params HashMap
+ let mut params: HashMap<String, Value> = HashMap::new();
+ params.insert("tradingsymbol".to_string(), Value::String(order.symbol.clone()));
+ params.insert("exchange".to_string(), Value::String(order.exchange.clone()));
+ params.insert("transaction_type".to_string(), Value::String(transaction_type));
+ params.insert("order_type".to_string(), Value::String(zerodha_order_type.to_string()));
+ params.insert("product".to_string(), Value::String(product.to_string()));
+ params.insert("quantity".to_string(), Value::Number(serde_json::Number::from(order.quantity as i64)));
+
+ if let Some(price) = order.price {
+ params.insert("price".to_string(), Value::Number(serde_json::Number::from_f64(price).unwrap_or(serde_json::Number::from(0))));
+ }
+ if let Some(trigger_price) = order.stop_price {
+ params.insert("trigger_price".to_string(), Value::Number(serde_json::Number::from_f64(trigger_price).unwrap_or(serde_json::Number::from(0))));
+ }
+
+ // Determine variety
+ let variety = "regular".to_string();
+
+ // Place order via Zerodha API
+ let response = brokers::zerodha_place_order(
+ api_key,
+ access_token,
+ params,
+ variety,
+ ).await.map_err(|e| e.to_string())?;
+
+ Ok(UnifiedOrderResponse {
+ success: response.success,
+ order_id: response.order_id,
+ message: response.error,
+ mode: TradingMode::Live,
+ })
+}
+
+// ============================================================================
+// Price Updates & Order Fills
+// ============================================================================
+
+/// Process tick for paper trading
+/// Called when we receive price updates from WebSocket
+#[tauri::command]
+pub async fn process_tick_for_paper_trading(
+ symbol: String,
+ price: f64,
+) -> Result<(), String> {
+ let session_guard = TRADING_SESSION.read().await;
+
+ let session = match session_guard.as_ref() {
+ Some(s) if s.mode == TradingMode::Paper => s,
+ _ => return Ok(()), // Not in paper mode, ignore
+ };
+
+ let portfolio_id = match &session.paper_portfolio_id {
+ Some(id) => id,
+ None => return Ok(()),
+ };
+
+ // 1. Update position prices
+ let _ = paper_trading::update_position_price(portfolio_id, &symbol, price);
+
+ // 2. Check and fill pending orders
+ let orders = paper_trading::get_orders(portfolio_id, Some("pending"))
+ .map_err(|e| e.to_string())?;
+
+ for order in orders {
+ if order.symbol != symbol {
+ continue;
+ }
+
+ let should_fill = match order.order_type.as_str() {
+ "market" => true,
+ "limit" => {
+ match order.side.as_str() {
+ "buy" => order.price.map(|p| price <= p).unwrap_or(false),
+ "sell" => order.price.map(|p| price >= p).unwrap_or(false),
+ _ => false,
+ }
+ }
+ "stop" => {
+ match order.side.as_str() {
+ "buy" => order.stop_price.map(|p| price >= p).unwrap_or(false),
+ "sell" => order.stop_price.map(|p| price <= p).unwrap_or(false),
+ _ => false,
+ }
+ }
+ "stop_limit" => {
+ // Stop triggered, now check limit
+ let stop_triggered = match order.side.as_str() {
+ "buy" => order.stop_price.map(|p| price >= p).unwrap_or(false),
+ "sell" => order.stop_price.map(|p| price <= p).unwrap_or(false),
+ _ => false,
+ };
+ if stop_triggered {
+ match order.side.as_str() {
+ "buy" => order.price.map(|p| price <= p).unwrap_or(false),
+ "sell" => order.price.map(|p| price >= p).unwrap_or(false),
+ _ => false,
+ }
+ } else {
+ false
+ }
+ }
+ _ => false,
+ };
+
+ if should_fill {
+ match paper_trading::fill_order(&order.id, price, None) {
+ Ok(trade) => {
+ eprintln!("[PaperTrading] Filled order {} at {}: {:?}", order.id, price, trade);
+ }
+ Err(e) => {
+ eprintln!("[PaperTrading] Failed to fill order {}: {}", order.id, e);
+ }
+ }
+ }
+ }
+
+ Ok(())
+}
+
+// ============================================================================
+// Position & Order Queries
+// ============================================================================
+
+/// Get positions - returns paper or live based on mode
+#[tauri::command]
+pub async fn unified_get_positions() -> Result<Vec<UnifiedPosition>, String> {
+ let session_guard = TRADING_SESSION.read().await;
+
+ let session = session_guard.as_ref()
+ .ok_or("No active trading session")?;
+
+ match session.mode {
+ TradingMode::Paper => {
+ let portfolio_id = session.paper_portfolio_id.as_ref()
+ .ok_or("No paper portfolio")?;
+
+ let positions = paper_trading::get_positions(portfolio_id)
+ .map_err(|e| e.to_string())?;
+
+ Ok(positions.into_iter().map(|p| {
+ let parts: Vec<&str> = p.symbol.splitn(2, ':').collect();
+ UnifiedPosition {
+ symbol: parts.get(1).unwrap_or(&p.symbol.as_str()).to_string(),
+ exchange: parts.get(0).unwrap_or(&"NSE").to_string(),
+ side: p.side,
+ quantity: p.quantity,
+ entry_price: p.entry_price,
+ current_price: p.current_price,
+ unrealized_pnl: p.unrealized_pnl,
+ realized_pnl: p.realized_pnl,
+ mode: TradingMode::Paper,
+ }
+ }).collect())
+ }
+ TradingMode::Live => {
+ // Get from broker
+ get_live_positions(&session).await
+ }
+ }
+}
+
+async fn get_live_positions(session: &TradingSession) -> Result<Vec<UnifiedPosition>, String> {
+ match session.broker.to_lowercase().as_str() {
+ "zerodha" => {
+ use crate::commands::brokers;
+
+ let creds = brokers::get_indian_broker_credentials("zerodha".to_string())
+ .await
+ .map_err(|e| e.to_string())?;
+
+ if !creds.success || creds.data.is_none() {
+ return Err("Credentials not found".to_string());
+ }
+
+ let cred_data = creds.data.unwrap();
+ let api_key = cred_data.get("apiKey")
+ .and_then(|v| v.as_str())
+ .ok_or("API key not found")?
+ .to_string();
+ let access_token = cred_data.get("accessToken")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let response = brokers::zerodha_get_positions(
+ api_key,
+ access_token,
+ ).await.map_err(|e| e.to_string())?;
+
+ if !response.success {
+ return Err(response.error.unwrap_or("Failed to get positions".to_string()));
+ }
+
+ // Map Zerodha positions to unified format
+ let positions: Vec<UnifiedPosition> = response.data.map(|data| {
+ if let Some(net_positions) = data.get("net").and_then(|v| v.as_array()) {
+ net_positions.iter().filter_map(|p| {
+ let qty = p.get("quantity").and_then(|v| v.as_f64()).unwrap_or(0.0);
+ let side = if qty >= 0.0 { "long" } else { "short" };
+ Some(UnifiedPosition {
+ symbol: p.get("tradingsymbol").and_then(|v| v.as_str()).unwrap_or("").to_string(),
+ exchange: p.get("exchange").and_then(|v| v.as_str()).unwrap_or("NSE").to_string(),
+ side: side.to_string(),
+ quantity: qty.abs(),
+ entry_price: p.get("average_price").and_then(|v| v.as_f64()).unwrap_or(0.0),
+ current_price: p.get("last_price").and_then(|v| v.as_f64()).unwrap_or(0.0),
+ unrealized_pnl: p.get("unrealised").and_then(|v| v.as_f64()).unwrap_or(0.0),
+ realized_pnl: p.get("realised").and_then(|v| v.as_f64()).unwrap_or(0.0),
+ mode: TradingMode::Live,
+ })
+ }).collect()
+ } else {
+ Vec::new()
+ }
+ }).unwrap_or_default();
+
+ Ok(positions)
+ }
+ _ => Err(format!("Not implemented for {}", session.broker))
+ }
+}
+
+/// Get orders - returns paper or live based on mode
+#[tauri::command]
+pub async fn unified_get_orders(status: Option<String>) -> Result<Vec<paper_trading::Order>, String> {
+ let session_guard = TRADING_SESSION.read().await;
+
+ let session = session_guard.as_ref()
+ .ok_or("No active trading session")?;
+
+ match session.mode {
+ TradingMode::Paper => {
+ let portfolio_id = session.paper_portfolio_id.as_ref()
+ .ok_or("No paper portfolio")?;
+
+ paper_trading::get_orders(portfolio_id, status.as_deref())
+ .map_err(|e| e.to_string())
+ }
+ TradingMode::Live => {
+ // TODO: Get from broker
+ Err("Live orders not yet implemented".to_string())
+ }
+ }
+}
+
+/// Cancel order
+#[tauri::command]
+pub async fn unified_cancel_order(order_id: String) -> Result<(), String> {
+ let session_guard = TRADING_SESSION.read().await;
+
+ let session = session_guard.as_ref()
+ .ok_or("No active trading session")?;
+
+ match session.mode {
+ TradingMode::Paper => {
+ paper_trading::cancel_order(&order_id)
+ .map_err(|e| e.to_string())
+ }
+ TradingMode::Live => {
+ // TODO: Cancel via broker
+ Err("Live cancel not yet implemented".to_string())
+ }
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/database/broker_credentials.rs b/fincept-terminal-desktop/src-tauri/src/database/broker_credentials.rs
index 9a7bd1cde..4e4a4bd14 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/broker_credentials.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/broker_credentials.rs
@@ -170,6 +170,16 @@ fn current_timestamp() -> i64 {
/// Save broker credentials (insert or update)
pub fn save_credentials(conn: &Connection, creds: &BrokerCredentials) -> Result<()> {
eprintln!("[BrokerCredentials] save_credentials called for broker: {}", creds.broker_id);
+
+ // Debug: Print what we received
+ eprintln!("[BrokerCredentials] Input data:");
+ eprintln!(" - api_key: {:?} (len: {})",
+ creds.api_key.as_ref().map(|s| if s.len() > 0 { "***PRESENT***" } else { "EMPTY" }),
+ creds.api_key.as_ref().map(|s| s.len()).unwrap_or(0));
+ eprintln!(" - api_secret: {:?} (len: {})",
+ creds.api_secret.as_ref().map(|s| if s.len() > 0 { "***PRESENT***" } else { "EMPTY" }),
+ creds.api_secret.as_ref().map(|s| s.len()).unwrap_or(0));
+
// Ensure encryption key is initialized
init_encryption_key()?;
@@ -246,6 +256,12 @@ pub fn get_credentials(conn: &Connection, broker_id: &str) -> Result<Option<Brok
match result {
Ok(mut creds) => {
+ // Debug: Print what was retrieved from database BEFORE decryption
+ eprintln!("[BrokerCredentials] Raw data from DB:");
+ eprintln!(" - api_key encrypted: {:?}", creds.api_key.as_ref().map(|s| format!("{}...", &s[..20.min(s.len())])));
+ eprintln!(" - api_secret encrypted: {:?}", creds.api_secret.as_ref().map(|s| format!("{}...", &s[..20.min(s.len())])));
+ eprintln!(" - encrypted flag: {}", creds.encrypted);
+
// Decrypt sensitive fields if encrypted
if creds.encrypted {
eprintln!("[BrokerCredentials] Decrypting api_key for: {}", broker_id);
diff --git a/fincept-terminal-desktop/src-tauri/src/database/fyers_symbols.rs b/fincept-terminal-desktop/src-tauri/src/database/fyers_symbols.rs
new file mode 100644
index 000000000..16830c066
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/database/fyers_symbols.rs
@@ -0,0 +1,397 @@
+// Fyers Symbol Master Database
+// Stores individual Fyers symbols with token mapping for fast lookup
+
+use crate::database::pool::get_db;
+use anyhow::{Context, Result};
+use rusqlite::{params, OptionalExtension};
+use serde::{Deserialize, Serialize};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+// ============================================================================
+// DATA STRUCTURES
+// ============================================================================
+
+/// Fyers symbol data structure
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct FyersSymbol {
+ pub token: i32,
+ pub symbol: String,
+ pub name: String,
+ pub exchange: String,
+ pub segment: String,
+ pub instrument_type: String,
+ pub isin: Option<String>,
+ pub tick_size: f64,
+ pub lot_size: i32,
+}
+
+/// Symbol search result
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SymbolSearchResult {
+ pub token: i32,
+ pub symbol: String,
+ pub name: String,
+ pub exchange: String,
+ pub relevance_score: f64,
+}
+
+// ============================================================================
+// DATABASE SCHEMA
+// ============================================================================
+
+/// Initialize Fyers symbols table
+pub fn init_fyers_symbols_table() -> Result<()> {
+ let db = get_db()?;
+
+ db.execute(
+ "CREATE TABLE IF NOT EXISTS fyers_symbols (
+ token INTEGER PRIMARY KEY,
+ symbol TEXT NOT NULL,
+ name TEXT NOT NULL,
+ exchange TEXT NOT NULL,
+ segment TEXT NOT NULL,
+ instrument_type TEXT NOT NULL,
+ isin TEXT,
+ tick_size REAL NOT NULL DEFAULT 0.05,
+ lot_size INTEGER NOT NULL DEFAULT 1,
+ last_updated INTEGER NOT NULL,
+ created_at INTEGER NOT NULL
+ )",
+ [],
+ )
+ .context("Failed to create fyers_symbols table")?;
+
+ // Create indexes for fast lookup
+ db.execute(
+ "CREATE INDEX IF NOT EXISTS idx_fyers_symbol ON fyers_symbols(symbol, exchange)",
+ [],
+ )?;
+
+ db.execute(
+ "CREATE INDEX IF NOT EXISTS idx_fyers_exchange ON fyers_symbols(exchange)",
+ [],
+ )?;
+
+ db.execute(
+ "CREATE INDEX IF NOT EXISTS idx_fyers_name ON fyers_symbols(name)",
+ [],
+ )?;
+
+ // Create metadata table to track last update
+ db.execute(
+ "CREATE TABLE IF NOT EXISTS fyers_symbols_metadata (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ last_updated INTEGER NOT NULL,
+ symbol_count INTEGER NOT NULL,
+ csv_data TEXT
+ )",
+ [],
+ )?;
+
+ Ok(())
+}
+
+// ============================================================================
+// WRITE OPERATIONS
+// ============================================================================
+
+/// Save a single Fyers symbol
+pub fn save_symbol(symbol: &FyersSymbol) -> Result<()> {
+ let db = get_db()?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ db.execute(
+ "INSERT OR REPLACE INTO fyers_symbols
+ (token, symbol, name, exchange, segment, instrument_type, isin, tick_size, lot_size, last_updated, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
+ COALESCE((SELECT created_at FROM fyers_symbols WHERE token = ?), ?))",
+ params![
+ symbol.token,
+ symbol.symbol,
+ symbol.name,
+ symbol.exchange,
+ symbol.segment,
+ symbol.instrument_type,
+ symbol.isin,
+ symbol.tick_size,
+ symbol.lot_size,
+ now,
+ symbol.token,
+ now
+ ],
+ )
+ .context("Failed to save Fyers symbol")?;
+
+ Ok(())
+}
+
+/// Save multiple symbols in a transaction (fast bulk insert)
+pub fn save_symbols_bulk(symbols: &[FyersSymbol]) -> Result<()> {
+ let db = get_db()?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ let tx = db.unchecked_transaction()?;
+
+ {
+ let mut stmt = tx.prepare(
+ "INSERT OR REPLACE INTO fyers_symbols
+ (token, symbol, name, exchange, segment, instrument_type, isin, tick_size, lot_size, last_updated, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
+ COALESCE((SELECT created_at FROM fyers_symbols WHERE token = ?), ?))",
+ )?;
+
+ for symbol in symbols {
+ stmt.execute(params![
+ symbol.token,
+ symbol.symbol,
+ symbol.name,
+ symbol.exchange,
+ symbol.segment,
+ symbol.instrument_type,
+ symbol.isin,
+ symbol.tick_size,
+ symbol.lot_size,
+ now,
+ symbol.token,
+ now
+ ])?;
+ }
+ }
+
+ tx.commit()?;
+
+ // Update metadata
+ update_metadata(symbols.len() as i64, None)?;
+
+ Ok(())
+}
+
+/// Update metadata after bulk insert
+pub fn update_metadata(symbol_count: i64, csv_data: Option<&str>) -> Result<()> {
+ let db = get_db()?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ db.execute(
+ "INSERT OR REPLACE INTO fyers_symbols_metadata (id, last_updated, symbol_count, csv_data)
+ VALUES (1, ?, ?, ?)",
+ params![now, symbol_count, csv_data],
+ )?;
+
+ Ok(())
+}
+
+// ============================================================================
+// READ OPERATIONS
+// ============================================================================
+
+/// Get symbol by token (exact match)
+pub fn get_symbol_by_token(token: i32) -> Result<Option<FyersSymbol>> {
+ let db = get_db()?;
+
+ let mut stmt = db.prepare(
+ "SELECT token, symbol, name, exchange, segment, instrument_type, isin, tick_size, lot_size
+ FROM fyers_symbols WHERE token = ?",
+ )?;
+
+ let result = stmt
+ .query_row(params![token], |row| {
+ Ok(FyersSymbol {
+ token: row.get(0)?,
+ symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ segment: row.get(4)?,
+ instrument_type: row.get(5)?,
+ isin: row.get(6)?,
+ tick_size: row.get(7)?,
+ lot_size: row.get(8)?,
+ })
+ })
+ .optional()
+ .context("Failed to get symbol by token")?;
+
+ Ok(result)
+}
+
+/// Get token by symbol and exchange (exact match)
+pub fn get_token_by_symbol(symbol: &str, exchange: &str) -> Result<Option<i32>> {
+ let db = get_db()?;
+
+ let mut stmt = db.prepare(
+ "SELECT token FROM fyers_symbols WHERE symbol = ? AND exchange = ? LIMIT 1",
+ )?;
+
+ let result = stmt
+ .query_row(params![symbol, exchange], |row| row.get(0))
+ .optional()
+ .context("Failed to get token by symbol")?;
+
+ Ok(result)
+}
+
+/// Search symbols by keyword (fuzzy search on symbol and name)
+pub fn search_symbols(keyword: &str, exchange: Option<&str>, limit: i32) -> Result<Vec<SymbolSearchResult>> {
+ let db = get_db()?;
+
+ let search_pattern = format!("%{}%", keyword.to_uppercase());
+
+ let query = if let Some(exch) = exchange {
+ "SELECT token, symbol, name, exchange,
+ CASE
+ WHEN UPPER(symbol) = UPPER(?) THEN 100.0
+ WHEN UPPER(symbol) LIKE ? || '%' THEN 90.0
+ WHEN UPPER(name) LIKE ? || '%' THEN 80.0
+ WHEN UPPER(symbol) LIKE ? THEN 70.0
+ WHEN UPPER(name) LIKE ? THEN 60.0
+ ELSE 50.0
+ END as relevance_score
+ FROM fyers_symbols
+ WHERE (UPPER(symbol) LIKE ? OR UPPER(name) LIKE ?)
+ AND exchange = ?
+ ORDER BY relevance_score DESC, symbol ASC
+ LIMIT ?"
+ } else {
+ "SELECT token, symbol, name, exchange,
+ CASE
+ WHEN UPPER(symbol) = UPPER(?) THEN 100.0
+ WHEN UPPER(symbol) LIKE ? || '%' THEN 90.0
+ WHEN UPPER(name) LIKE ? || '%' THEN 80.0
+ WHEN UPPER(symbol) LIKE ? THEN 70.0
+ WHEN UPPER(name) LIKE ? THEN 60.0
+ ELSE 50.0
+ END as relevance_score
+ FROM fyers_symbols
+ WHERE UPPER(symbol) LIKE ? OR UPPER(name) LIKE ?
+ ORDER BY relevance_score DESC, symbol ASC
+ LIMIT ?"
+ };
+
+ let mut stmt = db.prepare(query)?;
+
+ let results = if let Some(exch) = exchange {
+ let keyword_upper = keyword.to_uppercase();
+ stmt.query_map(
+ params![&keyword_upper, &keyword_upper, &keyword_upper, &search_pattern, &search_pattern, &search_pattern, &search_pattern, exch, limit],
+ |row| {
+ Ok(SymbolSearchResult {
+ token: row.get(0)?,
+ symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ relevance_score: row.get(4)?,
+ })
+ },
+ )?
+ .collect::<Result<Vec<_>, _>>()?
+ } else {
+ let keyword_upper = keyword.to_uppercase();
+ stmt.query_map(
+ params![&keyword_upper, &keyword_upper, &keyword_upper, &search_pattern, &search_pattern, &search_pattern, &search_pattern, limit],
+ |row| {
+ Ok(SymbolSearchResult {
+ token: row.get(0)?,
+ symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ relevance_score: row.get(4)?,
+ })
+ },
+ )?
+ .collect::<Result<Vec<_>, _>>()?
+ };
+
+ Ok(results)
+}
+
+/// Get all symbols for an exchange
+pub fn get_symbols_by_exchange(exchange: &str, limit: i32) -> Result<Vec<FyersSymbol>> {
+ let db = get_db()?;
+
+ let mut stmt = db.prepare(
+ "SELECT token, symbol, name, exchange, segment, instrument_type, isin, tick_size, lot_size
+ FROM fyers_symbols WHERE exchange = ? ORDER BY symbol LIMIT ?",
+ )?;
+
+ let results = stmt
+ .query_map(params![exchange, limit], |row| {
+ Ok(FyersSymbol {
+ token: row.get(0)?,
+ symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ segment: row.get(4)?,
+ instrument_type: row.get(5)?,
+ isin: row.get(6)?,
+ tick_size: row.get(7)?,
+ lot_size: row.get(8)?,
+ })
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+
+ Ok(results)
+}
+
+/// Get total symbol count
+pub fn get_symbol_count() -> Result<i64> {
+ let db = get_db()?;
+
+ let count: i64 = db.query_row("SELECT COUNT(*) FROM fyers_symbols", [], |row| row.get(0))?;
+
+ Ok(count)
+}
+
+/// Get metadata (last updated timestamp and count)
+pub fn get_metadata() -> Result<Option<(i64, i64)>> {
+ let db = get_db()?;
+
+ let mut stmt = db.prepare("SELECT last_updated, symbol_count FROM fyers_symbols_metadata WHERE id = 1")?;
+
+ let result = stmt
+ .query_row([], |row| Ok((row.get(0)?, row.get(1)?)))
+ .optional()?;
+
+ Ok(result)
+}
+
+/// Check if database is populated and recent
+pub fn is_database_valid(max_age_seconds: i64) -> Result<bool> {
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ match get_metadata()? {
+ Some((last_updated, count)) => {
+ Ok(count > 0 && (now - last_updated) < max_age_seconds)
+ }
+ None => Ok(false),
+ }
+}
+
+// ============================================================================
+// DELETE OPERATIONS
+// ============================================================================
+
+/// Clear all symbols (for re-import)
+pub fn clear_all_symbols() -> Result<()> {
+ let db = get_db()?;
+
+ db.execute("DELETE FROM fyers_symbols", [])?;
+ db.execute("DELETE FROM fyers_symbols_metadata", [])?;
+
+ Ok(())
+}
+
+/// Delete symbols by exchange
+pub fn delete_symbols_by_exchange(exchange: &str) -> Result<()> {
+ let db = get_db()?;
+
+ db.execute("DELETE FROM fyers_symbols WHERE exchange = ?", params![exchange])?;
+
+ Ok(())
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/database/master_contract.rs b/fincept-terminal-desktop/src-tauri/src/database/master_contract.rs
index 8470f18bd..a82ac9759 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/master_contract.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/master_contract.rs
@@ -1,12 +1,339 @@
-// Master Contract Cache Database
+// Master Contract Database Operations
// Stores broker symbol data for fast lookup and offline access
use crate::database::pool::get_db;
use anyhow::{Context, Result};
use rusqlite::{params, OptionalExtension};
+use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};
-/// Save master contract data for a broker
+// ============================================================================
+// Data Structures
+// ============================================================================
+
+/// Symbol record for database storage
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Symbol {
+ pub id: Option<i64>,
+ pub broker_id: String,
+ pub symbol: String,
+ pub br_symbol: String,
+ pub name: Option<String>,
+ pub exchange: String,
+ pub br_exchange: Option<String>,
+ pub token: String,
+ pub expiry: Option<String>,
+ pub strike: Option<f64>,
+ pub lot_size: Option<i32>,
+ pub instrument_type: Option<String>,
+ pub tick_size: Option<f64>,
+ pub segment: Option<String>,
+}
+
+/// Master contract cache metadata
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MasterContractCache {
+ pub broker_id: String,
+ pub symbols_data: String,
+ pub symbol_count: i64,
+ pub last_updated: i64,
+ pub created_at: i64,
+}
+
+/// Search result with relevance score
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SearchResult {
+ pub symbol: String,
+ pub br_symbol: String,
+ pub name: Option<String>,
+ pub exchange: String,
+ pub token: String,
+ pub expiry: Option<String>,
+ pub strike: Option<f64>,
+ pub lot_size: Option<i32>,
+ pub instrument_type: Option<String>,
+ pub tick_size: Option<f64>,
+}
+
+// ============================================================================
+// Symbol Operations (New searchable table)
+// ============================================================================
+
+/// Delete all symbols for a broker
+pub fn delete_symbols_for_broker(broker_id: &str) -> Result<i64> {
+ let db = get_db()?;
+ let deleted = db.execute(
+ "DELETE FROM symbols WHERE broker_id = ?",
+ params![broker_id],
+ ).context("Failed to delete symbols")?;
+
+ Ok(deleted as i64)
+}
+
+/// Bulk insert symbols using a transaction for performance
+pub fn bulk_insert_symbols(symbols: &[Symbol]) -> Result<i64> {
+ if symbols.is_empty() {
+ return Ok(0);
+ }
+
+ let mut db = get_db()?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)?
+ .as_secs() as i64;
+
+ let tx = db.transaction()?;
+
+ {
+ let mut stmt = tx.prepare_cached(
+ "INSERT INTO symbols (broker_id, symbol, br_symbol, name, exchange, br_exchange, token, expiry, strike, lot_size, instrument_type, tick_size, segment, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
+ )?;
+
+ for symbol in symbols {
+ stmt.execute(params![
+ symbol.broker_id,
+ symbol.symbol,
+ symbol.br_symbol,
+ symbol.name,
+ symbol.exchange,
+ symbol.br_exchange,
+ symbol.token,
+ symbol.expiry,
+ symbol.strike,
+ symbol.lot_size,
+ symbol.instrument_type,
+ symbol.tick_size,
+ symbol.segment,
+ now,
+ ])?;
+ }
+ }
+
+ tx.commit()?;
+
+ Ok(symbols.len() as i64)
+}
+
+/// Search symbols by query string
+pub fn search_symbols(
+ broker_id: &str,
+ query: &str,
+ exchange: Option<&str>,
+ instrument_type: Option<&str>,
+ limit: i32,
+) -> Result<Vec<SearchResult>> {
+ let db = get_db()?;
+
+ let search_pattern = format!("%{}%", query.to_uppercase());
+
+ // Build dynamic query based on filters
+ let mut sql = String::from(
+ "SELECT symbol, br_symbol, name, exchange, token, expiry, strike, lot_size, instrument_type, tick_size
+ FROM symbols
+ WHERE broker_id = ? AND (
+ UPPER(symbol) LIKE ? OR
+ UPPER(name) LIKE ? OR
+ UPPER(br_symbol) LIKE ? OR
+ token LIKE ?
+ )"
+ );
+
+ let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![
+ Box::new(broker_id.to_string()),
+ Box::new(search_pattern.clone()),
+ Box::new(search_pattern.clone()),
+ Box::new(search_pattern.clone()),
+ Box::new(search_pattern.clone()),
+ ];
+
+ if let Some(exch) = exchange {
+ sql.push_str(" AND exchange = ?");
+ params_vec.push(Box::new(exch.to_string()));
+ }
+
+ if let Some(inst_type) = instrument_type {
+ sql.push_str(" AND instrument_type = ?");
+ params_vec.push(Box::new(inst_type.to_string()));
+ }
+
+ // Order by relevance: exact matches first, then starts with, then contains
+ sql.push_str(&format!(
+ " ORDER BY
+ CASE
+ WHEN UPPER(symbol) = UPPER(?) THEN 0
+ WHEN UPPER(symbol) LIKE UPPER(?) || '%' THEN 1
+ WHEN UPPER(name) = UPPER(?) THEN 2
+ WHEN UPPER(name) LIKE UPPER(?) || '%' THEN 3
+ ELSE 4
+ END,
+ symbol
+ LIMIT ?"
+ ));
+
+ params_vec.push(Box::new(query.to_uppercase()));
+ params_vec.push(Box::new(query.to_uppercase()));
+ params_vec.push(Box::new(query.to_uppercase()));
+ params_vec.push(Box::new(query.to_uppercase()));
+ params_vec.push(Box::new(limit));
+
+ let mut stmt = db.prepare(&sql)?;
+
+ let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
+
+ let results = stmt.query_map(params_refs.as_slice(), |row| {
+ Ok(SearchResult {
+ symbol: row.get(0)?,
+ br_symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ token: row.get(4)?,
+ expiry: row.get(5)?,
+ strike: row.get(6)?,
+ lot_size: row.get(7)?,
+ instrument_type: row.get(8)?,
+ tick_size: row.get(9)?,
+ })
+ })?;
+
+ let mut symbols = Vec::new();
+ for result in results {
+ symbols.push(result?);
+ }
+
+ Ok(symbols)
+}
+
+/// Get symbol by exact match
+pub fn get_symbol(broker_id: &str, symbol: &str, exchange: &str) -> Result<Option<SearchResult>> {
+ let db = get_db()?;
+
+ let result = db.query_row(
+ "SELECT symbol, br_symbol, name, exchange, token, expiry, strike, lot_size, instrument_type, tick_size
+ FROM symbols
+ WHERE broker_id = ? AND UPPER(symbol) = UPPER(?) AND exchange = ?",
+ params![broker_id, symbol, exchange],
+ |row| {
+ Ok(SearchResult {
+ symbol: row.get(0)?,
+ br_symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ token: row.get(4)?,
+ expiry: row.get(5)?,
+ strike: row.get(6)?,
+ lot_size: row.get(7)?,
+ instrument_type: row.get(8)?,
+ tick_size: row.get(9)?,
+ })
+ },
+ ).optional()?;
+
+ Ok(result)
+}
+
+/// Get symbol by token
+pub fn get_symbol_by_token(broker_id: &str, token: &str) -> Result<Option<SearchResult>> {
+ let db = get_db()?;
+
+ let result = db.query_row(
+ "SELECT symbol, br_symbol, name, exchange, token, expiry, strike, lot_size, instrument_type, tick_size
+ FROM symbols
+ WHERE broker_id = ? AND token = ?",
+ params![broker_id, token],
+ |row| {
+ Ok(SearchResult {
+ symbol: row.get(0)?,
+ br_symbol: row.get(1)?,
+ name: row.get(2)?,
+ exchange: row.get(3)?,
+ token: row.get(4)?,
+ expiry: row.get(5)?,
+ strike: row.get(6)?,
+ lot_size: row.get(7)?,
+ instrument_type: row.get(8)?,
+ tick_size: row.get(9)?,
+ })
+ },
+ ).optional()?;
+
+ Ok(result)
+}
+
+/// Get symbol count for a broker
+pub fn get_symbol_count(broker_id: &str) -> Result<i64> {
+ let db = get_db()?;
+
+ let count: i64 = db.query_row(
+ "SELECT COUNT(*) FROM symbols WHERE broker_id = ?",
+ params![broker_id],
+ |row| row.get(0),
+ )?;
+
+ Ok(count)
+}
+
+/// Get distinct exchanges for a broker
+pub fn get_exchanges(broker_id: &str) -> Result<Vec<String>> {
+ let db = get_db()?;
+
+ let mut stmt = db.prepare(
+ "SELECT DISTINCT exchange FROM symbols WHERE broker_id = ? ORDER BY exchange"
+ )?;
+
+ let results = stmt.query_map(params![broker_id], |row| row.get(0))?;
+
+ let mut exchanges = Vec::new();
+ for result in results {
+ exchanges.push(result?);
+ }
+
+ Ok(exchanges)
+}
+
+/// Get distinct expiries for a broker/exchange/underlying
+pub fn get_expiries(
+ broker_id: &str,
+ exchange: Option<&str>,
+ underlying: Option<&str>,
+) -> Result<Vec<String>> {
+ let db = get_db()?;
+
+ let mut sql = String::from(
+ "SELECT DISTINCT expiry FROM symbols WHERE broker_id = ? AND expiry IS NOT NULL AND expiry != ''"
+ );
+
+ let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(broker_id.to_string())];
+
+ if let Some(exch) = exchange {
+ sql.push_str(" AND exchange = ?");
+ params_vec.push(Box::new(exch.to_string()));
+ }
+
+ if let Some(name) = underlying {
+ sql.push_str(" AND name = ?");
+ params_vec.push(Box::new(name.to_string()));
+ }
+
+ sql.push_str(" ORDER BY expiry");
+
+ let mut stmt = db.prepare(&sql)?;
+ let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect();
+
+ let results = stmt.query_map(params_refs.as_slice(), |row| row.get(0))?;
+
+ let mut expiries = Vec::new();
+ for result in results {
+ expiries.push(result?);
+ }
+
+ Ok(expiries)
+}
+
+// ============================================================================
+// Cache Metadata Operations (Existing)
+// ============================================================================
+
+/// Save master contract cache metadata
pub fn save_master_contract(
broker_id: &str,
symbols_data: &str,
@@ -28,7 +355,7 @@ pub fn save_master_contract(
Ok(())
}
-/// Get master contract data for a broker
+/// Get master contract cache metadata
pub fn get_master_contract(broker_id: &str) -> Result<Option<MasterContractCache>> {
let db = get_db()?;
@@ -51,7 +378,7 @@ pub fn get_master_contract(broker_id: &str) -> Result<Option<MasterContractCache
Ok(result)
}
-/// Delete master contract data for a broker
+/// Delete master contract cache
pub fn delete_master_contract(broker_id: &str) -> Result<()> {
let db = get_db()?;
@@ -64,7 +391,7 @@ pub fn delete_master_contract(broker_id: &str) -> Result<()> {
Ok(())
}
-/// Check if master contract exists and is not expired
+/// Check if cache is valid (not expired)
pub fn is_cache_valid(broker_id: &str, ttl_seconds: i64) -> Result<bool> {
let db = get_db()?;
let now = SystemTime::now()
@@ -102,13 +429,3 @@ pub fn get_cache_age(broker_id: &str) -> Result<Option<i64>> {
Ok(last_updated.map(|ts| now - ts))
}
-
-/// Master contract cache data structure
-#[derive(Debug, Clone)]
-pub struct MasterContractCache {
- pub broker_id: String,
- pub symbols_data: String,
- pub symbol_count: i64,
- pub last_updated: i64,
- pub created_at: i64,
-}
diff --git a/fincept-terminal-desktop/src-tauri/src/database/mod.rs b/fincept-terminal-desktop/src-tauri/src/database/mod.rs
index 23ba4c8de..c82e153ea 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/mod.rs
@@ -11,6 +11,7 @@ pub mod notes_excel;
pub mod broker_credentials;
pub mod master_contract;
pub mod storage;
+pub mod fyers_symbols;
pub use pool::init_database;
pub use types::*;
@@ -29,5 +30,13 @@ pub async fn initialize() -> Result<()> {
eprintln!("[Database] ✓ Paper trading tables initialized");
}
+ // Initialize Fyers symbols table
+ eprintln!("[Database] Initializing Fyers symbols table...");
+ if let Err(e) = fyers_symbols::init_fyers_symbols_table() {
+ eprintln!("[Database] Warning: Failed to initialize Fyers symbols table: {}", e);
+ } else {
+ eprintln!("[Database] ✓ Fyers symbols table initialized");
+ }
+
Ok(())
}
diff --git a/fincept-terminal-desktop/src-tauri/src/database/operations.rs b/fincept-terminal-desktop/src-tauri/src/database/operations.rs
index 67c61bb90..5b29a780a 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/operations.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/operations.rs
@@ -232,6 +232,124 @@ pub fn save_llm_global_settings(settings: &LLMGlobalSettings) -> Result<()> {
Ok(())
}
+pub fn set_active_llm_provider(provider: &str) -> Result<()> {
+ let pool = get_pool()?;
+ let conn = pool.get()?;
+
+ // First, set all providers to inactive
+ conn.execute("UPDATE llm_configs SET is_active = 0", [])?;
+
+ // Then set the specified provider as active
+ conn.execute(
+ "UPDATE llm_configs SET is_active = 1 WHERE provider = ?1",
+ params![provider],
+ )?;
+
+ Ok(())
+}
+
+// ============================================================================
+// LLM Model Config Operations
+// ============================================================================
+
+pub fn get_llm_model_configs() -> Result<Vec<LLMModelConfig>> {
+ let pool = get_pool()?;
+ let conn = pool.get()?;
+
+ let mut stmt = conn.prepare(
+ "SELECT id, provider, model_id, display_name, api_key, base_url, is_enabled, is_default, created_at, updated_at
+ FROM llm_model_configs"
+ )?;
+
+ let configs = stmt
+ .query_map([], |row| {
+ Ok(LLMModelConfig {
+ id: row.get(0)?,
+ provider: row.get(1)?,
+ model_id: row.get(2)?,
+ display_name: row.get(3)?,
+ api_key: row.get(4)?,
+ base_url: row.get(5)?,
+ is_enabled: row.get::<_, i32>(6)? != 0,
+ is_default: row.get::<_, i32>(7)? != 0,
+ created_at: row.get(8)?,
+ updated_at: row.get(9)?,
+ })
+ })?
+ .collect::<std::result::Result<Vec<_>, _>>()?;
+
+ Ok(configs)
+}
+
+pub fn save_llm_model_config(config: &LLMModelConfig) -> Result<OperationResult> {
+ let pool = get_pool()?;
+ let conn = pool.get()?;
+
+ conn.execute(
+ "INSERT OR REPLACE INTO llm_model_configs (id, provider, model_id, display_name, api_key, base_url, is_enabled, is_default, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, CURRENT_TIMESTAMP)",
+ params![
+ config.id,
+ config.provider,
+ config.model_id,
+ config.display_name,
+ config.api_key,
+ config.base_url,
+ if config.is_enabled { 1 } else { 0 },
+ if config.is_default { 1 } else { 0 },
+ ],
+ )?;
+
+ Ok(OperationResult {
+ success: true,
+ message: "Model configuration saved".to_string(),
+ })
+}
+
+pub fn delete_llm_model_config(id: &str) -> Result<OperationResult> {
+ let pool = get_pool()?;
+ let conn = pool.get()?;
+
+ let rows_affected = conn.execute(
+ "DELETE FROM llm_model_configs WHERE id = ?1",
+ params![id],
+ )?;
+
+ if rows_affected > 0 {
+ Ok(OperationResult {
+ success: true,
+ message: "Model configuration deleted".to_string(),
+ })
+ } else {
+ Ok(OperationResult {
+ success: false,
+ message: "Model configuration not found".to_string(),
+ })
+ }
+}
+
+pub fn toggle_llm_model_config_enabled(id: &str) -> Result<OperationResult> {
+ let pool = get_pool()?;
+ let conn = pool.get()?;
+
+ let rows_affected = conn.execute(
+ "UPDATE llm_model_configs SET is_enabled = NOT is_enabled, updated_at = CURRENT_TIMESTAMP WHERE id = ?1",
+ params![id],
+ )?;
+
+ if rows_affected > 0 {
+ Ok(OperationResult {
+ success: true,
+ message: "Model enabled state toggled".to_string(),
+ })
+ } else {
+ Ok(OperationResult {
+ success: false,
+ message: "Model configuration not found".to_string(),
+ })
+ }
+}
+
// ============================================================================
// Chat Operations
// ============================================================================
diff --git a/fincept-terminal-desktop/src-tauri/src/database/schema.rs b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
index b57f3bf38..fcb7f6533 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/schema.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
@@ -50,6 +50,27 @@ pub fn create_schema(conn: &Connection) -> Result<()> {
INSERT OR IGNORE INTO llm_global_settings (id, temperature, max_tokens, system_prompt)
VALUES (1, 0.7, 2000, 'You are a helpful AI assistant specialized in financial analysis and market data.');
+ -- LLM model configurations table (user-added custom models)
+ CREATE TABLE IF NOT EXISTS llm_model_configs (
+ id TEXT PRIMARY KEY,
+ provider TEXT NOT NULL,
+ model_id TEXT NOT NULL,
+ display_name TEXT NOT NULL,
+ api_key TEXT,
+ base_url TEXT,
+ is_enabled INTEGER DEFAULT 1,
+ is_default INTEGER DEFAULT 0,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_llm_model_configs_provider ON llm_model_configs(provider);
+ CREATE INDEX IF NOT EXISTS idx_llm_model_configs_enabled ON llm_model_configs(is_enabled);
+
+ -- Insert default Fincept LLM config if not exists
+ INSERT OR IGNORE INTO llm_configs (provider, api_key, base_url, model, is_active)
+ VALUES ('fincept', '', 'https://finceptbackend.share.zrok.io/research/llm', 'fincept-llm', 1);
+
-- Chat sessions table
CREATE TABLE IF NOT EXISTS chat_sessions (
session_uuid TEXT PRIMARY KEY,
@@ -624,7 +645,7 @@ pub fn create_schema(conn: &Connection) -> Result<()> {
CREATE INDEX IF NOT EXISTS idx_broker_credentials_broker_id ON broker_credentials(broker_id);
- -- Master Contract Cache table (Broker symbol data)
+ -- Master Contract Cache table (Broker symbol data metadata)
CREATE TABLE IF NOT EXISTS master_contract_cache (
broker_id TEXT PRIMARY KEY,
symbols_data TEXT NOT NULL,
@@ -633,6 +654,35 @@ pub fn create_schema(conn: &Connection) -> Result<()> {
created_at INTEGER NOT NULL
);
+ -- Symbols table (Searchable instrument database)
+ CREATE TABLE IF NOT EXISTS symbols (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ broker_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ br_symbol TEXT NOT NULL,
+ name TEXT,
+ exchange TEXT NOT NULL,
+ br_exchange TEXT,
+ token TEXT NOT NULL,
+ expiry TEXT,
+ strike REAL,
+ lot_size INTEGER,
+ instrument_type TEXT,
+ tick_size REAL,
+ segment TEXT,
+ created_at INTEGER NOT NULL
+ );
+
+ -- Symbols indices for fast search
+ CREATE INDEX IF NOT EXISTS idx_symbols_broker ON symbols(broker_id);
+ CREATE INDEX IF NOT EXISTS idx_symbols_symbol ON symbols(symbol);
+ CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name);
+ CREATE INDEX IF NOT EXISTS idx_symbols_exchange ON symbols(exchange);
+ CREATE INDEX IF NOT EXISTS idx_symbols_token ON symbols(token);
+ CREATE INDEX IF NOT EXISTS idx_symbols_instrument_type ON symbols(instrument_type);
+ CREATE INDEX IF NOT EXISTS idx_symbols_broker_exchange ON symbols(broker_id, exchange);
+ CREATE INDEX IF NOT EXISTS idx_symbols_symbol_exchange ON symbols(symbol, exchange);
+
-- Generic Key-Value Storage table (localStorage replacement)
CREATE TABLE IF NOT EXISTS key_value_storage (
key TEXT PRIMARY KEY,
diff --git a/fincept-terminal-desktop/src-tauri/src/database/types.rs b/fincept-terminal-desktop/src-tauri/src/database/types.rs
index 6c52e2cfc..2d78b55e2 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/types.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/types.rs
@@ -77,6 +77,20 @@ pub struct LLMGlobalSettings {
pub system_prompt: String,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LLMModelConfig {
+ pub id: String,
+ pub provider: String,
+ pub model_id: String,
+ pub display_name: String,
+ pub api_key: Option<String>,
+ pub base_url: Option<String>,
+ pub is_enabled: bool,
+ pub is_default: bool,
+ pub created_at: Option<String>,
+ pub updated_at: Option<String>,
+}
+
// ============================================================================
// Chat
// ============================================================================
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index a86c0ed52..5cce20125 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -1697,6 +1697,11 @@ pub fn run() {
commands::database::db_save_llm_config,
commands::database::db_get_llm_global_settings,
commands::database::db_save_llm_global_settings,
+ commands::database::db_set_active_llm_provider,
+ commands::database::db_get_llm_model_configs,
+ commands::database::db_save_llm_model_config,
+ commands::database::db_delete_llm_model_config,
+ commands::database::db_toggle_llm_model_config_enabled,
commands::database::db_create_chat_session,
commands::database::db_get_chat_sessions,
commands::database::db_add_chat_message,
@@ -1798,12 +1803,78 @@ pub fn run() {
commands::broker_credentials::get_broker_credentials,
commands::broker_credentials::delete_broker_credentials,
commands::broker_credentials::list_broker_credentials,
- // Master Contract Cache Commands
+ // Master Contract Commands
commands::master_contract::save_master_contract_cache,
commands::master_contract::get_master_contract_cache,
commands::master_contract::delete_master_contract_cache,
commands::master_contract::is_master_contract_cache_valid,
commands::master_contract::get_master_contract_cache_info,
+ commands::master_contract::download_master_contract,
+ commands::master_contract::download_angelone_master_contract,
+ commands::master_contract::download_fyers_master_contract,
+ commands::master_contract::search_symbols,
+ commands::master_contract::get_symbol,
+ commands::master_contract::get_symbol_by_token,
+ commands::master_contract::get_symbol_count,
+ commands::master_contract::get_exchanges,
+ commands::master_contract::get_expiries,
+ // Indian Broker Commands (Zerodha, Angel, Dhan, etc.)
+ commands::brokers::zerodha_exchange_token,
+ commands::brokers::zerodha_validate_token,
+ commands::brokers::zerodha_place_order,
+ commands::brokers::zerodha_modify_order,
+ commands::brokers::zerodha_cancel_order,
+ commands::brokers::zerodha_get_orders,
+ commands::brokers::zerodha_get_positions,
+ commands::brokers::zerodha_get_holdings,
+ commands::brokers::zerodha_get_margins,
+ commands::brokers::zerodha_get_quote,
+ commands::brokers::zerodha_get_historical,
+ commands::brokers::zerodha_download_master_contract,
+ commands::brokers::zerodha_ws_connect,
+ commands::brokers::zerodha_ws_disconnect,
+ commands::brokers::zerodha_ws_subscribe,
+ commands::brokers::zerodha_ws_unsubscribe,
+ commands::brokers::zerodha_ws_set_token_map,
+ commands::brokers::zerodha_ws_is_connected,
+ commands::brokers::zerodha_get_trade_book,
+ commands::brokers::zerodha_get_open_position,
+ commands::brokers::zerodha_place_smart_order,
+ commands::brokers::zerodha_close_all_positions,
+ commands::brokers::zerodha_cancel_all_orders,
+ commands::brokers::zerodha_calculate_margin,
+ commands::brokers::zerodha_search_symbols,
+ commands::brokers::zerodha_get_instrument,
+ commands::brokers::store_indian_broker_credentials,
+ commands::brokers::get_indian_broker_credentials,
+ commands::brokers::delete_indian_broker_credentials,
+ commands::brokers::search_indian_symbols,
+ commands::brokers::get_indian_symbol_token,
+ commands::brokers::get_master_contract_timestamp,
+ // Fyers Broker Commands
+ commands::brokers::fyers_exchange_token,
+ commands::brokers::fyers_place_order,
+ commands::brokers::fyers_modify_order,
+ commands::brokers::fyers_cancel_order,
+ commands::brokers::fyers_get_orders,
+ commands::brokers::fyers_get_trade_book,
+ commands::brokers::fyers_get_positions,
+ commands::brokers::fyers_get_holdings,
+ commands::brokers::fyers_get_funds,
+ commands::brokers::fyers_get_quotes,
+ commands::brokers::fyers_get_history,
+ commands::brokers::fyers_get_depth,
+ commands::brokers::fyers_calculate_margin,
+ commands::brokers::fyers_download_master_contract,
+ commands::brokers::fyers_search_symbol,
+ commands::brokers::fyers_get_token_for_symbol,
+ commands::brokers::fyers_get_symbol_by_token,
+ commands::brokers::fyers_get_master_contract_metadata,
+ commands::brokers::fyers_ws_connect,
+ commands::brokers::fyers_ws_disconnect,
+ commands::brokers::fyers_ws_subscribe,
+ commands::brokers::fyers_ws_unsubscribe,
+ commands::brokers::fyers_ws_is_connected,
// Generic Storage Commands (localStorage replacement)
commands::storage::storage_set,
commands::storage::storage_get,
@@ -1814,7 +1885,16 @@ pub fn run() {
commands::storage::storage_keys,
commands::storage::storage_size,
commands::storage::storage_get_many,
- commands::storage::storage_set_many
+ commands::storage::storage_set_many,
+ // Unified Trading Commands (Live/Paper mode)
+ commands::unified_trading::init_trading_session,
+ commands::unified_trading::get_trading_session,
+ commands::unified_trading::switch_trading_mode,
+ commands::unified_trading::unified_place_order,
+ commands::unified_trading::unified_get_positions,
+ commands::unified_trading::unified_get_orders,
+ commands::unified_trading::unified_cancel_order,
+ commands::unified_trading::process_tick_for_paper_trading
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
diff --git a/fincept-terminal-desktop/src-tauri/src/setup.rs b/fincept-terminal-desktop/src-tauri/src/setup.rs
index df744704c..e7fd179a4 100644
--- a/fincept-terminal-desktop/src-tauri/src/setup.rs
+++ b/fincept-terminal-desktop/src-tauri/src/setup.rs
@@ -725,24 +725,17 @@ pub fn check_setup_status(app: AppHandle) -> Result<SetupStatus, String> {
// Initialize worker pool in background if setup is already complete (non-blocking)
// CRITICAL: Use tauri::async_runtime to ensure worker pool lives in Tauri's persistent runtime
if !needs_setup && python_installed {
- eprintln!("[SETUP] Python already installed, initializing worker pool in background...");
let app_clone = app.clone();
tauri::async_runtime::spawn(async move {
let install_dir = match get_install_dir(&app_clone) {
Ok(dir) => dir,
- Err(e) => {
- eprintln!("[SETUP] Failed to get install dir: {}", e);
+ Err(_e) => {
return;
}
};
- if let Err(e) = crate::python_runtime::initialize_global_async(install_dir).await {
- eprintln!("[SETUP] Warning: Failed to initialize worker pool: {}", e);
- } else {
- eprintln!("[SETUP] Worker pool initialized successfully in background");
- }
+ let _ = crate::python_runtime::initialize_global_async(install_dir).await;
});
- eprintln!("[SETUP] Worker pool initialization started in background (non-blocking)");
}
Ok(SetupStatus {
@@ -830,16 +823,10 @@ pub async fn run_setup(app: AppHandle) -> Result<String, String> {
// Initialize worker pool in background (non-blocking)
// CRITICAL: Use tauri::async_runtime to ensure worker pool lives in Tauri's persistent runtime
- eprintln!("[SETUP] Initializing worker pool in background...");
let install_dir_clone = install_dir.clone();
tauri::async_runtime::spawn(async move {
- if let Err(e) = crate::python_runtime::initialize_global_async(install_dir_clone).await {
- eprintln!("[SETUP] Warning: Failed to initialize worker pool: {}", e);
- } else {
- eprintln!("[SETUP] Worker pool initialized successfully in background");
- }
+ let _ = crate::python_runtime::initialize_global_async(install_dir_clone).await;
});
- eprintln!("[SETUP] Worker pool initialization started in background (non-blocking)");
Ok("Setup complete".to_string())
}.await;
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs
index 1c39cdb54..93b2ad82d 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs
@@ -1,45 +1,548 @@
-// Fyers WebSocket Adapter (Stub - to be implemented)
+// Fyers WebSocket Adapter with Binary Protocol (HSM v1.5)
+//
+// Fyers uses a proprietary binary protocol over WebSocket for real-time data:
+// - Connection: wss://socket.fyers.in/hsm/v1-5/prod
+// - Authentication: Requires access token in connection URL
+// - Protocol: Binary messages with specific packet structures
+// - Subscription: Symbol tokens from master contract (e.g., NSE:RELIANCE-EQ)
use super::WebSocketAdapter;
use crate::websocket::types::*;
use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
use serde_json::Value;
+use std::collections::HashMap;
+use std::sync::Arc;
+use tokio::net::TcpStream;
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};
+
+// Subscription mode for internal tracking
+#[derive(Debug, Clone, PartialEq)]
+enum SubscriptionMode {
+ Ltp,
+ Quote,
+ Full,
+}
+
+// ============================================================================
+// FYERS WEBSOCKET CONFIGURATION
+// ============================================================================
+
+const FYERS_WS_URL: &str = "wss://socket.fyers.in/hsm/v1-5/prod";
+
+// Fyers data packet structure constants
+const PACKET_TYPE_TICK: u8 = 31;
+const PACKET_TYPE_DEPTH: u8 = 41;
+const PACKET_TYPE_FULL_DEPTH: u8 = 43;
+const PACKET_TYPE_CONFIRMATION: u8 = 8;
+
+// ============================================================================
+// BINARY PROTOCOL STRUCTURES
+// ============================================================================
+
+/// Fyers tick data packet (minimal binary structure)
+#[derive(Debug, Clone)]
+struct FyersTickPacket {
+ packet_type: u8,
+ token: i32,
+ ltp: f64,
+ volume: i64,
+ change_percent: f64,
+ timestamp: u64,
+}
+
+/// Fyers market depth packet
+#[derive(Debug, Clone)]
+struct FyersDepthPacket {
+ packet_type: u8,
+ token: i32,
+ bids: Vec<(f64, i32)>, // (price, quantity)
+ asks: Vec<(f64, i32)>,
+}
+
+// ============================================================================
+// FYERS ADAPTER
+// ============================================================================
pub struct FyersAdapter {
config: ProviderConfig,
+ access_token: String,
+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,
message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,
+ subscriptions: Arc<RwLock<HashMap<String, SubscriptionMode>>>,
+ is_connected: Arc<RwLock<bool>>,
+ token_symbol_map: Arc<RwLock<HashMap<i32, String>>>, // Token -> Symbol mapping
}
impl FyersAdapter {
pub fn new(config: ProviderConfig) -> Self {
+ let access_token = config.api_key.clone().unwrap_or_default();
Self {
config,
+ access_token,
+ ws_stream: Arc::new(RwLock::new(None)),
message_callback: None,
+ subscriptions: Arc::new(RwLock::new(HashMap::new())),
+ is_connected: Arc::new(RwLock::new(false)),
+ token_symbol_map: Arc::new(RwLock::new(HashMap::new())),
+ }
+ }
+
+ /// Parse binary tick data from Fyers HSM protocol
+ fn parse_tick_data(&self, data: &[u8]) -> Option<FyersTickPacket> {
+ if data.len() < 32 {
+ return None;
+ }
+
+ let packet_type = data[0];
+ if packet_type != PACKET_TYPE_TICK {
+ return None;
}
+
+ // Parse binary fields (little-endian)
+ let token = i32::from_le_bytes([data[1], data[2], data[3], data[4]]);
+ let ltp = f64::from_le_bytes([
+ data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12],
+ ]);
+ let volume = i64::from_le_bytes([
+ data[13], data[14], data[15], data[16], data[17], data[18], data[19], data[20],
+ ]);
+ let change_percent = f64::from_le_bytes([
+ data[21], data[22], data[23], data[24], data[25], data[26], data[27], data[28],
+ ]);
+ let timestamp = u64::from_le_bytes([
+ data[29], data[30], data[31], data[32], data[33], data[34], data[35], data[36],
+ ]);
+
+ Some(FyersTickPacket {
+ packet_type,
+ token,
+ ltp,
+ volume,
+ change_percent,
+ timestamp,
+ })
+ }
+
+ /// Parse binary market depth from Fyers
+ fn parse_depth_data(&self, data: &[u8]) -> Option<FyersDepthPacket> {
+ if data.len() < 10 {
+ return None;
+ }
+
+ let packet_type = data[0];
+ if packet_type != PACKET_TYPE_DEPTH && packet_type != PACKET_TYPE_FULL_DEPTH {
+ return None;
+ }
+
+ let token = i32::from_le_bytes([data[1], data[2], data[3], data[4]]);
+
+ // Parse 5 levels of bids and asks
+ let mut bids = Vec::new();
+ let mut asks = Vec::new();
+
+ let mut offset = 5;
+ for _ in 0..5 {
+ if offset + 12 <= data.len() {
+ let price = f64::from_le_bytes([
+ data[offset],
+ data[offset + 1],
+ data[offset + 2],
+ data[offset + 3],
+ data[offset + 4],
+ data[offset + 5],
+ data[offset + 6],
+ data[offset + 7],
+ ]);
+ let qty = i32::from_le_bytes([
+ data[offset + 8],
+ data[offset + 9],
+ data[offset + 10],
+ data[offset + 11],
+ ]);
+ bids.push((price, qty));
+ offset += 12;
+ }
+ }
+
+ for _ in 0..5 {
+ if offset + 12 <= data.len() {
+ let price = f64::from_le_bytes([
+ data[offset],
+ data[offset + 1],
+ data[offset + 2],
+ data[offset + 3],
+ data[offset + 4],
+ data[offset + 5],
+ data[offset + 6],
+ data[offset + 7],
+ ]);
+ let qty = i32::from_le_bytes([
+ data[offset + 8],
+ data[offset + 9],
+ data[offset + 10],
+ data[offset + 11],
+ ]);
+ asks.push((price, qty));
+ offset += 12;
+ }
+ }
+
+ Some(FyersDepthPacket {
+ packet_type,
+ token,
+ bids,
+ asks,
+ })
+ }
+
+ /// Convert Fyers symbol to token (uses master contract database)
+ async fn symbol_to_token(&self, symbol: &str) -> Option<i32> {
+ // Parse Fyers symbol format: "EXCHANGE:SYMBOL" (e.g., "NSE:RELIANCE-EQ")
+ let parts: Vec<&str> = symbol.split(':').collect();
+
+ if parts.len() != 2 {
+ eprintln!("Fyers: Invalid symbol format (expected EXCHANGE:SYMBOL): {}", symbol);
+ return None;
+ }
+
+ let exchange = parts[0];
+ let symbol_name = parts[1];
+
+ // Look up token in database
+ match crate::database::fyers_symbols::get_token_by_symbol(symbol_name, exchange) {
+ Ok(Some(token)) => {
+ eprintln!("Fyers: Mapped {}:{} -> token {}", exchange, symbol_name, token);
+ Some(token)
+ }
+ Ok(None) => {
+ eprintln!("Fyers: Symbol not found in database: {}:{}", exchange, symbol_name);
+ None
+ }
+ Err(e) => {
+ eprintln!("Fyers: Database error during token lookup: {}", e);
+ None
+ }
+ }
+ }
+
+ /// Build subscription message for Fyers
+ fn build_subscription_message(&self, tokens: Vec<i32>, mode: &str) -> Vec<u8> {
+ // Fyers subscription format (binary):
+ // [message_type (1 byte)][mode (1 byte)][token_count (2 bytes)][tokens...]
+ let mut msg = Vec::new();
+
+ // Message type: 1 = Subscribe, 0 = Unsubscribe
+ msg.push(1);
+
+ // Mode: 1 = LTP, 2 = Quotes, 3 = Full depth
+ let mode_byte = match mode {
+ "ltp" => 1,
+ "quotes" => 2,
+ "depth" => 3,
+ _ => 1,
+ };
+ msg.push(mode_byte);
+
+ // Token count
+ let token_count = tokens.len() as u16;
+ msg.extend_from_slice(&token_count.to_le_bytes());
+
+ // Tokens
+ for token in tokens {
+ msg.extend_from_slice(&token.to_le_bytes());
+ }
+
+ msg
+ }
+
+ /// Handle incoming binary message
+ async fn handle_binary_message(&self, data: Vec<u8>) {
+ if data.is_empty() {
+ return;
+ }
+
+ let packet_type = data[0];
+
+ match packet_type {
+ PACKET_TYPE_TICK => {
+ if let Some(tick) = self.parse_tick_data(&data) {
+ self.emit_tick_message(tick).await;
+ }
+ }
+ PACKET_TYPE_DEPTH | PACKET_TYPE_FULL_DEPTH => {
+ if let Some(depth) = self.parse_depth_data(&data) {
+ self.emit_depth_message(depth).await;
+ }
+ }
+ PACKET_TYPE_CONFIRMATION => {
+ eprintln!("Fyers: Subscription confirmed");
+ }
+ _ => {
+ eprintln!("Fyers: Unknown packet type: {}", packet_type);
+ }
+ }
+ }
+
+ /// Emit tick message to callback
+ async fn emit_tick_message(&self, tick: FyersTickPacket) {
+ if let Some(callback) = &self.message_callback {
+ // Look up symbol from token
+ let symbol_map = self.token_symbol_map.read().await;
+ let symbol = symbol_map
+ .get(&tick.token)
+ .cloned()
+ .unwrap_or_else(|| format!("TOKEN_{}", tick.token));
+
+ let message = MarketMessage::Ticker(TickerData {
+ provider: "fyers".to_string(),
+ symbol,
+ price: tick.ltp,
+ bid: None,
+ ask: None,
+ bid_size: None,
+ ask_size: None,
+ volume: Some(tick.volume as f64),
+ high: None,
+ low: None,
+ open: None,
+ close: None,
+ change: None,
+ change_percent: Some(tick.change_percent),
+ timestamp: tick.timestamp,
+ });
+
+ callback(message);
+ }
+ }
+
+ /// Emit depth message to callback
+ async fn emit_depth_message(&self, depth: FyersDepthPacket) {
+ if let Some(callback) = &self.message_callback {
+ let symbol_map = self.token_symbol_map.read().await;
+ let symbol = symbol_map
+ .get(&depth.token)
+ .cloned()
+ .unwrap_or_else(|| format!("TOKEN_{}", depth.token));
+
+ let bids: Vec<OrderBookLevel> = depth
+ .bids
+ .iter()
+ .map(|(price, qty)| OrderBookLevel {
+ price: *price,
+ quantity: *qty as f64,
+ count: None,
+ })
+ .collect();
+
+ let asks: Vec<OrderBookLevel> = depth
+ .asks
+ .iter()
+ .map(|(price, qty)| OrderBookLevel {
+ price: *price,
+ quantity: *qty as f64,
+ count: None,
+ })
+ .collect();
+
+ let message = MarketMessage::OrderBook(OrderBookData {
+ provider: "fyers".to_string(),
+ symbol,
+ bids,
+ asks,
+ timestamp: chrono::Utc::now().timestamp() as u64,
+ is_snapshot: true,
+ });
+
+ callback(message);
+ }
+ }
+
+ /// Start message processing loop
+ async fn start_message_loop(
+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,
+ adapter: Arc<RwLock<FyersAdapter>>,
+ ) {
+ loop {
+ let mut stream_lock = ws_stream.write().await;
+
+ if let Some(stream) = stream_lock.as_mut() {
+ match stream.next().await {
+ Some(Ok(Message::Binary(data))) => {
+ drop(stream_lock);
+ let adapter_read = adapter.read().await;
+ adapter_read.handle_binary_message(data).await;
+ }
+ Some(Ok(Message::Text(text))) => {
+ drop(stream_lock);
+ eprintln!("Fyers: Unexpected text message: {}", text);
+ }
+ Some(Ok(Message::Ping(data))) => {
+ let _ = stream.send(Message::Pong(data)).await;
+ }
+ Some(Ok(Message::Close(_))) => {
+ drop(stream_lock);
+ eprintln!("Fyers: WebSocket closed");
+ break;
+ }
+ Some(Err(e)) => {
+ drop(stream_lock);
+ eprintln!("Fyers: WebSocket error: {}", e);
+ break;
+ }
+ None => {
+ drop(stream_lock);
+ eprintln!("Fyers: Stream ended");
+ break;
+ }
+ _ => {}
+ }
+ } else {
+ drop(stream_lock);
+ break;
+ }
+ }
+
+ // Mark as disconnected
+ let adapter_read = adapter.read().await;
+ let mut connected = adapter_read.is_connected.write().await;
+ *connected = false;
}
}
#[async_trait]
impl WebSocketAdapter for FyersAdapter {
async fn connect(&mut self) -> anyhow::Result<()> {
- // TODO: Implement Fyers connection
- Err(anyhow::anyhow!("Fyers adapter not yet implemented"))
+ // Use access token from adapter
+ if self.access_token.is_empty() {
+ return Err(anyhow::anyhow!("Access token not configured"));
+ }
+
+ // Build WebSocket URL with access token
+ let url = format!("{}?access_token={}", FYERS_WS_URL, self.access_token);
+
+ // Connect to WebSocket
+ let (ws_stream, _) = connect_async(&url).await?;
+
+ eprintln!("Fyers: WebSocket connected");
+
+ // Store stream
+ let mut stream_lock = self.ws_stream.write().await;
+ *stream_lock = Some(ws_stream);
+ drop(stream_lock);
+
+ // Mark as connected
+ let mut connected = self.is_connected.write().await;
+ *connected = true;
+
+ // Start message processing loop
+ let ws_stream_clone = Arc::clone(&self.ws_stream);
+ let adapter_arc = Arc::new(RwLock::new(Self {
+ config: self.config.clone(),
+ access_token: self.access_token.clone(),
+ ws_stream: Arc::clone(&self.ws_stream),
+ message_callback: self.message_callback.take(),
+ subscriptions: Arc::clone(&self.subscriptions),
+ is_connected: Arc::clone(&self.is_connected),
+ token_symbol_map: Arc::clone(&self.token_symbol_map),
+ }));
+
+ tokio::spawn(async move {
+ Self::start_message_loop(ws_stream_clone, adapter_arc).await;
+ });
+
+ Ok(())
}
async fn disconnect(&mut self) -> anyhow::Result<()> {
+ let mut stream_lock = self.ws_stream.write().await;
+ if let Some(mut stream) = stream_lock.take() {
+ stream.close(None).await?;
+ }
+
+ let mut connected = self.is_connected.write().await;
+ *connected = false;
+
+ eprintln!("Fyers: Disconnected");
Ok(())
}
async fn subscribe(
&mut self,
- _symbol: &str,
- _channel: &str,
+ symbol: &str,
+ channel: &str,
_params: Option<Value>,
) -> anyhow::Result<()> {
- Err(anyhow::anyhow!("Fyers adapter not yet implemented"))
+ // Convert symbol to token
+ let token = self
+ .symbol_to_token(symbol)
+ .await
+ .ok_or_else(|| anyhow::anyhow!("Could not map symbol to token: {}", symbol))?;
+
+ // Store symbol-token mapping
+ let mut symbol_map = self.token_symbol_map.write().await;
+ symbol_map.insert(token, symbol.to_string());
+ drop(symbol_map);
+
+ // Determine subscription mode from channel
+ let mode = match channel {
+ "tick" | "ltp" => "ltp",
+ "quote" | "quotes" => "quotes",
+ "depth" | "market_depth" => "depth",
+ _ => "ltp",
+ };
+
+ // Build subscription message
+ let sub_msg = self.build_subscription_message(vec![token], mode);
+
+ // Send subscription
+ let mut stream_lock = self.ws_stream.write().await;
+ if let Some(stream) = stream_lock.as_mut() {
+ stream.send(Message::Binary(sub_msg)).await?;
+
+ // Store subscription
+ drop(stream_lock);
+ let mut subs = self.subscriptions.write().await;
+ let sub_mode = match mode {
+ "ltp" => SubscriptionMode::Ltp,
+ "quotes" => SubscriptionMode::Quote,
+ "depth" => SubscriptionMode::Full,
+ _ => SubscriptionMode::Ltp,
+ };
+ subs.insert(symbol.to_string(), sub_mode);
+
+ eprintln!("Fyers: Subscribed to {} (token: {}, mode: {})", symbol, token, mode);
+ Ok(())
+ } else {
+ Err(anyhow::anyhow!("Not connected"))
+ }
}
- async fn unsubscribe(&mut self, _symbol: &str, _channel: &str) -> anyhow::Result<()> {
+ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {
+ // Convert symbol to token
+ if let Some(token) = self.symbol_to_token(symbol).await {
+ // Build unsubscribe message (same format, but message_type = 0)
+ let mut msg = Vec::new();
+ msg.push(0); // Unsubscribe
+ msg.push(1); // Mode (doesn't matter for unsubscribe)
+ msg.extend_from_slice(&1u16.to_le_bytes()); // Token count
+ msg.extend_from_slice(&token.to_le_bytes()); // Token
+
+ // Send unsubscribe
+ let mut stream_lock = self.ws_stream.write().await;
+ if let Some(stream) = stream_lock.as_mut() {
+ stream.send(Message::Binary(msg)).await?;
+
+ // Remove subscription
+ drop(stream_lock);
+ let mut subs = self.subscriptions.write().await;
+ subs.remove(symbol);
+
+ eprintln!("Fyers: Unsubscribed from {} (token: {})", symbol, token);
+ }
+ }
+
Ok(())
}
@@ -52,6 +555,7 @@ impl WebSocketAdapter for FyersAdapter {
}
fn is_connected(&self) -> bool {
- false
+ // Read from Arc<RwLock<bool>> synchronously (blocking)
+ futures::executor::block_on(async { *self.is_connected.read().await })
}
}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs
index bc0bcafcc..7ab2fd28a 100644
--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs
@@ -7,11 +7,13 @@ pub mod kraken;
pub mod hyperliquid;
pub mod binance;
pub mod fyers;
+pub mod zerodha;
pub use kraken::KrakenAdapter;
pub use hyperliquid::HyperLiquidAdapter;
pub use binance::BinanceAdapter;
pub use fyers::FyersAdapter;
+pub use zerodha::ZerodhaAdapter;
// ============================================================================
// ADAPTER TRAIT
@@ -61,6 +63,7 @@ pub fn create_adapter(
"hyperliquid" => Ok(Box::new(HyperLiquidAdapter::new(config))),
"binance" => Ok(Box::new(BinanceAdapter::new(config))),
"fyers" => Ok(Box::new(FyersAdapter::new(config))),
+ "zerodha" | "kite" => Ok(Box::new(ZerodhaAdapter::new(config))),
_ => Err(anyhow::anyhow!("Unknown provider: {}", provider)),
}
}
diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/zerodha.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/zerodha.rs
new file mode 100644
index 000000000..28b2abeea
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/zerodha.rs
@@ -0,0 +1,619 @@
+// Zerodha KiteTicker WebSocket Adapter
+//
+// Implements Zerodha's KiteTicker WebSocket API for real-time market data
+// Binary protocol for high-performance data streaming
+// Supports: LTP, Quote, Full depth modes
+
+use super::WebSocketAdapter;
+use crate::websocket::types::*;
+use async_trait::async_trait;
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use tokio::sync::RwLock;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+// Zerodha WebSocket URL format
+const ZERODHA_WS_BASE_URL: &str = "wss://ws.kite.trade";
+
+// Subscription modes
+const MODE_LTP: &str = "ltp";
+const MODE_QUOTE: &str = "quote";
+const MODE_FULL: &str = "full";
+
+// Packet sizes for different modes
+const PACKET_SIZE_LTP: usize = 8;
+const PACKET_SIZE_QUOTE: usize = 44;
+const PACKET_SIZE_FULL: usize = 184;
+
+// Batching settings
+const MAX_TOKENS_PER_SUBSCRIBE: usize = 200;
+const SUBSCRIPTION_DELAY_MS: u64 = 2000;
+
+/// Callback type for connection errors (used to trigger reconnection)
+type ErrorCallback = Box<dyn Fn(String) + Send + Sync>;
+
+pub struct ZerodhaAdapter {
+ config: ProviderConfig,
+ api_key: String,
+ access_token: String,
+ ws: Option<Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>>,
+ message_callback: Option<Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>>,
+ error_callback: Option<Arc<ErrorCallback>>,
+ connected: Arc<AtomicBool>,
+ last_message_time: Arc<RwLock<u64>>,
+ // Token tracking
+ subscribed_tokens: Arc<RwLock<HashMap<i64, String>>>, // token -> mode
+ token_symbol_map: Arc<RwLock<HashMap<i64, (String, String)>>>, // token -> (symbol, exchange)
+ // Statistics
+ message_count: Arc<AtomicU64>,
+ tick_count: Arc<AtomicU64>,
+}
+
+impl ZerodhaAdapter {
+ pub fn new(config: ProviderConfig) -> Self {
+ let api_key = config.api_key.clone().unwrap_or_default();
+ let access_token = config.api_secret.clone().unwrap_or_default(); // access_token stored in api_secret
+
+ Self {
+ config,
+ api_key,
+ access_token,
+ ws: None,
+ message_callback: None,
+ error_callback: None,
+ connected: Arc::new(AtomicBool::new(false)),
+ last_message_time: Arc::new(RwLock::new(0)),
+ subscribed_tokens: Arc::new(RwLock::new(HashMap::new())),
+ token_symbol_map: Arc::new(RwLock::new(HashMap::new())),
+ message_count: Arc::new(AtomicU64::new(0)),
+ tick_count: Arc::new(AtomicU64::new(0)),
+ }
+ }
+
+ /// Create with explicit credentials
+ pub fn new_with_credentials(api_key: String, access_token: String) -> Self {
+ let config = ProviderConfig {
+ name: "zerodha".to_string(),
+ url: ZERODHA_WS_BASE_URL.to_string(),
+ api_key: Some(api_key.clone()),
+ api_secret: Some(access_token.clone()),
+ enabled: true,
+ ..Default::default()
+ };
+
+ Self {
+ config,
+ api_key,
+ access_token,
+ ws: None,
+ message_callback: None,
+ error_callback: None,
+ connected: Arc::new(AtomicBool::new(false)),
+ last_message_time: Arc::new(RwLock::new(0)),
+ subscribed_tokens: Arc::new(RwLock::new(HashMap::new())),
+ token_symbol_map: Arc::new(RwLock::new(HashMap::new())),
+ message_count: Arc::new(AtomicU64::new(0)),
+ tick_count: Arc::new(AtomicU64::new(0)),
+ }
+ }
+
+ fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_else(|_| Duration::from_secs(0))
+ .as_millis() as u64
+ }
+
+ /// Set error callback for connection errors
+ pub fn set_error_callback(&mut self, callback: ErrorCallback) {
+ self.error_callback = Some(Arc::new(callback));
+ }
+
+ /// Set token to symbol mapping
+ pub fn set_token_symbol_map(&self, token: i64, symbol: String, exchange: String) {
+ if let Ok(mut map) = self.token_symbol_map.try_write() {
+ map.insert(token, (symbol, exchange));
+ }
+ }
+
+ /// Build WebSocket URL with authentication
+ fn build_ws_url(&self) -> String {
+ format!(
+ "{}?api_key={}&access_token={}",
+ ZERODHA_WS_BASE_URL, self.api_key, self.access_token
+ )
+ }
+
+ /// Subscribe to tokens with a specific mode
+ pub async fn subscribe_tokens(&self, tokens: Vec<i64>, mode: &str) -> anyhow::Result<()> {
+ if !self.connected.load(Ordering::SeqCst) {
+ return Err(anyhow::anyhow!("Not connected"));
+ }
+
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("WebSocket not initialized"))?;
+
+ // Process in batches
+ for chunk in tokens.chunks(MAX_TOKENS_PER_SUBSCRIBE) {
+ let chunk_vec: Vec<i64> = chunk.to_vec();
+
+ // Send subscribe message
+ let sub_msg = json!({
+ "a": "subscribe",
+ "v": chunk_vec
+ });
+
+ {
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(sub_msg.to_string())).await?;
+ }
+
+ eprintln!("[Zerodha] Subscribed to {} tokens", chunk_vec.len());
+
+ // Wait a bit for subscription to process
+ tokio::time::sleep(Duration::from_secs(1)).await;
+
+ // Set mode
+ let mode_msg = json!({
+ "a": "mode",
+ "v": [mode, chunk_vec]
+ });
+
+ {
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(mode_msg.to_string())).await?;
+ }
+
+ eprintln!("[Zerodha] Set mode {} for {} tokens", mode, chunk_vec.len());
+
+ // Update subscribed tokens
+ {
+ let mut subscribed = self.subscribed_tokens.write().await;
+ for token in chunk_vec {
+ subscribed.insert(token, mode.to_string());
+ }
+ }
+
+ // Delay between batches
+ if chunk.len() == MAX_TOKENS_PER_SUBSCRIBE {
+ tokio::time::sleep(Duration::from_millis(SUBSCRIPTION_DELAY_MS)).await;
+ }
+ }
+
+ Ok(())
+ }
+
+ /// Unsubscribe from tokens
+ pub async fn unsubscribe_tokens(&self, tokens: Vec<i64>) -> anyhow::Result<()> {
+ if !self.connected.load(Ordering::SeqCst) {
+ return Err(anyhow::anyhow!("Not connected"));
+ }
+
+ let ws = self.ws.as_ref().ok_or_else(|| anyhow::anyhow!("WebSocket not initialized"))?;
+
+ let unsub_msg = json!({
+ "a": "unsubscribe",
+ "v": tokens
+ });
+
+ {
+ let mut ws_lock = ws.write().await;
+ ws_lock.send(Message::Text(unsub_msg.to_string())).await?;
+ }
+
+ // Update subscribed tokens
+ {
+ let mut subscribed = self.subscribed_tokens.write().await;
+ for token in &tokens {
+ subscribed.remove(token);
+ }
+ }
+
+ eprintln!("[Zerodha] Unsubscribed from {} tokens", tokens.len());
+
+ Ok(())
+ }
+
+ /// Message receiver loop
+ async fn receive_loop(
+ ws: Arc<RwLock<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>>>,
+ callback: Arc<Box<dyn Fn(MarketMessage) + Send + Sync>>,
+ error_callback: Option<Arc<ErrorCallback>>,
+ connected: Arc<AtomicBool>,
+ last_message_time: Arc<RwLock<u64>>,
+ token_symbol_map: Arc<RwLock<HashMap<i64, (String, String)>>>,
+ message_count: Arc<AtomicU64>,
+ tick_count: Arc<AtomicU64>,
+ ) {
+ loop {
+ let msg_result = {
+ let mut ws_lock = ws.write().await;
+ ws_lock.next().await
+ };
+
+ match msg_result {
+ Some(Ok(msg)) => {
+ // Update last message time
+ *last_message_time.write().await = Self::now();
+ message_count.fetch_add(1, Ordering::Relaxed);
+
+ match msg {
+ Message::Binary(data) => {
+ // Handle binary market data
+ if data.len() == 1 {
+ // Zerodha heartbeat - 1 byte message
+ continue;
+ }
+
+ // Parse binary data
+ let ticks = Self::parse_binary_message(&data, &token_symbol_map).await;
+ tick_count.fetch_add(ticks.len() as u64, Ordering::Relaxed);
+
+ for tick in ticks {
+ callback(MarketMessage::Ticker(tick));
+ }
+ }
+ Message::Text(text) => {
+ // Handle JSON messages (errors, order updates)
+ if let Ok(data) = serde_json::from_str::<Value>(&text) {
+ if let Some(msg_type) = data.get("type").and_then(|t| t.as_str()) {
+ if msg_type == "error" {
+ let error_msg = data.get("data")
+ .and_then(|d| d.as_str())
+ .unwrap_or("Unknown error")
+ .to_string();
+ eprintln!("[Zerodha] Error: {}", error_msg);
+
+ callback(MarketMessage::Status(StatusData {
+ provider: "zerodha".to_string(),
+ status: ConnectionStatus::Error,
+ message: Some(error_msg),
+ timestamp: Self::now(),
+ }));
+ }
+ }
+ }
+ }
+ Message::Ping(data) => {
+ // Respond to ping with pong
+ let mut ws_lock = ws.write().await;
+ let _ = ws_lock.send(Message::Pong(data)).await;
+ }
+ Message::Close(_) => {
+ eprintln!("[Zerodha] Connection closed by server");
+ break;
+ }
+ _ => {}
+ }
+ }
+ Some(Err(e)) => {
+ let error_msg = format!("WebSocket error: {}", e);
+ eprintln!("[Zerodha] {}", error_msg);
+ connected.store(false, Ordering::SeqCst);
+
+ callback(MarketMessage::Status(StatusData {
+ provider: "zerodha".to_string(),
+ status: ConnectionStatus::Error,
+ message: Some(error_msg.clone()),
+ timestamp: Self::now(),
+ }));
+
+ if let Some(err_cb) = &error_callback {
+ err_cb(error_msg);
+ }
+ break;
+ }
+ None => {
+ let error_msg = "WebSocket connection closed unexpectedly".to_string();
+ eprintln!("[Zerodha] {}", error_msg);
+ connected.store(false, Ordering::SeqCst);
+
+ callback(MarketMessage::Status(StatusData {
+ provider: "zerodha".to_string(),
+ status: ConnectionStatus::Disconnected,
+ message: Some(error_msg.clone()),
+ timestamp: Self::now(),
+ }));
+
+ if let Some(err_cb) = &error_callback {
+ err_cb(error_msg);
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ /// Parse binary message according to Zerodha specification
+ async fn parse_binary_message(
+ data: &[u8],
+ token_symbol_map: &Arc<RwLock<HashMap<i64, (String, String)>>>,
+ ) -> Vec<TickerData> {
+ let mut ticks = Vec::new();
+
+ if data.len() < 4 {
+ return ticks;
+ }
+
+ // Parse header: first 2 bytes = number of packets
+ let num_packets = u16::from_be_bytes([data[0], data[1]]) as usize;
+ let mut offset = 2;
+
+ for _ in 0..num_packets {
+ if offset + 2 > data.len() {
+ break;
+ }
+
+ // Next 2 bytes: packet length
+ let packet_length = u16::from_be_bytes([data[offset], data[offset + 1]]) as usize;
+ offset += 2;
+
+ if offset + packet_length > data.len() {
+ break;
+ }
+
+ // Extract and parse packet
+ let packet_data = &data[offset..offset + packet_length];
+ if let Some(tick) = Self::parse_packet(packet_data, token_symbol_map).await {
+ ticks.push(tick);
+ }
+
+ offset += packet_length;
+ }
+
+ ticks
+ }
+
+ /// Parse individual packet
+ async fn parse_packet(
+ packet: &[u8],
+ token_symbol_map: &Arc<RwLock<HashMap<i64, (String, String)>>>,
+ ) -> Option<TickerData> {
+ if packet.len() < PACKET_SIZE_LTP {
+ return None;
+ }
+
+ // Extract instrument token (first 4 bytes, big-endian)
+ let instrument_token = i32::from_be_bytes([packet[0], packet[1], packet[2], packet[3]]) as i64;
+
+ // Extract last price (next 4 bytes, big-endian, in paise)
+ let last_price_paise = i32::from_be_bytes([packet[4], packet[5], packet[6], packet[7]]);
+ let last_price = last_price_paise as f64 / 100.0;
+
+ // Get symbol and exchange from map
+ let (symbol, exchange) = {
+ let map = token_symbol_map.read().await;
+ map.get(&instrument_token)
+ .cloned()
+ .unwrap_or_else(|| (instrument_token.to_string(), "NSE".to_string()))
+ };
+
+ let mut tick = TickerData {
+ provider: "zerodha".to_string(),
+ symbol: format!("{}:{}", exchange, symbol),
+ price: last_price,
+ bid: None,
+ ask: None,
+ bid_size: None,
+ ask_size: None,
+ volume: None,
+ high: None,
+ low: None,
+ open: None,
+ close: None,
+ change: None,
+ change_percent: None,
+ timestamp: Self::now(),
+ };
+
+ // Parse Quote mode fields (44 bytes)
+ if packet.len() >= PACKET_SIZE_QUOTE {
+ // Fields: token(4), ltp(4), qty(4), avg(4), vol(4), buy_qty(4), sell_qty(4), open(4), high(4), low(4), close(4)
+ let last_qty = i32::from_be_bytes([packet[8], packet[9], packet[10], packet[11]]);
+ let avg_price = i32::from_be_bytes([packet[12], packet[13], packet[14], packet[15]]) as f64 / 100.0;
+ let volume = i32::from_be_bytes([packet[16], packet[17], packet[18], packet[19]]) as u64;
+ let buy_qty = i32::from_be_bytes([packet[20], packet[21], packet[22], packet[23]]);
+ let sell_qty = i32::from_be_bytes([packet[24], packet[25], packet[26], packet[27]]);
+ let open = i32::from_be_bytes([packet[28], packet[29], packet[30], packet[31]]) as f64 / 100.0;
+ let high = i32::from_be_bytes([packet[32], packet[33], packet[34], packet[35]]) as f64 / 100.0;
+ let low = i32::from_be_bytes([packet[36], packet[37], packet[38], packet[39]]) as f64 / 100.0;
+ let close = i32::from_be_bytes([packet[40], packet[41], packet[42], packet[43]]) as f64 / 100.0;
+
+ tick.volume = Some(volume as f64);
+ tick.open = Some(open);
+ tick.high = Some(high);
+ tick.low = Some(low);
+ tick.close = Some(close);
+ tick.bid_size = Some(buy_qty as f64);
+ tick.ask_size = Some(sell_qty as f64);
+
+ // Calculate change
+ if close > 0.0 {
+ tick.change = Some(last_price - close);
+ tick.change_percent = Some(((last_price - close) / close) * 100.0);
+ }
+ }
+
+ // Parse Full mode fields (184+ bytes) - includes depth
+ if packet.len() >= PACKET_SIZE_FULL {
+ // Additional fields at offset 44+
+ // last_trade_time(4), oi(4), oi_day_high(4), oi_day_low(4), exchange_timestamp(4)
+ // Then market depth: 5 buy + 5 sell levels (each: qty(4), price(4), orders(2))
+
+ // For now, we'll just note that depth is available
+ // Full depth parsing can be added if needed
+ }
+
+ Some(tick)
+ }
+
+ /// Get connection statistics
+ pub fn get_statistics(&self) -> (u64, u64, usize) {
+ let msg_count = self.message_count.load(Ordering::Relaxed);
+ let tick_count = self.tick_count.load(Ordering::Relaxed);
+ let sub_count = self.subscribed_tokens.try_read()
+ .map(|t| t.len())
+ .unwrap_or(0);
+ (msg_count, tick_count, sub_count)
+ }
+}
+
+#[async_trait]
+impl WebSocketAdapter for ZerodhaAdapter {
+ async fn connect(&mut self) -> anyhow::Result<()> {
+ if self.connected.load(Ordering::SeqCst) {
+ return Ok(());
+ }
+
+ let url = self.build_ws_url();
+ eprintln!("[Zerodha] Connecting to WebSocket...");
+
+ // Connect with timeout
+ let (ws_stream, _response) = tokio::time::timeout(
+ Duration::from_secs(10),
+ connect_async(&url),
+ )
+ .await
+ .map_err(|_| anyhow::anyhow!("Connection timeout"))?
+ .map_err(|e| anyhow::anyhow!("Connection failed: {}", e))?;
+
+ eprintln!("[Zerodha] WebSocket connected successfully");
+
+ let ws = Arc::new(RwLock::new(ws_stream));
+ self.ws = Some(ws.clone());
+ self.connected.store(true, Ordering::SeqCst);
+ *self.last_message_time.write().await = Self::now();
+
+ // Emit connected status
+ if let Some(ref callback) = self.message_callback {
+ callback(MarketMessage::Status(StatusData {
+ provider: "zerodha".to_string(),
+ status: ConnectionStatus::Connected,
+ message: Some("Connected to Zerodha KiteTicker".to_string()),
+ timestamp: Self::now(),
+ }));
+ }
+
+ // Start receive loop
+ if let Some(callback) = &self.message_callback {
+ let callback = callback.clone();
+ let error_callback = self.error_callback.clone();
+ let connected = self.connected.clone();
+ let last_message_time = self.last_message_time.clone();
+ let token_symbol_map = self.token_symbol_map.clone();
+ let message_count = self.message_count.clone();
+ let tick_count = self.tick_count.clone();
+
+ tokio::spawn(async move {
+ Self::receive_loop(
+ ws,
+ callback,
+ error_callback,
+ connected,
+ last_message_time,
+ token_symbol_map,
+ message_count,
+ tick_count,
+ )
+ .await;
+ });
+ }
+
+ Ok(())
+ }
+
+ async fn disconnect(&mut self) -> anyhow::Result<()> {
+ self.connected.store(false, Ordering::SeqCst);
+
+ if let Some(ws) = self.ws.take() {
+ let mut ws_lock = ws.write().await;
+ let _ = ws_lock.close(None).await;
+ }
+
+ // Emit disconnected status
+ if let Some(ref callback) = self.message_callback {
+ callback(MarketMessage::Status(StatusData {
+ provider: "zerodha".to_string(),
+ status: ConnectionStatus::Disconnected,
+ message: Some("Disconnected from Zerodha".to_string()),
+ timestamp: Self::now(),
+ }));
+ }
+
+ eprintln!("[Zerodha] WebSocket disconnected");
+ Ok(())
+ }
+
+ async fn subscribe(
+ &mut self,
+ symbol: &str,
+ channel: &str,
+ params: Option<Value>,
+ ) -> anyhow::Result<()> {
+ // Extract token from params
+ let token = params
+ .as_ref()
+ .and_then(|p| p.get("token"))
+ .and_then(|t| t.as_i64())
+ .ok_or_else(|| anyhow::anyhow!("Token required in params"))?;
+
+ // Map channel to Zerodha mode
+ let mode = match channel {
+ "ticker" | "ltp" => MODE_LTP,
+ "quote" => MODE_QUOTE,
+ "book" | "depth" | "full" => MODE_FULL,
+ _ => MODE_QUOTE,
+ };
+
+ // Extract exchange from params or default
+ let exchange = params
+ .as_ref()
+ .and_then(|p| p.get("exchange"))
+ .and_then(|e| e.as_str())
+ .unwrap_or("NSE")
+ .to_string();
+
+ // Store symbol mapping
+ self.set_token_symbol_map(token, symbol.to_string(), exchange);
+
+ // Subscribe
+ self.subscribe_tokens(vec![token], mode).await?;
+
+ Ok(())
+ }
+
+ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {
+ // Find token for symbol
+ let token = {
+ let map = self.token_symbol_map.read().await;
+ map.iter()
+ .find(|(_, (s, _))| s == symbol)
+ .map(|(t, _)| *t)
+ };
+
+ if let Some(token) = token {
+ self.unsubscribe_tokens(vec![token]).await?;
+
+ // Remove from symbol map
+ let mut map = self.token_symbol_map.write().await;
+ map.remove(&token);
+ }
+
+ Ok(())
+ }
+
+ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {
+ self.message_callback = Some(Arc::new(callback));
+ }
+
+ fn provider_name(&self) -> &str {
+ "zerodha"
+ }
+
+ fn is_connected(&self) -> bool {
+ self.connected.load(Ordering::SeqCst)
+ }
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs b/fincept-terminal-desktop/src-tauri/src/worker_pool.rs
index 61aa8f33f..ffb850a55 100644
--- a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs
+++ b/fincept-terminal-desktop/src-tauri/src/worker_pool.rs
@@ -105,7 +105,6 @@ impl WorkerPool {
// Try each candidate path
for path in candidate_paths.iter() {
- eprintln!("[WorkerPool] Checking: {:?}", path);
if path.exists() {
// Strip the \\?\ prefix that can cause issues on Windows
let path_str = path.to_string_lossy().to_string();
@@ -114,30 +113,22 @@ impl WorkerPool {
} else {
path.clone()
};
- eprintln!("[WorkerPool] Found worker script at: {:?}", clean_path);
return Ok(clean_path);
}
}
- Err(format!(
- "Worker script 'worker.py' not found in any of {} candidate locations",
- candidate_paths.len()
- ))
+ Err("Worker script 'worker.py' not found".to_string())
}
/// Initialize the worker pool
pub async fn new(python_base_path: PathBuf) -> Result<Self, String> {
- eprintln!("[WorkerPool] Initializing with {} workers, {} threads each", NUM_WORKERS, NUM_THREADS);
-
// Create socket name base
let socket_name = format!("fincept-worker-{}", std::process::id());
- eprintln!("[WorkerPool] Socket name base: {}", socket_name);
// Start multiple worker processes
let mut workers_vec = Vec::new();
for i in 0..NUM_WORKERS {
let worker_socket = format!("{}-{}", socket_name, i);
- eprintln!("[WorkerPool] Starting worker {} with {} threads", i, NUM_THREADS);
// Use venv-numpy2 as default (has most modern libraries)
let worker = Self::spawn_worker(i, &python_base_path, "venv-numpy2", &worker_socket).await?;
@@ -151,8 +142,6 @@ impl WorkerPool {
let response_senders = Arc::new(Mutex::new(std::collections::HashMap::new()));
let sequence_counter = Arc::new(AtomicU64::new(0));
- eprintln!("[WorkerPool] All {} workers started successfully", NUM_WORKERS);
-
// Spawn queue processor task
let workers_clone = workers.clone();
let response_senders_clone = response_senders.clone();
@@ -192,9 +181,6 @@ impl WorkerPool {
return Err(format!("Worker script not found at: {:?}", worker_script));
}
- eprintln!("[Worker {}] Python: {:?}", worker_id, python_exe);
- eprintln!("[Worker {}] Script: {:?}", worker_id, worker_script);
- eprintln!("[Worker {}] Socket: {}", worker_id, socket_name);
// Spawn Python process
let mut cmd = Command::new(&python_exe);
@@ -212,8 +198,6 @@ impl WorkerPool {
let process = cmd.spawn()
.map_err(|e| format!("Failed to spawn worker {}: {}", worker_id, e))?;
- eprintln!("[Worker {}] Process spawned, PID: {:?}", worker_id, process.id());
-
// Wait for worker to start listening with retry logic
// Python worker creates server socket, so we need to wait for it
let mut socket: Option<LocalSocketStream> = None;
@@ -228,7 +212,6 @@ impl WorkerPool {
) {
Ok(s) => {
socket = Some(s);
- eprintln!("[Worker {}] Connected to socket after {} attempts", worker_id, attempt + 1);
break;
}
Err(e) => {
@@ -257,8 +240,6 @@ impl WorkerPool {
let mut priority_queue: BinaryHeap<PrioritizedTask> = BinaryHeap::new();
let mut worker_index = 0; // Round-robin worker selection
- eprintln!("[WorkerPool] Queue processor started with {} workers", NUM_WORKERS);
-
// Spawn response reader tasks for each worker
for i in 0..NUM_WORKERS {
let workers_clone = workers.clone();
@@ -283,8 +264,6 @@ impl WorkerPool {
if worker.socket.read_exact(&mut response_buf).is_ok() {
if let Ok(response) = rmp_serde::from_slice::<WorkerResponse>(&response_buf) {
- eprintln!("[WorkerPool] Worker {} completed task {}: {}", i, response.task_id, response.status);
-
// Send response back to caller
let mut senders = response_senders_clone.lock().await;
if let Some(sender) = senders.remove(&response.task_id) {
@@ -310,8 +289,6 @@ impl WorkerPool {
if let Some(prioritized_task) = priority_queue.pop() {
let task = prioritized_task.task;
- eprintln!("[WorkerPool] Dispatching task {} (priority {}) to worker {}", task.task_id, task.priority, worker_index);
-
// Send task to next worker (round-robin)
let mut workers_lock = workers.lock().await;
if worker_index < workers_lock.len() {
@@ -324,12 +301,8 @@ impl WorkerPool {
if worker.socket.write_all(&len_bytes).is_ok()
&& worker.socket.write_all(&task_bytes).is_ok()
&& worker.socket.flush().is_ok() {
- eprintln!("[WorkerPool] Task {} sent to worker {}", task.task_id, worker_index);
-
// Round-robin to next worker
worker_index = (worker_index + 1) % NUM_WORKERS;
- } else {
- eprintln!("[WorkerPool] Failed to send task {} to worker {}", task.task_id, worker_index);
}
}
}
@@ -344,8 +317,6 @@ impl WorkerPool {
pub async fn execute_task(&self, task: WorkerTask) -> Result<WorkerResponse, String> {
let task_id = task.task_id.clone();
- eprintln!("[WorkerPool] Queuing task {} with priority {}", task_id, task.priority);
-
// Create response channel
let (response_tx, response_rx) = tokio::sync::oneshot::channel();
@@ -373,22 +344,11 @@ impl WorkerPool {
/// Shutdown all workers
pub async fn shutdown(&self) {
- eprintln!("[WorkerPool] Shutting down all workers");
-
let mut workers = self.workers.lock().await;
- for (i, worker) in workers.iter_mut().enumerate() {
- eprintln!("[WorkerPool] Killing worker {}", i);
+ for (_i, worker) in workers.iter_mut().enumerate() {
let _ = worker.process.kill();
}
-
- eprintln!("[WorkerPool] Shutdown complete");
- }
-}
-
-impl Drop for WorkerPool {
- fn drop(&mut self) {
- eprintln!("[WorkerPool] Dropping worker pool");
}
}
@@ -398,13 +358,10 @@ static WORKER_POOL: OnceCell<Arc<Mutex<Option<WorkerPool>>>> = OnceCell::new();
/// Initialize the global worker pool
pub async fn initialize_worker_pool(python_base_path: PathBuf) -> Result<(), String> {
- eprintln!("[WorkerPool] Initializing global worker pool");
-
let pool = WorkerPool::new(python_base_path).await?;
WORKER_POOL.get_or_init(|| Arc::new(Mutex::new(Some(pool))));
- eprintln!("[WorkerPool] Global worker pool initialized");
Ok(())
}
diff --git a/fincept-terminal-desktop/src/App.tsx b/fincept-terminal-desktop/src/App.tsx
index e990ee0c9..37a845aa2 100644
--- a/fincept-terminal-desktop/src/App.tsx
+++ b/fincept-terminal-desktop/src/App.tsx
@@ -8,6 +8,8 @@ import { ThemeProvider } from './contexts/ThemeContext';
import { DataSourceProvider } from './contexts/DataSourceContext';
import { ProviderProvider } from './contexts/ProviderContext';
import { workflowService } from './services/core/workflowService';
+import { initializeNodeSystem } from './services/nodeSystem';
+import { initializeStockBrokers } from './brokers/stocks';
// Import screens
import LoginScreen from './components/auth/LoginScreen';
@@ -51,7 +53,7 @@ const App: React.FC = () => {
const [setupComplete, setSetupComplete] = useState(false);
const [checkingSetup, setCheckingSetup] = useState(true);
- // Check setup status on app initialization
+ // Check setup status on app initialization and initialize node system
useEffect(() => {
const checkSetup = async () => {
try {
@@ -67,6 +69,18 @@ const App: React.FC = () => {
}
};
+ // Initialize node system (loads all nodes into registry)
+ initializeNodeSystem().catch((err) => {
+ console.error('Failed to initialize node system:', err);
+ });
+
+ // Initialize stock broker adapters
+ try {
+ initializeStockBrokers();
+ } catch (err) {
+ console.error('Failed to initialize stock brokers:', err);
+ }
+
checkSetup();
}, []);
diff --git a/fincept-terminal-desktop/src/brokers/india/BaseIndianBrokerAdapter.ts b/fincept-terminal-desktop/src/brokers/india/BaseIndianBrokerAdapter.ts
new file mode 100644
index 000000000..baa53336f
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/BaseIndianBrokerAdapter.ts
@@ -0,0 +1,759 @@
+/**
+ * Base adapter class for Indian stock brokers
+ * Provides common functionality and abstract methods for broker implementations
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+import type {
+ IIndianBrokerAdapter,
+ IndianBrokerMetadata,
+ BrokerCredentials,
+ AuthResponse,
+ AuthCallbackParams,
+ FundsData,
+ MarginRequired,
+ OrderParams,
+ OrderResponse,
+ ModifyOrderParams,
+ Order,
+ Position,
+ Holding,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ TimeFrame,
+ IndianExchange,
+ SymbolSearchResult,
+ SymbolToken,
+ WebSocketConfig,
+ SubscriptionMode,
+ TickData,
+ ApiResponse,
+ Trade,
+ SmartOrderParams,
+ OpenPositionResult,
+ BulkOperationResult,
+ MarginOrderParams,
+ MarginCalculation,
+ ProductType,
+} from './types';
+import { ERROR_CODES, ERROR_MESSAGES } from './constants';
+
+/**
+ * Abstract base class for Indian broker adapters
+ * Implements common functionality and defines abstract methods for broker-specific logic
+ */
+export abstract class BaseIndianBrokerAdapter implements IIndianBrokerAdapter {
+ // ============================================================================
+ // Abstract Properties (must be implemented by subclass)
+ // ============================================================================
+
+ abstract readonly brokerId: string;
+ abstract readonly brokerName: string;
+ abstract readonly metadata: IndianBrokerMetadata;
+
+ // ============================================================================
+ // Protected Properties
+ // ============================================================================
+
+ protected _isConnected: boolean = false;
+ protected credentials: BrokerCredentials | null = null;
+ protected accessToken: string | null = null;
+ protected userId: string | null = null;
+
+ // WebSocket state
+ protected wsConnected: boolean = false;
+ protected wsConfig: WebSocketConfig | null = null;
+ protected subscriptions: Map<string, { symbol: string; exchange: IndianExchange; mode: SubscriptionMode }> = new Map();
+
+ // Rate limiting
+ protected lastApiCall: number = 0;
+ protected apiCallQueue: Array<() => Promise<unknown>> = [];
+
+ // ============================================================================
+ // Public Getters
+ // ============================================================================
+
+ get isConnected(): boolean {
+ return this._isConnected && this.accessToken !== null;
+ }
+
+ // ============================================================================
+ // Abstract Methods (must be implemented by subclass)
+ // ============================================================================
+
+ /**
+ * Get the authentication URL for OAuth flow
+ */
+ abstract getAuthUrl(): string;
+
+ /**
+ * Process the authentication callback and exchange tokens
+ */
+ abstract handleAuthCallback(params: AuthCallbackParams): Promise<AuthResponse>;
+
+ /**
+ * Broker-specific order placement
+ */
+ protected abstract placeOrderInternal(params: OrderParams): Promise<OrderResponse>;
+
+ /**
+ * Broker-specific order modification
+ */
+ protected abstract modifyOrderInternal(params: ModifyOrderParams): Promise<OrderResponse>;
+
+ /**
+ * Broker-specific order cancellation
+ */
+ protected abstract cancelOrderInternal(orderId: string): Promise<OrderResponse>;
+
+ /**
+ * Broker-specific order fetch
+ */
+ protected abstract getOrdersInternal(): Promise<Order[]>;
+
+ /**
+ * Broker-specific position fetch
+ */
+ protected abstract getPositionsInternal(): Promise<Position[]>;
+
+ /**
+ * Broker-specific holdings fetch
+ */
+ protected abstract getHoldingsInternal(): Promise<Holding[]>;
+
+ /**
+ * Broker-specific funds fetch
+ */
+ protected abstract getFundsInternal(): Promise<FundsData>;
+
+ /**
+ * Broker-specific quote fetch
+ */
+ protected abstract getQuoteInternal(symbol: string, exchange: IndianExchange): Promise<Quote>;
+
+ /**
+ * Broker-specific OHLCV fetch
+ */
+ protected abstract getOHLCVInternal(
+ symbol: string,
+ exchange: IndianExchange,
+ timeframe: TimeFrame,
+ from: Date,
+ to: Date
+ ): Promise<OHLCV[]>;
+
+ /**
+ * Broker-specific market depth fetch
+ */
+ protected abstract getMarketDepthInternal(
+ symbol: string,
+ exchange: IndianExchange
+ ): Promise<MarketDepth>;
+
+ /**
+ * Broker-specific WebSocket connection
+ */
+ protected abstract connectWebSocketInternal(config: WebSocketConfig): Promise<void>;
+
+ /**
+ * Broker-specific WebSocket subscription
+ */
+ protected abstract subscribeInternal(
+ symbol: string,
+ exchange: IndianExchange,
+ mode: SubscriptionMode
+ ): Promise<void>;
+
+ /**
+ * Broker-specific WebSocket unsubscription
+ */
+ protected abstract unsubscribeInternal(
+ symbol: string,
+ exchange: IndianExchange
+ ): Promise<void>;
+
+ /**
+ * Broker-specific master contract download
+ */
+ protected abstract downloadMasterContractInternal(): Promise<void>;
+
+ // ============================================================================
+ // Abstract Methods for New Features (Trade Book, Smart Orders, Bulk Operations)
+ // Subclasses must implement these methods
+ // ============================================================================
+
+ /**
+ * Get trade book (executed trades)
+ */
+ abstract getTradeBook(): Promise<Trade[]>;
+
+ /**
+ * Get open position for a specific symbol
+ */
+ abstract getOpenPosition(
+ symbol: string,
+ exchange: IndianExchange,
+ product: ProductType
+ ): Promise<OpenPositionResult>;
+
+ /**
+ * Place smart order (checks position and adjusts)
+ */
+ abstract placeSmartOrder(params: SmartOrderParams): Promise<OrderResponse>;
+
+ /**
+ * Close all open positions
+ */
+ abstract closeAllPositions(): Promise<BulkOperationResult>;
+
+ /**
+ * Cancel all open orders
+ */
+ abstract cancelAllOrders(): Promise<BulkOperationResult>;
+
+ /**
+ * Calculate margin for orders
+ */
+ abstract calculateMargin(orders: MarginOrderParams[]): Promise<MarginCalculation>;
+
+ // ============================================================================
+ // Common Authentication Methods
+ // ============================================================================
+
+ async authenticate(credentials: BrokerCredentials): Promise<AuthResponse> {
+ try {
+ this.credentials = credentials;
+
+ // If access token is already provided, validate it
+ if (credentials.accessToken) {
+ const isValid = await this.validateToken(credentials.accessToken);
+ if (isValid) {
+ this.accessToken = credentials.accessToken;
+ this.userId = credentials.userId || null;
+ this._isConnected = true;
+
+ // Store credentials in SQLite
+ await this.storeCredentials(credentials);
+
+ return {
+ success: true,
+ accessToken: credentials.accessToken,
+ userId: this.userId || undefined,
+ message: 'Authentication successful',
+ };
+ }
+ }
+
+ // If no access token, return auth URL for OAuth flow
+ return {
+ success: false,
+ message: 'Please complete authentication via browser',
+ errorCode: ERROR_CODES.AUTH_TOKEN_EXPIRED,
+ };
+ } catch (error) {
+ return this.handleAuthError(error);
+ }
+ }
+
+ async logout(): Promise<void> {
+ try {
+ // Disconnect WebSocket if connected
+ if (this.wsConnected) {
+ await this.disconnectWebSocket();
+ }
+
+ // Clear credentials from storage
+ await this.clearCredentials();
+
+ // Reset state
+ this._isConnected = false;
+ this.accessToken = null;
+ this.userId = null;
+ this.credentials = null;
+ } catch (error) {
+ console.error(`[${this.brokerId}] Logout error:`, error);
+ throw error;
+ }
+ }
+
+ async refreshSession(): Promise<AuthResponse> {
+ try {
+ if (!this.credentials?.refreshToken) {
+ return {
+ success: false,
+ message: 'No refresh token available',
+ errorCode: ERROR_CODES.AUTH_SESSION_EXPIRED,
+ };
+ }
+
+ // This should be overridden by brokers that support refresh tokens
+ return {
+ success: false,
+ message: 'Session refresh not supported. Please login again.',
+ errorCode: ERROR_CODES.AUTH_SESSION_EXPIRED,
+ };
+ } catch (error) {
+ return this.handleAuthError(error);
+ }
+ }
+
+ /**
+ * Validate if a token is still valid
+ */
+ protected async validateToken(token: string): Promise<boolean> {
+ try {
+ // Try to fetch user profile or funds as a validation check
+ // This should be overridden by subclasses with broker-specific validation
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ // ============================================================================
+ // Order Methods (with common wrapper logic)
+ // ============================================================================
+
+ async placeOrder(params: OrderParams): Promise<OrderResponse> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ try {
+ return await this.placeOrderInternal(params);
+ } catch (error) {
+ return this.handleOrderError(error);
+ }
+ }
+
+ async modifyOrder(params: ModifyOrderParams): Promise<OrderResponse> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ try {
+ return await this.modifyOrderInternal(params);
+ } catch (error) {
+ return this.handleOrderError(error);
+ }
+ }
+
+ async cancelOrder(orderId: string): Promise<OrderResponse> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ try {
+ return await this.cancelOrderInternal(orderId);
+ } catch (error) {
+ return this.handleOrderError(error);
+ }
+ }
+
+ async getOrders(): Promise<Order[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ return this.getOrdersInternal();
+ }
+
+ async getOrderHistory(orderId: string): Promise<Order[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ // Default implementation returns the order
+ const orders = await this.getOrders();
+ return orders.filter((o) => o.orderId === orderId);
+ }
+
+ // ============================================================================
+ // Position & Holdings Methods
+ // ============================================================================
+
+ async getPositions(): Promise<Position[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ return this.getPositionsInternal();
+ }
+
+ async getHoldings(): Promise<Holding[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ return this.getHoldingsInternal();
+ }
+
+ async getFunds(): Promise<FundsData> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ return this.getFundsInternal();
+ }
+
+ async getMarginRequired(params: OrderParams): Promise<MarginRequired> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ // Default implementation - should be overridden by brokers that support margin calculator
+ return {
+ total: 0,
+ var: 0,
+ span: 0,
+ exposure: 0,
+ premium: 0,
+ };
+ }
+
+ // ============================================================================
+ // Market Data Methods
+ // ============================================================================
+
+ async getQuote(symbol: string, exchange: IndianExchange): Promise<Quote> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ return this.getQuoteInternal(symbol, exchange);
+ }
+
+ async getQuotes(
+ symbols: Array<{ symbol: string; exchange: IndianExchange }>
+ ): Promise<Quote[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ // Default implementation - fetch one by one
+ // Subclasses should override for batch API support
+ const quotes: Quote[] = [];
+ for (const { symbol, exchange } of symbols) {
+ try {
+ const quote = await this.getQuoteInternal(symbol, exchange);
+ quotes.push(quote);
+ } catch (error) {
+ console.error(`[${this.brokerId}] Error fetching quote for ${symbol}:`, error);
+ }
+ }
+ return quotes;
+ }
+
+ async getOHLCV(
+ symbol: string,
+ exchange: IndianExchange,
+ timeframe: TimeFrame,
+ from: Date,
+ to: Date
+ ): Promise<OHLCV[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ return this.getOHLCVInternal(symbol, exchange, timeframe, from, to);
+ }
+
+ async getMarketDepth(symbol: string, exchange: IndianExchange): Promise<MarketDepth> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ return this.getMarketDepthInternal(symbol, exchange);
+ }
+
+ // ============================================================================
+ // Symbol Management Methods
+ // ============================================================================
+
+ async searchSymbols(
+ query: string,
+ exchange?: IndianExchange
+ ): Promise<SymbolSearchResult[]> {
+ try {
+ const results = await invoke<SymbolSearchResult[]>('search_indian_symbols', {
+ brokerId: this.brokerId,
+ query,
+ exchange,
+ });
+ return results;
+ } catch (error) {
+ console.error(`[${this.brokerId}] Symbol search error:`, error);
+ return [];
+ }
+ }
+
+ async getSymbolToken(
+ symbol: string,
+ exchange: IndianExchange
+ ): Promise<SymbolToken | null> {
+ try {
+ const result = await invoke<SymbolToken | null>('get_indian_symbol_token', {
+ brokerId: this.brokerId,
+ symbol,
+ exchange,
+ });
+ return result;
+ } catch (error) {
+ console.error(`[${this.brokerId}] Get symbol token error:`, error);
+ return null;
+ }
+ }
+
+ // ============================================================================
+ // WebSocket Methods
+ // ============================================================================
+
+ async connectWebSocket(config: WebSocketConfig): Promise<void> {
+ if (this.wsConnected) {
+ console.warn(`[${this.brokerId}] WebSocket already connected`);
+ return;
+ }
+
+ this.wsConfig = config;
+ await this.connectWebSocketInternal(config);
+ this.wsConnected = true;
+ }
+
+ async disconnectWebSocket(): Promise<void> {
+ if (!this.wsConnected) {
+ return;
+ }
+
+ try {
+ // Unsubscribe from all symbols
+ for (const [key, sub] of this.subscriptions) {
+ await this.unsubscribeInternal(sub.symbol, sub.exchange);
+ }
+ this.subscriptions.clear();
+
+ // Close WebSocket connection
+ await invoke('disconnect_indian_broker_websocket', {
+ brokerId: this.brokerId,
+ });
+
+ this.wsConnected = false;
+ this.wsConfig = null;
+ } catch (error) {
+ console.error(`[${this.brokerId}] WebSocket disconnect error:`, error);
+ throw error;
+ }
+ }
+
+ async subscribe(
+ symbol: string,
+ exchange: IndianExchange,
+ mode: SubscriptionMode
+ ): Promise<void> {
+ if (!this.wsConnected) {
+ throw new Error('WebSocket not connected');
+ }
+
+ const key = `${exchange}:${symbol}`;
+ if (this.subscriptions.has(key)) {
+ // Update mode if different
+ const existing = this.subscriptions.get(key)!;
+ if (existing.mode !== mode) {
+ await this.unsubscribeInternal(symbol, exchange);
+ await this.subscribeInternal(symbol, exchange, mode);
+ this.subscriptions.set(key, { symbol, exchange, mode });
+ }
+ return;
+ }
+
+ await this.subscribeInternal(symbol, exchange, mode);
+ this.subscriptions.set(key, { symbol, exchange, mode });
+ }
+
+ async unsubscribe(symbol: string, exchange: IndianExchange): Promise<void> {
+ const key = `${exchange}:${symbol}`;
+ if (!this.subscriptions.has(key)) {
+ return;
+ }
+
+ await this.unsubscribeInternal(symbol, exchange);
+ this.subscriptions.delete(key);
+ }
+
+ // ============================================================================
+ // Master Contract Methods
+ // ============================================================================
+
+ async downloadMasterContract(): Promise<void> {
+ this.ensureConnected();
+
+ await this.downloadMasterContractInternal();
+ }
+
+ async getMasterContractLastUpdated(): Promise<Date | null> {
+ try {
+ const timestamp = await invoke<number | null>('get_master_contract_timestamp', {
+ brokerId: this.brokerId,
+ });
+ return timestamp ? new Date(timestamp) : null;
+ } catch {
+ return null;
+ }
+ }
+
+ // ============================================================================
+ // Protected Helper Methods
+ // ============================================================================
+
+ /**
+ * Ensure adapter is connected before making API calls
+ */
+ protected ensureConnected(): void {
+ if (!this.isConnected) {
+ throw new Error(ERROR_MESSAGES[ERROR_CODES.AUTH_SESSION_EXPIRED]);
+ }
+ }
+
+ /**
+ * Simple rate limiting
+ */
+ protected async rateLimit(): Promise<void> {
+ const now = Date.now();
+ const minInterval = 100; // 100ms between calls
+
+ if (now - this.lastApiCall < minInterval) {
+ await new Promise((resolve) => setTimeout(resolve, minInterval - (now - this.lastApiCall)));
+ }
+
+ this.lastApiCall = Date.now();
+ }
+
+ /**
+ * Make HTTP request through Tauri backend
+ */
+ protected async makeRequest<T>(
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE',
+ endpoint: string,
+ data?: Record<string, unknown>,
+ headers?: Record<string, string>
+ ): Promise<ApiResponse<T>> {
+ try {
+ const response = await invoke<ApiResponse<T>>('indian_broker_request', {
+ brokerId: this.brokerId,
+ method,
+ endpoint,
+ data,
+ headers: {
+ ...headers,
+ Authorization: this.accessToken ? `token ${this.accessToken}` : undefined,
+ },
+ });
+ return response;
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Request failed',
+ timestamp: Date.now(),
+ };
+ }
+ }
+
+ /**
+ * Store credentials in SQLite database
+ */
+ protected async storeCredentials(credentials: BrokerCredentials): Promise<void> {
+ try {
+ await invoke('store_indian_broker_credentials', {
+ brokerId: this.brokerId,
+ credentials: {
+ ...credentials,
+ // Don't store password
+ password: undefined,
+ },
+ });
+ } catch (error) {
+ console.error(`[${this.brokerId}] Failed to store credentials:`, error);
+ }
+ }
+
+ /**
+ * Load credentials from SQLite database
+ */
+ protected async loadCredentials(): Promise<BrokerCredentials | null> {
+ try {
+ const credentials = await invoke<BrokerCredentials | null>(
+ 'get_indian_broker_credentials',
+ {
+ brokerId: this.brokerId,
+ }
+ );
+ return credentials;
+ } catch {
+ return null;
+ }
+ }
+
+ /**
+ * Clear stored credentials
+ */
+ protected async clearCredentials(): Promise<void> {
+ try {
+ await invoke('delete_indian_broker_credentials', {
+ brokerId: this.brokerId,
+ });
+ } catch (error) {
+ console.error(`[${this.brokerId}] Failed to clear credentials:`, error);
+ }
+ }
+
+ /**
+ * Handle authentication errors
+ */
+ protected handleAuthError(error: unknown): AuthResponse {
+ const message = error instanceof Error ? error.message : 'Authentication failed';
+ console.error(`[${this.brokerId}] Auth error:`, message);
+
+ return {
+ success: false,
+ message,
+ errorCode: ERROR_CODES.AUTH_INVALID_CREDENTIALS,
+ };
+ }
+
+ /**
+ * Handle order errors
+ */
+ protected handleOrderError(error: unknown): OrderResponse {
+ const message = error instanceof Error ? error.message : 'Order operation failed';
+ console.error(`[${this.brokerId}] Order error:`, message);
+
+ return {
+ success: false,
+ message,
+ errorCode: ERROR_CODES.UNKNOWN_ERROR,
+ };
+ }
+
+ /**
+ * Emit tick data to registered callback
+ */
+ protected emitTick(tick: TickData): void {
+ if (this.wsConfig?.onTick) {
+ this.wsConfig.onTick(tick);
+ }
+ }
+
+ /**
+ * Emit connection event
+ */
+ protected emitConnect(): void {
+ if (this.wsConfig?.onConnect) {
+ this.wsConfig.onConnect();
+ }
+ }
+
+ /**
+ * Emit disconnection event
+ */
+ protected emitDisconnect(): void {
+ if (this.wsConfig?.onDisconnect) {
+ this.wsConfig.onDisconnect();
+ }
+ }
+
+ /**
+ * Emit error event
+ */
+ protected emitError(error: Error): void {
+ if (this.wsConfig?.onError) {
+ this.wsConfig.onError(error);
+ }
+ }
+}
diff --git a/fincept-terminal-desktop/src/brokers/india/constants.ts b/fincept-terminal-desktop/src/brokers/india/constants.ts
new file mode 100644
index 000000000..dea3bcc08
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/constants.ts
@@ -0,0 +1,259 @@
+/**
+ * Constants for Indian stock broker integrations
+ */
+
+import type { IndianExchange, ProductType, OrderType, TimeFrame } from './types';
+
+// ============================================================================
+// Market Timing
+// ============================================================================
+
+export const MARKET_TIMING = {
+ NSE: {
+ preOpen: { start: '09:00', end: '09:08' },
+ normal: { start: '09:15', end: '15:30' },
+ postClose: { start: '15:40', end: '16:00' },
+ timezone: 'Asia/Kolkata',
+ },
+ BSE: {
+ preOpen: { start: '09:00', end: '09:08' },
+ normal: { start: '09:15', end: '15:30' },
+ postClose: { start: '15:40', end: '16:00' },
+ timezone: 'Asia/Kolkata',
+ },
+ MCX: {
+ morning: { start: '09:00', end: '17:00' },
+ evening: { start: '17:00', end: '23:30' },
+ timezone: 'Asia/Kolkata',
+ },
+ CDS: {
+ normal: { start: '09:00', end: '17:00' },
+ timezone: 'Asia/Kolkata',
+ },
+} as const;
+
+// ============================================================================
+// Exchange Mappings
+// ============================================================================
+
+export const EXCHANGE_DISPLAY_NAMES: Record<IndianExchange, string> = {
+ NSE: 'NSE',
+ BSE: 'BSE',
+ NFO: 'NSE F&O',
+ BFO: 'BSE F&O',
+ CDS: 'Currency',
+ BCD: 'BSE Currency',
+ MCX: 'MCX',
+ NSE_INDEX: 'NSE Index',
+ BSE_INDEX: 'BSE Index',
+ MCX_INDEX: 'MCX Index',
+ CDS_INDEX: 'Currency Index',
+};
+
+export const EQUITY_EXCHANGES: IndianExchange[] = ['NSE', 'BSE'];
+export const DERIVATIVE_EXCHANGES: IndianExchange[] = ['NFO', 'BFO', 'MCX', 'CDS', 'BCD'];
+export const INDEX_EXCHANGES: IndianExchange[] = ['NSE_INDEX', 'BSE_INDEX', 'MCX_INDEX', 'CDS_INDEX'];
+
+// ============================================================================
+// Product Type Mappings
+// ============================================================================
+
+export const PRODUCT_DISPLAY_NAMES: Record<ProductType, string> = {
+ CNC: 'Delivery',
+ MIS: 'Intraday',
+ NRML: 'Carry Forward',
+ CO: 'Cover Order',
+ BO: 'Bracket Order',
+};
+
+export const PRODUCT_DESCRIPTIONS: Record<ProductType, string> = {
+ CNC: 'Cash and Carry - Take delivery of shares',
+ MIS: 'Margin Intraday - Auto squared off at 3:20 PM',
+ NRML: 'Normal - Carry forward for F&O positions',
+ CO: 'Cover Order - Compulsory stop loss',
+ BO: 'Bracket Order - Target and stop loss',
+};
+
+// ============================================================================
+// Order Type Mappings
+// ============================================================================
+
+export const ORDER_TYPE_DISPLAY_NAMES: Record<OrderType, string> = {
+ MARKET: 'Market',
+ LIMIT: 'Limit',
+ SL: 'Stop Loss',
+ 'SL-M': 'Stop Loss Market',
+};
+
+// ============================================================================
+// Index Symbols Mapping
+// ============================================================================
+
+export const INDEX_SYMBOL_MAP: Record<string, string> = {
+ 'NIFTY 50': 'NIFTY',
+ 'NIFTY NEXT 50': 'NIFTYNXT50',
+ 'NIFTY FIN SERVICE': 'FINNIFTY',
+ 'NIFTY BANK': 'BANKNIFTY',
+ 'NIFTY MID SELECT': 'MIDCPNIFTY',
+ 'INDIA VIX': 'INDIAVIX',
+ 'SENSEX': 'SENSEX',
+ 'BANKEX': 'BANKEX',
+ 'SNSX50': 'SENSEX50',
+};
+
+export const POPULAR_INDICES = [
+ { symbol: 'NIFTY', name: 'Nifty 50', exchange: 'NSE_INDEX' as IndianExchange },
+ { symbol: 'BANKNIFTY', name: 'Bank Nifty', exchange: 'NSE_INDEX' as IndianExchange },
+ { symbol: 'FINNIFTY', name: 'Fin Nifty', exchange: 'NSE_INDEX' as IndianExchange },
+ { symbol: 'MIDCPNIFTY', name: 'Midcap Nifty', exchange: 'NSE_INDEX' as IndianExchange },
+ { symbol: 'SENSEX', name: 'Sensex', exchange: 'BSE_INDEX' as IndianExchange },
+ { symbol: 'BANKEX', name: 'Bankex', exchange: 'BSE_INDEX' as IndianExchange },
+];
+
+// ============================================================================
+// Timeframe Mappings
+// ============================================================================
+
+export const TIMEFRAME_MINUTES: Record<TimeFrame, number> = {
+ '1m': 1,
+ '3m': 3,
+ '5m': 5,
+ '10m': 10,
+ '15m': 15,
+ '30m': 30,
+ '1h': 60,
+ '2h': 120,
+ '4h': 240,
+ '1d': 1440,
+ '1w': 10080,
+ '1M': 43200,
+};
+
+export const TIMEFRAME_DISPLAY_NAMES: Record<TimeFrame, string> = {
+ '1m': '1 Minute',
+ '3m': '3 Minutes',
+ '5m': '5 Minutes',
+ '10m': '10 Minutes',
+ '15m': '15 Minutes',
+ '30m': '30 Minutes',
+ '1h': '1 Hour',
+ '2h': '2 Hours',
+ '4h': '4 Hours',
+ '1d': 'Daily',
+ '1w': 'Weekly',
+ '1M': 'Monthly',
+};
+
+// ============================================================================
+// Lot Sizes for Popular F&O Stocks
+// ============================================================================
+
+export const DEFAULT_LOT_SIZES: Record<string, number> = {
+ NIFTY: 50,
+ BANKNIFTY: 15,
+ FINNIFTY: 40,
+ MIDCPNIFTY: 75,
+ SENSEX: 10,
+ BANKEX: 15,
+ RELIANCE: 250,
+ TCS: 150,
+ INFY: 300,
+ HDFCBANK: 550,
+ ICICIBANK: 700,
+ SBIN: 750,
+ TATAMOTORS: 575,
+ TATASTEEL: 550,
+};
+
+// ============================================================================
+// Error Codes
+// ============================================================================
+
+export const ERROR_CODES = {
+ // Authentication errors
+ AUTH_INVALID_CREDENTIALS: 'AUTH001',
+ AUTH_TOKEN_EXPIRED: 'AUTH002',
+ AUTH_SESSION_EXPIRED: 'AUTH003',
+ AUTH_TOTP_REQUIRED: 'AUTH004',
+ AUTH_TOTP_INVALID: 'AUTH005',
+
+ // Order errors
+ ORDER_INVALID_SYMBOL: 'ORD001',
+ ORDER_INVALID_QUANTITY: 'ORD002',
+ ORDER_INSUFFICIENT_FUNDS: 'ORD003',
+ ORDER_MARKET_CLOSED: 'ORD004',
+ ORDER_PRICE_OUT_OF_RANGE: 'ORD005',
+ ORDER_MODIFICATION_NOT_ALLOWED: 'ORD006',
+ ORDER_CANCELLATION_NOT_ALLOWED: 'ORD007',
+
+ // Connection errors
+ CONNECTION_FAILED: 'CONN001',
+ CONNECTION_TIMEOUT: 'CONN002',
+ WEBSOCKET_DISCONNECTED: 'CONN003',
+
+ // Rate limit errors
+ RATE_LIMIT_EXCEEDED: 'RATE001',
+
+ // General errors
+ UNKNOWN_ERROR: 'ERR001',
+ INVALID_REQUEST: 'ERR002',
+ SERVER_ERROR: 'ERR003',
+} as const;
+
+export const ERROR_MESSAGES: Record<string, string> = {
+ [ERROR_CODES.AUTH_INVALID_CREDENTIALS]: 'Invalid credentials provided',
+ [ERROR_CODES.AUTH_TOKEN_EXPIRED]: 'Access token has expired. Please login again.',
+ [ERROR_CODES.AUTH_SESSION_EXPIRED]: 'Session has expired. Please login again.',
+ [ERROR_CODES.AUTH_TOTP_REQUIRED]: 'TOTP verification required',
+ [ERROR_CODES.AUTH_TOTP_INVALID]: 'Invalid TOTP code',
+ [ERROR_CODES.ORDER_INVALID_SYMBOL]: 'Invalid symbol or symbol not found',
+ [ERROR_CODES.ORDER_INVALID_QUANTITY]: 'Invalid quantity specified',
+ [ERROR_CODES.ORDER_INSUFFICIENT_FUNDS]: 'Insufficient funds for this order',
+ [ERROR_CODES.ORDER_MARKET_CLOSED]: 'Market is closed',
+ [ERROR_CODES.ORDER_PRICE_OUT_OF_RANGE]: 'Price is outside circuit limits',
+ [ERROR_CODES.ORDER_MODIFICATION_NOT_ALLOWED]: 'Order cannot be modified in current state',
+ [ERROR_CODES.ORDER_CANCELLATION_NOT_ALLOWED]: 'Order cannot be cancelled in current state',
+ [ERROR_CODES.CONNECTION_FAILED]: 'Failed to connect to broker',
+ [ERROR_CODES.CONNECTION_TIMEOUT]: 'Connection timed out',
+ [ERROR_CODES.WEBSOCKET_DISCONNECTED]: 'WebSocket connection lost',
+ [ERROR_CODES.RATE_LIMIT_EXCEEDED]: 'Rate limit exceeded. Please try again later.',
+ [ERROR_CODES.UNKNOWN_ERROR]: 'An unknown error occurred',
+ [ERROR_CODES.INVALID_REQUEST]: 'Invalid request parameters',
+ [ERROR_CODES.SERVER_ERROR]: 'Server error. Please try again later.',
+};
+
+// ============================================================================
+// WebSocket Constants
+// ============================================================================
+
+export const WEBSOCKET_CONFIG = {
+ MAX_RECONNECT_ATTEMPTS: 50,
+ RECONNECT_DELAY_MS: 2000,
+ MAX_RECONNECT_DELAY_MS: 60000,
+ PING_INTERVAL_MS: 30000,
+ CONNECTION_TIMEOUT_MS: 10000,
+ MAX_SUBSCRIPTIONS_PER_CONNECTION: 3000,
+ SUBSCRIPTION_BATCH_SIZE: 200,
+ SUBSCRIPTION_BATCH_DELAY_MS: 2000,
+} as const;
+
+// ============================================================================
+// API Rate Limits (Default values, brokers may vary)
+// ============================================================================
+
+export const DEFAULT_RATE_LIMITS = {
+ ORDERS_PER_SECOND: 10,
+ QUOTES_PER_SECOND: 1,
+ HISTORICAL_DATA_PER_SECOND: 3,
+} as const;
+
+// ============================================================================
+// Database Table Names
+// ============================================================================
+
+export const DB_TABLES = {
+ BROKER_CREDENTIALS: 'indian_broker_credentials',
+ MASTER_CONTRACTS: 'indian_master_contracts',
+ ORDER_HISTORY: 'indian_order_history',
+ TRADE_LOG: 'indian_trade_log',
+} as const;
diff --git a/fincept-terminal-desktop/src/brokers/india/index.ts b/fincept-terminal-desktop/src/brokers/india/index.ts
new file mode 100644
index 000000000..0cdec161b
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/index.ts
@@ -0,0 +1,24 @@
+/**
+ * Indian Stock Brokers Module
+ *
+ * This module provides adapter implementations for Indian stock brokers
+ * supporting NSE, BSE, NFO, MCX and other Indian exchanges.
+ */
+
+// Types
+export * from './types';
+
+// Constants
+export * from './constants';
+
+// Utilities
+export * from './utils';
+
+// Base adapter
+export { BaseIndianBrokerAdapter } from './BaseIndianBrokerAdapter';
+
+// Broker adapters
+export * from './zerodha';
+
+// Re-export individual adapters for convenience
+export { zerodhaAdapter } from './zerodha';
diff --git a/fincept-terminal-desktop/src/brokers/india/types.ts b/fincept-terminal-desktop/src/brokers/india/types.ts
new file mode 100644
index 000000000..68583c60c
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/types.ts
@@ -0,0 +1,525 @@
+/**
+ * Type definitions for Indian stock broker integrations
+ * Supports NSE, BSE, NFO, MCX and other Indian exchanges
+ */
+
+// ============================================================================
+// Exchange Types
+// ============================================================================
+
+export type IndianExchange =
+ | 'NSE' // National Stock Exchange - Equity
+ | 'BSE' // Bombay Stock Exchange - Equity
+ | 'NFO' // NSE Futures & Options
+ | 'BFO' // BSE Futures & Options
+ | 'CDS' // Currency Derivatives Segment
+ | 'BCD' // BSE Currency Derivatives
+ | 'MCX' // Multi Commodity Exchange
+ | 'NSE_INDEX' // NSE Indices (NIFTY, BANKNIFTY)
+ | 'BSE_INDEX' // BSE Indices (SENSEX)
+ | 'MCX_INDEX' // MCX Indices
+ | 'CDS_INDEX';// Currency Indices
+
+export type InstrumentType =
+ | 'EQ' // Equity
+ | 'FUT' // Futures
+ | 'CE' // Call Option
+ | 'PE' // Put Option
+ | 'INDEX' // Index
+ | 'FUTIDX' // Index Futures
+ | 'OPTIDX' // Index Options
+ | 'FUTSTK' // Stock Futures
+ | 'OPTSTK'; // Stock Options
+
+export type ProductType =
+ | 'CNC' // Cash and Carry (Delivery)
+ | 'MIS' // Margin Intraday Square-off
+ | 'NRML' // Normal (Carry Forward)
+ | 'CO' // Cover Order
+ | 'BO'; // Bracket Order
+
+export type OrderType =
+ | 'MARKET' // Market Order
+ | 'LIMIT' // Limit Order
+ | 'SL' // Stop Loss
+ | 'SL-M'; // Stop Loss Market
+
+export type TransactionType = 'BUY' | 'SELL';
+
+export type OrderValidity =
+ | 'DAY' // Valid for the day
+ | 'IOC' // Immediate or Cancel
+ | 'GTC' // Good Till Cancelled (not supported by all)
+ | 'GTD'; // Good Till Date
+
+export type OrderStatus =
+ | 'PENDING'
+ | 'OPEN'
+ | 'COMPLETE'
+ | 'CANCELLED'
+ | 'REJECTED'
+ | 'MODIFIED'
+ | 'TRIGGER_PENDING'
+ | 'AMO_SUBMITTED';
+
+// ============================================================================
+// Symbol & Instrument Types
+// ============================================================================
+
+export interface SymbolToken {
+ symbol: string; // Standardized symbol (e.g., 'RELIANCE')
+ brokerSymbol: string; // Broker-specific symbol
+ name: string; // Full name
+ exchange: IndianExchange;
+ brokerExchange: string; // Broker-specific exchange code
+ token: string; // Instrument token
+ expiry?: string; // Expiry date for derivatives (DD-MMM-YY)
+ strike?: number; // Strike price for options
+ lotSize: number;
+ instrumentType: InstrumentType;
+ tickSize: number;
+}
+
+export interface SymbolSearchResult {
+ symbol: string;
+ name: string;
+ exchange: IndianExchange;
+ token: string;
+ instrumentType: InstrumentType;
+ expiry?: string;
+ strike?: number;
+}
+
+// ============================================================================
+// Order Types
+// ============================================================================
+
+export interface OrderParams {
+ symbol: string;
+ exchange: IndianExchange;
+ transactionType: TransactionType;
+ orderType: OrderType;
+ productType: ProductType;
+ quantity: number;
+ price?: number; // Required for LIMIT orders
+ triggerPrice?: number; // Required for SL/SL-M orders
+ disclosedQuantity?: number;
+ validity?: OrderValidity;
+ tag?: string; // Order tag for tracking
+ amo?: boolean; // After Market Order
+}
+
+export interface OrderResponse {
+ success: boolean;
+ orderId?: string;
+ message?: string;
+ errorCode?: string;
+}
+
+export interface Order {
+ orderId: string;
+ exchangeOrderId?: string;
+ symbol: string;
+ exchange: IndianExchange;
+ transactionType: TransactionType;
+ orderType: OrderType;
+ productType: ProductType;
+ quantity: number;
+ filledQuantity: number;
+ pendingQuantity: number;
+ price: number;
+ averagePrice: number;
+ triggerPrice?: number;
+ status: OrderStatus;
+ statusMessage?: string;
+ orderTimestamp: number;
+ exchangeTimestamp?: number;
+ tag?: string;
+}
+
+export interface ModifyOrderParams {
+ orderId: string;
+ orderType?: OrderType;
+ quantity?: number;
+ price?: number;
+ triggerPrice?: number;
+ validity?: OrderValidity;
+}
+
+// ============================================================================
+// Position & Holdings Types
+// ============================================================================
+
+export interface Position {
+ symbol: string;
+ exchange: IndianExchange;
+ productType: ProductType;
+ quantity: number;
+ averagePrice: number;
+ lastPrice: number;
+ pnl: number;
+ pnlPercentage: number;
+ dayPnl: number;
+ buyQuantity: number;
+ sellQuantity: number;
+ buyValue: number;
+ sellValue: number;
+ multiplier: number;
+}
+
+export interface Holding {
+ symbol: string;
+ exchange: IndianExchange;
+ isin: string;
+ quantity: number;
+ averagePrice: number;
+ lastPrice: number;
+ pnl: number;
+ pnlPercentage: number;
+ dayChange: number;
+ dayChangePercentage: number;
+ pledgedQuantity: number;
+ collateralQuantity: number;
+}
+
+// ============================================================================
+// Account & Margin Types
+// ============================================================================
+
+export interface FundsData {
+ availableCash: number;
+ usedMargin: number;
+ availableMargin: number;
+ collateral: number;
+ unrealizedMtm: number;
+ realizedMtm: number;
+}
+
+export interface MarginRequired {
+ total: number;
+ var: number;
+ span: number;
+ exposure: number;
+ premium: number;
+}
+
+// ============================================================================
+// Market Data Types
+// ============================================================================
+
+export interface Quote {
+ symbol: string;
+ exchange: IndianExchange;
+ lastPrice: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+ change: number;
+ changePercent: number;
+ averagePrice?: number;
+ lastTradedQuantity?: number;
+ totalBuyQuantity?: number;
+ totalSellQuantity?: number;
+ openInterest?: number;
+ timestamp: number;
+}
+
+export interface MarketDepthLevel {
+ price: number;
+ quantity: number;
+ orders: number;
+}
+
+export interface MarketDepth {
+ buy: MarketDepthLevel[];
+ sell: MarketDepthLevel[];
+}
+
+export interface OHLCV {
+ timestamp: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+}
+
+export type TimeFrame =
+ | '1m' | '3m' | '5m' | '10m' | '15m' | '30m'
+ | '1h' | '2h' | '4h'
+ | '1d' | '1w' | '1M';
+
+// ============================================================================
+// WebSocket Types
+// ============================================================================
+
+export type SubscriptionMode =
+ | 'ltp' // Last Traded Price only
+ | 'quote' // Quote data (OHLC + Volume)
+ | 'full'; // Full data including market depth
+
+export interface TickData {
+ symbol: string;
+ exchange: IndianExchange;
+ token: string;
+ mode: SubscriptionMode;
+ lastPrice: number;
+ timestamp: number;
+ // Quote mode fields
+ open?: number;
+ high?: number;
+ low?: number;
+ close?: number;
+ volume?: number;
+ averagePrice?: number;
+ lastTradedQuantity?: number;
+ totalBuyQuantity?: number;
+ totalSellQuantity?: number;
+ openInterest?: number;
+ // Full mode fields
+ depth?: MarketDepth;
+}
+
+export interface WebSocketConfig {
+ apiKey: string;
+ accessToken: string;
+ onTick?: (tick: TickData) => void;
+ onConnect?: () => void;
+ onDisconnect?: () => void;
+ onError?: (error: Error) => void;
+ reconnectAttempts?: number;
+ reconnectDelay?: number;
+}
+
+// ============================================================================
+// Authentication Types
+// ============================================================================
+
+export interface BrokerCredentials {
+ brokerId: string;
+ apiKey: string;
+ apiSecret?: string;
+ accessToken?: string;
+ refreshToken?: string;
+ userId?: string;
+ password?: string; // For brokers requiring password
+ totp?: string; // For 2FA
+ expiresAt?: number; // Token expiry timestamp
+}
+
+export interface AuthResponse {
+ success: boolean;
+ accessToken?: string;
+ refreshToken?: string;
+ userId?: string;
+ expiresAt?: number;
+ message?: string;
+ errorCode?: string;
+}
+
+export interface AuthCallbackParams {
+ requestToken?: string;
+ code?: string;
+ state?: string;
+}
+
+// ============================================================================
+// Broker Adapter Interface
+// ============================================================================
+
+export interface IIndianBrokerAdapter {
+ // Broker identification
+ readonly brokerId: string;
+ readonly brokerName: string;
+ readonly isConnected: boolean;
+
+ // Authentication
+ authenticate(credentials: BrokerCredentials): Promise<AuthResponse>;
+ handleAuthCallback(params: AuthCallbackParams): Promise<AuthResponse>;
+ logout(): Promise<void>;
+ refreshSession(): Promise<AuthResponse>;
+
+ // Account
+ getFunds(): Promise<FundsData>;
+ getMarginRequired(params: OrderParams): Promise<MarginRequired>;
+ calculateMargin(orders: MarginOrderParams[]): Promise<MarginCalculation>;
+
+ // Orders
+ placeOrder(params: OrderParams): Promise<OrderResponse>;
+ modifyOrder(params: ModifyOrderParams): Promise<OrderResponse>;
+ cancelOrder(orderId: string): Promise<OrderResponse>;
+ getOrders(): Promise<Order[]>;
+ getOrderHistory(orderId: string): Promise<Order[]>;
+ getTradeBook(): Promise<Trade[]>;
+ cancelAllOrders(): Promise<BulkOperationResult>;
+
+ // Smart Orders
+ placeSmartOrder(params: SmartOrderParams): Promise<OrderResponse>;
+
+ // Positions & Holdings
+ getPositions(): Promise<Position[]>;
+ getHoldings(): Promise<Holding[]>;
+ getOpenPosition(symbol: string, exchange: IndianExchange, product: ProductType): Promise<OpenPositionResult>;
+ closeAllPositions(): Promise<BulkOperationResult>;
+
+ // Market Data
+ getQuote(symbol: string, exchange: IndianExchange): Promise<Quote>;
+ getQuotes(symbols: Array<{ symbol: string; exchange: IndianExchange }>): Promise<Quote[]>;
+ getOHLCV(
+ symbol: string,
+ exchange: IndianExchange,
+ timeframe: TimeFrame,
+ from: Date,
+ to: Date
+ ): Promise<OHLCV[]>;
+ getMarketDepth(symbol: string, exchange: IndianExchange): Promise<MarketDepth>;
+
+ // Symbol Management
+ searchSymbols(query: string, exchange?: IndianExchange): Promise<SymbolSearchResult[]>;
+ getSymbolToken(symbol: string, exchange: IndianExchange): Promise<SymbolToken | null>;
+
+ // WebSocket
+ connectWebSocket(config: WebSocketConfig): Promise<void>;
+ disconnectWebSocket(): Promise<void>;
+ subscribe(symbol: string, exchange: IndianExchange, mode: SubscriptionMode): Promise<void>;
+ unsubscribe(symbol: string, exchange: IndianExchange): Promise<void>;
+
+ // Master Contract
+ downloadMasterContract(): Promise<void>;
+ getMasterContractLastUpdated(): Promise<Date | null>;
+}
+
+// ============================================================================
+// Trade Book Types
+// ============================================================================
+
+export interface Trade {
+ tradeId: string;
+ orderId: string;
+ symbol: string;
+ exchange: IndianExchange;
+ transactionType: TransactionType;
+ quantity: number;
+ price: number;
+ product: ProductType;
+ tradeTime: Date;
+ exchangeOrderId?: string;
+ exchangeTradeId?: string;
+}
+
+// ============================================================================
+// Smart Order Types
+// ============================================================================
+
+export interface SmartOrderParams {
+ symbol: string;
+ exchange: IndianExchange;
+ transactionType: TransactionType;
+ quantity: number;
+ product: ProductType;
+ orderType: OrderType;
+ price?: number;
+ triggerPrice?: number;
+ positionSize?: number; // Current position size to adjust order
+}
+
+export interface OpenPositionResult {
+ symbol: string;
+ exchange: IndianExchange;
+ product: ProductType;
+ quantity: number;
+ position?: Position;
+}
+
+// ============================================================================
+// Bulk Operation Types
+// ============================================================================
+
+export interface BulkOperationResult {
+ success: boolean;
+ totalCount: number;
+ successCount: number;
+ failedCount: number;
+ results: Array<{
+ success: boolean;
+ orderId?: string;
+ error?: string;
+ }>;
+}
+
+// ============================================================================
+// Margin Calculation Types
+// ============================================================================
+
+export interface MarginOrderParams {
+ symbol: string;
+ exchange: IndianExchange;
+ transactionType: TransactionType;
+ quantity: number;
+ product: ProductType;
+ orderType: OrderType;
+ price?: number;
+ triggerPrice?: number;
+}
+
+export interface MarginCalculation {
+ totalMargin: number;
+ initialMargin: number;
+ exposureMargin: number;
+ spanMargin?: number;
+ optionPremium?: number;
+ leverage?: number;
+ orders: Array<{
+ symbol: string;
+ margin: number;
+ pnl?: number;
+ }>;
+}
+
+// ============================================================================
+// Broker Metadata
+// ============================================================================
+
+export interface IndianBrokerMetadata {
+ id: string;
+ name: string;
+ displayName: string;
+ logo?: string;
+ website: string;
+ supportedExchanges: IndianExchange[];
+ supportedProducts: ProductType[];
+ supportedOrderTypes: OrderType[];
+ features: {
+ webSocket: boolean;
+ amo: boolean;
+ gtt: boolean;
+ bracketOrder: boolean;
+ coverOrder: boolean;
+ marginCalculator: boolean;
+ };
+ authType: 'oauth' | 'totp' | 'password' | 'api_key';
+ rateLimit: {
+ ordersPerSecond: number;
+ quotesPerSecond: number;
+ };
+}
+
+// ============================================================================
+// API Response Types
+// ============================================================================
+
+export interface ApiResponse<T> {
+ success: boolean;
+ data?: T;
+ error?: string;
+ errorCode?: string;
+ timestamp: number;
+}
+
+export interface ApiError {
+ code: string;
+ message: string;
+ details?: Record<string, unknown>;
+}
diff --git a/fincept-terminal-desktop/src/brokers/india/utils/index.ts b/fincept-terminal-desktop/src/brokers/india/utils/index.ts
new file mode 100644
index 000000000..ad27df49b
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/utils/index.ts
@@ -0,0 +1,7 @@
+/**
+ * Utility exports for Indian broker integrations
+ */
+
+export * from './symbolMapper';
+export * from './orderTransformer';
+export * from './marketUtils';
diff --git a/fincept-terminal-desktop/src/brokers/india/utils/marketUtils.ts b/fincept-terminal-desktop/src/brokers/india/utils/marketUtils.ts
new file mode 100644
index 000000000..367cf6413
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/utils/marketUtils.ts
@@ -0,0 +1,390 @@
+/**
+ * Market utilities for Indian stock markets
+ * Handles market timing, holidays, and trading sessions
+ */
+
+import type { IndianExchange } from '../types';
+import { MARKET_TIMING } from '../constants';
+
+// ============================================================================
+// Timezone Utilities
+// ============================================================================
+
+const IST_OFFSET = 5.5 * 60 * 60 * 1000; // IST is UTC+5:30
+
+/**
+ * Get current time in IST
+ */
+export function getISTTime(): Date {
+ const now = new Date();
+ const utc = now.getTime() + now.getTimezoneOffset() * 60 * 1000;
+ return new Date(utc + IST_OFFSET);
+}
+
+/**
+ * Convert any date to IST
+ */
+export function toIST(date: Date): Date {
+ const utc = date.getTime() + date.getTimezoneOffset() * 60 * 1000;
+ return new Date(utc + IST_OFFSET);
+}
+
+/**
+ * Parse time string (HH:MM) to minutes from midnight
+ */
+function parseTimeToMinutes(timeStr: string): number {
+ const [hours, minutes] = timeStr.split(':').map(Number);
+ return hours * 60 + minutes;
+}
+
+/**
+ * Get minutes from midnight for a date
+ */
+function getMinutesFromMidnight(date: Date): number {
+ return date.getHours() * 60 + date.getMinutes();
+}
+
+// ============================================================================
+// Market Status
+// ============================================================================
+
+export type MarketStatus =
+ | 'PRE_OPEN'
+ | 'OPEN'
+ | 'POST_CLOSE'
+ | 'CLOSED'
+ | 'HOLIDAY';
+
+export interface MarketStatusInfo {
+ status: MarketStatus;
+ message: string;
+ nextOpenTime?: Date;
+ closingTime?: Date;
+}
+
+/**
+ * Check if a date is a weekend (Saturday or Sunday)
+ */
+export function isWeekend(date: Date): boolean {
+ const day = date.getDay();
+ return day === 0 || day === 6;
+}
+
+/**
+ * Get market status for NSE/BSE
+ */
+export function getEquityMarketStatus(date?: Date): MarketStatusInfo {
+ const istNow = date ? toIST(date) : getISTTime();
+ const currentMinutes = getMinutesFromMidnight(istNow);
+
+ // Check weekend
+ if (isWeekend(istNow)) {
+ return {
+ status: 'CLOSED',
+ message: 'Market closed (Weekend)',
+ nextOpenTime: getNextTradingDay(istNow),
+ };
+ }
+
+ const { preOpen, normal, postClose } = MARKET_TIMING.NSE;
+
+ const preOpenStart = parseTimeToMinutes(preOpen.start);
+ const preOpenEnd = parseTimeToMinutes(preOpen.end);
+ const normalStart = parseTimeToMinutes(normal.start);
+ const normalEnd = parseTimeToMinutes(normal.end);
+ const postCloseStart = parseTimeToMinutes(postClose.start);
+ const postCloseEnd = parseTimeToMinutes(postClose.end);
+
+ // Pre-open session
+ if (currentMinutes >= preOpenStart && currentMinutes < preOpenEnd) {
+ return {
+ status: 'PRE_OPEN',
+ message: 'Pre-open session',
+ closingTime: createTimeOnDate(istNow, preOpen.end),
+ };
+ }
+
+ // Normal trading hours
+ if (currentMinutes >= normalStart && currentMinutes < normalEnd) {
+ return {
+ status: 'OPEN',
+ message: 'Market open',
+ closingTime: createTimeOnDate(istNow, normal.end),
+ };
+ }
+
+ // Post-close session
+ if (currentMinutes >= postCloseStart && currentMinutes < postCloseEnd) {
+ return {
+ status: 'POST_CLOSE',
+ message: 'Post-close session',
+ closingTime: createTimeOnDate(istNow, postClose.end),
+ };
+ }
+
+ // Market closed
+ const message =
+ currentMinutes < preOpenStart
+ ? 'Market opens at 9:00 AM'
+ : 'Market closed for the day';
+
+ return {
+ status: 'CLOSED',
+ message,
+ nextOpenTime:
+ currentMinutes < preOpenStart
+ ? createTimeOnDate(istNow, preOpen.start)
+ : getNextTradingDay(istNow),
+ };
+}
+
+/**
+ * Get market status for MCX
+ */
+export function getMCXMarketStatus(date?: Date): MarketStatusInfo {
+ const istNow = date ? toIST(date) : getISTTime();
+ const currentMinutes = getMinutesFromMidnight(istNow);
+ const day = istNow.getDay();
+
+ // MCX is closed on Sundays
+ if (day === 0) {
+ return {
+ status: 'CLOSED',
+ message: 'Market closed (Sunday)',
+ nextOpenTime: getNextTradingDay(istNow),
+ };
+ }
+
+ const { morning, evening } = MARKET_TIMING.MCX;
+ const morningStart = parseTimeToMinutes(morning.start);
+ const eveningEnd = parseTimeToMinutes(evening.end);
+
+ // Morning session (9:00 - 17:00)
+ if (currentMinutes >= morningStart && currentMinutes < parseTimeToMinutes(morning.end)) {
+ return {
+ status: 'OPEN',
+ message: 'Morning session',
+ closingTime: createTimeOnDate(istNow, evening.end),
+ };
+ }
+
+ // Evening session (17:00 - 23:30)
+ if (currentMinutes >= parseTimeToMinutes(evening.start) && currentMinutes < eveningEnd) {
+ return {
+ status: 'OPEN',
+ message: 'Evening session',
+ closingTime: createTimeOnDate(istNow, evening.end),
+ };
+ }
+
+ // On Saturday, MCX closes at 11:30 PM
+ if (day === 6 && currentMinutes >= eveningEnd) {
+ return {
+ status: 'CLOSED',
+ message: 'Market closed for weekend',
+ nextOpenTime: getNextTradingDay(istNow),
+ };
+ }
+
+ return {
+ status: 'CLOSED',
+ message: 'Market closed',
+ nextOpenTime:
+ currentMinutes < morningStart
+ ? createTimeOnDate(istNow, morning.start)
+ : getNextTradingDay(istNow),
+ };
+}
+
+/**
+ * Get market status for an exchange
+ */
+export function getMarketStatus(exchange: IndianExchange, date?: Date): MarketStatusInfo {
+ switch (exchange) {
+ case 'NSE':
+ case 'BSE':
+ case 'NFO':
+ case 'BFO':
+ case 'NSE_INDEX':
+ case 'BSE_INDEX':
+ return getEquityMarketStatus(date);
+
+ case 'MCX':
+ case 'MCX_INDEX':
+ return getMCXMarketStatus(date);
+
+ case 'CDS':
+ case 'BCD':
+ case 'CDS_INDEX':
+ return getCDSMarketStatus(date);
+
+ default:
+ return getEquityMarketStatus(date);
+ }
+}
+
+/**
+ * Get market status for Currency (CDS)
+ */
+export function getCDSMarketStatus(date?: Date): MarketStatusInfo {
+ const istNow = date ? toIST(date) : getISTTime();
+ const currentMinutes = getMinutesFromMidnight(istNow);
+
+ if (isWeekend(istNow)) {
+ return {
+ status: 'CLOSED',
+ message: 'Market closed (Weekend)',
+ nextOpenTime: getNextTradingDay(istNow),
+ };
+ }
+
+ const { normal } = MARKET_TIMING.CDS;
+ const start = parseTimeToMinutes(normal.start);
+ const end = parseTimeToMinutes(normal.end);
+
+ if (currentMinutes >= start && currentMinutes < end) {
+ return {
+ status: 'OPEN',
+ message: 'Currency market open',
+ closingTime: createTimeOnDate(istNow, normal.end),
+ };
+ }
+
+ return {
+ status: 'CLOSED',
+ message: 'Currency market closed',
+ nextOpenTime:
+ currentMinutes < start
+ ? createTimeOnDate(istNow, normal.start)
+ : getNextTradingDay(istNow),
+ };
+}
+
+/**
+ * Check if market is open for trading
+ */
+export function isMarketOpen(exchange: IndianExchange, date?: Date): boolean {
+ const status = getMarketStatus(exchange, date);
+ return status.status === 'OPEN' || status.status === 'PRE_OPEN';
+}
+
+// ============================================================================
+// Helper Functions
+// ============================================================================
+
+/**
+ * Create a date with specific time on the same day
+ */
+function createTimeOnDate(date: Date, timeStr: string): Date {
+ const [hours, minutes] = timeStr.split(':').map(Number);
+ const result = new Date(date);
+ result.setHours(hours, minutes, 0, 0);
+ return result;
+}
+
+/**
+ * Get the next trading day
+ */
+export function getNextTradingDay(fromDate: Date): Date {
+ const result = new Date(fromDate);
+ result.setDate(result.getDate() + 1);
+
+ // Skip weekends
+ while (isWeekend(result)) {
+ result.setDate(result.getDate() + 1);
+ }
+
+ // Set to market open time (9:00 AM IST)
+ result.setHours(9, 0, 0, 0);
+ return result;
+}
+
+/**
+ * Get previous trading day
+ */
+export function getPreviousTradingDay(fromDate: Date): Date {
+ const result = new Date(fromDate);
+ result.setDate(result.getDate() - 1);
+
+ // Skip weekends
+ while (isWeekend(result)) {
+ result.setDate(result.getDate() - 1);
+ }
+
+ return result;
+}
+
+// ============================================================================
+// Time Formatting
+// ============================================================================
+
+/**
+ * Format time remaining until market close
+ */
+export function formatTimeRemaining(ms: number): string {
+ const hours = Math.floor(ms / (1000 * 60 * 60));
+ const minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60));
+
+ if (hours > 0) {
+ return `${hours}h ${minutes}m`;
+ }
+ return `${minutes}m`;
+}
+
+/**
+ * Get time until market close
+ */
+export function getTimeUntilClose(exchange: IndianExchange): number | null {
+ const status = getMarketStatus(exchange);
+ if (status.status !== 'OPEN' || !status.closingTime) {
+ return null;
+ }
+
+ const now = getISTTime();
+ return status.closingTime.getTime() - now.getTime();
+}
+
+/**
+ * Check if we're in the last N minutes of trading
+ */
+export function isNearClose(exchange: IndianExchange, minutesBefore: number = 15): boolean {
+ const timeRemaining = getTimeUntilClose(exchange);
+ if (timeRemaining === null) return false;
+ return timeRemaining <= minutesBefore * 60 * 1000;
+}
+
+// ============================================================================
+// Session Types
+// ============================================================================
+
+export type TradingSession = 'REGULAR' | 'AMO' | 'PRE_MARKET' | 'POST_MARKET';
+
+/**
+ * Get current trading session
+ */
+export function getCurrentSession(exchange: IndianExchange): TradingSession {
+ const status = getMarketStatus(exchange);
+
+ switch (status.status) {
+ case 'PRE_OPEN':
+ return 'PRE_MARKET';
+ case 'OPEN':
+ return 'REGULAR';
+ case 'POST_CLOSE':
+ return 'POST_MARKET';
+ case 'CLOSED':
+ case 'HOLIDAY':
+ return 'AMO';
+ default:
+ return 'REGULAR';
+ }
+}
+
+/**
+ * Check if AMO (After Market Orders) are allowed
+ */
+export function isAMOAllowed(exchange: IndianExchange): boolean {
+ const status = getMarketStatus(exchange);
+ // AMO typically allowed between 3:45 PM and 8:57 AM next day
+ return status.status === 'CLOSED' || status.status === 'POST_CLOSE';
+}
diff --git a/fincept-terminal-desktop/src/brokers/india/utils/orderTransformer.ts b/fincept-terminal-desktop/src/brokers/india/utils/orderTransformer.ts
new file mode 100644
index 000000000..804d208b9
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/utils/orderTransformer.ts
@@ -0,0 +1,538 @@
+/**
+ * Order transformation utilities for Indian brokers
+ * Handles conversion between standardized order format and broker-specific formats
+ */
+
+import type {
+ OrderParams,
+ Order,
+ OrderStatus,
+ OrderType,
+ ProductType,
+ TransactionType,
+ OrderValidity,
+ Position,
+ Holding,
+ FundsData,
+} from '../types';
+
+// ============================================================================
+// Order Status Mapping
+// ============================================================================
+
+/**
+ * Standardize order status from various broker formats
+ */
+export function standardizeOrderStatus(
+ status: string,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): OrderStatus {
+ const statusLower = status.toLowerCase().trim();
+
+ // Common status mappings
+ const statusMap: Record<string, OrderStatus> = {
+ // Completed
+ complete: 'COMPLETE',
+ completed: 'COMPLETE',
+ filled: 'COMPLETE',
+ traded: 'COMPLETE',
+
+ // Pending/Open
+ pending: 'PENDING',
+ open: 'OPEN',
+ 'open pending': 'OPEN',
+ 'after market order req received': 'AMO_SUBMITTED',
+ 'amo req received': 'AMO_SUBMITTED',
+ amo: 'AMO_SUBMITTED',
+
+ // Cancelled
+ cancelled: 'CANCELLED',
+ canceled: 'CANCELLED',
+
+ // Rejected
+ rejected: 'REJECTED',
+ failed: 'REJECTED',
+
+ // Trigger pending (for SL orders)
+ 'trigger pending': 'TRIGGER_PENDING',
+ 'sl pending': 'TRIGGER_PENDING',
+
+ // Modified
+ modified: 'MODIFIED',
+ 'modify pending': 'MODIFIED',
+ };
+
+ return statusMap[statusLower] || 'PENDING';
+}
+
+/**
+ * Convert standardized order status to broker format
+ */
+export function toBrokerOrderStatus(
+ status: OrderStatus,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): string {
+ // Zerodha format
+ if (brokerFormat === 'zerodha') {
+ const zerodhaMap: Record<OrderStatus, string> = {
+ PENDING: 'PENDING',
+ OPEN: 'OPEN',
+ COMPLETE: 'COMPLETE',
+ CANCELLED: 'CANCELLED',
+ REJECTED: 'REJECTED',
+ MODIFIED: 'MODIFIED',
+ TRIGGER_PENDING: 'TRIGGER PENDING',
+ AMO_SUBMITTED: 'AMO REQ RECEIVED',
+ };
+ return zerodhaMap[status] || status;
+ }
+
+ return status;
+}
+
+// ============================================================================
+// Order Type Mapping
+// ============================================================================
+
+export function standardizeOrderType(
+ orderType: string,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): OrderType {
+ const typeUpper = orderType.toUpperCase().trim();
+
+ const typeMap: Record<string, OrderType> = {
+ MARKET: 'MARKET',
+ MKT: 'MARKET',
+ LIMIT: 'LIMIT',
+ LMT: 'LIMIT',
+ SL: 'SL',
+ 'SL-L': 'SL',
+ 'STOPLOSS_LIMIT': 'SL',
+ 'SL-M': 'SL-M',
+ 'STOPLOSS_MARKET': 'SL-M',
+ SLM: 'SL-M',
+ };
+
+ return typeMap[typeUpper] || 'MARKET';
+}
+
+export function toBrokerOrderType(
+ orderType: OrderType,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): string {
+ if (brokerFormat === 'zerodha') {
+ return orderType; // Zerodha uses same format
+ }
+
+ if (brokerFormat === 'angel') {
+ const angelMap: Record<OrderType, string> = {
+ MARKET: 'MARKET',
+ LIMIT: 'LIMIT',
+ SL: 'STOPLOSS_LIMIT',
+ 'SL-M': 'STOPLOSS_MARKET',
+ };
+ return angelMap[orderType] || orderType;
+ }
+
+ return orderType;
+}
+
+// ============================================================================
+// Product Type Mapping
+// ============================================================================
+
+export function standardizeProductType(
+ productType: string,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): ProductType {
+ const typeUpper = productType.toUpperCase().trim();
+
+ const typeMap: Record<string, ProductType> = {
+ // Delivery
+ CNC: 'CNC',
+ DELIVERY: 'CNC',
+ C: 'CNC',
+
+ // Intraday
+ MIS: 'MIS',
+ INTRADAY: 'MIS',
+ I: 'MIS',
+
+ // Normal (F&O)
+ NRML: 'NRML',
+ NORMAL: 'NRML',
+ M: 'NRML',
+ MARGIN: 'NRML',
+
+ // Cover Order
+ CO: 'CO',
+
+ // Bracket Order
+ BO: 'BO',
+ };
+
+ return typeMap[typeUpper] || 'CNC';
+}
+
+export function toBrokerProductType(
+ productType: ProductType,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): string {
+ if (brokerFormat === 'zerodha') {
+ return productType;
+ }
+
+ if (brokerFormat === 'angel') {
+ const angelMap: Record<ProductType, string> = {
+ CNC: 'DELIVERY',
+ MIS: 'INTRADAY',
+ NRML: 'CARRYFORWARD',
+ CO: 'CO',
+ BO: 'BO',
+ };
+ return angelMap[productType] || productType;
+ }
+
+ if (brokerFormat === 'dhan') {
+ const dhanMap: Record<ProductType, string> = {
+ CNC: 'CNC',
+ MIS: 'INTRADAY',
+ NRML: 'MARGIN',
+ CO: 'CO',
+ BO: 'BO',
+ };
+ return dhanMap[productType] || productType;
+ }
+
+ return productType;
+}
+
+// ============================================================================
+// Transaction Type Mapping
+// ============================================================================
+
+export function standardizeTransactionType(
+ txnType: string,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): TransactionType {
+ const typeUpper = txnType.toUpperCase().trim();
+
+ if (['BUY', 'B', 'LONG'].includes(typeUpper)) {
+ return 'BUY';
+ }
+
+ if (['SELL', 'S', 'SHORT'].includes(typeUpper)) {
+ return 'SELL';
+ }
+
+ return 'BUY';
+}
+
+export function toBrokerTransactionType(
+ txnType: TransactionType,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): string {
+ // Most brokers use BUY/SELL
+ return txnType;
+}
+
+// ============================================================================
+// Validity Mapping
+// ============================================================================
+
+export function standardizeValidity(
+ validity: string,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): OrderValidity {
+ const validityUpper = validity.toUpperCase().trim();
+
+ const validityMap: Record<string, OrderValidity> = {
+ DAY: 'DAY',
+ IOC: 'IOC',
+ GTC: 'GTC',
+ GTD: 'GTD',
+ };
+
+ return validityMap[validityUpper] || 'DAY';
+}
+
+// ============================================================================
+// Transform Functions
+// ============================================================================
+
+/**
+ * Transform broker order response to standardized Order
+ */
+export function transformOrder(
+ brokerOrder: Record<string, unknown>,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): Order {
+ if (brokerFormat === 'zerodha') {
+ return transformZerodhaOrder(brokerOrder);
+ }
+
+ // Default transformation
+ return {
+ orderId: String(brokerOrder.order_id || brokerOrder.orderId || ''),
+ exchangeOrderId: String(brokerOrder.exchange_order_id || ''),
+ symbol: String(brokerOrder.tradingsymbol || brokerOrder.symbol || ''),
+ exchange: (brokerOrder.exchange as string) as any,
+ transactionType: standardizeTransactionType(
+ String(brokerOrder.transaction_type || brokerOrder.transactionType || 'BUY'),
+ brokerFormat
+ ),
+ orderType: standardizeOrderType(
+ String(brokerOrder.order_type || brokerOrder.orderType || 'MARKET'),
+ brokerFormat
+ ),
+ productType: standardizeProductType(
+ String(brokerOrder.product || brokerOrder.productType || 'CNC'),
+ brokerFormat
+ ),
+ quantity: Number(brokerOrder.quantity || 0),
+ filledQuantity: Number(brokerOrder.filled_quantity || brokerOrder.filledQuantity || 0),
+ pendingQuantity: Number(brokerOrder.pending_quantity || brokerOrder.pendingQuantity || 0),
+ price: Number(brokerOrder.price || 0),
+ averagePrice: Number(brokerOrder.average_price || brokerOrder.averagePrice || 0),
+ triggerPrice: Number(brokerOrder.trigger_price || brokerOrder.triggerPrice || 0),
+ status: standardizeOrderStatus(
+ String(brokerOrder.status || 'PENDING'),
+ brokerFormat
+ ),
+ statusMessage: String(brokerOrder.status_message || brokerOrder.statusMessage || ''),
+ orderTimestamp: Number(brokerOrder.order_timestamp || Date.now()),
+ exchangeTimestamp: Number(brokerOrder.exchange_timestamp || 0),
+ tag: String(brokerOrder.tag || ''),
+ };
+}
+
+function transformZerodhaOrder(order: Record<string, unknown>): Order {
+ return {
+ orderId: String(order.order_id || ''),
+ exchangeOrderId: String(order.exchange_order_id || ''),
+ symbol: String(order.tradingsymbol || ''),
+ exchange: (order.exchange as string) as any,
+ transactionType: standardizeTransactionType(String(order.transaction_type || 'BUY'), 'zerodha'),
+ orderType: standardizeOrderType(String(order.order_type || 'MARKET'), 'zerodha'),
+ productType: standardizeProductType(String(order.product || 'CNC'), 'zerodha'),
+ quantity: Number(order.quantity || 0),
+ filledQuantity: Number(order.filled_quantity || 0),
+ pendingQuantity: Number(order.pending_quantity || 0),
+ price: Number(order.price || 0),
+ averagePrice: Number(order.average_price || 0),
+ triggerPrice: Number(order.trigger_price || 0),
+ status: standardizeOrderStatus(String(order.status || 'PENDING'), 'zerodha'),
+ statusMessage: String(order.status_message || ''),
+ orderTimestamp: order.order_timestamp
+ ? new Date(order.order_timestamp as string).getTime()
+ : Date.now(),
+ exchangeTimestamp: order.exchange_timestamp
+ ? new Date(order.exchange_timestamp as string).getTime()
+ : 0,
+ tag: String(order.tag || ''),
+ };
+}
+
+/**
+ * Transform broker position to standardized Position
+ */
+export function transformPosition(
+ brokerPosition: Record<string, unknown>,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): Position {
+ if (brokerFormat === 'zerodha') {
+ return transformZerodhaPosition(brokerPosition);
+ }
+
+ return {
+ symbol: String(brokerPosition.tradingsymbol || brokerPosition.symbol || ''),
+ exchange: (brokerPosition.exchange as string) as any,
+ productType: standardizeProductType(
+ String(brokerPosition.product || brokerPosition.productType || 'MIS'),
+ brokerFormat
+ ),
+ quantity: Number(brokerPosition.quantity || brokerPosition.netQuantity || 0),
+ averagePrice: Number(brokerPosition.average_price || brokerPosition.averagePrice || 0),
+ lastPrice: Number(brokerPosition.last_price || brokerPosition.ltp || 0),
+ pnl: Number(brokerPosition.pnl || brokerPosition.unrealised || 0),
+ pnlPercentage: 0, // Calculate if needed
+ dayPnl: Number(brokerPosition.day_pnl || brokerPosition.dayPnl || 0),
+ buyQuantity: Number(brokerPosition.buy_quantity || brokerPosition.buyQuantity || 0),
+ sellQuantity: Number(brokerPosition.sell_quantity || brokerPosition.sellQuantity || 0),
+ buyValue: Number(brokerPosition.buy_value || brokerPosition.buyValue || 0),
+ sellValue: Number(brokerPosition.sell_value || brokerPosition.sellValue || 0),
+ multiplier: Number(brokerPosition.multiplier || 1),
+ };
+}
+
+function transformZerodhaPosition(position: Record<string, unknown>): Position {
+ const avgPrice = Number(position.average_price || 0);
+ const lastPrice = Number(position.last_price || 0);
+ const quantity = Number(position.quantity || 0);
+ const pnl = Number(position.pnl || position.unrealised || 0);
+ const pnlPercentage = avgPrice > 0 ? ((lastPrice - avgPrice) / avgPrice) * 100 : 0;
+
+ return {
+ symbol: String(position.tradingsymbol || ''),
+ exchange: (position.exchange as string) as any,
+ productType: standardizeProductType(String(position.product || 'MIS'), 'zerodha'),
+ quantity,
+ averagePrice: avgPrice,
+ lastPrice,
+ pnl,
+ pnlPercentage,
+ dayPnl: Number(position.day_m2m || 0),
+ buyQuantity: Number(position.day_buy_quantity || 0),
+ sellQuantity: Number(position.day_sell_quantity || 0),
+ buyValue: Number(position.day_buy_value || 0),
+ sellValue: Number(position.day_sell_value || 0),
+ multiplier: Number(position.multiplier || 1),
+ };
+}
+
+/**
+ * Transform broker holding to standardized Holding
+ */
+export function transformHolding(
+ brokerHolding: Record<string, unknown>,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): Holding {
+ const avgPrice = Number(
+ brokerHolding.average_price || brokerHolding.averagePrice || brokerHolding.avgPrice || 0
+ );
+ const lastPrice = Number(brokerHolding.last_price || brokerHolding.ltp || 0);
+ const quantity = Number(brokerHolding.quantity || brokerHolding.holdingQuantity || 0);
+ const pnl = (lastPrice - avgPrice) * quantity;
+ const pnlPercentage = avgPrice > 0 ? ((lastPrice - avgPrice) / avgPrice) * 100 : 0;
+ const close = Number(brokerHolding.close_price || brokerHolding.previousClose || lastPrice);
+ const dayChange = lastPrice - close;
+ const dayChangePercentage = close > 0 ? (dayChange / close) * 100 : 0;
+
+ return {
+ symbol: String(
+ brokerHolding.tradingsymbol || brokerHolding.symbol || brokerHolding.tradingSymbol || ''
+ ),
+ exchange: (brokerHolding.exchange as string || 'NSE') as any,
+ isin: String(brokerHolding.isin || ''),
+ quantity,
+ averagePrice: avgPrice,
+ lastPrice,
+ pnl,
+ pnlPercentage,
+ dayChange,
+ dayChangePercentage,
+ pledgedQuantity: Number(brokerHolding.pledged_quantity || brokerHolding.pledgedQuantity || 0),
+ collateralQuantity: Number(
+ brokerHolding.collateral_quantity || brokerHolding.collateralQuantity || 0
+ ),
+ };
+}
+
+/**
+ * Transform broker funds data to standardized FundsData
+ */
+export function transformFunds(
+ brokerFunds: Record<string, unknown>,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): FundsData {
+ if (brokerFormat === 'zerodha') {
+ return transformZerodhaFunds(brokerFunds);
+ }
+
+ return {
+ availableCash: Number(brokerFunds.available_cash || brokerFunds.availableCash || 0),
+ usedMargin: Number(brokerFunds.used_margin || brokerFunds.usedMargin || 0),
+ availableMargin: Number(brokerFunds.available_margin || brokerFunds.availableMargin || 0),
+ collateral: Number(brokerFunds.collateral || 0),
+ unrealizedMtm: Number(brokerFunds.unrealized_mtm || brokerFunds.unrealizedMtm || 0),
+ realizedMtm: Number(brokerFunds.realized_mtm || brokerFunds.realizedMtm || 0),
+ };
+}
+
+function transformZerodhaFunds(funds: Record<string, unknown>): FundsData {
+ // Zerodha returns separate equity and commodity margins
+ const equity = (funds.equity as Record<string, unknown>) || {};
+ const commodity = (funds.commodity as Record<string, unknown>) || {};
+
+ const equityNet = Number(equity.net || 0);
+ const commodityNet = Number(commodity.net || 0);
+
+ const equityUtilised = (equity.utilised as Record<string, unknown>) || {};
+ const commodityUtilised = (commodity.utilised as Record<string, unknown>) || {};
+
+ const equityAvailable = (equity.available as Record<string, unknown>) || {};
+ const commodityAvailable = (commodity.available as Record<string, unknown>) || {};
+
+ const availableCash = equityNet + commodityNet;
+ const usedMargin =
+ Number(equityUtilised.debits || 0) + Number(commodityUtilised.debits || 0);
+ const collateral =
+ Number(equityAvailable.collateral || 0) + Number(commodityAvailable.collateral || 0);
+ const unrealizedMtm =
+ Number(equityUtilised.m2m_unrealised || 0) + Number(commodityUtilised.m2m_unrealised || 0);
+ const realizedMtm =
+ Number(equityUtilised.m2m_realised || 0) + Number(commodityUtilised.m2m_realised || 0);
+
+ return {
+ availableCash,
+ usedMargin,
+ availableMargin: availableCash - usedMargin,
+ collateral,
+ unrealizedMtm,
+ realizedMtm,
+ };
+}
+
+/**
+ * Build order params for broker API
+ */
+export function buildBrokerOrderParams(
+ params: OrderParams,
+ brokerFormat: 'zerodha' | 'angel' | 'dhan' | 'fyers' | 'upstox'
+): Record<string, unknown> {
+ if (brokerFormat === 'zerodha') {
+ return {
+ tradingsymbol: params.symbol,
+ exchange: params.exchange,
+ transaction_type: params.transactionType,
+ order_type: params.orderType,
+ product: params.productType,
+ quantity: params.quantity,
+ price: params.price || 0,
+ trigger_price: params.triggerPrice || 0,
+ disclosed_quantity: params.disclosedQuantity || 0,
+ validity: params.validity || 'DAY',
+ tag: params.tag || '',
+ };
+ }
+
+ if (brokerFormat === 'angel') {
+ return {
+ tradingsymbol: params.symbol,
+ exchange: params.exchange,
+ transactiontype: params.transactionType,
+ ordertype: toBrokerOrderType(params.orderType, 'angel'),
+ producttype: toBrokerProductType(params.productType, 'angel'),
+ quantity: params.quantity,
+ price: params.price || 0,
+ triggerprice: params.triggerPrice || 0,
+ disclosedquantity: params.disclosedQuantity || 0,
+ duration: params.validity || 'DAY',
+ ordertag: params.tag || '',
+ };
+ }
+
+ // Default format
+ return {
+ symbol: params.symbol,
+ exchange: params.exchange,
+ transactionType: params.transactionType,
+ orderType: params.orderType,
+ productType: params.productType,
+ quantity: params.quantity,
+ price: params.price || 0,
+ triggerPrice: params.triggerPrice || 0,
+ validity: params.validity || 'DAY',
+ tag: params.tag || '',
+ };
+}
diff --git a/fincept-terminal-desktop/src/brokers/india/utils/symbolMapper.ts b/fincept-terminal-desktop/src/brokers/india/utils/symbolMapper.ts
new file mode 100644
index 000000000..50444854d
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/utils/symbolMapper.ts
@@ -0,0 +1,245 @@
+/**
+ * Symbol mapping utilities for Indian brokers
+ * Handles conversion between standardized symbols and broker-specific formats
+ */
+
+import type { IndianExchange, InstrumentType } from '../types';
+import { INDEX_SYMBOL_MAP } from '../constants';
+
+/**
+ * Parse expiry date from various formats to standardized DD-MMM-YY format
+ */
+export function parseExpiry(expiry: string | Date | null | undefined): string {
+ if (!expiry) return '';
+
+ try {
+ let date: Date;
+
+ if (expiry instanceof Date) {
+ date = expiry;
+ } else if (typeof expiry === 'string') {
+ // Handle formats like "2024-01-25", "25-JAN-24", "25JAN24"
+ if (expiry.includes('-') && expiry.length === 10) {
+ // ISO format: 2024-01-25
+ date = new Date(expiry);
+ } else if (expiry.includes('-')) {
+ // DD-MMM-YY format
+ return expiry.toUpperCase();
+ } else {
+ // Try to parse as date string
+ date = new Date(expiry);
+ }
+ } else {
+ return '';
+ }
+
+ if (isNaN(date.getTime())) return '';
+
+ const months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
+ 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
+ const day = String(date.getDate()).padStart(2, '0');
+ const month = months[date.getMonth()];
+ const year = String(date.getFullYear()).slice(-2);
+
+ return `${day}-${month}-${year}`;
+ } catch {
+ return '';
+ }
+}
+
+/**
+ * Format expiry for symbol construction (removes dashes)
+ */
+export function formatExpiryForSymbol(expiry: string): string {
+ return expiry.replace(/-/g, '');
+}
+
+/**
+ * Format strike price (remove decimals if whole number)
+ */
+export function formatStrike(strike: number | string): string {
+ const num = typeof strike === 'string' ? parseFloat(strike) : strike;
+ return Number.isInteger(num) ? String(Math.floor(num)) : String(num);
+}
+
+/**
+ * Standardize index symbol names
+ */
+export function standardizeIndexSymbol(symbol: string): string {
+ return INDEX_SYMBOL_MAP[symbol] || symbol;
+}
+
+/**
+ * Build standardized options symbol
+ * Format: {UNDERLYING}{EXPIRY}{STRIKE}{OPTIONTYPE}
+ * Example: NIFTY25JAN2450000CE
+ */
+export function buildOptionsSymbol(
+ underlying: string,
+ expiry: string,
+ strike: number,
+ optionType: 'CE' | 'PE'
+): string {
+ const formattedExpiry = formatExpiryForSymbol(parseExpiry(expiry));
+ const formattedStrike = formatStrike(strike);
+ return `${underlying}${formattedExpiry}${formattedStrike}${optionType}`;
+}
+
+/**
+ * Build standardized futures symbol
+ * Format: {UNDERLYING}{EXPIRY}FUT
+ * Example: NIFTY25JAN25FUT
+ */
+export function buildFuturesSymbol(underlying: string, expiry: string): string {
+ const formattedExpiry = formatExpiryForSymbol(parseExpiry(expiry));
+ return `${underlying}${formattedExpiry}FUT`;
+}
+
+/**
+ * Parse symbol to extract components
+ */
+export interface ParsedSymbol {
+ underlying: string;
+ expiry?: string;
+ strike?: number;
+ optionType?: 'CE' | 'PE';
+ instrumentType: InstrumentType;
+}
+
+export function parseSymbol(symbol: string): ParsedSymbol {
+ // Check for options (ends with CE or PE)
+ const optionsMatch = symbol.match(/^(.+?)(\d{2}[A-Z]{3}\d{2})(\d+)(CE|PE)$/);
+ if (optionsMatch) {
+ return {
+ underlying: optionsMatch[1],
+ expiry: optionsMatch[2],
+ strike: parseInt(optionsMatch[3], 10),
+ optionType: optionsMatch[4] as 'CE' | 'PE',
+ instrumentType: optionsMatch[4] as 'CE' | 'PE',
+ };
+ }
+
+ // Check for futures (ends with FUT)
+ const futuresMatch = symbol.match(/^(.+?)(\d{2}[A-Z]{3}\d{2})FUT$/);
+ if (futuresMatch) {
+ return {
+ underlying: futuresMatch[1],
+ expiry: futuresMatch[2],
+ instrumentType: 'FUT',
+ };
+ }
+
+ // Equity symbol
+ return {
+ underlying: symbol,
+ instrumentType: 'EQ',
+ };
+}
+
+/**
+ * Get the exchange for derivatives based on underlying
+ */
+export function getDerivativesExchange(underlying: string): IndianExchange {
+ // Index derivatives are on NFO
+ const indexUnderlyings = ['NIFTY', 'BANKNIFTY', 'FINNIFTY', 'MIDCPNIFTY'];
+ if (indexUnderlyings.includes(underlying)) {
+ return 'NFO';
+ }
+
+ // BSE indices
+ if (['SENSEX', 'BANKEX', 'SENSEX50'].includes(underlying)) {
+ return 'BFO';
+ }
+
+ // Commodities
+ if (['GOLD', 'SILVER', 'CRUDEOIL', 'NATURALGAS', 'COPPER'].includes(underlying)) {
+ return 'MCX';
+ }
+
+ // Currency
+ if (['USDINR', 'EURINR', 'GBPINR', 'JPYINR'].includes(underlying)) {
+ return 'CDS';
+ }
+
+ // Default to NFO for stock derivatives
+ return 'NFO';
+}
+
+/**
+ * Check if exchange is an index exchange
+ */
+export function isIndexExchange(exchange: IndianExchange): boolean {
+ return ['NSE_INDEX', 'BSE_INDEX', 'MCX_INDEX', 'CDS_INDEX'].includes(exchange);
+}
+
+/**
+ * Get the base exchange for an index exchange
+ */
+export function getBaseExchange(exchange: IndianExchange): IndianExchange {
+ const mapping: Partial<Record<IndianExchange, IndianExchange>> = {
+ NSE_INDEX: 'NSE',
+ BSE_INDEX: 'BSE',
+ MCX_INDEX: 'MCX',
+ CDS_INDEX: 'CDS',
+ };
+ return mapping[exchange] || exchange;
+}
+
+/**
+ * Convert exchange code for different broker formats
+ */
+export function mapExchangeCode(
+ exchange: IndianExchange,
+ brokerFormat: 'standard' | 'zerodha' | 'angel' | 'dhan'
+): string {
+ // Most brokers use the same codes
+ if (brokerFormat === 'standard' || brokerFormat === 'zerodha') {
+ return exchange;
+ }
+
+ // Angel uses different codes for some exchanges
+ if (brokerFormat === 'angel') {
+ const angelMapping: Partial<Record<IndianExchange, string>> = {
+ NSE: 'NSE',
+ BSE: 'BSE',
+ NFO: 'NFO',
+ MCX: 'MCX',
+ CDS: 'CDS',
+ NSE_INDEX: 'NSE',
+ BSE_INDEX: 'BSE',
+ };
+ return angelMapping[exchange] || exchange;
+ }
+
+ // Dhan uses segment codes
+ if (brokerFormat === 'dhan') {
+ const dhanMapping: Partial<Record<IndianExchange, string>> = {
+ NSE: 'NSE_EQ',
+ BSE: 'BSE_EQ',
+ NFO: 'NSE_FNO',
+ BFO: 'BSE_FNO',
+ MCX: 'MCX_COMM',
+ CDS: 'NSE_CURRENCY',
+ };
+ return dhanMapping[exchange] || exchange;
+ }
+
+ return exchange;
+}
+
+/**
+ * Validate symbol format
+ */
+export function isValidSymbol(symbol: string): boolean {
+ if (!symbol || typeof symbol !== 'string') return false;
+
+ // Basic validation: alphanumeric, can contain & and -
+ return /^[A-Z0-9&\-]+$/i.test(symbol);
+}
+
+/**
+ * Normalize symbol (uppercase, trim)
+ */
+export function normalizeSymbol(symbol: string): string {
+ return symbol.toUpperCase().trim();
+}
diff --git a/fincept-terminal-desktop/src/brokers/india/zerodha/ZerodhaAdapter.ts b/fincept-terminal-desktop/src/brokers/india/zerodha/ZerodhaAdapter.ts
new file mode 100644
index 000000000..117007771
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/zerodha/ZerodhaAdapter.ts
@@ -0,0 +1,778 @@
+/**
+ * Zerodha (Kite) Broker Adapter
+ * Implements the IIndianBrokerAdapter interface for Zerodha's Kite Connect API
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+import { BaseIndianBrokerAdapter } from '../BaseIndianBrokerAdapter';
+import type {
+ IndianBrokerMetadata,
+ AuthResponse,
+ AuthCallbackParams,
+ OrderParams,
+ OrderResponse,
+ ModifyOrderParams,
+ Order,
+ Position,
+ Holding,
+ FundsData,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ TimeFrame,
+ IndianExchange,
+ WebSocketConfig,
+ SubscriptionMode,
+ Trade,
+ SmartOrderParams,
+ OpenPositionResult,
+ BulkOperationResult,
+ MarginOrderParams,
+ MarginCalculation,
+ ProductType,
+} from '../types';
+import {
+ ZERODHA_METADATA,
+ ZERODHA_API_BASE_URL,
+ ZERODHA_LOGIN_URL,
+ ZERODHA_ENDPOINTS,
+ ZERODHA_EXCHANGE_MAP,
+} from './constants';
+import {
+ toZerodhaOrderParams,
+ toZerodhaModifyParams,
+ toZerodhaInterval,
+ fromZerodhaOrder,
+ fromZerodhaPosition,
+ fromZerodhaHolding,
+ fromZerodhaFunds,
+ fromZerodhaQuote,
+ fromZerodhaOHLCV,
+ fromZerodhaDepth,
+ fromZerodhaInstrument,
+ fromZerodhaTick,
+ fromZerodhaTrade,
+ toZerodhaWSMode,
+ toZerodhaMarginParams,
+} from './mapper';
+
+/**
+ * Zerodha broker adapter implementation
+ */
+export class ZerodhaAdapter extends BaseIndianBrokerAdapter {
+ readonly brokerId = 'zerodha';
+ readonly brokerName = 'Zerodha';
+ readonly metadata: IndianBrokerMetadata = ZERODHA_METADATA;
+
+ private apiKey: string | null = null;
+ private apiSecret: string | null = null;
+
+ // Token to symbol mapping for WebSocket
+ private tokenSymbolMap: Map<number, { symbol: string; exchange: IndianExchange }> = new Map();
+
+ // ============================================================================
+ // Authentication Methods
+ // ============================================================================
+
+ getAuthUrl(): string {
+ if (!this.apiKey) {
+ throw new Error('API key not set. Please set API key before getting auth URL.');
+ }
+ return `${ZERODHA_LOGIN_URL}?api_key=${this.apiKey}&v=3`;
+ }
+
+ async handleAuthCallback(params: AuthCallbackParams): Promise<AuthResponse> {
+ try {
+ if (!params.requestToken) {
+ return {
+ success: false,
+ message: 'Request token not provided',
+ errorCode: 'AUTH001',
+ };
+ }
+
+ if (!this.apiKey || !this.apiSecret) {
+ return {
+ success: false,
+ message: 'API key and secret must be set before handling callback',
+ errorCode: 'AUTH001',
+ };
+ }
+
+ // Exchange request token for access token via Tauri backend
+ const response = await invoke<{
+ success: boolean;
+ access_token?: string;
+ user_id?: string;
+ error?: string;
+ }>('zerodha_exchange_token', {
+ apiKey: this.apiKey,
+ apiSecret: this.apiSecret,
+ requestToken: params.requestToken,
+ });
+
+ if (!response.success || !response.access_token) {
+ return {
+ success: false,
+ message: response.error || 'Failed to exchange token',
+ errorCode: 'AUTH001',
+ };
+ }
+
+ // Store the access token
+ this.accessToken = response.access_token;
+ this.userId = response.user_id || null;
+ this._isConnected = true;
+
+ // Store credentials in database
+ await this.storeCredentials({
+ brokerId: this.brokerId,
+ apiKey: this.apiKey,
+ apiSecret: this.apiSecret,
+ accessToken: this.accessToken,
+ userId: this.userId || undefined,
+ });
+
+ return {
+ success: true,
+ accessToken: this.accessToken,
+ userId: this.userId || undefined,
+ message: 'Authentication successful',
+ };
+ } catch (error) {
+ return this.handleAuthError(error);
+ }
+ }
+
+ /**
+ * Set API credentials
+ */
+ setCredentials(apiKey: string, apiSecret: string): void {
+ this.apiKey = apiKey;
+ this.apiSecret = apiSecret;
+ }
+
+ /**
+ * Initialize from stored credentials
+ */
+ async initFromStorage(): Promise<boolean> {
+ try {
+ const credentials = await this.loadCredentials();
+ if (!credentials) return false;
+
+ this.apiKey = credentials.apiKey;
+ this.apiSecret = credentials.apiSecret || null;
+ this.accessToken = credentials.accessToken || null;
+ this.userId = credentials.userId || null;
+
+ if (this.accessToken) {
+ // Validate the token
+ const isValid = await this.validateToken(this.accessToken);
+ this._isConnected = isValid;
+ return isValid;
+ }
+
+ return false;
+ } catch {
+ return false;
+ }
+ }
+
+ protected override async validateToken(token: string): Promise<boolean> {
+ try {
+ const response = await invoke<{ success: boolean }>('zerodha_validate_token', {
+ apiKey: this.apiKey,
+ accessToken: token,
+ });
+ return response.success;
+ } catch {
+ return false;
+ }
+ }
+
+ // ============================================================================
+ // Order Methods
+ // ============================================================================
+
+ protected async placeOrderInternal(params: OrderParams): Promise<OrderResponse> {
+ const zerodhaParams = toZerodhaOrderParams(params);
+
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('zerodha_place_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ params: zerodhaParams,
+ variety: params.amo ? 'amo' : 'regular',
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ protected async modifyOrderInternal(params: ModifyOrderParams): Promise<OrderResponse> {
+ const zerodhaParams = toZerodhaModifyParams(params);
+
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('zerodha_modify_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ orderId: params.orderId,
+ params: zerodhaParams,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ protected async cancelOrderInternal(orderId: string): Promise<OrderResponse> {
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('zerodha_cancel_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ orderId,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ protected async getOrdersInternal(): Promise<Order[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>[];
+ error?: string;
+ }>('zerodha_get_orders', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(fromZerodhaOrder);
+ }
+
+ // ============================================================================
+ // Position & Holdings Methods
+ // ============================================================================
+
+ protected async getPositionsInternal(): Promise<Position[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ net?: Record<string, unknown>[];
+ day?: Record<string, unknown>[];
+ };
+ error?: string;
+ }>('zerodha_get_positions', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ // Combine net and day positions
+ const positions = response.data.net || [];
+ return positions.map(fromZerodhaPosition);
+ }
+
+ protected async getHoldingsInternal(): Promise<Holding[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>[];
+ error?: string;
+ }>('zerodha_get_holdings', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(fromZerodhaHolding);
+ }
+
+ protected async getFundsInternal(): Promise<FundsData> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ }>('zerodha_get_margins', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ availableCash: 0,
+ usedMargin: 0,
+ availableMargin: 0,
+ collateral: 0,
+ unrealizedMtm: 0,
+ realizedMtm: 0,
+ };
+ }
+
+ return fromZerodhaFunds(response.data);
+ }
+
+ // ============================================================================
+ // Market Data Methods
+ // ============================================================================
+
+ protected async getQuoteInternal(
+ symbol: string,
+ exchange: IndianExchange
+ ): Promise<Quote> {
+ const instrumentKey = `${ZERODHA_EXCHANGE_MAP[exchange] || exchange}:${symbol}`;
+
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, Record<string, unknown>>;
+ error?: string;
+ }>('zerodha_get_quote', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ instruments: [instrumentKey],
+ });
+
+ if (!response.success || !response.data) {
+ throw new Error('Failed to fetch quote');
+ }
+
+ const quoteData = response.data[instrumentKey];
+ if (!quoteData) {
+ throw new Error(`Quote not found for ${symbol}`);
+ }
+
+ return fromZerodhaQuote(quoteData, symbol, exchange);
+ }
+
+ protected async getOHLCVInternal(
+ symbol: string,
+ exchange: IndianExchange,
+ timeframe: TimeFrame,
+ from: Date,
+ to: Date
+ ): Promise<OHLCV[]> {
+ // Get instrument token first
+ const symbolToken = await this.getSymbolToken(symbol, exchange);
+ if (!symbolToken) {
+ throw new Error(`Symbol token not found for ${symbol}`);
+ }
+
+ // Extract instrument token from the combined token
+ const instrumentToken = symbolToken.token.split('::::')[0];
+
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ candles?: unknown[][];
+ };
+ error?: string;
+ }>('zerodha_get_historical', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ instrumentToken,
+ interval: toZerodhaInterval(timeframe),
+ from: from.toISOString().split('T')[0],
+ to: to.toISOString().split('T')[0],
+ });
+
+ if (!response.success || !response.data?.candles) {
+ return [];
+ }
+
+ return response.data.candles.map(fromZerodhaOHLCV);
+ }
+
+ protected async getMarketDepthInternal(
+ symbol: string,
+ exchange: IndianExchange
+ ): Promise<MarketDepth> {
+ const quote = await this.getQuoteInternal(symbol, exchange);
+
+ // Quote includes depth data - need to fetch full quote with depth
+ const instrumentKey = `${ZERODHA_EXCHANGE_MAP[exchange] || exchange}:${symbol}`;
+
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, Record<string, unknown>>;
+ error?: string;
+ }>('zerodha_get_quote', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ instruments: [instrumentKey],
+ });
+
+ if (!response.success || !response.data) {
+ return { buy: [], sell: [] };
+ }
+
+ const quoteData = response.data[instrumentKey];
+ if (!quoteData?.depth) {
+ return { buy: [], sell: [] };
+ }
+
+ return fromZerodhaDepth(quoteData.depth as Record<string, unknown>);
+ }
+
+ // ============================================================================
+ // WebSocket Methods
+ // ============================================================================
+
+ protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {
+ if (!this.apiKey || !this.accessToken) {
+ throw new Error('API key and access token required for WebSocket');
+ }
+
+ // Connect via Tauri backend
+ await invoke('zerodha_ws_connect', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ // Listen for tick events from Tauri
+ // This will be handled by the Tauri event system
+ }
+
+ protected async subscribeInternal(
+ symbol: string,
+ exchange: IndianExchange,
+ mode: SubscriptionMode
+ ): Promise<void> {
+ // Get instrument token
+ const symbolToken = await this.getSymbolToken(symbol, exchange);
+ if (!symbolToken) {
+ throw new Error(`Symbol token not found for ${symbol}`);
+ }
+
+ const instrumentToken = parseInt(symbolToken.token.split('::::')[0], 10);
+
+ // Store mapping for tick processing
+ this.tokenSymbolMap.set(instrumentToken, { symbol, exchange });
+
+ // Subscribe via Tauri backend
+ await invoke('zerodha_ws_subscribe', {
+ tokens: [instrumentToken],
+ mode: toZerodhaWSMode(mode),
+ });
+ }
+
+ protected async unsubscribeInternal(
+ symbol: string,
+ exchange: IndianExchange
+ ): Promise<void> {
+ // Get instrument token
+ const symbolToken = await this.getSymbolToken(symbol, exchange);
+ if (!symbolToken) return;
+
+ const instrumentToken = parseInt(symbolToken.token.split('::::')[0], 10);
+
+ // Remove from mapping
+ this.tokenSymbolMap.delete(instrumentToken);
+
+ // Unsubscribe via Tauri backend
+ await invoke('zerodha_ws_unsubscribe', {
+ tokens: [instrumentToken],
+ });
+ }
+
+ /**
+ * Handle incoming tick from WebSocket
+ * This is called from Tauri event listener
+ */
+ handleTick(tick: Record<string, unknown>): void {
+ const instrumentToken = Number(tick.instrument_token);
+ const symbolInfo = this.tokenSymbolMap.get(instrumentToken);
+
+ if (!symbolInfo) {
+ console.warn(`[Zerodha] Unknown instrument token: ${instrumentToken}`);
+ return;
+ }
+
+ // Determine mode from tick data
+ let mode: SubscriptionMode = 'ltp';
+ if (tick.depth) {
+ mode = 'full';
+ } else if (tick.ohlc || tick.volume) {
+ mode = 'quote';
+ }
+
+ const tickData = fromZerodhaTick(tick, symbolInfo, mode);
+ this.emitTick(tickData);
+ }
+
+ // ============================================================================
+ // Master Contract Methods
+ // ============================================================================
+
+ protected async downloadMasterContractInternal(): Promise<void> {
+ // Download and process instruments via Tauri backend
+ await invoke('zerodha_download_master_contract', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+ }
+
+ // ============================================================================
+ // Trade Book Methods
+ // ============================================================================
+
+ async getTradeBook(): Promise<Trade[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>[];
+ error?: string;
+ }>('zerodha_get_trade_book', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(fromZerodhaTrade);
+ }
+
+ // ============================================================================
+ // Open Position Methods
+ // ============================================================================
+
+ async getOpenPosition(
+ symbol: string,
+ exchange: IndianExchange,
+ product: ProductType
+ ): Promise<OpenPositionResult> {
+ const zerodhaExchange = ZERODHA_EXCHANGE_MAP[exchange] || exchange;
+
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ tradingsymbol: string;
+ exchange: string;
+ product: string;
+ quantity: number;
+ position?: Record<string, unknown>;
+ };
+ error?: string;
+ }>('zerodha_get_open_position', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ tradingsymbol: symbol,
+ exchange: zerodhaExchange,
+ product,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ symbol,
+ exchange,
+ product,
+ quantity: 0,
+ };
+ }
+
+ return {
+ symbol: response.data.tradingsymbol,
+ exchange,
+ product,
+ quantity: response.data.quantity,
+ position: response.data.position ? fromZerodhaPosition(response.data.position) : undefined,
+ };
+ }
+
+ // ============================================================================
+ // Smart Order Methods
+ // ============================================================================
+
+ async placeSmartOrder(params: SmartOrderParams): Promise<OrderResponse> {
+ const zerodhaExchange = ZERODHA_EXCHANGE_MAP[params.exchange] || params.exchange;
+
+ // Get current position size if not provided
+ let positionSize = params.positionSize ?? 0;
+ if (params.positionSize === undefined) {
+ const position = await this.getOpenPosition(params.symbol, params.exchange, params.product);
+ positionSize = position.quantity;
+ }
+
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('zerodha_place_smart_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ tradingsymbol: params.symbol,
+ exchange: zerodhaExchange,
+ product: params.product,
+ action: params.transactionType,
+ quantity: params.quantity,
+ orderType: params.orderType,
+ price: params.price,
+ triggerPrice: params.triggerPrice,
+ positionSize,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ // ============================================================================
+ // Bulk Operation Methods
+ // ============================================================================
+
+ async closeAllPositions(): Promise<BulkOperationResult> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Array<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>;
+ error?: string;
+ }>('zerodha_close_all_positions', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ success: false,
+ totalCount: 0,
+ successCount: 0,
+ failedCount: 0,
+ results: [],
+ };
+ }
+
+ const results = response.data.map(r => ({
+ success: r.success,
+ orderId: r.order_id,
+ error: r.error,
+ }));
+
+ return {
+ success: true,
+ totalCount: results.length,
+ successCount: results.filter(r => r.success).length,
+ failedCount: results.filter(r => !r.success).length,
+ results,
+ };
+ }
+
+ async cancelAllOrders(): Promise<BulkOperationResult> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Array<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>;
+ error?: string;
+ }>('zerodha_cancel_all_orders', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ success: false,
+ totalCount: 0,
+ successCount: 0,
+ failedCount: 0,
+ results: [],
+ };
+ }
+
+ const results = response.data.map(r => ({
+ success: r.success,
+ orderId: r.order_id,
+ error: r.error,
+ }));
+
+ return {
+ success: true,
+ totalCount: results.length,
+ successCount: results.filter(r => r.success).length,
+ failedCount: results.filter(r => !r.success).length,
+ results,
+ };
+ }
+
+ // ============================================================================
+ // Margin Calculator Methods
+ // ============================================================================
+
+ async calculateMargin(orders: MarginOrderParams[]): Promise<MarginCalculation> {
+ const zerodhaOrders = orders.map(toZerodhaMarginParams);
+
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ }>('zerodha_calculate_margin', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ orders: zerodhaOrders,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ totalMargin: 0,
+ initialMargin: 0,
+ exposureMargin: 0,
+ orders: [],
+ };
+ }
+
+ const data = response.data;
+
+ // Extract margin data from response
+ const initial = Number(data.initial || data.total || 0);
+ const exposure = Number(data.exposure || 0);
+ const total = Number(data.total || initial + exposure);
+
+ return {
+ totalMargin: total,
+ initialMargin: initial,
+ exposureMargin: exposure,
+ spanMargin: data.span ? Number(data.span) : undefined,
+ optionPremium: data.option_premium ? Number(data.option_premium) : undefined,
+ leverage: data.leverage ? Number(data.leverage) : undefined,
+ orders: orders.map((o, i) => ({
+ symbol: o.symbol,
+ margin: Array.isArray(data.orders) ? Number((data.orders as Record<string, unknown>[])[i]?.margin || 0) : 0,
+ })),
+ };
+ }
+}
+
+// Export singleton instance
+export const zerodhaAdapter = new ZerodhaAdapter();
diff --git a/fincept-terminal-desktop/src/brokers/india/zerodha/constants.ts b/fincept-terminal-desktop/src/brokers/india/zerodha/constants.ts
new file mode 100644
index 000000000..19141ddda
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/zerodha/constants.ts
@@ -0,0 +1,161 @@
+/**
+ * Zerodha (Kite) specific constants
+ */
+
+import type { IndianBrokerMetadata } from '../types';
+
+// ============================================================================
+// API Configuration
+// ============================================================================
+
+export const ZERODHA_API_BASE_URL = 'https://api.kite.trade';
+export const ZERODHA_LOGIN_URL = 'https://kite.zerodha.com/connect/login';
+export const ZERODHA_WS_URL = 'wss://ws.kite.trade';
+
+export const ZERODHA_API_VERSION = '3';
+
+// ============================================================================
+// Endpoints
+// ============================================================================
+
+export const ZERODHA_ENDPOINTS = {
+ // Authentication
+ SESSION: '/session/token',
+ USER_PROFILE: '/user/profile',
+ USER_MARGINS: '/user/margins',
+
+ // Orders
+ ORDERS: '/orders',
+ ORDERS_REGULAR: '/orders/regular',
+ ORDERS_AMO: '/orders/amo',
+ TRADES: '/trades',
+
+ // Portfolio
+ POSITIONS: '/portfolio/positions',
+ HOLDINGS: '/portfolio/holdings',
+
+ // Market Data
+ QUOTE: '/quote',
+ OHLC: '/quote/ohlc',
+ LTP: '/quote/ltp',
+ INSTRUMENTS: '/instruments',
+ HISTORICAL: '/instruments/historical',
+
+ // GTT
+ GTT: '/gtt/triggers',
+} as const;
+
+// ============================================================================
+// Broker Metadata
+// ============================================================================
+
+export const ZERODHA_METADATA: IndianBrokerMetadata = {
+ id: 'zerodha',
+ name: 'zerodha',
+ displayName: 'Zerodha (Kite)',
+ logo: 'zerodha-logo.svg',
+ website: 'https://zerodha.com',
+ supportedExchanges: [
+ 'NSE',
+ 'BSE',
+ 'NFO',
+ 'BFO',
+ 'CDS',
+ 'BCD',
+ 'MCX',
+ 'NSE_INDEX',
+ 'BSE_INDEX',
+ 'MCX_INDEX',
+ 'CDS_INDEX',
+ ],
+ supportedProducts: ['CNC', 'MIS', 'NRML', 'CO', 'BO'],
+ supportedOrderTypes: ['MARKET', 'LIMIT', 'SL', 'SL-M'],
+ features: {
+ webSocket: true,
+ amo: true,
+ gtt: true,
+ bracketOrder: true,
+ coverOrder: true,
+ marginCalculator: true,
+ },
+ authType: 'oauth',
+ rateLimit: {
+ ordersPerSecond: 10,
+ quotesPerSecond: 1,
+ },
+};
+
+// ============================================================================
+// Exchange Mappings
+// ============================================================================
+
+export const ZERODHA_EXCHANGE_MAP: Record<string, string> = {
+ NSE: 'NSE',
+ BSE: 'BSE',
+ NFO: 'NFO',
+ BFO: 'BFO',
+ CDS: 'CDS',
+ BCD: 'BCD',
+ MCX: 'MCX',
+ NSE_INDEX: 'NSE',
+ BSE_INDEX: 'BSE',
+ MCX_INDEX: 'MCX',
+ CDS_INDEX: 'CDS',
+};
+
+// ============================================================================
+// WebSocket Constants
+// ============================================================================
+
+export const ZERODHA_WS_CONFIG = {
+ // Subscription modes
+ MODE_LTP: 'ltp',
+ MODE_QUOTE: 'quote',
+ MODE_FULL: 'full',
+
+ // Connection settings
+ PING_INTERVAL: null, // Zerodha sends heartbeats
+ KEEPALIVE_INTERVAL: 30000, // 30 seconds
+ PING_TIMEOUT: 10000,
+ CONNECTION_TIMEOUT: 10000,
+ MAX_MESSAGE_SIZE: 10 * 1024 * 1024, // 10MB
+
+ // Subscription batching
+ MAX_TOKENS_PER_SUBSCRIBE: 200,
+ SUBSCRIPTION_DELAY: 2000, // 2 seconds between batches
+ MAX_INSTRUMENTS_PER_CONNECTION: 3000,
+
+ // Reconnection
+ MAX_RECONNECT_ATTEMPTS: 50,
+ MAX_RECONNECT_DELAY: 60000,
+ INITIAL_RECONNECT_DELAY: 2000,
+} as const;
+
+// ============================================================================
+// Timeframe Mappings
+// ============================================================================
+
+export const ZERODHA_TIMEFRAME_MAP: Record<string, string> = {
+ '1m': 'minute',
+ '3m': '3minute',
+ '5m': '5minute',
+ '10m': '10minute',
+ '15m': '15minute',
+ '30m': '30minute',
+ '1h': '60minute',
+ '1d': 'day',
+ '1w': 'week',
+ '1M': 'month',
+};
+
+// ============================================================================
+// Error Code Mappings
+// ============================================================================
+
+export const ZERODHA_ERROR_CODES: Record<string, string> = {
+ TokenException: 'AUTH002', // Token expired
+ InputException: 'ERR002', // Invalid input
+ OrderException: 'ORD001', // Order error
+ NetworkException: 'CONN001', // Network error
+ GeneralException: 'ERR001', // General error
+};
diff --git a/fincept-terminal-desktop/src/brokers/india/zerodha/index.ts b/fincept-terminal-desktop/src/brokers/india/zerodha/index.ts
new file mode 100644
index 000000000..869d3727e
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/zerodha/index.ts
@@ -0,0 +1,7 @@
+/**
+ * Zerodha broker module exports
+ */
+
+export { ZerodhaAdapter, zerodhaAdapter } from './ZerodhaAdapter';
+export * from './constants';
+export * from './mapper';
diff --git a/fincept-terminal-desktop/src/brokers/india/zerodha/mapper.ts b/fincept-terminal-desktop/src/brokers/india/zerodha/mapper.ts
new file mode 100644
index 000000000..170887073
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/india/zerodha/mapper.ts
@@ -0,0 +1,469 @@
+/**
+ * Zerodha data transformation and mapping utilities
+ */
+
+import type {
+ Order,
+ Position,
+ Holding,
+ FundsData,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ MarketDepthLevel,
+ OrderParams,
+ ModifyOrderParams,
+ SymbolToken,
+ IndianExchange,
+ TickData,
+ SubscriptionMode,
+} from '../types';
+import {
+ standardizeOrderStatus,
+ standardizeOrderType,
+ standardizeProductType,
+ standardizeTransactionType,
+} from '../utils/orderTransformer';
+import { parseExpiry } from '../utils/symbolMapper';
+import { ZERODHA_EXCHANGE_MAP, ZERODHA_TIMEFRAME_MAP } from './constants';
+
+// ============================================================================
+// Request Transformers
+// ============================================================================
+
+/**
+ * Transform order params to Zerodha format
+ */
+export function toZerodhaOrderParams(params: OrderParams): Record<string, unknown> {
+ return {
+ tradingsymbol: params.symbol,
+ exchange: ZERODHA_EXCHANGE_MAP[params.exchange] || params.exchange,
+ transaction_type: params.transactionType,
+ order_type: params.orderType,
+ product: params.productType,
+ quantity: params.quantity,
+ price: params.price || 0,
+ trigger_price: params.triggerPrice || 0,
+ disclosed_quantity: params.disclosedQuantity || 0,
+ validity: params.validity || 'DAY',
+ tag: params.tag || '',
+ };
+}
+
+/**
+ * Transform modify order params to Zerodha format
+ */
+export function toZerodhaModifyParams(params: ModifyOrderParams): Record<string, unknown> {
+ const zerodhaParams: Record<string, unknown> = {};
+
+ if (params.orderType) zerodhaParams.order_type = params.orderType;
+ if (params.quantity) zerodhaParams.quantity = params.quantity;
+ if (params.price !== undefined) zerodhaParams.price = params.price;
+ if (params.triggerPrice !== undefined) zerodhaParams.trigger_price = params.triggerPrice;
+ if (params.validity) zerodhaParams.validity = params.validity;
+
+ return zerodhaParams;
+}
+
+/**
+ * Get Zerodha interval string from timeframe
+ */
+export function toZerodhaInterval(timeframe: string): string {
+ return ZERODHA_TIMEFRAME_MAP[timeframe] || 'day';
+}
+
+// ============================================================================
+// Response Transformers
+// ============================================================================
+
+/**
+ * Transform Zerodha order response to standard format
+ */
+export function fromZerodhaOrder(order: Record<string, unknown>): Order {
+ return {
+ orderId: String(order.order_id || ''),
+ exchangeOrderId: String(order.exchange_order_id || ''),
+ symbol: String(order.tradingsymbol || ''),
+ exchange: mapZerodhaExchange(String(order.exchange || 'NSE')),
+ transactionType: standardizeTransactionType(
+ String(order.transaction_type || 'BUY'),
+ 'zerodha'
+ ),
+ orderType: standardizeOrderType(String(order.order_type || 'MARKET'), 'zerodha'),
+ productType: standardizeProductType(String(order.product || 'CNC'), 'zerodha'),
+ quantity: Number(order.quantity || 0),
+ filledQuantity: Number(order.filled_quantity || 0),
+ pendingQuantity: Number(order.pending_quantity || 0),
+ price: Number(order.price || 0),
+ averagePrice: Number(order.average_price || 0),
+ triggerPrice: Number(order.trigger_price || 0),
+ status: standardizeOrderStatus(String(order.status || 'PENDING'), 'zerodha'),
+ statusMessage: String(order.status_message || ''),
+ orderTimestamp: order.order_timestamp
+ ? new Date(order.order_timestamp as string).getTime()
+ : Date.now(),
+ exchangeTimestamp: order.exchange_timestamp
+ ? new Date(order.exchange_timestamp as string).getTime()
+ : undefined,
+ tag: String(order.tag || ''),
+ };
+}
+
+/**
+ * Transform Zerodha position to standard format
+ */
+export function fromZerodhaPosition(position: Record<string, unknown>): Position {
+ const avgPrice = Number(position.average_price || 0);
+ const lastPrice = Number(position.last_price || 0);
+ const quantity = Number(position.quantity || 0);
+ const pnl = Number(position.pnl || position.unrealised || 0);
+ const pnlPercentage = avgPrice > 0 ? ((lastPrice - avgPrice) / avgPrice) * 100 : 0;
+
+ return {
+ symbol: String(position.tradingsymbol || ''),
+ exchange: mapZerodhaExchange(String(position.exchange || 'NSE')),
+ productType: standardizeProductType(String(position.product || 'MIS'), 'zerodha'),
+ quantity,
+ averagePrice: avgPrice,
+ lastPrice,
+ pnl,
+ pnlPercentage,
+ dayPnl: Number(position.day_m2m || 0),
+ buyQuantity: Number(position.day_buy_quantity || 0),
+ sellQuantity: Number(position.day_sell_quantity || 0),
+ buyValue: Number(position.day_buy_value || 0),
+ sellValue: Number(position.day_sell_value || 0),
+ multiplier: Number(position.multiplier || 1),
+ };
+}
+
+/**
+ * Transform Zerodha holding to standard format
+ */
+export function fromZerodhaHolding(holding: Record<string, unknown>): Holding {
+ const avgPrice = Number(holding.average_price || 0);
+ const lastPrice = Number(holding.last_price || 0);
+ const quantity = Number(holding.quantity || 0);
+ const pnl = (lastPrice - avgPrice) * quantity;
+ const pnlPercentage = avgPrice > 0 ? ((lastPrice - avgPrice) / avgPrice) * 100 : 0;
+ const close = Number(holding.close_price || lastPrice);
+ const dayChange = lastPrice - close;
+ const dayChangePercentage = close > 0 ? (dayChange / close) * 100 : 0;
+
+ return {
+ symbol: String(holding.tradingsymbol || ''),
+ exchange: mapZerodhaExchange(String(holding.exchange || 'NSE')),
+ isin: String(holding.isin || ''),
+ quantity,
+ averagePrice: avgPrice,
+ lastPrice,
+ pnl,
+ pnlPercentage,
+ dayChange,
+ dayChangePercentage,
+ pledgedQuantity: Number(holding.pledged_quantity || 0),
+ collateralQuantity: Number(holding.collateral_quantity || 0),
+ };
+}
+
+/**
+ * Transform Zerodha funds/margins to standard format
+ */
+export function fromZerodhaFunds(data: Record<string, unknown>): FundsData {
+ const equity = (data.equity as Record<string, unknown>) || {};
+ const commodity = (data.commodity as Record<string, unknown>) || {};
+
+ const equityNet = Number(equity.net || 0);
+ const commodityNet = Number(commodity.net || 0);
+
+ const equityUtilised = (equity.utilised as Record<string, number>) || {};
+ const commodityUtilised = (commodity.utilised as Record<string, number>) || {};
+
+ const equityAvailable = (equity.available as Record<string, number>) || {};
+ const commodityAvailable = (commodity.available as Record<string, number>) || {};
+
+ return {
+ availableCash: equityNet + commodityNet,
+ usedMargin: (equityUtilised.debits || 0) + (commodityUtilised.debits || 0),
+ availableMargin: equityNet + commodityNet,
+ collateral: (equityAvailable.collateral || 0) + (commodityAvailable.collateral || 0),
+ unrealizedMtm:
+ (equityUtilised.m2m_unrealised || 0) + (commodityUtilised.m2m_unrealised || 0),
+ realizedMtm: (equityUtilised.m2m_realised || 0) + (commodityUtilised.m2m_realised || 0),
+ };
+}
+
+/**
+ * Transform Zerodha quote to standard format
+ */
+export function fromZerodhaQuote(
+ quote: Record<string, unknown>,
+ symbol: string,
+ exchange: IndianExchange
+): Quote {
+ const ohlc = (quote.ohlc as Record<string, number>) || {};
+
+ return {
+ symbol,
+ exchange,
+ lastPrice: Number(quote.last_price || 0),
+ open: Number(ohlc.open || 0),
+ high: Number(ohlc.high || 0),
+ low: Number(ohlc.low || 0),
+ close: Number(ohlc.close || 0),
+ volume: Number(quote.volume || 0),
+ change: Number(quote.change || 0),
+ changePercent: Number(quote.change_percent || 0),
+ averagePrice: Number(quote.average_price || 0),
+ lastTradedQuantity: Number(quote.last_quantity || 0),
+ totalBuyQuantity: Number(quote.buy_quantity || 0),
+ totalSellQuantity: Number(quote.sell_quantity || 0),
+ openInterest: Number(quote.oi || 0),
+ timestamp: quote.last_trade_time
+ ? new Date(quote.last_trade_time as string).getTime()
+ : Date.now(),
+ };
+}
+
+/**
+ * Transform Zerodha historical data to OHLCV format
+ */
+export function fromZerodhaOHLCV(candle: unknown[]): OHLCV {
+ // Zerodha candle format: [datetime, open, high, low, close, volume]
+ return {
+ timestamp: new Date(candle[0] as string).getTime(),
+ open: Number(candle[1]),
+ high: Number(candle[2]),
+ low: Number(candle[3]),
+ close: Number(candle[4]),
+ volume: Number(candle[5]),
+ };
+}
+
+/**
+ * Transform Zerodha market depth to standard format
+ */
+export function fromZerodhaDepth(depth: Record<string, unknown>): MarketDepth {
+ const buy = (depth.buy as unknown[]) || [];
+ const sell = (depth.sell as unknown[]) || [];
+
+ return {
+ buy: buy.map((level) => fromZerodhaDepthLevel(level as Record<string, unknown>)),
+ sell: sell.map((level) => fromZerodhaDepthLevel(level as Record<string, unknown>)),
+ };
+}
+
+function fromZerodhaDepthLevel(level: Record<string, unknown>): MarketDepthLevel {
+ return {
+ price: Number(level.price || 0),
+ quantity: Number(level.quantity || 0),
+ orders: Number(level.orders || 0),
+ };
+}
+
+// ============================================================================
+// Master Contract Transformers
+// ============================================================================
+
+/**
+ * Transform Zerodha instrument to SymbolToken
+ */
+export function fromZerodhaInstrument(instrument: Record<string, unknown>): SymbolToken {
+ const exchange = String(instrument.exchange || 'NSE');
+ const segment = String(instrument.segment || '');
+
+ // Determine the mapped exchange (handle indices)
+ let mappedExchange: IndianExchange = exchange as IndianExchange;
+ if (segment === 'INDICES') {
+ if (exchange === 'NSE') mappedExchange = 'NSE_INDEX';
+ else if (exchange === 'BSE') mappedExchange = 'BSE_INDEX';
+ else if (exchange === 'MCX') mappedExchange = 'MCX_INDEX';
+ else if (exchange === 'CDS') mappedExchange = 'CDS_INDEX';
+ }
+
+ // Build token combining instrument_token and exchange_token
+ const instrumentToken = String(instrument.instrument_token || '');
+ const exchangeToken = String(instrument.exchange_token || '');
+ const token = `${instrumentToken}::::${exchangeToken}`;
+
+ return {
+ symbol: buildStandardSymbol(instrument),
+ brokerSymbol: String(instrument.tradingsymbol || ''),
+ name: String(instrument.name || ''),
+ exchange: mappedExchange,
+ brokerExchange: exchange,
+ token,
+ expiry: parseExpiry(instrument.expiry as string | null),
+ strike: instrument.strike ? Number(instrument.strike) : undefined,
+ lotSize: Number(instrument.lot_size || 1),
+ instrumentType: mapInstrumentType(String(instrument.instrument_type || 'EQ')),
+ tickSize: Number(instrument.tick_size || 0.05),
+ };
+}
+
+/**
+ * Build standardized symbol from Zerodha instrument
+ */
+function buildStandardSymbol(instrument: Record<string, unknown>): string {
+ const tradingsymbol = String(instrument.tradingsymbol || '');
+ const instrumentType = String(instrument.instrument_type || 'EQ');
+ const name = String(instrument.name || tradingsymbol);
+
+ // For equity, use tradingsymbol as-is
+ if (instrumentType === 'EQ') {
+ return tradingsymbol;
+ }
+
+ // For futures
+ if (instrumentType === 'FUT') {
+ const expiry = parseExpiry(instrument.expiry as string).replace(/-/g, '');
+ return `${name}${expiry}FUT`;
+ }
+
+ // For options
+ if (instrumentType === 'CE' || instrumentType === 'PE') {
+ const expiry = parseExpiry(instrument.expiry as string).replace(/-/g, '');
+ const strike = String(Math.floor(Number(instrument.strike || 0)));
+ return `${name}${expiry}${strike}${instrumentType}`;
+ }
+
+ // Default
+ return tradingsymbol;
+}
+
+/**
+ * Map Zerodha instrument type to standard type
+ */
+function mapInstrumentType(type: string): import('../types').InstrumentType {
+ const typeMap: Record<string, import('../types').InstrumentType> = {
+ EQ: 'EQ',
+ FUT: 'FUT',
+ CE: 'CE',
+ PE: 'PE',
+ FUTIDX: 'FUTIDX',
+ OPTIDX: 'OPTIDX',
+ FUTSTK: 'FUTSTK',
+ OPTSTK: 'OPTSTK',
+ };
+ return typeMap[type] || 'EQ';
+}
+
+/**
+ * Map Zerodha exchange to standard exchange
+ */
+function mapZerodhaExchange(exchange: string): IndianExchange {
+ // Reverse mapping - Zerodha doesn't use _INDEX suffixes
+ return exchange as IndianExchange;
+}
+
+// ============================================================================
+// WebSocket Tick Transformers
+// ============================================================================
+
+/**
+ * Transform Zerodha WebSocket tick to standard format
+ */
+export function fromZerodhaTick(
+ tick: Record<string, unknown>,
+ symbolInfo: { symbol: string; exchange: IndianExchange },
+ mode: SubscriptionMode
+): TickData {
+ const baseTick: TickData = {
+ symbol: symbolInfo.symbol,
+ exchange: symbolInfo.exchange,
+ token: String(tick.instrument_token || ''),
+ mode,
+ lastPrice: Number(tick.last_traded_price || tick.last_price || 0),
+ timestamp: Number(tick.timestamp || Date.now()),
+ };
+
+ // Add quote mode fields
+ if (mode === 'quote' || mode === 'full') {
+ const ohlc = tick.ohlc as Record<string, number> | undefined;
+ baseTick.open = Number(ohlc?.open || tick.open_price || 0);
+ baseTick.high = Number(ohlc?.high || tick.high_price || 0);
+ baseTick.low = Number(ohlc?.low || tick.low_price || 0);
+ baseTick.close = Number(ohlc?.close || tick.close_price || 0);
+ baseTick.volume = Number(tick.volume_traded || tick.volume || 0);
+ baseTick.averagePrice = Number(tick.average_traded_price || tick.average_price || 0);
+ baseTick.lastTradedQuantity = Number(tick.last_traded_quantity || 0);
+ baseTick.totalBuyQuantity = Number(tick.total_buy_quantity || 0);
+ baseTick.totalSellQuantity = Number(tick.total_sell_quantity || 0);
+ baseTick.openInterest = Number(tick.oi || tick.open_interest || 0);
+ }
+
+ // Add depth for full mode
+ if (mode === 'full' && tick.depth) {
+ baseTick.depth = fromZerodhaDepth(tick.depth as Record<string, unknown>);
+ }
+
+ return baseTick;
+}
+
+/**
+ * Get Zerodha WebSocket mode string
+ */
+export function toZerodhaWSMode(mode: SubscriptionMode): string {
+ const modeMap: Record<SubscriptionMode, string> = {
+ ltp: 'ltp',
+ quote: 'quote',
+ full: 'full',
+ };
+ return modeMap[mode] || 'quote';
+}
+
+/**
+ * Parse Zerodha WebSocket mode string
+ */
+export function fromZerodhaWSMode(mode: string): SubscriptionMode {
+ const modeMap: Record<string, SubscriptionMode> = {
+ ltp: 'ltp',
+ quote: 'quote',
+ full: 'full',
+ };
+ return modeMap[mode] || 'quote';
+}
+
+// ============================================================================
+// Trade Book Transformers
+// ============================================================================
+
+/**
+ * Transform Zerodha trade to standard format
+ */
+export function fromZerodhaTrade(trade: Record<string, unknown>): import('../types').Trade {
+ return {
+ tradeId: String(trade.trade_id || ''),
+ orderId: String(trade.order_id || ''),
+ symbol: String(trade.tradingsymbol || ''),
+ exchange: mapZerodhaExchange(String(trade.exchange || 'NSE')),
+ transactionType: String(trade.transaction_type || 'BUY').toUpperCase() as import('../types').TransactionType,
+ quantity: Number(trade.quantity || 0),
+ price: Number(trade.average_price || trade.price || 0),
+ product: String(trade.product || 'CNC') as import('../types').ProductType,
+ tradeTime: new Date(trade.fill_timestamp as string || trade.order_timestamp as string || Date.now()),
+ exchangeOrderId: trade.exchange_order_id ? String(trade.exchange_order_id) : undefined,
+ exchangeTradeId: trade.exchange_trade_id ? String(trade.exchange_trade_id) : undefined,
+ };
+}
+
+// ============================================================================
+// Margin Calculator Transformers
+// ============================================================================
+
+/**
+ * Transform margin order params to Zerodha format
+ */
+export function toZerodhaMarginParams(params: import('../types').MarginOrderParams): Record<string, unknown> {
+ return {
+ exchange: params.exchange,
+ tradingsymbol: params.symbol,
+ transaction_type: params.transactionType,
+ variety: 'regular',
+ product: params.product,
+ order_type: params.orderType,
+ quantity: params.quantity,
+ price: params.price || 0,
+ trigger_price: params.triggerPrice || 0,
+ };
+}
diff --git a/fincept-terminal-desktop/src/brokers/registry.ts b/fincept-terminal-desktop/src/brokers/registry.ts
index b0c2c871d..bd57a20fc 100644
--- a/fincept-terminal-desktop/src/brokers/registry.ts
+++ b/fincept-terminal-desktop/src/brokers/registry.ts
@@ -7,8 +7,10 @@
import { KrakenAdapter } from './crypto/kraken/KrakenAdapter';
import { HyperLiquidAdapter } from './crypto/hyperliquid/HyperLiquidAdapter';
-// import { ZerodhaAdapter } from './stocks/zerodha/ZerodhaAdapter'; // TODO: Implement when ready
+import { ZerodhaAdapter } from './india/zerodha/ZerodhaAdapter';
+import { FyersAdapter } from './stocks/india/fyers/FyersAdapter';
import type { IExchangeAdapter, ExchangeConfig } from './crypto/types';
+import type { IIndianBrokerAdapter } from './india/types';
// ============================================================================
// BROKER METADATA
@@ -202,7 +204,147 @@ export const BROKER_REGISTRY: Record<string, BrokerMetadata> = {
},
},
- // zerodha: { ... } // TODO: Implement when ZerodhaAdapter is ready
+ // ============================================================================
+ // INDIAN STOCK BROKERS
+ // ============================================================================
+
+ zerodha: {
+ id: 'zerodha',
+ name: 'zerodha',
+ displayName: 'Zerodha (Kite)',
+ type: 'stocks',
+ category: 'centralized',
+ region: 'india',
+ adapterClass: ZerodhaAdapter,
+
+ features: {
+ spot: true, // Equity delivery
+ margin: true, // MIS (Intraday)
+ futures: true, // F&O
+ perpetuals: false,
+ options: true, // Options
+ staking: false,
+ vaults: false,
+ subaccounts: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true, // SL
+ stopLimitOrders: true, // SL-M
+ trailingStopOrders: false,
+ icebergOrders: false,
+ batchOrders: false,
+ editOrders: true,
+ },
+
+ advancedFeatures: {
+ leverage: true,
+ maxLeverage: 5, // MIS leverage up to 5x
+ marginMode: true,
+ transfers: false,
+ withdrawals: false,
+ deposits: false,
+ },
+
+ defaultSymbols: [
+ 'RELIANCE',
+ 'TCS',
+ 'HDFCBANK',
+ 'INFY',
+ 'ICICIBANK',
+ 'SBIN',
+ 'BHARTIARTL',
+ 'HINDUNILVR',
+ 'ITC',
+ 'KOTAKBANK',
+ 'LT',
+ 'AXISBANK',
+ 'MARUTI',
+ 'TATAMOTORS',
+ 'WIPRO',
+ ],
+
+ websocket: {
+ enabled: true,
+ endpoint: 'wss://ws.kite.trade',
+ },
+
+ fees: {
+ maker: 0, // Zerodha has zero brokerage for equity delivery
+ taker: 0.0003, // 0.03% or Rs 20 whichever is lower for intraday
+ },
+ },
+
+ fyers: {
+ id: 'fyers',
+ name: 'fyers',
+ displayName: 'Fyers',
+ type: 'stocks',
+ category: 'centralized',
+ region: 'india',
+ adapterClass: FyersAdapter,
+
+ features: {
+ spot: true, // Equity delivery
+ margin: true, // INTRADAY
+ futures: true, // F&O
+ perpetuals: false,
+ options: true, // Options
+ staking: false,
+ vaults: false,
+ subaccounts: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true, // Stop Loss
+ stopLimitOrders: true, // Stop Loss Limit
+ trailingStopOrders: false,
+ icebergOrders: false,
+ batchOrders: false,
+ editOrders: true,
+ },
+
+ advancedFeatures: {
+ leverage: true,
+ maxLeverage: 5, // Intraday leverage
+ marginMode: true,
+ transfers: false,
+ withdrawals: false,
+ deposits: false,
+ },
+
+ defaultSymbols: [
+ 'RELIANCE',
+ 'TCS',
+ 'HDFCBANK',
+ 'INFY',
+ 'ICICIBANK',
+ 'SBIN',
+ 'BHARTIARTL',
+ 'HINDUNILVR',
+ 'ITC',
+ 'KOTAKBANK',
+ 'LT',
+ 'AXISBANK',
+ 'MARUTI',
+ 'TATAMOTORS',
+ 'WIPRO',
+ ],
+
+ websocket: {
+ enabled: true,
+ endpoint: 'wss://socket.fyers.in/hsm/v1-5/prod',
+ },
+
+ fees: {
+ maker: 0, // Fyers has zero brokerage for equity delivery
+ taker: 0.0003, // 0.03% or Rs 20 whichever is lower for intraday
+ },
+ },
};
// ============================================================================
@@ -223,6 +365,20 @@ export function getBrokersByType(type: 'crypto' | 'stocks' | 'forex' | 'commodit
return getAllBrokers().filter(broker => broker.type === type);
}
+/**
+ * Get brokers by region
+ */
+export function getBrokersByRegion(region: 'global' | 'us' | 'india' | 'asia' | 'europe'): BrokerMetadata[] {
+ return getAllBrokers().filter(broker => broker.region === region);
+}
+
+/**
+ * Get Indian stock brokers
+ */
+export function getIndianBrokers(): BrokerMetadata[] {
+ return getAllBrokers().filter(broker => broker.type === 'stocks' && broker.region === 'india');
+}
+
/**
* Get broker metadata by ID
*/
diff --git a/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.ts
new file mode 100644
index 000000000..9d2be9b5c
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.ts
@@ -0,0 +1,560 @@
+/**
+ * Base Stock Broker Adapter
+ *
+ * Abstract base class for all stock brokers globally
+ * Provides common functionality - subclasses implement broker-specific logic
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+import type {
+ IStockBrokerAdapter,
+ StockBrokerMetadata,
+ Region,
+ BrokerCredentials,
+ AuthResponse,
+ AuthCallbackParams,
+ Funds,
+ MarginRequired,
+ OrderParams,
+ OrderResponse,
+ ModifyOrderParams,
+ Order,
+ Trade,
+ Position,
+ Holding,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ TimeFrame,
+ StockExchange,
+ Instrument,
+ WebSocketConfig,
+ SubscriptionMode,
+ TickData,
+ BulkOperationResult,
+ SmartOrderParams,
+ ProductType,
+} from './types';
+import { ERROR_CODES, ERROR_MESSAGES, DEFAULT_RATE_LIMITS, WEBSOCKET_DEFAULTS } from './constants';
+
+/**
+ * Abstract base class for stock broker adapters
+ */
+export abstract class BaseStockBrokerAdapter implements IStockBrokerAdapter {
+ // ============================================================================
+ // Abstract Properties (must be implemented by subclass)
+ // ============================================================================
+
+ abstract readonly brokerId: string;
+ abstract readonly brokerName: string;
+ abstract readonly region: Region;
+ abstract readonly metadata: StockBrokerMetadata;
+
+ // ============================================================================
+ // Protected State
+ // ============================================================================
+
+ protected _isConnected: boolean = false;
+ protected credentials: BrokerCredentials | null = null;
+ protected accessToken: string | null = null;
+ protected userId: string | null = null;
+
+ // WebSocket state
+ protected wsConnected: boolean = false;
+ protected wsConfig: WebSocketConfig | null = null;
+ protected tickCallbacks: Set<(tick: TickData) => void> = new Set();
+ protected subscriptions: Map<string, { symbol: string; exchange: StockExchange; mode: SubscriptionMode }> = new Map();
+
+ // Rate limiting
+ protected lastApiCall: number = 0;
+ protected requestQueue: Array<() => Promise<unknown>> = [];
+
+ // ============================================================================
+ // Public Getters
+ // ============================================================================
+
+ get isConnected(): boolean {
+ return this._isConnected && this.accessToken !== null;
+ }
+
+ // ============================================================================
+ // Abstract Methods (must be implemented by subclass)
+ // ============================================================================
+
+ // Authentication
+ abstract authenticate(credentials: BrokerCredentials): Promise<AuthResponse>;
+
+ // Orders - Internal implementations
+ protected abstract placeOrderInternal(params: OrderParams): Promise<OrderResponse>;
+ protected abstract modifyOrderInternal(params: ModifyOrderParams): Promise<OrderResponse>;
+ protected abstract cancelOrderInternal(orderId: string): Promise<OrderResponse>;
+ protected abstract getOrdersInternal(): Promise<Order[]>;
+ protected abstract getTradeBookInternal(): Promise<Trade[]>;
+
+ // Positions & Holdings - Internal implementations
+ protected abstract getPositionsInternal(): Promise<Position[]>;
+ protected abstract getHoldingsInternal(): Promise<Holding[]>;
+ protected abstract getFundsInternal(): Promise<Funds>;
+
+ // Market Data - Internal implementations
+ protected abstract getQuoteInternal(symbol: string, exchange: StockExchange): Promise<Quote>;
+ protected abstract getOHLCVInternal(symbol: string, exchange: StockExchange, timeframe: TimeFrame, from: Date, to: Date): Promise<OHLCV[]>;
+ protected abstract getMarketDepthInternal(symbol: string, exchange: StockExchange): Promise<MarketDepth>;
+
+ // WebSocket - Internal implementations
+ protected abstract connectWebSocketInternal(config: WebSocketConfig): Promise<void>;
+ protected abstract subscribeInternal(symbol: string, exchange: StockExchange, mode: SubscriptionMode): Promise<void>;
+ protected abstract unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void>;
+
+ // Bulk Operations - Internal implementations
+ protected abstract cancelAllOrdersInternal(): Promise<BulkOperationResult>;
+ protected abstract closeAllPositionsInternal(): Promise<BulkOperationResult>;
+
+ // Smart Order - Internal implementation
+ protected abstract placeSmartOrderInternal(params: SmartOrderParams): Promise<OrderResponse>;
+
+ // Margin Calculator - Internal implementation
+ protected abstract calculateMarginInternal(orders: OrderParams[]): Promise<MarginRequired>;
+
+ // ============================================================================
+ // Common Authentication Methods
+ // ============================================================================
+
+ async logout(): Promise<void> {
+ this._isConnected = false;
+ this.accessToken = null;
+ this.userId = null;
+ this.credentials = null;
+
+ // Disconnect WebSocket
+ if (this.wsConnected) {
+ await this.disconnectWebSocket();
+ }
+
+ // Clear stored credentials
+ await this.clearCredentials();
+ }
+
+ async refreshSession?(): Promise<AuthResponse> {
+ // Default implementation - subclasses can override
+ if (!this.credentials) {
+ return {
+ success: false,
+ message: 'No credentials to refresh',
+ errorCode: ERROR_CODES.AUTH_FAILED,
+ };
+ }
+ return this.authenticate(this.credentials);
+ }
+
+ // ============================================================================
+ // Credential Storage (via Rust backend)
+ // ============================================================================
+
+ protected async storeCredentials(credentials: BrokerCredentials): Promise<void> {
+ try {
+ console.log(`[${this.brokerId}] storeCredentials called with:`, {
+ hasApiKey: !!credentials.apiKey,
+ hasApiSecret: !!credentials.apiSecret,
+ apiKeyLength: credentials.apiKey?.length || 0,
+ apiSecretLength: credentials.apiSecret?.length || 0,
+ apiKeyValue: credentials.apiKey ? '***' : 'undefined',
+ apiSecretValue: credentials.apiSecret ? '***' : 'undefined',
+ });
+
+ const payload = {
+ apiKey: credentials.apiKey,
+ apiSecret: credentials.apiSecret,
+ accessToken: credentials.accessToken,
+ userId: credentials.userId,
+ };
+
+ console.log(`[${this.brokerId}] Sending to Rust:`, {
+ brokerId: this.brokerId,
+ credentials: {
+ apiKey: payload.apiKey ? '***' : payload.apiKey,
+ apiSecret: payload.apiSecret ? '***' : payload.apiSecret,
+ accessToken: payload.accessToken,
+ userId: payload.userId,
+ },
+ });
+
+ await invoke('store_indian_broker_credentials', {
+ brokerId: this.brokerId,
+ credentials: payload,
+ });
+
+ console.log(`[${this.brokerId}] ✓ Credentials stored successfully`);
+ } catch (error) {
+ console.error(`[${this.brokerId}] Failed to store credentials:`, error);
+ }
+ }
+
+ protected async loadCredentials(): Promise<BrokerCredentials | null> {
+ try {
+ console.log(`[${this.brokerId}] Loading credentials from Rust backend...`);
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ apiKey?: string;
+ apiSecret?: string;
+ accessToken?: string;
+ additionalData?: string;
+ };
+ }>('get_indian_broker_credentials', {
+ brokerId: this.brokerId,
+ });
+
+ console.log(`[${this.brokerId}] Rust response:`, {
+ success: response.success,
+ hasData: !!response.data,
+ hasApiKey: !!(response.data?.apiKey),
+ hasApiSecret: !!(response.data?.apiSecret),
+ apiKeyLength: response.data?.apiKey?.length || 0,
+ });
+
+ if (!response.success || !response.data) {
+ console.warn(`[${this.brokerId}] No credentials found in response`);
+ return null;
+ }
+
+ const creds = {
+ apiKey: response.data.apiKey || '',
+ apiSecret: response.data.apiSecret,
+ accessToken: response.data.accessToken,
+ };
+
+ console.log(`[${this.brokerId}] ✓ Credentials loaded successfully`);
+ return creds;
+ } catch (error) {
+ console.error(`[${this.brokerId}] Failed to load credentials:`, error);
+ return null;
+ }
+ }
+
+ protected async clearCredentials(): Promise<void> {
+ try {
+ await invoke('delete_indian_broker_credentials', {
+ brokerId: this.brokerId,
+ });
+ } catch (error) {
+ console.error(`[${this.brokerId}] Failed to clear credentials:`, error);
+ }
+ }
+
+ // ============================================================================
+ // Rate Limiting
+ // ============================================================================
+
+ protected async rateLimit(): Promise<void> {
+ const now = Date.now();
+ const elapsed = now - this.lastApiCall;
+ const minInterval = DEFAULT_RATE_LIMITS.minRequestInterval;
+
+ if (elapsed < minInterval) {
+ await new Promise(resolve => setTimeout(resolve, minInterval - elapsed));
+ }
+
+ this.lastApiCall = Date.now();
+ }
+
+ // ============================================================================
+ // Connection Check
+ // ============================================================================
+
+ protected ensureConnected(): void {
+ if (!this.isConnected) {
+ throw new Error(`Not connected to ${this.brokerName}. Please authenticate first.`);
+ }
+ }
+
+ // ============================================================================
+ // Public Order Methods (with rate limiting and connection checks)
+ // ============================================================================
+
+ async placeOrder(params: OrderParams): Promise<OrderResponse> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.placeOrderInternal(params);
+ }
+
+ async modifyOrder(params: ModifyOrderParams): Promise<OrderResponse> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.modifyOrderInternal(params);
+ }
+
+ async cancelOrder(orderId: string): Promise<OrderResponse> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.cancelOrderInternal(orderId);
+ }
+
+ async getOrders(): Promise<Order[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.getOrdersInternal();
+ }
+
+ async getTradeBook(): Promise<Trade[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.getTradeBookInternal();
+ }
+
+ async cancelAllOrders(): Promise<BulkOperationResult> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.cancelAllOrdersInternal();
+ }
+
+ async placeSmartOrder(params: SmartOrderParams): Promise<OrderResponse> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.placeSmartOrderInternal(params);
+ }
+
+ // ============================================================================
+ // Public Position & Holdings Methods
+ // ============================================================================
+
+ async getPositions(): Promise<Position[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.getPositionsInternal();
+ }
+
+ async getHoldings(): Promise<Holding[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.getHoldingsInternal();
+ }
+
+ async getFunds(): Promise<Funds> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.getFundsInternal();
+ }
+
+ async getOpenPosition(
+ symbol: string,
+ exchange: StockExchange,
+ productType: ProductType
+ ): Promise<Position | null> {
+ const positions = await this.getPositions();
+ return positions.find(
+ p => p.symbol === symbol && p.exchange === exchange && p.productType === productType
+ ) || null;
+ }
+
+ async closeAllPositions(): Promise<BulkOperationResult> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.closeAllPositionsInternal();
+ }
+
+ // ============================================================================
+ // Public Account Methods
+ // ============================================================================
+
+ async getMarginRequired(params: OrderParams): Promise<MarginRequired> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.calculateMarginInternal([params]);
+ }
+
+ async calculateMargin(orders: OrderParams[]): Promise<MarginRequired> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.calculateMarginInternal(orders);
+ }
+
+ // ============================================================================
+ // Public Market Data Methods
+ // ============================================================================
+
+ async getQuote(symbol: string, exchange: StockExchange): Promise<Quote> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.getQuoteInternal(symbol, exchange);
+ }
+
+ async getQuotes(
+ instruments: Array<{ symbol: string; exchange: StockExchange }>
+ ): Promise<Quote[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+
+ // Default: fetch one by one (subclasses should override for batch support)
+ const quotes: Quote[] = [];
+ for (const { symbol, exchange } of instruments) {
+ try {
+ const quote = await this.getQuoteInternal(symbol, exchange);
+ quotes.push(quote);
+ } catch (error) {
+ console.error(`[${this.brokerId}] Error fetching quote for ${symbol}:`, error);
+ }
+ }
+ return quotes;
+ }
+
+ async getOHLCV(
+ symbol: string,
+ exchange: StockExchange,
+ timeframe: TimeFrame,
+ from: Date,
+ to: Date
+ ): Promise<OHLCV[]> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.getOHLCVInternal(symbol, exchange, timeframe, from, to);
+ }
+
+ async getMarketDepth(symbol: string, exchange: StockExchange): Promise<MarketDepth> {
+ this.ensureConnected();
+ await this.rateLimit();
+ return this.getMarketDepthInternal(symbol, exchange);
+ }
+
+ // ============================================================================
+ // Symbol Search (via Rust backend)
+ // ============================================================================
+
+ async searchSymbols(query: string, exchange?: StockExchange): Promise<Instrument[]> {
+ try {
+ const results = await invoke<Instrument[]>('search_indian_symbols', {
+ brokerId: this.brokerId,
+ query,
+ exchange,
+ });
+ return results;
+ } catch (error) {
+ console.error(`[${this.brokerId}] Symbol search error:`, error);
+ return [];
+ }
+ }
+
+ async getInstrument(symbol: string, exchange: StockExchange): Promise<Instrument | null> {
+ try {
+ const result = await invoke<Instrument | null>('get_indian_symbol_token', {
+ brokerId: this.brokerId,
+ symbol,
+ exchange,
+ });
+ return result;
+ } catch (error) {
+ console.error(`[${this.brokerId}] Get instrument error:`, error);
+ return null;
+ }
+ }
+
+ // ============================================================================
+ // WebSocket Methods
+ // ============================================================================
+
+ async connectWebSocket(config?: WebSocketConfig): Promise<void> {
+ this.ensureConnected();
+
+ this.wsConfig = {
+ ...WEBSOCKET_DEFAULTS,
+ ...config,
+ };
+
+ await this.connectWebSocketInternal(this.wsConfig);
+ this.wsConnected = true;
+ }
+
+ async disconnectWebSocket(): Promise<void> {
+ // Unsubscribe all
+ for (const [key, sub] of this.subscriptions) {
+ try {
+ await this.unsubscribeInternal(sub.symbol, sub.exchange);
+ } catch {
+ // Ignore errors during disconnect
+ }
+ }
+
+ this.subscriptions.clear();
+ this.wsConnected = false;
+ }
+
+ async subscribe(
+ symbol: string,
+ exchange: StockExchange,
+ mode: SubscriptionMode
+ ): Promise<void> {
+ if (!this.wsConnected) {
+ await this.connectWebSocket();
+ }
+
+ const key = `${exchange}:${symbol}`;
+ this.subscriptions.set(key, { symbol, exchange, mode });
+
+ await this.subscribeInternal(symbol, exchange, mode);
+ }
+
+ async unsubscribe(symbol: string, exchange: StockExchange): Promise<void> {
+ const key = `${exchange}:${symbol}`;
+ this.subscriptions.delete(key);
+
+ if (this.wsConnected) {
+ await this.unsubscribeInternal(symbol, exchange);
+ }
+ }
+
+ onTick(callback: (tick: TickData) => void): void {
+ this.tickCallbacks.add(callback);
+ }
+
+ offTick(callback: (tick: TickData) => void): void {
+ this.tickCallbacks.delete(callback);
+ }
+
+ protected emitTick(tick: TickData): void {
+ for (const callback of this.tickCallbacks) {
+ try {
+ callback(tick);
+ } catch (error) {
+ console.error(`[${this.brokerId}] Tick callback error:`, error);
+ }
+ }
+ }
+
+ // ============================================================================
+ // Master Contract (Optional - subclasses can override)
+ // ============================================================================
+
+ async downloadMasterContract?(): Promise<void> {
+ // Default: no-op, subclasses implement if needed
+ }
+
+ async getMasterContractLastUpdated?(): Promise<Date | null> {
+ try {
+ const timestamp = await invoke<number | null>('get_master_contract_timestamp', {
+ brokerId: this.brokerId,
+ });
+ return timestamp ? new Date(timestamp) : null;
+ } catch {
+ return null;
+ }
+ }
+
+ // ============================================================================
+ // Error Handling Helpers
+ // ============================================================================
+
+ protected handleError(error: unknown, operation: string): never {
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(`[${this.brokerId}] ${operation} failed:`, message);
+
+ throw new Error(`${operation} failed: ${message}`);
+ }
+
+ protected createErrorResponse(message: string, errorCode?: string): OrderResponse {
+ return {
+ success: false,
+ message,
+ errorCode: errorCode || ERROR_CODES.UNKNOWN_ERROR,
+ };
+ }
+}
diff --git a/fincept-terminal-desktop/src/brokers/stocks/constants.ts b/fincept-terminal-desktop/src/brokers/stocks/constants.ts
new file mode 100644
index 000000000..86af2864d
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/constants.ts
@@ -0,0 +1,210 @@
+/**
+ * Stock Broker Constants
+ *
+ * Global constants for stock trading across all regions
+ */
+
+import type { Region, Currency, MarketHours, StockExchange } from './types';
+
+// ============================================================================
+// MARKET HOURS BY REGION
+// ============================================================================
+
+export const MARKET_HOURS: Record<string, MarketHours> = {
+ // India
+ NSE: {
+ open: '09:15',
+ close: '15:30',
+ timezone: 'Asia/Kolkata',
+ preMarketOpen: '09:00',
+ preMarketClose: '09:08',
+ },
+ BSE: {
+ open: '09:15',
+ close: '15:30',
+ timezone: 'Asia/Kolkata',
+ preMarketOpen: '09:00',
+ preMarketClose: '09:08',
+ },
+ MCX: {
+ open: '09:00',
+ close: '23:30',
+ timezone: 'Asia/Kolkata',
+ },
+
+ // US
+ NYSE: {
+ open: '09:30',
+ close: '16:00',
+ timezone: 'America/New_York',
+ preMarketOpen: '04:00',
+ preMarketClose: '09:30',
+ postMarketOpen: '16:00',
+ postMarketClose: '20:00',
+ },
+ NASDAQ: {
+ open: '09:30',
+ close: '16:00',
+ timezone: 'America/New_York',
+ preMarketOpen: '04:00',
+ preMarketClose: '09:30',
+ postMarketOpen: '16:00',
+ postMarketClose: '20:00',
+ },
+
+ // Europe
+ LSE: {
+ open: '08:00',
+ close: '16:30',
+ timezone: 'Europe/London',
+ },
+ XETRA: {
+ open: '09:00',
+ close: '17:30',
+ timezone: 'Europe/Berlin',
+ },
+};
+
+// ============================================================================
+// CURRENCY BY REGION
+// ============================================================================
+
+export const REGION_CURRENCY: Record<Region, Currency> = {
+ india: 'INR',
+ us: 'USD',
+ europe: 'EUR',
+ uk: 'GBP',
+ asia: 'JPY',
+ australia: 'AUD',
+ canada: 'CAD',
+};
+
+// ============================================================================
+// EXCHANGES BY REGION
+// ============================================================================
+
+export const REGION_EXCHANGES: Record<Region, StockExchange[]> = {
+ india: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'],
+ us: ['NYSE', 'NASDAQ', 'AMEX', 'ARCA', 'BATS'],
+ europe: ['LSE', 'XETRA', 'EURONEXT', 'SIX'],
+ uk: ['LSE'],
+ asia: ['TSE', 'HKEX', 'SGX', 'KRX'],
+ australia: ['ASX'],
+ canada: ['TSX', 'TSXV'],
+};
+
+// ============================================================================
+// PRODUCT TYPE MAPPINGS
+// ============================================================================
+
+// Map standard product types to broker-specific codes
+export const PRODUCT_TYPE_MAP = {
+ india: {
+ CASH: 'CNC',
+ INTRADAY: 'MIS',
+ MARGIN: 'NRML',
+ COVER: 'CO',
+ BRACKET: 'BO',
+ },
+ us: {
+ CASH: 'CASH',
+ INTRADAY: 'DAY',
+ MARGIN: 'MARGIN',
+ },
+} as const;
+
+// ============================================================================
+// ORDER STATUS MAPPINGS
+// ============================================================================
+
+export const ORDER_STATUS_DISPLAY: Record<string, { label: string; color: string }> = {
+ PENDING: { label: 'Pending', color: 'yellow' },
+ OPEN: { label: 'Open', color: 'blue' },
+ PARTIALLY_FILLED: { label: 'Partial', color: 'cyan' },
+ FILLED: { label: 'Filled', color: 'green' },
+ CANCELLED: { label: 'Cancelled', color: 'gray' },
+ REJECTED: { label: 'Rejected', color: 'red' },
+ EXPIRED: { label: 'Expired', color: 'gray' },
+ TRIGGER_PENDING: { label: 'Trigger Pending', color: 'orange' },
+};
+
+// ============================================================================
+// ERROR CODES
+// ============================================================================
+
+export const ERROR_CODES = {
+ // Authentication
+ AUTH_FAILED: 'AUTH001',
+ TOKEN_EXPIRED: 'AUTH002',
+ INVALID_CREDENTIALS: 'AUTH003',
+
+ // Orders
+ ORDER_FAILED: 'ORD001',
+ INSUFFICIENT_MARGIN: 'ORD002',
+ INVALID_QUANTITY: 'ORD003',
+ MARKET_CLOSED: 'ORD004',
+ CIRCUIT_LIMIT: 'ORD005',
+
+ // Network
+ NETWORK_ERROR: 'NET001',
+ TIMEOUT: 'NET002',
+ RATE_LIMIT: 'NET003',
+
+ // General
+ UNKNOWN_ERROR: 'ERR999',
+} as const;
+
+export const ERROR_MESSAGES: Record<string, string> = {
+ [ERROR_CODES.AUTH_FAILED]: 'Authentication failed',
+ [ERROR_CODES.TOKEN_EXPIRED]: 'Session expired. Please login again.',
+ [ERROR_CODES.INVALID_CREDENTIALS]: 'Invalid credentials',
+ [ERROR_CODES.ORDER_FAILED]: 'Order placement failed',
+ [ERROR_CODES.INSUFFICIENT_MARGIN]: 'Insufficient margin for this order',
+ [ERROR_CODES.INVALID_QUANTITY]: 'Invalid quantity',
+ [ERROR_CODES.MARKET_CLOSED]: 'Market is closed',
+ [ERROR_CODES.CIRCUIT_LIMIT]: 'Price is at circuit limit',
+ [ERROR_CODES.NETWORK_ERROR]: 'Network error. Please check your connection.',
+ [ERROR_CODES.TIMEOUT]: 'Request timed out',
+ [ERROR_CODES.RATE_LIMIT]: 'Rate limit exceeded. Please try again.',
+ [ERROR_CODES.UNKNOWN_ERROR]: 'An unknown error occurred',
+};
+
+// ============================================================================
+// TIMEFRAME MAPPINGS
+// ============================================================================
+
+export const TIMEFRAME_LABELS: Record<string, string> = {
+ '1m': '1 Min',
+ '3m': '3 Min',
+ '5m': '5 Min',
+ '10m': '10 Min',
+ '15m': '15 Min',
+ '30m': '30 Min',
+ '1h': '1 Hour',
+ '2h': '2 Hour',
+ '4h': '4 Hour',
+ '1d': 'Daily',
+ '1w': 'Weekly',
+ '1M': 'Monthly',
+};
+
+// ============================================================================
+// RATE LIMITING
+// ============================================================================
+
+export const DEFAULT_RATE_LIMITS = {
+ ordersPerSecond: 10,
+ quotesPerSecond: 5,
+ minRequestInterval: 100, // ms between requests
+};
+
+// ============================================================================
+// WEBSOCKET DEFAULTS
+// ============================================================================
+
+export const WEBSOCKET_DEFAULTS = {
+ autoReconnect: true,
+ reconnectInterval: 5000,
+ maxReconnectAttempts: 5,
+ heartbeatInterval: 30000,
+};
diff --git a/fincept-terminal-desktop/src/brokers/stocks/index.ts b/fincept-terminal-desktop/src/brokers/stocks/index.ts
new file mode 100644
index 000000000..262c6bdd8
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/index.ts
@@ -0,0 +1,37 @@
+/**
+ * Stock Brokers Module
+ *
+ * Unified exports for all stock broker functionality
+ */
+
+// Types
+export * from './types';
+
+// Constants
+export * from './constants';
+
+// Base Adapter
+export { BaseStockBrokerAdapter } from './BaseStockBrokerAdapter';
+
+// Registry
+export {
+ STOCK_BROKER_REGISTRY,
+ registerBrokerAdapter,
+ createStockBrokerAdapter,
+ getAllStockBrokers,
+ getStockBrokersByRegion,
+ getStockBrokerMetadata,
+ isStockBrokerRegistered,
+ getStockBrokerDisplayName,
+ getStockBrokerDefaultSymbols,
+ stockBrokerSupportsFeature,
+ stockBrokerSupportsTradingFeature,
+ getAvailableRegions,
+ getStockBrokersWithFeature,
+} from './registry';
+
+// Initialization
+export { initializeStockBrokers } from './init';
+
+// Indian Brokers
+export * from './india';
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.ts
new file mode 100644
index 000000000..e51ac27fd
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.ts
@@ -0,0 +1,1134 @@
+/**
+ * Angel One Stock Broker Adapter
+ *
+ * Implements IStockBrokerAdapter for Angel One Smart API
+ * Based on OpenAlgo broker integration patterns
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+import { listen, UnlistenFn } from '@tauri-apps/api/event';
+import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';
+import type {
+ StockBrokerMetadata,
+ Region,
+ BrokerCredentials,
+ AuthResponse,
+ AuthCallbackParams,
+ Funds,
+ MarginRequired,
+ OrderParams,
+ OrderResponse,
+ ModifyOrderParams,
+ Order,
+ Trade,
+ Position,
+ Holding,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ TimeFrame,
+ StockExchange,
+ WebSocketConfig,
+ SubscriptionMode,
+ BulkOperationResult,
+ SmartOrderParams,
+ TickData,
+ Instrument,
+ ProductType,
+} from '../../types';
+import {
+ ANGELONE_METADATA,
+ ANGELONE_API_BASE_URL,
+ ANGELONE_ENDPOINTS,
+ ANGELONE_EXCHANGE_MAP,
+ ANGELONE_INTERVAL_LIMITS,
+ getAngelOneHeaders,
+} from './constants';
+import {
+ toAngelOneOrderParams,
+ toAngelOneModifyParams,
+ toAngelOneInterval,
+ toAngelOneWSMode,
+ fromAngelOneOrder,
+ fromAngelOneTrade,
+ fromAngelOnePosition,
+ fromAngelOneHolding,
+ fromAngelOneFunds,
+ fromAngelOneQuote,
+ fromAngelOneOHLCV,
+ fromAngelOneDepth,
+ fromAngelOneTick,
+} from './mapper';
+
+/**
+ * Angel One broker adapter
+ */
+export class AngelOneAdapter extends BaseStockBrokerAdapter {
+ readonly brokerId = 'angelone';
+ readonly brokerName = 'Angel One';
+ readonly region: Region = 'india';
+ readonly metadata: StockBrokerMetadata = ANGELONE_METADATA;
+
+ private apiKey: string | null = null;
+ private clientCode: string | null = null;
+ private totpSecret: string | null = null;
+ private password: string | null = null;
+ private feedToken: string | null = null;
+
+ // REST API polling for quotes
+ private quotePollingInterval: NodeJS.Timeout | null = null;
+ private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();
+
+ // Token to symbol mapping
+ private tokenSymbolMap: Map<string, { symbol: string; exchange: StockExchange }> = new Map();
+
+ // Tauri event unlisteners
+ private eventUnlisteners: UnlistenFn[] = [];
+
+ // ============================================================================
+ // Authentication
+ // ============================================================================
+
+ /**
+ * Set API credentials before authentication
+ */
+ setCredentials(apiKey: string, apiSecret: string): void {
+ this.apiKey = apiKey;
+ // apiSecret can be used for TOTP or other purposes
+ }
+
+ /**
+ * Authenticate with Angel One
+ * Requires: apiKey, clientCode (userId), password, and TOTP
+ */
+ async authenticate(credentials: BrokerCredentials): Promise<AuthResponse> {
+ try {
+ this.apiKey = credentials.apiKey;
+ this.clientCode = credentials.userId || null;
+ this.password = credentials.password || null;
+ this.totpSecret = credentials.totpSecret || null;
+
+ // If access token provided, validate it
+ if (credentials.accessToken) {
+ console.log('[AngelOne] Access token provided, validating...');
+ const isValid = await this.validateToken(credentials.accessToken);
+ if (isValid) {
+ this.accessToken = credentials.accessToken;
+ this.userId = credentials.userId || null;
+ this._isConnected = true;
+
+ await this.storeCredentials(credentials);
+
+ return {
+ success: true,
+ accessToken: this.accessToken,
+ userId: this.userId || undefined,
+ message: 'Authentication successful',
+ };
+ } else {
+ console.error('[AngelOne] Access token validation failed');
+ return {
+ success: false,
+ message: 'Invalid or expired access token',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+ }
+
+ // Need client code, password, and TOTP for login
+ if (!this.clientCode || !this.password) {
+ return {
+ success: false,
+ message: 'Client code and password are required',
+ errorCode: 'AUTH_REQUIRED',
+ };
+ }
+
+ // Perform login via Rust backend
+ const response = await invoke<{
+ success: boolean;
+ access_token?: string;
+ refresh_token?: string;
+ feed_token?: string;
+ user_id?: string;
+ error?: string;
+ }>('angelone_login', {
+ apiKey: this.apiKey,
+ clientCode: this.clientCode,
+ password: this.password,
+ totp: credentials.pin || '', // TOTP can be passed as pin
+ });
+
+ if (!response.success || !response.access_token) {
+ return {
+ success: false,
+ message: response.error || 'Login failed',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+
+ this.accessToken = response.access_token;
+ this.feedToken = response.feed_token || null;
+ this.userId = response.user_id || this.clientCode;
+ this._isConnected = true;
+
+ // Store credentials
+ await this.storeCredentials({
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken,
+ refreshToken: response.refresh_token,
+ userId: this.userId || undefined,
+ });
+
+ return {
+ success: true,
+ accessToken: this.accessToken,
+ refreshToken: response.refresh_token,
+ userId: this.userId || undefined,
+ message: 'Authentication successful',
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Authentication failed',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+ }
+
+ /**
+ * Handle auth callback (not typically used for Angel One as it uses TOTP)
+ */
+ async handleAuthCallback(params: AuthCallbackParams): Promise<AuthResponse> {
+ // Angel One doesn't use OAuth callback, but we implement for interface compliance
+ return {
+ success: false,
+ message: 'Angel One uses TOTP authentication, not OAuth callback',
+ errorCode: 'NOT_SUPPORTED',
+ };
+ }
+
+ /**
+ * Validate access token
+ */
+ private async validateToken(token: string): Promise<boolean> {
+ try {
+ const response = await invoke<{ success: boolean }>('angelone_validate_token', {
+ apiKey: this.apiKey,
+ accessToken: token,
+ });
+ return response.success;
+ } catch {
+ return false;
+ }
+ }
+
+ /**
+ * Initialize from stored credentials
+ */
+ async initFromStorage(): Promise<boolean> {
+ try {
+ const credentials = await this.loadCredentials();
+ if (!credentials) return false;
+
+ this.apiKey = credentials.apiKey;
+ this.accessToken = credentials.accessToken || null;
+ this.userId = credentials.userId || null;
+
+ if (this.accessToken) {
+ console.log('[AngelOne] Validating stored access token...');
+ const isValid = await this.validateToken(this.accessToken);
+
+ if (!isValid) {
+ console.warn('[AngelOne] Access token expired or invalid');
+ this.accessToken = null;
+ this._isConnected = false;
+ return false;
+ }
+
+ console.log('[AngelOne] Token is valid, session restored');
+ this._isConnected = true;
+ return true;
+ }
+
+ return false;
+ } catch {
+ return false;
+ }
+ }
+
+ /**
+ * Refresh session (generate new token using refresh token)
+ */
+ async refreshSession(): Promise<AuthResponse> {
+ try {
+ const response = await invoke<{
+ success: boolean;
+ access_token?: string;
+ error?: string;
+ }>('angelone_refresh_token', {
+ apiKey: this.apiKey,
+ refreshToken: this.accessToken, // Using stored token
+ });
+
+ if (!response.success || !response.access_token) {
+ return {
+ success: false,
+ message: response.error || 'Token refresh failed',
+ errorCode: 'REFRESH_FAILED',
+ };
+ }
+
+ this.accessToken = response.access_token;
+ this._isConnected = true;
+
+ return {
+ success: true,
+ accessToken: this.accessToken,
+ message: 'Session refreshed',
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Refresh failed',
+ errorCode: 'REFRESH_FAILED',
+ };
+ }
+ }
+
+ // ============================================================================
+ // Orders
+ // ============================================================================
+
+ protected async placeOrderInternal(params: OrderParams): Promise<OrderResponse> {
+ // Get symbol token first
+ const instrument = await this.getInstrument(params.symbol, params.exchange);
+ const symbolToken = instrument?.token || '0';
+
+ const angelParams = toAngelOneOrderParams(params, symbolToken);
+
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('angelone_place_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ params: angelParams,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ protected async modifyOrderInternal(params: ModifyOrderParams): Promise<OrderResponse> {
+ // Get original order info for modify
+ const orders = await this.getOrders();
+ const originalOrder = orders.find(o => o.orderId === params.orderId);
+
+ if (!originalOrder) {
+ return {
+ success: false,
+ message: 'Original order not found',
+ errorCode: 'ORDER_NOT_FOUND',
+ };
+ }
+
+ const instrument = await this.getInstrument(originalOrder.symbol, originalOrder.exchange);
+ const symbolToken = instrument?.token || '0';
+
+ const angelParams = toAngelOneModifyParams(params.orderId, params, {
+ symbol: originalOrder.symbol,
+ exchange: originalOrder.exchange,
+ symbolToken,
+ });
+
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('angelone_modify_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ params: angelParams,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ protected async cancelOrderInternal(orderId: string): Promise<OrderResponse> {
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('angelone_cancel_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ orderId,
+ variety: 'NORMAL',
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ protected async getOrdersInternal(): Promise<Order[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>[];
+ error?: string;
+ }>('angelone_get_order_book', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(fromAngelOneOrder);
+ }
+
+ protected async getTradeBookInternal(): Promise<Trade[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>[];
+ error?: string;
+ }>('angelone_get_trade_book', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(fromAngelOneTrade);
+ }
+
+ // ============================================================================
+ // Bulk Operations
+ // ============================================================================
+
+ protected async cancelAllOrdersInternal(): Promise<BulkOperationResult> {
+ // Get all open orders
+ const orders = await this.getOrders();
+ const openOrders = orders.filter(o =>
+ o.status === 'OPEN' || o.status === 'PENDING' || o.status === 'TRIGGER_PENDING'
+ );
+
+ if (openOrders.length === 0) {
+ return {
+ success: true,
+ totalCount: 0,
+ successCount: 0,
+ failedCount: 0,
+ results: [],
+ };
+ }
+
+ const results: Array<{ success: boolean; orderId?: string; error?: string }> = [];
+
+ for (const order of openOrders) {
+ try {
+ const response = await this.cancelOrder(order.orderId);
+ results.push({
+ success: response.success,
+ orderId: order.orderId,
+ error: response.message,
+ });
+ } catch (error) {
+ results.push({
+ success: false,
+ orderId: order.orderId,
+ error: error instanceof Error ? error.message : 'Cancel failed',
+ });
+ }
+ }
+
+ return {
+ success: true,
+ totalCount: results.length,
+ successCount: results.filter(r => r.success).length,
+ failedCount: results.filter(r => !r.success).length,
+ results,
+ };
+ }
+
+ protected async closeAllPositionsInternal(): Promise<BulkOperationResult> {
+ // Get all open positions
+ const positions = await this.getPositions();
+ const openPositions = positions.filter(p => p.quantity !== 0);
+
+ if (openPositions.length === 0) {
+ return {
+ success: true,
+ totalCount: 0,
+ successCount: 0,
+ failedCount: 0,
+ results: [],
+ };
+ }
+
+ const results: Array<{ success: boolean; orderId?: string; symbol?: string; error?: string }> = [];
+
+ for (const position of openPositions) {
+ try {
+ // Determine action based on position
+ const action = position.quantity > 0 ? 'SELL' : 'BUY';
+ const quantity = Math.abs(position.quantity);
+
+ const response = await this.placeOrder({
+ symbol: position.symbol,
+ exchange: position.exchange,
+ side: action,
+ quantity,
+ orderType: 'MARKET',
+ productType: position.productType,
+ });
+
+ results.push({
+ success: response.success,
+ orderId: response.orderId,
+ symbol: position.symbol,
+ error: response.message,
+ });
+ } catch (error) {
+ results.push({
+ success: false,
+ symbol: position.symbol,
+ error: error instanceof Error ? error.message : 'Close failed',
+ });
+ }
+ }
+
+ return {
+ success: true,
+ totalCount: results.length,
+ successCount: results.filter(r => r.success).length,
+ failedCount: results.filter(r => !r.success).length,
+ results,
+ };
+ }
+
+ // ============================================================================
+ // Smart Order
+ // ============================================================================
+
+ protected async placeSmartOrderInternal(params: SmartOrderParams): Promise<OrderResponse> {
+ // Get current position size if not provided
+ let positionSize = params.positionSize ?? 0;
+ if (params.positionSize === undefined) {
+ const position = await this.getOpenPosition(params.symbol, params.exchange, params.productType);
+ positionSize = position?.quantity ?? 0;
+ }
+
+ // If both position_size and current_position are 0, place regular order
+ if (positionSize === 0 && params.quantity !== 0) {
+ return this.placeOrder(params);
+ }
+
+ // If position matches desired size, no action needed
+ if (positionSize === params.positionSize) {
+ return {
+ success: true,
+ message: params.quantity === 0
+ ? 'No open position found. Not placing exit order.'
+ : 'No action needed. Position size matches current position',
+ };
+ }
+
+ // Calculate action and quantity needed
+ let action: 'BUY' | 'SELL';
+ let quantity: number;
+
+ const targetPosition = params.positionSize ?? (params.side === 'BUY' ? params.quantity : -params.quantity);
+
+ if (targetPosition === 0) {
+ // Close position
+ action = positionSize > 0 ? 'SELL' : 'BUY';
+ quantity = Math.abs(positionSize);
+ } else if (positionSize === 0) {
+ // Open new position
+ action = targetPosition > 0 ? 'BUY' : 'SELL';
+ quantity = Math.abs(targetPosition);
+ } else if (targetPosition > positionSize) {
+ action = 'BUY';
+ quantity = targetPosition - positionSize;
+ } else {
+ action = 'SELL';
+ quantity = positionSize - targetPosition;
+ }
+
+ return this.placeOrder({
+ ...params,
+ side: action,
+ quantity,
+ });
+ }
+
+ // ============================================================================
+ // Positions & Holdings
+ // ============================================================================
+
+ protected async getPositionsInternal(): Promise<Position[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>[];
+ error?: string;
+ }>('angelone_get_positions', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(fromAngelOnePosition);
+ }
+
+ protected async getHoldingsInternal(): Promise<Holding[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ holdings?: Record<string, unknown>[];
+ };
+ error?: string;
+ }>('angelone_get_holdings', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data?.holdings) {
+ return [];
+ }
+
+ return response.data.holdings.map(fromAngelOneHolding);
+ }
+
+ protected async getFundsInternal(): Promise<Funds> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ }>('angelone_get_rms', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ availableCash: 0,
+ usedMargin: 0,
+ availableMargin: 0,
+ totalBalance: 0,
+ currency: 'INR',
+ };
+ }
+
+ return fromAngelOneFunds(response.data);
+ }
+
+ // ============================================================================
+ // Margin Calculator
+ // ============================================================================
+
+ protected async calculateMarginInternal(orders: OrderParams[]): Promise<MarginRequired> {
+ // Angel One margin calculation via batch endpoint
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ }>('angelone_calculate_margin', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ orders: orders.map(o => ({
+ symbol: o.symbol,
+ exchange: o.exchange,
+ quantity: o.quantity,
+ price: o.price || 0,
+ productType: o.productType,
+ transactionType: o.side,
+ })),
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ totalMargin: 0,
+ initialMargin: 0,
+ };
+ }
+
+ const data = response.data;
+ return {
+ totalMargin: Number(data.totalMarginRequired || 0),
+ initialMargin: Number(data.spanMargin || data.totalMarginRequired || 0),
+ exposureMargin: Number(data.exposureMargin || 0),
+ orders: orders.map(o => ({
+ symbol: o.symbol,
+ margin: Number(data.totalMarginRequired || 0) / orders.length,
+ })),
+ };
+ }
+
+ // ============================================================================
+ // Market Data
+ // ============================================================================
+
+ protected async getQuoteInternal(symbol: string, exchange: StockExchange): Promise<Quote> {
+ // Get token for the symbol
+ const instrument = await this.getInstrument(symbol, exchange);
+ const token = instrument?.token || '0';
+
+ // Normalize exchange for index symbols
+ let apiExchange = ANGELONE_EXCHANGE_MAP[exchange] || exchange;
+ if (exchange === 'NSE_INDEX') apiExchange = 'NSE';
+ if (exchange === 'BSE_INDEX') apiExchange = 'BSE';
+ if (exchange === 'MCX_INDEX') apiExchange = 'MCX';
+
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ fetched?: Record<string, unknown>[];
+ };
+ error?: string;
+ }>('angelone_get_quote', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ exchange: apiExchange,
+ tokens: [token],
+ });
+
+ if (!response.success || !response.data?.fetched?.[0]) {
+ throw new Error(response.error || 'Failed to fetch quote');
+ }
+
+ return fromAngelOneQuote(response.data.fetched[0], symbol, exchange);
+ }
+
+ /**
+ * Get multiple quotes (with automatic batching - max 50 per request)
+ */
+ async getMultiQuotes(
+ symbols: Array<{ symbol: string; exchange: StockExchange }>
+ ): Promise<Array<{ symbol: string; exchange: StockExchange; quote?: Quote; error?: string }>> {
+ this.ensureConnected();
+
+ const BATCH_SIZE = 50;
+ const RATE_LIMIT_DELAY = 1000; // 1 second between batches
+ const results: Array<{ symbol: string; exchange: StockExchange; quote?: Quote; error?: string }> = [];
+
+ // Build token map
+ const symbolMap: Map<string, { symbol: string; exchange: StockExchange }> = new Map();
+
+ for (let i = 0; i < symbols.length; i += BATCH_SIZE) {
+ const batch = symbols.slice(i, i + BATCH_SIZE);
+
+ // Group by exchange
+ const exchangeGroups: Map<string, string[]> = new Map();
+
+ for (const { symbol, exchange } of batch) {
+ try {
+ const instrument = await this.getInstrument(symbol, exchange);
+ const token = instrument?.token || '0';
+
+ let apiExchange = ANGELONE_EXCHANGE_MAP[exchange] || exchange;
+ if (exchange === 'NSE_INDEX') apiExchange = 'NSE';
+ if (exchange === 'BSE_INDEX') apiExchange = 'BSE';
+
+ if (!exchangeGroups.has(apiExchange)) {
+ exchangeGroups.set(apiExchange, []);
+ }
+ exchangeGroups.get(apiExchange)!.push(token);
+ symbolMap.set(`${apiExchange}:${token}`, { symbol, exchange });
+ } catch (error) {
+ results.push({
+ symbol,
+ exchange,
+ error: 'Failed to resolve token',
+ });
+ }
+ }
+
+ // Fetch quotes for each exchange group
+ for (const [apiExchange, tokens] of exchangeGroups) {
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ fetched?: Record<string, unknown>[];
+ };
+ error?: string;
+ }>('angelone_get_quote', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ exchange: apiExchange,
+ tokens,
+ });
+
+ if (response.success && response.data?.fetched) {
+ for (const quoteData of response.data.fetched) {
+ const token = String(quoteData.symbolToken || '');
+ const key = `${apiExchange}:${token}`;
+ const symbolInfo = symbolMap.get(key);
+
+ if (symbolInfo) {
+ try {
+ const quote = fromAngelOneQuote(quoteData, symbolInfo.symbol, symbolInfo.exchange);
+ results.push({ ...symbolInfo, quote });
+ } catch (err) {
+ results.push({ ...symbolInfo, error: 'Parse error' });
+ }
+ }
+ }
+ }
+ } catch (error) {
+ console.error(`[AngelOne] Quote batch error for ${apiExchange}:`, error);
+ }
+ }
+
+ // Rate limit delay between batches
+ if (i + BATCH_SIZE < symbols.length) {
+ await new Promise(resolve => setTimeout(resolve, RATE_LIMIT_DELAY));
+ }
+ }
+
+ return results;
+ }
+
+ protected async getOHLCVInternal(
+ symbol: string,
+ exchange: StockExchange,
+ timeframe: TimeFrame,
+ from: Date,
+ to: Date
+ ): Promise<OHLCV[]> {
+ // Get instrument token
+ const instrument = await this.getInstrument(symbol, exchange);
+ const token = instrument?.token || '0';
+
+ const interval = toAngelOneInterval(timeframe);
+ const chunkDays = ANGELONE_INTERVAL_LIMITS[timeframe] || 30;
+
+ const allCandles: OHLCV[] = [];
+ let currentStart = new Date(from);
+ const endDate = new Date(to);
+
+ // Normalize exchange
+ let apiExchange = ANGELONE_EXCHANGE_MAP[exchange] || exchange;
+ if (exchange === 'NSE_INDEX') apiExchange = 'NSE';
+ if (exchange === 'BSE_INDEX') apiExchange = 'BSE';
+
+ while (currentStart <= endDate) {
+ const currentEnd = new Date(currentStart);
+ currentEnd.setDate(currentEnd.getDate() + chunkDays - 1);
+ if (currentEnd > endDate) currentEnd.setTime(endDate.getTime());
+
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown[][];
+ error?: string;
+ }>('angelone_get_historical', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ exchange: apiExchange,
+ symbolToken: token,
+ interval,
+ fromDate: currentStart.toISOString().replace('T', ' ').slice(0, 16),
+ toDate: currentEnd.toISOString().replace('T', ' ').slice(0, 16),
+ });
+
+ if (response.success && response.data) {
+ const candles = response.data.map(fromAngelOneOHLCV);
+ allCandles.push(...candles);
+ }
+
+ currentStart.setDate(currentEnd.getDate() + 1);
+
+ // Rate limit delay
+ if (currentStart <= endDate) {
+ await new Promise(resolve => setTimeout(resolve, 500));
+ }
+ } catch (error) {
+ console.error(`[AngelOne] OHLCV chunk error:`, error);
+ currentStart.setDate(currentEnd.getDate() + 1);
+ }
+ }
+
+ // Sort and dedupe
+ return allCandles
+ .sort((a, b) => a.timestamp - b.timestamp)
+ .filter((c, i, arr) => i === 0 || c.timestamp !== arr[i - 1].timestamp);
+ }
+
+ protected async getMarketDepthInternal(symbol: string, exchange: StockExchange): Promise<MarketDepth> {
+ try {
+ const quote = await this.getQuote(symbol, exchange);
+ // Quote includes depth data from the full quote mode
+ // We need to fetch with depth mode
+ const instrument = await this.getInstrument(symbol, exchange);
+ const token = instrument?.token || '0';
+
+ let apiExchange = ANGELONE_EXCHANGE_MAP[exchange] || exchange;
+ if (exchange === 'NSE_INDEX') apiExchange = 'NSE';
+ if (exchange === 'BSE_INDEX') apiExchange = 'BSE';
+
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ fetched?: Record<string, unknown>[];
+ };
+ error?: string;
+ }>('angelone_get_quote', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ exchange: apiExchange,
+ tokens: [token],
+ mode: 'FULL',
+ });
+
+ if (!response.success || !response.data?.fetched?.[0]) {
+ return { bids: [], asks: [] };
+ }
+
+ const quoteData = response.data.fetched[0];
+ if (quoteData.depth) {
+ return fromAngelOneDepth(quoteData.depth as Record<string, unknown>);
+ }
+
+ return { bids: [], asks: [] };
+ } catch {
+ return { bids: [], asks: [] };
+ }
+ }
+
+ // ============================================================================
+ // WebSocket / Polling
+ // ============================================================================
+
+ protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {
+ this.ensureConnected();
+
+ try {
+ // Start REST API polling (Angel One rate limit: 1 req/sec)
+ this.startQuotePolling();
+ this.wsConnected = true;
+ console.log('[AngelOne] REST API polling started');
+ } catch (error) {
+ console.error('[AngelOne] Failed to start polling:', error);
+ throw error;
+ }
+ }
+
+ private startQuotePolling(): void {
+ this.stopQuotePolling();
+
+ // Poll every 2 minutes (to stay within rate limits)
+ this.quotePollingInterval = setInterval(async () => {
+ await this.pollQuotesSequentially();
+ }, 120000);
+
+ // Initial poll
+ this.pollQuotesSequentially();
+ }
+
+ private stopQuotePolling(): void {
+ if (this.quotePollingInterval) {
+ clearInterval(this.quotePollingInterval);
+ this.quotePollingInterval = null;
+ }
+ }
+
+ private async pollQuotesSequentially(): Promise<void> {
+ if (this.pollingSymbols.size === 0) return;
+
+ console.log(`[AngelOne] Polling ${this.pollingSymbols.size} symbols...`);
+
+ for (const [key, { symbol, exchange }] of this.pollingSymbols) {
+ try {
+ const quote = await this.getQuoteInternal(symbol, exchange);
+
+ const tick: TickData = {
+ symbol,
+ exchange,
+ lastPrice: quote.lastPrice,
+ open: quote.open,
+ high: quote.high,
+ low: quote.low,
+ close: quote.close,
+ volume: quote.volume,
+ change: quote.change,
+ changePercent: quote.changePercent,
+ timestamp: quote.timestamp,
+ bid: quote.bid,
+ bidQty: quote.bidQty,
+ ask: quote.ask,
+ askQty: quote.askQty,
+ mode: 'full',
+ };
+
+ this.emitTick(tick);
+ } catch (error) {
+ console.error(`[AngelOne] Poll error for ${symbol}:`, error);
+ }
+
+ // Rate limit: 1 second between requests
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ }
+
+ console.log(`[AngelOne] Polling complete`);
+ }
+
+ async disconnectWebSocket(): Promise<void> {
+ this.stopQuotePolling();
+ this.pollingSymbols.clear();
+ this.wsConnected = false;
+ console.log('[AngelOne] Polling stopped');
+ }
+
+ protected async subscribeInternal(
+ symbol: string,
+ exchange: StockExchange,
+ mode: SubscriptionMode
+ ): Promise<void> {
+ const key = `${exchange}:${symbol}`;
+ this.pollingSymbols.set(key, { symbol, exchange });
+ console.log(`[AngelOne] Added ${key} to polling (${this.pollingSymbols.size} total)`);
+
+ // Trigger immediate poll
+ this.pollQuotesSequentially();
+ }
+
+ protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {
+ const key = `${exchange}:${symbol}`;
+ this.pollingSymbols.delete(key);
+ console.log(`[AngelOne] Removed ${key} from polling`);
+ }
+
+ // ============================================================================
+ // Symbol Search
+ // ============================================================================
+
+ async searchSymbols(query: string, exchange?: StockExchange): Promise<Instrument[]> {
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: Array<Record<string, unknown>>;
+ error?: string;
+ }>('angelone_search_symbols', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ query,
+ exchange: exchange || null,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(item => ({
+ symbol: String(item.symbol || item.tradingsymbol || ''),
+ exchange: String(item.exchange || 'NSE') as StockExchange,
+ name: String(item.name || item.symbol || ''),
+ token: String(item.symboltoken || item.token || '0'),
+ lotSize: Number(item.lotsize || 1),
+ tickSize: Number(item.ticksize || 0.05),
+ instrumentType: String(item.instrumenttype || 'EQ') as any,
+ currency: 'INR',
+ expiry: item.expiry ? String(item.expiry) : undefined,
+ strike: item.strike ? Number(item.strike) : undefined,
+ }));
+ } catch (error) {
+ console.error('[AngelOne] searchSymbols error:', error);
+ return [];
+ }
+ }
+
+ async getInstrument(symbol: string, exchange: StockExchange): Promise<Instrument | null> {
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ }>('angelone_get_instrument', {
+ apiKey: this.apiKey,
+ symbol,
+ exchange,
+ });
+
+ if (!response.success || !response.data) {
+ // Return fallback
+ return {
+ symbol,
+ exchange,
+ name: symbol,
+ token: '0',
+ lotSize: 1,
+ tickSize: 0.05,
+ instrumentType: 'EQUITY',
+ currency: 'INR',
+ };
+ }
+
+ const data = response.data;
+ return {
+ symbol: String(data.symbol || data.tradingsymbol || symbol),
+ exchange: String(data.exchange || exchange) as StockExchange,
+ name: String(data.name || symbol),
+ token: String(data.symboltoken || data.token || '0'),
+ lotSize: Number(data.lotsize || 1),
+ tickSize: Number(data.ticksize || 0.05),
+ instrumentType: String(data.instrumenttype || 'EQ') as any,
+ currency: 'INR',
+ expiry: data.expiry ? String(data.expiry) : undefined,
+ strike: data.strike ? Number(data.strike) : undefined,
+ };
+ } catch (error) {
+ console.error('[AngelOne] getInstrument error:', error);
+ return {
+ symbol,
+ exchange,
+ name: symbol,
+ token: '0',
+ lotSize: 1,
+ tickSize: 0.05,
+ instrumentType: 'EQUITY',
+ currency: 'INR',
+ };
+ }
+ }
+
+ // ============================================================================
+ // Master Contract
+ // ============================================================================
+
+ async downloadMasterContract(): Promise<void> {
+ await invoke('angelone_download_master_contract', {
+ apiKey: this.apiKey,
+ });
+ }
+
+ async getMasterContractLastUpdated(): Promise<Date | null> {
+ try {
+ const response = await invoke<{ timestamp?: number }>('angelone_master_contract_info');
+ return response.timestamp ? new Date(response.timestamp) : null;
+ } catch {
+ return null;
+ }
+ }
+}
+
+// Export singleton instance
+export const angelOneAdapter = new AngelOneAdapter();
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/constants.ts b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/constants.ts
new file mode 100644
index 000000000..7c8f6fb95
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/constants.ts
@@ -0,0 +1,287 @@
+/**
+ * Angel One (AngelBroking) Constants
+ *
+ * API endpoints, mappings, and configuration for Angel One Smart API
+ * Based on OpenAlgo broker integration patterns
+ */
+
+import type { StockBrokerMetadata } from '../../types';
+
+// ============================================================================
+// API CONFIGURATION
+// ============================================================================
+
+export const ANGELONE_API_BASE_URL = 'https://apiconnect.angelbroking.com';
+export const ANGELONE_LOGIN_URL = 'https://smartapi.angelbroking.com/publisher-login';
+export const ANGELONE_API_VERSION = 'v1';
+
+export const ANGELONE_ENDPOINTS = {
+ // Auth
+ LOGIN: '/rest/auth/angelbroking/user/v1/loginByPassword',
+ GENERATE_TOKEN: '/rest/auth/angelbroking/user/v1/generateToken',
+ LOGOUT: '/rest/secure/angelbroking/user/v1/logout',
+ GET_PROFILE: '/rest/secure/angelbroking/user/v1/getProfile',
+
+ // Orders
+ PLACE_ORDER: '/rest/secure/angelbroking/order/v1/placeOrder',
+ MODIFY_ORDER: '/rest/secure/angelbroking/order/v1/modifyOrder',
+ CANCEL_ORDER: '/rest/secure/angelbroking/order/v1/cancelOrder',
+ ORDER_BOOK: '/rest/secure/angelbroking/order/v1/getOrderBook',
+ TRADE_BOOK: '/rest/secure/angelbroking/order/v1/getTradeBook',
+
+ // Portfolio
+ POSITIONS: '/rest/secure/angelbroking/order/v1/getPosition',
+ HOLDINGS: '/rest/secure/angelbroking/portfolio/v1/getAllHolding',
+
+ // Account
+ RMS: '/rest/secure/angelbroking/user/v1/getRMS',
+
+ // Market Data
+ QUOTE: '/rest/secure/angelbroking/market/v1/quote/',
+ LTP: '/rest/secure/angelbroking/order/v1/getLtpData',
+ HISTORICAL: '/rest/secure/angelbroking/historical/v1/getCandleData',
+ OI_DATA: '/rest/secure/angelbroking/historical/v1/getOIData',
+
+ // Search
+ SEARCH: '/rest/secure/angelbroking/order/v1/searchScrip',
+
+ // Margin
+ MARGIN: '/rest/secure/angelbroking/margin/v1/batch',
+} as const;
+
+// ============================================================================
+// WEBSOCKET CONFIGURATION
+// ============================================================================
+
+export const ANGELONE_WS_URL = 'wss://smartapisocket.angelone.in/smart-stream';
+
+// ============================================================================
+// EXCHANGE MAPPINGS
+// ============================================================================
+
+export const ANGELONE_EXCHANGE_MAP: Record<string, string> = {
+ NSE: 'NSE',
+ BSE: 'BSE',
+ NFO: 'NFO',
+ BFO: 'BFO',
+ CDS: 'CDS',
+ MCX: 'MCX',
+ NSE_INDEX: 'NSE',
+ BSE_INDEX: 'BSE',
+ MCX_INDEX: 'MCX',
+};
+
+// Exchange segment codes for WebSocket
+export const ANGELONE_EXCHANGE_SEGMENTS: Record<string, number> = {
+ NSE: 1, // NSE Cash
+ NFO: 2, // NSE F&O
+ BSE: 3, // BSE Cash
+ BFO: 4, // BSE F&O
+ MCX: 5, // MCX
+ CDS: 7, // Currency
+};
+
+// ============================================================================
+// PRODUCT TYPE MAPPINGS
+// ============================================================================
+
+// OpenAlgo/Fincept -> Angel One
+export const ANGELONE_PRODUCT_MAP: Record<string, string> = {
+ CASH: 'DELIVERY',
+ CNC: 'DELIVERY',
+ INTRADAY: 'INTRADAY',
+ MIS: 'INTRADAY',
+ MARGIN: 'CARRYFORWARD',
+ NRML: 'CARRYFORWARD',
+};
+
+// Angel One -> OpenAlgo/Fincept
+export const ANGELONE_PRODUCT_REVERSE_MAP: Record<string, string> = {
+ DELIVERY: 'CASH',
+ INTRADAY: 'INTRADAY',
+ CARRYFORWARD: 'MARGIN',
+};
+
+// ============================================================================
+// ORDER TYPE MAPPINGS
+// ============================================================================
+
+// OpenAlgo/Fincept -> Angel One
+export const ANGELONE_ORDER_TYPE_MAP: Record<string, string> = {
+ MARKET: 'MARKET',
+ LIMIT: 'LIMIT',
+ STOP: 'STOPLOSS_LIMIT',
+ STOP_LIMIT: 'STOPLOSS_LIMIT',
+ STOP_MARKET: 'STOPLOSS_MARKET',
+ SL: 'STOPLOSS_LIMIT',
+ 'SL-M': 'STOPLOSS_MARKET',
+};
+
+// Angel One -> OpenAlgo/Fincept
+export const ANGELONE_ORDER_TYPE_REVERSE_MAP: Record<string, string> = {
+ MARKET: 'MARKET',
+ LIMIT: 'LIMIT',
+ STOPLOSS_LIMIT: 'STOP_LIMIT',
+ STOPLOSS_MARKET: 'STOP_MARKET',
+};
+
+// ============================================================================
+// VARIETY MAPPINGS
+// ============================================================================
+
+// Pricetype -> Angel One Variety
+export const ANGELONE_VARIETY_MAP: Record<string, string> = {
+ MARKET: 'NORMAL',
+ LIMIT: 'NORMAL',
+ STOP: 'STOPLOSS',
+ STOP_LIMIT: 'STOPLOSS',
+ STOP_MARKET: 'STOPLOSS',
+ SL: 'STOPLOSS',
+ 'SL-M': 'STOPLOSS',
+};
+
+// ============================================================================
+// ORDER STATUS MAPPINGS
+// ============================================================================
+
+export const ANGELONE_STATUS_MAP: Record<string, string> = {
+ complete: 'FILLED',
+ open: 'OPEN',
+ pending: 'PENDING',
+ rejected: 'REJECTED',
+ cancelled: 'CANCELLED',
+ 'trigger pending': 'TRIGGER_PENDING',
+ 'validation pending': 'PENDING',
+ 'put order req received': 'PENDING',
+ 'modify pending': 'PENDING',
+ 'cancel pending': 'PENDING',
+ 'open pending': 'PENDING',
+ 'not modified': 'OPEN',
+ 'not cancelled': 'OPEN',
+ 'modify validation pending': 'PENDING',
+ 'trigger validation pending': 'TRIGGER_PENDING',
+ 'amo submitted': 'PENDING',
+ 'amo cancelled': 'CANCELLED',
+ 'amo req received': 'PENDING',
+};
+
+// ============================================================================
+// VALIDITY MAPPINGS
+// ============================================================================
+
+export const ANGELONE_VALIDITY_MAP: Record<string, string> = {
+ DAY: 'DAY',
+ IOC: 'IOC',
+};
+
+// ============================================================================
+// TIMEFRAME MAPPINGS
+// ============================================================================
+
+// Standard timeframe -> Angel One interval
+export const ANGELONE_INTERVAL_MAP: Record<string, string> = {
+ '1m': 'ONE_MINUTE',
+ '3m': 'THREE_MINUTE',
+ '5m': 'FIVE_MINUTE',
+ '10m': 'TEN_MINUTE',
+ '15m': 'FIFTEEN_MINUTE',
+ '30m': 'THIRTY_MINUTE',
+ '1h': 'ONE_HOUR',
+ '1d': 'ONE_DAY',
+ D: 'ONE_DAY',
+};
+
+// Angel One interval limits (max days per request)
+export const ANGELONE_INTERVAL_LIMITS: Record<string, number> = {
+ '1m': 30,
+ '3m': 60,
+ '5m': 100,
+ '10m': 100,
+ '15m': 200,
+ '30m': 200,
+ '1h': 400,
+ '1d': 2000,
+ D: 2000,
+};
+
+// ============================================================================
+// BROKER METADATA
+// ============================================================================
+
+export const ANGELONE_METADATA: StockBrokerMetadata = {
+ id: 'angelone',
+ name: 'angelone',
+ displayName: 'Angel One',
+ logo: '/brokers/angelone.png',
+ website: 'https://www.angelone.in',
+
+ region: 'india',
+ country: 'IN',
+ currency: 'INR',
+ exchanges: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'],
+ marketHours: {
+ open: '09:15',
+ close: '15:30',
+ timezone: 'Asia/Kolkata',
+ preMarketOpen: '09:00',
+ preMarketClose: '09:08',
+ },
+
+ features: {
+ webSocket: true,
+ amo: true,
+ gtt: true,
+ bracketOrder: true,
+ coverOrder: true,
+ marginCalculator: true,
+ optionsChain: true,
+ paperTrading: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true,
+ stopLimitOrders: true,
+ trailingStopOrders: false,
+ },
+
+ productTypes: ['CASH', 'INTRADAY', 'MARGIN'],
+
+ authType: 'totp',
+
+ rateLimit: {
+ ordersPerSecond: 10,
+ quotesPerSecond: 1, // Angel One has 1 request per second for quotes
+ },
+
+ fees: {
+ equity: { brokerage: 0, stt: 0.001 },
+ intraday: { brokerage: 20 },
+ fno: { brokerage: 20 },
+ },
+
+ defaultSymbols: [
+ 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',
+ 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',
+ 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',
+ ],
+};
+
+// ============================================================================
+// API HEADERS TEMPLATE
+// ============================================================================
+
+export function getAngelOneHeaders(authToken: string, apiKey: string): Record<string, string> {
+ return {
+ 'Authorization': `Bearer ${authToken}`,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ 'X-UserType': 'USER',
+ 'X-SourceID': 'WEB',
+ 'X-ClientLocalIP': 'CLIENT_LOCAL_IP',
+ 'X-ClientPublicIP': 'CLIENT_PUBLIC_IP',
+ 'X-MACAddress': 'MAC_ADDRESS',
+ 'X-PrivateKey': apiKey,
+ };
+}
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/index.ts b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/index.ts
new file mode 100644
index 000000000..f4244d35b
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/index.ts
@@ -0,0 +1,7 @@
+/**
+ * Angel One Broker Module
+ */
+
+export { AngelOneAdapter } from './AngelOneAdapter';
+export { ANGELONE_METADATA, ANGELONE_EXCHANGE_MAP } from './constants';
+export * from './mapper';
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/mapper.ts b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/mapper.ts
new file mode 100644
index 000000000..cb53e9b92
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/mapper.ts
@@ -0,0 +1,519 @@
+/**
+ * Angel One Data Mappers
+ *
+ * Transform between Angel One API format and standard stock broker format
+ * Based on OpenAlgo broker integration patterns
+ */
+
+import type {
+ Order,
+ Trade,
+ Position,
+ Holding,
+ Funds,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ DepthLevel,
+ OrderParams,
+ ModifyOrderParams,
+ TimeFrame,
+ OrderStatus,
+ OrderSide,
+ OrderType,
+ ProductType,
+ StockExchange,
+ TickData,
+ SubscriptionMode,
+} from '../../types';
+
+import {
+ ANGELONE_EXCHANGE_MAP,
+ ANGELONE_PRODUCT_MAP,
+ ANGELONE_PRODUCT_REVERSE_MAP,
+ ANGELONE_ORDER_TYPE_MAP,
+ ANGELONE_ORDER_TYPE_REVERSE_MAP,
+ ANGELONE_VARIETY_MAP,
+ ANGELONE_STATUS_MAP,
+ ANGELONE_VALIDITY_MAP,
+ ANGELONE_INTERVAL_MAP,
+} from './constants';
+
+// ============================================================================
+// ORDER MAPPERS
+// ============================================================================
+
+/**
+ * Convert standard order params to Angel One format
+ */
+export function toAngelOneOrderParams(
+ params: OrderParams,
+ symbolToken: string
+): Record<string, unknown> {
+ const orderType = params.orderType || 'MARKET';
+ const variety = ANGELONE_VARIETY_MAP[orderType] || 'NORMAL';
+
+ return {
+ variety: variety,
+ tradingsymbol: params.symbol,
+ symboltoken: symbolToken,
+ transactiontype: params.side,
+ exchange: ANGELONE_EXCHANGE_MAP[params.exchange] || params.exchange,
+ ordertype: ANGELONE_ORDER_TYPE_MAP[orderType] || 'MARKET',
+ producttype: ANGELONE_PRODUCT_MAP[params.productType] || 'INTRADAY',
+ duration: ANGELONE_VALIDITY_MAP[params.validity || 'DAY'] || 'DAY',
+ price: String(params.price || 0),
+ triggerprice: String(params.triggerPrice || 0),
+ squareoff: '0',
+ stoploss: '0',
+ quantity: String(params.quantity),
+ disclosedquantity: String(params.disclosedQuantity || 0),
+ };
+}
+
+/**
+ * Convert modify order params to Angel One format
+ */
+export function toAngelOneModifyParams(
+ orderId: string,
+ params: ModifyOrderParams,
+ originalOrder: {
+ symbol: string;
+ exchange: string;
+ symbolToken: string;
+ }
+): Record<string, unknown> {
+ const orderType = params.orderType || 'LIMIT';
+ const variety = ANGELONE_VARIETY_MAP[orderType] || 'NORMAL';
+
+ return {
+ variety: variety,
+ orderid: orderId,
+ ordertype: params.orderType ? ANGELONE_ORDER_TYPE_MAP[params.orderType] || 'LIMIT' : 'LIMIT',
+ producttype: ANGELONE_PRODUCT_MAP['INTRADAY'], // Will be set from original order
+ duration: ANGELONE_VALIDITY_MAP[params.validity || 'DAY'] || 'DAY',
+ price: String(params.price || 0),
+ quantity: String(params.quantity || 0),
+ tradingsymbol: originalOrder.symbol,
+ symboltoken: originalOrder.symbolToken,
+ exchange: originalOrder.exchange,
+ disclosedquantity: '0',
+ stoploss: String(params.triggerPrice || 0),
+ };
+}
+
+/**
+ * Convert Angel One order to standard format
+ */
+export function fromAngelOneOrder(order: Record<string, unknown>): Order {
+ const status = String(order.status || 'pending').toLowerCase();
+ const orderType = String(order.ordertype || 'MARKET');
+
+ // Map Angel One order type back to standard
+ let mappedOrderType = ANGELONE_ORDER_TYPE_REVERSE_MAP[orderType] || 'LIMIT';
+ if (orderType === 'STOPLOSS_LIMIT') mappedOrderType = 'STOP_LIMIT';
+ if (orderType === 'STOPLOSS_MARKET') mappedOrderType = 'STOP_MARKET';
+
+ // Map product type
+ const productType = String(order.producttype || 'INTRADAY');
+ const mappedProductType = ANGELONE_PRODUCT_REVERSE_MAP[productType] || 'INTRADAY';
+
+ return {
+ orderId: String(order.orderid || ''),
+ symbol: String(order.tradingsymbol || ''),
+ exchange: String(order.exchange || 'NSE') as StockExchange,
+ side: String(order.transactiontype || 'BUY').toUpperCase() as OrderSide,
+ quantity: Number(order.quantity || 0),
+ filledQuantity: Number(order.filledshares || 0),
+ pendingQuantity: Number(order.unfilledshares || Number(order.quantity || 0) - Number(order.filledshares || 0)),
+ price: Number(order.price || 0),
+ averagePrice: Number(order.averageprice || 0),
+ triggerPrice: order.triggerprice ? Number(order.triggerprice) : undefined,
+ orderType: mappedOrderType as OrderType,
+ productType: mappedProductType as ProductType,
+ validity: String(order.duration || 'DAY') as 'DAY' | 'IOC' | 'GTC' | 'GTD',
+ status: (ANGELONE_STATUS_MAP[status] || 'PENDING') as OrderStatus,
+ statusMessage: order.text ? String(order.text) : undefined,
+ placedAt: order.orderentryTime
+ ? new Date(order.orderentryTime as string)
+ : new Date(),
+ updatedAt: order.updatetime
+ ? new Date(order.updatetime as string)
+ : undefined,
+ exchangeOrderId: order.exchorderId ? String(order.exchorderId) : undefined,
+ tag: order.tag ? String(order.tag) : undefined,
+ };
+}
+
+// ============================================================================
+// TRADE MAPPERS
+// ============================================================================
+
+/**
+ * Convert Angel One trade to standard format
+ */
+export function fromAngelOneTrade(trade: Record<string, unknown>): Trade {
+ const productType = String(trade.producttype || 'INTRADAY');
+ const mappedProductType = ANGELONE_PRODUCT_REVERSE_MAP[productType] || 'INTRADAY';
+
+ return {
+ tradeId: String(trade.tradeid || trade.fillid || ''),
+ orderId: String(trade.orderid || ''),
+ symbol: String(trade.tradingsymbol || ''),
+ exchange: String(trade.exchange || 'NSE') as StockExchange,
+ side: String(trade.transactiontype || 'BUY').toUpperCase() as OrderSide,
+ quantity: Number(trade.fillquantity || trade.quantity || 0),
+ price: Number(trade.fillprice || trade.price || 0),
+ productType: mappedProductType as ProductType,
+ tradedAt: trade.filltime
+ ? new Date(trade.filltime as string)
+ : new Date(),
+ exchangeTradeId: trade.exchtradenumber ? String(trade.exchtradenumber) : undefined,
+ };
+}
+
+// ============================================================================
+// POSITION MAPPERS
+// ============================================================================
+
+/**
+ * Convert Angel One position to standard format
+ */
+export function fromAngelOnePosition(position: Record<string, unknown>): Position {
+ const netQty = Number(position.netqty || 0);
+ const buyQty = Number(position.buyqty || 0);
+ const sellQty = Number(position.sellqty || 0);
+ const buyValue = Number(position.totalbuyvalue || 0);
+ const sellValue = Number(position.totalsellvalue || 0);
+ const avgPrice = Number(position.avgnetprice || position.netprice || 0);
+ const lastPrice = Number(position.ltp || 0);
+ const pnl = Number(position.pnl || position.unrealised || 0);
+ const pnlPercent = avgPrice > 0 ? ((lastPrice - avgPrice) / avgPrice) * 100 : 0;
+
+ // Map product type
+ const productType = String(position.producttype || 'INTRADAY');
+ const mappedProductType = ANGELONE_PRODUCT_REVERSE_MAP[productType] || 'INTRADAY';
+
+ return {
+ symbol: String(position.tradingsymbol || ''),
+ exchange: String(position.exchange || 'NSE') as StockExchange,
+ productType: mappedProductType as ProductType,
+ quantity: netQty,
+ buyQuantity: buyQty,
+ sellQuantity: sellQty,
+ buyValue,
+ sellValue,
+ averagePrice: avgPrice,
+ lastPrice,
+ pnl,
+ pnlPercent,
+ dayPnl: Number(position.realised || 0),
+ overnight: Boolean(position.cfbuyqty || position.cfsellqty),
+ };
+}
+
+// ============================================================================
+// HOLDING MAPPERS
+// ============================================================================
+
+/**
+ * Convert Angel One holding to standard format
+ */
+export function fromAngelOneHolding(holding: Record<string, unknown>): Holding {
+ const quantity = Number(holding.quantity || 0);
+ const avgPrice = Number(holding.averageprice || 0);
+ const lastPrice = Number(holding.ltp || 0);
+ const investedValue = quantity * avgPrice;
+ const currentValue = quantity * lastPrice;
+ const pnl = Number(holding.profitandloss || (currentValue - investedValue));
+ const pnlPercent = Number(holding.pnlpercentage || (investedValue > 0 ? (pnl / investedValue) * 100 : 0));
+
+ return {
+ symbol: String(holding.tradingsymbol || ''),
+ exchange: String(holding.exchange || 'NSE') as StockExchange,
+ quantity,
+ averagePrice: avgPrice,
+ lastPrice,
+ investedValue,
+ currentValue,
+ pnl,
+ pnlPercent,
+ isin: holding.isin ? String(holding.isin) : undefined,
+ pledgedQuantity: holding.pledgedquantity ? Number(holding.pledgedquantity) : undefined,
+ collateralQuantity: holding.collateralqty ? Number(holding.collateralqty) : undefined,
+ t1Quantity: holding.t1quantity ? Number(holding.t1quantity) : undefined,
+ };
+}
+
+// ============================================================================
+// FUNDS MAPPERS
+// ============================================================================
+
+/**
+ * Convert Angel One RMS (Risk Management System) data to standard funds format
+ */
+export function fromAngelOneFunds(funds: Record<string, unknown>): Funds {
+ // Angel One provides funds via getRMS endpoint
+ const availableCash = Number(funds.availablecash || funds.net || 0);
+ const utilisedDebits = Number(funds.utiliseddebits || 0);
+ const utilisedPayout = Number(funds.utilisedpayout || 0);
+
+ // Calculate collateral as availablecash - utilisedpayout (as per OpenAlgo)
+ const collateral = availableCash - utilisedPayout;
+
+ const m2mRealized = Number(funds.m2mrealized || 0);
+ const m2mUnrealized = Number(funds.m2munrealized || 0);
+
+ return {
+ availableCash,
+ usedMargin: utilisedDebits,
+ availableMargin: availableCash - utilisedDebits,
+ totalBalance: availableCash,
+ currency: 'INR',
+ equityAvailable: availableCash,
+ commodityAvailable: 0, // Angel One provides combined margin
+ collateral,
+ unrealizedPnl: m2mUnrealized,
+ realizedPnl: m2mRealized,
+ };
+}
+
+// ============================================================================
+// QUOTE MAPPERS
+// ============================================================================
+
+/**
+ * Convert Angel One quote to standard format
+ */
+export function fromAngelOneQuote(
+ quote: Record<string, unknown>,
+ symbol: string,
+ exchange: StockExchange
+): Quote {
+ const depth = quote.depth as Record<string, unknown[]> | undefined;
+ const buyDepth = depth?.buy as Record<string, number>[] || [];
+ const sellDepth = depth?.sell as Record<string, number>[] || [];
+
+ const bid = buyDepth.length > 0 ? Number(buyDepth[0].price || 0) : 0;
+ const bidQty = buyDepth.length > 0 ? Number(buyDepth[0].quantity || 0) : 0;
+ const ask = sellDepth.length > 0 ? Number(sellDepth[0].price || 0) : 0;
+ const askQty = sellDepth.length > 0 ? Number(sellDepth[0].quantity || 0) : 0;
+
+ const lastPrice = Number(quote.ltp || 0);
+ const previousClose = Number(quote.close || 0);
+ const change = lastPrice - previousClose;
+ const changePercent = previousClose > 0 ? (change / previousClose) * 100 : 0;
+
+ return {
+ symbol,
+ exchange,
+ lastPrice,
+ open: Number(quote.open || 0),
+ high: Number(quote.high || 0),
+ low: Number(quote.low || 0),
+ close: lastPrice,
+ previousClose,
+ change,
+ changePercent,
+ volume: Number(quote.tradeVolume || quote.volume || 0),
+ averagePrice: quote.avgTradedPrice ? Number(quote.avgTradedPrice) : undefined,
+ bid,
+ bidQty,
+ ask,
+ askQty,
+ timestamp: Date.now(),
+ openInterest: quote.opnInterest ? Number(quote.opnInterest) : undefined,
+ };
+}
+
+// ============================================================================
+// OHLCV MAPPERS
+// ============================================================================
+
+/**
+ * Convert Angel One candle data to standard OHLCV format
+ * Angel One returns: [timestamp, open, high, low, close, volume]
+ */
+export function fromAngelOneOHLCV(candle: unknown[]): OHLCV {
+ // Angel One returns timestamp as ISO string
+ const timestamp = typeof candle[0] === 'string'
+ ? new Date(candle[0]).getTime()
+ : Number(candle[0]);
+
+ return {
+ timestamp,
+ open: Number(candle[1] || 0),
+ high: Number(candle[2] || 0),
+ low: Number(candle[3] || 0),
+ close: Number(candle[4] || 0),
+ volume: Number(candle[5] || 0),
+ };
+}
+
+/**
+ * Convert timeframe to Angel One interval
+ */
+export function toAngelOneInterval(timeframe: TimeFrame): string {
+ return ANGELONE_INTERVAL_MAP[timeframe] || 'ONE_DAY';
+}
+
+// ============================================================================
+// DEPTH MAPPERS
+// ============================================================================
+
+/**
+ * Convert Angel One depth to standard format
+ */
+export function fromAngelOneDepth(depth: Record<string, unknown>): MarketDepth {
+ const buyLevels = (depth.buy as Record<string, unknown>[]) || [];
+ const sellLevels = (depth.sell as Record<string, unknown>[]) || [];
+
+ const bids: DepthLevel[] = [];
+ const asks: DepthLevel[] = [];
+
+ // Ensure exactly 5 levels for bids
+ for (let i = 0; i < 5; i++) {
+ if (i < buyLevels.length) {
+ bids.push({
+ price: Number(buyLevels[i].price || 0),
+ quantity: Number(buyLevels[i].quantity || 0),
+ orders: buyLevels[i].orders ? Number(buyLevels[i].orders) : undefined,
+ });
+ } else {
+ bids.push({ price: 0, quantity: 0 });
+ }
+ }
+
+ // Ensure exactly 5 levels for asks
+ for (let i = 0; i < 5; i++) {
+ if (i < sellLevels.length) {
+ asks.push({
+ price: Number(sellLevels[i].price || 0),
+ quantity: Number(sellLevels[i].quantity || 0),
+ orders: sellLevels[i].orders ? Number(sellLevels[i].orders) : undefined,
+ });
+ } else {
+ asks.push({ price: 0, quantity: 0 });
+ }
+ }
+
+ return { bids, asks };
+}
+
+// ============================================================================
+// WEBSOCKET MAPPERS
+// ============================================================================
+
+/**
+ * Convert Angel One tick to standard format
+ */
+export function fromAngelOneTick(
+ tick: Record<string, unknown>,
+ symbolInfo: { symbol: string; exchange: StockExchange },
+ mode: SubscriptionMode
+): TickData {
+ const baseTick: TickData = {
+ symbol: symbolInfo.symbol,
+ exchange: symbolInfo.exchange,
+ token: String(tick.token || ''),
+ mode,
+ lastPrice: Number(tick.ltp || tick.last_traded_price || 0),
+ timestamp: Number(tick.exchange_timestamp || tick.timestamp || Date.now()),
+ };
+
+ if (mode === 'quote' || mode === 'full') {
+ baseTick.open = Number(tick.open_price_of_the_day || tick.open || 0);
+ baseTick.high = Number(tick.high_price_of_the_day || tick.high || 0);
+ baseTick.low = Number(tick.low_price_of_the_day || tick.low || 0);
+ baseTick.close = Number(tick.closed_price || tick.close || 0);
+ baseTick.volume = Number(tick.volume_trade_for_the_day || tick.volume || 0);
+
+ const lastPrice = baseTick.lastPrice;
+ const close = baseTick.close || 0;
+ baseTick.change = lastPrice - close;
+ baseTick.changePercent = close > 0 ? ((lastPrice - close) / close) * 100 : 0;
+ }
+
+ if (mode === 'full') {
+ baseTick.bid = Number(tick.best_bid_price || 0);
+ baseTick.bidQty = Number(tick.best_bid_quantity || 0);
+ baseTick.ask = Number(tick.best_ask_price || 0);
+ baseTick.askQty = Number(tick.best_ask_quantity || 0);
+ baseTick.openInterest = tick.open_interest ? Number(tick.open_interest) : undefined;
+ }
+
+ return baseTick;
+}
+
+/**
+ * Convert subscription mode to Angel One WS mode
+ */
+export function toAngelOneWSMode(mode: SubscriptionMode): number {
+ const modeMap: Record<SubscriptionMode, number> = {
+ ltp: 1, // LTP mode
+ quote: 2, // Quote mode
+ full: 3, // Snap Quote mode (full depth)
+ };
+ return modeMap[mode] || 2;
+}
+
+// ============================================================================
+// SYMBOL MAPPERS
+// ============================================================================
+
+/**
+ * Map order data for database lookup (OpenAlgo compatible)
+ * Converts Angel One response to standardized format
+ */
+export function mapOrderData(orderData: Record<string, unknown>): Record<string, unknown>[] {
+ if (!orderData || !orderData.data || orderData.data === null) {
+ return [];
+ }
+
+ const orders = orderData.data as Record<string, unknown>[];
+
+ return orders.map(order => {
+ const productType = String(order.producttype || 'INTRADAY');
+ const exchange = String(order.exchange || 'NSE');
+
+ // Map product type based on exchange
+ let mappedProduct = productType;
+ if ((exchange === 'NSE' || exchange === 'BSE') && productType === 'DELIVERY') {
+ mappedProduct = 'CNC';
+ } else if (productType === 'INTRADAY') {
+ mappedProduct = 'MIS';
+ } else if (['NFO', 'MCX', 'BFO', 'CDS'].includes(exchange) && productType === 'CARRYFORWARD') {
+ mappedProduct = 'NRML';
+ }
+
+ return {
+ ...order,
+ producttype: mappedProduct,
+ };
+ });
+}
+
+/**
+ * Transform order data to standard OpenAlgo format
+ */
+export function transformOrderData(orders: Record<string, unknown>[]): Record<string, unknown>[] {
+ return orders.map(order => {
+ let orderType = String(order.ordertype || 'MARKET');
+ if (orderType === 'STOPLOSS_LIMIT') orderType = 'SL';
+ if (orderType === 'STOPLOSS_MARKET') orderType = 'SL-M';
+
+ return {
+ symbol: order.tradingsymbol || '',
+ exchange: order.exchange || '',
+ action: order.transactiontype || '',
+ quantity: order.quantity || 0,
+ price: order.averageprice || 0,
+ trigger_price: order.triggerprice || 0,
+ pricetype: orderType,
+ product: order.producttype || '',
+ orderid: order.orderid || '',
+ order_status: order.status || '',
+ timestamp: order.updatetime || '',
+ };
+ });
+}
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.ts
new file mode 100644
index 000000000..c4ed28104
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.ts
@@ -0,0 +1,1274 @@
+/**
+ * Fyers Stock Broker Adapter
+ *
+ * Implements IStockBrokerAdapter for Fyers API v3
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+import { listen, UnlistenFn } from '@tauri-apps/api/event';
+import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';
+import type {
+ StockBrokerMetadata,
+ Region,
+ BrokerCredentials,
+ AuthResponse,
+ AuthCallbackParams,
+ Funds,
+ MarginRequired,
+ OrderParams,
+ OrderResponse,
+ ModifyOrderParams,
+ Order,
+ Trade,
+ Position,
+ Holding,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ TimeFrame,
+ StockExchange,
+ WebSocketConfig,
+ SubscriptionMode,
+ BulkOperationResult,
+ SmartOrderParams,
+ TickData,
+} from '../../types';
+import {
+ FYERS_METADATA,
+ FYERS_LOGIN_URL,
+ FYERS_EXCHANGE_MAP,
+ FYERS_WS_URL,
+} from './constants';
+import {
+ toFyersOrderParams,
+ toFyersModifyParams,
+ toFyersSymbol,
+ toFyersInterval,
+ fromFyersOrder,
+ fromFyersTrade,
+ fromFyersPosition,
+ fromFyersHolding,
+ fromFyersFunds,
+ fromFyersQuote,
+ fromFyersTickData,
+} from './mapper';
+
+/**
+ * Fyers broker adapter
+ */
+export class FyersAdapter extends BaseStockBrokerAdapter {
+ readonly brokerId = 'fyers';
+ readonly brokerName = 'Fyers';
+ readonly region: Region = 'india';
+ readonly metadata: StockBrokerMetadata = FYERS_METADATA;
+
+ private apiKey: string | null = null;
+ private apiSecret: string | null = null;
+
+ // Tauri event unlisteners
+ private eventUnlisteners: UnlistenFn[] = [];
+
+ // REST API polling for quotes (instead of WebSocket)
+ private quotePollingInterval: NodeJS.Timeout | null = null;
+ private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();
+
+ // ============================================================================
+ // Authentication
+ // ============================================================================
+
+ /**
+ * Get OAuth login URL
+ */
+ getAuthUrl(): string {
+ if (!this.apiKey) {
+ throw new Error('API key not set. Call setCredentials first.');
+ }
+ // Fyers requires HTTPS with 127.0.0.1
+ const redirectUri = encodeURIComponent('https://127.0.0.1/');
+ const responseType = 'code';
+ const state = 'fyers_auth';
+
+ return `${FYERS_LOGIN_URL}?client_id=${this.apiKey}&redirect_uri=${redirectUri}&response_type=${responseType}&state=${state}`;
+ }
+
+ /**
+ * Set API credentials before authentication
+ */
+ setCredentials(apiKey: string, apiSecret: string): void {
+ console.log('[FyersAdapter] setCredentials called with:', {
+ apiKey: apiKey ? `${apiKey.substring(0, 10)}...` : 'empty',
+ apiSecret: apiSecret ? '***' : 'empty',
+ apiKeyLength: apiKey?.length || 0,
+ apiSecretLength: apiSecret?.length || 0,
+ });
+ this.apiKey = apiKey;
+ this.apiSecret = apiSecret;
+ console.log('[FyersAdapter] Credentials stored in memory:', {
+ hasApiKey: !!this.apiKey,
+ hasApiSecret: !!this.apiSecret,
+ });
+ }
+
+ /**
+ * Authenticate with stored or new credentials
+ */
+ async authenticate(credentials: BrokerCredentials): Promise<AuthResponse> {
+ try {
+ this.apiKey = credentials.apiKey;
+ this.apiSecret = credentials.apiSecret || null;
+
+ // Check if this is an auth_code that needs to be exchanged (OAuth callback)
+ const authCode = (credentials as any).authCode;
+ if (authCode) {
+ console.log('[FyersAdapter] Auth code detected, exchanging for access token...');
+ return this.handleAuthCallback({ authCode });
+ }
+
+ // If access token provided, use it directly (assume already exchanged)
+ if (credentials.accessToken) {
+ console.log('[FyersAdapter] Access token provided, storing...');
+ // For Fyers, if it's a short code, it might be an auth_code
+ // Auth codes are typically alphanumeric and ~30 chars
+ // Access tokens are longer (typically 60+ chars)
+ if (credentials.accessToken.length < 40 && /^[A-Za-z0-9]+$/.test(credentials.accessToken)) {
+ console.log('[FyersAdapter] Short token detected, treating as auth_code...');
+ return this.handleAuthCallback({ authCode: credentials.accessToken });
+ }
+
+ this.accessToken = credentials.accessToken;
+ this.userId = credentials.userId || null;
+ this._isConnected = true;
+
+ await this.storeCredentials(credentials);
+
+ return {
+ success: true,
+ accessToken: this.accessToken,
+ userId: this.userId || undefined,
+ message: 'Authentication successful',
+ };
+ }
+
+ // Need to go through OAuth flow
+ console.warn('[FyersAdapter] No access token or auth code provided');
+ return {
+ success: false,
+ message: 'Please complete OAuth login',
+ errorCode: 'AUTH_REQUIRED',
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Authentication failed',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+ }
+
+ /**
+ * Handle OAuth callback
+ */
+ async handleAuthCallback(params: AuthCallbackParams): Promise<AuthResponse> {
+ try {
+ if (!params.authCode && !params.requestToken) {
+ return {
+ success: false,
+ message: 'Authorization code not provided',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+
+ if (!this.apiKey || !this.apiSecret) {
+ return {
+ success: false,
+ message: 'API credentials not set',
+ errorCode: 'CREDENTIALS_MISSING',
+ };
+ }
+
+ const authCode = params.authCode || params.requestToken || '';
+
+ // Call Rust backend to exchange auth code for access token
+ const response = await invoke<{
+ success: boolean;
+ access_token?: string;
+ user_id?: string;
+ error?: string;
+ }>('fyers_exchange_token', {
+ apiKey: this.apiKey,
+ apiSecret: this.apiSecret,
+ authCode,
+ });
+
+ if (response.success && response.access_token) {
+ this.accessToken = response.access_token;
+ this.userId = response.user_id || null;
+ this._isConnected = true;
+
+ // Store credentials
+ await this.storeCredentials({
+ apiKey: this.apiKey,
+ apiSecret: this.apiSecret,
+ accessToken: this.accessToken,
+ userId: this.userId || undefined,
+ });
+
+ return {
+ success: true,
+ accessToken: this.accessToken,
+ userId: this.userId || undefined,
+ message: 'Authentication successful',
+ };
+ }
+
+ return {
+ success: false,
+ message: response.error || 'Token exchange failed',
+ errorCode: 'TOKEN_EXCHANGE_FAILED',
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Authentication callback failed',
+ errorCode: 'AUTH_CALLBACK_FAILED',
+ };
+ }
+ }
+
+ /**
+ * Initialize from stored credentials on app startup
+ */
+ async initFromStorage(): Promise<boolean> {
+ try {
+ console.log(`[${this.brokerId}] Attempting to load stored credentials...`);
+ const credentials = await this.loadCredentials();
+
+ if (!credentials || !credentials.apiKey) {
+ console.log(`[${this.brokerId}] No stored credentials found`);
+ return false;
+ }
+
+ console.log(`[${this.brokerId}] Found stored credentials, restoring session...`);
+ this.apiKey = credentials.apiKey;
+ this.apiSecret = credentials.apiSecret || null;
+ this.accessToken = credentials.accessToken || null;
+
+ // If we have an access token, assume valid (Fyers tokens don't expire for 24h)
+ // If expired, API calls will fail and user will need to re-auth
+ if (this.accessToken) {
+ // TODO: Add token validation when Fyers provides an endpoint
+ // For now, optimistically restore session
+ console.log(`[${this.brokerId}] Access token found, attempting to restore session...`);
+
+ // Test token with a lightweight API call
+ try {
+ await this.getFundsInternal();
+ this._isConnected = true;
+ console.log(`[${this.brokerId}] ✓ Session restored successfully`);
+ return true;
+ } catch (err) {
+ console.warn(`[${this.brokerId}] Access token expired or invalid, clearing from storage...`);
+
+ // Clear expired token from database
+ await this.storeCredentials({
+ apiKey: this.apiKey,
+ apiSecret: this.apiSecret || '',
+ // No accessToken = clears it
+ });
+
+ this.accessToken = null;
+ this._isConnected = false;
+
+ console.log(`[${this.brokerId}] Please re-authenticate to continue`);
+ return false;
+ }
+ }
+
+ console.log(`[${this.brokerId}] No access token found, manual authentication required`);
+ return false;
+ } catch (error) {
+ console.error(`[${this.brokerId}] Failed to initialize from storage:`, error);
+ return false;
+ }
+ }
+
+ // ============================================================================
+ // Orders - Internal Implementations
+ // ============================================================================
+
+ /**
+ * Place a new order (internal)
+ */
+ protected async placeOrderInternal(params: OrderParams): Promise<OrderResponse> {
+ this.ensureAuthenticated();
+
+ try {
+ const fyersParams = toFyersOrderParams(params);
+
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('fyers_place_order', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ ...fyersParams,
+ });
+
+ if (response.success && response.order_id) {
+ return {
+ success: true,
+ orderId: response.order_id,
+ message: 'Order placed successfully',
+ };
+ }
+
+ return {
+ success: false,
+ message: response.error || 'Order placement failed',
+ errorCode: 'ORDER_PLACEMENT_FAILED',
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Failed to place order',
+ errorCode: 'ORDER_PLACEMENT_ERROR',
+ };
+ }
+ }
+
+ /**
+ * Modify an existing order (internal)
+ */
+ protected async modifyOrderInternal(params: ModifyOrderParams): Promise<OrderResponse> {
+ this.ensureAuthenticated();
+
+ if (!params.orderId) {
+ return {
+ success: false,
+ message: 'Order ID is required',
+ errorCode: 'MISSING_ORDER_ID',
+ };
+ }
+
+ try {
+ const fyersParams = toFyersModifyParams(params.orderId, params);
+
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown;
+ error?: string;
+ }>('fyers_modify_order', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ ...fyersParams,
+ });
+
+ if (response.success) {
+ return {
+ success: true,
+ orderId: params.orderId,
+ message: 'Order modified successfully',
+ };
+ }
+
+ return {
+ success: false,
+ message: response.error || 'Order modification failed',
+ errorCode: 'ORDER_MODIFICATION_FAILED',
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Failed to modify order',
+ errorCode: 'ORDER_MODIFICATION_ERROR',
+ };
+ }
+ }
+
+ /**
+ * Cancel an order (internal)
+ */
+ protected async cancelOrderInternal(orderId: string): Promise<OrderResponse> {
+ this.ensureAuthenticated();
+
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown;
+ error?: string;
+ }>('fyers_cancel_order', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ orderId,
+ });
+
+ if (response.success) {
+ return {
+ success: true,
+ orderId,
+ message: 'Order cancelled successfully',
+ };
+ }
+
+ return {
+ success: false,
+ message: response.error || 'Order cancellation failed',
+ errorCode: 'ORDER_CANCELLATION_FAILED',
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Failed to cancel order',
+ errorCode: 'ORDER_CANCELLATION_ERROR',
+ };
+ }
+ }
+
+ /**
+ * Get all orders (internal)
+ */
+ protected async getOrdersInternal(): Promise<Order[]> {
+ this.ensureAuthenticated();
+
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown[];
+ error?: string;
+ }>('fyers_get_orders', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ });
+
+ if (response.success && response.data) {
+ return response.data.map((order: unknown) =>
+ fromFyersOrder(order as Record<string, unknown>)
+ );
+ }
+
+ return [];
+ } catch (error) {
+ console.error('Failed to fetch orders:', error);
+ return [];
+ }
+ }
+
+ /**
+ * Get all trades (internal)
+ */
+ protected async getTradeBookInternal(): Promise<Trade[]> {
+ this.ensureAuthenticated();
+
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown[];
+ error?: string;
+ }>('fyers_get_trade_book', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ });
+
+ if (response.success && response.data) {
+ return response.data.map((trade: unknown) =>
+ fromFyersTrade(trade as Record<string, unknown>)
+ );
+ }
+
+ return [];
+ } catch (error) {
+ console.error('Failed to fetch trades:', error);
+ return [];
+ }
+ }
+
+ // ============================================================================
+ // Portfolio - Internal Implementations
+ // ============================================================================
+
+ /**
+ * Get all positions (internal)
+ */
+ protected async getPositionsInternal(): Promise<Position[]> {
+ this.ensureAuthenticated();
+
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown[];
+ error?: string;
+ }>('fyers_get_positions', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ });
+
+ if (response.success && response.data) {
+ return response.data.map((position: unknown) =>
+ fromFyersPosition(position as Record<string, unknown>)
+ );
+ }
+
+ return [];
+ } catch (error) {
+ console.error('Failed to fetch positions:', error);
+ return [];
+ }
+ }
+
+ /**
+ * Get open position quantity for a specific symbol
+ * Used by smart order logic to determine current position
+ */
+ private async getOpenPositionQuantity(
+ symbol: string,
+ exchange: StockExchange,
+ productType: string
+ ): Promise<number> {
+ try {
+ const positions = await this.getPositionsInternal();
+ const position = positions.find(
+ p =>
+ p.symbol === symbol &&
+ p.exchange === exchange &&
+ p.productType === productType
+ );
+
+ return position ? position.quantity : 0;
+ } catch (error) {
+ console.error('Failed to get open position:', error);
+ return 0;
+ }
+ }
+
+ /**
+ * Get all holdings (internal)
+ */
+ protected async getHoldingsInternal(): Promise<Holding[]> {
+ this.ensureAuthenticated();
+
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown[];
+ error?: string;
+ }>('fyers_get_holdings', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ });
+
+ if (response.success && response.data) {
+ return response.data.map((holding: unknown) =>
+ fromFyersHolding(holding as Record<string, unknown>)
+ );
+ }
+
+ return [];
+ } catch (error) {
+ console.error('Failed to fetch holdings:', error);
+ return [];
+ }
+ }
+
+ // ============================================================================
+ // Funds - Internal Implementation
+ // ============================================================================
+
+ /**
+ * Get account funds/margins (internal)
+ * Combines funds data with unrealized P&L from positions (like OpenAlgo)
+ */
+ protected async getFundsInternal(): Promise<Funds> {
+ this.ensureAuthenticated();
+
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown;
+ error?: string;
+ }>('fyers_get_funds', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ });
+
+ if (response.success && response.data) {
+ const funds = fromFyersFunds(response.data as Record<string, unknown>);
+
+ // Get positions to calculate total unrealized P&L (OpenAlgo pattern)
+ try {
+ const positions = await this.getPositionsInternal();
+ const totalUnrealizedPnl = positions.reduce((sum, pos) => sum + pos.pnl, 0);
+
+ // Update unrealized P&L if we got it from positions
+ if (positions.length > 0) {
+ funds.unrealizedPnl = totalUnrealizedPnl;
+ }
+ } catch (err) {
+ console.warn('[Fyers] Failed to fetch position P&L for funds:', err);
+ // Continue with funds data even if positions fail
+ }
+
+ return funds;
+ }
+
+ // Return default funds structure
+ return {
+ availableCash: 0,
+ usedMargin: 0,
+ availableMargin: 0,
+ totalBalance: 0,
+ currency: 'INR',
+ };
+ } catch (error) {
+ console.error('Failed to fetch funds:', error);
+ return {
+ availableCash: 0,
+ usedMargin: 0,
+ availableMargin: 0,
+ totalBalance: 0,
+ currency: 'INR',
+ };
+ }
+ }
+
+ // ============================================================================
+ // Market Data - Internal Implementations
+ // ============================================================================
+
+ /**
+ * Get quote for a single symbol (internal)
+ */
+ protected async getQuoteInternal(symbol: string, exchange: StockExchange): Promise<Quote> {
+ this.ensureAuthenticated();
+
+ try {
+ // Convert symbol to Fyers format
+ const fyersSymbol = toFyersSymbol(symbol, exchange);
+
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown[];
+ error?: string;
+ }>('fyers_get_quotes', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ symbols: [fyersSymbol],
+ });
+
+ if (response.success && response.data && response.data.length > 0) {
+ return fromFyersQuote(response.data[0] as Record<string, unknown>);
+ }
+
+ // Return default quote if not found
+ return {
+ symbol,
+ exchange,
+ lastPrice: 0,
+ open: 0,
+ high: 0,
+ low: 0,
+ close: 0,
+ previousClose: 0,
+ change: 0,
+ changePercent: 0,
+ volume: 0,
+ bid: 0,
+ bidQty: 0,
+ ask: 0,
+ askQty: 0,
+ timestamp: Date.now(),
+ };
+ } catch (error) {
+ console.error('Failed to fetch quote:', error);
+ return {
+ symbol,
+ exchange,
+ lastPrice: 0,
+ open: 0,
+ high: 0,
+ low: 0,
+ close: 0,
+ previousClose: 0,
+ change: 0,
+ changePercent: 0,
+ volume: 0,
+ bid: 0,
+ bidQty: 0,
+ ask: 0,
+ askQty: 0,
+ timestamp: Date.now(),
+ };
+ }
+ }
+
+ /**
+ * Get quotes for multiple symbols (batch processing)
+ * Automatically batches into groups of 50 symbols
+ */
+ protected async getMultipleQuotesInternal(
+ symbols: Array<{ symbol: string; exchange: StockExchange }>
+ ): Promise<Quote[]> {
+ this.ensureAuthenticated();
+
+ const BATCH_SIZE = 50;
+ const RATE_LIMIT_DELAY = 100; // 100ms delay between batches
+ const allResults: Quote[] = [];
+
+ try {
+ // Process in batches of 50
+ for (let i = 0; i < symbols.length; i += BATCH_SIZE) {
+ const batch = symbols.slice(i, i + BATCH_SIZE);
+
+ // Convert to Fyers format
+ const fyersSymbols = batch.map(({ symbol, exchange }) =>
+ toFyersSymbol(symbol, exchange)
+ );
+
+ const response = await invoke<{
+ success: boolean;
+ data?: unknown[];
+ error?: string;
+ }>('fyers_get_quotes', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ symbols: fyersSymbols,
+ });
+
+ if (response.success && response.data) {
+ const quotes = response.data.map((item: unknown) =>
+ fromFyersQuote(item as Record<string, unknown>)
+ );
+ allResults.push(...quotes);
+ }
+
+ // Rate limit delay between batches
+ if (i + BATCH_SIZE < symbols.length) {
+ await new Promise(resolve => setTimeout(resolve, RATE_LIMIT_DELAY));
+ }
+ }
+
+ console.log(`[Fyers] Fetched ${allResults.length} quotes in ${Math.ceil(symbols.length / BATCH_SIZE)} batches`);
+ return allResults;
+ } catch (error) {
+ console.error('Failed to fetch multiple quotes:', error);
+ return [];
+ }
+ }
+
+ /**
+ * Get OHLCV data (internal) - Historical data with chunking
+ */
+ protected async getOHLCVInternal(
+ symbol: string,
+ exchange: StockExchange,
+ timeframe: TimeFrame,
+ from: Date,
+ to: Date
+ ): Promise<OHLCV[]> {
+ this.ensureAuthenticated();
+
+ try {
+ const fyersSymbol = toFyersSymbol(symbol, exchange);
+ const fyersInterval = toFyersInterval(timeframe);
+
+ const response = await invoke<{
+ success: boolean;
+ data?: Array<[number, number, number, number, number, number]>; // [timestamp, O, H, L, C, V]
+ error?: string;
+ }>('fyers_get_history', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ symbol: fyersSymbol,
+ resolution: fyersInterval,
+ fromDate: from.toISOString().split('T')[0], // YYYY-MM-DD
+ toDate: to.toISOString().split('T')[0],
+ });
+
+ console.log('[FyersAdapter] Raw response:', {
+ success: response.success,
+ dataLength: response.data?.length,
+ error: response.error,
+ firstCandle: response.data?.[0],
+ });
+
+ if (response.success && response.data) {
+ const candles = response.data.map(candle => ({
+ timestamp: candle[0],
+ open: candle[1],
+ high: candle[2],
+ low: candle[3],
+ close: candle[4],
+ volume: candle[5],
+ }));
+ console.log(`[FyersAdapter] ✓ Fetched ${candles.length} candles for ${fyersSymbol}`);
+ return candles;
+ }
+
+ // API returned error
+ const errorMsg = response.error || 'Unknown error from Fyers API';
+ console.error(`[FyersAdapter] ❌ Fyers API error: ${errorMsg}`);
+ throw new Error(`Fyers API error: ${errorMsg}`);
+ } catch (error) {
+ console.error('[FyersAdapter] Failed to fetch historical data:', error);
+ throw error; // Re-throw so the UI can display the error
+ }
+ }
+
+ /**
+ * Get market depth (internal) - 5-level bid/ask
+ */
+ protected async getMarketDepthInternal(symbol: string, exchange: StockExchange): Promise<MarketDepth> {
+ this.ensureAuthenticated();
+
+ try {
+ const fyersSymbol = toFyersSymbol(symbol, exchange);
+
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ }>('fyers_get_depth', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ symbol: fyersSymbol,
+ });
+
+ if (response.success && response.data) {
+ const depth = response.data;
+ const bids = (depth.bids as Array<Record<string, unknown>>) || [];
+ const asks = (depth.ask as Array<Record<string, unknown>>) || []; // Fyers uses 'ask' not 'asks'
+
+ return {
+ bids: bids.slice(0, 5).map(b => ({
+ price: Number(b.price || 0),
+ quantity: Number(b.volume || 0),
+ orders: Number(b.ord || 0),
+ })),
+ asks: asks.slice(0, 5).map(a => ({
+ price: Number(a.price || 0),
+ quantity: Number(a.volume || 0),
+ orders: Number(a.ord || 0),
+ })),
+ };
+ }
+
+ return { bids: [], asks: [] };
+ } catch (error) {
+ console.error('Failed to fetch market depth:', error);
+ return { bids: [], asks: [] };
+ }
+ }
+
+ // ============================================================================
+ // WebSocket - Internal Implementations
+ // ============================================================================
+
+ /**
+ * Connect to WebSocket (internal) - Uses REST API polling instead
+ */
+ protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {
+ this.ensureAuthenticated();
+
+ try {
+ if (!this.apiKey || !this.accessToken) {
+ throw new Error('API credentials not set');
+ }
+
+ // Start REST API polling (every 2 minutes as requested)
+ this.startQuotePolling();
+
+ console.log('Fyers: REST API polling started (2 min interval)');
+ } catch (error) {
+ console.error('Failed to start Fyers polling:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Start REST API polling for quotes
+ */
+ private startQuotePolling(): void {
+ // Stop existing polling
+ this.stopQuotePolling();
+
+ // Poll every 2 minutes (120000ms)
+ this.quotePollingInterval = setInterval(async () => {
+ await this.pollQuotesSequentially();
+ }, 120000);
+
+ // Initial poll
+ this.pollQuotesSequentially();
+ }
+
+ /**
+ * Stop REST API polling
+ */
+ private stopQuotePolling(): void {
+ if (this.quotePollingInterval) {
+ clearInterval(this.quotePollingInterval);
+ this.quotePollingInterval = null;
+ }
+ }
+
+ /**
+ * Poll quotes sequentially (not parallel) for all subscribed symbols
+ */
+ private async pollQuotesSequentially(): Promise<void> {
+ if (this.pollingSymbols.size === 0) {
+ return;
+ }
+
+ console.log(`[Fyers] Polling ${this.pollingSymbols.size} symbols sequentially...`);
+
+ // Process each symbol one by one
+ for (const [key, { symbol, exchange }] of this.pollingSymbols) {
+ try {
+ // Fetch quote via REST API
+ const quote = await this.getQuoteInternal(symbol, exchange);
+
+ // Convert quote to tick and emit
+ const tick: TickData = {
+ symbol,
+ exchange,
+ mode: 'quote',
+ lastPrice: quote.lastPrice,
+ open: quote.open,
+ high: quote.high,
+ low: quote.low,
+ close: quote.close,
+ volume: quote.volume,
+ change: quote.change,
+ changePercent: quote.changePercent,
+ timestamp: quote.timestamp,
+ };
+
+ this.emitTick(tick);
+ } catch (error) {
+ console.error(`[Fyers] Failed to poll ${symbol}:`, error);
+ }
+
+ // Small delay between requests to avoid rate limiting
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+
+ console.log(`[Fyers] ✓ Polling complete for ${this.pollingSymbols.size} symbols`);
+ }
+
+ /**
+ * Subscribe to symbol (internal) - Adds to polling list
+ */
+ protected async subscribeInternal(symbol: string, exchange: StockExchange, mode: SubscriptionMode): Promise<void> {
+ try {
+ const key = `${exchange}:${symbol}`;
+ this.pollingSymbols.set(key, { symbol, exchange });
+
+ console.log(`Fyers: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);
+
+ // Trigger immediate poll for this symbol
+ this.pollQuotesSequentially();
+ } catch (error) {
+ console.error('Failed to subscribe:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Unsubscribe from symbol (internal) - Removes from polling list
+ */
+ protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {
+ try {
+ const key = `${exchange}:${symbol}`;
+ this.pollingSymbols.delete(key);
+
+ console.log(`Fyers: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);
+ } catch (error) {
+ console.error('Failed to unsubscribe:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Cleanup polling on logout
+ */
+ async logout(): Promise<void> {
+ this.stopQuotePolling();
+ this.pollingSymbols.clear();
+ await super.logout();
+ }
+
+ // ============================================================================
+ // Bulk Operations - Internal Implementations
+ // ============================================================================
+
+ /**
+ * Cancel all orders (internal)
+ */
+ protected async cancelAllOrdersInternal(): Promise<BulkOperationResult> {
+ const orders = await this.getOrdersInternal();
+ const openOrders = orders.filter(o => o.status === 'OPEN' || o.status === 'PENDING');
+
+ const results = await Promise.all(
+ openOrders.map(async (order) => {
+ try {
+ const result = await this.cancelOrderInternal(order.orderId);
+ return { success: result.success, orderId: order.orderId };
+ } catch (error) {
+ return { success: false, orderId: order.orderId, error: String(error) };
+ }
+ })
+ );
+
+ const successful = results.filter(r => r.success).length;
+ const failed = results.filter(r => !r.success).length;
+
+ return {
+ success: failed === 0,
+ totalCount: results.length,
+ successCount: successful,
+ failedCount: failed,
+ results,
+ };
+ }
+
+ /**
+ * Close all positions (internal)
+ * Iterates through all positions and places exit orders
+ */
+ protected async closeAllPositionsInternal(): Promise<BulkOperationResult> {
+ this.ensureAuthenticated();
+
+ try {
+ const positions = await this.getPositionsInternal();
+
+ // Filter out positions with 0 quantity
+ const activePositions = positions.filter(p => p.quantity !== 0);
+
+ if (activePositions.length === 0) {
+ return {
+ success: true,
+ totalCount: 0,
+ successCount: 0,
+ failedCount: 0,
+ results: [],
+ };
+ }
+
+ const results = await Promise.all(
+ activePositions.map(async (position) => {
+ try {
+ // Determine exit side (reverse of current position)
+ const exitSide: 'BUY' | 'SELL' = position.quantity > 0 ? 'SELL' : 'BUY';
+ const exitQuantity = Math.abs(position.quantity);
+
+ const orderParams: OrderParams = {
+ symbol: position.symbol,
+ exchange: position.exchange,
+ side: exitSide,
+ quantity: exitQuantity,
+ orderType: 'MARKET',
+ productType: position.productType,
+ validity: 'DAY',
+ };
+
+ const result = await this.placeOrderInternal(orderParams);
+ return {
+ success: result.success,
+ symbol: position.symbol,
+ orderId: result.orderId,
+ error: result.message
+ };
+ } catch (error) {
+ return {
+ success: false,
+ symbol: position.symbol,
+ error: String(error)
+ };
+ }
+ })
+ );
+
+ const successful = results.filter(r => r.success).length;
+ const failed = results.filter(r => !r.success).length;
+
+ console.log(`[Fyers] Close All Positions: ${successful} success, ${failed} failed`);
+
+ return {
+ success: failed === 0,
+ totalCount: results.length,
+ successCount: successful,
+ failedCount: failed,
+ results,
+ };
+ } catch (error) {
+ console.error('Failed to close all positions:', error);
+ return {
+ success: false,
+ totalCount: 0,
+ successCount: 0,
+ failedCount: 0,
+ results: [],
+ };
+ }
+ }
+
+ /**
+ * Place smart order (internal) - Position-aware order placement
+ * Automatically calculates required quantity based on target position size
+ */
+ protected async placeSmartOrderInternal(params: SmartOrderParams): Promise<OrderResponse> {
+ this.ensureAuthenticated();
+
+ try {
+ // Get current position quantity
+ const currentPosition = await this.getOpenPositionQuantity(
+ params.symbol,
+ params.exchange,
+ params.productType
+ );
+
+ const targetPosition = params.positionSize || 0;
+
+ // Calculate what order is needed
+ let action: 'BUY' | 'SELL';
+ let quantity: number;
+
+ if (targetPosition > currentPosition) {
+ // Need to buy more
+ action = 'BUY';
+ quantity = targetPosition - currentPosition;
+ } else if (targetPosition < currentPosition) {
+ // Need to sell/reduce
+ action = 'SELL';
+ quantity = currentPosition - targetPosition;
+ } else {
+ // Already at target position
+ return {
+ success: true,
+ message: 'Already at target position',
+ };
+ }
+
+ // Place the calculated order
+ const orderParams: OrderParams = {
+ symbol: params.symbol,
+ exchange: params.exchange,
+ side: action,
+ quantity,
+ orderType: params.orderType || 'MARKET',
+ productType: params.productType,
+ price: params.price,
+ triggerPrice: params.triggerPrice,
+ validity: params.validity || 'DAY',
+ };
+
+ console.log(`[Fyers Smart Order] Current: ${currentPosition}, Target: ${targetPosition}, Action: ${action} ${quantity}`);
+
+ return this.placeOrderInternal(orderParams);
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Smart order failed',
+ errorCode: 'SMART_ORDER_FAILED',
+ };
+ }
+ }
+
+ /**
+ * Calculate margin (internal) - Margin calculator
+ * POST to /api/v3/multiorder/margin with order list
+ */
+ protected async calculateMarginInternal(orders: OrderParams[]): Promise<MarginRequired> {
+ this.ensureAuthenticated();
+
+ try {
+ // Transform orders to Fyers format
+ const fyersOrders = orders.map(order => toFyersOrderParams(order));
+
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ margin_total?: number;
+ margin_new_order?: number;
+ margin_avail?: number;
+ };
+ error?: string;
+ }>('fyers_calculate_margin', {
+ apiKey: this.apiKey!,
+ accessToken: this.accessToken!,
+ orders: fyersOrders,
+ });
+
+ if (response.success && response.data) {
+ const marginData = response.data;
+
+ // Fyers returns:
+ // - margin_total: Approximate margin required
+ // - margin_new_order: Total margin including existing positions
+ // - margin_avail: Available margin
+ //
+ // Note: Fyers doesn't provide SPAN/Exposure breakdown
+
+ return {
+ totalMargin: marginData.margin_new_order || marginData.margin_total || 0,
+ initialMargin: marginData.margin_total || 0,
+ };
+ }
+
+ return {
+ totalMargin: 0,
+ initialMargin: 0,
+ };
+ } catch (error) {
+ console.error('Failed to calculate margin:', error);
+ return {
+ totalMargin: 0,
+ initialMargin: 0,
+ };
+ }
+ }
+
+ // ============================================================================
+ // Helper Methods
+ // ============================================================================
+
+ /**
+ * Ensure user is authenticated before making API calls
+ */
+ private ensureAuthenticated(): void {
+ if (!this.accessToken || !this.apiKey) {
+ throw new Error('Not authenticated. Please login first.');
+ }
+ }
+
+ /**
+ * Store credentials securely
+ */
+ protected async storeCredentials(credentials: BrokerCredentials): Promise<void> {
+ try {
+ await invoke('store_indian_broker_credentials', {
+ brokerId: this.brokerId,
+ credentials: {
+ api_key: credentials.apiKey,
+ api_secret: credentials.apiSecret || '',
+ access_token: credentials.accessToken || '',
+ user_id: credentials.userId || '',
+ },
+ });
+ } catch (error) {
+ console.error('Failed to store credentials:', error);
+ }
+ }
+
+ /**
+ * Clear stored credentials
+ */
+ private async clearStoredCredentials(): Promise<void> {
+ try {
+ await invoke('delete_indian_broker_credentials', {
+ brokerId: this.brokerId,
+ });
+ } catch (error) {
+ console.error('Failed to clear credentials:', error);
+ }
+ }
+}
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/constants.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/constants.ts
new file mode 100644
index 000000000..8a53694b1
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/constants.ts
@@ -0,0 +1,212 @@
+/**
+ * Fyers Constants
+ *
+ * API endpoints, mappings, and configuration for Fyers API v3
+ */
+
+import type { StockBrokerMetadata } from '../../types';
+
+// ============================================================================
+// API CONFIGURATION
+// ============================================================================
+
+export const FYERS_API_BASE_URL = 'https://api-t1.fyers.in';
+export const FYERS_LOGIN_URL = 'https://api-t1.fyers.in/api/v3/generate-authcode';
+export const FYERS_API_VERSION = 'v3';
+
+export const FYERS_ENDPOINTS = {
+ // Auth
+ VALIDATE_AUTHCODE: '/api/v3/validate-authcode',
+ GENERATE_AUTHCODE: '/api/v3/generate-authcode',
+
+ // Orders
+ ORDERS: '/api/v3/orders',
+ TRADEBOOK: '/api/v3/tradebook',
+
+ // Portfolio
+ POSITIONS: '/api/v3/positions',
+ HOLDINGS: '/api/v3/holdings',
+
+ // Account
+ FUNDS: '/api/v3/funds',
+ PROFILE: '/api/v3/profile',
+
+ // Market Data
+ QUOTES: '/data-rest/v3/quotes',
+ HISTORICAL: '/data-rest/v3/history',
+ MARKET_DEPTH: '/data-rest/v3/depth',
+ SYMBOL_MASTER: '/data-rest/v3/symbol-master',
+} as const;
+
+// ============================================================================
+// WEBSOCKET CONFIGURATION
+// ============================================================================
+
+export const FYERS_WS_URL = 'wss://socket.fyers.in/hsm/v1-5/prod';
+
+// ============================================================================
+// EXCHANGE MAPPINGS
+// ============================================================================
+
+export const FYERS_EXCHANGE_MAP: Record<string, string> = {
+ NSE: 'NSE',
+ BSE: 'BSE',
+ NFO: 'NFO',
+ BFO: 'BFO',
+ CDS: 'CDS',
+ MCX: 'MCX',
+ NSE_INDEX: 'NSE',
+ BSE_INDEX: 'BSE',
+};
+
+// Exchange segment codes (used in symbol format)
+export const FYERS_EXCHANGE_SEGMENTS: Record<string, string> = {
+ NSE: '10:10', // NSE Cash
+ NFO: '10:11', // NSE F&O
+ BSE: '12:10', // BSE Cash
+ BFO: '12:11', // BSE F&O
+ CDS: '10:12', // Currency Derivatives
+ MCX: '11:20', // MCX F&O
+};
+
+// ============================================================================
+// PRODUCT TYPE MAPPINGS
+// ============================================================================
+
+export const FYERS_PRODUCT_MAP: Record<string, string> = {
+ CASH: 'CNC',
+ INTRADAY: 'INTRADAY',
+ MARGIN: 'MARGIN',
+ COVER: 'CO',
+ BRACKET: 'BO',
+};
+
+export const FYERS_PRODUCT_REVERSE_MAP: Record<string, string> = {
+ CNC: 'CASH',
+ INTRADAY: 'INTRADAY',
+ MARGIN: 'MARGIN',
+ CO: 'COVER',
+ BO: 'BRACKET',
+};
+
+// ============================================================================
+// ORDER TYPE MAPPINGS
+// ============================================================================
+
+// Fyers order types: 1=Limit, 2=Market, 3=Stop Loss Limit, 4=Stop Loss Market
+export const FYERS_ORDER_TYPE_MAP: Record<string, number> = {
+ MARKET: 2,
+ LIMIT: 1,
+ STOP_LIMIT: 3,
+ STOP_MARKET: 4,
+};
+
+export const FYERS_ORDER_TYPE_REVERSE_MAP: Record<number, string> = {
+ 1: 'LIMIT',
+ 2: 'MARKET',
+ 3: 'STOP_LIMIT',
+ 4: 'STOP_MARKET',
+};
+
+// ============================================================================
+// ORDER SIDE MAPPINGS
+// ============================================================================
+
+// Fyers side: 1=Buy, -1=Sell
+export const FYERS_SIDE_MAP: Record<string, number> = {
+ BUY: 1,
+ SELL: -1,
+};
+
+export const FYERS_SIDE_REVERSE_MAP: Record<string, string> = {
+ '1': 'BUY',
+ '-1': 'SELL',
+};
+
+// ============================================================================
+// ORDER STATUS MAPPINGS
+// ============================================================================
+
+// Fyers status codes
+export const FYERS_STATUS_MAP: Record<number, string> = {
+ 1: 'PENDING', // Pending
+ 2: 'FILLED', // Filled/Executed
+ 3: 'CANCELLED', // Cancelled
+ 4: 'REJECTED', // Rejected
+ 5: 'REJECTED', // Invalid Order
+ 6: 'OPEN', // Open/Placed
+ 7: 'PENDING', // Pending
+};
+
+// ============================================================================
+// VALIDITY MAPPINGS
+// ============================================================================
+
+export const FYERS_VALIDITY_MAP: Record<string, string> = {
+ DAY: 'DAY',
+ IOC: 'IOC',
+};
+
+// ============================================================================
+// BROKER METADATA
+// ============================================================================
+
+export const FYERS_METADATA: StockBrokerMetadata = {
+ id: 'fyers',
+ name: 'fyers',
+ displayName: 'Fyers',
+ logo: '/brokers/fyers.png',
+ website: 'https://fyers.in',
+
+ region: 'india',
+ country: 'IN',
+ currency: 'INR',
+ exchanges: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'],
+ marketHours: {
+ open: '09:15',
+ close: '15:30',
+ timezone: 'Asia/Kolkata',
+ preMarketOpen: '09:00',
+ preMarketClose: '09:08',
+ },
+
+ features: {
+ webSocket: true,
+ amo: true,
+ gtt: false,
+ bracketOrder: true,
+ coverOrder: true,
+ marginCalculator: false,
+ optionsChain: true,
+ paperTrading: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true,
+ stopLimitOrders: true,
+ trailingStopOrders: false,
+ },
+
+ productTypes: ['CASH', 'INTRADAY', 'MARGIN'],
+
+ authType: 'oauth',
+
+ rateLimit: {
+ ordersPerSecond: 10,
+ quotesPerSecond: 5,
+ },
+
+ fees: {
+ equity: { brokerage: 0, stt: 0.001 },
+ intraday: { brokerage: 0.0003 },
+ fno: { brokerage: 20 },
+ },
+
+ defaultSymbols: [
+ 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',
+ 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',
+ 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',
+ ],
+};
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/index.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/index.ts
new file mode 100644
index 000000000..e51d10c40
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/index.ts
@@ -0,0 +1,7 @@
+/**
+ * Fyers Broker Module
+ */
+
+export { FyersAdapter } from './FyersAdapter';
+export { FYERS_METADATA, FYERS_EXCHANGE_MAP } from './constants';
+export * from './mapper';
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/mapper.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/mapper.ts
new file mode 100644
index 000000000..b01627493
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/mapper.ts
@@ -0,0 +1,475 @@
+/**
+ * Fyers Data Mappers
+ *
+ * Transform between Fyers API format and standard stock broker format
+ */
+
+import type {
+ Order,
+ Trade,
+ Position,
+ Holding,
+ Funds,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ DepthLevel,
+ OrderParams,
+ ModifyOrderParams,
+ TimeFrame,
+ OrderStatus,
+ OrderSide,
+ OrderType,
+ ProductType,
+ StockExchange,
+ TickData,
+ SubscriptionMode,
+} from '../../types';
+
+import {
+ FYERS_EXCHANGE_MAP,
+ FYERS_PRODUCT_MAP,
+ FYERS_PRODUCT_REVERSE_MAP,
+ FYERS_ORDER_TYPE_MAP,
+ FYERS_ORDER_TYPE_REVERSE_MAP,
+ FYERS_SIDE_MAP,
+ FYERS_SIDE_REVERSE_MAP,
+ FYERS_STATUS_MAP,
+ FYERS_VALIDITY_MAP,
+} from './constants';
+
+// ============================================================================
+// ORDER MAPPERS
+// ============================================================================
+
+/**
+ * Convert standard order params to Fyers format
+ */
+export function toFyersOrderParams(params: OrderParams): Record<string, unknown> {
+ const orderType = FYERS_ORDER_TYPE_MAP[params.orderType] || 2; // Default to Market
+ const side = FYERS_SIDE_MAP[params.side] || 1; // Default to BUY
+
+ // Build Fyers symbol format: EXCHANGE:SYMBOL-INSTRUMENTTYPE
+ // Use toFyersSymbol() to ensure correct format (e.g., NSE:RELIANCE-EQ)
+ const fyersSymbol = toFyersSymbol(params.symbol, params.exchange);
+
+ return {
+ symbol: fyersSymbol,
+ qty: params.quantity,
+ type: orderType,
+ side: side,
+ productType: FYERS_PRODUCT_MAP[params.productType] || 'CNC',
+ limitPrice: params.price || 0,
+ stopPrice: params.triggerPrice || 0,
+ validity: FYERS_VALIDITY_MAP[params.validity || 'DAY'] || 'DAY',
+ disclosedQty: params.disclosedQuantity || 0,
+ offlineOrder: false,
+ };
+}
+
+/**
+ * Convert modify order params to Fyers format
+ */
+export function toFyersModifyParams(orderId: string, params: ModifyOrderParams): Record<string, unknown> {
+ const fyersParams: Record<string, unknown> = {
+ id: orderId,
+ };
+
+ if (params.quantity !== undefined) {
+ fyersParams.qty = params.quantity;
+ }
+ if (params.price !== undefined) {
+ fyersParams.limitPrice = params.price;
+ }
+ if (params.triggerPrice !== undefined) {
+ fyersParams.stopPrice = params.triggerPrice;
+ }
+ if (params.orderType !== undefined) {
+ fyersParams.type = FYERS_ORDER_TYPE_MAP[params.orderType] || 2;
+ }
+
+ return fyersParams;
+}
+
+/**
+ * Convert Fyers order to standard format
+ */
+export function fromFyersOrder(order: Record<string, unknown>): Order {
+ // Parse symbol (format: EXCHANGE:SYMBOL)
+ const symbolStr = String(order.symbol || '');
+ const [exchange, symbol] = symbolStr.includes(':') ? symbolStr.split(':') : ['NSE', symbolStr];
+
+ // Map status code to string
+ const statusCode = Number(order.status || 6);
+ const status = FYERS_STATUS_MAP[statusCode] || 'PENDING';
+
+ // Map side (-1 = Sell, 1 = Buy)
+ const sideCode = Number(order.side || 1);
+ const side = FYERS_SIDE_REVERSE_MAP[sideCode] || 'BUY';
+
+ // Map order type
+ const typeCode = Number(order.type || 2);
+ const orderType = FYERS_ORDER_TYPE_REVERSE_MAP[typeCode] || 'MARKET';
+
+ return {
+ orderId: String(order.id || ''),
+ symbol,
+ exchange: exchange as StockExchange,
+ side: side as OrderSide,
+ quantity: Number(order.qty || 0),
+ filledQuantity: Number(order.filledQty || 0),
+ pendingQuantity: Number(order.qty || 0) - Number(order.filledQty || 0),
+ price: Number(order.limitPrice || 0),
+ averagePrice: Number(order.tradedPrice || order.limitPrice || 0),
+ triggerPrice: order.stopPrice ? Number(order.stopPrice) : undefined,
+ orderType: orderType as OrderType,
+ productType: (FYERS_PRODUCT_REVERSE_MAP[String(order.productType)] || 'CASH') as ProductType,
+ validity: String(order.validity || 'DAY') as 'DAY' | 'IOC' | 'GTC' | 'GTD',
+ status: status as OrderStatus,
+ statusMessage: order.message ? String(order.message) : undefined,
+ placedAt: order.orderDateTime ? new Date(order.orderDateTime as string) : new Date(),
+ updatedAt: order.orderDateTime ? new Date(order.orderDateTime as string) : undefined,
+ exchangeOrderId: order.exchOrdId ? String(order.exchOrdId) : undefined,
+ tag: order.clientId ? String(order.clientId) : undefined,
+ };
+}
+
+// ============================================================================
+// TRADE MAPPERS
+// ============================================================================
+
+/**
+ * Convert Fyers trade to standard format
+ */
+export function fromFyersTrade(trade: Record<string, unknown>): Trade {
+ // Parse symbol (format: EXCHANGE:SYMBOL)
+ const symbolStr = String(trade.symbol || '');
+ const [exchange, symbol] = symbolStr.includes(':') ? symbolStr.split(':') : ['NSE', symbolStr];
+
+ // Map side
+ const sideCode = Number(trade.side || 1);
+ const side = FYERS_SIDE_REVERSE_MAP[sideCode] || 'BUY';
+
+ return {
+ tradeId: String(trade.tradeNumber || trade.id || ''),
+ orderId: String(trade.id || ''),
+ symbol,
+ exchange: exchange as StockExchange,
+ side: side as OrderSide,
+ quantity: Number(trade.tradedQty || trade.qty || 0),
+ price: Number(trade.tradedPrice || 0),
+ productType: (FYERS_PRODUCT_REVERSE_MAP[String(trade.productType)] || 'CASH') as ProductType,
+ tradedAt: trade.orderDateTime ? new Date(trade.orderDateTime as string) : new Date(),
+ exchangeTradeId: trade.exchOrdId ? String(trade.exchOrdId) : undefined,
+ };
+}
+
+// ============================================================================
+// POSITION MAPPERS
+// ============================================================================
+
+/**
+ * Convert Fyers position to standard format
+ */
+export function fromFyersPosition(position: Record<string, unknown>): Position {
+ // Parse symbol
+ const symbolStr = String(position.symbol || '');
+ const [exchange, symbol] = symbolStr.includes(':') ? symbolStr.split(':') : ['NSE', symbolStr];
+
+ const netQty = Number(position.netQty || 0);
+ const buyQty = Number(position.buyQty || 0);
+ const sellQty = Number(position.sellQty || 0);
+ const buyAvg = Number(position.buyAvg || 0);
+ const sellAvg = Number(position.sellAvg || 0);
+ const ltp = Number(position.ltp || position.marketVal || 0);
+
+ // Calculate average price
+ const avgPrice = netQty > 0 ? buyAvg : sellAvg;
+
+ // Calculate P&L
+ const pnl = Number(position.pl || position.realizedProfit || 0);
+ const pnlPercent = avgPrice > 0 ? ((ltp - avgPrice) / avgPrice) * 100 : 0;
+
+ return {
+ symbol,
+ exchange: exchange as StockExchange,
+ productType: (FYERS_PRODUCT_REVERSE_MAP[String(position.productType)] || 'INTRADAY') as ProductType,
+ quantity: netQty,
+ buyQuantity: buyQty,
+ sellQuantity: sellQty,
+ buyValue: buyQty * buyAvg,
+ sellValue: sellQty * sellAvg,
+ averagePrice: avgPrice,
+ lastPrice: ltp,
+ pnl,
+ pnlPercent,
+ dayPnl: pnl,
+ overnight: false,
+ };
+}
+
+// ============================================================================
+// HOLDING MAPPERS
+// ============================================================================
+
+/**
+ * Convert Fyers holding to standard format
+ */
+export function fromFyersHolding(holding: Record<string, unknown>): Holding {
+ // Parse symbol
+ const symbolStr = String(holding.symbol || '');
+ const [exchange, symbol] = symbolStr.includes(':') ? symbolStr.split(':') : ['NSE', symbolStr];
+
+ const quantity = Number(holding.quantity || holding.holdingQty || 0);
+ const avgPrice = Number(holding.buyAvg || holding.costPrice || 0);
+ const lastPrice = Number(holding.ltp || holding.marketVal || 0);
+ const investedValue = quantity * avgPrice;
+ const currentValue = quantity * lastPrice;
+ const pnl = Number(holding.pl || (currentValue - investedValue));
+ const pnlPercent = investedValue > 0 ? (pnl / investedValue) * 100 : 0;
+
+ return {
+ symbol,
+ exchange: exchange as StockExchange,
+ quantity,
+ averagePrice: avgPrice,
+ lastPrice,
+ investedValue,
+ currentValue,
+ pnl,
+ pnlPercent,
+ isin: holding.isin ? String(holding.isin) : undefined,
+ };
+}
+
+// ============================================================================
+// FUNDS MAPPERS
+// ============================================================================
+
+/**
+ * Convert Fyers funds to standard format
+ * Processes both equity (id=10) and commodity (id=11) segments
+ */
+export function fromFyersFunds(funds: Record<string, unknown>): Funds {
+ // Fyers fund structure
+ const fundLimit = (funds.fund_limit as Array<Record<string, unknown>>) || [];
+
+ // Find equity segment data (id=10)
+ const equityFund = fundLimit.find(f => f.id === 10) || {};
+
+ // Find commodity segment data (id=11)
+ const commodityFund = fundLimit.find(f => f.id === 11) || {};
+
+ const equityMargin = Number(equityFund.equityMargin || 0);
+ const equityUsed = Number(equityFund.utilizedMargin || 0);
+ const equityAvailable = equityMargin - equityUsed;
+
+ const commodityMargin = Number(commodityFund.equityMargin || 0);
+ const commodityUsed = Number(commodityFund.utilizedMargin || 0);
+ const commodityAvailable = commodityMargin - commodityUsed;
+
+ // Total calculations (equity + commodity)
+ const totalMargin = equityMargin + commodityMargin;
+ const totalUsed = equityUsed + commodityUsed;
+ const totalAvailable = equityAvailable + commodityAvailable;
+
+ return {
+ availableCash: totalAvailable,
+ usedMargin: totalUsed,
+ availableMargin: totalAvailable,
+ totalBalance: totalMargin,
+ currency: 'INR',
+ equityAvailable,
+ commodityAvailable,
+ collateral: Number(equityFund.collateralAmount || 0) + Number(commodityFund.collateralAmount || 0),
+ unrealizedPnl: Number(equityFund.unmrealizedMtomPrsnt || 0) + Number(commodityFund.unmrealizedMtomPrsnt || 0),
+ realizedPnl: Number(equityFund.realizedMtomPrsnt || 0) + Number(commodityFund.realizedMtomPrsnt || 0),
+ };
+}
+
+// ============================================================================
+// QUOTE MAPPERS
+// ============================================================================
+
+/**
+ * Convert Fyers quote to standard format
+ */
+export function fromFyersQuote(quote: Record<string, unknown>): Quote {
+ // Parse symbol
+ const symbolStr = String(quote.n || quote.symbol || '');
+ const [exchange, symbol] = symbolStr.includes(':') ? symbolStr.split(':') : ['NSE', symbolStr];
+
+ const v = quote.v as Record<string, unknown> || quote;
+
+ const lastPrice = Number(v.lp || quote.ltp || 0);
+ const prevClose = Number(v.prev_close_price || quote.prev_close_price || 0);
+ const change = Number(v.ch || quote.ch || (lastPrice - prevClose));
+ const changePercent = prevClose > 0 ? (change / prevClose) * 100 : 0;
+
+ return {
+ symbol,
+ exchange: exchange as StockExchange,
+ lastPrice,
+ open: Number(v.open_price || quote.open_price || 0),
+ high: Number(v.high_price || quote.high_price || 0),
+ low: Number(v.low_price || quote.low_price || 0),
+ close: lastPrice,
+ previousClose: prevClose,
+ change,
+ changePercent: Number(v.chp || quote.chp || changePercent),
+ volume: Number(v.volume || v.vol_traded_today || quote.volume || 0),
+ averagePrice: Number(v.avg_trade_price || quote.avg_trade_price || 0),
+ bid: Number(v.bid || v.bid_price || quote.best_bid_price || 0),
+ bidQty: Number(v.bid_size || quote.best_bid_qty || 0),
+ ask: Number(v.ask || v.ask_price || quote.best_ask_price || 0),
+ askQty: Number(v.ask_size || quote.best_ask_qty || 0),
+ timestamp: Date.now(),
+ openInterest: Number(v.oi || quote.oi || 0),
+ };
+}
+
+// ============================================================================
+// TICK DATA MAPPERS
+// ============================================================================
+
+/**
+ * Convert Fyers tick data to standard format
+ */
+export function fromFyersTickData(tick: Record<string, unknown>): TickData {
+ // Parse symbol
+ const symbolStr = String(tick.symbol || tick.ticker || '');
+ const [exchange, symbol] = symbolStr.includes(':') ? symbolStr.split(':') : ['NSE', symbolStr];
+
+ return {
+ symbol,
+ exchange: exchange as StockExchange,
+ mode: 'full',
+ lastPrice: Number(tick.ltp || tick.last_price || 0),
+ timestamp: tick.feed_time ? Number(tick.feed_time) : Date.now(),
+ volume: Number(tick.volume || tick.vol_traded_today || 0),
+ open: Number(tick.open_price || 0),
+ high: Number(tick.high_price || 0),
+ low: Number(tick.low_price || 0),
+ close: Number(tick.prev_close_price || 0),
+ change: Number(tick.ch || 0),
+ changePercent: Number(tick.chp || 0),
+ bid: Number(tick.bid_price || tick.best_bid_price || 0),
+ bidQty: Number(tick.bid_size || tick.best_bid_qty || 0),
+ ask: Number(tick.ask_price || tick.best_ask_price || 0),
+ askQty: Number(tick.ask_size || tick.best_ask_qty || 0),
+ openInterest: Number(tick.oi || 0),
+ };
+}
+
+// ============================================================================
+// MARKET DEPTH MAPPERS
+// ============================================================================
+
+/**
+ * Convert Fyers market depth to standard format
+ */
+export function fromFyersDepth(depth: Record<string, unknown>): MarketDepth {
+ const bids: DepthLevel[] = [];
+ const asks: DepthLevel[] = [];
+
+ // Fyers provides depth data in asks and bids arrays
+ const asksData = (depth.asks as Array<Record<string, unknown>>) || [];
+ const bidsData = (depth.bids as Array<Record<string, unknown>>) || [];
+
+ // Convert asks
+ for (const ask of asksData.slice(0, 5)) {
+ asks.push({
+ price: Number(ask.price || 0),
+ quantity: Number(ask.qty || ask.volume || 0),
+ orders: Number(ask.nord || ask.orders || 0),
+ });
+ }
+
+ // Convert bids
+ for (const bid of bidsData.slice(0, 5)) {
+ bids.push({
+ price: Number(bid.price || 0),
+ quantity: Number(bid.qty || bid.volume || 0),
+ orders: Number(bid.nord || bid.orders || 0),
+ });
+ }
+
+ return {
+ bids,
+ asks,
+ };
+}
+
+// ============================================================================
+// SYMBOL MAPPERS
+// ============================================================================
+
+/**
+ * Convert symbol to Fyers format (EXCHANGE:SYMBOL-INSTRUMENTTYPE)
+ *
+ * Fyers requires instrument type suffix:
+ * - NSE/BSE equity: -EQ (e.g., NSE:RELIANCE-EQ)
+ * - Futures: -FUT
+ * - Options: -OPT
+ *
+ * @param symbol - The stock symbol (e.g., "RELIANCE", "SBIN")
+ * @param exchange - The exchange (NSE, BSE, etc.)
+ * @param instrumentType - Optional instrument type suffix (defaults to "EQ" for equity)
+ */
+export function toFyersSymbol(
+ symbol: string,
+ exchange: StockExchange,
+ instrumentType: string = 'EQ'
+): string {
+ const fyersExchange = FYERS_EXCHANGE_MAP[exchange] || exchange;
+
+ // Fyers format: EXCHANGE:SYMBOL-INSTRUMENTTYPE
+ // Example: NSE:RELIANCE-EQ, BSE:SBIN-EQ
+ return `${fyersExchange}:${symbol}-${instrumentType}`;
+}
+
+/**
+ * Parse Fyers symbol format to separate exchange and symbol
+ *
+ * Parses format: EXCHANGE:SYMBOL-INSTRUMENTTYPE
+ * Example: NSE:RELIANCE-EQ -> { exchange: "NSE", symbol: "RELIANCE" }
+ */
+export function fromFyersSymbol(fyersSymbol: string): { exchange: StockExchange; symbol: string } {
+ const [exchange, symbolWithSuffix] = fyersSymbol.includes(':')
+ ? fyersSymbol.split(':')
+ : ['NSE', fyersSymbol];
+
+ // Remove instrument type suffix (e.g., -EQ, -FUT, -OPT)
+ const symbol = symbolWithSuffix.includes('-')
+ ? symbolWithSuffix.split('-')[0]
+ : symbolWithSuffix;
+
+ return {
+ exchange: exchange as StockExchange,
+ symbol,
+ };
+}
+
+/**
+ * Convert standard TimeFrame to Fyers API resolution format
+ *
+ * Fyers API expects: 1, 2, 3, 5, 10, 15, 20, 30, 60, 120, 240, 1D
+ * Standard format: 1m, 3m, 5m, 10m, 15m, 30m, 1h, 2h, 4h, 1d, 1w, 1M
+ */
+export function toFyersInterval(timeframe: TimeFrame): string {
+ switch (timeframe) {
+ case '1m': return '1';
+ case '3m': return '3';
+ case '5m': return '5';
+ case '10m': return '10';
+ case '15m': return '15';
+ case '30m': return '30';
+ case '1h': return '60';
+ case '2h': return '120';
+ case '4h': return '240';
+ case '1d': return '1D';
+ case '1w': return '1D'; // Fyers doesn't support weekly, use daily
+ case '1M': return '1D'; // Fyers doesn't support monthly, use daily
+ default: return '5'; // Default to 5 minutes
+ }
+}
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/index.ts b/fincept-terminal-desktop/src/brokers/stocks/india/index.ts
new file mode 100644
index 000000000..50e222c80
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/index.ts
@@ -0,0 +1,17 @@
+/**
+ * Indian Stock Brokers Module
+ */
+
+// Zerodha
+export * from './zerodha';
+
+// Fyers
+export * from './fyers';
+
+// Angel One
+export * from './angelone';
+
+// Future brokers
+// export * from './dhan';
+// export * from './upstox';
+// export * from './groww';
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.ts
new file mode 100644
index 000000000..c620e40b4
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.ts
@@ -0,0 +1,1296 @@
+/**
+ * Zerodha Stock Broker Adapter
+ *
+ * Implements IStockBrokerAdapter for Zerodha Kite Connect API
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+import { listen, UnlistenFn } from '@tauri-apps/api/event';
+import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';
+import type {
+ StockBrokerMetadata,
+ Region,
+ BrokerCredentials,
+ AuthResponse,
+ AuthCallbackParams,
+ Funds,
+ MarginRequired,
+ OrderParams,
+ OrderResponse,
+ ModifyOrderParams,
+ Order,
+ Trade,
+ Position,
+ Holding,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ TimeFrame,
+ StockExchange,
+ WebSocketConfig,
+ SubscriptionMode,
+ BulkOperationResult,
+ SmartOrderParams,
+ TickData,
+ Instrument,
+ InstrumentType,
+} from '../../types';
+import {
+ ZERODHA_METADATA,
+ ZERODHA_LOGIN_URL,
+ ZERODHA_EXCHANGE_MAP,
+} from './constants';
+import {
+ toZerodhaOrderParams,
+ toZerodhaModifyParams,
+ toZerodhaInterval,
+ toZerodhaMarginParams,
+ toZerodhaWSMode,
+ fromZerodhaOrder,
+ fromZerodhaTrade,
+ fromZerodhaPosition,
+ fromZerodhaHolding,
+ fromZerodhaFunds,
+ fromZerodhaQuote,
+ fromZerodhaOHLCV,
+ fromZerodhaDepth,
+ fromZerodhaTick,
+} from './mapper';
+
+/**
+ * Zerodha broker adapter
+ */
+export class ZerodhaAdapter extends BaseStockBrokerAdapter {
+ readonly brokerId = 'zerodha';
+ readonly brokerName = 'Zerodha';
+ readonly region: Region = 'india';
+ readonly metadata: StockBrokerMetadata = ZERODHA_METADATA;
+
+ private apiKey: string | null = null;
+ private apiSecret: string | null = null;
+
+ // REST API polling for quotes (instead of WebSocket)
+ private quotePollingInterval: NodeJS.Timeout | null = null;
+ private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();
+
+ // Legacy WebSocket support (deprecated - use REST API polling)
+ // Token to symbol mapping for WebSocket
+ private tokenSymbolMap: Map<number, { symbol: string; exchange: StockExchange }> = new Map();
+
+ // Tauri event unlisteners
+ private eventUnlisteners: UnlistenFn[] = [];
+
+ // ============================================================================
+ // Authentication
+ // ============================================================================
+
+ /**
+ * Get OAuth login URL
+ */
+ getAuthUrl(): string {
+ if (!this.apiKey) {
+ throw new Error('API key not set. Call setCredentials first.');
+ }
+ return `${ZERODHA_LOGIN_URL}?api_key=${this.apiKey}&v=3`;
+ }
+
+ /**
+ * Set API credentials before authentication
+ */
+ setCredentials(apiKey: string, apiSecret: string): void {
+ this.apiKey = apiKey;
+ this.apiSecret = apiSecret;
+ }
+
+ /**
+ * Authenticate with stored or new credentials
+ */
+ async authenticate(credentials: BrokerCredentials): Promise<AuthResponse> {
+ try {
+ this.apiKey = credentials.apiKey;
+ this.apiSecret = credentials.apiSecret || null;
+
+ // Check if this is a request_token that needs to be exchanged (OAuth callback)
+ const requestToken = (credentials as any).requestToken;
+ if (requestToken) {
+ console.log('[ZerodhaAdapter] Request token detected, exchanging for access token...');
+ return this.handleAuthCallback({ requestToken });
+ }
+
+ // If access token provided, validate it
+ if (credentials.accessToken) {
+ console.log('[ZerodhaAdapter] Access token provided, validating...');
+ const isValid = await this.validateToken(credentials.accessToken);
+ if (isValid) {
+ this.accessToken = credentials.accessToken;
+ this.userId = credentials.userId || null;
+ this._isConnected = true;
+
+ await this.storeCredentials(credentials);
+
+ return {
+ success: true,
+ accessToken: this.accessToken,
+ userId: this.userId || undefined,
+ message: 'Authentication successful',
+ };
+ } else {
+ console.error('[ZerodhaAdapter] Access token validation failed');
+ return {
+ success: false,
+ message: 'Invalid or expired access token',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+ }
+
+ // Need to go through OAuth flow
+ console.warn('[ZerodhaAdapter] No access token or request token provided');
+ return {
+ success: false,
+ message: 'Please complete OAuth login',
+ errorCode: 'AUTH_REQUIRED',
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Authentication failed',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+ }
+
+ /**
+ * Handle OAuth callback
+ */
+ async handleAuthCallback(params: AuthCallbackParams): Promise<AuthResponse> {
+ try {
+ if (!params.requestToken) {
+ return {
+ success: false,
+ message: 'Request token not provided',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+
+ if (!this.apiKey || !this.apiSecret) {
+ return {
+ success: false,
+ message: 'API credentials not set',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+
+ // Exchange request token for access token via Rust backend
+ const response = await invoke<{
+ success: boolean;
+ access_token?: string;
+ user_id?: string;
+ error?: string;
+ }>('zerodha_exchange_token', {
+ apiKey: this.apiKey,
+ apiSecret: this.apiSecret,
+ requestToken: params.requestToken,
+ });
+
+ if (!response.success || !response.access_token) {
+ return {
+ success: false,
+ message: response.error || 'Token exchange failed',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+
+ this.accessToken = response.access_token;
+ this.userId = response.user_id || null;
+ this._isConnected = true;
+
+ // Store credentials
+ await this.storeCredentials({
+ apiKey: this.apiKey,
+ apiSecret: this.apiSecret,
+ accessToken: this.accessToken,
+ userId: this.userId || undefined,
+ });
+
+ return {
+ success: true,
+ accessToken: this.accessToken,
+ userId: this.userId || undefined,
+ message: 'Authentication successful',
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Auth callback failed',
+ errorCode: 'AUTH_FAILED',
+ };
+ }
+ }
+
+ /**
+ * Validate access token
+ */
+ private async validateToken(token: string): Promise<boolean> {
+ try {
+ const response = await invoke<{ success: boolean }>('zerodha_validate_token', {
+ apiKey: this.apiKey,
+ accessToken: token,
+ });
+ return response.success;
+ } catch {
+ return false;
+ }
+ }
+
+ /**
+ * Initialize from stored credentials
+ */
+ async initFromStorage(): Promise<boolean> {
+ try {
+ const credentials = await this.loadCredentials();
+ if (!credentials) return false;
+
+ this.apiKey = credentials.apiKey;
+ this.apiSecret = credentials.apiSecret || null;
+ this.accessToken = credentials.accessToken || null;
+
+ if (this.accessToken) {
+ console.log('[Zerodha] Validating stored access token...');
+ const isValid = await this.validateToken(this.accessToken);
+
+ if (!isValid) {
+ console.warn('[Zerodha] Access token expired or invalid, clearing from storage...');
+
+ // Clear expired token from database
+ await this.storeCredentials({
+ apiKey: this.apiKey,
+ apiSecret: this.apiSecret || '',
+ // No accessToken = clears it
+ });
+
+ this.accessToken = null;
+ this._isConnected = false;
+
+ console.log('[Zerodha] Please re-authenticate to continue');
+ return false;
+ }
+
+ console.log('[Zerodha] ✓ Token is valid, session restored');
+ this._isConnected = isValid;
+ return isValid;
+ }
+
+ return false;
+ } catch {
+ return false;
+ }
+ }
+
+ // ============================================================================
+ // Orders
+ // ============================================================================
+
+ protected async placeOrderInternal(params: OrderParams): Promise<OrderResponse> {
+ const zerodhaParams = toZerodhaOrderParams(params);
+ const variety = params.amo ? 'amo' : 'regular';
+
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('zerodha_place_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ params: zerodhaParams,
+ variety,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ protected async modifyOrderInternal(params: ModifyOrderParams): Promise<OrderResponse> {
+ const zerodhaParams = toZerodhaModifyParams(params);
+
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('zerodha_modify_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ orderId: params.orderId,
+ params: zerodhaParams,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ protected async cancelOrderInternal(orderId: string): Promise<OrderResponse> {
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('zerodha_cancel_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ orderId,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ protected async getOrdersInternal(): Promise<Order[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>[];
+ error?: string;
+ }>('zerodha_get_orders', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(fromZerodhaOrder);
+ }
+
+ protected async getTradeBookInternal(): Promise<Trade[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>[];
+ error?: string;
+ }>('zerodha_get_trade_book', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(fromZerodhaTrade);
+ }
+
+ // ============================================================================
+ // Bulk Operations
+ // ============================================================================
+
+ protected async cancelAllOrdersInternal(): Promise<BulkOperationResult> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Array<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>;
+ error?: string;
+ }>('zerodha_cancel_all_orders', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ success: false,
+ totalCount: 0,
+ successCount: 0,
+ failedCount: 0,
+ results: [],
+ };
+ }
+
+ const results = response.data.map(r => ({
+ success: r.success,
+ orderId: r.order_id,
+ error: r.error,
+ }));
+
+ return {
+ success: true,
+ totalCount: results.length,
+ successCount: results.filter(r => r.success).length,
+ failedCount: results.filter(r => !r.success).length,
+ results,
+ };
+ }
+
+ protected async closeAllPositionsInternal(): Promise<BulkOperationResult> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Array<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>;
+ error?: string;
+ }>('zerodha_close_all_positions', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ success: false,
+ totalCount: 0,
+ successCount: 0,
+ failedCount: 0,
+ results: [],
+ };
+ }
+
+ const results = response.data.map(r => ({
+ success: r.success,
+ orderId: r.order_id,
+ error: r.error,
+ }));
+
+ return {
+ success: true,
+ totalCount: results.length,
+ successCount: results.filter(r => r.success).length,
+ failedCount: results.filter(r => !r.success).length,
+ results,
+ };
+ }
+
+ // ============================================================================
+ // Smart Order
+ // ============================================================================
+
+ protected async placeSmartOrderInternal(params: SmartOrderParams): Promise<OrderResponse> {
+ const zerodhaExchange = ZERODHA_EXCHANGE_MAP[params.exchange] || params.exchange;
+
+ // Get current position size if not provided
+ let positionSize = params.positionSize ?? 0;
+ if (params.positionSize === undefined) {
+ const position = await this.getOpenPosition(params.symbol, params.exchange, params.productType);
+ positionSize = position?.quantity ?? 0;
+ }
+
+ const response = await invoke<{
+ success: boolean;
+ order_id?: string;
+ error?: string;
+ }>('zerodha_place_smart_order', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ tradingsymbol: params.symbol,
+ exchange: zerodhaExchange,
+ product: params.productType,
+ action: params.side,
+ quantity: params.quantity,
+ orderType: params.orderType,
+ price: params.price,
+ triggerPrice: params.triggerPrice,
+ positionSize,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.order_id,
+ message: response.error,
+ };
+ }
+
+ // ============================================================================
+ // Positions & Holdings
+ // ============================================================================
+
+ protected async getPositionsInternal(): Promise<Position[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ net?: Record<string, unknown>[];
+ day?: Record<string, unknown>[];
+ };
+ error?: string;
+ }>('zerodha_get_positions', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ const positions = response.data.net || [];
+ return positions.map(fromZerodhaPosition);
+ }
+
+ protected async getHoldingsInternal(): Promise<Holding[]> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>[];
+ error?: string;
+ }>('zerodha_get_holdings', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return [];
+ }
+
+ return response.data.map(fromZerodhaHolding);
+ }
+
+ protected async getFundsInternal(): Promise<Funds> {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ }>('zerodha_get_margins', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ availableCash: 0,
+ usedMargin: 0,
+ availableMargin: 0,
+ totalBalance: 0,
+ currency: 'INR',
+ };
+ }
+
+ return fromZerodhaFunds(response.data);
+ }
+
+ // ============================================================================
+ // Margin Calculator
+ // ============================================================================
+
+ protected async calculateMarginInternal(orders: OrderParams[]): Promise<MarginRequired> {
+ const zerodhaOrders = orders.map(toZerodhaMarginParams);
+
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ }>('zerodha_calculate_margin', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ orders: zerodhaOrders,
+ });
+
+ if (!response.success || !response.data) {
+ return {
+ totalMargin: 0,
+ initialMargin: 0,
+ };
+ }
+
+ const data = response.data;
+ const initial = Number(data.initial || data.total || 0);
+ const exposure = Number(data.exposure || 0);
+ const total = Number(data.total || initial + exposure);
+
+ return {
+ totalMargin: total,
+ initialMargin: initial,
+ exposureMargin: exposure,
+ spanMargin: data.span ? Number(data.span) : undefined,
+ optionPremium: data.option_premium ? Number(data.option_premium) : undefined,
+ orders: orders.map((o, i) => ({
+ symbol: o.symbol,
+ margin: Array.isArray(data.orders) ? Number((data.orders as Record<string, unknown>[])[i]?.margin || 0) : 0,
+ })),
+ };
+ }
+
+ // ============================================================================
+ // Market Data
+ // ============================================================================
+
+ protected async getQuoteInternal(symbol: string, exchange: StockExchange): Promise<Quote> {
+ const instrumentKey = `${ZERODHA_EXCHANGE_MAP[exchange] || exchange}:${symbol}`;
+
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, Record<string, unknown>>;
+ error?: string;
+ }>('zerodha_get_quote', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ instruments: [instrumentKey],
+ });
+
+ if (!response.success || !response.data) {
+ throw new Error(response.error || 'Failed to fetch quote');
+ }
+
+ const quoteData = response.data[instrumentKey];
+ if (!quoteData) {
+ throw new Error(`Quote not found for ${symbol}`);
+ }
+
+ return fromZerodhaQuote(quoteData, symbol, exchange);
+ }
+
+ /**
+ * Get multiple quotes in batch (up to 500 symbols per request)
+ * Automatically batches if more than 500 symbols
+ */
+ async getMultiQuotes(
+ symbols: Array<{ symbol: string; exchange: StockExchange }>
+ ): Promise<Array<{ symbol: string; exchange: StockExchange; quote?: Quote; error?: string }>> {
+ this.ensureConnected();
+
+ const BATCH_SIZE = 500;
+ const results: Array<{ symbol: string; exchange: StockExchange; quote?: Quote; error?: string }> = [];
+
+ // Process in batches of 500
+ for (let i = 0; i < symbols.length; i += BATCH_SIZE) {
+ const batch = symbols.slice(i, i + BATCH_SIZE);
+ const instrumentKeys = batch.map(
+ ({ symbol, exchange }) => `${ZERODHA_EXCHANGE_MAP[exchange] || exchange}:${symbol}`
+ );
+
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, Record<string, unknown>>;
+ error?: string;
+ }>('zerodha_get_quote', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ instruments: instrumentKeys,
+ });
+
+ if (!response.success || !response.data) {
+ // Mark all in batch as failed
+ batch.forEach(({ symbol, exchange }) => {
+ results.push({
+ symbol,
+ exchange,
+ error: response.error || 'Failed to fetch quotes',
+ });
+ });
+ continue;
+ }
+
+ // Parse each symbol's quote
+ batch.forEach(({ symbol, exchange }) => {
+ const instrumentKey = `${ZERODHA_EXCHANGE_MAP[exchange] || exchange}:${symbol}`;
+ const quoteData = response.data![instrumentKey];
+
+ if (quoteData) {
+ try {
+ const quote = fromZerodhaQuote(quoteData, symbol, exchange);
+ results.push({ symbol, exchange, quote });
+ } catch (error) {
+ results.push({
+ symbol,
+ exchange,
+ error: error instanceof Error ? error.message : 'Failed to parse quote',
+ });
+ }
+ } else {
+ results.push({
+ symbol,
+ exchange,
+ error: 'Quote not found',
+ });
+ }
+ });
+
+ // Rate limit delay between batches
+ if (i + BATCH_SIZE < symbols.length) {
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ }
+ } catch (error) {
+ // Mark all in batch as failed
+ batch.forEach(({ symbol, exchange }) => {
+ results.push({
+ symbol,
+ exchange,
+ error: error instanceof Error ? error.message : 'Request failed',
+ });
+ });
+ }
+ }
+
+ return results;
+ }
+
+ protected async getOHLCVInternal(
+ symbol: string,
+ exchange: StockExchange,
+ timeframe: TimeFrame,
+ from: Date,
+ to: Date
+ ): Promise<OHLCV[]> {
+ // Get instrument token
+ const instrument = await this.getInstrument(symbol, exchange);
+ if (!instrument?.token) {
+ throw new Error(`Instrument token not found for ${symbol}`);
+ }
+
+ const interval = toZerodhaInterval(timeframe);
+ const allCandles: OHLCV[] = [];
+
+ // Zerodha API has 60-day limit for historical data, so we chunk the request
+ const CHUNK_DAYS = 60;
+ let currentStart = new Date(from);
+ const endDate = new Date(to);
+
+ while (currentStart <= endDate) {
+ // Calculate chunk end date (60 days or remaining period)
+ const currentEnd = new Date(currentStart);
+ currentEnd.setDate(currentEnd.getDate() + CHUNK_DAYS - 1);
+
+ if (currentEnd > endDate) {
+ currentEnd.setTime(endDate.getTime());
+ }
+
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: {
+ candles?: unknown[][];
+ };
+ error?: string;
+ }>('zerodha_get_historical', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ instrumentToken: instrument.token,
+ interval,
+ from: currentStart.toISOString().split('T')[0],
+ to: currentEnd.toISOString().split('T')[0],
+ });
+
+ if (response.success && response.data?.candles) {
+ const candles = response.data.candles.map(fromZerodhaOHLCV);
+ allCandles.push(...candles);
+ }
+
+ // Move to next chunk
+ currentStart.setDate(currentEnd.getDate() + 1);
+
+ // Rate limit delay between chunks
+ if (currentStart <= endDate) {
+ await new Promise(resolve => setTimeout(resolve, 500));
+ }
+ } catch (error) {
+ console.error(`Failed to fetch OHLCV chunk from ${currentStart} to ${currentEnd}:`, error);
+ // Continue with next chunk instead of failing completely
+ currentStart.setDate(currentEnd.getDate() + 1);
+ }
+ }
+
+ // Sort by timestamp and remove duplicates
+ const uniqueCandles = allCandles
+ .sort((a, b) => a.timestamp - b.timestamp)
+ .filter((candle, index, arr) =>
+ index === 0 || candle.timestamp !== arr[index - 1].timestamp
+ );
+
+ return uniqueCandles;
+ }
+
+ protected async getMarketDepthInternal(symbol: string, exchange: StockExchange): Promise<MarketDepth> {
+ const instrumentKey = `${ZERODHA_EXCHANGE_MAP[exchange] || exchange}:${symbol}`;
+
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, Record<string, unknown>>;
+ error?: string;
+ }>('zerodha_get_quote', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ instruments: [instrumentKey],
+ });
+
+ if (!response.success || !response.data) {
+ return { bids: [], asks: [] };
+ }
+
+ const quoteData = response.data[instrumentKey];
+ if (!quoteData?.depth) {
+ return { bids: [], asks: [] };
+ }
+
+ return fromZerodhaDepth(quoteData.depth as Record<string, unknown>);
+ }
+
+ // ============================================================================
+ // REST API Polling (replaces WebSocket)
+ // ============================================================================
+
+ protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {
+ this.ensureConnected();
+
+ try {
+ if (!this.apiKey || !this.accessToken) {
+ throw new Error('API credentials not set');
+ }
+
+ // Start REST API polling (every 2 minutes as per requirement)
+ this.startQuotePolling();
+
+ this.wsConnected = true;
+ console.log('Zerodha: REST API polling started (2 min interval)');
+ } catch (error) {
+ console.error('Failed to start Zerodha polling:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * Start REST API polling for quotes
+ */
+ private startQuotePolling(): void {
+ // Stop existing polling
+ this.stopQuotePolling();
+
+ // Poll every 2 minutes (120000ms)
+ this.quotePollingInterval = setInterval(async () => {
+ await this.pollQuotesSequentially();
+ }, 120000);
+
+ // Initial poll
+ this.pollQuotesSequentially();
+ }
+
+ /**
+ * Stop REST API polling
+ */
+ private stopQuotePolling(): void {
+ if (this.quotePollingInterval) {
+ clearInterval(this.quotePollingInterval);
+ this.quotePollingInterval = null;
+ }
+ }
+
+ /**
+ * Poll quotes sequentially (not parallel) for all subscribed symbols
+ */
+ private async pollQuotesSequentially(): Promise<void> {
+ if (this.pollingSymbols.size === 0) {
+ return;
+ }
+
+ console.log(`[Zerodha] Polling ${this.pollingSymbols.size} symbols sequentially...`);
+
+ // Process each symbol one by one
+ for (const [key, { symbol, exchange }] of this.pollingSymbols) {
+ try {
+ // Fetch quote via REST API
+ const quote = await this.getQuoteInternal(symbol, exchange);
+
+ // Convert quote to tick and emit
+ const tick: TickData = {
+ symbol,
+ exchange,
+ mode: 'full',
+ lastPrice: quote.lastPrice,
+ open: quote.open,
+ high: quote.high,
+ low: quote.low,
+ close: quote.close,
+ volume: quote.volume,
+ change: quote.change,
+ changePercent: quote.changePercent,
+ timestamp: quote.timestamp,
+ bid: quote.bid,
+ bidQty: quote.bidQty,
+ ask: quote.ask,
+ askQty: quote.askQty,
+ };
+
+ this.emitTick(tick);
+ } catch (error) {
+ console.error(`[Zerodha] Failed to poll ${symbol}:`, error);
+ }
+
+ // Small delay between requests to avoid rate limiting
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+
+ console.log(`[Zerodha] ✓ Polling complete for ${this.pollingSymbols.size} symbols`);
+ }
+
+ /**
+ * Set up Tauri event listeners for WebSocket data
+ */
+ private async setupWebSocketEventListeners(): Promise<void> {
+ // Clean up any existing listeners
+ await this.cleanupWebSocketEventListeners();
+
+ // Listen for ticker (price) updates
+ const tickerUnlisten = await listen<{
+ provider: string;
+ symbol: string;
+ price: number;
+ bid?: number;
+ ask?: number;
+ bid_size?: number;
+ ask_size?: number;
+ volume?: number;
+ high?: number;
+ low?: number;
+ open?: number;
+ close?: number;
+ change?: number;
+ change_percent?: number;
+ timestamp: number;
+ }>('zerodha_ticker', (event) => {
+ this.handleTickerEvent(event.payload);
+ });
+ this.eventUnlisteners.push(tickerUnlisten);
+
+ // Listen for status updates
+ const statusUnlisten = await listen<{
+ provider: string;
+ status: string;
+ message?: string;
+ timestamp: number;
+ }>('zerodha_status', (event) => {
+ this.handleStatusEvent(event.payload);
+ });
+ this.eventUnlisteners.push(statusUnlisten);
+
+ // Listen for orderbook updates
+ const orderbookUnlisten = await listen<{
+ provider: string;
+ symbol: string;
+ bids: Array<{ price: number; quantity: number }>;
+ asks: Array<{ price: number; quantity: number }>;
+ timestamp: number;
+ }>('zerodha_orderbook', (event) => {
+ this.handleOrderBookEvent(event.payload);
+ });
+ this.eventUnlisteners.push(orderbookUnlisten);
+
+ console.log('[Zerodha] WebSocket event listeners set up');
+ }
+
+ /**
+ * Handle ticker event from Rust backend
+ */
+ private handleTickerEvent(data: {
+ symbol: string;
+ price: number;
+ bid?: number;
+ ask?: number;
+ bid_size?: number;
+ ask_size?: number;
+ volume?: number;
+ high?: number;
+ low?: number;
+ open?: number;
+ close?: number;
+ change?: number;
+ change_percent?: number;
+ timestamp: number;
+ }): void {
+ // Parse symbol: format is "EXCHANGE:SYMBOL"
+ const parts = data.symbol.split(':');
+ const exchange = (parts[0] || 'NSE') as StockExchange;
+ const symbol = parts[1] || data.symbol;
+
+ // Determine mode from available data
+ let mode: SubscriptionMode = 'ltp';
+ if (data.bid && data.ask) {
+ mode = 'full';
+ } else if (data.open || data.volume) {
+ mode = 'quote';
+ }
+
+ const tickData: TickData = {
+ symbol,
+ exchange,
+ lastPrice: data.price,
+ timestamp: data.timestamp,
+ mode,
+ bid: data.bid,
+ ask: data.ask,
+ bidQty: data.bid_size,
+ askQty: data.ask_size,
+ volume: data.volume,
+ high: data.high,
+ low: data.low,
+ open: data.open,
+ close: data.close,
+ change: data.change,
+ changePercent: data.change_percent,
+ };
+
+ this.emitTick(tickData);
+
+ // Also send to paper trading engine for order fills
+ this.processPaperTradingTick(data.symbol, data.price);
+ }
+
+ /**
+ * Process tick for paper trading (auto-fill orders, update positions)
+ */
+ private async processPaperTradingTick(symbol: string, price: number): Promise<void> {
+ try {
+ await invoke('process_tick_for_paper_trading', { symbol, price });
+ } catch (error) {
+ // Silently ignore - paper trading may not be active
+ }
+ }
+
+ /**
+ * Handle status event from Rust backend
+ */
+ private handleStatusEvent(data: {
+ status: string;
+ message?: string;
+ timestamp: number;
+ }): void {
+ console.log(`[Zerodha] WebSocket status: ${data.status}`, data.message || '');
+
+ if (data.status === 'error' || data.status === 'disconnected') {
+ this.wsConnected = false;
+ } else if (data.status === 'connected') {
+ this.wsConnected = true;
+ }
+ }
+
+ /**
+ * Handle orderbook event from Rust backend
+ */
+ private handleOrderBookEvent(data: {
+ symbol: string;
+ bids: Array<{ price: number; quantity: number }>;
+ asks: Array<{ price: number; quantity: number }>;
+ timestamp: number;
+ }): void {
+ // Parse symbol: format is "EXCHANGE:SYMBOL"
+ const parts = data.symbol.split(':');
+ const exchange = (parts[0] || 'NSE') as StockExchange;
+ const symbol = parts[1] || data.symbol;
+
+ // Emit orderbook update
+ const tickData: TickData = {
+ symbol,
+ exchange,
+ lastPrice: data.bids[0]?.price || 0,
+ timestamp: data.timestamp,
+ mode: 'full',
+ depth: {
+ bids: data.bids.map((b) => ({
+ price: b.price,
+ quantity: b.quantity,
+ orders: 1,
+ })),
+ asks: data.asks.map((a) => ({
+ price: a.price,
+ quantity: a.quantity,
+ orders: 1,
+ })),
+ },
+ };
+
+ this.emitTick(tickData);
+ }
+
+ /**
+ * Clean up WebSocket event listeners
+ */
+ private async cleanupWebSocketEventListeners(): Promise<void> {
+ for (const unlisten of this.eventUnlisteners) {
+ unlisten();
+ }
+ this.eventUnlisteners = [];
+ }
+
+ /**
+ * Disconnect from WebSocket
+ */
+ async disconnectWebSocket(): Promise<void> {
+ // Stop REST API polling
+ this.stopQuotePolling();
+ this.pollingSymbols.clear();
+
+ this.wsConnected = false;
+ console.log('[Zerodha] REST API polling stopped');
+ }
+
+ protected async subscribeInternal(
+ symbol: string,
+ exchange: StockExchange,
+ mode: SubscriptionMode
+ ): Promise<void> {
+ try {
+ const key = `${exchange}:${symbol}`;
+ this.pollingSymbols.set(key, { symbol, exchange });
+
+ console.log(`Zerodha: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);
+
+ // Trigger immediate poll for this symbol
+ this.pollQuotesSequentially();
+ } catch (error) {
+ console.error('Failed to subscribe:', error);
+ throw error;
+ }
+ }
+
+ protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {
+ const key = `${exchange}:${symbol}`;
+ this.pollingSymbols.delete(key);
+
+ console.log(`Zerodha: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);
+ }
+
+ /**
+ * Check if WebSocket is connected
+ */
+ async isWebSocketConnected(): Promise<boolean> {
+ try {
+ return await invoke<boolean>('zerodha_ws_is_connected');
+ } catch {
+ return false;
+ }
+ }
+
+ /**
+ * Handle incoming tick from WebSocket (legacy method for compatibility)
+ */
+ handleTick(tick: Record<string, unknown>): void {
+ const instrumentToken = Number(tick.instrument_token);
+ const symbolInfo = this.tokenSymbolMap.get(instrumentToken);
+
+ if (!symbolInfo) {
+ console.warn(`[Zerodha] Unknown instrument token: ${instrumentToken}`);
+ return;
+ }
+
+ // Determine mode from tick data
+ let mode: SubscriptionMode = 'ltp';
+ if (tick.depth) {
+ mode = 'full';
+ } else if (tick.ohlc || tick.volume) {
+ mode = 'quote';
+ }
+
+ const tickData = fromZerodhaTick(tick, symbolInfo, mode);
+ this.emitTick(tickData);
+ }
+
+ // ============================================================================
+ // Symbol Search & Instruments
+ // ============================================================================
+
+ async searchSymbols(query: string, exchange?: StockExchange): Promise<Instrument[]> {
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: Array<Record<string, unknown>>;
+ error?: string;
+ }>('zerodha_search_symbols', {
+ query,
+ exchange: exchange || null,
+ });
+
+ if (!response.success || !response.data) {
+ console.warn('[Zerodha] Symbol search failed:', response.error);
+ return [];
+ }
+
+ return response.data.map(item => ({
+ symbol: String(item.symbol || ''),
+ exchange: String(item.exchange || 'NSE') as StockExchange,
+ name: String(item.name || item.symbol || ''),
+ token: String(item.token || item.instrument_token || '0'),
+ lotSize: Number(item.lot_size || 1),
+ tickSize: Number(item.tick_size || 0.05),
+ instrumentType: String(item.instrument_type || 'EQ') as InstrumentType,
+ currency: 'INR' as const,
+ expiry: item.expiry ? String(item.expiry) : undefined,
+ strike: item.strike ? Number(item.strike) : undefined,
+ }));
+ } catch (error) {
+ console.error('[Zerodha] searchSymbols error:', error);
+ return [];
+ }
+ }
+
+ async getInstrument(symbol: string, exchange: StockExchange): Promise<Instrument | null> {
+ try {
+ const response = await invoke<{
+ success: boolean;
+ data?: Record<string, unknown>;
+ error?: string;
+ }>('zerodha_get_instrument', {
+ symbol,
+ exchange,
+ });
+
+ if (!response.success || !response.data) {
+ console.warn('[Zerodha] Instrument lookup failed:', response.error);
+ // Fallback to basic instrument
+ return {
+ symbol,
+ exchange,
+ name: symbol,
+ token: '0',
+ lotSize: 1,
+ tickSize: 0.05,
+ instrumentType: 'EQ' as any,
+ currency: 'INR',
+ };
+ }
+
+ const data = response.data;
+ return {
+ symbol: String(data.symbol || symbol),
+ exchange: String(data.exchange || exchange) as StockExchange,
+ name: String(data.name || symbol),
+ token: String(data.token || data.instrument_token || '0'),
+ lotSize: Number(data.lot_size || 1),
+ tickSize: Number(data.tick_size || 0.05),
+ instrumentType: String(data.instrument_type || 'EQ') as InstrumentType,
+ currency: 'INR' as const,
+ expiry: data.expiry ? String(data.expiry) : undefined,
+ strike: data.strike ? Number(data.strike) : undefined,
+ };
+ } catch (error) {
+ console.error('[Zerodha] getInstrument error:', error);
+ // Return fallback
+ return {
+ symbol,
+ exchange,
+ name: symbol,
+ token: '0',
+ lotSize: 1,
+ tickSize: 0.05,
+ instrumentType: 'EQ' as any,
+ currency: 'INR',
+ };
+ }
+ }
+
+ // ============================================================================
+ // Master Contract
+ // ============================================================================
+
+ async downloadMasterContract(): Promise<void> {
+ await invoke('zerodha_download_master_contract', {
+ apiKey: this.apiKey,
+ accessToken: this.accessToken,
+ });
+ }
+}
+
+// Export singleton instance
+export const zerodhaAdapter = new ZerodhaAdapter();
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/constants.ts b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/constants.ts
new file mode 100644
index 000000000..0312e6322
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/constants.ts
@@ -0,0 +1,190 @@
+/**
+ * Zerodha Constants
+ *
+ * API endpoints, mappings, and configuration for Zerodha Kite Connect
+ */
+
+import type { StockBrokerMetadata } from '../../types';
+
+// ============================================================================
+// API CONFIGURATION
+// ============================================================================
+
+export const ZERODHA_API_BASE_URL = 'https://api.kite.trade';
+export const ZERODHA_LOGIN_URL = 'https://kite.zerodha.com/connect/login';
+export const ZERODHA_API_VERSION = '3';
+
+export const ZERODHA_ENDPOINTS = {
+ // Auth
+ SESSION_TOKEN: '/session/token',
+ USER_PROFILE: '/user/profile',
+
+ // Orders
+ ORDERS: '/orders',
+ TRADES: '/trades',
+
+ // Portfolio
+ POSITIONS: '/portfolio/positions',
+ HOLDINGS: '/portfolio/holdings',
+
+ // Account
+ MARGINS: '/user/margins',
+
+ // Market Data
+ QUOTE: '/quote',
+ HISTORICAL: '/instruments/historical',
+ INSTRUMENTS: '/instruments',
+
+ // GTT
+ GTT: '/gtt/triggers',
+
+ // Margins
+ MARGIN_ORDERS: '/margins/orders',
+ MARGIN_BASKET: '/margins/basket',
+} as const;
+
+// ============================================================================
+// EXCHANGE MAPPINGS
+// ============================================================================
+
+export const ZERODHA_EXCHANGE_MAP: Record<string, string> = {
+ NSE: 'NSE',
+ BSE: 'BSE',
+ NFO: 'NFO',
+ BFO: 'BFO',
+ CDS: 'CDS',
+ BCD: 'BCD',
+ MCX: 'MCX',
+ NSE_INDEX: 'NSE',
+ BSE_INDEX: 'BSE',
+};
+
+// ============================================================================
+// PRODUCT TYPE MAPPINGS
+// ============================================================================
+
+export const ZERODHA_PRODUCT_MAP: Record<string, string> = {
+ CASH: 'CNC',
+ INTRADAY: 'MIS',
+ MARGIN: 'NRML',
+ COVER: 'CO',
+ BRACKET: 'BO',
+};
+
+export const ZERODHA_PRODUCT_REVERSE_MAP: Record<string, string> = {
+ CNC: 'CASH',
+ MIS: 'INTRADAY',
+ NRML: 'MARGIN',
+ CO: 'COVER',
+ BO: 'BRACKET',
+};
+
+// ============================================================================
+// ORDER TYPE MAPPINGS
+// ============================================================================
+
+export const ZERODHA_ORDER_TYPE_MAP: Record<string, string> = {
+ MARKET: 'MARKET',
+ LIMIT: 'LIMIT',
+ STOP: 'SL',
+ STOP_LIMIT: 'SL-M',
+};
+
+export const ZERODHA_ORDER_TYPE_REVERSE_MAP: Record<string, string> = {
+ MARKET: 'MARKET',
+ LIMIT: 'LIMIT',
+ SL: 'STOP',
+ 'SL-M': 'STOP_LIMIT',
+};
+
+// ============================================================================
+// ORDER STATUS MAPPINGS
+// ============================================================================
+
+export const ZERODHA_STATUS_MAP: Record<string, string> = {
+ PENDING: 'PENDING',
+ OPEN: 'OPEN',
+ COMPLETE: 'FILLED',
+ CANCELLED: 'CANCELLED',
+ REJECTED: 'REJECTED',
+ MODIFIED: 'OPEN',
+ 'TRIGGER PENDING': 'TRIGGER_PENDING',
+ 'AMO SUBMITTED': 'PENDING',
+ 'PUT ORDER REQ RECEIVED': 'PENDING',
+ 'VALIDATION PENDING': 'PENDING',
+};
+
+// ============================================================================
+// VALIDITY MAPPINGS
+// ============================================================================
+
+export const ZERODHA_VALIDITY_MAP: Record<string, string> = {
+ DAY: 'DAY',
+ IOC: 'IOC',
+ GTC: 'GTC',
+ GTD: 'GTD',
+};
+
+// ============================================================================
+// BROKER METADATA
+// ============================================================================
+
+export const ZERODHA_METADATA: StockBrokerMetadata = {
+ id: 'zerodha',
+ name: 'zerodha',
+ displayName: 'Zerodha (Kite)',
+ logo: '/brokers/zerodha.png',
+ website: 'https://zerodha.com',
+
+ region: 'india',
+ country: 'IN',
+ currency: 'INR',
+ exchanges: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'],
+ marketHours: {
+ open: '09:15',
+ close: '15:30',
+ timezone: 'Asia/Kolkata',
+ preMarketOpen: '09:00',
+ preMarketClose: '09:08',
+ },
+
+ features: {
+ webSocket: true,
+ amo: true,
+ gtt: true,
+ bracketOrder: true,
+ coverOrder: true,
+ marginCalculator: true,
+ optionsChain: true,
+ paperTrading: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true,
+ stopLimitOrders: true,
+ trailingStopOrders: false,
+ },
+
+ productTypes: ['CASH', 'INTRADAY', 'MARGIN'],
+
+ authType: 'oauth',
+
+ rateLimit: {
+ ordersPerSecond: 10,
+ quotesPerSecond: 5,
+ },
+
+ fees: {
+ equity: { brokerage: 0, stt: 0.001 },
+ intraday: { brokerage: 0.0003 },
+ fno: { brokerage: 20 },
+ },
+
+ defaultSymbols: [
+ 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',
+ 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',
+ 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',
+ ],
+};
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/index.ts b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/index.ts
new file mode 100644
index 000000000..028e5682f
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/index.ts
@@ -0,0 +1,7 @@
+/**
+ * Zerodha Broker Module
+ */
+
+export { ZerodhaAdapter, zerodhaAdapter } from './ZerodhaAdapter';
+export { ZERODHA_METADATA, ZERODHA_EXCHANGE_MAP } from './constants';
+export * from './mapper';
diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/mapper.ts b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/mapper.ts
new file mode 100644
index 000000000..28fd04d96
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/mapper.ts
@@ -0,0 +1,453 @@
+/**
+ * Zerodha Data Mappers
+ *
+ * Transform between Zerodha API format and standard stock broker format
+ */
+
+import type {
+ Order,
+ Trade,
+ Position,
+ Holding,
+ Funds,
+ Quote,
+ OHLCV,
+ MarketDepth,
+ DepthLevel,
+ OrderParams,
+ ModifyOrderParams,
+ TimeFrame,
+ OrderStatus,
+ OrderSide,
+ OrderType,
+ ProductType,
+ StockExchange,
+ TickData,
+ SubscriptionMode,
+} from '../../types';
+
+import {
+ ZERODHA_EXCHANGE_MAP,
+ ZERODHA_PRODUCT_MAP,
+ ZERODHA_PRODUCT_REVERSE_MAP,
+ ZERODHA_ORDER_TYPE_MAP,
+ ZERODHA_ORDER_TYPE_REVERSE_MAP,
+ ZERODHA_STATUS_MAP,
+ ZERODHA_VALIDITY_MAP,
+} from './constants';
+
+// ============================================================================
+// ORDER MAPPERS
+// ============================================================================
+
+/**
+ * Convert standard order params to Zerodha format
+ */
+export function toZerodhaOrderParams(params: OrderParams): Record<string, unknown> {
+ return {
+ tradingsymbol: params.symbol,
+ exchange: ZERODHA_EXCHANGE_MAP[params.exchange] || params.exchange,
+ transaction_type: params.side,
+ quantity: params.quantity,
+ order_type: ZERODHA_ORDER_TYPE_MAP[params.orderType] || params.orderType,
+ product: ZERODHA_PRODUCT_MAP[params.productType] || params.productType,
+ price: params.price || 0,
+ trigger_price: params.triggerPrice || 0,
+ validity: ZERODHA_VALIDITY_MAP[params.validity || 'DAY'] || 'DAY',
+ disclosed_quantity: params.disclosedQuantity || 0,
+ tag: params.tag || '',
+ };
+}
+
+/**
+ * Convert modify order params to Zerodha format
+ */
+export function toZerodhaModifyParams(params: ModifyOrderParams): Record<string, unknown> {
+ const zerodhaParams: Record<string, unknown> = {};
+
+ if (params.quantity !== undefined) {
+ zerodhaParams.quantity = params.quantity;
+ }
+ if (params.price !== undefined) {
+ zerodhaParams.price = params.price;
+ }
+ if (params.triggerPrice !== undefined) {
+ zerodhaParams.trigger_price = params.triggerPrice;
+ }
+ if (params.orderType !== undefined) {
+ zerodhaParams.order_type = ZERODHA_ORDER_TYPE_MAP[params.orderType] || params.orderType;
+ }
+ if (params.validity !== undefined) {
+ zerodhaParams.validity = ZERODHA_VALIDITY_MAP[params.validity] || params.validity;
+ }
+
+ return zerodhaParams;
+}
+
+/**
+ * Convert Zerodha order to standard format
+ */
+export function fromZerodhaOrder(order: Record<string, unknown>): Order {
+ const status = String(order.status || 'PENDING').toUpperCase();
+
+ return {
+ orderId: String(order.order_id || ''),
+ symbol: String(order.tradingsymbol || ''),
+ exchange: String(order.exchange || 'NSE') as StockExchange,
+ side: String(order.transaction_type || 'BUY').toUpperCase() as OrderSide,
+ quantity: Number(order.quantity || 0),
+ filledQuantity: Number(order.filled_quantity || 0),
+ pendingQuantity: Number(order.pending_quantity || 0),
+ price: Number(order.price || 0),
+ averagePrice: Number(order.average_price || 0),
+ triggerPrice: order.trigger_price ? Number(order.trigger_price) : undefined,
+ orderType: (ZERODHA_ORDER_TYPE_REVERSE_MAP[String(order.order_type)] || 'LIMIT') as OrderType,
+ productType: (ZERODHA_PRODUCT_REVERSE_MAP[String(order.product)] || 'CASH') as ProductType,
+ validity: String(order.validity || 'DAY') as 'DAY' | 'IOC' | 'GTC' | 'GTD',
+ status: (ZERODHA_STATUS_MAP[status] || 'PENDING') as OrderStatus,
+ statusMessage: order.status_message ? String(order.status_message) : undefined,
+ placedAt: new Date(order.order_timestamp as string || Date.now()),
+ updatedAt: order.exchange_update_timestamp
+ ? new Date(order.exchange_update_timestamp as string)
+ : undefined,
+ exchangeOrderId: order.exchange_order_id ? String(order.exchange_order_id) : undefined,
+ tag: order.tag ? String(order.tag) : undefined,
+ };
+}
+
+// ============================================================================
+// TRADE MAPPERS
+// ============================================================================
+
+/**
+ * Convert Zerodha trade to standard format
+ */
+export function fromZerodhaTrade(trade: Record<string, unknown>): Trade {
+ return {
+ tradeId: String(trade.trade_id || ''),
+ orderId: String(trade.order_id || ''),
+ symbol: String(trade.tradingsymbol || ''),
+ exchange: String(trade.exchange || 'NSE') as StockExchange,
+ side: String(trade.transaction_type || 'BUY').toUpperCase() as OrderSide,
+ quantity: Number(trade.quantity || 0),
+ price: Number(trade.average_price || trade.price || 0),
+ productType: (ZERODHA_PRODUCT_REVERSE_MAP[String(trade.product)] || 'CASH') as ProductType,
+ tradedAt: new Date(trade.fill_timestamp as string || trade.order_timestamp as string || Date.now()),
+ exchangeTradeId: trade.exchange_trade_id ? String(trade.exchange_trade_id) : undefined,
+ };
+}
+
+// ============================================================================
+// POSITION MAPPERS
+// ============================================================================
+
+/**
+ * Convert Zerodha position to standard format
+ */
+export function fromZerodhaPosition(position: Record<string, unknown>): Position {
+ const buyQty = Number(position.buy_quantity || 0);
+ const sellQty = Number(position.sell_quantity || 0);
+ const buyValue = Number(position.buy_value || 0);
+ const sellValue = Number(position.sell_value || 0);
+ const netQty = Number(position.quantity || 0);
+ const lastPrice = Number(position.last_price || 0);
+ const avgPrice = Number(position.average_price || 0);
+
+ // Calculate P&L
+ const pnl = Number(position.pnl || position.unrealised || 0);
+ const pnlPercent = avgPrice > 0 ? ((lastPrice - avgPrice) / avgPrice) * 100 : 0;
+ const dayPnl = Number(position.day_m2m || position.m2m || 0);
+
+ return {
+ symbol: String(position.tradingsymbol || ''),
+ exchange: String(position.exchange || 'NSE') as StockExchange,
+ productType: (ZERODHA_PRODUCT_REVERSE_MAP[String(position.product)] || 'INTRADAY') as ProductType,
+ quantity: netQty,
+ buyQuantity: buyQty,
+ sellQuantity: sellQty,
+ buyValue,
+ sellValue,
+ averagePrice: avgPrice,
+ lastPrice,
+ pnl,
+ pnlPercent,
+ dayPnl,
+ overnight: Boolean(position.overnight_quantity),
+ };
+}
+
+// ============================================================================
+// HOLDING MAPPERS
+// ============================================================================
+
+/**
+ * Convert Zerodha holding to standard format
+ */
+export function fromZerodhaHolding(holding: Record<string, unknown>): Holding {
+ const quantity = Number(holding.quantity || 0);
+ const avgPrice = Number(holding.average_price || 0);
+ const lastPrice = Number(holding.last_price || 0);
+ const investedValue = quantity * avgPrice;
+ const currentValue = quantity * lastPrice;
+ const pnl = currentValue - investedValue;
+ const pnlPercent = investedValue > 0 ? (pnl / investedValue) * 100 : 0;
+
+ return {
+ symbol: String(holding.tradingsymbol || ''),
+ exchange: String(holding.exchange || 'NSE') as StockExchange,
+ quantity,
+ averagePrice: avgPrice,
+ lastPrice,
+ investedValue,
+ currentValue,
+ pnl,
+ pnlPercent,
+ isin: holding.isin ? String(holding.isin) : undefined,
+ pledgedQuantity: holding.pledged_quantity ? Number(holding.pledged_quantity) : undefined,
+ collateralQuantity: holding.collateral_quantity ? Number(holding.collateral_quantity) : undefined,
+ t1Quantity: holding.t1_quantity ? Number(holding.t1_quantity) : undefined,
+ };
+}
+
+// ============================================================================
+// FUNDS MAPPERS
+// ============================================================================
+
+/**
+ * Convert Zerodha margins to standard funds format
+ */
+export function fromZerodhaFunds(funds: Record<string, unknown>): Funds {
+ // Handle both combined and segment-wise data
+ const equity = (funds.equity as Record<string, unknown>) || {};
+ const commodity = (funds.commodity as Record<string, unknown>) || {};
+
+ const equityAvailableObj = (equity.available as Record<string, unknown>) || {};
+ const commodityAvailableObj = (commodity.available as Record<string, unknown>) || {};
+ const equityUtilisedObj = (equity.utilised as Record<string, unknown>) || {};
+ const commodityUtilisedObj = (commodity.utilised as Record<string, unknown>) || {};
+
+ const equityAvailable = Number(equityAvailableObj.cash || equity.net || 0);
+ const commodityAvailable = Number(commodityAvailableObj.cash || commodity.net || 0);
+
+ const equityUsed = Number(equityUtilisedObj.debits || 0);
+ const commodityUsed = Number(commodityUtilisedObj.debits || 0);
+
+ return {
+ availableCash: equityAvailable + commodityAvailable,
+ usedMargin: equityUsed + commodityUsed,
+ availableMargin: equityAvailable + commodityAvailable,
+ totalBalance: equityAvailable + commodityAvailable + equityUsed + commodityUsed,
+ currency: 'INR',
+ equityAvailable,
+ commodityAvailable,
+ collateral: Number(equityAvailableObj.collateral || 0) + Number(commodityAvailableObj.collateral || 0),
+ unrealizedPnl: Number(equityUtilisedObj.m2m_unrealised || 0) + Number(commodityUtilisedObj.m2m_unrealised || 0),
+ realizedPnl: Number(equityUtilisedObj.m2m_realised || 0) + Number(commodityUtilisedObj.m2m_realised || 0),
+ };
+}
+
+// ============================================================================
+// QUOTE MAPPERS
+// ============================================================================
+
+/**
+ * Convert Zerodha quote to standard format
+ */
+export function fromZerodhaQuote(quote: Record<string, unknown>, symbol: string, exchange: StockExchange): Quote {
+ const ohlc = (quote.ohlc as Record<string, number>) || {};
+ const depth = quote.depth as Record<string, unknown[]> | undefined;
+
+ let bid = 0, bidQty = 0, ask = 0, askQty = 0;
+
+ if (depth) {
+ const buyDepth = depth.buy as Record<string, number>[] || [];
+ const sellDepth = depth.sell as Record<string, number>[] || [];
+
+ if (buyDepth.length > 0) {
+ bid = Number(buyDepth[0].price || 0);
+ bidQty = Number(buyDepth[0].quantity || 0);
+ }
+ if (sellDepth.length > 0) {
+ ask = Number(sellDepth[0].price || 0);
+ askQty = Number(sellDepth[0].quantity || 0);
+ }
+ }
+
+ const lastPrice = Number(quote.last_price || 0);
+ const previousClose = Number(ohlc.close || quote.close || 0);
+ const change = lastPrice - previousClose;
+ const changePercent = previousClose > 0 ? (change / previousClose) * 100 : 0;
+
+ return {
+ symbol,
+ exchange,
+ lastPrice,
+ open: Number(ohlc.open || quote.open || 0),
+ high: Number(ohlc.high || quote.high || 0),
+ low: Number(ohlc.low || quote.low || 0),
+ close: Number(ohlc.close || quote.close || 0),
+ previousClose,
+ change,
+ changePercent,
+ volume: Number(quote.volume || quote.volume_traded || 0),
+ value: quote.traded_value ? Number(quote.traded_value) : undefined,
+ averagePrice: quote.average_price ? Number(quote.average_price) : undefined,
+ bid,
+ bidQty,
+ ask,
+ askQty,
+ timestamp: Number(quote.timestamp || Date.now()),
+ openInterest: quote.oi ? Number(quote.oi) : undefined,
+ oiChange: quote.oi_day_change ? Number(quote.oi_day_change) : undefined,
+ upperCircuit: quote.upper_circuit_limit ? Number(quote.upper_circuit_limit) : undefined,
+ lowerCircuit: quote.lower_circuit_limit ? Number(quote.lower_circuit_limit) : undefined,
+ };
+}
+
+// ============================================================================
+// OHLCV MAPPERS
+// ============================================================================
+
+/**
+ * Convert Zerodha OHLCV candle to standard format
+ */
+export function fromZerodhaOHLCV(candle: unknown[]): OHLCV {
+ return {
+ timestamp: new Date(candle[0] as string).getTime(),
+ open: Number(candle[1] || 0),
+ high: Number(candle[2] || 0),
+ low: Number(candle[3] || 0),
+ close: Number(candle[4] || 0),
+ volume: Number(candle[5] || 0),
+ };
+}
+
+/**
+ * Convert timeframe to Zerodha interval
+ */
+export function toZerodhaInterval(timeframe: TimeFrame): string {
+ const intervalMap: Record<TimeFrame, string> = {
+ '1m': 'minute',
+ '3m': '3minute',
+ '5m': '5minute',
+ '10m': '10minute',
+ '15m': '15minute',
+ '30m': '30minute',
+ '1h': '60minute',
+ '2h': '2hour',
+ '4h': '4hour',
+ '1d': 'day',
+ '1w': 'week',
+ '1M': 'month',
+ };
+ return intervalMap[timeframe] || 'day';
+}
+
+// ============================================================================
+// DEPTH MAPPERS
+// ============================================================================
+
+/**
+ * Convert Zerodha depth to standard format
+ */
+export function fromZerodhaDepth(depth: Record<string, unknown>): MarketDepth {
+ const buyLevels = (depth.buy as Record<string, unknown>[]) || [];
+ const sellLevels = (depth.sell as Record<string, unknown>[]) || [];
+
+ const bids: DepthLevel[] = buyLevels.map(level => ({
+ price: Number(level.price || 0),
+ quantity: Number(level.quantity || 0),
+ orders: level.orders ? Number(level.orders) : undefined,
+ }));
+
+ const asks: DepthLevel[] = sellLevels.map(level => ({
+ price: Number(level.price || 0),
+ quantity: Number(level.quantity || 0),
+ orders: level.orders ? Number(level.orders) : undefined,
+ }));
+
+ return { bids, asks };
+}
+
+// ============================================================================
+// WEBSOCKET MAPPERS
+// ============================================================================
+
+/**
+ * Convert Zerodha tick to standard format
+ */
+export function fromZerodhaTick(
+ tick: Record<string, unknown>,
+ symbolInfo: { symbol: string; exchange: StockExchange },
+ mode: SubscriptionMode
+): TickData {
+ const baseTick: TickData = {
+ symbol: symbolInfo.symbol,
+ exchange: symbolInfo.exchange,
+ token: String(tick.instrument_token || ''),
+ mode,
+ lastPrice: Number(tick.last_traded_price || tick.last_price || 0),
+ timestamp: Number(tick.timestamp || Date.now()),
+ };
+
+ if (mode === 'quote' || mode === 'full') {
+ const ohlc = tick.ohlc as Record<string, number> | undefined;
+ baseTick.open = Number(ohlc?.open || tick.open_price || 0);
+ baseTick.high = Number(ohlc?.high || tick.high_price || 0);
+ baseTick.low = Number(ohlc?.low || tick.low_price || 0);
+ baseTick.close = Number(ohlc?.close || tick.close_price || 0);
+ baseTick.volume = Number(tick.volume_traded || tick.volume || 0);
+
+ const lastPrice = baseTick.lastPrice;
+ const close = baseTick.close || 0;
+ baseTick.change = lastPrice - close;
+ baseTick.changePercent = close > 0 ? ((lastPrice - close) / close) * 100 : 0;
+ }
+
+ if (mode === 'full') {
+ baseTick.bid = Number(tick.best_bid_price || 0);
+ baseTick.bidQty = Number(tick.best_bid_quantity || 0);
+ baseTick.ask = Number(tick.best_ask_price || 0);
+ baseTick.askQty = Number(tick.best_ask_quantity || 0);
+ baseTick.openInterest = tick.oi ? Number(tick.oi) : undefined;
+
+ if (tick.depth) {
+ baseTick.depth = fromZerodhaDepth(tick.depth as Record<string, unknown>);
+ }
+ }
+
+ return baseTick;
+}
+
+/**
+ * Convert subscription mode to Zerodha WS mode
+ */
+export function toZerodhaWSMode(mode: SubscriptionMode): string {
+ const modeMap: Record<SubscriptionMode, string> = {
+ ltp: 'ltp',
+ quote: 'quote',
+ full: 'full',
+ };
+ return modeMap[mode] || 'quote';
+}
+
+// ============================================================================
+// MARGIN MAPPERS
+// ============================================================================
+
+/**
+ * Convert order params to Zerodha margin request format
+ */
+export function toZerodhaMarginParams(params: OrderParams): Record<string, unknown> {
+ return {
+ exchange: ZERODHA_EXCHANGE_MAP[params.exchange] || params.exchange,
+ tradingsymbol: params.symbol,
+ transaction_type: params.side,
+ variety: 'regular',
+ product: ZERODHA_PRODUCT_MAP[params.productType] || params.productType,
+ order_type: ZERODHA_ORDER_TYPE_MAP[params.orderType] || params.orderType,
+ quantity: params.quantity,
+ price: params.price || 0,
+ trigger_price: params.triggerPrice || 0,
+ };
+}
diff --git a/fincept-terminal-desktop/src/brokers/stocks/init.ts b/fincept-terminal-desktop/src/brokers/stocks/init.ts
new file mode 100644
index 000000000..590529d23
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/init.ts
@@ -0,0 +1,26 @@
+/**
+ * Stock Broker Initialization
+ *
+ * Registers all broker adapters at application startup
+ */
+
+import { registerBrokerAdapter } from './registry';
+import { ZerodhaAdapter } from './india/zerodha/ZerodhaAdapter';
+import { FyersAdapter } from './india/fyers/FyersAdapter';
+import { AngelOneAdapter } from './india/angelone/AngelOneAdapter';
+
+/**
+ * Initialize all stock broker adapters
+ * Must be called during application startup
+ */
+export function initializeStockBrokers(): void {
+ // Register Indian brokers
+ registerBrokerAdapter('zerodha', ZerodhaAdapter);
+ registerBrokerAdapter('fyers', FyersAdapter);
+ registerBrokerAdapter('angelone', AngelOneAdapter);
+
+ // Future brokers
+ // registerBrokerAdapter('dhan', DhanAdapter);
+ // registerBrokerAdapter('upstox', UpstoxAdapter);
+ // registerBrokerAdapter('groww', GrowwAdapter);
+}
diff --git a/fincept-terminal-desktop/src/brokers/stocks/registry.ts b/fincept-terminal-desktop/src/brokers/stocks/registry.ts
new file mode 100644
index 000000000..69b93fc2f
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/registry.ts
@@ -0,0 +1,335 @@
+/**
+ * Stock Broker Registry
+ *
+ * Central registry for all stock brokers globally
+ * Enables broker discovery, switching, and capability detection
+ */
+
+import type { StockBrokerMetadata, Region, IStockBrokerAdapter } from './types';
+
+// ============================================================================
+// BROKER REGISTRY
+// ============================================================================
+
+export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {
+ // ============================================================================
+ // INDIAN BROKERS
+ // ============================================================================
+
+ zerodha: {
+ id: 'zerodha',
+ name: 'zerodha',
+ displayName: 'Zerodha (Kite)',
+ logo: '/brokers/zerodha.png',
+ website: 'https://zerodha.com',
+
+ region: 'india',
+ country: 'IN',
+ currency: 'INR',
+ exchanges: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'],
+ marketHours: {
+ open: '09:15',
+ close: '15:30',
+ timezone: 'Asia/Kolkata',
+ preMarketOpen: '09:00',
+ preMarketClose: '09:08',
+ },
+
+ features: {
+ webSocket: true,
+ amo: true,
+ gtt: true,
+ bracketOrder: true,
+ coverOrder: true,
+ marginCalculator: true,
+ optionsChain: true,
+ paperTrading: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true,
+ stopLimitOrders: true,
+ trailingStopOrders: false,
+ },
+
+ productTypes: ['CASH', 'INTRADAY', 'MARGIN'],
+
+ authType: 'oauth',
+
+ rateLimit: {
+ ordersPerSecond: 10,
+ quotesPerSecond: 5,
+ },
+
+ fees: {
+ equity: { brokerage: 0, stt: 0.001 },
+ intraday: { brokerage: 0.0003 },
+ fno: { brokerage: 20 },
+ },
+
+ defaultSymbols: [
+ 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',
+ 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',
+ 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',
+ ],
+ },
+
+ fyers: {
+ id: 'fyers',
+ name: 'fyers',
+ displayName: 'Fyers',
+ logo: '/brokers/fyers.png',
+ website: 'https://fyers.in',
+
+ region: 'india',
+ country: 'IN',
+ currency: 'INR',
+ exchanges: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'],
+ marketHours: {
+ open: '09:15',
+ close: '15:30',
+ timezone: 'Asia/Kolkata',
+ preMarketOpen: '09:00',
+ preMarketClose: '09:08',
+ },
+
+ features: {
+ webSocket: true,
+ amo: true,
+ gtt: false,
+ bracketOrder: true,
+ coverOrder: true,
+ marginCalculator: false,
+ optionsChain: true,
+ paperTrading: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true,
+ stopLimitOrders: true,
+ trailingStopOrders: false,
+ },
+
+ productTypes: ['CASH', 'INTRADAY', 'MARGIN'],
+
+ authType: 'oauth',
+
+ rateLimit: {
+ ordersPerSecond: 10,
+ quotesPerSecond: 5,
+ },
+
+ fees: {
+ equity: { brokerage: 0, stt: 0.001 },
+ intraday: { brokerage: 0.0003 },
+ fno: { brokerage: 20 },
+ },
+
+ defaultSymbols: [
+ 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',
+ 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',
+ 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',
+ ],
+ },
+
+ angelone: {
+ id: 'angelone',
+ name: 'angelone',
+ displayName: 'Angel One',
+ logo: '/brokers/angelone.png',
+ website: 'https://www.angelone.in',
+
+ region: 'india',
+ country: 'IN',
+ currency: 'INR',
+ exchanges: ['NSE', 'BSE', 'NFO', 'BFO', 'CDS', 'MCX'],
+ marketHours: {
+ open: '09:15',
+ close: '15:30',
+ timezone: 'Asia/Kolkata',
+ preMarketOpen: '09:00',
+ preMarketClose: '09:08',
+ },
+
+ features: {
+ webSocket: true,
+ amo: true,
+ gtt: true,
+ bracketOrder: true,
+ coverOrder: true,
+ marginCalculator: true,
+ optionsChain: true,
+ paperTrading: false,
+ },
+
+ tradingFeatures: {
+ marketOrders: true,
+ limitOrders: true,
+ stopOrders: true,
+ stopLimitOrders: true,
+ trailingStopOrders: false,
+ },
+
+ productTypes: ['CASH', 'INTRADAY', 'MARGIN'],
+
+ authType: 'totp',
+
+ rateLimit: {
+ ordersPerSecond: 10,
+ quotesPerSecond: 1, // Angel One has 1 request per second for quotes
+ },
+
+ fees: {
+ equity: { brokerage: 0, stt: 0.001 },
+ intraday: { brokerage: 20 },
+ fno: { brokerage: 20 },
+ },
+
+ defaultSymbols: [
+ 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',
+ 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',
+ 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',
+ ],
+ },
+
+ // Placeholder for future brokers
+ // dhan: { ... },
+ // upstox: { ... },
+ // groww: { ... },
+
+ // ============================================================================
+ // US BROKERS (Placeholder)
+ // ============================================================================
+
+ // alpaca: { ... },
+ // tradier: { ... },
+ // ibkr: { ... },
+
+ // ============================================================================
+ // EUROPE BROKERS (Placeholder)
+ // ============================================================================
+
+ // degiro: { ... },
+};
+
+// ============================================================================
+// ADAPTER REGISTRY (Runtime instances)
+// ============================================================================
+
+// Map of broker ID to adapter class constructor
+const adapterClasses: Record<string, new () => IStockBrokerAdapter> = {};
+
+/**
+ * Register a broker adapter class
+ */
+export function registerBrokerAdapter(
+ brokerId: string,
+ adapterClass: new () => IStockBrokerAdapter
+): void {
+ adapterClasses[brokerId] = adapterClass;
+}
+
+/**
+ * Create a broker adapter instance
+ */
+export function createStockBrokerAdapter(brokerId: string): IStockBrokerAdapter {
+ const AdapterClass = adapterClasses[brokerId];
+
+ if (!AdapterClass) {
+ throw new Error(`Broker adapter not registered: ${brokerId}`);
+ }
+
+ return new AdapterClass();
+}
+
+// ============================================================================
+// HELPER FUNCTIONS
+// ============================================================================
+
+/**
+ * Get all registered stock brokers
+ */
+export function getAllStockBrokers(): StockBrokerMetadata[] {
+ return Object.values(STOCK_BROKER_REGISTRY);
+}
+
+/**
+ * Get brokers by region
+ */
+export function getStockBrokersByRegion(region: Region): StockBrokerMetadata[] {
+ return getAllStockBrokers().filter(broker => broker.region === region);
+}
+
+/**
+ * Get broker metadata by ID
+ */
+export function getStockBrokerMetadata(brokerId: string): StockBrokerMetadata | undefined {
+ return STOCK_BROKER_REGISTRY[brokerId];
+}
+
+/**
+ * Check if broker is registered
+ */
+export function isStockBrokerRegistered(brokerId: string): boolean {
+ return brokerId in STOCK_BROKER_REGISTRY;
+}
+
+/**
+ * Get broker display name
+ */
+export function getStockBrokerDisplayName(brokerId: string): string {
+ return STOCK_BROKER_REGISTRY[brokerId]?.displayName || brokerId.toUpperCase();
+}
+
+/**
+ * Get default symbols for broker
+ */
+export function getStockBrokerDefaultSymbols(brokerId: string): string[] {
+ return STOCK_BROKER_REGISTRY[brokerId]?.defaultSymbols || [];
+}
+
+/**
+ * Check if broker supports feature
+ */
+export function stockBrokerSupportsFeature(
+ brokerId: string,
+ feature: keyof StockBrokerMetadata['features']
+): boolean {
+ const metadata = STOCK_BROKER_REGISTRY[brokerId];
+ return metadata?.features[feature] === true;
+}
+
+/**
+ * Check if broker supports trading feature
+ */
+export function stockBrokerSupportsTradingFeature(
+ brokerId: string,
+ feature: keyof StockBrokerMetadata['tradingFeatures']
+): boolean {
+ const metadata = STOCK_BROKER_REGISTRY[brokerId];
+ return metadata?.tradingFeatures[feature] === true;
+}
+
+/**
+ * Get available regions
+ */
+export function getAvailableRegions(): Region[] {
+ const regions = new Set<Region>();
+ for (const broker of getAllStockBrokers()) {
+ regions.add(broker.region);
+ }
+ return Array.from(regions);
+}
+
+/**
+ * Get brokers with specific feature
+ */
+export function getStockBrokersWithFeature(
+ feature: keyof StockBrokerMetadata['features']
+): StockBrokerMetadata[] {
+ return getAllStockBrokers().filter(broker => broker.features[feature] === true);
+}
diff --git a/fincept-terminal-desktop/src/brokers/stocks/types.ts b/fincept-terminal-desktop/src/brokers/stocks/types.ts
new file mode 100644
index 000000000..2ba739129
--- /dev/null
+++ b/fincept-terminal-desktop/src/brokers/stocks/types.ts
@@ -0,0 +1,555 @@
+/**
+ * Unified Stock Broker Types
+ *
+ * Base types for all stock brokers globally (India, US, Europe, Asia, etc.)
+ * Region-specific features handled via metadata and feature flags
+ */
+
+// ============================================================================
+// REGION & MARKET TYPES
+// ============================================================================
+
+export type Region = 'india' | 'us' | 'europe' | 'uk' | 'asia' | 'australia' | 'canada';
+
+export type Currency = 'INR' | 'USD' | 'EUR' | 'GBP' | 'JPY' | 'AUD' | 'CAD' | 'SGD' | 'HKD';
+
+export interface MarketHours {
+ open: string; // "09:15" (24hr format)
+ close: string; // "15:30"
+ timezone: string; // "Asia/Kolkata"
+ preMarketOpen?: string;
+ preMarketClose?: string;
+ postMarketOpen?: string;
+ postMarketClose?: string;
+}
+
+export type MarketStatus = 'PRE_OPEN' | 'OPEN' | 'CLOSED' | 'POST_MARKET' | 'HOLIDAY';
+
+// ============================================================================
+// EXCHANGE TYPES
+// ============================================================================
+
+export interface Exchange {
+ code: string; // "NSE", "NYSE", "LSE"
+ name: string; // "National Stock Exchange"
+ country: string; // "IN", "US", "GB"
+ currency: Currency;
+ marketHours: MarketHours;
+}
+
+// Common exchanges by region
+export type IndianExchange = 'NSE' | 'BSE' | 'NFO' | 'BFO' | 'CDS' | 'BCD' | 'MCX';
+export type USExchange = 'NYSE' | 'NASDAQ' | 'AMEX' | 'ARCA' | 'BATS';
+export type EuropeExchange = 'LSE' | 'XETRA' | 'EURONEXT' | 'SIX';
+
+// Union of all exchanges
+export type StockExchange = IndianExchange | USExchange | EuropeExchange | string;
+
+// ============================================================================
+// INSTRUMENT TYPES
+// ============================================================================
+
+export type InstrumentType =
+ | 'EQUITY' // Stocks
+ | 'ETF' // Exchange Traded Funds
+ | 'INDEX' // Index
+ | 'FUTURE' // Futures
+ | 'OPTION' // Options
+ | 'BOND' // Bonds
+ | 'MUTUAL_FUND'; // Mutual Funds
+
+export type OptionType = 'CE' | 'PE' | 'CALL' | 'PUT';
+
+export interface Instrument {
+ symbol: string; // "RELIANCE", "AAPL"
+ name: string; // "Reliance Industries Ltd"
+ exchange: StockExchange;
+ instrumentType: InstrumentType;
+ currency: Currency;
+ token?: string; // Broker-specific token
+ isin?: string; // International Securities ID
+ lotSize: number;
+ tickSize: number;
+ // Derivatives specific
+ expiry?: string; // "2024-01-25"
+ strike?: number;
+ optionType?: OptionType;
+ underlying?: string;
+}
+
+// ============================================================================
+// ORDER TYPES
+// ============================================================================
+
+export type OrderSide = 'BUY' | 'SELL';
+
+export type OrderType =
+ | 'MARKET'
+ | 'LIMIT'
+ | 'STOP' // Stop loss
+ | 'STOP_LIMIT' // Stop loss limit
+ | 'TRAILING_STOP';
+
+export type OrderValidity =
+ | 'DAY' // Valid for the day
+ | 'IOC' // Immediate or Cancel
+ | 'GTC' // Good Till Cancelled
+ | 'GTD'; // Good Till Date
+
+export type OrderStatus =
+ | 'PENDING'
+ | 'OPEN'
+ | 'PARTIALLY_FILLED'
+ | 'FILLED'
+ | 'CANCELLED'
+ | 'REJECTED'
+ | 'EXPIRED'
+ | 'TRIGGER_PENDING'; // For stop orders
+
+// Product types (vary by region but have common concepts)
+export type ProductType =
+ | 'CASH' // Delivery/Investment (CNC in India)
+ | 'INTRADAY' // Day trading (MIS in India)
+ | 'MARGIN' // Margin trading (NRML in India)
+ | 'COVER' // Cover order
+ | 'BRACKET'; // Bracket order
+
+// ============================================================================
+// ORDER PARAMS & RESPONSE
+// ============================================================================
+
+export interface OrderParams {
+ symbol: string;
+ exchange: StockExchange;
+ side: OrderSide;
+ quantity: number;
+ orderType: OrderType;
+ productType: ProductType;
+ price?: number; // For limit orders
+ triggerPrice?: number; // For stop orders
+ validity?: OrderValidity;
+ disclosedQuantity?: number; // Iceberg orders
+ tag?: string; // Order tag/reference
+ // Region-specific (optional)
+ amo?: boolean; // After Market Order (India)
+ squareOff?: number; // Bracket order target
+ stopLoss?: number; // Bracket order SL
+}
+
+export interface ModifyOrderParams {
+ orderId: string;
+ quantity?: number;
+ price?: number;
+ triggerPrice?: number;
+ orderType?: OrderType;
+ validity?: OrderValidity;
+}
+
+export interface OrderResponse {
+ success: boolean;
+ orderId?: string;
+ message?: string;
+ errorCode?: string;
+}
+
+export interface Order {
+ orderId: string;
+ symbol: string;
+ exchange: StockExchange;
+ side: OrderSide;
+ quantity: number;
+ filledQuantity: number;
+ pendingQuantity: number;
+ price: number;
+ averagePrice: number;
+ triggerPrice?: number;
+ orderType: OrderType;
+ productType: ProductType;
+ validity: OrderValidity;
+ status: OrderStatus;
+ statusMessage?: string;
+ placedAt: Date;
+ updatedAt?: Date;
+ exchangeOrderId?: string;
+ tag?: string;
+}
+
+// ============================================================================
+// TRADE TYPES
+// ============================================================================
+
+export interface Trade {
+ tradeId: string;
+ orderId: string;
+ symbol: string;
+ exchange: StockExchange;
+ side: OrderSide;
+ quantity: number;
+ price: number;
+ productType: ProductType;
+ tradedAt: Date;
+ exchangeTradeId?: string;
+}
+
+// ============================================================================
+// POSITION & HOLDINGS
+// ============================================================================
+
+export interface Position {
+ symbol: string;
+ exchange: StockExchange;
+ productType: ProductType;
+ quantity: number; // Net quantity (+ve long, -ve short)
+ buyQuantity: number;
+ sellQuantity: number;
+ buyValue: number;
+ sellValue: number;
+ averagePrice: number;
+ lastPrice: number;
+ pnl: number;
+ pnlPercent: number;
+ dayPnl: number;
+ overnight?: boolean; // Carried forward position
+}
+
+export interface Holding {
+ symbol: string;
+ exchange: StockExchange;
+ quantity: number;
+ averagePrice: number;
+ lastPrice: number;
+ investedValue: number;
+ currentValue: number;
+ pnl: number;
+ pnlPercent: number;
+ isin?: string;
+ // Pledged/collateral info
+ pledgedQuantity?: number;
+ collateralQuantity?: number;
+ t1Quantity?: number; // T+1 holdings (India specific)
+}
+
+// ============================================================================
+// FUNDS & MARGIN
+// ============================================================================
+
+export interface Funds {
+ availableCash: number;
+ usedMargin: number;
+ availableMargin: number;
+ totalBalance: number;
+ currency: Currency;
+ // Segment-wise (optional)
+ equityAvailable?: number;
+ commodityAvailable?: number;
+ // Collateral
+ collateral?: number;
+ // MTM
+ unrealizedPnl?: number;
+ realizedPnl?: number;
+}
+
+export interface MarginRequired {
+ totalMargin: number;
+ initialMargin: number;
+ exposureMargin?: number;
+ spanMargin?: number;
+ optionPremium?: number;
+ // Breakdown per order (for basket)
+ orders?: Array<{
+ symbol: string;
+ margin: number;
+ }>;
+}
+
+// ============================================================================
+// MARKET DATA
+// ============================================================================
+
+export interface Quote {
+ symbol: string;
+ exchange: StockExchange;
+ lastPrice: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ previousClose: number;
+ change: number;
+ changePercent: number;
+ volume: number;
+ value?: number; // Traded value
+ averagePrice?: number;
+ bid: number;
+ bidQty: number;
+ ask: number;
+ askQty: number;
+ timestamp: number;
+ // Derivatives specific
+ openInterest?: number;
+ oiChange?: number;
+ // Circuit limits (India specific)
+ upperCircuit?: number;
+ lowerCircuit?: number;
+}
+
+export interface OHLCV {
+ timestamp: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+}
+
+export type TimeFrame =
+ | '1m' | '3m' | '5m' | '10m' | '15m' | '30m'
+ | '1h' | '2h' | '4h'
+ | '1d' | '1w' | '1M';
+
+export interface DepthLevel {
+ price: number;
+ quantity: number;
+ orders?: number;
+}
+
+export interface MarketDepth {
+ bids: DepthLevel[];
+ asks: DepthLevel[];
+ timestamp?: number;
+}
+
+// ============================================================================
+// WEBSOCKET TYPES
+// ============================================================================
+
+export type SubscriptionMode = 'ltp' | 'quote' | 'full';
+
+export interface TickData {
+ symbol: string;
+ exchange: StockExchange;
+ token?: string;
+ mode: SubscriptionMode;
+ lastPrice: number;
+ timestamp: number;
+ // Quote mode
+ open?: number;
+ high?: number;
+ low?: number;
+ close?: number;
+ change?: number;
+ changePercent?: number;
+ volume?: number;
+ // Full mode
+ bid?: number;
+ bidQty?: number;
+ ask?: number;
+ askQty?: number;
+ depth?: MarketDepth;
+ openInterest?: number;
+}
+
+export interface WebSocketConfig {
+ autoReconnect?: boolean;
+ reconnectInterval?: number;
+ maxReconnectAttempts?: number;
+ heartbeatInterval?: number;
+}
+
+// ============================================================================
+// AUTHENTICATION
+// ============================================================================
+
+export interface BrokerCredentials {
+ apiKey: string;
+ apiSecret?: string;
+ accessToken?: string;
+ refreshToken?: string;
+ userId?: string;
+ // Region specific
+ totpSecret?: string; // For TOTP-based auth
+ password?: string; // For password-based auth
+ pin?: string; // Trading PIN
+}
+
+export interface AuthResponse {
+ success: boolean;
+ accessToken?: string;
+ refreshToken?: string;
+ userId?: string;
+ expiresAt?: Date;
+ message?: string;
+ errorCode?: string;
+}
+
+export interface AuthCallbackParams {
+ requestToken?: string;
+ authCode?: string;
+ state?: string;
+}
+
+// ============================================================================
+// BULK OPERATIONS
+// ============================================================================
+
+export interface BulkOperationResult {
+ success: boolean;
+ totalCount: number;
+ successCount: number;
+ failedCount: number;
+ results: Array<{
+ success: boolean;
+ orderId?: string;
+ symbol?: string;
+ error?: string;
+ }>;
+}
+
+// ============================================================================
+// SMART ORDER
+// ============================================================================
+
+export interface SmartOrderParams extends OrderParams {
+ positionSize?: number; // Current position to adjust order logic
+}
+
+// ============================================================================
+// BROKER ADAPTER INTERFACE
+// ============================================================================
+
+export interface IStockBrokerAdapter {
+ // Identification
+ readonly brokerId: string;
+ readonly brokerName: string;
+ readonly region: Region;
+ readonly isConnected: boolean;
+
+ // Authentication
+ setCredentials?(apiKey: string, apiSecret: string): void; // Set credentials before OAuth
+ getAuthUrl?(): string; // For OAuth brokers
+ authenticate(credentials: BrokerCredentials): Promise<AuthResponse>;
+ handleAuthCallback?(params: AuthCallbackParams): Promise<AuthResponse>;
+ logout(): Promise<void>;
+ refreshSession?(): Promise<AuthResponse>;
+
+ // Account
+ getFunds(): Promise<Funds>;
+ getMarginRequired(params: OrderParams): Promise<MarginRequired>;
+ calculateMargin(orders: OrderParams[]): Promise<MarginRequired>;
+
+ // Orders
+ placeOrder(params: OrderParams): Promise<OrderResponse>;
+ modifyOrder(params: ModifyOrderParams): Promise<OrderResponse>;
+ cancelOrder(orderId: string): Promise<OrderResponse>;
+ getOrders(): Promise<Order[]>;
+ getOrderHistory?(orderId: string): Promise<Order[]>;
+ getTradeBook(): Promise<Trade[]>;
+
+ // Bulk Operations
+ cancelAllOrders(): Promise<BulkOperationResult>;
+ closeAllPositions(): Promise<BulkOperationResult>;
+
+ // Smart Orders
+ placeSmartOrder(params: SmartOrderParams): Promise<OrderResponse>;
+
+ // Positions & Holdings
+ getPositions(): Promise<Position[]>;
+ getHoldings(): Promise<Holding[]>;
+ getOpenPosition(symbol: string, exchange: StockExchange, productType: ProductType): Promise<Position | null>;
+
+ // Market Data
+ getQuote(symbol: string, exchange: StockExchange): Promise<Quote>;
+ getQuotes(instruments: Array<{ symbol: string; exchange: StockExchange }>): Promise<Quote[]>;
+ getOHLCV(symbol: string, exchange: StockExchange, timeframe: TimeFrame, from: Date, to: Date): Promise<OHLCV[]>;
+ getMarketDepth(symbol: string, exchange: StockExchange): Promise<MarketDepth>;
+
+ // Symbol Search
+ searchSymbols(query: string, exchange?: StockExchange): Promise<Instrument[]>;
+ getInstrument(symbol: string, exchange: StockExchange): Promise<Instrument | null>;
+
+ // WebSocket
+ connectWebSocket(config?: WebSocketConfig): Promise<void>;
+ disconnectWebSocket(): Promise<void>;
+ subscribe(symbol: string, exchange: StockExchange, mode: SubscriptionMode): Promise<void>;
+ unsubscribe(symbol: string, exchange: StockExchange): Promise<void>;
+ onTick(callback: (tick: TickData) => void): void;
+ offTick(callback: (tick: TickData) => void): void;
+
+ // Master Contract (Symbol Database)
+ downloadMasterContract?(): Promise<void>;
+ getMasterContractLastUpdated?(): Promise<Date | null>;
+}
+
+// ============================================================================
+// BROKER METADATA
+// ============================================================================
+
+export interface StockBrokerMetadata {
+ id: string;
+ name: string;
+ displayName: string;
+ logo?: string;
+ website: string;
+
+ // Region & Market
+ region: Region;
+ country: string; // ISO country code
+ currency: Currency;
+ exchanges: StockExchange[];
+ marketHours: MarketHours;
+
+ // Features
+ features: {
+ webSocket: boolean;
+ amo: boolean; // After Market Orders
+ gtt: boolean; // Good Till Triggered
+ bracketOrder: boolean;
+ coverOrder: boolean;
+ marginCalculator: boolean;
+ optionsChain: boolean;
+ paperTrading: boolean;
+ };
+
+ // Trading capabilities
+ tradingFeatures: {
+ marketOrders: boolean;
+ limitOrders: boolean;
+ stopOrders: boolean;
+ stopLimitOrders: boolean;
+ trailingStopOrders: boolean;
+ };
+
+ // Product types supported
+ productTypes: ProductType[];
+
+ // Auth type
+ authType: 'oauth' | 'totp' | 'password' | 'api_key';
+
+ // Rate limits
+ rateLimit: {
+ ordersPerSecond: number;
+ quotesPerSecond: number;
+ };
+
+ // Fees
+ fees?: {
+ equity?: { brokerage: number; stt?: number };
+ intraday?: { brokerage: number };
+ fno?: { brokerage: number };
+ };
+
+ // Default symbols for this broker
+ defaultSymbols: string[];
+}
+
+// ============================================================================
+// API RESPONSE WRAPPER
+// ============================================================================
+
+export interface ApiResponse<T> {
+ success: boolean;
+ data?: T;
+ error?: string;
+ errorCode?: string;
+ timestamp: number;
+}
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 26e16b461..66ebf56c0 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -47,7 +47,7 @@ const NodeEditorTab = React.lazy(() => import('@/components/tabs/NodeEditorTab')
const PolygonEqTab = React.lazy(() => import('@/components/tabs/PolygonEqTab'));
const DerivativesTab = React.lazy(() => import('@/components/tabs/DerivativesTab').then(m => ({ default: m.DerivativesTab })));
const TradingTab = React.lazy(() => import('@/components/tabs/TradingTab').then(m => ({ default: m.TradingTab })));
-// const EquityTradingTab = React.lazy(() => import('@/components/tabs/equity-trading/EquityTradingTab')); // TODO: Implement
+const EquityTradingTab = React.lazy(() => import('@/components/tabs/equity-trading/EquityTradingTab'));
const DBnomicsTab = React.lazy(() => import('@/components/tabs/DBnomicsTab'));
const EconomicsTab = React.lazy(() => import('@/components/tabs/EconomicsTab'));
const MaritimeTab = React.lazy(() => import('@/components/tabs/MaritimeTabDeck'));
@@ -1107,13 +1107,11 @@ function FinxeptTerminalContent() {
<TradingTab />
</React.Suspense>
</TabsContent>
- {/* TODO: Implement EquityTradingTab
<TabsContent value="equity-trading" className="h-full m-0 p-0">
<React.Suspense fallback={<TabLoadingFallback />}>
<EquityTradingTab />
</React.Suspense>
</TabsContent>
- */}
<TabsContent value="polymarket" className="h-full m-0 p-0">
<React.Suspense fallback={<TabLoadingFallback />}>
<PolymarketTab />
diff --git a/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx b/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx
index 10322e3e5..f2c1435b5 100644
--- a/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/settings/PolymarketCredentialsPanel.tsx
@@ -1,5 +1,5 @@
// File: src/components/settings/PolymarketCredentialsPanel.tsx
-// Polymarket API credentials management panel
+// Polymarket API credentials management panel - Bloomberg Terminal Style
import React, { useState, useEffect } from 'react';
import {
@@ -24,6 +24,27 @@ import {
import polymarketServiceEnhanced from '@/services/polymarket/polymarketServiceEnhanced';
import { getSetting, saveSetting } from '@/services/core/sqliteService';
+// Bloomberg Professional Color Palette
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#888888',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ INPUT_BG: '#141414',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#666666',
+ FONT: '"IBM Plex Mono", "Consolas", monospace',
+};
+
interface PolymarketCredentials {
apiKey: string;
apiSecret: string;
@@ -60,50 +81,43 @@ export const PolymarketCredentialsPanel: React.FC = () => {
const loadSavedCredentials = async () => {
try {
- // PURE SQLite - Load credentials from database
const saved = await getSetting('polymarket_credentials');
if (saved) {
const parsed = JSON.parse(saved);
setCredentials(parsed);
-
- // Set credentials in service
polymarketServiceEnhanced.setCredentials({
apiKey: parsed.apiKey,
apiSecret: parsed.apiSecret,
apiPassphrase: parsed.apiPassphrase
});
-
if (parsed.walletAddress) {
setWalletAddress(parsed.walletAddress);
setWalletConnected(true);
}
}
} catch (error) {
- console.error('[PolymarketCredentials] Failed to load credentials from SQLite:', error);
+ console.error('[PolymarketCredentials] Failed to load credentials:', error);
}
};
const saveCredentials = async (creds: PolymarketCredentials) => {
try {
- // PURE SQLite - Save credentials to database
await saveSetting('polymarket_credentials', JSON.stringify(creds), 'polymarket');
setCredentials(creds);
-
- // Set in service
polymarketServiceEnhanced.setCredentials({
apiKey: creds.apiKey,
apiSecret: creds.apiSecret,
apiPassphrase: creds.apiPassphrase
});
} catch (error) {
- console.error('[PolymarketCredentials] Failed to save credentials to SQLite:', error);
+ console.error('[PolymarketCredentials] Failed to save credentials:', error);
throw error;
}
};
const handleManualSave = () => {
if (!formData.apiKey || !formData.apiSecret || !formData.apiPassphrase) {
- alert('All fields are required');
+ setTestResult({ success: false, message: 'All fields are required' });
return;
}
@@ -126,12 +140,10 @@ export const PolymarketCredentialsPanel: React.FC = () => {
setTestResult(null);
try {
- // Check if MetaMask is installed
if (!window.ethereum) {
throw new Error('MetaMask not detected. Please install MetaMask to continue.');
}
- // Request account access
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
@@ -143,8 +155,6 @@ export const PolymarketCredentialsPanel: React.FC = () => {
const address = accounts[0];
setWalletAddress(address);
setWalletConnected(true);
-
- // Now generate API credentials
await generateAPICredentials(address);
} catch (error: any) {
@@ -160,53 +170,34 @@ export const PolymarketCredentialsPanel: React.FC = () => {
const generateAPICredentials = async (address: string) => {
try {
- // Import ethers dynamically (v6 API)
const { BrowserProvider } = await import('ethers');
-
const provider = new BrowserProvider(window.ethereum as any);
const signer = await provider.getSigner();
- // EIP-712 domain and types for Polymarket
const domain = {
name: 'ClobAuthDomain',
version: '1',
- chainId: 137 // Polygon Mainnet
+ chainId: 137
};
const types = {
- ClobAuth: [
- { name: 'message', type: 'string' }
- ]
+ ClobAuth: [{ name: 'message', type: 'string' }]
};
const value = {
message: 'This message attests that I control the given wallet'
};
- setTestResult({
- success: true,
- message: 'Please sign the message in MetaMask...'
- });
+ setTestResult({ success: true, message: 'Please sign the message in MetaMask...' });
- // Request signature from user (v6 API uses signTypedData)
const signature = await signer.signTypedData(domain, types, value);
- setTestResult({
- success: true,
- message: 'Generating API credentials...'
- });
+ setTestResult({ success: true, message: 'Generating API credentials...' });
- // Call Polymarket API to generate credentials
const response = await fetch('https://clob.polymarket.com/auth/api-key', {
method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- address: address,
- signature: signature,
- nonce: 0 // Use 0 for deterministic credentials
- })
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ address, signature, nonce: 0 })
});
if (!response.ok) {
@@ -216,7 +207,6 @@ export const PolymarketCredentialsPanel: React.FC = () => {
const apiCredentials = await response.json();
- // Save credentials
const newCredentials: PolymarketCredentials = {
apiKey: apiCredentials.apiKey,
apiSecret: apiCredentials.secret,
@@ -227,18 +217,11 @@ export const PolymarketCredentialsPanel: React.FC = () => {
};
saveCredentials(newCredentials);
-
- setTestResult({
- success: true,
- message: 'API credentials generated and saved successfully!'
- });
+ setTestResult({ success: true, message: 'API credentials generated and saved!' });
} catch (error: any) {
console.error('Failed to generate API credentials:', error);
- setTestResult({
- success: false,
- message: error.message || 'Failed to generate API credentials'
- });
+ setTestResult({ success: false, message: error.message || 'Failed to generate credentials' });
}
};
@@ -252,63 +235,47 @@ export const PolymarketCredentialsPanel: React.FC = () => {
setTestResult(null);
try {
- // Test by fetching CLOB markets (public endpoint that requires auth for rate limits)
const markets = await polymarketServiceEnhanced.getCLOBMarkets();
-
if (markets && (markets.length > 0 || Array.isArray(markets))) {
- setTestResult({
- success: true,
- message: 'Connection successful! Credentials are valid.'
- });
+ setTestResult({ success: true, message: 'Connection successful! Credentials valid.' });
} else {
- setTestResult({
- success: false,
- message: 'Invalid response from API'
- });
+ setTestResult({ success: false, message: 'Invalid response from API' });
}
} catch (error: any) {
- console.error('API test failed:', error);
- setTestResult({
- success: false,
- message: `Test failed: ${error.message}`
- });
+ setTestResult({ success: false, message: `Test failed: ${error.message}` });
} finally {
setIsTesting(false);
}
};
const handleDelete = async () => {
- if (confirm('Are you sure you want to delete your Polymarket credentials?')) {
- // PURE SQLite - Clear credentials from database
+ if (confirm('Delete Polymarket credentials?')) {
await saveSetting('polymarket_credentials', '', 'polymarket');
setCredentials(null);
setWalletConnected(false);
setWalletAddress('');
polymarketServiceEnhanced.clearCredentials();
- setTestResult({ success: true, message: 'Credentials deleted successfully' });
+ setTestResult({ success: true, message: 'Credentials deleted' });
}
};
const handleCopy = (text: string, label: string) => {
navigator.clipboard.writeText(text);
- setTestResult({ success: true, message: `${label} copied to clipboard!` });
+ setTestResult({ success: true, message: `${label} copied!` });
setTimeout(() => setTestResult(null), 2000);
};
const handleExport = () => {
if (!credentials) return;
-
const dataStr = JSON.stringify(credentials, null, 2);
const dataBlob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(dataBlob);
-
const link = document.createElement('a');
link.href = url;
link.download = 'polymarket-credentials.json';
link.click();
-
URL.revokeObjectURL(url);
- setTestResult({ success: true, message: 'Credentials exported successfully!' });
+ setTestResult({ success: true, message: 'Credentials exported!' });
};
const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
@@ -319,203 +286,258 @@ export const PolymarketCredentialsPanel: React.FC = () => {
reader.onload = (e) => {
try {
const imported = JSON.parse(e.target?.result as string);
-
if (imported.apiKey && imported.apiSecret && imported.apiPassphrase) {
saveCredentials(imported);
- setTestResult({ success: true, message: 'Credentials imported successfully!' });
+ setTestResult({ success: true, message: 'Credentials imported!' });
} else {
- throw new Error('Invalid credentials file');
+ throw new Error('Invalid file');
}
- } catch (error) {
+ } catch {
setTestResult({ success: false, message: 'Failed to import credentials' });
}
};
reader.readAsText(file);
};
+ // Button style helper
+ const btnStyle = (color: string, isDisabled?: boolean) => ({
+ padding: '6px 12px',
+ backgroundColor: isDisabled ? BLOOMBERG.MUTED : color,
+ border: 'none',
+ color: color === BLOOMBERG.ORANGE ? '#000' : BLOOMBERG.WHITE,
+ cursor: isDisabled ? 'not-allowed' : 'pointer',
+ fontSize: '10px',
+ fontWeight: 600,
+ fontFamily: BLOOMBERG.FONT,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ opacity: isDisabled ? 0.5 : 1,
+ letterSpacing: '0.5px',
+ });
+
return (
- <div className="space-y-6">
+ <div style={{
+ fontFamily: BLOOMBERG.FONT,
+ color: BLOOMBERG.WHITE,
+ backgroundColor: BLOOMBERG.DARK_BG,
+ }}>
{/* Header */}
- <div className="border-b border-gray-700 pb-4">
- <div className="flex items-center gap-3 mb-2">
- <Shield className="text-orange-500" size={24} />
- <h2 className="text-lg font-bold text-white">Polymarket API Credentials</h2>
+ <div style={{
+ borderBottom: `2px solid ${BLOOMBERG.ORANGE}`,
+ padding: '12px 0',
+ marginBottom: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ }}>
+ <Shield size={20} color={BLOOMBERG.ORANGE} />
+ <div>
+ <div style={{ color: BLOOMBERG.ORANGE, fontSize: '14px', fontWeight: 700, letterSpacing: '0.5px' }}>
+ POLYMARKET API CREDENTIALS
+ </div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '10px', marginTop: '2px' }}>
+ Manage API credentials for trading and portfolio access
+ </div>
</div>
- <p className="text-sm text-gray-400">
- Manage your Polymarket API credentials for trading and portfolio access
- </p>
</div>
{/* Status Message */}
{testResult && (
- <div className={`flex items-start gap-3 p-3 rounded border ${
- testResult.success
- ? 'bg-green-900/20 border-green-700'
- : 'bg-red-900/20 border-red-700'
- }`}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '10px 12px',
+ marginBottom: '16px',
+ backgroundColor: testResult.success ? `${BLOOMBERG.GREEN}15` : `${BLOOMBERG.RED}15`,
+ border: `1px solid ${testResult.success ? BLOOMBERG.GREEN : BLOOMBERG.RED}`,
+ }}>
{testResult.success ? (
- <CheckCircle className="text-green-400 flex-shrink-0" size={20} />
+ <CheckCircle size={16} color={BLOOMBERG.GREEN} />
) : (
- <XCircle className="text-red-400 flex-shrink-0" size={20} />
+ <XCircle size={16} color={BLOOMBERG.RED} />
)}
- <p className={`text-sm ${testResult.success ? 'text-green-300' : 'text-red-300'}`}>
+ <span style={{ color: testResult.success ? BLOOMBERG.GREEN : BLOOMBERG.RED, fontSize: '11px' }}>
{testResult.message}
- </p>
+ </span>
</div>
)}
- {/* Info Alert */}
- <div className="flex items-start gap-3 p-3 rounded border bg-blue-900/20 border-blue-700">
- <AlertCircle className="text-blue-400 flex-shrink-0" size={20} />
- <div className="text-sm text-blue-300 space-y-2">
- <p>
- <strong>Two ways to get credentials:</strong>
- </p>
- <ol className="list-decimal list-inside space-y-1 ml-2">
- <li><strong>Wallet Connection</strong> - Automatic credential generation from MetaMask</li>
- <li><strong>Manual Entry</strong> - Enter existing credentials from Polymarket</li>
- </ol>
- <p className="mt-2">
- <a
- href="https://docs.polymarket.com/developers/CLOB/authentication"
- target="_blank"
- rel="noopener noreferrer"
- className="text-blue-400 hover:text-blue-300 underline inline-flex items-center gap-1"
- >
- Learn more about authentication <ExternalLink size={12} />
- </a>
- </p>
+ {/* Info Box */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: '10px',
+ padding: '12px',
+ marginBottom: '16px',
+ backgroundColor: `${BLOOMBERG.BLUE}10`,
+ border: `1px solid ${BLOOMBERG.BLUE}40`,
+ }}>
+ <AlertCircle size={16} color={BLOOMBERG.BLUE} style={{ flexShrink: 0, marginTop: '2px' }} />
+ <div style={{ fontSize: '10px', color: BLOOMBERG.CYAN, lineHeight: 1.5 }}>
+ <div style={{ fontWeight: 600, marginBottom: '6px' }}>TWO WAYS TO GET CREDENTIALS:</div>
+ <div style={{ marginBottom: '4px' }}>1. <span style={{ color: BLOOMBERG.ORANGE }}>WALLET CONNECTION</span> - Auto-generate from MetaMask</div>
+ <div style={{ marginBottom: '8px' }}>2. <span style={{ color: BLOOMBERG.BLUE }}>MANUAL ENTRY</span> - Enter existing credentials</div>
+ <a
+ href="https://docs.polymarket.com/developers/CLOB/authentication"
+ target="_blank"
+ rel="noopener noreferrer"
+ style={{ color: BLOOMBERG.CYAN, textDecoration: 'underline', display: 'inline-flex', alignItems: 'center', gap: '4px' }}
+ >
+ Documentation <ExternalLink size={10} />
+ </a>
</div>
</div>
{/* Current Credentials Display */}
{credentials && !isEditing && (
- <div className="bg-gray-800 rounded-lg border border-gray-700 p-4 space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <CheckCircle className="text-green-400" size={20} />
- <h3 className="font-semibold text-white">Credentials Active</h3>
+ <div style={{
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '16px',
+ marginBottom: '16px',
+ }}>
+ {/* Status Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '16px',
+ paddingBottom: '12px',
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <CheckCircle size={16} color={BLOOMBERG.GREEN} />
+ <span style={{ color: BLOOMBERG.GREEN, fontSize: '12px', fontWeight: 600 }}>CREDENTIALS ACTIVE</span>
</div>
- <div className="flex items-center gap-2">
- <span className="text-xs text-gray-400">
- Method: {credentials.method === 'wallet' ? 'Wallet' : 'Manual'}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.MUTED, fontSize: '9px' }}>
+ METHOD: {credentials.method === 'wallet' ? 'WALLET' : 'MANUAL'}
</span>
- {credentials.method === 'wallet' && (
- <Wallet className="text-blue-400" size={16} />
- )}
+ {credentials.method === 'wallet' && <Wallet size={12} color={BLOOMBERG.BLUE} />}
</div>
</div>
- {/* Wallet Address */}
- {credentials.walletAddress && (
+ {/* Credential Fields */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ {/* Wallet Address */}
+ {credentials.walletAddress && (
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '4px', letterSpacing: '0.5px' }}>WALLET ADDRESS</div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px 10px',
+ }}>
+ <code style={{ flex: 1, color: BLOOMBERG.CYAN, fontSize: '11px' }}>{credentials.walletAddress}</code>
+ <button onClick={() => handleCopy(credentials.walletAddress!, 'Address')} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
+ <Copy size={12} color={BLOOMBERG.GRAY} />
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* API Key */}
<div>
- <label className="block text-xs text-gray-400 mb-1">Wallet Address</label>
- <div className="flex items-center gap-2 bg-gray-900 rounded px-3 py-2">
- <code className="flex-1 text-sm text-white font-mono">
- {credentials.walletAddress}
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '4px', letterSpacing: '0.5px' }}>API KEY</div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px 10px',
+ }}>
+ <code style={{ flex: 1, color: BLOOMBERG.WHITE, fontSize: '11px' }}>
+ {showSecrets ? credentials.apiKey : '••••••••••••••••••••'}
</code>
- <button
- onClick={() => handleCopy(credentials.walletAddress!, 'Wallet address')}
- className="text-gray-400 hover:text-white transition-colors"
- >
- <Copy size={14} />
+ <button onClick={() => handleCopy(credentials.apiKey, 'API Key')} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
+ <Copy size={12} color={BLOOMBERG.GRAY} />
</button>
</div>
</div>
- )}
- {/* API Key */}
- <div>
- <label className="block text-xs text-gray-400 mb-1">API Key</label>
- <div className="flex items-center gap-2 bg-gray-900 rounded px-3 py-2">
- <code className="flex-1 text-sm text-white font-mono">
- {showSecrets ? credentials.apiKey : '••••••••••••••••'}
- </code>
- <button
- onClick={() => handleCopy(credentials.apiKey, 'API Key')}
- className="text-gray-400 hover:text-white transition-colors"
- >
- <Copy size={14} />
- </button>
+ {/* API Secret */}
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '4px', letterSpacing: '0.5px' }}>API SECRET</div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px 10px',
+ }}>
+ <code style={{ flex: 1, color: BLOOMBERG.WHITE, fontSize: '11px' }}>
+ {showSecrets ? credentials.apiSecret : '••••••••••••••••••••'}
+ </code>
+ <button onClick={() => handleCopy(credentials.apiSecret, 'API Secret')} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
+ <Copy size={12} color={BLOOMBERG.GRAY} />
+ </button>
+ </div>
</div>
- </div>
- {/* API Secret */}
- <div>
- <label className="block text-xs text-gray-400 mb-1">API Secret</label>
- <div className="flex items-center gap-2 bg-gray-900 rounded px-3 py-2">
- <code className="flex-1 text-sm text-white font-mono">
- {showSecrets ? credentials.apiSecret : '••••••••••••••••'}
- </code>
- <button
- onClick={() => handleCopy(credentials.apiSecret, 'API Secret')}
- className="text-gray-400 hover:text-white transition-colors"
- >
- <Copy size={14} />
- </button>
+ {/* API Passphrase */}
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '4px', letterSpacing: '0.5px' }}>API PASSPHRASE</div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px 10px',
+ }}>
+ <code style={{ flex: 1, color: BLOOMBERG.WHITE, fontSize: '11px' }}>
+ {showSecrets ? credentials.apiPassphrase : '••••••••••••••••••••'}
+ </code>
+ <button onClick={() => handleCopy(credentials.apiPassphrase, 'Passphrase')} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
+ <Copy size={12} color={BLOOMBERG.GRAY} />
+ </button>
+ </div>
</div>
- </div>
- {/* API Passphrase */}
- <div>
- <label className="block text-xs text-gray-400 mb-1">API Passphrase</label>
- <div className="flex items-center gap-2 bg-gray-900 rounded px-3 py-2">
- <code className="flex-1 text-sm text-white font-mono">
- {showSecrets ? credentials.apiPassphrase : '••••••••••••••••'}
- </code>
- <button
- onClick={() => handleCopy(credentials.apiPassphrase, 'API Passphrase')}
- className="text-gray-400 hover:text-white transition-colors"
- >
- <Copy size={14} />
- </button>
- </div>
+ {/* Created Date */}
+ {credentials.createdAt && (
+ <div style={{ color: BLOOMBERG.MUTED, fontSize: '9px' }}>
+ CREATED: {new Date(credentials.createdAt).toLocaleString()}
+ </div>
+ )}
</div>
- {/* Creation Date */}
- {credentials.createdAt && (
- <div className="text-xs text-gray-400">
- Created: {new Date(credentials.createdAt).toLocaleString()}
- </div>
- )}
-
{/* Actions */}
- <div className="flex items-center gap-2 pt-2 border-t border-gray-700">
- <button
- onClick={() => setShowSecrets(!showSecrets)}
- className="flex items-center gap-2 px-3 py-1.5 bg-gray-700 hover:bg-gray-600 rounded text-sm transition-colors"
- >
- {showSecrets ? <EyeOff size={14} /> : <Eye size={14} />}
- {showSecrets ? 'Hide' : 'Show'}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginTop: '16px',
+ paddingTop: '12px',
+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,
+ flexWrap: 'wrap',
+ }}>
+ <button onClick={() => setShowSecrets(!showSecrets)} style={btnStyle(BLOOMBERG.HEADER_BG)}>
+ {showSecrets ? <EyeOff size={12} /> : <Eye size={12} />}
+ {showSecrets ? 'HIDE' : 'SHOW'}
</button>
- <button
- onClick={handleTest}
- disabled={isTesting}
- className="flex items-center gap-2 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded text-sm transition-colors"
- >
- {isTesting ? <RefreshCw size={14} className="animate-spin" /> : <Zap size={14} />}
- Test Connection
+ <button onClick={handleTest} disabled={isTesting} style={btnStyle(BLOOMBERG.BLUE, isTesting)}>
+ {isTesting ? <RefreshCw size={12} className="animate-spin" /> : <Zap size={12} />}
+ TEST
</button>
- <button
- onClick={handleExport}
- className="flex items-center gap-2 px-3 py-1.5 bg-gray-700 hover:bg-gray-600 rounded text-sm transition-colors"
- >
- <Download size={14} />
- Export
+ <button onClick={handleExport} style={btnStyle(BLOOMBERG.HEADER_BG)}>
+ <Download size={12} />
+ EXPORT
</button>
- <button
- onClick={() => setIsEditing(true)}
- className="flex items-center gap-2 px-3 py-1.5 bg-orange-600 hover:bg-orange-700 rounded text-sm transition-colors"
- >
- <Key size={14} />
- Update
+ <button onClick={() => setIsEditing(true)} style={btnStyle(BLOOMBERG.ORANGE)}>
+ <Key size={12} />
+ UPDATE
</button>
- <button
- onClick={handleDelete}
- className="flex items-center gap-2 px-3 py-1.5 bg-red-600 hover:bg-red-700 rounded text-sm transition-colors ml-auto"
- >
- <Trash2 size={14} />
- Delete
+ <button onClick={handleDelete} style={{ ...btnStyle(BLOOMBERG.RED), marginLeft: 'auto' }}>
+ <Trash2 size={12} />
+ DELETE
</button>
</div>
</div>
@@ -523,190 +545,239 @@ export const PolymarketCredentialsPanel: React.FC = () => {
{/* Setup/Edit Section */}
{(!credentials || isEditing) && (
- <div className="space-y-4">
- {/* Method Selection */}
- <div className="grid grid-cols-2 gap-4">
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* Method Selection Cards */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
{/* Wallet Connection */}
<button
onClick={handleWalletConnect}
disabled={isConnecting}
- className="border border-gray-700 bg-gray-800 hover:bg-gray-700 rounded-lg p-6 text-left transition-all hover:border-orange-500 disabled:opacity-50 disabled:cursor-not-allowed"
+ style={{
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '20px',
+ textAlign: 'left',
+ cursor: isConnecting ? 'not-allowed' : 'pointer',
+ opacity: isConnecting ? 0.6 : 1,
+ transition: 'border-color 0.2s',
+ }}
+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.ORANGE; }}
+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.BORDER; }}
>
- <div className="flex items-center gap-3 mb-3">
- <Wallet className="text-orange-500" size={24} />
- <h3 className="font-semibold text-white">Wallet Connection</h3>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '10px' }}>
+ <Wallet size={20} color={BLOOMBERG.ORANGE} />
+ <span style={{ color: BLOOMBERG.WHITE, fontSize: '12px', fontWeight: 600 }}>WALLET CONNECTION</span>
</div>
- <p className="text-sm text-gray-400 mb-3">
- Connect MetaMask to automatically generate API credentials
- </p>
- <div className="flex items-center gap-2 text-xs text-green-400">
- <CheckCircle size={14} />
- <span>Recommended</span>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '10px', marginBottom: '10px', lineHeight: 1.4 }}>
+ Connect MetaMask to auto-generate API credentials
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', color: BLOOMBERG.GREEN, fontSize: '9px' }}>
+ <CheckCircle size={12} />
+ RECOMMENDED
</div>
{isConnecting && (
- <div className="mt-3 flex items-center gap-2 text-sm text-orange-400">
- <RefreshCw size={14} className="animate-spin" />
- <span>Connecting...</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', color: BLOOMBERG.ORANGE, fontSize: '10px', marginTop: '10px' }}>
+ <RefreshCw size={12} className="animate-spin" />
+ CONNECTING...
</div>
)}
</button>
{/* Manual Entry */}
<button
- onClick={() => {
- setIsEditing(true);
- setTestResult(null);
+ onClick={() => { setIsEditing(true); setTestResult(null); }}
+ style={{
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '20px',
+ textAlign: 'left',
+ cursor: 'pointer',
+ transition: 'border-color 0.2s',
}}
- className="border border-gray-700 bg-gray-800 hover:bg-gray-700 rounded-lg p-6 text-left transition-all hover:border-blue-500"
+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.BLUE; }}
+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.BORDER; }}
>
- <div className="flex items-center gap-3 mb-3">
- <Key className="text-blue-500" size={24} />
- <h3 className="font-semibold text-white">Manual Entry</h3>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '10px' }}>
+ <Key size={20} color={BLOOMBERG.BLUE} />
+ <span style={{ color: BLOOMBERG.WHITE, fontSize: '12px', fontWeight: 600 }}>MANUAL ENTRY</span>
</div>
- <p className="text-sm text-gray-400 mb-3">
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '10px', marginBottom: '10px', lineHeight: 1.4 }}>
Enter existing API credentials from Polymarket
- </p>
- <div className="flex items-center gap-2 text-xs text-gray-400">
- <LinkIcon size={14} />
- <span>For existing credentials</span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', color: BLOOMBERG.MUTED, fontSize: '9px' }}>
+ <LinkIcon size={12} />
+ FOR EXISTING CREDENTIALS
</div>
</button>
</div>
{/* Manual Entry Form */}
{isEditing && (
- <>
- <div className="bg-gray-800 rounded-lg border border-gray-700 p-4 space-y-4">
- <h3 className="font-semibold text-white flex items-center gap-2">
- <Key size={18} />
- Enter API Credentials
- </h3>
-
- {/* API Key Input */}
+ <div style={{
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '16px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>
+ <Key size={16} color={BLOOMBERG.ORANGE} />
+ <span style={{ color: BLOOMBERG.WHITE, fontSize: '12px', fontWeight: 600 }}>ENTER API CREDENTIALS</span>
+ </div>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ {/* API Key */}
<div>
- <label className="block text-sm text-gray-300 mb-2">
- API Key <span className="text-red-400">*</span>
- </label>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '4px', letterSpacing: '0.5px' }}>
+ API KEY <span style={{ color: BLOOMBERG.RED }}>*</span>
+ </div>
<input
type="text"
value={formData.apiKey}
onChange={(e) => setFormData({ ...formData, apiKey: e.target.value })}
placeholder="Enter your API key"
- className="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-white text-sm focus:border-orange-500 focus:outline-none"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '10px 12px',
+ color: BLOOMBERG.WHITE,
+ fontSize: '11px',
+ fontFamily: BLOOMBERG.FONT,
+ outline: 'none',
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.ORANGE; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.BORDER; }}
/>
</div>
- {/* API Secret Input */}
+ {/* API Secret */}
<div>
- <label className="block text-sm text-gray-300 mb-2">
- API Secret <span className="text-red-400">*</span>
- </label>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '4px', letterSpacing: '0.5px' }}>
+ API SECRET <span style={{ color: BLOOMBERG.RED }}>*</span>
+ </div>
<input
type="password"
value={formData.apiSecret}
onChange={(e) => setFormData({ ...formData, apiSecret: e.target.value })}
placeholder="Enter your API secret"
- className="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-white text-sm focus:border-orange-500 focus:outline-none"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '10px 12px',
+ color: BLOOMBERG.WHITE,
+ fontSize: '11px',
+ fontFamily: BLOOMBERG.FONT,
+ outline: 'none',
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.ORANGE; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.BORDER; }}
/>
</div>
- {/* API Passphrase Input */}
+ {/* API Passphrase */}
<div>
- <label className="block text-sm text-gray-300 mb-2">
- API Passphrase <span className="text-red-400">*</span>
- </label>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '4px', letterSpacing: '0.5px' }}>
+ API PASSPHRASE <span style={{ color: BLOOMBERG.RED }}>*</span>
+ </div>
<input
type="password"
value={formData.apiPassphrase}
onChange={(e) => setFormData({ ...formData, apiPassphrase: e.target.value })}
placeholder="Enter your API passphrase"
- className="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-white text-sm focus:border-orange-500 focus:outline-none"
+ style={{
+ width: '100%',
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '10px 12px',
+ color: BLOOMBERG.WHITE,
+ fontSize: '11px',
+ fontFamily: BLOOMBERG.FONT,
+ outline: 'none',
+ }}
+ onFocus={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.ORANGE; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = BLOOMBERG.BORDER; }}
/>
</div>
{/* Import Option */}
- <div className="pt-3 border-t border-gray-700">
- <label className="flex items-center gap-2 text-sm text-gray-400 cursor-pointer hover:text-white transition-colors">
- <Upload size={16} />
- <span>Or import from file</span>
- <input
- type="file"
- accept=".json"
- onChange={handleImport}
- className="hidden"
- />
+ <div style={{ paddingTop: '8px', borderTop: `1px solid ${BLOOMBERG.BORDER}` }}>
+ <label style={{
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: '6px',
+ color: BLOOMBERG.GRAY,
+ fontSize: '10px',
+ cursor: 'pointer',
+ }}>
+ <Upload size={14} />
+ Or import from file
+ <input type="file" accept=".json" onChange={handleImport} style={{ display: 'none' }} />
</label>
</div>
- {/* Action Buttons */}
- <div className="flex items-center gap-3 pt-2">
- <button
- onClick={handleManualSave}
- className="flex items-center gap-2 px-4 py-2 bg-orange-600 hover:bg-orange-700 rounded text-sm font-semibold transition-colors"
- >
- <Save size={16} />
- Save Credentials
+ {/* Actions */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px' }}>
+ <button onClick={handleManualSave} style={btnStyle(BLOOMBERG.ORANGE)}>
+ <Save size={12} />
+ SAVE CREDENTIALS
</button>
{credentials && (
<button
- onClick={() => {
- setIsEditing(false);
- setFormData({ apiKey: '', apiSecret: '', apiPassphrase: '' });
- }}
- className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded text-sm transition-colors"
+ onClick={() => { setIsEditing(false); setFormData({ apiKey: '', apiSecret: '', apiPassphrase: '' }); }}
+ style={btnStyle(BLOOMBERG.HEADER_BG)}
>
- Cancel
+ CANCEL
</button>
)}
</div>
</div>
- </>
+ </div>
)}
</div>
)}
{/* Help Section */}
- <div className="bg-gray-800/50 rounded-lg border border-gray-700 p-4">
- <h3 className="font-semibold text-white mb-3 flex items-center gap-2">
- <AlertCircle size={18} />
- Need Help?
- </h3>
- <ul className="space-y-2 text-sm text-gray-300">
- <li className="flex items-start gap-2">
- <span className="text-orange-500">•</span>
- <span>
- <strong>No credentials?</strong> Use wallet connection to automatically generate them
- </span>
- </li>
- <li className="flex items-start gap-2">
- <span className="text-orange-500">•</span>
- <span>
- <strong>Already have credentials?</strong> Enter them manually or import from file
- </span>
- </li>
- <li className="flex items-start gap-2">
- <span className="text-orange-500">•</span>
- <span>
- <strong>Security:</strong> Credentials are stored locally and never sent to our servers
- </span>
- </li>
- <li className="flex items-start gap-2">
- <span className="text-orange-500">•</span>
+ <div style={{
+ backgroundColor: `${BLOOMBERG.PANEL_BG}80`,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '16px',
+ marginTop: '16px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
+ <AlertCircle size={14} color={BLOOMBERG.ORANGE} />
+ <span style={{ color: BLOOMBERG.WHITE, fontSize: '11px', fontWeight: 600 }}>NEED HELP?</span>
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', fontSize: '10px', color: BLOOMBERG.GRAY, lineHeight: 1.5 }}>
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.ORANGE }}>&#8226;</span>
+ <span><span style={{ color: BLOOMBERG.WHITE }}>No credentials?</span> Use wallet connection to auto-generate</span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.ORANGE }}>&#8226;</span>
+ <span><span style={{ color: BLOOMBERG.WHITE }}>Already have credentials?</span> Enter manually or import from file</span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.ORANGE }}>&#8226;</span>
+ <span><span style={{ color: BLOOMBERG.WHITE }}>Security:</span> Credentials stored locally, never sent to our servers</span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.ORANGE }}>&#8226;</span>
<span>
Visit{' '}
- <a
- href="https://docs.polymarket.com"
- target="_blank"
- rel="noopener noreferrer"
- className="text-blue-400 hover:text-blue-300 underline"
- >
+ <a href="https://docs.polymarket.com" target="_blank" rel="noopener noreferrer" style={{ color: BLOOMBERG.CYAN, textDecoration: 'underline' }}>
Polymarket Docs
</a>
- {' '}for more information
+ {' '}for more info
</span>
- </li>
- </ul>
+ </div>
+ </div>
</div>
+
+ {/* CSS for spin animation */}
+ <style>{`
+ @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
+ .animate-spin { animation: spin 1s linear infinite; }
+ `}</style>
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
index 3fd5578cd..ce52492e7 100644
--- a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
@@ -1,5 +1,5 @@
import { useTerminalTheme } from '@/contexts/ThemeContext';
-import React, { useState, useCallback, useMemo, useEffect } from 'react';
+import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
import { saveSetting, getSetting } from '@/services/core/sqliteService';
import ReactFlow, {
Node,
@@ -15,6 +15,8 @@ import ReactFlow, {
NodeTypes,
Handle,
Position,
+ ReactFlowProvider,
+ useReactFlow,
} from 'reactflow';
import 'reactflow/dist/style.css';
import {
@@ -33,7 +35,21 @@ import {
Edit3,
X,
Monitor,
- Rocket
+ Rocket,
+ ChevronLeft,
+ ChevronRight,
+ Search,
+ Settings2,
+ Workflow,
+ Filter,
+ GitBranch,
+ Code,
+ Bell,
+ Shield,
+ BarChart2,
+ Activity,
+ RefreshCw,
+ AlertCircle,
} from 'lucide-react';
import MCPToolNode from './node-editor/MCPToolNode';
import { generateMCPNodeConfigs, MCPNodeConfig } from './node-editor/mcpNodeConfigs';
@@ -42,14 +58,20 @@ import ResultsDisplayNode from './node-editor/ResultsDisplayNode';
import AgentMediatorNode from './node-editor/AgentMediatorNode';
import DataSourceNode from './node-editor/DataSourceNode';
import TechnicalIndicatorNode from './node-editor/TechnicalIndicatorNode';
+import BacktestNode from './node-editor/BacktestNode';
+import OptimizationNode from './node-editor/OptimizationNode';
+import { SystemNode } from './node-editor/SystemNode';
import WorkflowManager from './node-editor/WorkflowManager';
import ResultsModal from './node-editor/ResultsModal';
+import { NodeParameterInput } from './node-editor/NodeParameterInput';
+import type { INodeProperties, NodeParameterValue } from '@/services/nodeSystem';
import { pythonAgentService, AgentMetadata } from '@/services/chat/pythonAgentService';
import { workflowExecutor } from './node-editor/WorkflowExecutor';
-import { Workflow, workflowService } from '@/services/core/workflowService';
+import { Workflow as WorkflowType, workflowService } from '@/services/core/workflowService';
import { nodeExecutionManager } from '@/services/core/nodeExecutionManager';
import { TabFooter } from '@/components/common/TabFooter';
import { useTranslation } from 'react-i18next';
+import { NodeRegistry, INodeTypeDescription } from '@/services/nodeSystem';
// Custom Node Component
const CustomNode = ({ data, id, selected }: any) => {
@@ -216,7 +238,8 @@ const CustomNode = ({ data, id, selected }: any) => {
);
};
-const NODE_CONFIGS = [
+// Built-in UI node configs (these have custom React components)
+const BUILTIN_NODE_CONFIGS = [
{
type: 'data-source',
label: 'Data Source',
@@ -224,6 +247,7 @@ const NODE_CONFIGS = [
category: 'Input',
hasInput: false,
hasOutput: true,
+ description: 'Connect to databases and fetch data',
},
{
type: 'technical-indicator',
@@ -232,14 +256,16 @@ const NODE_CONFIGS = [
category: 'Processing',
hasInput: true,
hasOutput: true,
+ description: 'Calculate technical indicators on market data',
},
{
type: 'agent-mediator',
label: 'Agent Mediator',
- color: '#3b82f6',
- category: 'Processing',
+ color: '#8b5cf6',
+ category: 'AI',
hasInput: true,
hasOutput: true,
+ description: 'AI-powered data analysis and decision making',
},
{
type: 'results-display',
@@ -248,9 +274,449 @@ const NODE_CONFIGS = [
category: 'Output',
hasInput: true,
hasOutput: false,
+ description: 'Display workflow results with formatting',
+ },
+ {
+ type: 'backtest',
+ label: 'Backtest',
+ color: '#06b6d4',
+ category: 'Analytics',
+ hasInput: true,
+ hasOutput: true,
+ description: 'Run backtests on trading strategies',
+ },
+ {
+ type: 'optimization',
+ label: 'Optimization',
+ color: '#a855f7',
+ category: 'Analytics',
+ hasInput: true,
+ hasOutput: true,
+ description: 'Optimize strategy parameters using grid/genetic algorithms',
},
];
+// Category icons and colors for the palette
+const CATEGORY_CONFIG: Record<string, { icon: React.ReactNode; color: string }> = {
+ 'Core': { icon: <Workflow size={14} />, color: '#6b7280' },
+ 'Input': { icon: <Database size={14} />, color: '#3b82f6' },
+ 'Processing': { icon: <Zap size={14} />, color: '#10b981' },
+ 'Output': { icon: <Monitor size={14} />, color: '#f59e0b' },
+ 'AI': { icon: <Brain size={14} />, color: '#8b5cf6' },
+ 'Analytics': { icon: <BarChart2 size={14} />, color: '#06b6d4' },
+ 'Market Data': { icon: <Activity size={14} />, color: '#22c55e' },
+ 'Control Flow': { icon: <GitBranch size={14} />, color: '#eab308' },
+ 'Transform': { icon: <Filter size={14} />, color: '#ec4899' },
+ 'Safety': { icon: <Shield size={14} />, color: '#ef4444' },
+ 'Notifications': { icon: <Bell size={14} />, color: '#f97316' },
+ 'Triggers': { icon: <Zap size={14} />, color: '#a855f7' },
+ 'Trading': { icon: <TrendingUp size={14} />, color: '#14b8a6' },
+ 'agents': { icon: <Brain size={14} />, color: '#8b5cf6' },
+ 'marketData': { icon: <Activity size={14} />, color: '#22c55e' },
+ 'trading': { icon: <TrendingUp size={14} />, color: '#14b8a6' },
+ 'triggers': { icon: <Zap size={14} />, color: '#a855f7' },
+ 'controlFlow': { icon: <GitBranch size={14} />, color: '#eab308' },
+ 'transform': { icon: <Filter size={14} />, color: '#ec4899' },
+ 'safety': { icon: <Shield size={14} />, color: '#ef4444' },
+ 'notifications': { icon: <Bell size={14} />, color: '#f97316' },
+ 'analytics': { icon: <BarChart2 size={14} />, color: '#06b6d4' },
+};
+
+// Integrated Node Palette Component
+interface NodePaletteProps {
+ onNodeAdd: (nodeType: string, nodeData: any) => void;
+ isCollapsed: boolean;
+ onToggleCollapse: () => void;
+ mcpNodeConfigs: MCPNodeConfig[];
+ agentConfigs: AgentMetadata[];
+}
+
+const IntegratedNodePalette: React.FC<NodePaletteProps> = ({
+ onNodeAdd,
+ isCollapsed,
+ onToggleCollapse,
+ mcpNodeConfigs,
+ agentConfigs,
+}) => {
+ const [searchQuery, setSearchQuery] = useState('');
+ const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set(['Input', 'Processing', 'Output']));
+
+ // Get all registered nodes from NodeRegistry
+ const registryNodes = useMemo(() => {
+ try {
+ return NodeRegistry.getAllNodes();
+ } catch (e) {
+ console.warn('[NodePalette] NodeRegistry not initialized yet');
+ return [];
+ }
+ }, []);
+
+ // Combine builtin nodes with registry nodes
+ const allNodes = useMemo(() => {
+ const nodes: Array<{
+ id: string;
+ type: string;
+ label: string;
+ category: string;
+ color: string;
+ description: string;
+ source: 'builtin' | 'registry' | 'mcp' | 'agent';
+ data?: any;
+ }> = [];
+
+ // Add builtin UI nodes
+ BUILTIN_NODE_CONFIGS.forEach(config => {
+ nodes.push({
+ id: config.type,
+ type: config.type,
+ label: config.label,
+ category: config.category,
+ color: config.color,
+ description: config.description,
+ source: 'builtin',
+ data: config,
+ });
+ });
+
+ // Add registry nodes
+ registryNodes.forEach((node: INodeTypeDescription) => {
+ const category = node.group?.[0] || 'Core';
+ const categoryConfig = CATEGORY_CONFIG[category] || CATEGORY_CONFIG['Core'];
+ nodes.push({
+ id: node.name,
+ type: 'registry-node',
+ label: node.displayName,
+ category,
+ color: node.defaults?.color || categoryConfig.color,
+ description: node.description || '',
+ source: 'registry',
+ data: node,
+ });
+ });
+
+ // Add MCP tool nodes
+ mcpNodeConfigs.forEach(config => {
+ nodes.push({
+ id: config.id,
+ type: 'mcp-tool',
+ label: config.label,
+ category: 'MCP Tools',
+ color: '#ea580c',
+ description: `MCP: ${config.serverId}`,
+ source: 'mcp',
+ data: config,
+ });
+ });
+
+ // Add Python agent nodes
+ agentConfigs.forEach(agent => {
+ nodes.push({
+ id: agent.id,
+ type: 'python-agent',
+ label: agent.name,
+ category: 'Python Agents',
+ color: agent.color || '#22c55e',
+ description: agent.description,
+ source: 'agent',
+ data: agent,
+ });
+ });
+
+ return nodes;
+ }, [registryNodes, mcpNodeConfigs, agentConfigs]);
+
+ // Group nodes by category
+ const nodesByCategory = useMemo(() => {
+ const grouped = new Map<string, typeof allNodes>();
+
+ allNodes.forEach(node => {
+ if (!grouped.has(node.category)) {
+ grouped.set(node.category, []);
+ }
+ grouped.get(node.category)!.push(node);
+ });
+
+ // Sort each category alphabetically
+ grouped.forEach((nodes, _) => {
+ nodes.sort((a, b) => a.label.localeCompare(b.label));
+ });
+
+ return grouped;
+ }, [allNodes]);
+
+ // Filter by search
+ const filteredCategories = useMemo(() => {
+ if (!searchQuery.trim()) return nodesByCategory;
+
+ const query = searchQuery.toLowerCase();
+ const filtered = new Map<string, typeof allNodes>();
+
+ nodesByCategory.forEach((nodes, category) => {
+ const matching = nodes.filter(
+ n => n.label.toLowerCase().includes(query) ||
+ n.description.toLowerCase().includes(query) ||
+ n.id.toLowerCase().includes(query)
+ );
+ if (matching.length > 0) {
+ filtered.set(category, matching);
+ }
+ });
+
+ return filtered;
+ }, [nodesByCategory, searchQuery]);
+
+ const toggleCategory = (category: string) => {
+ const newExpanded = new Set(expandedCategories);
+ if (newExpanded.has(category)) {
+ newExpanded.delete(category);
+ } else {
+ newExpanded.add(category);
+ }
+ setExpandedCategories(newExpanded);
+ };
+
+ if (isCollapsed) {
+ return (
+ <div style={{
+ width: '40px',
+ backgroundColor: '#0a0a0a',
+ borderRight: '1px solid #2d2d2d',
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ paddingTop: '8px',
+ }}>
+ <button
+ onClick={onToggleCollapse}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: '#a3a3a3',
+ cursor: 'pointer',
+ padding: '8px',
+ }}
+ title="Expand palette"
+ >
+ <ChevronRight size={16} />
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ width: '280px',
+ backgroundColor: '#0a0a0a',
+ borderRight: '1px solid #2d2d2d',
+ display: 'flex',
+ flexDirection: 'column',
+ height: '100%',
+ }}>
+ {/* Palette Header */}
+ <div style={{
+ padding: '12px',
+ borderBottom: '1px solid #2d2d2d',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ color: '#ea580c',
+ fontSize: '12px',
+ fontWeight: 'bold',
+ }}>
+ <Database size={14} />
+ NODE PALETTE
+ </div>
+ <button
+ onClick={onToggleCollapse}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: '#6b7280',
+ cursor: 'pointer',
+ padding: '4px',
+ }}
+ title="Collapse palette"
+ >
+ <ChevronLeft size={14} />
+ </button>
+ </div>
+
+ {/* Search */}
+ <div style={{ padding: '8px 12px', borderBottom: '1px solid #2d2d2d' }}>
+ <div style={{ position: 'relative' }}>
+ <Search size={14} style={{
+ position: 'absolute',
+ left: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ color: '#6b7280',
+ }} />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Search nodes..."
+ style={{
+ width: '100%',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #2d2d2d',
+ borderRadius: '4px',
+ padding: '8px 8px 8px 32px',
+ color: '#fff',
+ fontSize: '11px',
+ outline: 'none',
+ }}
+ />
+ </div>
+ <div style={{ color: '#6b7280', fontSize: '10px', marginTop: '6px' }}>
+ {allNodes.length} nodes available
+ </div>
+ </div>
+
+ {/* Node Categories */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {Array.from(filteredCategories.entries()).map(([category, categoryNodes]) => {
+ const catConfig = CATEGORY_CONFIG[category] || { icon: <Workflow size={14} />, color: '#6b7280' };
+ const isExpanded = expandedCategories.has(category);
+
+ return (
+ <div key={category} style={{ borderBottom: '1px solid #1a1a1a' }}>
+ {/* Category Header */}
+ <button
+ onClick={() => toggleCategory(category)}
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: 'transparent',
+ border: 'none',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ cursor: 'pointer',
+ color: '#d4d4d4',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: catConfig.color }}>{catConfig.icon}</span>
+ <span style={{ fontSize: '11px', fontWeight: 'bold' }}>{category}</span>
+ <span style={{ fontSize: '10px', color: '#6b7280' }}>({categoryNodes.length})</span>
+ </div>
+ {isExpanded ? <ChevronRight size={12} style={{ transform: 'rotate(90deg)' }} /> : <ChevronRight size={12} />}
+ </button>
+
+ {/* Category Nodes */}
+ {isExpanded && (
+ <div style={{ padding: '4px 8px 8px' }}>
+ {categoryNodes.map(node => (
+ <div
+ key={node.id}
+ onClick={() => onNodeAdd(node.type, node)}
+ draggable
+ onDragStart={(e) => {
+ e.dataTransfer.setData('application/reactflow', JSON.stringify(node));
+ e.dataTransfer.effectAllowed = 'move';
+ }}
+ style={{
+ backgroundColor: '#1a1a1a',
+ border: `1px solid ${node.color}30`,
+ borderRadius: '4px',
+ padding: '8px 10px',
+ marginBottom: '4px',
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = `${node.color}15`;
+ e.currentTarget.style.borderColor = `${node.color}60`;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = '#1a1a1a';
+ e.currentTarget.style.borderColor = `${node.color}30`;
+ }}
+ >
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ }}>
+ <div style={{
+ width: '24px',
+ height: '24px',
+ borderRadius: '4px',
+ backgroundColor: `${node.color}20`,
+ border: `1px solid ${node.color}40`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: node.color,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ }}>
+ {node.label[0]}
+ </div>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{
+ color: node.color,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ }}>
+ {node.label}
+ </div>
+ {node.description && (
+ <div style={{
+ color: '#6b7280',
+ fontSize: '9px',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ }}>
+ {node.description.substring(0, 40)}{node.description.length > 40 ? '...' : ''}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ })}
+
+ {filteredCategories.size === 0 && (
+ <div style={{
+ padding: '24px',
+ textAlign: 'center',
+ color: '#6b7280',
+ }}>
+ <Search size={24} style={{ margin: '0 auto 8px', opacity: 0.5 }} />
+ <div style={{ fontSize: '11px' }}>No nodes found</div>
+ </div>
+ )}
+ </div>
+
+ {/* Palette Footer */}
+ <div style={{
+ padding: '8px 12px',
+ borderTop: '1px solid #2d2d2d',
+ backgroundColor: '#0a0a0a',
+ }}>
+ <div style={{ color: '#6b7280', fontSize: '9px', textAlign: 'center' }}>
+ Drag nodes to canvas or click to add
+ </div>
+ </div>
+ </div>
+ );
+};
+
export default function NodeEditorTab() {
const { t } = useTranslation('nodeEditor');
const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
@@ -263,7 +729,6 @@ export default function NodeEditorTab() {
const saved = await getSetting('nodeEditorWorkflow');
if (saved) {
const workflow = JSON.parse(saved);
- console.log('[NodeEditor] Loaded saved workflow:', workflow.nodes.length, 'nodes');
return workflow;
}
} catch (error) {
@@ -291,7 +756,6 @@ export default function NodeEditorTab() {
try {
const workflow = { nodes, edges };
await saveSetting('nodeEditorWorkflow', JSON.stringify(workflow), 'node_editor');
- console.log('[NodeEditor] Auto-saved workflow:', nodes.length, 'nodes,', edges.length, 'edges');
} catch (error) {
console.error('[NodeEditor] Failed to save workflow:', error);
}
@@ -308,7 +772,6 @@ export default function NodeEditorTab() {
try {
const configs = await generateMCPNodeConfigs();
setMcpNodeConfigs(configs);
- console.log('[NodeEditor] Loaded MCP node configs:', configs.length);
} catch (error) {
console.error('[NodeEditor] Failed to load MCP configs:', error);
}
@@ -318,7 +781,6 @@ export default function NodeEditorTab() {
try {
const agents = await pythonAgentService.getAvailableAgents();
setAgentConfigs(agents);
- console.log('[NodeEditor] Loaded Python agents:', agents.length);
} catch (error) {
console.error('[NodeEditor] Failed to load agents:', error);
}
@@ -331,6 +793,10 @@ export default function NodeEditorTab() {
const [selectedNodes, setSelectedNodes] = useState<string[]>([]);
const [showNodeMenu, setShowNodeMenu] = useState(false);
const [activeView, setActiveView] = useState<'editor' | 'workflows'>('editor');
+ const [isPaletteCollapsed, setIsPaletteCollapsed] = useState(false);
+ const [showConfigPanel, setShowConfigPanel] = useState(false);
+ const [selectedNodeForConfig, setSelectedNodeForConfig] = useState<Node | null>(null);
+ const reactFlowWrapper = useRef<HTMLDivElement>(null);
const [showDeployDialog, setShowDeployDialog] = useState(false);
const [workflowName, setWorkflowName] = useState('');
const [workflowDescription, setWorkflowDescription] = useState('');
@@ -349,7 +815,10 @@ export default function NodeEditorTab() {
'results-display': ResultsDisplayNode,
'agent-mediator': AgentMediatorNode,
'data-source': DataSourceNode,
- 'technical-indicator': TechnicalIndicatorNode
+ 'technical-indicator': TechnicalIndicatorNode,
+ 'backtest': BacktestNode,
+ 'optimization': OptimizationNode,
+ 'system': SystemNode,
}), []);
// Handle label change
@@ -384,6 +853,106 @@ export default function NodeEditorTab() {
[setEdges]
);
+ // Handle node from palette (click or drag)
+ const handlePaletteNodeAdd = useCallback((nodeType: string, nodeData: any) => {
+
+ // Determine the actual node type for ReactFlow
+ let reactFlowType = 'custom';
+ if (nodeData.source === 'builtin') {
+ reactFlowType = nodeData.data?.type || nodeType;
+ } else if (nodeData.source === 'registry') {
+ reactFlowType = 'custom'; // Registry nodes use custom component for now
+ } else if (nodeData.source === 'mcp') {
+ reactFlowType = 'mcp-tool';
+ } else if (nodeData.source === 'agent') {
+ reactFlowType = 'python-agent';
+ }
+
+ // Build the node based on type
+ if (nodeData.source === 'builtin') {
+ // Use existing addNode logic for builtin types
+ addNode(nodeData.data);
+ } else if (nodeData.source === 'mcp') {
+ addNode(nodeData.data);
+ } else if (nodeData.source === 'agent') {
+ addNode({ ...nodeData.data, type: 'python-agent' });
+ } else if (nodeData.source === 'registry') {
+ // Create a new node from registry node description
+ const registryNode = nodeData.data as INodeTypeDescription;
+ const newNode: Node = {
+ id: `node_${Date.now()}`,
+ type: 'custom',
+ position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
+ data: {
+ label: registryNode.displayName,
+ nodeTypeName: registryNode.name,
+ color: nodeData.color || '#6b7280',
+ hasInput: (registryNode.inputs?.length || 0) > 0 || registryNode.name !== 'manualTrigger',
+ hasOutput: (registryNode.outputs?.length || 0) > 0,
+ status: 'idle',
+ parameters: {},
+ registryData: registryNode,
+ onLabelChange: handleLabelChange,
+ },
+ };
+ setNodes((nds) => [...nds, newNode]);
+ }
+
+ setShowNodeMenu(false);
+ }, [setNodes]);
+
+ // Handle drop from palette
+ const onDrop = useCallback(
+ (event: React.DragEvent) => {
+ event.preventDefault();
+
+ const data = event.dataTransfer.getData('application/reactflow');
+ if (!data) return;
+
+ const nodeData = JSON.parse(data);
+
+ // Get position relative to the canvas
+ const reactFlowBounds = reactFlowWrapper.current?.getBoundingClientRect();
+ if (!reactFlowBounds) return;
+
+ const position = {
+ x: event.clientX - reactFlowBounds.left - 150,
+ y: event.clientY - reactFlowBounds.top - 25,
+ };
+
+ // Add node at drop position
+ if (nodeData.source === 'registry') {
+ const registryNode = nodeData.data as INodeTypeDescription;
+ const newNode: Node = {
+ id: `node_${Date.now()}`,
+ type: 'custom',
+ position,
+ data: {
+ label: registryNode.displayName,
+ nodeTypeName: registryNode.name,
+ color: nodeData.color || '#6b7280',
+ hasInput: (registryNode.inputs?.length || 0) > 0 || registryNode.name !== 'manualTrigger',
+ hasOutput: (registryNode.outputs?.length || 0) > 0,
+ status: 'idle',
+ parameters: {},
+ registryData: registryNode,
+ onLabelChange: handleLabelChange,
+ },
+ };
+ setNodes((nds) => [...nds, newNode]);
+ } else {
+ // Use existing logic for other node types
+ handlePaletteNodeAdd(nodeData.type, nodeData);
+ }
+ },
+ [setNodes, handlePaletteNodeAdd]
+ );
+
+ const onDragOver = useCallback((event: React.DragEvent) => {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'move';
+ }, []);
+
// Add new node (handles regular nodes, MCP tool nodes, Python agent nodes, data source, technical indicators, and agent mediator)
const addNode = (config: any) => {
const isMCPNode = config.type === 'mcp-tool';
@@ -412,7 +981,6 @@ export default function NodeEditorTab() {
selectedLLM: 'active', // Default to active provider
status: 'idle',
onExecute: async (nodeId: string) => {
- console.log('[NodeEditor] Executing single Python agent node:', config.id);
// Execute just this node
try {
setNodes((nds) =>
@@ -453,8 +1021,8 @@ export default function NodeEditorTab() {
);
}
},
- onParameterChange: (params: Record<string, any>) => {
- console.log('[NodeEditor] Agent parameters changed:', params);
+ onParameterChange: (_params: Record<string, any>) => {
+ // Parameters updated
},
onLLMChange: (provider: string) => {
setNodes((nds) =>
@@ -476,11 +1044,11 @@ export default function NodeEditorTab() {
toolName: config.toolName,
label: config.label,
parameters: {},
- onParameterChange: (params: Record<string, any>) => {
- console.log('[NodeEditor] MCP tool parameters changed:', params);
+ onParameterChange: (_params: Record<string, any>) => {
+ // Parameters updated
},
- onExecute: (result: any) => {
- console.log('[NodeEditor] MCP tool executed with result:', result);
+ onExecute: (_result: any) => {
+ // Tool executed
},
} : (isResultsDisplay ? {
label: config.label,
@@ -494,8 +1062,7 @@ export default function NodeEditorTab() {
result: undefined,
error: undefined,
inputData: undefined,
- onExecute: (nodeId: string) => {
- console.log('[NodeEditor] Agent mediator execute clicked:', nodeId);
+ onExecute: (_nodeId: string) => {
// Workflow execution will handle this
},
onConfigChange: (newConfig: any) => {
@@ -552,7 +1119,6 @@ export default function NodeEditorTab() {
);
},
onExecute: async () => {
- console.log('[NodeEditor] Data source node execute clicked');
// Will be handled by workflow execution
},
} : (isTechnicalIndicator ? {
@@ -566,8 +1132,7 @@ export default function NodeEditorTab() {
status: 'idle',
result: undefined,
error: undefined,
- onExecute: (nodeId: string) => {
- console.log('[NodeEditor] Technical indicator node execute clicked:', nodeId);
+ onExecute: (_nodeId: string) => {
// Workflow execution will handle this
},
onParameterChange: (params: Record<string, any>) => {
@@ -646,8 +1211,6 @@ export default function NodeEditorTab() {
try {
const workflow = { nodes, edges };
await saveSetting('nodeEditorWorkflow', JSON.stringify(workflow), 'node_editor');
- console.log('[NodeEditor] Manually saved workflow:', nodes.length, 'nodes,', edges.length, 'edges');
- // Could add visual feedback here
} catch (error) {
console.error('[NodeEditor] Failed to save workflow:', error);
}
@@ -683,7 +1246,6 @@ export default function NodeEditorTab() {
const workflow = JSON.parse(event.target.result);
setNodes(workflow.nodes || []);
setEdges(workflow.edges || []);
- console.log('[NodeEditor] Imported workflow:', workflow.nodes?.length || 0, 'nodes');
} catch (error) {
console.error('[NodeEditor] Failed to import workflow:', error);
}
@@ -704,7 +1266,6 @@ export default function NodeEditorTab() {
setEditingDraftId(null);
setWorkflowName('');
setWorkflowDescription('');
- console.log('[NodeEditor] Cleared workflow and reset to new mode');
}, [setNodes, setEdges]);
// Deploy workflow
@@ -777,8 +1338,6 @@ export default function NodeEditorTab() {
);
if (result.success) {
- console.log('[NodeEditor] Workflow deployed successfully:', result.workflowId);
-
// Clear the canvas after successful deployment
setNodes([]);
setEdges([]);
@@ -788,8 +1347,6 @@ export default function NodeEditorTab() {
setCurrentWorkflowId(null);
setWorkflowMode('new');
setEditingDraftId(null);
-
- console.log('[NodeEditor] Canvas cleared, ready for new workflow');
} else {
console.error('[NodeEditor] Deployment failed:', result.error);
alert(`Deployment failed: ${result.error}`);
@@ -821,7 +1378,6 @@ export default function NodeEditorTab() {
nodes,
edges
);
- console.log('[NodeEditor] Draft updated:', editingDraftId);
workflowId = editingDraftId;
setEditingDraftId(null);
} else {
@@ -832,7 +1388,6 @@ export default function NodeEditorTab() {
nodes,
edges
);
- console.log('[NodeEditor] Draft saved:', workflowId);
}
setCurrentWorkflowId(workflowId);
setWorkflowMode('draft');
@@ -847,19 +1402,16 @@ export default function NodeEditorTab() {
}, [nodes, edges, workflowName, workflowDescription, editingDraftId]);
// Load workflow from manager (for play button on draft/completed workflows)
- const handleLoadWorkflow = useCallback((loadedNodes: Node[], loadedEdges: Edge[], workflowId: string, workflow: Workflow) => {
+ const handleLoadWorkflow = useCallback((loadedNodes: Node[], loadedEdges: Edge[], workflowId: string, workflow: WorkflowType) => {
setNodes(loadedNodes);
setEdges(loadedEdges);
setCurrentWorkflowId(workflowId);
setWorkflowMode(workflow.status === 'draft' ? 'draft' : 'deployed');
setActiveView('editor');
- console.log('[NodeEditor] Loaded workflow:', loadedNodes.length, 'nodes', 'Mode:', workflow.status);
}, [setNodes, setEdges]);
// View workflow results
- const handleViewResults = useCallback((workflow: Workflow) => {
- console.log('[NodeEditor] Viewing results for workflow:', workflow.id);
-
+ const handleViewResults = useCallback((workflow: WorkflowType) => {
// Ask user if they want to see in modal or navigate to workflow
const choice = window.confirm(
`View results for: ${workflow.name}\n\n` +
@@ -883,8 +1435,7 @@ export default function NodeEditorTab() {
}, [setNodes, setEdges]);
// Edit draft workflow
- const handleEditDraft = useCallback((workflow: Workflow) => {
- console.log('[NodeEditor] Editing draft:', workflow.id);
+ const handleEditDraft = useCallback((workflow: WorkflowType) => {
setNodes(workflow.nodes);
setEdges(workflow.edges);
setWorkflowName(workflow.name);
@@ -999,20 +1550,16 @@ export default function NodeEditorTab() {
try {
setIsExecuting(true);
- console.log('[NodeEditor] Starting workflow execution...');
await nodeExecutionManager.executeWorkflow(
nodes,
edges,
(nodeId, status, result) => {
- console.log(`[NodeEditor] Node ${nodeId} status: ${status}`, result);
// Update node status
setNodes((nds) =>
nds.map((node) => {
if (node.id === nodeId) {
// For results-display nodes, update inputData
if (node.type === 'results-display') {
- console.log('[NodeEditor] Updating results-display node:', nodeId, 'with data:', result);
- console.log('[NodeEditor] Status:', status);
// Force update to trigger re-render
const currentData = node.data as any;
return {
@@ -1040,7 +1587,6 @@ export default function NodeEditorTab() {
);
}
);
- console.log('[NodeEditor] Workflow execution completed');
} catch (error: any) {
console.error('[NodeEditor] Workflow execution failed:', error);
// Don't use alert - just log the error
@@ -1417,7 +1963,7 @@ export default function NodeEditorTab() {
>
{category}
</div>
- {NODE_CONFIGS.filter((t) => t.category === category).map((config) => (
+ {BUILTIN_NODE_CONFIGS.filter((t) => t.category === category).map((config) => (
<button
key={config.type}
onClick={() => addNode(config)}
@@ -1511,79 +2057,28 @@ export default function NodeEditorTab() {
</div>
)}
- {/* Python Agents Section */}
- {agentConfigs.length > 0 && (
- <div style={{ marginBottom: '12px' }}>
- <div
- style={{
- color: '#22c55e',
- fontSize: '10px',
- marginBottom: '6px',
- textTransform: 'uppercase',
- letterSpacing: '0.5px',
- fontWeight: 'bold',
- }}
- >
- 🤖 PYTHON AGENTS ({agentConfigs.length})
- </div>
- {['trader', 'hedge-fund', 'economic', 'geopolitics'].map((category) => {
- const categoryAgents = agentConfigs.filter(a => a.category === category);
- if (categoryAgents.length === 0) return null;
-
- return (
- <div key={category} style={{ marginBottom: '8px' }}>
- <div style={{ color: '#737373', fontSize: '9px', marginBottom: '4px', paddingLeft: '4px' }}>
- {category.toUpperCase()}
- </div>
- {categoryAgents.map((agent) => (
- <button
- key={agent.id}
- onClick={() => addNode({ ...agent, type: 'python-agent' })}
- style={{
- backgroundColor: 'colors.panel',
- color: agent.color,
- border: `1px solid ${agent.color}40`,
- padding: '8px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- width: '100%',
- marginBottom: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = `${agent.color}20`;
- e.currentTarget.style.borderColor = agent.color;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'colors.panel';
- e.currentTarget.style.borderColor = `${agent.color}40`;
- }}
- >
- <span style={{ fontSize: '14px' }}>{agent.icon}</span>
- <div style={{ flex: 1, textAlign: 'left' }}>
- <div>{agent.name}</div>
- <div style={{ fontSize: '9px', color: '#737373' }}>
- {agent.description.substring(0, 40)}...
- </div>
- </div>
- </button>
- ))}
- </div>
- );
- })}
- </div>
- )}
</div>
)}
{/* Main Content - Conditional Rendering */}
{activeView === 'editor' ? (
- <>
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Sidebar - Node Palette */}
+ <IntegratedNodePalette
+ onNodeAdd={handlePaletteNodeAdd}
+ isCollapsed={isPaletteCollapsed}
+ onToggleCollapse={() => setIsPaletteCollapsed(!isPaletteCollapsed)}
+ mcpNodeConfigs={mcpNodeConfigs}
+ agentConfigs={agentConfigs}
+ />
+
{/* React Flow Canvas */}
- <div style={{ flex: 1, position: 'relative' }}>
+ <div
+ ref={reactFlowWrapper}
+ style={{ flex: 1, position: 'relative' }}
+ onDrop={onDrop}
+ onDragOver={onDragOver}
+ >
<ReactFlow
nodes={nodes}
edges={edges}
@@ -1593,7 +2088,7 @@ export default function NodeEditorTab() {
onSelectionChange={onSelectionChange}
nodeTypes={nodeTypes}
fitView
- style={{ background: 'colors.panel' }}
+ style={{ background: '#0a0a0a' }}
defaultEdgeOptions={{
animated: true,
style: { stroke: '#ea580c', strokeWidth: 2 },
@@ -1603,7 +2098,7 @@ export default function NodeEditorTab() {
color="#2d2d2d"
gap={20}
size={1}
- style={{ backgroundColor: 'colors.panel' }}
+ style={{ backgroundColor: '#0a0a0a' }}
/>
<Controls
style={{
@@ -1622,8 +2117,591 @@ export default function NodeEditorTab() {
}}
/>
</ReactFlow>
+
+ {/* Empty State Overlay */}
+ {nodes.length === 0 && (
+ <div style={{
+ position: 'absolute',
+ top: '50%',
+ left: '50%',
+ transform: 'translate(-50%, -50%)',
+ textAlign: 'center',
+ color: '#6b7280',
+ pointerEvents: 'none',
+ }}>
+ <Workflow size={48} style={{ margin: '0 auto 16px', opacity: 0.3 }} />
+ <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ No nodes yet
+ </div>
+ <div style={{ fontSize: '12px', opacity: 0.7 }}>
+ Drag nodes from the palette or click ADD NODE to get started
+ </div>
+ </div>
+ )}
</div>
- </>
+
+ {/* Right Sidebar - Config Panel (Bloomberg Style) */}
+ {selectedNodes.length === 1 && (() => {
+ const selectedNode = nodes.find(n => n.id === selectedNodes[0]);
+ if (!selectedNode) return null;
+
+ // Get registry node type if this is a registry node
+ const registryData = selectedNode.data.registryData;
+ const nodeProperties: INodeProperties[] = registryData?.properties || [];
+
+ // Handler for parameter changes
+ const handleParameterChange = (paramName: string, value: NodeParameterValue) => {
+ setNodes((nds) =>
+ nds.map((node) => {
+ if (node.id === selectedNode.id) {
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ parameters: {
+ ...(node.data.parameters || {}),
+ [paramName]: value,
+ },
+ },
+ };
+ }
+ return node;
+ })
+ );
+ };
+
+ const nodeColor = selectedNode.data.color || '#FF8800';
+
+ return (
+ <div style={{
+ width: '300px',
+ backgroundColor: '#000000',
+ borderLeft: '2px solid #FF8800',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}>
+ {/* Panel Header - Bloomberg Style */}
+ <div style={{
+ backgroundColor: '#1A1A1A',
+ borderBottom: '1px solid #2A2A2A',
+ padding: '8px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Settings2 size={14} style={{ color: '#FF8800', filter: 'drop-shadow(0 0 4px #FF8800)' }} />
+ <span style={{
+ color: '#FF8800',
+ fontSize: '11px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ }}>
+ NODE CONFIG
+ </span>
+ </div>
+ <button
+ onClick={() => setSelectedNodes([])}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: '#787878',
+ cursor: 'pointer',
+ padding: '2px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}
+ >
+ <X size={14} />
+ </button>
+ </div>
+
+ {/* Node Type Badge */}
+ <div style={{
+ backgroundColor: '#0F0F0F',
+ padding: '10px 12px',
+ borderBottom: '1px solid #2A2A2A',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ }}>
+ <div style={{
+ width: '28px',
+ height: '28px',
+ backgroundColor: `${nodeColor}20`,
+ border: `1px solid ${nodeColor}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: '12px',
+ fontWeight: 700,
+ color: nodeColor,
+ }}>
+ {(selectedNode.data.label || selectedNode.type || 'N')[0].toUpperCase()}
+ </div>
+ <div>
+ <div style={{ color: '#FFFFFF', fontSize: '11px', fontWeight: 600 }}>
+ {selectedNode.data.label || selectedNode.type}
+ </div>
+ <div style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>
+ {selectedNode.type}
+ </div>
+ </div>
+ </div>
+
+ {/* Scrollable Content */}
+ <div style={{ flex: 1, overflow: 'auto', backgroundColor: '#000000' }}>
+ {/* Label Section */}
+ <div style={{ padding: '12px', borderBottom: '1px solid #2A2A2A' }}>
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ color: '#FF8800',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ <span>LABEL</span>
+ <span style={{ color: '#4A4A4A', fontSize: '8px', fontWeight: 400 }}>REQUIRED</span>
+ </label>
+ <div style={{
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'stretch',
+ }}>
+ <div style={{
+ backgroundColor: '#1A1A1A',
+ borderTop: '1px solid #2A2A2A',
+ borderLeft: '1px solid #2A2A2A',
+ borderBottom: '1px solid #2A2A2A',
+ padding: '0 8px',
+ display: 'flex',
+ alignItems: 'center',
+ color: '#FF8800',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}>
+ <Edit3 size={10} />
+ </div>
+ <input
+ type="text"
+ value={selectedNode.data.label || ''}
+ onChange={(e) => handleLabelChange(selectedNode.id, e.target.value)}
+ placeholder="Enter node label..."
+ style={{
+ flex: 1,
+ backgroundColor: '#0A0A0A',
+ border: '1px solid #2A2A2A',
+ borderLeft: 'none',
+ padding: '10px 12px',
+ color: '#FFFFFF',
+ fontSize: '11px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ outline: 'none',
+ transition: 'all 0.15s ease',
+ }}
+ onFocus={(e) => {
+ e.currentTarget.style.borderColor = '#FF8800';
+ e.currentTarget.style.backgroundColor = '#0F0F0F';
+ e.currentTarget.style.boxShadow = '0 0 8px #FF880030';
+ const iconDiv = e.currentTarget.previousElementSibling as HTMLElement;
+ if (iconDiv) iconDiv.style.borderColor = '#FF8800';
+ }}
+ onBlur={(e) => {
+ e.currentTarget.style.borderColor = '#2A2A2A';
+ e.currentTarget.style.backgroundColor = '#0A0A0A';
+ e.currentTarget.style.boxShadow = 'none';
+ const iconDiv = e.currentTarget.previousElementSibling as HTMLElement;
+ if (iconDiv) iconDiv.style.borderColor = '#2A2A2A';
+ }}
+ />
+ </div>
+ <div style={{
+ marginTop: '4px',
+ fontSize: '8px',
+ color: '#4A4A4A',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}>
+ Display name for this node in the workflow
+ </div>
+ </div>
+
+ {/* Registry Node Parameters */}
+ {nodeProperties.length > 0 && (
+ <div style={{
+ padding: '14px',
+ borderBottom: '1px solid #3A3A3A',
+ backgroundColor: '#111111',
+ }}>
+ {/* Parameters Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '16px',
+ paddingBottom: '10px',
+ borderBottom: '1px solid #2A2A2A',
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ }}>
+ <div style={{
+ width: '4px',
+ height: '18px',
+ backgroundColor: '#FF8800',
+ }} />
+ <span style={{
+ color: '#FF8800',
+ fontSize: '13px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '1.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}>
+ PARAMETERS
+ </span>
+ </div>
+ <div style={{
+ backgroundColor: '#FF880030',
+ border: '1px solid #FF8800',
+ padding: '4px 10px',
+ fontSize: '12px',
+ fontWeight: 700,
+ color: '#FF8800',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}>
+ {nodeProperties.length}
+ </div>
+ </div>
+
+ {/* Parameters List */}
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '14px',
+ }}>
+ {nodeProperties.map((param, index) => (
+ <div
+ key={param.name}
+ style={{
+ padding: '14px',
+ backgroundColor: '#1A1A1A',
+ border: '1px solid #333333',
+ position: 'relative',
+ }}
+ >
+ {/* Parameter Index Badge */}
+ <div style={{
+ position: 'absolute',
+ top: '-1px',
+ left: '-1px',
+ backgroundColor: '#2A2A2A',
+ color: '#AAAAAA',
+ fontSize: '11px',
+ fontWeight: 700,
+ padding: '4px 8px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ borderRight: '1px solid #444444',
+ borderBottom: '1px solid #444444',
+ }}>
+ {String(index + 1).padStart(2, '0')}
+ </div>
+
+ {/* Required Indicator */}
+ {param.required && (
+ <div style={{
+ position: 'absolute',
+ top: '0',
+ right: '0',
+ width: '0',
+ height: '0',
+ borderStyle: 'solid',
+ borderWidth: '0 16px 16px 0',
+ borderColor: 'transparent #FF3B3B transparent transparent',
+ }} />
+ )}
+
+ <div style={{ paddingTop: '12px' }}>
+ <NodeParameterInput
+ parameter={param}
+ value={selectedNode.data.parameters?.[param.name] ?? param.default}
+ onChange={(value) => handleParameterChange(param.name, value)}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Parameters Footer */}
+ <div style={{
+ marginTop: '14px',
+ paddingTop: '10px',
+ borderTop: '1px solid #2A2A2A',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ }}>
+ <div style={{
+ width: '8px',
+ height: '8px',
+ backgroundColor: '#00D66F',
+ borderRadius: '50%',
+ boxShadow: '0 0 6px #00D66F80',
+ }} />
+ <span style={{
+ color: '#AAAAAA',
+ fontSize: '11px',
+ fontWeight: 600,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ {nodeProperties.filter(p => p.required).length > 0
+ ? `${nodeProperties.filter(p => p.required).length} REQUIRED`
+ : 'ALL OPTIONAL'}
+ </span>
+ </div>
+ </div>
+ )}
+
+ {/* Node Info Section */}
+ <div style={{ padding: '12px', borderBottom: '1px solid #2A2A2A' }}>
+ <div style={{
+ color: '#FF8800',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '10px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ NODE INFO
+ </div>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ {/* Node ID */}
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>ID</span>
+ <code style={{ color: '#FFFFFF', fontSize: '9px' }}>{selectedNode.id}</code>
+ </div>
+
+ {/* Position */}
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>POS</span>
+ <span style={{ color: '#FFFFFF', fontSize: '9px' }}>
+ {Math.round(selectedNode.position.x)}, {Math.round(selectedNode.position.y)}
+ </span>
+ </div>
+
+ {/* Registry Type */}
+ {selectedNode.data.nodeTypeName && (
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>TYPE</span>
+ <span style={{ color: '#FFFFFF', fontSize: '9px' }}>{selectedNode.data.nodeTypeName}</span>
+ </div>
+ )}
+
+ {/* Status */}
+ {selectedNode.data.status && (
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>STATUS</span>
+ <span style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ padding: '2px 6px',
+ backgroundColor: selectedNode.data.status === 'completed' ? '#00D66F20' :
+ selectedNode.data.status === 'error' ? '#FF3B3B20' :
+ selectedNode.data.status === 'running' ? '#0088FF20' : '#78787820',
+ color: selectedNode.data.status === 'completed' ? '#00D66F' :
+ selectedNode.data.status === 'error' ? '#FF3B3B' :
+ selectedNode.data.status === 'running' ? '#0088FF' : '#787878',
+ textTransform: 'uppercase',
+ }}>
+ {selectedNode.data.status}
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Description (for registry nodes) */}
+ {registryData?.description && (
+ <div style={{ padding: '12px', borderBottom: '1px solid #2A2A2A' }}>
+ <div style={{
+ color: '#00E5FF',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}>
+ DESCRIPTION
+ </div>
+ <div style={{ color: '#FFFFFF', fontSize: '10px', lineHeight: '1.5' }}>
+ {registryData.description}
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {selectedNode.data.error && (
+ <div style={{
+ margin: '12px',
+ backgroundColor: '#FF3B3B15',
+ border: '1px solid #FF3B3B',
+ padding: '10px',
+ }}>
+ <div style={{
+ color: '#FF3B3B',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '4px',
+ textTransform: 'uppercase',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}>
+ <AlertCircle size={10} />
+ ERROR
+ </div>
+ <div style={{ color: '#FFFFFF', fontSize: '10px', lineHeight: '1.4' }}>
+ {selectedNode.data.error}
+ </div>
+ </div>
+ )}
+
+ {/* Result Preview (for completed nodes) */}
+ {selectedNode.data.result && selectedNode.data.status === 'completed' && (
+ <div style={{
+ margin: '12px',
+ backgroundColor: '#00D66F15',
+ border: '1px solid #00D66F',
+ padding: '10px',
+ }}>
+ <div style={{
+ color: '#00D66F',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}>
+ OUTPUT PREVIEW
+ </div>
+ <pre style={{
+ color: '#FFFFFF',
+ fontSize: '9px',
+ lineHeight: '1.4',
+ overflow: 'auto',
+ maxHeight: '80px',
+ margin: 0,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}>
+ {typeof selectedNode.data.result === 'string'
+ ? selectedNode.data.result.substring(0, 200)
+ : JSON.stringify(selectedNode.data.result, null, 2).substring(0, 200)}
+ {(typeof selectedNode.data.result === 'string'
+ ? selectedNode.data.result.length
+ : JSON.stringify(selectedNode.data.result).length) > 200 && '...'}
+ </pre>
+ </div>
+ )}
+ </div>
+
+ {/* Panel Footer with Actions - Bloomberg Style */}
+ <div style={{
+ padding: '10px 12px',
+ backgroundColor: '#0F0F0F',
+ borderTop: '1px solid #2A2A2A',
+ display: 'flex',
+ gap: '8px',
+ }}>
+ <button
+ onClick={() => deleteSelectedNodes()}
+ style={{
+ flex: 1,
+ backgroundColor: 'transparent',
+ color: '#FF3B3B',
+ border: '1px solid #FF3B3B',
+ padding: '6px 8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.3px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ transition: 'all 0.15s ease',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#FF3B3B';
+ e.currentTarget.style.color = '#000000';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#FF3B3B';
+ }}
+ >
+ <Trash2 size={10} />
+ DELETE
+ </button>
+ <button
+ onClick={() => {
+ // Duplicate node
+ const newNode = {
+ ...selectedNode,
+ id: `node_${Date.now()}`,
+ position: {
+ x: selectedNode.position.x + 50,
+ y: selectedNode.position.y + 50,
+ },
+ data: { ...selectedNode.data },
+ };
+ setNodes((nds) => [...nds, newNode]);
+ }}
+ style={{
+ flex: 1,
+ backgroundColor: '#FF8800',
+ color: '#000000',
+ border: '1px solid #FF8800',
+ padding: '6px 8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.3px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ transition: 'all 0.15s ease',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#FFA033';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = '#FF8800';
+ }}
+ >
+ <Plus size={10} />
+ DUPLICATE
+ </button>
+ </div>
+ </div>
+ );
+ })()}
+ </div>
) : (
/* Workflow Manager View */
<div style={{ flex: 1, overflow: 'hidden' }}>
diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
index 83d25919c..2ff679691 100644
--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
-import { Save, RefreshCw, Lock, User, Settings as SettingsIcon, Database, Terminal, Bell, Bot, Edit3, Type, Palette, Wifi, WifiOff, Activity, Zap, Link, Globe, Check, Plus, Trash2, ToggleLeft, ToggleRight, Eye, EyeOff, TrendingUp } from 'lucide-react';
+import { Save, RefreshCw, Lock, User, Settings as SettingsIcon, Database, Terminal, Bell, Bot, Edit3, Type, Palette, Wifi, WifiOff, Activity, Zap, Link, Globe, Check, Plus, Trash2, ToggleLeft, ToggleRight, Eye, EyeOff, TrendingUp, Key, X, Clock, Briefcase } from 'lucide-react';
import { sqliteService, type LLMConfig, type LLMGlobalSettings, type LLMModelConfig, PREDEFINED_API_KEYS, type ApiKeys, saveSetting, getSetting } from '@/services/core/sqliteService';
import { ollamaService } from '@/services/chat/ollamaService';
import { useTerminalTheme } from '@/contexts/ThemeContext';
@@ -10,8 +10,8 @@ import { BacktestingProvidersPanel } from '@/components/settings/BacktestingProv
import { LanguageSelector } from '@/components/settings/LanguageSelector';
import { TerminalConfigPanel } from '@/components/settings/TerminalConfigPanel';
import { PolymarketCredentialsPanel } from '@/components/settings/PolymarketCredentialsPanel';
+import { MasterContractManager } from '@/components/tabs/equity-trading/components';
import { useTimezone, TIMEZONE_OPTIONS } from '@/contexts/TimezoneContext';
-import { Clock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { TabFooter } from '@/components/common/TabFooter';
import { useAuth } from '@/contexts/AuthContext';
@@ -21,7 +21,7 @@ export default function SettingsTab() {
const { session } = useAuth();
const { theme, updateTheme, resetTheme, colors, fontSize: themeFontSize, fontFamily: themeFontFamily, fontWeight: themeFontWeight, fontStyle } = useTerminalTheme();
const { defaultTimezone, setDefaultTimezone, options: timezoneOptions } = useTimezone();
- const [activeSection, setActiveSection] = useState<'credentials' | 'polymarket' | 'terminal' | 'terminalConfig' | 'llm' | 'dataConnections' | 'backtesting' | 'language'>('credentials');
+ const [activeSection, setActiveSection] = useState<'credentials' | 'polymarket' | 'terminal' | 'terminalConfig' | 'llm' | 'dataConnections' | 'backtesting' | 'stockSymbols' | 'language'>('credentials');
const [apiKeys, setApiKeys] = useState<ApiKeys>({});
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
@@ -690,6 +690,7 @@ export default function SettingsTab() {
{ id: 'llm', icon: Bot, label: t('sidebar.llm') },
{ id: 'dataConnections', icon: Database, label: t('sidebar.dataSources') },
{ id: 'backtesting', icon: Activity, label: t('sidebar.backtesting') },
+ { id: 'stockSymbols', icon: Briefcase, label: 'Stock Symbols' },
{ id: 'terminalConfig', icon: SettingsIcon, label: t('sidebar.tabLayout') },
{ id: 'terminal', icon: Terminal, label: t('sidebar.appearance') },
{ id: 'language', icon: Globe, label: t('sidebar.language') }
@@ -814,100 +815,167 @@ export default function SettingsTab() {
<PolymarketCredentialsPanel />
)}
- {/* LLM Configuration Section */}
+ {/* LLM Configuration Section - Bloomberg Style */}
{activeSection === 'llm' && (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
- {/* Top Bar */}
+ <div style={{
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '20px'
+ }}>
+ {/* Header */}
<div style={{
- backgroundColor: '#1A1A1A',
borderBottom: `2px solid ${colors.primary}`,
- padding: '6px 12px',
+ padding: '16px 0',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
- boxShadow: `0 2px 8px ${colors.primary}20`
}}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Bot size={16} color={colors.primary} style={{ filter: `drop-shadow(0 0 4px ${colors.primary})` }} />
- <span style={{
- color: colors.primary,
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <Bot size={24} color={colors.primary} />
+ <div>
+ <div style={{
+ color: colors.primary,
+ fontWeight: 700,
+ fontSize: '16px',
+ letterSpacing: '0.5px',
+ }}>
+ LLM CONFIGURATION
+ </div>
+ <div style={{ color: '#888', fontSize: '12px', marginTop: '2px' }}>
+ Configure AI providers, models, and global settings
+ </div>
+ </div>
+ </div>
+ <button
+ onClick={handleSaveLLMConfig}
+ disabled={loading}
+ style={{
+ background: loading ? '#2A2A2A' : colors.primary,
+ color: loading ? '#666' : '#000',
+ border: 'none',
+ padding: '10px 20px',
+ fontSize: '12px',
fontWeight: 700,
- fontSize: '11px',
letterSpacing: '0.5px',
- textShadow: `0 0 10px ${colors.primary}40`
- }}>
- {t('llm.title').toUpperCase()}
- </span>
+ cursor: loading ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}
+ >
+ <Save size={14} />
+ {loading ? 'SAVING...' : 'SAVE ALL SETTINGS'}
+ </button>
+ </div>
+
+ {/* Provider Selection */}
+ <div style={{
+ backgroundColor: '#0F0F0F',
+ border: `1px solid #2A2A2A`,
+ padding: '20px'
+ }}>
+ <div style={{
+ color: colors.primary,
+ fontSize: '13px',
+ fontWeight: 700,
+ marginBottom: '16px',
+ letterSpacing: '0.5px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <Zap size={16} color={colors.primary} />
+ SELECT AI PROVIDER
</div>
- <div style={{ color: colors.text, fontSize: '9px' }}>
- {t('llm.description')}
+ <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
+ {llmConfigs.map(config => (
+ <button
+ key={config.provider}
+ onClick={() => setActiveProvider(config.provider)}
+ style={{
+ padding: '12px 20px',
+ backgroundColor: activeProvider === config.provider ? colors.primary : '#1A1A1A',
+ border: `2px solid ${activeProvider === config.provider ? colors.primary : '#2A2A2A'}`,
+ color: activeProvider === config.provider ? '#000' : '#FFF',
+ cursor: 'pointer',
+ fontSize: '13px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}
+ onMouseEnter={(e) => {
+ if (activeProvider !== config.provider) {
+ e.currentTarget.style.borderColor = colors.primary;
+ e.currentTarget.style.backgroundColor = '#252525';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (activeProvider !== config.provider) {
+ e.currentTarget.style.borderColor = '#2A2A2A';
+ e.currentTarget.style.backgroundColor = '#1A1A1A';
+ }
+ }}
+ >
+ {config.provider === 'fincept' && <span style={{ color: activeProvider === config.provider ? '#000' : colors.success }}>●</span>}
+ {config.provider.toUpperCase()}
+ </button>
+ ))}
</div>
</div>
{/* Main Content Grid */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
- {/* Left Column */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
- {/* Provider Selection */}
- <div style={{
- backgroundColor: '#0F0F0F',
- border: `1px solid #2A2A2A`,
- padding: '12px'
- }}>
- <div style={{
- color: colors.text,
- fontSize: '10px',
- fontWeight: 600,
- marginBottom: '8px',
- letterSpacing: '0.5px'
- }}>
- {t('llm.provider')}
- </div>
- <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
- {llmConfigs.map(config => (
- <button
- key={config.provider}
- onClick={() => setActiveProvider(config.provider)}
- style={{
- padding: '6px 12px',
- backgroundColor: activeProvider === config.provider ? colors.primary : '#0F0F0F',
- border: `1px solid ${activeProvider === config.provider ? colors.primary : '#2A2A2A'}`,
- color: activeProvider === config.provider ? '#000' : colors.text,
- cursor: 'pointer',
- fontSize: '9px',
- fontWeight: 600,
- letterSpacing: '0.5px',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- if (activeProvider !== config.provider) {
- e.currentTarget.style.borderColor = colors.primary;
- }
- }}
- onMouseLeave={(e) => {
- if (activeProvider !== config.provider) {
- e.currentTarget.style.borderColor = '#2A2A2A';
- }
- }}
- >
- {config.provider.toUpperCase()}
- </button>
- ))}
- </div>
- </div>
-
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
+ {/* Left Column - Provider Config */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
{/* Fincept Auto-Configured */}
{getCurrentLLMConfig() && getCurrentLLMConfig()!.provider === 'fincept' && (
<div style={{
- backgroundColor: '#0a3a0a',
- border: `1px solid ${colors.success}`,
- padding: '8px 10px'
+ backgroundColor: '#0a2a0a',
+ border: `2px solid ${colors.success}`,
+ padding: '20px'
}}>
- <div style={{ color: colors.success, fontSize: '9px', fontWeight: 600, marginBottom: '3px' }}>
- [OK] FINCEPT AUTO-CONFIGURED
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ marginBottom: '12px'
+ }}>
+ <Check size={20} color={colors.success} />
+ <span style={{ color: colors.success, fontSize: '14px', fontWeight: 700 }}>
+ FINCEPT LLM - AUTO CONFIGURED
+ </span>
</div>
- <div style={{ color: '#888', fontSize: '8px' }}>
- Key: {session?.api_key?.substring(0, 8)}... • 5 credits/response
+ <div style={{ color: '#AAA', fontSize: '12px', lineHeight: 1.6 }}>
+ <div style={{ marginBottom: '8px' }}>
+ Your Fincept API is automatically configured and ready to use.
+ </div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '16px',
+ padding: '12px',
+ backgroundColor: '#000',
+ border: `1px solid #2A2A2A`
+ }}>
+ <div>
+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>API KEY</div>
+ <div style={{ color: colors.primary, fontSize: '12px', fontFamily: 'monospace' }}>
+ {session?.api_key?.substring(0, 12)}...
+ </div>
+ </div>
+ <div>
+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>COST</div>
+ <div style={{ color: '#FFF', fontSize: '12px' }}>5 credits/response</div>
+ </div>
+ <div>
+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>MODEL</div>
+ <div style={{ color: '#FFF', fontSize: '12px' }}>fincept-llm</div>
+ </div>
+ </div>
</div>
</div>
)}
@@ -917,41 +985,55 @@ export default function SettingsTab() {
<div style={{
backgroundColor: '#0F0F0F',
border: `1px solid #2A2A2A`,
- padding: '12px'
+ padding: '20px'
}}>
<div style={{
color: colors.primary,
- fontSize: '10px',
+ fontSize: '13px',
fontWeight: 700,
- marginBottom: '10px',
+ marginBottom: '20px',
letterSpacing: '0.5px',
- borderBottom: `1px solid #2A2A2A`,
- paddingBottom: '6px'
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ paddingBottom: '12px',
+ borderBottom: `1px solid #2A2A2A`
}}>
- {getCurrentLLMConfig()!.provider.toUpperCase()} CONFIG
+ <Key size={16} color={colors.primary} />
+ {getCurrentLLMConfig()!.provider.toUpperCase()} CONFIGURATION
</div>
- <div style={{ display: 'grid', gap: '8px' }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
{/* API Key */}
{getCurrentLLMConfig()!.provider !== 'ollama' && (
<div>
- <label style={{ color: colors.text, fontSize: '8px', display: 'block', marginBottom: '3px', fontWeight: 600 }}>
- API KEY *
+ <label style={{
+ color: '#FFF',
+ fontSize: '11px',
+ display: 'block',
+ marginBottom: '8px',
+ fontWeight: 600,
+ letterSpacing: '0.5px'
+ }}>
+ API KEY <span style={{ color: colors.alert }}>*</span>
</label>
<input
type="password"
value={getCurrentLLMConfig()!.api_key || ''}
onChange={(e) => updateLLMConfig(activeProvider, 'api_key', e.target.value)}
- placeholder={`Enter ${activeProvider} API key`}
+ placeholder={`Enter your ${activeProvider} API key`}
style={{
width: '100%',
background: '#000',
border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '9px',
- fontFamily: 'monospace'
+ color: '#FFF',
+ padding: '12px 14px',
+ fontSize: '13px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ outline: 'none'
}}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}
/>
</div>
)}
@@ -959,69 +1041,91 @@ export default function SettingsTab() {
{/* Base URL */}
{(getCurrentLLMConfig()!.provider === 'ollama' || getCurrentLLMConfig()!.provider === 'deepseek' || getCurrentLLMConfig()!.provider === 'openrouter') && (
<div>
- <label style={{ color: colors.text, fontSize: '8px', display: 'block', marginBottom: '3px', fontWeight: 600 }}>
+ <label style={{
+ color: '#FFF',
+ fontSize: '11px',
+ display: 'block',
+ marginBottom: '8px',
+ fontWeight: 600,
+ letterSpacing: '0.5px'
+ }}>
BASE URL
</label>
<input
type="text"
value={getCurrentLLMConfig()!.base_url || ''}
onChange={(e) => updateLLMConfig(activeProvider, 'base_url', e.target.value)}
- placeholder={getCurrentLLMConfig()!.provider === 'ollama' ? 'http://localhost:11434' : 'Base URL'}
+ placeholder={getCurrentLLMConfig()!.provider === 'ollama' ? 'http://localhost:11434' : 'https://api.example.com'}
style={{
width: '100%',
background: '#000',
border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '9px',
- fontFamily: 'monospace'
+ color: '#FFF',
+ padding: '12px 14px',
+ fontSize: '13px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ outline: 'none'
}}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}
/>
</div>
)}
{/* Model */}
<div>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '3px' }}>
- <label style={{ color: colors.text, fontSize: '8px', fontWeight: 600 }}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '8px'
+ }}>
+ <label style={{
+ color: '#FFF',
+ fontSize: '11px',
+ fontWeight: 600,
+ letterSpacing: '0.5px'
+ }}>
MODEL
</label>
{getCurrentLLMConfig()!.provider === 'ollama' && (
- <div style={{ display: 'flex', gap: '4px' }}>
+ <div style={{ display: 'flex', gap: '8px' }}>
<button
onClick={fetchOllamaModels}
disabled={ollamaLoading}
style={{
- background: '#0F0F0F',
+ background: '#1A1A1A',
border: `1px solid #2A2A2A`,
color: colors.primary,
- padding: '2px 6px',
- fontSize: '8px',
+ padding: '6px 12px',
+ fontSize: '11px',
cursor: ollamaLoading ? 'not-allowed' : 'pointer',
display: 'flex',
alignItems: 'center',
- gap: '3px'
+ gap: '6px',
+ fontWeight: 600
}}
>
- <RefreshCw size={8} />
- {ollamaLoading ? 'LOAD' : 'REFR'}
+ <RefreshCw size={12} className={ollamaLoading ? 'animate-spin' : ''} />
+ {ollamaLoading ? 'LOADING...' : 'REFRESH MODELS'}
</button>
<button
onClick={() => setUseManualEntry(!useManualEntry)}
style={{
- background: useManualEntry ? colors.primary : '#0F0F0F',
+ background: useManualEntry ? colors.primary : '#1A1A1A',
border: `1px solid ${useManualEntry ? colors.primary : '#2A2A2A'}`,
- color: useManualEntry ? '#000' : colors.text,
- padding: '2px 6px',
- fontSize: '8px',
+ color: useManualEntry ? '#000' : '#FFF',
+ padding: '6px 12px',
+ fontSize: '11px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
- gap: '3px'
+ gap: '6px',
+ fontWeight: 600
}}
>
- <Edit3 size={8} />
- {useManualEntry ? 'DROP' : 'MAN'}
+ <Edit3 size={12} />
+ {useManualEntry ? 'USE DROPDOWN' : 'MANUAL ENTRY'}
</button>
</div>
)}
@@ -1037,33 +1141,41 @@ export default function SettingsTab() {
width: '100%',
background: '#000',
border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '9px',
+ color: '#FFF',
+ padding: '12px 14px',
+ fontSize: '13px',
cursor: ollamaLoading || ollamaModels.length === 0 ? 'not-allowed' : 'pointer'
}}
>
- {ollamaModels.length === 0 && !ollamaLoading && <option value="">No models found</option>}
- {ollamaLoading && <option value="">Loading...</option>}
+ {ollamaModels.length === 0 && !ollamaLoading && <option value="">No models found - Click REFRESH</option>}
+ {ollamaLoading && <option value="">Loading models...</option>}
{ollamaModels.map((model) => (
<option key={model} value={model}>{model}</option>
))}
</select>
{ollamaError && (
<div style={{
- marginTop: '3px',
- padding: '3px 5px',
+ marginTop: '8px',
+ padding: '10px 12px',
background: '#3a0a0a',
border: `1px solid ${colors.alert}`,
- fontSize: '8px',
+ fontSize: '12px',
color: colors.alert
}}>
{ollamaError}
</div>
)}
{ollamaModels.length > 0 && (
- <div style={{ marginTop: '3px', fontSize: '8px', color: colors.success }}>
- [OK] {ollamaModels.length} model{ollamaModels.length !== 1 ? 's' : ''}
+ <div style={{
+ marginTop: '8px',
+ fontSize: '12px',
+ color: colors.success,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}>
+ <Check size={14} />
+ {ollamaModels.length} model{ollamaModels.length !== 1 ? 's' : ''} available
</div>
)}
</div>
@@ -1072,15 +1184,18 @@ export default function SettingsTab() {
type="text"
value={getCurrentLLMConfig()!.model}
onChange={(e) => updateLLMConfig(activeProvider, 'model', e.target.value)}
- placeholder="Model name"
+ placeholder="Enter model name (e.g., gpt-4, claude-3-sonnet)"
style={{
width: '100%',
background: '#000',
border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '9px'
+ color: '#FFF',
+ padding: '12px 14px',
+ fontSize: '13px',
+ outline: 'none'
}}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}
/>
)}
</div>
@@ -1088,60 +1203,42 @@ export default function SettingsTab() {
</div>
)}
- {/* Save Button */}
- <button
- onClick={handleSaveLLMConfig}
- disabled={loading}
- style={{
- background: loading ? '#2A2A2A' : colors.primary,
- color: loading ? '#666' : '#000',
- border: 'none',
- padding: '6px 10px',
- fontSize: '9px',
- fontWeight: 700,
- letterSpacing: '0.5px',
- cursor: loading ? 'not-allowed' : 'pointer',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: '5px'
- }}
- >
- <Save size={10} />
- {loading ? 'SAVING...' : 'SAVE CONFIG'}
- </button>
- </div>
-
- {/* Right Column */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
{/* Global Settings */}
<div style={{
backgroundColor: '#0F0F0F',
border: `1px solid #2A2A2A`,
- padding: '12px'
+ padding: '20px'
}}>
<div style={{
- color: colors.text,
- fontSize: '10px',
+ color: colors.primary,
+ fontSize: '13px',
fontWeight: 700,
- marginBottom: '10px',
+ marginBottom: '20px',
letterSpacing: '0.5px',
- borderBottom: `1px solid #2A2A2A`,
- paddingBottom: '6px',
display: 'flex',
alignItems: 'center',
- gap: '6px'
+ gap: '8px',
+ paddingBottom: '12px',
+ borderBottom: `1px solid #2A2A2A`
}}>
- <Zap size={12} color={colors.primary} />
- {t('llm.globalSettings')}
+ <SettingsIcon size={16} color={colors.primary} />
+ GLOBAL SETTINGS
</div>
- <div style={{ display: 'grid', gap: '8px' }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* Temperature */}
<div>
- <label style={{ color: colors.text, fontSize: '8px', display: 'block', marginBottom: '3px', fontWeight: 600 }}>
- {t('llm.temperature')}
+ <label style={{
+ color: '#FFF',
+ fontSize: '11px',
+ display: 'block',
+ marginBottom: '8px',
+ fontWeight: 600,
+ letterSpacing: '0.5px'
+ }}>
+ TEMPERATURE (Creativity)
</label>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<input
type="range"
min="0"
@@ -1149,26 +1246,37 @@ export default function SettingsTab() {
step="0.1"
value={llmGlobalSettings.temperature}
onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, temperature: parseFloat(e.target.value) })}
- style={{ flex: 1, height: '4px', cursor: 'pointer' }}
+ style={{ flex: 1, height: '6px', cursor: 'pointer' }}
/>
<div style={{
- minWidth: '35px',
- padding: '2px 5px',
+ minWidth: '50px',
+ padding: '8px 12px',
background: colors.primary + '20',
border: `1px solid ${colors.primary}`,
color: colors.primary,
- fontSize: '8px',
- fontWeight: 600,
+ fontSize: '13px',
+ fontWeight: 700,
textAlign: 'center'
}}>
{llmGlobalSettings.temperature.toFixed(1)}
</div>
</div>
+ <div style={{ color: '#666', fontSize: '10px', marginTop: '6px' }}>
+ Lower = More focused, Higher = More creative
+ </div>
</div>
+ {/* Max Tokens */}
<div>
- <label style={{ color: colors.text, fontSize: '8px', display: 'block', marginBottom: '3px', fontWeight: 600 }}>
- {t('llm.maxTokens')}
+ <label style={{
+ color: '#FFF',
+ fontSize: '11px',
+ display: 'block',
+ marginBottom: '8px',
+ fontWeight: 600,
+ letterSpacing: '0.5px'
+ }}>
+ MAX TOKENS (Response Length)
</label>
<input
type="number"
@@ -1180,335 +1288,385 @@ export default function SettingsTab() {
width: '100%',
background: '#000',
border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '9px'
+ color: '#FFF',
+ padding: '12px 14px',
+ fontSize: '13px',
+ outline: 'none'
}}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}
/>
</div>
+ {/* System Prompt */}
<div>
- <label style={{ color: colors.text, fontSize: '8px', display: 'block', marginBottom: '3px', fontWeight: 600 }}>
- {t('llm.systemPrompt')}
+ <label style={{
+ color: '#FFF',
+ fontSize: '11px',
+ display: 'block',
+ marginBottom: '8px',
+ fontWeight: 600,
+ letterSpacing: '0.5px'
+ }}>
+ SYSTEM PROMPT (Optional)
</label>
<textarea
value={llmGlobalSettings.system_prompt}
onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, system_prompt: e.target.value })}
- rows={3}
- placeholder="Custom system prompt (optional)"
+ rows={4}
+ placeholder="Custom instructions for the AI assistant..."
style={{
width: '100%',
background: '#000',
border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '8px',
+ color: '#FFF',
+ padding: '12px 14px',
+ fontSize: '12px',
resize: 'vertical',
- fontFamily: 'monospace',
- lineHeight: '1.4'
+ fontFamily: '"IBM Plex Mono", monospace',
+ lineHeight: '1.5',
+ outline: 'none'
}}
+ onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}
/>
</div>
</div>
</div>
+ </div>
- {/* Model Library */}
- <div style={{
- backgroundColor: '#0F0F0F',
- border: `1px solid #2A2A2A`,
- padding: '12px'
- }}>
- <div style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- marginBottom: '10px',
- paddingBottom: '6px',
- borderBottom: `1px solid #2A2A2A`
- }}>
- <div>
- <div style={{ color: colors.text, fontSize: '10px', fontWeight: 700, letterSpacing: '0.5px', marginBottom: '2px' }}>
- {t('llm.modelLibrary')}
- </div>
- <div style={{ color: '#666', fontSize: '8px' }}>
- {t('llm.multiModelConfigs')}
- </div>
- </div>
- <button
- onClick={() => setShowAddModel(!showAddModel)}
- style={{
- background: showAddModel ? '#3a0a0a' : colors.primary,
- color: showAddModel ? colors.alert : '#000',
- border: 'none',
- padding: '3px 8px',
- fontSize: '8px',
- fontWeight: 600,
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '3px'
- }}
- >
- {showAddModel ? <><Trash2 size={8} /> CANCEL</> : <><Plus size={8} /> ADD</>}
- </button>
- </div>
-
- {/* Add Model Form */}
- {showAddModel && (
+ {/* Right Column - Model Library */}
+ <div style={{
+ backgroundColor: '#0F0F0F',
+ border: `1px solid #2A2A2A`,
+ padding: '20px',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Header */}
<div style={{
- background: '#000',
- border: `1px solid #2A2A2A`,
- padding: '10px',
- marginBottom: '10px'
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '20px',
+ paddingBottom: '12px',
+ borderBottom: `1px solid #2A2A2A`
}}>
- <div style={{ color: colors.primary, fontSize: '9px', fontWeight: 600, marginBottom: '8px' }}>
- ADD NEW MODEL
- </div>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '8px' }}>
- <div>
- <label style={{ color: colors.text, fontSize: '8px', display: 'block', marginBottom: '3px', fontWeight: 600 }}>
- PROVIDER
- </label>
- <select
- value={newModelConfig.provider}
- onChange={(e) => setNewModelConfig({ ...newModelConfig, provider: e.target.value })}
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '9px',
- cursor: 'pointer'
- }}
- >
- <option value="openai">OpenAI</option>
- <option value="google">Google (Gemini)</option>
- <option value="anthropic">Anthropic (Claude)</option>
- <option value="deepseek">DeepSeek</option>
- <option value="ollama">Ollama (Local)</option>
- <option value="openrouter">OpenRouter</option>
- <option value="groq">Groq</option>
- </select>
- </div>
- <div>
- <label style={{ color: colors.text, fontSize: '8px', display: 'block', marginBottom: '3px', fontWeight: 600 }}>
- MODEL ID *
- </label>
- <input
- type="text"
- value={newModelConfig.model_id}
- onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}
- placeholder="e.g. gpt-4o-mini"
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '9px'
- }}
- />
- </div>
- </div>
-
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '8px' }}>
- <div>
- <label style={{ color: colors.text, fontSize: '8px', display: 'block', marginBottom: '3px', fontWeight: 600 }}>
- DISPLAY NAME
- </label>
- <input
- type="text"
- value={newModelConfig.display_name}
- onChange={(e) => setNewModelConfig({ ...newModelConfig, display_name: e.target.value })}
- placeholder="e.g. GPT-4o Mini"
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '9px'
- }}
- />
+ <div>
+ <div style={{
+ color: colors.primary,
+ fontSize: '13px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <Bot size={16} color={colors.primary} />
+ MODEL LIBRARY
</div>
- <div>
- <label style={{ color: colors.text, fontSize: '8px', display: 'block', marginBottom: '3px', fontWeight: 600 }}>
- API KEY (Optional)
- </label>
- <input
- type="password"
- value={newModelConfig.api_key}
- onChange={(e) => setNewModelConfig({ ...newModelConfig, api_key: e.target.value })}
- placeholder="Uses provider key if empty"
- style={{
- width: '100%',
- background: '#000',
- border: `1px solid #2A2A2A`,
- color: colors.text,
- padding: '5px 6px',
- fontSize: '9px',
- fontFamily: 'monospace'
- }}
- />
+ <div style={{ color: '#888', fontSize: '11px' }}>
+ Add custom models for different use cases
</div>
</div>
-
<button
- onClick={handleAddModelConfig}
- disabled={loading || !newModelConfig.model_id}
+ onClick={() => setShowAddModel(!showAddModel)}
style={{
- background: loading || !newModelConfig.model_id ? '#2A2A2A' : colors.primary,
- color: loading || !newModelConfig.model_id ? '#666' : '#000',
+ background: showAddModel ? '#3a0a0a' : colors.primary,
+ color: showAddModel ? colors.alert : '#000',
border: 'none',
- padding: '5px 12px',
- fontSize: '9px',
- fontWeight: 600,
- cursor: loading || !newModelConfig.model_id ? 'not-allowed' : 'pointer',
+ padding: '8px 16px',
+ fontSize: '12px',
+ fontWeight: 700,
+ cursor: 'pointer',
display: 'flex',
alignItems: 'center',
- gap: '4px'
+ gap: '6px'
}}
>
- <Plus size={10} />
- ADD MODEL
+ {showAddModel ? <><X size={14} /> CANCEL</> : <><Plus size={14} /> ADD MODEL</>}
</button>
</div>
- )}
- {/* Models List */}
- {modelConfigs.length === 0 ? (
- <div style={{
- padding: '20px',
- textAlign: 'center',
- color: '#666',
- fontSize: '9px',
- border: `1px dashed #2A2A2A`,
- background: '#000'
- }}>
- <Bot size={24} color="#2A2A2A" style={{ marginBottom: '8px' }} />
- <div style={{ marginBottom: '4px', fontWeight: 600 }}>No models configured</div>
- <div style={{ fontSize: '8px' }}>Click "ADD" to configure models</div>
- </div>
- ) : (
- <div style={{ display: 'grid', gap: '6px' }}>
- {modelConfigs.map((model) => (
- <div
- key={model.id}
- style={{
- display: 'grid',
- gridTemplateColumns: 'auto 1fr auto',
- alignItems: 'center',
- gap: '10px',
- padding: '8px',
- background: model.is_enabled ? '#1A1A1A' : '#000',
- border: `1px solid ${model.is_enabled ? '#2A2A2A' : '#1a1a1a'}`
- }}
- >
- <button
- onClick={() => handleToggleModelEnabled(model.id)}
- style={{
- background: 'transparent',
- border: 'none',
- cursor: 'pointer',
- padding: 0
- }}
- >
- {model.is_enabled ? (
- <ToggleRight size={18} color={colors.success} />
- ) : (
- <ToggleLeft size={18} color="#666" />
- )}
- </button>
+ {/* Add Model Form */}
+ {showAddModel && (
+ <div style={{
+ background: '#000',
+ border: `1px solid ${colors.primary}`,
+ padding: '16px',
+ marginBottom: '16px'
+ }}>
+ <div style={{
+ color: colors.primary,
+ fontSize: '12px',
+ fontWeight: 700,
+ marginBottom: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <Plus size={14} />
+ ADD NEW MODEL CONFIGURATION
+ </div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>
<div>
- <div style={{
- fontSize: '10px',
- fontWeight: 600,
- color: model.is_enabled ? colors.text : '#666',
- marginBottom: '3px'
- }}>
- {model.display_name || model.model_id}
- </div>
- <div style={{ fontSize: '8px', color: '#666', display: 'flex', alignItems: 'center', gap: '6px' }}>
- <span style={{
- padding: '1px 4px',
- background: colors.primary + '20',
- border: `1px solid ${colors.primary}`,
- color: colors.primary,
- fontWeight: 600
- }}>
- {model.provider.toUpperCase()}
- </span>
- <span>{model.model_id}</span>
- {model.api_key && (
- <span style={{
- padding: '1px 4px',
- background: colors.success + '20',
- border: `1px solid ${colors.success}`,
- color: colors.success,
- fontWeight: 600
- }}>
- KEY
- </span>
- )}
- </div>
- </div>
- <div style={{ display: 'flex', gap: '4px' }}>
- {model.api_key && (
- <button
- onClick={() => setShowApiKeys(prev => ({ ...prev, [model.id]: !prev[model.id] }))}
- style={{
- background: '#0F0F0F',
- border: `1px solid #2A2A2A`,
- color: '#666',
- padding: '4px',
- cursor: 'pointer'
- }}
- >
- {showApiKeys[model.id] ? <EyeOff size={10} /> : <Eye size={10} />}
- </button>
- )}
- <button
- onClick={() => handleDeleteModelConfig(model.id)}
+ <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>
+ PROVIDER
+ </label>
+ <select
+ value={newModelConfig.provider}
+ onChange={(e) => setNewModelConfig({ ...newModelConfig, provider: e.target.value })}
style={{
- background: '#0F0F0F',
+ width: '100%',
+ background: '#1A1A1A',
border: `1px solid #2A2A2A`,
- color: colors.alert,
- padding: '4px 6px',
- fontSize: '8px',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '3px'
+ color: '#FFF',
+ padding: '10px 12px',
+ fontSize: '12px',
+ cursor: 'pointer'
}}
>
- <Trash2 size={8} />
- DEL
- </button>
+ <option value="openai">OpenAI</option>
+ <option value="google">Google (Gemini)</option>
+ <option value="anthropic">Anthropic (Claude)</option>
+ <option value="deepseek">DeepSeek</option>
+ <option value="ollama">Ollama (Local)</option>
+ <option value="openrouter">OpenRouter</option>
+ <option value="groq">Groq</option>
+ </select>
+ </div>
+ <div>
+ <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>
+ MODEL ID <span style={{ color: colors.alert }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={newModelConfig.model_id}
+ onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}
+ placeholder="e.g. gpt-4o-mini"
+ style={{
+ width: '100%',
+ background: '#1A1A1A',
+ border: `1px solid #2A2A2A`,
+ color: '#FFF',
+ padding: '10px 12px',
+ fontSize: '12px'
+ }}
+ />
+ </div>
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>
+ <div>
+ <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>
+ DISPLAY NAME
+ </label>
+ <input
+ type="text"
+ value={newModelConfig.display_name}
+ onChange={(e) => setNewModelConfig({ ...newModelConfig, display_name: e.target.value })}
+ placeholder="e.g. GPT-4o Mini"
+ style={{
+ width: '100%',
+ background: '#1A1A1A',
+ border: `1px solid #2A2A2A`,
+ color: '#FFF',
+ padding: '10px 12px',
+ fontSize: '12px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>
+ API KEY (Optional)
+ </label>
+ <input
+ type="password"
+ value={newModelConfig.api_key}
+ onChange={(e) => setNewModelConfig({ ...newModelConfig, api_key: e.target.value })}
+ placeholder="Uses provider key if empty"
+ style={{
+ width: '100%',
+ background: '#1A1A1A',
+ border: `1px solid #2A2A2A`,
+ color: '#FFF',
+ padding: '10px 12px',
+ fontSize: '12px',
+ fontFamily: 'monospace'
+ }}
+ />
</div>
</div>
- ))}
- </div>
- )}
- {/* Summary */}
- {modelConfigs.length > 0 && (
+ <button
+ onClick={handleAddModelConfig}
+ disabled={loading || !newModelConfig.model_id}
+ style={{
+ background: loading || !newModelConfig.model_id ? '#2A2A2A' : colors.success,
+ color: loading || !newModelConfig.model_id ? '#666' : '#000',
+ border: 'none',
+ padding: '10px 20px',
+ fontSize: '12px',
+ fontWeight: 700,
+ cursor: loading || !newModelConfig.model_id ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}
+ >
+ <Plus size={14} />
+ ADD MODEL
+ </button>
+ </div>
+ )}
+
+ {/* Models List */}
+ <div style={{ flex: 1, overflowY: 'auto' }}>
+ {modelConfigs.length === 0 ? (
<div style={{
- marginTop: '8px',
- padding: '5px 6px',
- background: '#0a3a0a',
- border: `1px solid ${colors.success}`,
- display: 'flex',
- alignItems: 'center',
- gap: '6px'
+ padding: '40px 20px',
+ textAlign: 'center',
+ color: '#666',
+ border: `1px dashed #2A2A2A`,
+ background: '#000'
}}>
- <Check size={10} color={colors.success} />
- <div style={{ fontSize: '8px', color: colors.success, fontWeight: 600 }}>
- {modelConfigs.filter(m => m.is_enabled).length} ENABLED · {modelConfigs.length} TOTAL
+ <Bot size={40} color="#2A2A2A" style={{ marginBottom: '16px' }} />
+ <div style={{ fontSize: '13px', marginBottom: '8px', fontWeight: 600, color: '#888' }}>
+ No Custom Models Configured
+ </div>
+ <div style={{ fontSize: '11px', color: '#666' }}>
+ Click "ADD MODEL" to add custom model configurations
</div>
</div>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {modelConfigs.map((model) => (
+ <div
+ key={model.id}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ padding: '12px 14px',
+ background: model.is_enabled ? '#1A1A1A' : '#0A0A0A',
+ border: `1px solid ${model.is_enabled ? '#2A2A2A' : '#1A1A1A'}`,
+ opacity: model.is_enabled ? 1 : 0.6
+ }}
+ >
+ <button
+ onClick={() => handleToggleModelEnabled(model.id)}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ padding: 0
+ }}
+ >
+ {model.is_enabled ? (
+ <ToggleRight size={24} color={colors.success} />
+ ) : (
+ <ToggleLeft size={24} color="#666" />
+ )}
+ </button>
+ <div style={{ flex: 1 }}>
+ <div style={{
+ fontSize: '13px',
+ fontWeight: 600,
+ color: model.is_enabled ? '#FFF' : '#666',
+ marginBottom: '4px'
+ }}>
+ {model.display_name || model.model_id}
+ </div>
+ <div style={{
+ fontSize: '11px',
+ color: '#888',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <span style={{
+ padding: '2px 8px',
+ background: colors.primary + '20',
+ border: `1px solid ${colors.primary}`,
+ color: colors.primary,
+ fontWeight: 600,
+ fontSize: '10px'
+ }}>
+ {model.provider.toUpperCase()}
+ </span>
+ <span style={{ fontFamily: 'monospace' }}>{model.model_id}</span>
+ {model.api_key && (
+ <span style={{
+ padding: '2px 8px',
+ background: colors.success + '20',
+ border: `1px solid ${colors.success}`,
+ color: colors.success,
+ fontWeight: 600,
+ fontSize: '10px'
+ }}>
+ HAS KEY
+ </span>
+ )}
+ </div>
+ </div>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ {model.api_key && (
+ <button
+ onClick={() => setShowApiKeys(prev => ({ ...prev, [model.id]: !prev[model.id] }))}
+ style={{
+ background: '#1A1A1A',
+ border: `1px solid #2A2A2A`,
+ color: '#888',
+ padding: '6px 8px',
+ cursor: 'pointer'
+ }}
+ >
+ {showApiKeys[model.id] ? <EyeOff size={14} /> : <Eye size={14} />}
+ </button>
+ )}
+ <button
+ onClick={() => handleDeleteModelConfig(model.id)}
+ style={{
+ background: '#1A1A1A',
+ border: `1px solid #2A2A2A`,
+ color: colors.alert,
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontWeight: 600
+ }}
+ >
+ <Trash2 size={12} />
+ DELETE
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
)}
</div>
+
+ {/* Summary */}
+ {modelConfigs.length > 0 && (
+ <div style={{
+ marginTop: '16px',
+ padding: '12px 14px',
+ background: '#0a2a0a',
+ border: `1px solid ${colors.success}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px'
+ }}>
+ <Check size={16} color={colors.success} />
+ <div style={{ fontSize: '12px', color: colors.success, fontWeight: 600 }}>
+ {modelConfigs.filter(m => m.is_enabled).length} ENABLED · {modelConfigs.length} TOTAL MODELS
+ </div>
+ </div>
+ )}
</div>
</div>
</div>
@@ -2134,6 +2292,39 @@ export default function SettingsTab() {
}} />
)}
+ {/* Stock Symbols Section */}
+ {activeSection === 'stockSymbols' && (
+ <div style={{ maxWidth: '600px' }}>
+ <div style={{ marginBottom: '16px' }}>
+ <h2 style={{ fontSize: '16px', fontWeight: 700, color: colors.text, margin: 0 }}>
+ Stock Symbol Database
+ </h2>
+ <p style={{ fontSize: '11px', color: colors.textMuted, marginTop: '8px', lineHeight: 1.5 }}>
+ Download and manage broker symbol data for fast offline search.
+ Symbol data includes stocks, F&O, commodities, and currency derivatives.
+ Update regularly to get latest instruments and expiries.
+ </p>
+ </div>
+ <MasterContractManager
+ brokers={['angelone', 'fyers']}
+ onUpdate={(brokerId, result) => {
+ if (result.success) {
+ setMessage({
+ type: 'success',
+ text: `${brokerId.toUpperCase()}: Downloaded ${result.symbol_count.toLocaleString()} symbols`
+ });
+ } else {
+ setMessage({
+ type: 'error',
+ text: `${brokerId.toUpperCase()}: ${result.message}`
+ });
+ }
+ setTimeout(() => setMessage(null), 5000);
+ }}
+ />
+ </div>
+ )}
+
{/* Language Section */}
{activeSection === 'language' && (
<div style={{ padding: '20px' }}>
diff --git a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
index 2233c4736..1ff227e5c 100644
--- a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
@@ -24,6 +24,7 @@ import { AccountStats, FeesDisplay, MarginPanel } from './trading/core/AccountIn
import { PortfolioAggregator, ArbitrageDetector } from './trading/cross-exchange';
import { TimezoneSelector } from '../common/TimezoneSelector';
import { AIAgentsPanel } from './trading/ai-agents/AIAgentsPanel';
+import { GridTradingPanel } from './trading/grid-trading';
import { ModelChatPanel } from './trading/ai-agents/ModelChatPanel';
import { LeaderboardPanel } from './trading/ai-agents/LeaderboardPanel';
import type { OrderRequest } from '../../types/trading';
@@ -125,7 +126,7 @@ export function TradingTab() {
const [balance, setBalance] = useState(0);
const [equity, setEquity] = useState(0);
const [stats, setStats] = useState<any>(null);
- const [activeBottomTab, setActiveBottomTab] = useState<'positions' | 'orders' | 'history' | 'trades' | 'stats' | 'features' | 'cross-exchange'>('positions');
+ const [activeBottomTab, setActiveBottomTab] = useState<'positions' | 'orders' | 'history' | 'trades' | 'stats' | 'features' | 'cross-exchange' | 'grid-trading'>('positions');
const [isBottomPanelMinimized, setIsBottomPanelMinimized] = useState(false);
// Trading settings
@@ -1360,7 +1361,7 @@ export function TradingTab() {
alignItems: 'center'
}}>
<div style={{ display: 'flex', gap: '4px' }}>
- {(['positions', 'orders', 'history', 'trades', 'stats', 'features', 'cross-exchange'] as const).map((tab) => (
+ {(['positions', 'orders', 'history', 'trades', 'stats', 'features', 'cross-exchange', 'grid-trading'] as const).map((tab) => (
<button
key={tab}
onClick={() => setActiveBottomTab(tab)}
@@ -1578,6 +1579,20 @@ export function TradingTab() {
</div>
</div>
)}
+
+ {/* Grid Trading Tab */}
+ {activeBottomTab === 'grid-trading' && (
+ <div style={{ padding: '16px', overflow: 'auto', height: '100%' }}>
+ <GridTradingPanel
+ symbol={selectedSymbol}
+ currentPrice={tickerState?.last || tickerState?.close || 0}
+ brokerType="crypto"
+ brokerId={activeBroker}
+ cryptoAdapter={realAdapter || undefined}
+ variant="full"
+ />
+ </div>
+ )}
</div>
)}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx
new file mode 100644
index 000000000..25cc6a8de
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx
@@ -0,0 +1,1336 @@
+/**
+ * Equity Trading Tab - Bloomberg Terminal Style
+ *
+ * Professional stock/equity trading interface matching the crypto trading tab design.
+ * Supports multiple brokers across different regions with real-time market data.
+ */
+
+import React, { useState, useEffect, useCallback, useMemo } from 'react';
+import {
+ TrendingUp, TrendingDown, Activity, DollarSign, BarChart3,
+ Settings as SettingsIcon, Globe, Wifi, WifiOff, Bell,
+ Zap, Target, AlertCircle, RefreshCw, Maximize2, ChevronDown,
+ Clock, ChevronUp, Minimize2, Search, Building2, Briefcase,
+ FileText, History, PieChart, LineChart, BarChart2, Layers
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { StockBrokerProvider, useStockBrokerContext, useStockTradingMode, useStockTradingData } from '@/contexts/StockBrokerContext';
+import {
+ BrokerSelector,
+ BrokerSetupPanel,
+ StockOrderForm,
+ PositionsPanel,
+ HoldingsPanel,
+ OrdersPanel,
+ FundsPanel,
+ StockTradingChart,
+ SymbolSearch,
+} from './components';
+import type { SymbolSearchResult, SupportedBroker } from '@/services/trading/masterContractService';
+
+import type { StockExchange, Quote } from '@/brokers/stocks/types';
+import { GridTradingPanel } from '../trading/grid-trading';
+
+// 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'
+};
+
+// Default Indian market watchlist
+const DEFAULT_WATCHLIST = [
+ 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',
+ 'HINDUNILVR', 'SBIN', 'BHARTIARTL', 'ITC', 'KOTAKBANK',
+ 'LT', 'AXISBANK', 'BAJFINANCE', 'MARUTI', 'ASIANPAINT',
+ 'HCLTECH', 'SUNPHARMA', 'TITAN', 'WIPRO', 'ULTRACEMCO',
+ 'NESTLEIND', 'M&M', 'TATASTEEL', 'POWERGRID', 'NTPC',
+ 'JSWSTEEL', 'TECHM', 'ADANIPORTS', 'DIVISLAB', 'DRREDDY'
+];
+
+// Market indices
+const MARKET_INDICES = [
+ { symbol: 'NIFTY 50', exchange: 'NSE' as StockExchange },
+ { symbol: 'SENSEX', exchange: 'BSE' as StockExchange },
+ { symbol: 'BANKNIFTY', exchange: 'NSE' as StockExchange },
+ { symbol: 'NIFTYIT', exchange: 'NSE' as StockExchange },
+];
+
+type BottomPanelTab = 'positions' | 'holdings' | 'orders' | 'history' | 'stats' | 'market' | 'grid-trading';
+type LeftSidebarView = 'watchlist' | 'indices' | 'sectors';
+type CenterView = 'chart' | 'depth' | 'trades';
+type RightPanelView = 'orderbook' | 'marketdepth' | 'info';
+
+// Main Tab Content (wrapped in provider)
+function EquityTradingContent() {
+ const { t } = useTranslation();
+ const {
+ activeBroker,
+ activeBrokerMetadata,
+ isAuthenticated,
+ adapter,
+ defaultSymbols,
+ isLoading,
+ isConnecting,
+ } = useStockBrokerContext();
+ const { mode: tradingMode, setMode: setTradingMode, isLive, isPaper } = useStockTradingMode();
+ const { positions, holdings, orders, funds, refreshAll, isRefreshing } = useStockTradingData();
+
+ // Time state
+ const [currentTime, setCurrentTime] = useState(new Date());
+
+ // Symbol state
+ const [selectedSymbol, setSelectedSymbol] = useState<string>('');
+ const [selectedExchange, setSelectedExchange] = useState<StockExchange>('NSE');
+ // Note: searchQuery, showSymbolDropdown, searchResults, isSearching moved to SymbolSearch component
+
+ // Quote data
+ const [quote, setQuote] = useState<Quote | null>(null);
+ const [wsError, setWsError] = useState<string | null>(null);
+
+ // Watchlist
+ const [watchlist, setWatchlist] = useState<string[]>(DEFAULT_WATCHLIST);
+ const [watchlistQuotes, setWatchlistQuotes] = useState<Record<string, Quote>>({});
+
+ // UI State
+ const [leftSidebarView, setLeftSidebarView] = useState<LeftSidebarView>('watchlist');
+ const [centerView, setCenterView] = useState<CenterView>('chart');
+ const [rightPanelView, setRightPanelView] = useState<RightPanelView>('orderbook');
+ const [activeBottomTab, setActiveBottomTab] = useState<BottomPanelTab>('positions');
+ const [isBottomPanelMinimized, setIsBottomPanelMinimized] = useState(false);
+ const [showSettings, setShowSettings] = useState(false);
+
+ // Recent trades for trades view
+ const [recentTrades, setRecentTrades] = useState<any[]>([]);
+
+ // Update clock
+ useEffect(() => {
+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);
+ return () => clearInterval(timer);
+ }, []);
+
+ // Set default symbol when broker changes
+ useEffect(() => {
+ if (defaultSymbols.length > 0 && !selectedSymbol) {
+ setSelectedSymbol(defaultSymbols[0]);
+ }
+ // Update watchlist from broker defaults
+ if (defaultSymbols.length > 0) {
+ setWatchlist(defaultSymbols.slice(0, 30));
+ }
+ }, [defaultSymbols, selectedSymbol]);
+
+ // Subscribe to WebSocket for live prices
+ useEffect(() => {
+ if (!adapter || !isAuthenticated || !selectedSymbol) return;
+
+ const subscribeToSymbol = async () => {
+ try {
+ console.log(`[EquityTrading] Subscribing to ${selectedSymbol} via WebSocket...`);
+
+ await adapter.subscribe(selectedSymbol, selectedExchange, 'quote');
+
+ const handleTick = (tick: any) => {
+ if (tick.symbol === selectedSymbol) {
+ setQuote({
+ symbol: tick.symbol,
+ exchange: tick.exchange,
+ lastPrice: tick.lastPrice || tick.price,
+ open: tick.open || tick.lastPrice,
+ high: tick.high || tick.lastPrice,
+ low: tick.low || tick.lastPrice,
+ close: tick.close || tick.lastPrice,
+ previousClose: tick.close || tick.lastPrice,
+ volume: tick.volume || 0,
+ change: tick.change || 0,
+ changePercent: tick.changePercent || 0,
+ bid: tick.bid || 0,
+ bidQty: tick.bidQty || 0,
+ ask: tick.ask || 0,
+ askQty: tick.askQty || 0,
+ timestamp: Date.now(),
+ });
+ }
+ };
+
+ adapter.onTick(handleTick);
+ setWsError(null);
+ } catch (err: any) {
+ console.error('[EquityTrading] WebSocket subscription failed:', err);
+ setWsError(err.message);
+ }
+ };
+
+ subscribeToSymbol();
+
+ return () => {
+ if (adapter && selectedSymbol) {
+ adapter.unsubscribe(selectedSymbol, selectedExchange).catch(console.error);
+ }
+ };
+ }, [adapter, isAuthenticated, selectedSymbol, selectedExchange]);
+
+ // Fetch watchlist quotes periodically
+ useEffect(() => {
+ if (!adapter || !isAuthenticated) return;
+
+ const fetchWatchlistQuotes = async () => {
+ try {
+ const quotes: Record<string, Quote> = {};
+ // Batch fetch quotes for watchlist
+ for (const symbol of watchlist.slice(0, 15)) {
+ try {
+ const q = await adapter.getQuote(symbol, selectedExchange);
+ if (q) {
+ quotes[symbol] = q;
+ }
+ } catch (err) {
+ // Skip individual quote errors
+ }
+ }
+ if (Object.keys(quotes).length > 0) {
+ setWatchlistQuotes(quotes);
+ }
+ } catch (err) {
+ console.error('[EquityTrading] Failed to fetch watchlist quotes:', err);
+ }
+ };
+
+ fetchWatchlistQuotes();
+ const interval = setInterval(fetchWatchlistQuotes, 30000);
+ return () => clearInterval(interval);
+ }, [adapter, isAuthenticated, watchlist, selectedExchange]);
+
+ // Select symbol from search (supports both legacy search and master contract search)
+ const handleSelectSymbol = (symbol: string, exchange: StockExchange, result?: SymbolSearchResult) => {
+ setSelectedSymbol(symbol);
+ setSelectedExchange(exchange);
+
+ // Log additional info from master contract if available
+ if (result) {
+ console.log(`[EquityTrading] Selected ${symbol} on ${exchange}`, {
+ token: result.token,
+ name: result.name,
+ instrumentType: result.instrument_type,
+ lotSize: result.lot_size
+ });
+ }
+ };
+
+ // Calculate derived values
+ const currentPrice = quote?.lastPrice || 0;
+ const priceChange = quote?.change || 0;
+ const priceChangePercent = quote?.changePercent || 0;
+ const spread = quote ? (quote.ask - quote.bid) : 0;
+ const spreadPercent = quote && quote.bid > 0 ? (spread / quote.bid) * 100 : 0;
+ const dayRange = quote ? (quote.high - quote.low) : 0;
+ const dayRangePercent = quote && quote.low > 0 ? (dayRange / quote.low) * 100 : 0;
+
+ // Connection status
+ const isConnected = isAuthenticated && adapter !== null;
+
+ // Calculate totals for display
+ const totalPositionValue = positions.reduce((acc, p) => acc + (p.quantity * p.lastPrice), 0);
+ const totalPositionPnl = positions.reduce((acc, p) => acc + p.pnl, 0);
+ const totalHoldingsValue = holdings.reduce((acc, h) => acc + h.currentValue, 0);
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG.DARK_BG,
+ color: BLOOMBERG.WHITE,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ <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' }}>
+ {/* Terminal Branding */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Building2 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`
+ }}>
+ EQUITY TERMINAL
+ </span>
+ </div>
+
+ <div style={{ height: '16px', width: '1px', backgroundColor: BLOOMBERG.BORDER }} />
+
+ {/* Broker Selector */}
+ <BrokerSelector />
+
+ <div style={{ height: '16px', width: '1px', backgroundColor: BLOOMBERG.BORDER }} />
+
+ {/* Trading Mode Toggle */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <button
+ onClick={() => setTradingMode('paper')}
+ style={{
+ padding: '4px 10px',
+ backgroundColor: isPaper ? BLOOMBERG.GREEN : BLOOMBERG.PANEL_BG,
+ border: `1px solid ${isPaper ? BLOOMBERG.GREEN : BLOOMBERG.BORDER}`,
+ color: isPaper ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ transition: 'all 0.2s'
+ }}
+ >
+ PAPER
+ </button>
+ <button
+ onClick={() => setTradingMode('live')}
+ style={{
+ padding: '4px 10px',
+ backgroundColor: isLive ? BLOOMBERG.RED : BLOOMBERG.PANEL_BG,
+ border: `1px solid ${isLive ? BLOOMBERG.RED : BLOOMBERG.BORDER}`,
+ color: isLive ? BLOOMBERG.WHITE : BLOOMBERG.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ transition: 'all 0.2s'
+ }}
+ >
+ LIVE
+ </button>
+ </div>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ {/* Connection Status */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '10px' }}>
+ {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 }} />
+
+ {/* Clock */}
+ <div style={{
+ fontSize: '11px',
+ fontWeight: 600,
+ color: BLOOMBERG.CYAN,
+ fontFamily: 'monospace'
+ }}>
+ {currentTime.toLocaleTimeString('en-IN', { hour12: false })}
+ </div>
+
+ {/* Settings */}
+ <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 - Using Master Contract Database */}
+ <SymbolSearch
+ selectedSymbol={selectedSymbol}
+ selectedExchange={selectedExchange}
+ onSymbolSelect={handleSelectSymbol}
+ brokerId={(activeBroker || 'angelone') as SupportedBroker}
+ placeholder="Search stocks, F&O, commodities..."
+ showDownloadStatus={true}
+ />
+
+ {/* Price Display */}
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px' }}>
+ <span style={{
+ fontSize: '24px',
+ fontWeight: 700,
+ color: BLOOMBERG.YELLOW,
+ willChange: 'contents',
+ transition: 'none'
+ }}>
+ {currentPrice > 0 ? `₹${currentPrice.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : '--'}
+ </span>
+ {quote && (priceChange !== 0 || priceChangePercent !== 0) && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ {priceChange >= 0 ? (
+ <TrendingUp size={16} color={BLOOMBERG.GREEN} />
+ ) : (
+ <TrendingDown 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', willChange: 'contents' }}>
+ <div style={{ minWidth: '60px' }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>BID</div>
+ <div style={{ color: BLOOMBERG.GREEN, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {quote?.bid ? `₹${quote.bid.toFixed(2)}` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '60px' }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>ASK</div>
+ <div style={{ color: BLOOMBERG.RED, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {quote?.ask ? `₹${quote.ask.toFixed(2)}` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '100px' }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>DAY RANGE</div>
+ <div style={{ color: BLOOMBERG.CYAN, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {dayRange > 0 ? `₹${dayRange.toFixed(2)} (${dayRangePercent.toFixed(2)}%)` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '80px' }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>HIGH</div>
+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {quote?.high ? `₹${quote.high.toFixed(2)}` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '80px' }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>LOW</div>
+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {quote?.low ? `₹${quote.low.toFixed(2)}` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '100px' }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>VOLUME</div>
+ <div style={{ color: BLOOMBERG.PURPLE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {quote?.volume ? quote.volume.toLocaleString('en-IN') : '--'}
+ </div>
+ </div>
+ </div>
+
+ {/* Account Summary */}
+ {isAuthenticated && (
+ <>
+ <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' }}>MARGIN</div>
+ <div style={{ color: BLOOMBERG.CYAN, fontWeight: 600 }}>
+ ₹{(funds?.availableMargin || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '2px' }}>P&L</div>
+ <div style={{ color: totalPositionPnl >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED, fontWeight: 600 }}>
+ {totalPositionPnl >= 0 ? '+' : ''}₹{totalPositionPnl.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+
+ {/* ========== MAIN CONTENT ========== */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* LEFT SIDEBAR - Watchlist / Indices / Sectors */}
+ <div style={{
+ width: '280px',
+ minWidth: '280px',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ borderRight: `1px solid ${BLOOMBERG.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ flexShrink: 0
+ }}>
+ {/* Toggle Header */}
+ <div style={{
+ padding: '6px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ display: 'flex',
+ gap: '4px'
+ }}>
+ {(['watchlist', 'indices', 'sectors'] as LeftSidebarView[]).map((view) => (
+ <button
+ key={view}
+ onClick={() => setLeftSidebarView(view)}
+ style={{
+ flex: 1,
+ padding: '6px 8px',
+ backgroundColor: leftSidebarView === view ? BLOOMBERG.ORANGE : 'transparent',
+ border: 'none',
+ color: leftSidebarView === view ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ borderRadius: '2px'
+ }}
+ >
+ {view.toUpperCase()}
+ </button>
+ ))}
+ </div>
+
+ {/* Content */}
+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ {leftSidebarView === 'watchlist' && (
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: '0',
+ alignContent: 'start'
+ }}>
+ {watchlist.map((symbol, idx) => {
+ const q = watchlistQuotes[symbol];
+ const isSelected = symbol === selectedSymbol;
+
+ return (
+ <div
+ key={symbol}
+ onClick={() => handleSelectSymbol(symbol, selectedExchange)}
+ style={{
+ padding: '8px 10px',
+ cursor: 'pointer',
+ backgroundColor: isSelected ? `${BLOOMBERG.ORANGE}15` : 'transparent',
+ borderLeft: isSelected ? `2px solid ${BLOOMBERG.ORANGE}` : '2px solid transparent',
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRight: idx % 2 === 0 ? `1px solid ${BLOOMBERG.BORDER}` : 'none',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (!isSelected) {
+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!isSelected) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <div style={{
+ fontSize: '11px',
+ fontWeight: 700,
+ color: isSelected ? BLOOMBERG.ORANGE : BLOOMBERG.WHITE,
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ maxWidth: '60px'
+ }}>
+ {symbol}
+ </div>
+
+ {q ? (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'flex-end',
+ gap: '2px'
+ }}>
+ <div style={{
+ fontSize: '10px',
+ color: BLOOMBERG.WHITE,
+ fontFamily: 'monospace',
+ fontWeight: 600
+ }}>
+ ₹{q.lastPrice >= 1000
+ ? q.lastPrice.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
+ : q.lastPrice.toFixed(2)
+ }
+ </div>
+ <div style={{
+ fontSize: '9px',
+ color: q.changePercent >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,
+ fontFamily: 'monospace',
+ fontWeight: 700
+ }}>
+ {q.changePercent >= 0 ? '▲' : '▼'} {Math.abs(q.changePercent).toFixed(2)}%
+ </div>
+ </div>
+ ) : (
+ <div style={{
+ fontSize: '9px',
+ color: BLOOMBERG.GRAY,
+ fontFamily: 'monospace'
+ }}>
+ ...
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {leftSidebarView === 'indices' && (
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
+ <div style={{
+ fontSize: '10px',
+ fontWeight: 700,
+ color: BLOOMBERG.GRAY,
+ marginBottom: '12px',
+ letterSpacing: '0.5px'
+ }}>
+ MARKET INDICES
+ </div>
+ {MARKET_INDICES.map((index) => (
+ <div
+ key={index.symbol}
+ style={{
+ padding: '12px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ marginBottom: '8px',
+ cursor: 'pointer'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = BLOOMBERG.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={{ fontSize: '12px', fontWeight: 700, color: BLOOMBERG.WHITE }}>{index.symbol}</div>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY }}>{index.exchange}</div>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <div style={{ fontSize: '12px', fontWeight: 600, color: BLOOMBERG.YELLOW }}>--</div>
+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY }}>--</div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {leftSidebarView === 'sectors' && (
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
+ <div style={{
+ fontSize: '10px',
+ fontWeight: 700,
+ color: BLOOMBERG.GRAY,
+ marginBottom: '12px',
+ letterSpacing: '0.5px'
+ }}>
+ SECTOR PERFORMANCE
+ </div>
+ {['IT', 'Banking', 'Pharma', 'Auto', 'FMCG', 'Metal', 'Realty', 'Energy'].map((sector) => (
+ <div
+ key={sector}
+ style={{
+ padding: '10px 12px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ marginBottom: '6px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ cursor: 'pointer'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = BLOOMBERG.CYAN;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;
+ }}
+ >
+ <span style={{ fontSize: '11px', color: BLOOMBERG.WHITE }}>{sector}</span>
+ <span style={{ fontSize: '10px', color: BLOOMBERG.GRAY }}>--</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* CENTER - Chart & Bottom Panel */}
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minWidth: 0 }}>
+ {/* Chart Area - Takes maximum available space */}
+ <div style={{
+ flex: isBottomPanelMinimized ? 1 : '1 1 auto',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ minHeight: '300px',
+ transition: 'flex 0.3s ease'
+ }}>
+ {/* Chart Header - Compact */}
+ <div style={{
+ padding: '4px 12px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ flexShrink: 0
+ }}>
+ {(['CHART', 'DEPTH', 'TRADES'] as const).map((view) => (
+ <button
+ key={view}
+ onClick={() => setCenterView(view.toLowerCase() as CenterView)}
+ style={{
+ padding: '3px 10px',
+ backgroundColor: centerView === view.toLowerCase() ? BLOOMBERG.ORANGE : 'transparent',
+ border: 'none',
+ color: centerView === view.toLowerCase() ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700,
+ transition: 'all 0.2s'
+ }}
+ >
+ {view}
+ </button>
+ ))}
+
+ <div style={{ flex: 1 }} />
+
+ {/* Refresh Button */}
+ <button
+ onClick={() => refreshAll()}
+ disabled={isRefreshing}
+ style={{
+ padding: '3px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <RefreshCw size={10} className={isRefreshing ? 'animate-spin' : ''} />
+ </button>
+ </div>
+
+ {/* Chart Content - Full Height */}
+ <div style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'stretch',
+ justifyContent: 'stretch',
+ color: BLOOMBERG.GRAY,
+ fontSize: '12px',
+ overflow: 'hidden',
+ minHeight: 0,
+ position: 'relative'
+ }}>
+ {centerView === 'chart' && (
+ <div style={{
+ width: '100%',
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column',
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ paddingBottom: '4px' // Give space for time axis
+ }}>
+ <StockTradingChart
+ symbol={selectedSymbol}
+ exchange={selectedExchange}
+ interval="5m"
+ />
+ </div>
+ )}
+ {centerView === 'depth' && (
+ <div style={{
+ width: '100%',
+ height: '100%',
+ padding: '20px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexDirection: 'column',
+ gap: '12px'
+ }}>
+ <BarChart3 size={48} color={BLOOMBERG.GRAY} />
+ <span style={{ fontSize: '14px', color: BLOOMBERG.GRAY }}>Market Depth Chart</span>
+ <span style={{ fontSize: '11px', color: BLOOMBERG.MUTED }}>Connect to broker for real-time depth data</span>
+ </div>
+ )}
+ {centerView === 'trades' && (
+ <div style={{ width: '100%', height: '100%', overflow: 'auto', padding: '8px' }}>
+ {recentTrades.length === 0 ? (
+ <div style={{
+ padding: '40px',
+ textAlign: 'center',
+ color: BLOOMBERG.GRAY,
+ fontSize: '11px'
+ }}>
+ No recent trades
+ </div>
+ ) : (
+ <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 }}>QTY</th>
+ </tr>
+ </thead>
+ <tbody>
+ {recentTrades.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.quantity}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Bottom Panel - Positions/Holdings/Orders - Compact by default */}
+ <div style={{
+ flex: isBottomPanelMinimized ? '0 0 32px' : '0 0 200px',
+ minHeight: isBottomPanelMinimized ? '32px' : '150px',
+ maxHeight: isBottomPanelMinimized ? '32px' : '220px',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ transition: 'all 0.3s ease'
+ }}>
+ {/* Bottom Panel Header */}
+ <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' }}>
+ {([
+ { id: 'positions', label: 'POSITIONS', count: positions.length },
+ { id: 'holdings', label: 'HOLDINGS', count: holdings.length },
+ { id: 'orders', label: 'ORDERS', count: orders.filter(o => ['PENDING', 'OPEN'].includes(o.status)).length },
+ { id: 'history', label: 'HISTORY', count: null },
+ { id: 'stats', label: 'STATS', count: null },
+ { id: 'grid-trading', label: 'GRID BOT', count: null },
+ ] as const).map((tab) => (
+ <button
+ key={tab.id}
+ onClick={() => setActiveBottomTab(tab.id)}
+ style={{
+ padding: '6px 16px',
+ backgroundColor: activeBottomTab === tab.id ? BLOOMBERG.ORANGE : 'transparent',
+ border: 'none',
+ color: activeBottomTab === tab.id ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ transition: 'all 0.2s'
+ }}
+ >
+ {tab.label} {tab.count !== null && `(${tab.count})`}
+ </button>
+ ))}
+ </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;
+ }}
+ >
+ {isBottomPanelMinimized ? (
+ <>
+ <ChevronUp size={14} />
+ <span>MAXIMIZE</span>
+ </>
+ ) : (
+ <>
+ <ChevronDown size={14} />
+ <span>MINIMIZE</span>
+ </>
+ )}
+ </button>
+ </div>
+
+ {/* Bottom Panel Content */}
+ {!isBottomPanelMinimized && (
+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ {activeBottomTab === 'positions' && <PositionsPanel />}
+ {activeBottomTab === 'holdings' && <HoldingsPanel />}
+ {activeBottomTab === 'orders' && <OrdersPanel />}
+ {activeBottomTab === 'history' && <OrdersPanel showHistory />}
+ {activeBottomTab === 'stats' && (
+ <div style={{
+ padding: '20px',
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '16px'
+ }}>
+ <div style={{
+ padding: '16px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '8px' }}>TOTAL POSITIONS VALUE</div>
+ <div style={{ fontSize: '18px', fontWeight: 700, color: BLOOMBERG.CYAN }}>
+ ₹{totalPositionValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div style={{
+ padding: '16px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '8px' }}>DAY P&L</div>
+ <div style={{
+ fontSize: '18px',
+ fontWeight: 700,
+ color: totalPositionPnl >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED
+ }}>
+ {totalPositionPnl >= 0 ? '+' : ''}₹{totalPositionPnl.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div style={{
+ padding: '16px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '8px' }}>PORTFOLIO VALUE</div>
+ <div style={{ fontSize: '18px', fontWeight: 700, color: BLOOMBERG.YELLOW }}>
+ ₹{totalHoldingsValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div style={{
+ padding: '16px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '8px' }}>AVAILABLE MARGIN</div>
+ <div style={{ fontSize: '18px', fontWeight: 700, color: BLOOMBERG.PURPLE }}>
+ ₹{(funds?.availableMargin || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Grid Trading Tab */}
+ {activeBottomTab === 'grid-trading' && (
+ <div style={{ padding: '16px', overflow: 'auto', height: '100%' }}>
+ <GridTradingPanel
+ symbol={selectedSymbol}
+ exchange={selectedExchange}
+ currentPrice={currentPrice}
+ brokerType="stock"
+ brokerId={activeBroker || ''}
+ stockAdapter={adapter || undefined}
+ variant="full"
+ />
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* RIGHT SIDEBAR - Order Entry & Market Depth */}
+ <div style={{
+ width: '280px',
+ minWidth: '280px',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ borderLeft: `1px solid ${BLOOMBERG.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ flexShrink: 0
+ }}>
+ {/* Order Entry Section */}
+ <div style={{
+ height: '50%',
+ 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' }}>
+ {!isAuthenticated ? (
+ <BrokerSetupPanel />
+ ) : (
+ <StockOrderForm
+ symbol={selectedSymbol}
+ exchange={selectedExchange}
+ lastPrice={currentPrice}
+ />
+ )}
+ </div>
+ </div>
+
+ {/* Market Depth / Info Section */}
+ <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', 'marketdepth', 'info'] as RightPanelView[]).map((view) => (
+ <button
+ key={view}
+ onClick={() => setRightPanelView(view)}
+ 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 === 'orderbook' ? 'BOOK' : view === 'marketdepth' ? 'DEPTH' : 'INFO'}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ {rightPanelView === 'orderbook' && (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '8px',
+ height: '100%'
+ }}>
+ {/* Buy Orders (Bids) */}
+ <div>
+ <div style={{ color: BLOOMBERG.GREEN, fontSize: '9px', fontWeight: 700, marginBottom: '4px' }}>
+ BIDS (BUY ORDERS)
+ </div>
+ <table style={{ width: '100%', fontSize: '10px' }}>
+ <thead>
+ <tr style={{ borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>
+ <th style={{ padding: '4px', textAlign: 'left', color: BLOOMBERG.GRAY }}>QTY</th>
+ <th style={{ padding: '4px', textAlign: 'right', color: BLOOMBERG.GRAY }}>PRICE</th>
+ <th style={{ padding: '4px', textAlign: 'right', color: BLOOMBERG.GRAY }}>ORDERS</th>
+ </tr>
+ </thead>
+ <tbody>
+ {[1, 2, 3, 4, 5].map((i) => (
+ <tr key={i} style={{ borderBottom: `1px solid ${BLOOMBERG.BORDER}40` }}>
+ <td style={{ padding: '4px', color: BLOOMBERG.WHITE }}>--</td>
+ <td style={{ padding: '4px', textAlign: 'right', color: BLOOMBERG.GREEN }}>--</td>
+ <td style={{ padding: '4px', textAlign: 'right', color: BLOOMBERG.GRAY }}>--</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+
+ {/* Spread Divider */}
+ <div style={{
+ padding: '8px',
+ textAlign: 'center',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ fontSize: '10px'
+ }}>
+ <span style={{ color: BLOOMBERG.GRAY }}>Spread: </span>
+ <span style={{ color: BLOOMBERG.YELLOW, fontWeight: 600 }}>
+ {spread > 0 ? `₹${spread.toFixed(2)} (${spreadPercent.toFixed(3)}%)` : '--'}
+ </span>
+ </div>
+
+ {/* Sell Orders (Asks) */}
+ <div>
+ <div style={{ color: BLOOMBERG.RED, fontSize: '9px', fontWeight: 700, marginBottom: '4px' }}>
+ ASKS (SELL ORDERS)
+ </div>
+ <table style={{ width: '100%', fontSize: '10px' }}>
+ <thead>
+ <tr style={{ borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>
+ <th style={{ padding: '4px', textAlign: 'left', color: BLOOMBERG.GRAY }}>PRICE</th>
+ <th style={{ padding: '4px', textAlign: 'right', color: BLOOMBERG.GRAY }}>QTY</th>
+ <th style={{ padding: '4px', textAlign: 'right', color: BLOOMBERG.GRAY }}>ORDERS</th>
+ </tr>
+ </thead>
+ <tbody>
+ {[1, 2, 3, 4, 5].map((i) => (
+ <tr key={i} style={{ borderBottom: `1px solid ${BLOOMBERG.BORDER}40` }}>
+ <td style={{ padding: '4px', color: BLOOMBERG.RED }}>--</td>
+ <td style={{ padding: '4px', textAlign: 'right', color: BLOOMBERG.WHITE }}>--</td>
+ <td style={{ padding: '4px', textAlign: 'right', color: BLOOMBERG.GRAY }}>--</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ )}
+
+ {rightPanelView === 'marketdepth' && (
+ <div style={{
+ height: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexDirection: 'column',
+ gap: '12px'
+ }}>
+ <Layers size={48} color={BLOOMBERG.GRAY} />
+ <span style={{ fontSize: '12px', color: BLOOMBERG.GRAY }}>Market Depth</span>
+ <span style={{ fontSize: '10px', color: BLOOMBERG.MUTED, textAlign: 'center' }}>
+ Connect to broker for<br />real-time depth visualization
+ </span>
+ </div>
+ )}
+
+ {rightPanelView === 'info' && (
+ <div style={{ padding: '8px' }}>
+ <div style={{
+ fontSize: '10px',
+ fontWeight: 700,
+ color: BLOOMBERG.GRAY,
+ marginBottom: '12px',
+ letterSpacing: '0.5px'
+ }}>
+ SYMBOL INFO
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {[
+ { label: 'Symbol', value: selectedSymbol || '--' },
+ { label: 'Exchange', value: selectedExchange },
+ { label: 'Open', value: quote?.open ? `₹${quote.open.toFixed(2)}` : '--' },
+ { label: 'Prev Close', value: quote?.previousClose ? `₹${quote.previousClose.toFixed(2)}` : '--' },
+ { label: 'Day High', value: quote?.high ? `₹${quote.high.toFixed(2)}` : '--' },
+ { label: 'Day Low', value: quote?.low ? `₹${quote.low.toFixed(2)}` : '--' },
+ { label: 'Volume', value: quote?.volume ? quote.volume.toLocaleString('en-IN') : '--' },
+ ].map((item) => (
+ <div
+ key={item.label}
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ padding: '6px 8px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`
+ }}
+ >
+ <span style={{ fontSize: '10px', color: BLOOMBERG.GRAY }}>{item.label}</span>
+ <span style={{ fontSize: '10px', color: BLOOMBERG.WHITE, fontWeight: 600 }}>{item.value}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Funds Panel (Compact) */}
+ {isAuthenticated && (
+ <div style={{
+ padding: '6px 8px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,
+ fontSize: '10px',
+ flexShrink: 0,
+ overflow: 'hidden'
+ }}>
+ <FundsPanel compact />
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* ========== STATUS BAR ========== */}
+ <div style={{
+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ padding: '4px 12px',
+ fontSize: '9px',
+ color: BLOOMBERG.GRAY,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0
+ }}>
+ <span>Fincept Terminal v3.1.4 | Equity Trading Platform</span>
+ <span>
+ Broker: <span style={{ color: BLOOMBERG.ORANGE }}>{activeBrokerMetadata?.displayName?.toUpperCase() || 'NONE'}</span> |
+ Mode: <span style={{ color: isPaper ? BLOOMBERG.GREEN : BLOOMBERG.RED }}>
+ {tradingMode.toUpperCase()}
+ </span> |
+ Status: <span style={{ color: isConnected ? BLOOMBERG.GREEN : BLOOMBERG.RED }}>
+ {isConnected ? 'CONNECTED' : 'DISCONNECTED'}
+ </span>
+ </span>
+ </div>
+ </div>
+ );
+}
+
+// Main export with Provider wrapper
+export function EquityTradingTab() {
+ return (
+ <StockBrokerProvider>
+ <EquityTradingContent />
+ </StockBrokerProvider>
+ );
+}
+
+export default EquityTradingTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerAuthPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerAuthPanel.tsx
new file mode 100644
index 000000000..730d0d316
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerAuthPanel.tsx
@@ -0,0 +1,792 @@
+/**
+ * Broker Authentication Panel - Bloomberg Style
+ *
+ * Handles OAuth and credential-based authentication for stock brokers
+ */
+
+import React, { useState } from 'react';
+import { KeyRound, ExternalLink, Loader2, AlertCircle, CheckCircle2, Eye, EyeOff, Lock, LogOut, Zap } from 'lucide-react';
+import { open } from '@tauri-apps/plugin-shell';
+import { useStockBrokerAuth, useStockBrokerSelection } from '@/contexts/StockBrokerContext';
+import type { BrokerCredentials } from '@/brokers/stocks/types';
+
+// Bloomberg color palette
+const COLORS = {
+ ORANGE: '#FF8800',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ GRAY: '#787878',
+ MUTED: '#4A4A4A',
+ WHITE: '#FFFFFF',
+};
+
+interface BrokerAuthPanelProps {
+ onAuthSuccess?: () => void;
+}
+
+export function BrokerAuthPanel({ onAuthSuccess }: BrokerAuthPanelProps) {
+ const { metadata } = useStockBrokerSelection();
+ const { isAuthenticated, authenticate, logout, getAuthUrl, isConnecting, error, clearError, adapter } = useStockBrokerAuth();
+
+ const [showCredentials, setShowCredentials] = useState(false);
+ const [credentials, setCredentials] = useState<BrokerCredentials>({
+ apiKey: '',
+ apiSecret: '',
+ accessToken: '',
+ userId: '',
+ totpSecret: '',
+ password: '',
+ pin: '',
+ });
+ const [callbackUrl, setCallbackUrl] = useState('');
+ const [showCallbackInput, setShowCallbackInput] = useState(false);
+
+ // Handle OAuth flow
+ const handleOAuthLogin = async () => {
+ try {
+ const authUrl = await getAuthUrl();
+ if (authUrl) {
+ console.log('[BrokerAuthPanel] Opening OAuth URL:', authUrl.substring(0, 50) + '...');
+ await open(authUrl);
+ console.log('[BrokerAuthPanel] ✓ Browser opened successfully');
+ setShowCallbackInput(true);
+ } else {
+ console.error('[BrokerAuthPanel] No auth URL returned');
+ }
+ } catch (err) {
+ console.error('[BrokerAuthPanel] Failed to get auth URL:', err);
+ }
+ };
+
+ // Handle callback URL submission
+ const handleCallbackSubmit = async () => {
+ try {
+ const url = new URL(callbackUrl);
+ const requestToken = url.searchParams.get('request_token');
+ const authCode = url.searchParams.get('auth_code');
+ const code = url.searchParams.get('code');
+
+ const token = requestToken || authCode || code;
+
+ if (!token) {
+ console.error('[BrokerAuthPanel] No auth code/token found in callback URL');
+ return;
+ }
+
+ console.log('[BrokerAuthPanel] Found auth token, loading stored credentials...');
+
+ const storedCreds = await (adapter as any)?.loadCredentials();
+
+ if (!storedCreds || !storedCreds.apiKey) {
+ console.error('[BrokerAuthPanel] No stored credentials found. Please save API credentials first.');
+ return;
+ }
+
+ const authCredentials: BrokerCredentials = {
+ apiKey: storedCreds.apiKey,
+ apiSecret: storedCreds.apiSecret,
+ };
+
+ if (requestToken) {
+ (authCredentials as any).requestToken = requestToken;
+ } else if (authCode) {
+ (authCredentials as any).authCode = authCode;
+ } else {
+ authCredentials.accessToken = token;
+ }
+
+ const response = await authenticate(authCredentials);
+
+ if (response.success) {
+ console.log('[BrokerAuthPanel] ✓ Authentication successful');
+ setShowCallbackInput(false);
+ setCallbackUrl('');
+ if (onAuthSuccess) {
+ onAuthSuccess();
+ }
+ } else {
+ console.error('[BrokerAuthPanel] Authentication failed:', response.message);
+ }
+ } catch (err) {
+ console.error('[BrokerAuthPanel] Failed to process callback:', err);
+ }
+ };
+
+ // Handle credential-based login
+ const handleCredentialLogin = async () => {
+ clearError();
+
+ const response = await authenticate(credentials);
+ if (response.success && onAuthSuccess) {
+ onAuthSuccess();
+ }
+ };
+
+ // Handle logout
+ const handleLogout = async () => {
+ await logout();
+ setCredentials({
+ apiKey: '',
+ apiSecret: '',
+ accessToken: '',
+ userId: '',
+ totpSecret: '',
+ password: '',
+ pin: '',
+ });
+ };
+
+ // Test API endpoint
+ const testApiEndpoint = async () => {
+ try {
+ console.log('[BrokerAuthPanel] Testing API endpoint...');
+
+ if (adapter && metadata?.id === 'zerodha') {
+ const quote = await adapter.getQuote('INFY', 'NSE');
+ console.log('[BrokerAuthPanel] ✓ Quote received:', quote);
+ alert(`Success! INFY LTP: ₹${quote.lastPrice}\nCheck console for full response`);
+ } else if (adapter && metadata?.id === 'fyers') {
+ const quote = await adapter.getQuote('RELIANCE', 'NSE');
+ console.log('[BrokerAuthPanel] ✓ Quote received:', quote);
+ alert(`Success! RELIANCE LTP: ₹${quote.lastPrice}\nCheck console for full response`);
+ } else if (adapter && metadata?.id === 'angelone') {
+ const quote = await adapter.getQuote('SBIN', 'NSE');
+ console.log('[BrokerAuthPanel] ✓ Quote received:', quote);
+ alert(`Success! SBIN LTP: ₹${quote.lastPrice}\nCheck console for full response`);
+ } else {
+ alert('Test only available for Zerodha, Fyers, and Angel One');
+ }
+ } catch (err: any) {
+ console.error('[BrokerAuthPanel] API test failed:', err);
+ alert(`API test failed: ${err.message}\nCheck console for details`);
+ }
+ };
+
+ if (!metadata) {
+ return (
+ <div style={{
+ padding: '24px',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ textAlign: 'center'
+ }}>
+ <p style={{ color: COLORS.GRAY, fontSize: '11px' }}>Select a broker to continue</p>
+ </div>
+ );
+ }
+
+ // Already authenticated
+ if (isAuthenticated) {
+ return (
+ <div style={{
+ padding: '20px',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {/* Connected Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ marginBottom: '20px',
+ paddingBottom: '16px',
+ borderBottom: `1px solid ${COLORS.BORDER}`
+ }}>
+ <div style={{
+ width: '36px',
+ height: '36px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: `${COLORS.GREEN}20`,
+ border: `1px solid ${COLORS.GREEN}40`
+ }}>
+ <CheckCircle2 size={18} color={COLORS.GREEN} />
+ </div>
+ <div>
+ <h3 style={{ color: COLORS.WHITE, fontSize: '13px', fontWeight: 600, margin: 0 }}>
+ CONNECTED TO {metadata.displayName.toUpperCase()}
+ </h3>
+ <p style={{ color: COLORS.GREEN, fontSize: '10px', margin: '4px 0 0 0' }}>
+ Your broker account is linked
+ </p>
+ </div>
+ </div>
+
+ {/* Action Buttons */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ <button
+ onClick={testApiEndpoint}
+ style={{
+ width: '100%',
+ padding: '10px 16px',
+ backgroundColor: `${COLORS.BLUE}20`,
+ border: `1px solid ${COLORS.BLUE}40`,
+ color: COLORS.BLUE,
+ fontSize: '11px',
+ fontWeight: 600,
+ fontFamily: '"IBM Plex Mono", monospace',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px'
+ }}
+ >
+ <Zap size={14} />
+ TEST API ENDPOINT
+ </button>
+
+ <button
+ onClick={handleLogout}
+ style={{
+ width: '100%',
+ padding: '10px 16px',
+ backgroundColor: `${COLORS.RED}20`,
+ border: `1px solid ${COLORS.RED}40`,
+ color: COLORS.RED,
+ fontSize: '11px',
+ fontWeight: 600,
+ fontFamily: '"IBM Plex Mono", monospace',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px'
+ }}
+ >
+ <LogOut size={14} />
+ DISCONNECT BROKER
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ padding: '20px',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ marginBottom: '20px',
+ paddingBottom: '16px',
+ borderBottom: `1px solid ${COLORS.BORDER}`
+ }}>
+ <div style={{
+ width: '36px',
+ height: '36px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: `${COLORS.ORANGE}20`,
+ border: `1px solid ${COLORS.ORANGE}40`
+ }}>
+ <KeyRound size={18} color={COLORS.ORANGE} />
+ </div>
+ <div>
+ <h3 style={{ color: COLORS.WHITE, fontSize: '13px', fontWeight: 600, margin: 0 }}>
+ CONNECT TO {metadata.displayName.toUpperCase()}
+ </h3>
+ <p style={{ color: COLORS.GRAY, fontSize: '10px', margin: '4px 0 0 0' }}>
+ {metadata.authType === 'oauth' ? 'OAuth 2.0 Authentication' : 'API Credentials'}
+ </p>
+ </div>
+ </div>
+
+ {/* Error display */}
+ {error && (
+ <div style={{
+ marginBottom: '16px',
+ padding: '12px',
+ backgroundColor: `${COLORS.RED}15`,
+ border: `1px solid ${COLORS.RED}40`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px'
+ }}>
+ <AlertCircle size={16} color={COLORS.RED} />
+ <p style={{ color: COLORS.RED, fontSize: '11px', margin: 0 }}>{error}</p>
+ </div>
+ )}
+
+ {/* OAuth Flow */}
+ {metadata.authType === 'oauth' && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ <p style={{ color: COLORS.GRAY, fontSize: '11px', margin: 0, lineHeight: 1.6 }}>
+ Click the button below to authenticate with {metadata.displayName}. You will be redirected to their login page.
+ </p>
+
+ <button
+ onClick={handleOAuthLogin}
+ disabled={isConnecting}
+ style={{
+ width: '100%',
+ padding: '12px 16px',
+ backgroundColor: isConnecting ? COLORS.MUTED : COLORS.ORANGE,
+ border: 'none',
+ color: isConnecting ? COLORS.GRAY : COLORS.DARK_BG,
+ fontSize: '11px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ letterSpacing: '0.5px',
+ cursor: isConnecting ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px'
+ }}
+ >
+ {isConnecting ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : (
+ <ExternalLink size={14} />
+ )}
+ LOGIN WITH {metadata.displayName.toUpperCase()}
+ </button>
+
+ {/* Callback URL Input */}
+ {showCallbackInput && (
+ <div style={{
+ marginTop: '8px',
+ padding: '16px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`
+ }}>
+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '10px', marginBottom: '12px' }}>
+ <AlertCircle size={16} color={COLORS.ORANGE} style={{ flexShrink: 0, marginTop: '2px' }} />
+ <div>
+ <p style={{ color: COLORS.WHITE, fontSize: '11px', fontWeight: 600, margin: '0 0 4px 0' }}>
+ PASTE CALLBACK URL
+ </p>
+ <p style={{ color: COLORS.GRAY, fontSize: '9px', margin: 0 }}>
+ After authorizing on {metadata.displayName}, copy the URL from your browser's address bar and paste it below.
+ </p>
+ </div>
+ </div>
+
+ <input
+ type="text"
+ value={callbackUrl}
+ onChange={(e) => setCallbackUrl(e.target.value)}
+ placeholder="https://127.0.0.1/?auth_code=..."
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '11px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ marginBottom: '12px'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+
+ <button
+ onClick={handleCallbackSubmit}
+ disabled={!callbackUrl || isConnecting}
+ style={{
+ width: '100%',
+ padding: '10px 16px',
+ backgroundColor: !callbackUrl || isConnecting ? COLORS.MUTED : COLORS.GREEN,
+ border: 'none',
+ color: !callbackUrl || isConnecting ? COLORS.GRAY : COLORS.DARK_BG,
+ fontSize: '11px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ cursor: !callbackUrl || isConnecting ? 'not-allowed' : 'pointer'
+ }}
+ >
+ COMPLETE AUTHENTICATION
+ </button>
+ </div>
+ )}
+
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', textAlign: 'center', margin: 0 }}>
+ You'll be redirected to {metadata.website} to authorize access
+ </p>
+ </div>
+ )}
+
+ {/* Credential-based Flow */}
+ {metadata.authType !== 'oauth' && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* API Key */}
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ API KEY
+ </label>
+ <input
+ type="text"
+ value={credentials.apiKey}
+ onChange={(e) => setCredentials({ ...credentials, apiKey: e.target.value })}
+ placeholder="Enter your API key"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ </div>
+
+ {/* API Secret */}
+ {metadata.authType === 'api_key' && (
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ API SECRET
+ </label>
+ <div style={{ position: 'relative' }}>
+ <input
+ type={showCredentials ? 'text' : 'password'}
+ value={credentials.apiSecret || ''}
+ onChange={(e) => setCredentials({ ...credentials, apiSecret: e.target.value })}
+ placeholder="Enter your API secret"
+ style={{
+ width: '100%',
+ padding: '10px 40px 10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ <button
+ type="button"
+ onClick={() => setShowCredentials(!showCredentials)}
+ style={{
+ position: 'absolute',
+ right: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'none',
+ border: 'none',
+ color: COLORS.GRAY,
+ cursor: 'pointer',
+ padding: '4px'
+ }}
+ >
+ {showCredentials ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* TOTP auth fields (Angel One style) */}
+ {metadata.authType === 'totp' && (
+ <>
+ {/* Client Code / User ID */}
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ CLIENT CODE / USER ID
+ </label>
+ <input
+ type="text"
+ value={credentials.userId || ''}
+ onChange={(e) => setCredentials({ ...credentials, userId: e.target.value })}
+ placeholder="Enter your client code"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ </div>
+
+ {/* Password */}
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ PASSWORD
+ </label>
+ <div style={{ position: 'relative' }}>
+ <input
+ type={showCredentials ? 'text' : 'password'}
+ value={credentials.password || ''}
+ onChange={(e) => setCredentials({ ...credentials, password: e.target.value })}
+ placeholder="Enter your password"
+ style={{
+ width: '100%',
+ padding: '10px 40px 10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ <button
+ type="button"
+ onClick={() => setShowCredentials(!showCredentials)}
+ style={{
+ position: 'absolute',
+ right: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'none',
+ border: 'none',
+ color: COLORS.GRAY,
+ cursor: 'pointer',
+ padding: '4px'
+ }}
+ >
+ {showCredentials ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ </div>
+
+ {/* TOTP Code */}
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ TOTP CODE
+ </label>
+ <input
+ type="text"
+ value={credentials.pin || ''}
+ onChange={(e) => setCredentials({ ...credentials, pin: e.target.value })}
+ placeholder="Enter 6-digit TOTP code"
+ maxLength={6}
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box',
+ letterSpacing: '4px',
+ textAlign: 'center'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>
+ Enter the 6-digit code from your authenticator app
+ </p>
+ </div>
+ </>
+ )}
+
+ {/* Password auth fields */}
+ {metadata.authType === 'password' && (
+ <>
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ USER ID
+ </label>
+ <input
+ type="text"
+ value={credentials.userId || ''}
+ onChange={(e) => setCredentials({ ...credentials, userId: e.target.value })}
+ placeholder="Enter your user ID"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ </div>
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ PASSWORD
+ </label>
+ <input
+ type="password"
+ value={credentials.password || ''}
+ onChange={(e) => setCredentials({ ...credentials, password: e.target.value })}
+ placeholder="Enter your password"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ </div>
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ TRADING PIN
+ </label>
+ <input
+ type="password"
+ value={credentials.pin || ''}
+ onChange={(e) => setCredentials({ ...credentials, pin: e.target.value })}
+ placeholder="Enter your trading PIN"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ </div>
+ </>
+ )}
+
+ <button
+ onClick={handleCredentialLogin}
+ disabled={isConnecting || !credentials.apiKey}
+ style={{
+ width: '100%',
+ padding: '12px 16px',
+ backgroundColor: isConnecting || !credentials.apiKey ? COLORS.MUTED : COLORS.ORANGE,
+ border: 'none',
+ color: isConnecting || !credentials.apiKey ? COLORS.GRAY : COLORS.DARK_BG,
+ fontSize: '11px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ letterSpacing: '0.5px',
+ cursor: isConnecting || !credentials.apiKey ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ marginTop: '8px'
+ }}
+ >
+ {isConnecting ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : (
+ <Lock size={14} />
+ )}
+ CONNECT BROKER
+ </button>
+ </div>
+ )}
+
+ {/* Security Note */}
+ <div style={{
+ marginTop: '20px',
+ padding: '12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`
+ }}>
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', margin: 0, lineHeight: 1.6 }}>
+ Your credentials are stored securely on your local device and are never sent to our servers.
+ We only communicate directly with {metadata.displayName}'s API.
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerConfigPanel.tsx
new file mode 100644
index 000000000..8108e428e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerConfigPanel.tsx
@@ -0,0 +1,454 @@
+/**
+ * Broker Configuration Panel - Bloomberg Style
+ *
+ * Handles broker API key configuration before authentication
+ * Required for OAuth brokers like Zerodha and Fyers
+ */
+
+import React, { useState, useEffect } from 'react';
+import { Settings, Save, Eye, EyeOff, AlertCircle, CheckCircle2, ExternalLink, HelpCircle, Loader2 } from 'lucide-react';
+import { useStockBrokerSelection, useStockBrokerContext } from '@/contexts/StockBrokerContext';
+import { createStockBrokerAdapter } from '@/brokers/stocks';
+import type { BrokerCredentials } from '@/brokers/stocks/types';
+
+// Bloomberg color palette
+const COLORS = {
+ ORANGE: '#FF8800',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ GRAY: '#787878',
+ MUTED: '#4A4A4A',
+ WHITE: '#FFFFFF',
+};
+
+interface BrokerConfigPanelProps {
+ onConfigSaved?: () => void;
+}
+
+export function BrokerConfigPanel({ onConfigSaved }: BrokerConfigPanelProps) {
+ const { metadata, broker, setBroker } = useStockBrokerSelection();
+ const { adapter } = useStockBrokerContext();
+
+ const [showSecret, setShowSecret] = useState(false);
+ const [config, setConfig] = useState<BrokerCredentials>({
+ apiKey: '',
+ apiSecret: '',
+ });
+ const [isSaving, setIsSaving] = useState(false);
+ const [saveSuccess, setSaveSuccess] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Debug: Log adapter availability
+ useEffect(() => {
+ console.log('[BrokerConfigPanel] Component mounted/updated', {
+ hasMetadata: !!metadata,
+ metadataId: metadata?.id,
+ hasAdapter: !!adapter,
+ adapterType: adapter?.constructor.name,
+ hasSetCredentials: !!(adapter && adapter.setCredentials),
+ });
+ }, [adapter, metadata]);
+
+ // Load existing config on mount
+ useEffect(() => {
+ if (adapter) {
+ setConfig({
+ apiKey: '',
+ apiSecret: '',
+ });
+ }
+ }, [adapter, metadata?.id]);
+
+ const handleSave = async () => {
+ setError(null);
+ setSaveSuccess(false);
+
+ // Validation
+ if (!config.apiKey?.trim()) {
+ setError('API Key is required');
+ return;
+ }
+
+ if (metadata?.authType === 'oauth' && !config.apiSecret?.trim()) {
+ setError('API Secret is required for OAuth brokers');
+ return;
+ }
+
+ if (!metadata) {
+ setError('No broker selected');
+ return;
+ }
+
+ setIsSaving(true);
+
+ try {
+ console.log('[BrokerConfigPanel] === SAVE CONFIGURATION STARTED ===');
+
+ // Get or create adapter
+ let adapterToUse = adapter;
+
+ if (!adapterToUse) {
+ console.log('[BrokerConfigPanel] Creating temporary adapter for configuration');
+ adapterToUse = createStockBrokerAdapter(metadata.id);
+ }
+
+ // Set credentials on the adapter
+ if (!adapterToUse.setCredentials) {
+ throw new Error(`${metadata.displayName} does not support credential configuration.`);
+ }
+
+ // Store to database FIRST
+ await (adapterToUse as any).storeCredentials({
+ apiKey: config.apiKey,
+ apiSecret: config.apiSecret || '',
+ });
+
+ // THEN set on adapter instance (in-memory)
+ adapterToUse.setCredentials(config.apiKey, config.apiSecret || '');
+
+ // If we created a temporary adapter and broker is selected, re-select
+ if (!adapter && broker) {
+ await setBroker(broker);
+ }
+
+ setSaveSuccess(true);
+ setTimeout(() => setSaveSuccess(false), 3000);
+
+ if (onConfigSaved) {
+ onConfigSaved();
+ }
+ } catch (err) {
+ console.error('[BrokerConfigPanel] Save failed:', err);
+ setError(err instanceof Error ? err.message : 'Failed to save configuration');
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ // Get API credentials URL for the broker
+ const getApiKeysUrl = (brokerId: string) => {
+ const urls: Record<string, string> = {
+ zerodha: 'https://developers.kite.trade/',
+ fyers: 'https://myapi.fyers.in/dashboard',
+ angelone: 'https://smartapi.angelbroking.com/publisher-login',
+ angel: 'https://smartapi.angelbroking.com/',
+ dhan: 'https://dhanhq.co/api',
+ upstox: 'https://upstox.com/developer/api/',
+ };
+ return urls[brokerId] || metadata?.website || '#';
+ };
+
+ if (!metadata) {
+ return (
+ <div style={{
+ padding: '24px',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ textAlign: 'center'
+ }}>
+ <p style={{ color: COLORS.GRAY, fontSize: '11px' }}>Select a broker to configure</p>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ padding: '20px',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '20px',
+ paddingBottom: '16px',
+ borderBottom: `1px solid ${COLORS.BORDER}`
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <div style={{
+ width: '36px',
+ height: '36px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: `${COLORS.ORANGE}20`,
+ border: `1px solid ${COLORS.ORANGE}40`
+ }}>
+ <Settings size={18} color={COLORS.ORANGE} />
+ </div>
+ <div>
+ <h3 style={{ color: COLORS.WHITE, fontSize: '13px', fontWeight: 600, margin: 0 }}>
+ CONFIGURE {metadata.displayName.toUpperCase()}
+ </h3>
+ <p style={{ color: COLORS.GRAY, fontSize: '10px', margin: '4px 0 0 0' }}>
+ Set up your API credentials
+ </p>
+ </div>
+ </div>
+
+ <a
+ href={getApiKeysUrl(metadata.id)}
+ target="_blank"
+ rel="noopener noreferrer"
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontSize: '10px',
+ color: COLORS.ORANGE,
+ textDecoration: 'none',
+ padding: '6px 10px',
+ border: `1px solid ${COLORS.ORANGE}40`,
+ backgroundColor: `${COLORS.ORANGE}10`
+ }}
+ >
+ <HelpCircle size={12} />
+ GET API KEYS
+ <ExternalLink size={10} />
+ </a>
+ </div>
+
+ {/* Success Message */}
+ {saveSuccess && (
+ <div style={{
+ marginBottom: '16px',
+ padding: '12px',
+ backgroundColor: `${COLORS.GREEN}15`,
+ border: `1px solid ${COLORS.GREEN}40`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px'
+ }}>
+ <CheckCircle2 size={16} color={COLORS.GREEN} />
+ <p style={{ color: COLORS.GREEN, fontSize: '11px', margin: 0 }}>Configuration saved successfully!</p>
+ </div>
+ )}
+
+ {/* Error Message */}
+ {error && (
+ <div style={{
+ marginBottom: '16px',
+ padding: '12px',
+ backgroundColor: `${COLORS.RED}15`,
+ border: `1px solid ${COLORS.RED}40`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px'
+ }}>
+ <AlertCircle size={16} color={COLORS.RED} />
+ <p style={{ color: COLORS.RED, fontSize: '11px', margin: 0 }}>{error}</p>
+ </div>
+ )}
+
+ {/* Info Box for OAuth Brokers */}
+ {metadata.authType === 'oauth' && (
+ <div style={{
+ marginBottom: '16px',
+ padding: '14px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`
+ }}>
+ <h4 style={{
+ color: COLORS.WHITE,
+ fontSize: '11px',
+ fontWeight: 600,
+ margin: '0 0 10px 0',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <HelpCircle size={14} color={COLORS.ORANGE} />
+ HOW TO GET YOUR API CREDENTIALS
+ </h4>
+ <ol style={{
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ margin: 0,
+ paddingLeft: '16px',
+ lineHeight: 1.8
+ }}>
+ <li>Visit <a href={getApiKeysUrl(metadata.id)} target="_blank" rel="noopener noreferrer" style={{ color: COLORS.ORANGE }}>{metadata.displayName} Developer Portal</a></li>
+ <li>Create a new app or use an existing one</li>
+ <li>Copy your App ID (API Key) and App Secret</li>
+ <li>Set the redirect URL to: <code style={{ padding: '2px 6px', backgroundColor: COLORS.DARK_BG, color: COLORS.CYAN, fontSize: '9px' }}>http://127.0.0.1/</code></li>
+ <li>Paste your credentials below and save</li>
+ </ol>
+ </div>
+ )}
+
+ {/* Form Fields */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* API Key */}
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ API KEY / APP ID
+ <span style={{ color: COLORS.RED, marginLeft: '4px' }}>*</span>
+ </label>
+ <input
+ type="text"
+ value={config.apiKey}
+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}
+ placeholder={`Enter your ${metadata.displayName} API Key`}
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>
+ {metadata.id === 'zerodha' && 'Your Kite Connect API key'}
+ {metadata.id === 'fyers' && 'Your Fyers App ID'}
+ {metadata.id === 'angelone' && 'Your Angel One Smart API key'}
+ {metadata.id !== 'zerodha' && metadata.id !== 'fyers' && metadata.id !== 'angelone' && 'Your broker API key'}
+ </p>
+ </div>
+
+ {/* API Secret (for OAuth brokers) */}
+ {metadata.authType === 'oauth' && (
+ <div>
+ <label style={{
+ display: 'block',
+ color: COLORS.GRAY,
+ fontSize: '10px',
+ fontWeight: 600,
+ marginBottom: '6px',
+ letterSpacing: '0.5px'
+ }}>
+ API SECRET / APP SECRET
+ <span style={{ color: COLORS.RED, marginLeft: '4px' }}>*</span>
+ </label>
+ <div style={{ position: 'relative' }}>
+ <input
+ type={showSecret ? 'text' : 'password'}
+ value={config.apiSecret || ''}
+ onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}
+ placeholder="Enter your API Secret"
+ style={{
+ width: '100%',
+ padding: '10px 40px 10px 12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none',
+ boxSizing: 'border-box'
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}
+ />
+ <button
+ type="button"
+ onClick={() => setShowSecret(!showSecret)}
+ style={{
+ position: 'absolute',
+ right: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ background: 'none',
+ border: 'none',
+ color: COLORS.GRAY,
+ cursor: 'pointer',
+ padding: '4px'
+ }}
+ >
+ {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}
+ </button>
+ </div>
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '4px' }}>
+ {metadata.id === 'zerodha' && 'Your Kite Connect API secret'}
+ {metadata.id === 'fyers' && 'Your Fyers App Secret'}
+ {metadata.id !== 'zerodha' && metadata.id !== 'fyers' && 'Your broker API secret'}
+ </p>
+ </div>
+ )}
+
+ {/* Save Button */}
+ <button
+ onClick={handleSave}
+ disabled={isSaving || !config.apiKey}
+ style={{
+ width: '100%',
+ padding: '12px 16px',
+ backgroundColor: isSaving || !config.apiKey ? COLORS.MUTED : COLORS.ORANGE,
+ border: 'none',
+ color: isSaving || !config.apiKey ? COLORS.GRAY : COLORS.DARK_BG,
+ fontSize: '11px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ letterSpacing: '0.5px',
+ cursor: isSaving || !config.apiKey ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ marginTop: '8px'
+ }}
+ >
+ {isSaving ? (
+ <>
+ <Loader2 size={14} className="animate-spin" />
+ SAVING...
+ </>
+ ) : (
+ <>
+ <Save size={14} />
+ SAVE CONFIGURATION
+ </>
+ )}
+ </button>
+ </div>
+
+ {/* Security Note */}
+ <div style={{
+ marginTop: '20px',
+ padding: '12px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`
+ }}>
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', margin: 0, lineHeight: 1.6 }}>
+ <strong style={{ color: COLORS.GRAY }}>🔒 SECURITY:</strong> Your API credentials are stored securely on your local device using encrypted storage.
+ They are never sent to our servers and only used to communicate directly with {metadata.displayName}'s API.
+ </p>
+ </div>
+
+ {/* Next Steps */}
+ {metadata.authType === 'oauth' && (
+ <div style={{
+ marginTop: '12px',
+ padding: '12px',
+ backgroundColor: `${COLORS.ORANGE}15`,
+ border: `1px solid ${COLORS.ORANGE}40`
+ }}>
+ <p style={{ color: COLORS.ORANGE, fontSize: '10px', margin: 0 }}>
+ <strong>NEXT STEP:</strong> After saving your configuration, switch to the <strong>AUTHENTICATION</strong> tab to complete the OAuth login flow.
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerSelector.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerSelector.tsx
new file mode 100644
index 000000000..191626171
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerSelector.tsx
@@ -0,0 +1,289 @@
+/**
+ * Stock Broker Selector Component - Bloomberg Style
+ *
+ * Dropdown for selecting stock brokers with region grouping
+ */
+
+import React, { useState, useRef, useEffect } from 'react';
+import { ChevronDown, Check, Globe, Building2 } from 'lucide-react';
+import { useStockBrokerSelection } from '@/contexts/StockBrokerContext';
+import type { Region, StockBrokerMetadata } from '@/brokers/stocks/types';
+
+// Bloomberg color palette
+const COLORS = {
+ ORANGE: '#FF8800',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ HOVER_BG: '#252525',
+ BORDER: '#2A2A2A',
+ GRAY: '#787878',
+ MUTED: '#4A4A4A',
+ WHITE: '#FFFFFF',
+};
+
+const REGION_LABELS: Record<Region, string> = {
+ india: 'INDIA',
+ us: 'UNITED STATES',
+ europe: 'EUROPE',
+ uk: 'UNITED KINGDOM',
+ asia: 'ASIA PACIFIC',
+ australia: 'AUSTRALIA',
+ canada: 'CANADA',
+};
+
+const REGION_FLAGS: Record<Region, string> = {
+ india: '🇮🇳',
+ us: '🇺🇸',
+ europe: '🇪🇺',
+ uk: '🇬🇧',
+ asia: '🌏',
+ australia: '🇦🇺',
+ canada: '🇨🇦',
+};
+
+interface BrokerSelectorProps {
+ className?: string;
+}
+
+export function BrokerSelector({ className = '' }: BrokerSelectorProps) {
+ const { broker, metadata, brokers, setBroker, isLoading } = useStockBrokerSelection();
+ const [isOpen, setIsOpen] = useState(false);
+ const [hoveredBroker, setHoveredBroker] = useState<string | null>(null);
+ const dropdownRef = useRef<HTMLDivElement>(null);
+
+ // Group brokers by region
+ const brokersByRegion = React.useMemo(() => {
+ const grouped: Record<Region, StockBrokerMetadata[]> = {
+ india: [],
+ us: [],
+ europe: [],
+ uk: [],
+ asia: [],
+ australia: [],
+ canada: [],
+ };
+
+ brokers.forEach((b) => {
+ if (grouped[b.region]) {
+ grouped[b.region].push(b);
+ }
+ });
+
+ return grouped;
+ }, [brokers]);
+
+ // Close dropdown on outside click
+ useEffect(() => {
+ function handleClickOutside(event: MouseEvent) {
+ if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
+ setIsOpen(false);
+ }
+ }
+
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }, []);
+
+ const handleSelect = async (brokerId: string) => {
+ try {
+ await setBroker(brokerId);
+ setIsOpen(false);
+ } catch (err) {
+ console.error('Failed to set broker:', err);
+ }
+ };
+
+ return (
+ <div style={{ position: 'relative' }} ref={dropdownRef}>
+ <button
+ onClick={() => setIsOpen(!isOpen)}
+ disabled={isLoading}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '5px 12px',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${isOpen ? COLORS.ORANGE : COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ minWidth: '180px',
+ opacity: isLoading ? 0.6 : 1,
+ transition: 'all 0.15s ease'
+ }}
+ onMouseEnter={(e) => {
+ if (!isOpen) e.currentTarget.style.borderColor = COLORS.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ if (!isOpen) e.currentTarget.style.borderColor = COLORS.BORDER;
+ }}
+ >
+ <Building2 size={14} color={COLORS.ORANGE} />
+ <span style={{
+ flex: 1,
+ textAlign: 'left',
+ fontSize: '11px',
+ fontWeight: 600,
+ fontFamily: '"IBM Plex Mono", monospace',
+ color: metadata ? COLORS.WHITE : COLORS.GRAY,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap'
+ }}>
+ {metadata ? metadata.displayName.toUpperCase() : 'SELECT BROKER'}
+ </span>
+ {metadata && (
+ <span style={{ fontSize: '12px' }}>
+ {REGION_FLAGS[metadata.region]}
+ </span>
+ )}
+ <ChevronDown
+ size={12}
+ color={COLORS.GRAY}
+ style={{
+ transition: 'transform 0.15s ease',
+ transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)'
+ }}
+ />
+ </button>
+
+ {isOpen && (
+ <div style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ marginTop: '4px',
+ width: '280px',
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ boxShadow: `0 4px 16px ${COLORS.DARK_BG}80`,
+ zIndex: 1000,
+ maxHeight: '400px',
+ overflowY: 'auto'
+ }}>
+ {Object.entries(brokersByRegion).map(([region, regionBrokers]) => {
+ if (regionBrokers.length === 0) return null;
+
+ return (
+ <div key={region}>
+ {/* Region Header */}
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: COLORS.DARK_BG,
+ borderBottom: `1px solid ${COLORS.BORDER}`,
+ position: 'sticky',
+ top: 0,
+ zIndex: 1
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ color: COLORS.GRAY,
+ letterSpacing: '0.5px'
+ }}>
+ <Globe size={10} color={COLORS.GRAY} />
+ <span>{REGION_FLAGS[region as Region]}</span>
+ <span>{REGION_LABELS[region as Region]}</span>
+ </div>
+ </div>
+
+ {/* Brokers in this region */}
+ {regionBrokers.map((b) => {
+ const isSelected = broker === b.id;
+ const isHovered = hoveredBroker === b.id;
+
+ return (
+ <button
+ key={b.id}
+ onClick={() => handleSelect(b.id)}
+ onMouseEnter={() => setHoveredBroker(b.id)}
+ onMouseLeave={() => setHoveredBroker(null)}
+ style={{
+ width: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ padding: '10px 12px',
+ backgroundColor: isSelected ? `${COLORS.ORANGE}15` : isHovered ? COLORS.HOVER_BG : 'transparent',
+ border: 'none',
+ borderLeft: isSelected ? `3px solid ${COLORS.ORANGE}` : '3px solid transparent',
+ cursor: 'pointer',
+ transition: 'all 0.1s ease'
+ }}
+ >
+ {/* Logo placeholder */}
+ <div style={{
+ width: '28px',
+ height: '28px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: isSelected ? `${COLORS.ORANGE}30` : COLORS.HEADER_BG,
+ border: `1px solid ${isSelected ? COLORS.ORANGE : COLORS.BORDER}`,
+ fontSize: '10px',
+ fontWeight: 700,
+ color: isSelected ? COLORS.ORANGE : COLORS.GRAY,
+ flexShrink: 0
+ }}>
+ {b.name.substring(0, 2).toUpperCase()}
+ </div>
+
+ {/* Broker info */}
+ <div style={{ flex: 1, textAlign: 'left', overflow: 'hidden' }}>
+ <div style={{
+ fontSize: '11px',
+ fontWeight: 600,
+ color: isSelected ? COLORS.ORANGE : COLORS.WHITE,
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis'
+ }}>
+ {b.displayName}
+ </div>
+ <div style={{
+ fontSize: '9px',
+ color: COLORS.MUTED,
+ marginTop: '2px',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis'
+ }}>
+ {b.exchanges.slice(0, 3).join(' • ')}
+ {b.exchanges.length > 3 && ` +${b.exchanges.length - 3}`}
+ </div>
+ </div>
+
+ {/* Selected check */}
+ {isSelected && (
+ <Check size={14} color={COLORS.GREEN} style={{ flexShrink: 0 }} />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+ })}
+
+ {brokers.length === 0 && (
+ <div style={{
+ padding: '24px 16px',
+ textAlign: 'center',
+ color: COLORS.GRAY,
+ fontSize: '11px'
+ }}>
+ No brokers available
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerSetupPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerSetupPanel.tsx
new file mode 100644
index 000000000..9279f0585
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokerSetupPanel.tsx
@@ -0,0 +1,128 @@
+/**
+ * Broker Setup Panel - Bloomberg Style
+ *
+ * Combined panel showing both Configuration and Authentication tabs
+ */
+
+import React, { useState } from 'react';
+import { Settings, KeyRound } from 'lucide-react';
+import { BrokerConfigPanel } from './BrokerConfigPanel';
+import { BrokerAuthPanel } from './BrokerAuthPanel';
+
+// Bloomberg color palette
+const COLORS = {
+ ORANGE: '#FF8800',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ CYAN: '#00E5FF',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ GRAY: '#787878',
+ MUTED: '#4A4A4A',
+ WHITE: '#FFFFFF',
+};
+
+type SetupTab = 'config' | 'auth';
+
+export function BrokerSetupPanel() {
+ const [activeTab, setActiveTab] = useState<SetupTab>('config');
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* Tab Navigation */}
+ <div style={{
+ display: 'flex',
+ gap: '0',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ padding: '2px'
+ }}>
+ <button
+ onClick={() => setActiveTab('config')}
+ style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ padding: '10px 16px',
+ backgroundColor: activeTab === 'config' ? COLORS.ORANGE : 'transparent',
+ border: 'none',
+ color: activeTab === 'config' ? COLORS.DARK_BG : COLORS.GRAY,
+ cursor: 'pointer',
+ fontSize: '11px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ letterSpacing: '0.5px',
+ transition: 'all 0.15s ease'
+ }}
+ onMouseEnter={(e) => {
+ if (activeTab !== 'config') {
+ e.currentTarget.style.backgroundColor = COLORS.HEADER_BG;
+ e.currentTarget.style.color = COLORS.WHITE;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (activeTab !== 'config') {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = COLORS.GRAY;
+ }
+ }}
+ >
+ <Settings size={14} />
+ CONFIGURATION
+ </button>
+ <button
+ onClick={() => setActiveTab('auth')}
+ style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ padding: '10px 16px',
+ backgroundColor: activeTab === 'auth' ? COLORS.ORANGE : 'transparent',
+ border: 'none',
+ color: activeTab === 'auth' ? COLORS.DARK_BG : COLORS.GRAY,
+ cursor: 'pointer',
+ fontSize: '11px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ letterSpacing: '0.5px',
+ transition: 'all 0.15s ease'
+ }}
+ onMouseEnter={(e) => {
+ if (activeTab !== 'auth') {
+ e.currentTarget.style.backgroundColor = COLORS.HEADER_BG;
+ e.currentTarget.style.color = COLORS.WHITE;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (activeTab !== 'auth') {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = COLORS.GRAY;
+ }
+ }}
+ >
+ <KeyRound size={14} />
+ AUTHENTICATION
+ </button>
+ </div>
+
+ {/* Tab Content */}
+ <div>
+ {activeTab === 'config' && (
+ <BrokerConfigPanel
+ onConfigSaved={() => {
+ // Auto-switch to auth tab after successful config
+ setTimeout(() => setActiveTab('auth'), 1500);
+ }}
+ />
+ )}
+ {activeTab === 'auth' && <BrokerAuthPanel />}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/FundsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/FundsPanel.tsx
new file mode 100644
index 000000000..c2d50266c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/FundsPanel.tsx
@@ -0,0 +1,235 @@
+/**
+ * Funds Panel Component
+ *
+ * Displays account funds and margin information
+ */
+
+import React from 'react';
+import { RefreshCw, Wallet, TrendingUp, TrendingDown, DollarSign, Shield, PieChart } from 'lucide-react';
+import { useStockTradingData, useStockBrokerSelection } from '@/contexts/StockBrokerContext';
+
+interface FundsPanelProps {
+ compact?: boolean;
+}
+
+export function FundsPanel({ compact = false }: FundsPanelProps) {
+ const { funds, refreshFunds, isRefreshing, isReady } = useStockTradingData();
+ const { metadata } = useStockBrokerSelection();
+
+ if (!isReady) {
+ return (
+ <div className="p-4 bg-[#1A1A1A] rounded-lg border border-[#2A2A2A]">
+ <p className="text-sm text-gray-500 text-center">Connect to view funds</p>
+ </div>
+ );
+ }
+
+ if (!funds) {
+ return (
+ <div className="p-4 bg-[#1A1A1A] rounded-lg border border-[#2A2A2A]">
+ <div className="flex items-center justify-between mb-3">
+ <h3 className="text-sm font-medium text-white">Funds</h3>
+ <button
+ onClick={() => refreshFunds()}
+ disabled={isRefreshing}
+ className="p-1 text-gray-400 hover:text-white"
+ >
+ <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
+ </button>
+ </div>
+ <p className="text-sm text-gray-500 text-center">Loading funds...</p>
+ </div>
+ );
+ }
+
+ // Calculate utilization percentage
+ const utilizationPercent = funds.totalBalance > 0
+ ? (funds.usedMargin / funds.totalBalance) * 100
+ : 0;
+
+ // Currency symbol
+ const currency = metadata?.currency || 'INR';
+ const formatCurrency = (value: number) =>
+ value.toLocaleString('en-IN', { style: 'currency', currency, minimumFractionDigits: 2 });
+
+ if (compact) {
+ return (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '8px',
+ width: '100%',
+ overflow: 'hidden'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0, flex: 1 }}>
+ <Wallet size={12} color="#FF8800" style={{ flexShrink: 0 }} />
+ <span style={{ fontSize: '9px', color: '#787878', whiteSpace: 'nowrap' }}>Available:</span>
+ <span style={{ fontSize: '10px', fontFamily: 'monospace', color: '#00D66F', fontWeight: 600, whiteSpace: 'nowrap' }}>
+ ₹{funds.availableCash.toLocaleString('en-IN', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}
+ </span>
+ </div>
+ <div style={{ width: '1px', height: '12px', backgroundColor: '#2A2A2A', flexShrink: 0 }} />
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0 }}>
+ <span style={{ fontSize: '9px', color: '#787878', whiteSpace: 'nowrap' }}>Margin:</span>
+ <span style={{ fontSize: '10px', fontFamily: 'monospace', color: '#FF8800', fontWeight: 600, whiteSpace: 'nowrap' }}>
+ ₹{funds.usedMargin.toLocaleString('en-IN', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}
+ </span>
+ </div>
+ <button
+ onClick={() => refreshFunds()}
+ disabled={isRefreshing}
+ style={{
+ padding: '2px',
+ background: 'none',
+ border: 'none',
+ cursor: 'pointer',
+ color: '#787878',
+ flexShrink: 0
+ }}
+ >
+ <RefreshCw size={10} className={isRefreshing ? 'animate-spin' : ''} />
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="bg-[#1A1A1A] rounded-lg border border-[#2A2A2A] overflow-hidden">
+ {/* Header */}
+ <div className="px-4 py-3 border-b border-[#2A2A2A] flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Wallet className="w-4 h-4 text-[#FF8800]" />
+ <h3 className="text-sm font-medium text-white">Funds & Margin</h3>
+ </div>
+ <button
+ onClick={() => refreshFunds()}
+ disabled={isRefreshing}
+ className="p-1.5 text-gray-400 hover:text-white hover:bg-[#2A2A2A] rounded-md transition-colors"
+ >
+ <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
+ </button>
+ </div>
+
+ <div className="p-4 space-y-4">
+ {/* Main Balance */}
+ <div className="grid grid-cols-2 gap-4">
+ <div className="p-3 bg-[#0F0F0F] rounded-lg">
+ <div className="flex items-center gap-2 mb-1">
+ <DollarSign className="w-3.5 h-3.5 text-gray-500" />
+ <span className="text-xs text-gray-400">Total Balance</span>
+ </div>
+ <p className="text-lg font-mono text-white">{formatCurrency(funds.totalBalance)}</p>
+ </div>
+
+ <div className="p-3 bg-[#0F0F0F] rounded-lg">
+ <div className="flex items-center gap-2 mb-1">
+ <Wallet className="w-3.5 h-3.5 text-[#00D66F]" />
+ <span className="text-xs text-gray-400">Available Cash</span>
+ </div>
+ <p className="text-lg font-mono text-[#00D66F]">{formatCurrency(funds.availableCash)}</p>
+ </div>
+ </div>
+
+ {/* Margin Details */}
+ <div className="space-y-3">
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-gray-400">Used Margin</span>
+ <span className="font-mono text-[#FF8800]">{formatCurrency(funds.usedMargin)}</span>
+ </div>
+
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-gray-400">Available Margin</span>
+ <span className="font-mono text-white">{formatCurrency(funds.availableMargin)}</span>
+ </div>
+
+ {/* Margin Utilization Bar */}
+ <div>
+ <div className="flex items-center justify-between text-xs mb-1">
+ <span className="text-gray-500">Margin Utilization</span>
+ <span className={`${
+ utilizationPercent > 80 ? 'text-[#FF3B3B]' :
+ utilizationPercent > 50 ? 'text-[#FF8800]' :
+ 'text-[#00D66F]'
+ }`}>
+ {utilizationPercent.toFixed(1)}%
+ </span>
+ </div>
+ <div className="h-2 bg-[#0F0F0F] rounded-full overflow-hidden">
+ <div
+ className={`h-full transition-all duration-300 ${
+ utilizationPercent > 80 ? 'bg-[#FF3B3B]' :
+ utilizationPercent > 50 ? 'bg-[#FF8800]' :
+ 'bg-[#00D66F]'
+ }`}
+ style={{ width: `${Math.min(utilizationPercent, 100)}%` }}
+ />
+ </div>
+ </div>
+ </div>
+
+ {/* Segment-wise (if available) */}
+ {(funds.equityAvailable !== undefined || funds.commodityAvailable !== undefined) && (
+ <div className="pt-3 border-t border-[#2A2A2A] space-y-2">
+ <p className="text-xs text-gray-500 font-medium mb-2">Segment Breakdown</p>
+ {funds.equityAvailable !== undefined && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-gray-400">Equity</span>
+ <span className="font-mono text-white">{formatCurrency(funds.equityAvailable)}</span>
+ </div>
+ )}
+ {funds.commodityAvailable !== undefined && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-gray-400">Commodity</span>
+ <span className="font-mono text-white">{formatCurrency(funds.commodityAvailable)}</span>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Collateral (if available) */}
+ {funds.collateral !== undefined && funds.collateral > 0 && (
+ <div className="flex items-center justify-between text-sm pt-3 border-t border-[#2A2A2A]">
+ <div className="flex items-center gap-2">
+ <Shield className="w-3.5 h-3.5 text-blue-400" />
+ <span className="text-gray-400">Collateral</span>
+ </div>
+ <span className="font-mono text-blue-400">{formatCurrency(funds.collateral)}</span>
+ </div>
+ )}
+
+ {/* P&L (if available) */}
+ {(funds.unrealizedPnl !== undefined || funds.realizedPnl !== undefined) && (
+ <div className="pt-3 border-t border-[#2A2A2A] space-y-2">
+ {funds.unrealizedPnl !== undefined && (
+ <div className="flex items-center justify-between text-sm">
+ <div className="flex items-center gap-2">
+ <PieChart className="w-3.5 h-3.5 text-gray-500" />
+ <span className="text-gray-400">Unrealized P&L</span>
+ </div>
+ <span className={`font-mono ${funds.unrealizedPnl >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}>
+ {funds.unrealizedPnl >= 0 ? '+' : ''}{formatCurrency(funds.unrealizedPnl)}
+ </span>
+ </div>
+ )}
+ {funds.realizedPnl !== undefined && (
+ <div className="flex items-center justify-between text-sm">
+ <div className="flex items-center gap-2">
+ {funds.realizedPnl >= 0 ? (
+ <TrendingUp className="w-3.5 h-3.5 text-[#00D66F]" />
+ ) : (
+ <TrendingDown className="w-3.5 h-3.5 text-[#FF3B3B]" />
+ )}
+ <span className="text-gray-400">Realized P&L</span>
+ </div>
+ <span className={`font-mono ${funds.realizedPnl >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}>
+ {funds.realizedPnl >= 0 ? '+' : ''}{formatCurrency(funds.realizedPnl)}
+ </span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/HoldingsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/HoldingsPanel.tsx
new file mode 100644
index 000000000..ce27db5c1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/HoldingsPanel.tsx
@@ -0,0 +1,385 @@
+/**
+ * Holdings Panel Component - Bloomberg Style
+ *
+ * Displays portfolio holdings (long-term investments) with proper scrolling
+ */
+
+import React, { useState } from 'react';
+import { RefreshCw, TrendingUp, TrendingDown, Search, SortAsc, SortDesc, PieChart } from 'lucide-react';
+import { useStockTradingData } from '@/contexts/StockBrokerContext';
+import type { Holding } from '@/brokers/stocks/types';
+
+// Bloomberg color palette
+const COLORS = {
+ ORANGE: '#FF8800',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ GRAY: '#787878',
+ MUTED: '#4A4A4A',
+ WHITE: '#FFFFFF',
+};
+
+type SortField = 'symbol' | 'quantity' | 'investedValue' | 'currentValue' | 'pnl' | 'pnlPercent';
+type SortDirection = 'asc' | 'desc';
+
+interface HoldingsPanelProps {
+ onSell?: (holding: Holding) => void;
+}
+
+export function HoldingsPanel({ onSell }: HoldingsPanelProps) {
+ const { holdings, refreshHoldings, isRefreshing, isReady } = useStockTradingData();
+
+ const [searchQuery, setSearchQuery] = useState('');
+ const [sortField, setSortField] = useState<SortField>('currentValue');
+ const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
+
+ // Calculate totals
+ const totals = React.useMemo(() => {
+ return holdings.reduce(
+ (acc, h) => ({
+ investedValue: acc.investedValue + h.investedValue,
+ currentValue: acc.currentValue + h.currentValue,
+ totalPnl: acc.totalPnl + h.pnl,
+ }),
+ { investedValue: 0, currentValue: 0, totalPnl: 0 }
+ );
+ }, [holdings]);
+
+ const totalPnlPercent = totals.investedValue > 0
+ ? ((totals.currentValue - totals.investedValue) / totals.investedValue) * 100
+ : 0;
+
+ // Filter and sort holdings
+ const filteredHoldings = React.useMemo(() => {
+ let result = [...holdings];
+
+ // Filter by search
+ if (searchQuery) {
+ const query = searchQuery.toLowerCase();
+ result = result.filter(
+ (h) =>
+ h.symbol.toLowerCase().includes(query) ||
+ (h.isin && h.isin.toLowerCase().includes(query))
+ );
+ }
+
+ // Sort
+ result.sort((a, b) => {
+ let aVal = a[sortField];
+ let bVal = b[sortField];
+
+ if (typeof aVal === 'string') {
+ return sortDirection === 'asc'
+ ? aVal.localeCompare(bVal as string)
+ : (bVal as string).localeCompare(aVal);
+ }
+
+ return sortDirection === 'asc'
+ ? (aVal as number) - (bVal as number)
+ : (bVal as number) - (aVal as number);
+ });
+
+ return result;
+ }, [holdings, searchQuery, sortField, sortDirection]);
+
+ // Handle sort click
+ const handleSort = (field: SortField) => {
+ if (sortField === field) {
+ setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
+ } else {
+ setSortField(field);
+ setSortDirection('desc');
+ }
+ };
+
+ // Sort indicator component
+ const SortIndicator = ({ field }: { field: SortField }) => {
+ if (sortField !== field) return null;
+ return sortDirection === 'asc' ? (
+ <SortAsc size={10} color={COLORS.ORANGE} />
+ ) : (
+ <SortDesc size={10} color={COLORS.ORANGE} />
+ );
+ };
+
+ if (!isReady) {
+ return (
+ <div style={{
+ height: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: COLORS.GRAY,
+ fontSize: '11px'
+ }}>
+ Connect to your broker to view holdings
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ backgroundColor: COLORS.PANEL_BG,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {/* Header */}
+ <div style={{
+ padding: '6px 12px',
+ borderBottom: `1px solid ${COLORS.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ backgroundColor: COLORS.HEADER_BG,
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ fontSize: '11px', fontWeight: 600, color: COLORS.WHITE }}>HOLDINGS</span>
+ <span style={{ fontSize: '10px', color: COLORS.GRAY }}>({holdings.length})</span>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ {/* Search */}
+ <div style={{ position: 'relative' }}>
+ <Search size={12} color={COLORS.GRAY} style={{ position: 'absolute', left: '8px', top: '50%', transform: 'translateY(-50%)' }} />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Search..."
+ style={{
+ width: '120px',
+ padding: '4px 8px 4px 26px',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '10px',
+ outline: 'none'
+ }}
+ />
+ </div>
+
+ {/* Refresh */}
+ <button
+ onClick={() => refreshHoldings()}
+ disabled={isRefreshing}
+ style={{
+ padding: '4px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.GRAY,
+ cursor: 'pointer'
+ }}
+ >
+ <RefreshCw size={12} className={isRefreshing ? 'animate-spin' : ''} />
+ </button>
+ </div>
+ </div>
+
+ {/* Portfolio Summary */}
+ {holdings.length > 0 && (
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: COLORS.DARK_BG,
+ borderBottom: `1px solid ${COLORS.BORDER}`,
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '12px',
+ flexShrink: 0
+ }}>
+ <div>
+ <div style={{ fontSize: '9px', color: COLORS.GRAY, marginBottom: '2px' }}>INVESTED</div>
+ <div style={{ fontSize: '11px', fontFamily: 'monospace', color: COLORS.WHITE }}>
+ ₹{totals.investedValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: COLORS.GRAY, marginBottom: '2px' }}>CURRENT</div>
+ <div style={{ fontSize: '11px', fontFamily: 'monospace', color: COLORS.CYAN }}>
+ ₹{totals.currentValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: COLORS.GRAY, marginBottom: '2px' }}>P&L</div>
+ <div style={{
+ fontSize: '11px',
+ fontFamily: 'monospace',
+ color: totals.totalPnl >= 0 ? COLORS.GREEN : COLORS.RED
+ }}>
+ {totals.totalPnl >= 0 ? '+' : ''}₹{totals.totalPnl.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: COLORS.GRAY, marginBottom: '2px' }}>RETURNS</div>
+ <div style={{
+ fontSize: '11px',
+ fontFamily: 'monospace',
+ color: totalPnlPercent >= 0 ? COLORS.GREEN : COLORS.RED
+ }}>
+ {totalPnlPercent >= 0 ? '+' : ''}{totalPnlPercent.toFixed(2)}%
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Holdings Table */}
+ <div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>
+ {filteredHoldings.length === 0 ? (
+ <div style={{
+ padding: '24px',
+ textAlign: 'center',
+ color: COLORS.GRAY
+ }}>
+ <PieChart size={32} color={COLORS.MUTED} style={{ margin: '0 auto 12px' }} />
+ <p style={{ fontSize: '11px' }}>
+ {searchQuery ? 'No holdings match your search' : 'No holdings in your portfolio'}
+ </p>
+ </div>
+ ) : (
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>
+ <thead style={{ position: 'sticky', top: 0, backgroundColor: COLORS.HEADER_BG, zIndex: 1 }}>
+ <tr style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>
+ <th
+ style={{ padding: '6px 8px', textAlign: 'left', color: COLORS.GRAY, fontWeight: 600, cursor: 'pointer' }}
+ onClick={() => handleSort('symbol')}
+ >
+ <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ SYMBOL <SortIndicator field="symbol" />
+ </span>
+ </th>
+ <th
+ style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600, cursor: 'pointer' }}
+ onClick={() => handleSort('quantity')}
+ >
+ <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '4px' }}>
+ QTY <SortIndicator field="quantity" />
+ </span>
+ </th>
+ <th style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600 }}>AVG</th>
+ <th style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600 }}>LTP</th>
+ <th
+ style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600, cursor: 'pointer' }}
+ onClick={() => handleSort('currentValue')}
+ >
+ <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '4px' }}>
+ VALUE <SortIndicator field="currentValue" />
+ </span>
+ </th>
+ <th
+ style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600, cursor: 'pointer' }}
+ onClick={() => handleSort('pnl')}
+ >
+ <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '4px' }}>
+ P&L <SortIndicator field="pnl" />
+ </span>
+ </th>
+ <th style={{ padding: '6px 8px', textAlign: 'center', color: COLORS.GRAY, fontWeight: 600 }}>ACT</th>
+ </tr>
+ </thead>
+ <tbody>
+ {filteredHoldings.map((holding, idx) => {
+ const isProfit = holding.pnl >= 0;
+
+ return (
+ <tr
+ key={`${holding.symbol}-${holding.exchange}`}
+ style={{
+ borderBottom: `1px solid ${COLORS.BORDER}40`,
+ backgroundColor: idx % 2 === 0 ? 'transparent' : `${COLORS.HEADER_BG}40`
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = COLORS.HEADER_BG}
+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = idx % 2 === 0 ? 'transparent' : `${COLORS.HEADER_BG}40`}
+ >
+ <td style={{ padding: '8px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{
+ width: '18px',
+ height: '18px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: isProfit ? `${COLORS.GREEN}20` : `${COLORS.RED}20`,
+ flexShrink: 0
+ }}>
+ {isProfit ? (
+ <TrendingUp size={10} color={COLORS.GREEN} />
+ ) : (
+ <TrendingDown size={10} color={COLORS.RED} />
+ )}
+ </div>
+ <div>
+ <span style={{ fontSize: '10px', color: COLORS.WHITE, fontWeight: 600 }}>{holding.symbol}</span>
+ <span style={{ fontSize: '9px', color: COLORS.GRAY, marginLeft: '4px' }}>{holding.exchange}</span>
+ </div>
+ </div>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>
+ <span style={{ fontFamily: 'monospace', color: COLORS.WHITE }}>{holding.quantity}</span>
+ {holding.t1Quantity && holding.t1Quantity > 0 && (
+ <div style={{ fontSize: '9px', color: COLORS.ORANGE }}>+{holding.t1Quantity} T1</div>
+ )}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', fontFamily: 'monospace', color: COLORS.WHITE }}>
+ {holding.averagePrice.toFixed(2)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', fontFamily: 'monospace', color: COLORS.YELLOW }}>
+ {holding.lastPrice.toFixed(2)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', fontFamily: 'monospace', color: COLORS.WHITE }}>
+ ₹{holding.currentValue.toLocaleString('en-IN', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>
+ <div style={{
+ fontFamily: 'monospace',
+ color: isProfit ? COLORS.GREEN : COLORS.RED
+ }}>
+ {isProfit ? '+' : ''}{holding.pnl.toFixed(0)}
+ </div>
+ <div style={{
+ fontSize: '9px',
+ color: isProfit ? COLORS.GREEN : COLORS.RED
+ }}>
+ {isProfit ? '+' : ''}{holding.pnlPercent.toFixed(2)}%
+ </div>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <button
+ onClick={() => onSell?.(holding)}
+ style={{
+ padding: '3px 8px',
+ fontSize: '9px',
+ fontWeight: 600,
+ backgroundColor: `${COLORS.RED}20`,
+ color: COLORS.RED,
+ border: `1px solid ${COLORS.RED}40`,
+ cursor: 'pointer'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = `${COLORS.RED}40`;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = `${COLORS.RED}20`;
+ }}
+ >
+ SELL
+ </button>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/MasterContractManager.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/MasterContractManager.tsx
new file mode 100644
index 000000000..e11d88821
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/MasterContractManager.tsx
@@ -0,0 +1,336 @@
+/**
+ * MasterContractManager Component
+ *
+ * Standalone component for managing master contract symbol data.
+ * Can be used in Settings or as a dedicated panel.
+ */
+
+import React, { useState, useEffect } from 'react';
+import { Database, Download, RefreshCw, Check, AlertCircle, Trash2, Clock } from 'lucide-react';
+import {
+ masterContractService,
+ type SupportedBroker,
+ type DownloadResult,
+ getBrokerDisplayName,
+} from '@/services/trading/masterContractService';
+
+// 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',
+ MUTED: '#4A4A4A'
+};
+
+interface BrokerSymbolStatus {
+ brokerId: SupportedBroker;
+ symbolCount: number;
+ lastUpdated: Date | null;
+ isLoading: boolean;
+ error: string | null;
+}
+
+interface MasterContractManagerProps {
+ /** List of brokers to manage */
+ brokers?: SupportedBroker[];
+ /** Compact mode for embedding in other panels */
+ compact?: boolean;
+ /** Callback when symbols are updated */
+ onUpdate?: (brokerId: SupportedBroker, result: DownloadResult) => void;
+}
+
+export function MasterContractManager({
+ brokers = ['angelone', 'fyers', 'zerodha'],
+ compact = false,
+ onUpdate
+}: MasterContractManagerProps) {
+ const [brokerStatus, setBrokerStatus] = useState<Record<string, BrokerSymbolStatus>>({});
+ const [isUpdatingAll, setIsUpdatingAll] = useState(false);
+
+ // Load initial status for all brokers
+ useEffect(() => {
+ const loadStatus = async () => {
+ const status: Record<string, BrokerSymbolStatus> = {};
+
+ for (const brokerId of brokers) {
+ try {
+ const count = await masterContractService.getSymbolCount(brokerId);
+ const cache = await masterContractService.getMasterContractCache(brokerId);
+
+ status[brokerId] = {
+ brokerId,
+ symbolCount: count,
+ lastUpdated: cache ? new Date(cache.last_updated * 1000) : null,
+ isLoading: false,
+ error: null
+ };
+ } catch (error) {
+ status[brokerId] = {
+ brokerId,
+ symbolCount: 0,
+ lastUpdated: null,
+ isLoading: false,
+ error: null
+ };
+ }
+ }
+
+ setBrokerStatus(status);
+ };
+
+ loadStatus();
+ }, [brokers]);
+
+ // Update a single broker
+ const handleUpdateBroker = async (brokerId: SupportedBroker) => {
+ setBrokerStatus(prev => ({
+ ...prev,
+ [brokerId]: { ...prev[brokerId], isLoading: true, error: null }
+ }));
+
+ try {
+ const result = await masterContractService.downloadMasterContract(brokerId);
+
+ setBrokerStatus(prev => ({
+ ...prev,
+ [brokerId]: {
+ ...prev[brokerId],
+ symbolCount: result.symbol_count,
+ lastUpdated: new Date(),
+ isLoading: false,
+ error: result.success ? null : result.message
+ }
+ }));
+
+ onUpdate?.(brokerId, result);
+ } catch (error: any) {
+ setBrokerStatus(prev => ({
+ ...prev,
+ [brokerId]: {
+ ...prev[brokerId],
+ isLoading: false,
+ error: error.message || 'Update failed'
+ }
+ }));
+ }
+ };
+
+ // Update all brokers
+ const handleUpdateAll = async () => {
+ setIsUpdatingAll(true);
+
+ for (const brokerId of brokers) {
+ await handleUpdateBroker(brokerId);
+ }
+
+ setIsUpdatingAll(false);
+ };
+
+ // Format last updated time
+ const formatLastUpdated = (date: Date | null): string => {
+ if (!date) return 'Never';
+
+ const now = new Date();
+ const diff = now.getTime() - date.getTime();
+ const hours = Math.floor(diff / (1000 * 60 * 60));
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) return `${days}d ago`;
+ if (hours > 0) return `${hours}h ago`;
+ return 'Just now';
+ };
+
+ return (
+ <div style={{
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: compact ? '12px' : '16px'
+ }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: compact ? '12px' : '16px',
+ paddingBottom: '12px',
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Database size={compact ? 16 : 20} color={BLOOMBERG.ORANGE} />
+ <span style={{
+ fontSize: compact ? '12px' : '14px',
+ fontWeight: 700,
+ color: BLOOMBERG.WHITE
+ }}>
+ Symbol Database
+ </span>
+ </div>
+
+ <button
+ onClick={handleUpdateAll}
+ disabled={isUpdatingAll}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: BLOOMBERG.ORANGE,
+ border: 'none',
+ color: BLOOMBERG.DARK_BG,
+ cursor: isUpdatingAll ? 'not-allowed' : 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ opacity: isUpdatingAll ? 0.7 : 1
+ }}
+ >
+ {isUpdatingAll ? (
+ <RefreshCw size={12} className="animate-spin" />
+ ) : (
+ <Download size={12} />
+ )}
+ UPDATE ALL
+ </button>
+ </div>
+
+ {/* Broker List */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {brokers.map(brokerId => {
+ const status = brokerStatus[brokerId] || {
+ brokerId,
+ symbolCount: 0,
+ lastUpdated: null,
+ isLoading: false,
+ error: null
+ };
+
+ return (
+ <div
+ key={brokerId}
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ padding: '10px 12px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`
+ }}
+ >
+ {/* Broker Info */}
+ <div style={{ flex: 1 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{
+ fontSize: '12px',
+ fontWeight: 600,
+ color: BLOOMBERG.WHITE
+ }}>
+ {getBrokerDisplayName(brokerId)}
+ </span>
+ {status.error && (
+ <AlertCircle size={12} color={BLOOMBERG.RED} />
+ )}
+ </div>
+ <div style={{
+ display: 'flex',
+ gap: '12px',
+ marginTop: '4px',
+ fontSize: '10px',
+ color: BLOOMBERG.GRAY
+ }}>
+ <span>
+ {status.symbolCount > 0
+ ? `${status.symbolCount.toLocaleString()} symbols`
+ : 'No data'
+ }
+ </span>
+ <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <Clock size={10} />
+ {formatLastUpdated(status.lastUpdated)}
+ </span>
+ </div>
+ {status.error && (
+ <div style={{
+ fontSize: '9px',
+ color: BLOOMBERG.RED,
+ marginTop: '4px'
+ }}>
+ {status.error}
+ </div>
+ )}
+ </div>
+
+ {/* Update Button */}
+ <button
+ onClick={() => handleUpdateBroker(brokerId)}
+ disabled={status.isLoading}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${status.isLoading ? BLOOMBERG.MUTED : BLOOMBERG.CYAN}`,
+ color: status.isLoading ? BLOOMBERG.MUTED : BLOOMBERG.CYAN,
+ cursor: status.isLoading ? 'not-allowed' : 'pointer',
+ fontSize: '9px',
+ fontWeight: 600,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ {status.isLoading ? (
+ <>
+ <RefreshCw size={10} className="animate-spin" />
+ UPDATING...
+ </>
+ ) : status.symbolCount > 0 ? (
+ <>
+ <RefreshCw size={10} />
+ REFRESH
+ </>
+ ) : (
+ <>
+ <Download size={10} />
+ DOWNLOAD
+ </>
+ )}
+ </button>
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Info Text */}
+ <div style={{
+ marginTop: '12px',
+ padding: '8px',
+ backgroundColor: BLOOMBERG.DARK_BG,
+ fontSize: '9px',
+ color: BLOOMBERG.MUTED,
+ lineHeight: 1.4
+ }}>
+ Symbol data is cached locally for fast offline search.
+ Update daily to get latest instruments including new F&O expiries.
+ Angel One: ~70k symbols | Fyers: ~100k symbols
+ </div>
+
+ {/* Spinner animation CSS */}
+ <style>{`
+ @keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+ }
+ .animate-spin {
+ animation: spin 1s linear infinite;
+ }
+ `}</style>
+ </div>
+ );
+}
+
+export default MasterContractManager;
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/OrdersPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/OrdersPanel.tsx
new file mode 100644
index 000000000..17d63eead
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/OrdersPanel.tsx
@@ -0,0 +1,441 @@
+/**
+ * Orders Panel Component - Bloomberg Style
+ *
+ * Displays open orders and order history with actions
+ */
+
+import React, { useState } from 'react';
+import {
+ RefreshCw, X, Clock, CheckCircle2, XCircle, AlertCircle,
+ Loader2, Edit2, Filter, FileText
+} from 'lucide-react';
+import { useStockTradingData, useStockBrokerContext } from '@/contexts/StockBrokerContext';
+import type { Order, OrderStatus } from '@/brokers/stocks/types';
+
+// Bloomberg color palette
+const COLORS = {
+ ORANGE: '#FF8800',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ PURPLE: '#A855F7',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ GRAY: '#787878',
+ MUTED: '#4A4A4A',
+ WHITE: '#FFFFFF',
+};
+
+const STATUS_CONFIG: Record<OrderStatus, { label: string; color: string; icon: React.ElementType }> = {
+ PENDING: { label: 'PENDING', color: COLORS.YELLOW, icon: Clock },
+ OPEN: { label: 'OPEN', color: COLORS.CYAN, icon: Clock },
+ PARTIALLY_FILLED: { label: 'PARTIAL', color: COLORS.ORANGE, icon: Clock },
+ FILLED: { label: 'FILLED', color: COLORS.GREEN, icon: CheckCircle2 },
+ CANCELLED: { label: 'CANCELLED', color: COLORS.GRAY, icon: XCircle },
+ REJECTED: { label: 'REJECTED', color: COLORS.RED, icon: XCircle },
+ EXPIRED: { label: 'EXPIRED', color: COLORS.MUTED, icon: AlertCircle },
+ TRIGGER_PENDING: { label: 'TRIGGER', color: COLORS.PURPLE, icon: Clock },
+};
+
+interface OrdersPanelProps {
+ showHistory?: boolean;
+ onModifyOrder?: (order: Order) => void;
+}
+
+export function OrdersPanel({ showHistory = false, onModifyOrder }: OrdersPanelProps) {
+ const { orders, refreshOrders, isRefreshing, isReady } = useStockTradingData();
+ const { adapter } = useStockBrokerContext();
+
+ const [statusFilter, setStatusFilter] = useState<OrderStatus | 'ALL'>('ALL');
+ const [cancellingOrderId, setCancellingOrderId] = useState<string | null>(null);
+ const [isCancellingAll, setIsCancellingAll] = useState(false);
+ const [showFilters, setShowFilters] = useState(false);
+
+ // Filter orders
+ const filteredOrders = React.useMemo(() => {
+ let result = [...orders];
+
+ // Filter by status
+ if (statusFilter !== 'ALL') {
+ result = result.filter((o) => o.status === statusFilter);
+ }
+
+ // If not showing history, only show open/pending orders
+ if (!showHistory) {
+ result = result.filter((o) =>
+ ['PENDING', 'OPEN', 'PARTIALLY_FILLED', 'TRIGGER_PENDING'].includes(o.status)
+ );
+ }
+
+ // Sort by date
+ result.sort((a, b) => new Date(b.placedAt).getTime() - new Date(a.placedAt).getTime());
+
+ return result;
+ }, [orders, statusFilter, showHistory]);
+
+ // Count open orders
+ const openOrdersCount = orders.filter((o) =>
+ ['PENDING', 'OPEN', 'PARTIALLY_FILLED', 'TRIGGER_PENDING'].includes(o.status)
+ ).length;
+
+ // Handle cancel order
+ const handleCancelOrder = async (orderId: string) => {
+ if (!adapter) return;
+
+ setCancellingOrderId(orderId);
+
+ try {
+ const response = await adapter.cancelOrder(orderId);
+ if (response.success) {
+ await refreshOrders();
+ }
+ } catch (err) {
+ console.error('Failed to cancel order:', err);
+ } finally {
+ setCancellingOrderId(null);
+ }
+ };
+
+ // Handle cancel all orders
+ const handleCancelAll = async () => {
+ if (!adapter || openOrdersCount === 0) return;
+
+ setIsCancellingAll(true);
+
+ try {
+ const result = await adapter.cancelAllOrders();
+ if (result.success) {
+ await refreshOrders();
+ }
+ } catch (err) {
+ console.error('Failed to cancel all orders:', err);
+ } finally {
+ setIsCancellingAll(false);
+ }
+ };
+
+ // Format time
+ const formatTime = (date: Date) => {
+ return new Date(date).toLocaleTimeString('en-IN', {
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ hour12: false,
+ });
+ };
+
+ if (!isReady) {
+ return (
+ <div style={{
+ height: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: COLORS.GRAY,
+ fontSize: '11px'
+ }}>
+ Connect to your broker to view orders
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ backgroundColor: COLORS.PANEL_BG,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {/* Header */}
+ <div style={{
+ padding: '6px 12px',
+ borderBottom: `1px solid ${COLORS.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ backgroundColor: COLORS.HEADER_BG,
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ fontSize: '11px', fontWeight: 600, color: COLORS.WHITE }}>
+ {showHistory ? 'ORDER HISTORY' : 'OPEN ORDERS'}
+ </span>
+ <span style={{ fontSize: '10px', color: COLORS.GRAY }}>
+ ({showHistory ? filteredOrders.length : openOrdersCount})
+ </span>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ {/* Filter Toggle */}
+ {showHistory && (
+ <button
+ onClick={() => setShowFilters(!showFilters)}
+ style={{
+ padding: '4px',
+ backgroundColor: showFilters ? `${COLORS.ORANGE}20` : 'transparent',
+ border: `1px solid ${showFilters ? COLORS.ORANGE : COLORS.BORDER}`,
+ color: showFilters ? COLORS.ORANGE : COLORS.GRAY,
+ cursor: 'pointer'
+ }}
+ >
+ <Filter size={12} />
+ </button>
+ )}
+
+ {/* Refresh */}
+ <button
+ onClick={() => refreshOrders()}
+ disabled={isRefreshing}
+ style={{
+ padding: '4px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.GRAY,
+ cursor: 'pointer'
+ }}
+ >
+ <RefreshCw size={12} className={isRefreshing ? 'animate-spin' : ''} />
+ </button>
+
+ {/* Cancel All */}
+ {!showHistory && openOrdersCount > 0 && (
+ <button
+ onClick={handleCancelAll}
+ disabled={isCancellingAll}
+ style={{
+ padding: '3px 8px',
+ fontSize: '9px',
+ fontWeight: 600,
+ backgroundColor: `${COLORS.RED}20`,
+ color: COLORS.RED,
+ border: `1px solid ${COLORS.RED}40`,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ {isCancellingAll ? (
+ <Loader2 size={10} className="animate-spin" />
+ ) : (
+ <X size={10} />
+ )}
+ CANCEL ALL
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* Filters */}
+ {showFilters && showHistory && (
+ <div style={{
+ padding: '6px 12px',
+ backgroundColor: COLORS.DARK_BG,
+ borderBottom: `1px solid ${COLORS.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ flexShrink: 0
+ }}>
+ <span style={{ fontSize: '9px', color: COLORS.GRAY }}>STATUS:</span>
+ <select
+ value={statusFilter}
+ onChange={(e) => setStatusFilter(e.target.value as OrderStatus | 'ALL')}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '10px',
+ outline: 'none',
+ cursor: 'pointer'
+ }}
+ >
+ <option value="ALL">All</option>
+ <option value="FILLED">Filled</option>
+ <option value="CANCELLED">Cancelled</option>
+ <option value="REJECTED">Rejected</option>
+ <option value="EXPIRED">Expired</option>
+ </select>
+ </div>
+ )}
+
+ {/* Orders Table */}
+ <div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>
+ {filteredOrders.length === 0 ? (
+ <div style={{
+ padding: '24px',
+ textAlign: 'center',
+ color: COLORS.GRAY
+ }}>
+ <FileText size={32} color={COLORS.MUTED} style={{ margin: '0 auto 12px' }} />
+ <p style={{ fontSize: '11px' }}>
+ {showHistory ? 'No orders match the filter' : 'No open orders'}
+ </p>
+ </div>
+ ) : (
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>
+ <thead style={{ position: 'sticky', top: 0, backgroundColor: COLORS.HEADER_BG, zIndex: 1 }}>
+ <tr style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>
+ <th style={{ padding: '6px 8px', textAlign: 'left', color: COLORS.GRAY, fontWeight: 600 }}>ORDER</th>
+ <th style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600 }}>QTY</th>
+ <th style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600 }}>PRICE</th>
+ <th style={{ padding: '6px 8px', textAlign: 'center', color: COLORS.GRAY, fontWeight: 600 }}>STATUS</th>
+ <th style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600 }}>TIME</th>
+ <th style={{ padding: '6px 8px', textAlign: 'center', color: COLORS.GRAY, fontWeight: 600 }}>ACT</th>
+ </tr>
+ </thead>
+ <tbody>
+ {filteredOrders.map((order, idx) => {
+ const statusConfig = STATUS_CONFIG[order.status];
+ const StatusIcon = statusConfig.icon;
+ const isCancelling = cancellingOrderId === order.orderId;
+ const canCancel = ['PENDING', 'OPEN', 'TRIGGER_PENDING'].includes(order.status);
+ const canModify = ['PENDING', 'OPEN'].includes(order.status);
+ const isBuy = order.side === 'BUY';
+
+ return (
+ <tr
+ key={order.orderId}
+ style={{
+ borderBottom: `1px solid ${COLORS.BORDER}40`,
+ backgroundColor: idx % 2 === 0 ? 'transparent' : `${COLORS.HEADER_BG}40`
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = COLORS.HEADER_BG}
+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = idx % 2 === 0 ? 'transparent' : `${COLORS.HEADER_BG}40`}
+ >
+ <td style={{ padding: '8px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <span style={{
+ padding: '2px 4px',
+ fontSize: '9px',
+ fontWeight: 600,
+ backgroundColor: isBuy ? `${COLORS.GREEN}20` : `${COLORS.RED}20`,
+ color: isBuy ? COLORS.GREEN : COLORS.RED
+ }}>
+ {order.side}
+ </span>
+ <div>
+ <span style={{ fontSize: '10px', color: COLORS.WHITE, fontWeight: 600 }}>{order.symbol}</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <span style={{ fontSize: '9px', color: COLORS.GRAY }}>{order.exchange}</span>
+ <span style={{ fontSize: '9px', color: COLORS.MUTED }}>|</span>
+ <span style={{ fontSize: '9px', color: COLORS.ORANGE }}>{order.orderType}</span>
+ </div>
+ </div>
+ </div>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>
+ <span style={{ fontFamily: 'monospace', color: COLORS.WHITE }}>{order.quantity}</span>
+ {order.filledQuantity > 0 && order.filledQuantity < order.quantity && (
+ <div style={{ fontSize: '9px', color: COLORS.ORANGE }}>
+ {order.filledQuantity} filled
+ </div>
+ )}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>
+ {order.price > 0 ? (
+ <span style={{ fontFamily: 'monospace', color: COLORS.WHITE }}>{order.price.toFixed(2)}</span>
+ ) : (
+ <span style={{ fontSize: '9px', color: COLORS.GRAY }}>MKT</span>
+ )}
+ {order.triggerPrice && order.triggerPrice > 0 && (
+ <div style={{ fontSize: '9px', color: COLORS.PURPLE }}>
+ @ {order.triggerPrice.toFixed(2)}
+ </div>
+ )}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <div style={{
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: '4px',
+ padding: '2px 6px',
+ backgroundColor: `${statusConfig.color}20`,
+ color: statusConfig.color
+ }}>
+ <StatusIcon size={10} />
+ <span style={{ fontSize: '9px', fontWeight: 600 }}>{statusConfig.label}</span>
+ </div>
+ {order.statusMessage && (
+ <div style={{ fontSize: '8px', color: COLORS.RED, marginTop: '2px', maxWidth: '80px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {order.statusMessage}
+ </div>
+ )}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', fontFamily: 'monospace', color: COLORS.GRAY, fontSize: '9px' }}>
+ {formatTime(order.placedAt)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ {(canCancel || canModify) ? (
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}>
+ {canModify && onModifyOrder && (
+ <button
+ onClick={() => onModifyOrder(order)}
+ style={{
+ padding: '3px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.GRAY,
+ cursor: 'pointer'
+ }}
+ title="Modify Order"
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = COLORS.ORANGE;
+ e.currentTarget.style.color = COLORS.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = COLORS.BORDER;
+ e.currentTarget.style.color = COLORS.GRAY;
+ }}
+ >
+ <Edit2 size={10} />
+ </button>
+ )}
+
+ {canCancel && (
+ <button
+ onClick={() => handleCancelOrder(order.orderId)}
+ disabled={isCancelling}
+ style={{
+ padding: '3px',
+ backgroundColor: `${COLORS.RED}20`,
+ border: `1px solid ${COLORS.RED}40`,
+ color: COLORS.RED,
+ cursor: 'pointer'
+ }}
+ title="Cancel Order"
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = `${COLORS.RED}40`;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = `${COLORS.RED}20`;
+ }}
+ >
+ {isCancelling ? (
+ <Loader2 size={10} className="animate-spin" />
+ ) : (
+ <X size={10} />
+ )}
+ </button>
+ )}
+ </div>
+ ) : (
+ <span style={{ fontSize: '9px', color: COLORS.MUTED }}>-</span>
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/PositionsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/PositionsPanel.tsx
new file mode 100644
index 000000000..714cb52e4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/PositionsPanel.tsx
@@ -0,0 +1,443 @@
+/**
+ * Positions Panel Component - Bloomberg Style
+ *
+ * Displays open positions with P&L and action buttons with proper scrolling
+ */
+
+import React, { useState } from 'react';
+import {
+ TrendingUp, TrendingDown, RefreshCw, X, ChevronDown, ChevronUp,
+ AlertCircle, Loader2, Target
+} from 'lucide-react';
+import { useStockTradingData, useStockBrokerContext } from '@/contexts/StockBrokerContext';
+import type { Position, ProductType } from '@/brokers/stocks/types';
+
+// Bloomberg color palette
+const COLORS = {
+ ORANGE: '#FF8800',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ GRAY: '#787878',
+ MUTED: '#4A4A4A',
+ WHITE: '#FFFFFF',
+};
+
+const PRODUCT_LABELS: Record<ProductType, string> = {
+ CASH: 'CNC',
+ INTRADAY: 'MIS',
+ MARGIN: 'NRML',
+ COVER: 'CO',
+ BRACKET: 'BO',
+};
+
+interface PositionsPanelProps {
+ onSquareOff?: (position: Position) => void;
+}
+
+export function PositionsPanel({ onSquareOff }: PositionsPanelProps) {
+ const { positions, refreshPositions, isRefreshing, isReady } = useStockTradingData();
+ const { adapter } = useStockBrokerContext();
+
+ const [expandedPosition, setExpandedPosition] = useState<string | null>(null);
+ const [isClosingAll, setIsClosingAll] = useState(false);
+ const [closingPositionId, setClosingPositionId] = useState<string | null>(null);
+
+ // Calculate totals
+ const totals = React.useMemo(() => {
+ return positions.reduce(
+ (acc, pos) => ({
+ totalPnl: acc.totalPnl + pos.pnl,
+ totalValue: acc.totalValue + (pos.quantity * pos.lastPrice),
+ dayPnl: acc.dayPnl + pos.dayPnl,
+ }),
+ { totalPnl: 0, totalValue: 0, dayPnl: 0 }
+ );
+ }, [positions]);
+
+ // Handle square off single position
+ const handleSquareOff = async (position: Position) => {
+ if (!adapter) return;
+
+ setClosingPositionId(`${position.symbol}-${position.exchange}-${position.productType}`);
+
+ try {
+ const side = position.quantity > 0 ? 'SELL' : 'BUY';
+ const response = await adapter.placeOrder({
+ symbol: position.symbol,
+ exchange: position.exchange,
+ side,
+ quantity: Math.abs(position.quantity),
+ orderType: 'MARKET',
+ productType: position.productType,
+ });
+
+ if (response.success) {
+ await refreshPositions();
+ if (onSquareOff) {
+ onSquareOff(position);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to square off position:', err);
+ } finally {
+ setClosingPositionId(null);
+ }
+ };
+
+ // Handle close all positions
+ const handleCloseAll = async () => {
+ if (!adapter || positions.length === 0) return;
+
+ setIsClosingAll(true);
+
+ try {
+ const result = await adapter.closeAllPositions();
+ if (result.success) {
+ await refreshPositions();
+ }
+ } catch (err) {
+ console.error('Failed to close all positions:', err);
+ } finally {
+ setIsClosingAll(false);
+ }
+ };
+
+ if (!isReady) {
+ return (
+ <div style={{
+ height: '100%',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: COLORS.GRAY,
+ fontSize: '11px'
+ }}>
+ Connect to your broker to view positions
+ </div>
+ );
+ }
+
+ return (
+ <div style={{
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ backgroundColor: COLORS.PANEL_BG,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {/* Header */}
+ <div style={{
+ padding: '6px 12px',
+ borderBottom: `1px solid ${COLORS.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ backgroundColor: COLORS.HEADER_BG,
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ fontSize: '11px', fontWeight: 600, color: COLORS.WHITE }}>POSITIONS</span>
+ <span style={{ fontSize: '10px', color: COLORS.GRAY }}>({positions.length})</span>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ {/* Refresh */}
+ <button
+ onClick={() => refreshPositions()}
+ disabled={isRefreshing}
+ style={{
+ padding: '4px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.GRAY,
+ cursor: 'pointer'
+ }}
+ >
+ <RefreshCw size={12} className={isRefreshing ? 'animate-spin' : ''} />
+ </button>
+
+ {/* Close All */}
+ {positions.length > 0 && (
+ <button
+ onClick={handleCloseAll}
+ disabled={isClosingAll}
+ style={{
+ padding: '3px 8px',
+ fontSize: '9px',
+ fontWeight: 600,
+ backgroundColor: `${COLORS.RED}20`,
+ color: COLORS.RED,
+ border: `1px solid ${COLORS.RED}40`,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ {isClosingAll ? (
+ <Loader2 size={10} className="animate-spin" />
+ ) : (
+ <X size={10} />
+ )}
+ EXIT ALL
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* Summary Row */}
+ {positions.length > 0 && (
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: COLORS.DARK_BG,
+ borderBottom: `1px solid ${COLORS.BORDER}`,
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: '12px',
+ flexShrink: 0
+ }}>
+ <div>
+ <div style={{ fontSize: '9px', color: COLORS.GRAY, marginBottom: '2px' }}>TOTAL VALUE</div>
+ <div style={{ fontSize: '11px', fontFamily: 'monospace', color: COLORS.WHITE }}>
+ ₹{totals.totalValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: COLORS.GRAY, marginBottom: '2px' }}>DAY P&L</div>
+ <div style={{
+ fontSize: '11px',
+ fontFamily: 'monospace',
+ color: totals.dayPnl >= 0 ? COLORS.GREEN : COLORS.RED
+ }}>
+ {totals.dayPnl >= 0 ? '+' : ''}₹{totals.dayPnl.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: COLORS.GRAY, marginBottom: '2px' }}>TOTAL P&L</div>
+ <div style={{
+ fontSize: '11px',
+ fontFamily: 'monospace',
+ color: totals.totalPnl >= 0 ? COLORS.GREEN : COLORS.RED
+ }}>
+ {totals.totalPnl >= 0 ? '+' : ''}₹{totals.totalPnl.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Positions Table */}
+ <div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>
+ {positions.length === 0 ? (
+ <div style={{
+ padding: '24px',
+ textAlign: 'center',
+ color: COLORS.GRAY
+ }}>
+ <Target size={32} color={COLORS.MUTED} style={{ margin: '0 auto 12px' }} />
+ <p style={{ fontSize: '11px' }}>No open positions</p>
+ </div>
+ ) : (
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>
+ <thead style={{ position: 'sticky', top: 0, backgroundColor: COLORS.HEADER_BG, zIndex: 1 }}>
+ <tr style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>
+ <th style={{ padding: '6px 8px', textAlign: 'left', color: COLORS.GRAY, fontWeight: 600 }}>SYMBOL</th>
+ <th style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600 }}>QTY</th>
+ <th style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600 }}>AVG</th>
+ <th style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600 }}>LTP</th>
+ <th style={{ padding: '6px 8px', textAlign: 'right', color: COLORS.GRAY, fontWeight: 600 }}>P&L</th>
+ <th style={{ padding: '6px 8px', textAlign: 'center', color: COLORS.GRAY, fontWeight: 600 }}>ACT</th>
+ </tr>
+ </thead>
+ <tbody>
+ {positions.map((position, idx) => {
+ const positionKey = `${position.symbol}-${position.exchange}-${position.productType}`;
+ const isExpanded = expandedPosition === positionKey;
+ const isClosing = closingPositionId === positionKey;
+ const isLong = position.quantity > 0;
+ const isProfit = position.pnl >= 0;
+
+ return (
+ <React.Fragment key={positionKey}>
+ <tr
+ style={{
+ borderBottom: `1px solid ${COLORS.BORDER}40`,
+ backgroundColor: idx % 2 === 0 ? 'transparent' : `${COLORS.HEADER_BG}40`
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = COLORS.HEADER_BG}
+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = idx % 2 === 0 ? 'transparent' : `${COLORS.HEADER_BG}40`}
+ >
+ <td style={{ padding: '8px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{
+ width: '18px',
+ height: '18px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: isLong ? `${COLORS.GREEN}20` : `${COLORS.RED}20`,
+ flexShrink: 0
+ }}>
+ {isLong ? (
+ <TrendingUp size={10} color={COLORS.GREEN} />
+ ) : (
+ <TrendingDown size={10} color={COLORS.RED} />
+ )}
+ </div>
+ <div>
+ <span style={{ fontSize: '10px', color: COLORS.WHITE, fontWeight: 600 }}>{position.symbol}</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <span style={{ fontSize: '9px', color: COLORS.GRAY }}>{position.exchange}</span>
+ <span style={{
+ fontSize: '9px',
+ color: position.productType === 'INTRADAY' ? COLORS.ORANGE : COLORS.CYAN
+ }}>
+ {PRODUCT_LABELS[position.productType]}
+ </span>
+ </div>
+ </div>
+ </div>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>
+ <span style={{
+ fontFamily: 'monospace',
+ color: isLong ? COLORS.GREEN : COLORS.RED,
+ fontWeight: 600
+ }}>
+ {position.quantity > 0 ? '+' : ''}{position.quantity}
+ </span>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', fontFamily: 'monospace', color: COLORS.WHITE }}>
+ {position.averagePrice.toFixed(2)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', fontFamily: 'monospace', color: COLORS.YELLOW }}>
+ {position.lastPrice.toFixed(2)}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right' }}>
+ <div style={{
+ fontFamily: 'monospace',
+ color: isProfit ? COLORS.GREEN : COLORS.RED
+ }}>
+ {isProfit ? '+' : ''}{position.pnl.toFixed(0)}
+ </div>
+ <div style={{
+ fontSize: '9px',
+ color: isProfit ? COLORS.GREEN : COLORS.RED
+ }}>
+ {isProfit ? '+' : ''}{position.pnlPercent.toFixed(2)}%
+ </div>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}>
+ <button
+ onClick={() => handleSquareOff(position)}
+ disabled={isClosing}
+ style={{
+ padding: '3px 8px',
+ fontSize: '9px',
+ fontWeight: 600,
+ backgroundColor: `${COLORS.RED}20`,
+ color: COLORS.RED,
+ border: `1px solid ${COLORS.RED}40`,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '2px'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = `${COLORS.RED}40`;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = `${COLORS.RED}20`;
+ }}
+ >
+ {isClosing ? (
+ <Loader2 size={10} className="animate-spin" />
+ ) : (
+ <X size={10} />
+ )}
+ EXIT
+ </button>
+ <button
+ onClick={() => setExpandedPosition(isExpanded ? null : positionKey)}
+ style={{
+ padding: '3px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.GRAY,
+ cursor: 'pointer'
+ }}
+ >
+ {isExpanded ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
+ </button>
+ </div>
+ </td>
+ </tr>
+
+ {/* Expanded Details */}
+ {isExpanded && (
+ <tr style={{ backgroundColor: COLORS.DARK_BG }}>
+ <td colSpan={6} style={{ padding: '8px 12px' }}>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(5, 1fr)',
+ gap: '12px',
+ fontSize: '9px'
+ }}>
+ <div>
+ <div style={{ color: COLORS.GRAY, marginBottom: '2px' }}>BUY QTY</div>
+ <div style={{ color: COLORS.WHITE, fontFamily: 'monospace' }}>{position.buyQuantity}</div>
+ </div>
+ <div>
+ <div style={{ color: COLORS.GRAY, marginBottom: '2px' }}>SELL QTY</div>
+ <div style={{ color: COLORS.WHITE, fontFamily: 'monospace' }}>{position.sellQuantity}</div>
+ </div>
+ <div>
+ <div style={{ color: COLORS.GRAY, marginBottom: '2px' }}>BUY VALUE</div>
+ <div style={{ color: COLORS.WHITE, fontFamily: 'monospace' }}>{position.buyValue.toFixed(2)}</div>
+ </div>
+ <div>
+ <div style={{ color: COLORS.GRAY, marginBottom: '2px' }}>SELL VALUE</div>
+ <div style={{ color: COLORS.WHITE, fontFamily: 'monospace' }}>{position.sellValue.toFixed(2)}</div>
+ </div>
+ <div>
+ <div style={{ color: COLORS.GRAY, marginBottom: '2px' }}>DAY P&L</div>
+ <div style={{
+ fontFamily: 'monospace',
+ color: position.dayPnl >= 0 ? COLORS.GREEN : COLORS.RED
+ }}>
+ {position.dayPnl >= 0 ? '+' : ''}{position.dayPnl.toFixed(2)}
+ </div>
+ </div>
+ {position.overnight && (
+ <div style={{ gridColumn: 'span 5' }}>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: `${COLORS.CYAN}20`,
+ color: COLORS.CYAN,
+ fontSize: '9px'
+ }}>
+ OVERNIGHT POSITION
+ </span>
+ </div>
+ )}
+ </div>
+ </td>
+ </tr>
+ )}
+ </React.Fragment>
+ );
+ })}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockOrderForm.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockOrderForm.tsx
new file mode 100644
index 000000000..7b1e8b8fe
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockOrderForm.tsx
@@ -0,0 +1,605 @@
+/**
+ * Stock Order Form Component
+ *
+ * Order entry form for stock trading with support for various order types
+ */
+
+import React, { useState, useEffect } from 'react';
+import {
+ TrendingUp, TrendingDown, Loader2, AlertCircle, DollarSign,
+ Clock, Target, ShieldAlert, Calculator, Info
+} from 'lucide-react';
+import { useStockBrokerContext, useStockBrokerCapabilities } from '@/contexts/StockBrokerContext';
+import type {
+ OrderParams,
+ OrderSide,
+ OrderType,
+ ProductType,
+ OrderValidity,
+ StockExchange,
+ MarginRequired,
+} from '@/brokers/stocks/types';
+
+interface StockOrderFormProps {
+ symbol: string;
+ exchange: StockExchange;
+ lastPrice?: number;
+ onOrderPlaced?: (orderId: string) => void;
+}
+
+const ORDER_TYPES: { value: OrderType; label: string; description: string }[] = [
+ { value: 'MARKET', label: 'Market', description: 'Execute at current market price' },
+ { value: 'LIMIT', label: 'Limit', description: 'Execute at specified price or better' },
+ { value: 'STOP', label: 'Stop Loss', description: 'Trigger when price reaches stop price' },
+ { value: 'STOP_LIMIT', label: 'Stop Limit', description: 'Limit order triggered at stop price' },
+];
+
+const PRODUCT_TYPES: { value: ProductType; label: string; description: string }[] = [
+ { value: 'CASH', label: 'Delivery', description: 'Hold position overnight (CNC)' },
+ { value: 'INTRADAY', label: 'Intraday', description: 'Square off same day (MIS)' },
+ { value: 'MARGIN', label: 'Margin', description: 'Leverage with margin (NRML)' },
+];
+
+const VALIDITY_OPTIONS: { value: OrderValidity; label: string }[] = [
+ { value: 'DAY', label: 'Day' },
+ { value: 'IOC', label: 'IOC' },
+ { value: 'GTC', label: 'GTC' },
+];
+
+export function StockOrderForm({ symbol, exchange, lastPrice, onOrderPlaced }: StockOrderFormProps) {
+ const { adapter, isAuthenticated, refreshOrders, refreshPositions, refreshFunds } = useStockBrokerContext();
+ const { supportsFeature, supportsTradingFeature, hasAMO, hasBracketOrder } = useStockBrokerCapabilities();
+
+ // Order state
+ const [side, setSide] = useState<OrderSide>('BUY');
+ const [orderType, setOrderType] = useState<OrderType>('LIMIT');
+ const [productType, setProductType] = useState<ProductType>('CASH');
+ const [quantity, setQuantity] = useState<string>('');
+ const [price, setPrice] = useState<string>(lastPrice?.toString() || '');
+ const [triggerPrice, setTriggerPrice] = useState<string>('');
+ const [validity, setValidity] = useState<OrderValidity>('DAY');
+ const [isAMO, setIsAMO] = useState(false);
+
+ // Bracket order
+ const [showBracket, setShowBracket] = useState(false);
+ const [squareOffTarget, setSquareOffTarget] = useState<string>('');
+ const [stopLoss, setStopLoss] = useState<string>('');
+
+ // UI state
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [marginRequired, setMarginRequired] = useState<MarginRequired | null>(null);
+ const [isCalculatingMargin, setIsCalculatingMargin] = useState(false);
+
+ // Update price when lastPrice changes
+ useEffect(() => {
+ if (lastPrice && orderType !== 'MARKET') {
+ setPrice(lastPrice.toFixed(2));
+ }
+ }, [lastPrice, orderType]);
+
+ // Calculate margin when order params change
+ useEffect(() => {
+ const calculateMargin = async () => {
+ if (!adapter || !isAuthenticated || !quantity || Number(quantity) <= 0) {
+ setMarginRequired(null);
+ return;
+ }
+
+ setIsCalculatingMargin(true);
+ try {
+ const orderParams: OrderParams = {
+ symbol,
+ exchange,
+ side,
+ quantity: Number(quantity),
+ orderType,
+ productType,
+ price: orderType !== 'MARKET' ? Number(price) : undefined,
+ triggerPrice: ['STOP', 'STOP_LIMIT'].includes(orderType) ? Number(triggerPrice) : undefined,
+ };
+
+ const margin = await adapter.getMarginRequired(orderParams);
+ setMarginRequired(margin);
+ } catch (err) {
+ console.error('Failed to calculate margin:', err);
+ } finally {
+ setIsCalculatingMargin(false);
+ }
+ };
+
+ const debounce = setTimeout(calculateMargin, 500);
+ return () => clearTimeout(debounce);
+ }, [adapter, isAuthenticated, symbol, exchange, side, quantity, orderType, productType, price, triggerPrice]);
+
+ // Submit order
+ const handleSubmit = async () => {
+ if (!adapter || !isAuthenticated) {
+ setError('Please connect to your broker first');
+ return;
+ }
+
+ if (!quantity || Number(quantity) <= 0) {
+ setError('Please enter a valid quantity');
+ return;
+ }
+
+ if (orderType !== 'MARKET' && (!price || Number(price) <= 0)) {
+ setError('Please enter a valid price');
+ return;
+ }
+
+ if (['STOP', 'STOP_LIMIT'].includes(orderType) && (!triggerPrice || Number(triggerPrice) <= 0)) {
+ setError('Please enter a valid trigger price');
+ return;
+ }
+
+ setError(null);
+ setIsSubmitting(true);
+
+ try {
+ const orderParams: OrderParams = {
+ symbol,
+ exchange,
+ side,
+ quantity: Number(quantity),
+ orderType,
+ productType,
+ validity,
+ price: orderType !== 'MARKET' ? Number(price) : undefined,
+ triggerPrice: ['STOP', 'STOP_LIMIT'].includes(orderType) ? Number(triggerPrice) : undefined,
+ amo: isAMO,
+ squareOff: showBracket && squareOffTarget ? Number(squareOffTarget) : undefined,
+ stopLoss: showBracket && stopLoss ? Number(stopLoss) : undefined,
+ };
+
+ const response = await adapter.placeOrder(orderParams);
+
+ if (response.success && response.orderId) {
+ // Reset form
+ setQuantity('');
+ setTriggerPrice('');
+ setSquareOffTarget('');
+ setStopLoss('');
+
+ // Refresh data
+ await Promise.all([refreshOrders(), refreshPositions(), refreshFunds()]);
+
+ // Callback
+ if (onOrderPlaced) {
+ onOrderPlaced(response.orderId);
+ }
+ } else {
+ setError(response.message || 'Order placement failed');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Order placement failed');
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ // Estimated order value
+ const estimatedValue = Number(quantity) * (orderType === 'MARKET' ? (lastPrice || 0) : Number(price) || 0);
+
+ // Bloomberg color constants
+ const COLORS = {
+ ORANGE: '#FF8800',
+ GREEN: '#00D66F',
+ RED: '#FF3B3B',
+ CYAN: '#00E5FF',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ GRAY: '#787878',
+ WHITE: '#FFFFFF',
+ };
+
+ return (
+ <div style={{
+ backgroundColor: COLORS.PANEL_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ overflow: 'hidden',
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace'
+ }}>
+ {/* Header */}
+ <div style={{
+ padding: '8px 12px',
+ borderBottom: `1px solid ${COLORS.BORDER}`,
+ backgroundColor: COLORS.HEADER_BG,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: COLORS.WHITE, fontWeight: 600, fontSize: '12px' }}>{symbol}</span>
+ <span style={{ color: COLORS.GRAY, fontSize: '10px' }}>{exchange}</span>
+ </div>
+ {lastPrice && (
+ <span style={{ color: COLORS.ORANGE, fontFamily: 'monospace', fontSize: '12px', fontWeight: 600 }}>
+ ₹{lastPrice.toFixed(2)}
+ </span>
+ )}
+ </div>
+
+ {/* Buy/Sell Toggle */}
+ <div style={{ padding: '8px', borderBottom: `1px solid ${COLORS.BORDER}` }}>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button
+ onClick={() => setSide('BUY')}
+ style={{
+ flex: 1,
+ padding: '10px',
+ fontWeight: 700,
+ fontSize: '11px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ border: side === 'BUY' ? `2px solid ${COLORS.GREEN}` : `1px solid ${COLORS.BORDER}`,
+ backgroundColor: side === 'BUY' ? COLORS.GREEN : COLORS.DARK_BG,
+ color: side === 'BUY' ? COLORS.DARK_BG : COLORS.GRAY,
+ transition: 'all 0.15s'
+ }}
+ >
+ <TrendingUp size={14} />
+ BUY
+ </button>
+ <button
+ onClick={() => setSide('SELL')}
+ style={{
+ flex: 1,
+ padding: '10px',
+ fontWeight: 700,
+ fontSize: '11px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ border: side === 'SELL' ? `2px solid ${COLORS.RED}` : `1px solid ${COLORS.BORDER}`,
+ backgroundColor: side === 'SELL' ? COLORS.RED : COLORS.DARK_BG,
+ color: side === 'SELL' ? COLORS.WHITE : COLORS.GRAY,
+ transition: 'all 0.15s'
+ }}
+ >
+ <TrendingDown size={14} />
+ SELL
+ </button>
+ </div>
+ </div>
+
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ {/* Order Type */}
+ <div style={{ marginBottom: '10px' }}>
+ <label style={{ display: 'block', fontSize: '9px', color: COLORS.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>
+ ORDER TYPE
+ </label>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px' }}>
+ {ORDER_TYPES.map((type) => (
+ <button
+ key={type.value}
+ onClick={() => setOrderType(type.value)}
+ disabled={type.value === 'TRAILING_STOP' && !supportsTradingFeature('trailingStopOrders')}
+ style={{
+ padding: '6px 8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ border: orderType === type.value ? `1px solid ${COLORS.ORANGE}` : `1px solid ${COLORS.BORDER}`,
+ backgroundColor: orderType === type.value ? `${COLORS.ORANGE}20` : COLORS.DARK_BG,
+ color: orderType === type.value ? COLORS.ORANGE : COLORS.GRAY,
+ transition: 'all 0.15s',
+ opacity: type.value === 'TRAILING_STOP' && !supportsTradingFeature('trailingStopOrders') ? 0.5 : 1
+ }}
+ >
+ {type.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Product Type */}
+ <div style={{ marginBottom: '10px' }}>
+ <label style={{ display: 'block', fontSize: '9px', color: COLORS.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>
+ PRODUCT
+ </label>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {PRODUCT_TYPES.map((type) => (
+ <button
+ key={type.value}
+ onClick={() => setProductType(type.value)}
+ style={{
+ flex: 1,
+ padding: '6px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ border: productType === type.value ? `1px solid ${COLORS.CYAN}` : `1px solid ${COLORS.BORDER}`,
+ backgroundColor: productType === type.value ? `${COLORS.CYAN}15` : COLORS.DARK_BG,
+ color: productType === type.value ? COLORS.CYAN : COLORS.GRAY,
+ transition: 'all 0.15s'
+ }}
+ title={type.description}
+ >
+ {type.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Quantity */}
+ <div style={{ marginBottom: '10px' }}>
+ <label style={{ display: 'block', fontSize: '9px', color: COLORS.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>
+ QUANTITY
+ </label>
+ <input
+ type="number"
+ value={quantity}
+ onChange={(e) => setQuantity(e.target.value)}
+ placeholder="0"
+ min="1"
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none'
+ }}
+ onFocus={(e) => e.target.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.target.style.borderColor = COLORS.BORDER}
+ />
+ </div>
+
+ {/* Price (for limit orders) */}
+ {orderType !== 'MARKET' && (
+ <div style={{ marginBottom: '10px' }}>
+ <label style={{ display: 'block', fontSize: '9px', color: COLORS.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>
+ PRICE
+ </label>
+ <input
+ type="number"
+ value={price}
+ onChange={(e) => setPrice(e.target.value)}
+ placeholder="0.00"
+ step="0.05"
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none'
+ }}
+ onFocus={(e) => e.target.style.borderColor = COLORS.ORANGE}
+ onBlur={(e) => e.target.style.borderColor = COLORS.BORDER}
+ />
+ </div>
+ )}
+
+ {/* Trigger Price (for stop orders) */}
+ {['STOP', 'STOP_LIMIT'].includes(orderType) && (
+ <div style={{ marginBottom: '10px' }}>
+ <label style={{ display: 'block', fontSize: '9px', color: COLORS.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>
+ TRIGGER PRICE
+ </label>
+ <input
+ type="number"
+ value={triggerPrice}
+ onChange={(e) => setTriggerPrice(e.target.value)}
+ placeholder="0.00"
+ step="0.05"
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '12px',
+ fontFamily: 'monospace',
+ outline: 'none'
+ }}
+ onFocus={(e) => e.target.style.borderColor = COLORS.RED}
+ onBlur={(e) => e.target.style.borderColor = COLORS.BORDER}
+ />
+ </div>
+ )}
+
+ {/* Validity & AMO */}
+ <div style={{ display: 'flex', alignItems: 'flex-end', gap: '8px', marginBottom: '10px' }}>
+ <div style={{ flex: 1 }}>
+ <label style={{ display: 'block', fontSize: '9px', color: COLORS.GRAY, marginBottom: '4px', fontWeight: 600, letterSpacing: '0.5px' }}>
+ VALIDITY
+ </label>
+ <select
+ value={validity}
+ onChange={(e) => setValidity(e.target.value as OrderValidity)}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ fontSize: '11px',
+ outline: 'none',
+ cursor: 'pointer'
+ }}
+ >
+ {VALIDITY_OPTIONS.map((opt) => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ </div>
+
+ {/* AMO Toggle */}
+ {hasAMO && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', paddingBottom: '2px' }}>
+ <input
+ type="checkbox"
+ id="amo"
+ checked={isAMO}
+ onChange={(e) => setIsAMO(e.target.checked)}
+ style={{ width: '14px', height: '14px', cursor: 'pointer' }}
+ />
+ <label htmlFor="amo" style={{ fontSize: '10px', color: COLORS.GRAY, cursor: 'pointer' }}>AMO</label>
+ </div>
+ )}
+ </div>
+
+ {/* Bracket Order */}
+ {hasBracketOrder && productType === 'INTRADAY' && (
+ <div style={{ marginBottom: '10px' }}>
+ <button
+ onClick={() => setShowBracket(!showBracket)}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontSize: '10px',
+ color: COLORS.ORANGE,
+ background: 'none',
+ border: 'none',
+ cursor: 'pointer',
+ padding: 0
+ }}
+ >
+ <Target size={12} />
+ {showBracket ? 'Hide' : 'Add'} Bracket Order
+ </button>
+
+ {showBracket && (
+ <div style={{ marginTop: '8px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
+ <div>
+ <label style={{ display: 'block', fontSize: '9px', color: COLORS.GRAY, marginBottom: '4px' }}>
+ TARGET
+ </label>
+ <input
+ type="number"
+ value={squareOffTarget}
+ onChange={(e) => setSquareOffTarget(e.target.value)}
+ placeholder="0.00"
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.GREEN}40`,
+ color: COLORS.WHITE,
+ fontSize: '11px',
+ fontFamily: 'monospace',
+ outline: 'none'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ display: 'block', fontSize: '9px', color: COLORS.GRAY, marginBottom: '4px' }}>
+ STOP LOSS
+ </label>
+ <input
+ type="number"
+ value={stopLoss}
+ onChange={(e) => setStopLoss(e.target.value)}
+ placeholder="0.00"
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.RED}40`,
+ color: COLORS.WHITE,
+ fontSize: '11px',
+ fontFamily: 'monospace',
+ outline: 'none'
+ }}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Error Display */}
+ {error && (
+ <div style={{
+ padding: '8px',
+ backgroundColor: `${COLORS.RED}15`,
+ border: `1px solid ${COLORS.RED}40`,
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: '8px',
+ marginBottom: '10px'
+ }}>
+ <AlertCircle size={14} color={COLORS.RED} style={{ flexShrink: 0, marginTop: '1px' }} />
+ <p style={{ fontSize: '10px', color: COLORS.RED, margin: 0 }}>{error}</p>
+ </div>
+ )}
+
+ {/* Order Summary */}
+ <div style={{
+ padding: '8px',
+ backgroundColor: COLORS.DARK_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ marginBottom: '10px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', marginBottom: '4px' }}>
+ <span style={{ color: COLORS.GRAY }}>Est. Value</span>
+ <span style={{ color: COLORS.WHITE, fontFamily: 'monospace' }}>
+ ₹{estimatedValue.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
+ </span>
+ </div>
+ {marginRequired && (
+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px' }}>
+ <span style={{ color: COLORS.GRAY }}>Margin Req.</span>
+ <span style={{ color: COLORS.ORANGE, fontFamily: 'monospace' }}>
+ {isCalculatingMargin ? (
+ <Loader2 size={12} className="animate-spin" />
+ ) : (
+ `₹${marginRequired.totalMargin.toLocaleString('en-IN', { minimumFractionDigits: 2 })}`
+ )}
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Submit Button - Fixed at bottom */}
+ <div style={{ padding: '8px', borderTop: `1px solid ${COLORS.BORDER}` }}>
+ <button
+ onClick={handleSubmit}
+ disabled={isSubmitting || !isAuthenticated || !quantity}
+ style={{
+ width: '100%',
+ padding: '12px',
+ fontWeight: 700,
+ fontSize: '12px',
+ cursor: isSubmitting || !isAuthenticated || !quantity ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ border: 'none',
+ backgroundColor: side === 'BUY' ? COLORS.GREEN : COLORS.RED,
+ color: side === 'BUY' ? COLORS.DARK_BG : COLORS.WHITE,
+ opacity: isSubmitting || !isAuthenticated || !quantity ? 0.5 : 1,
+ transition: 'all 0.15s'
+ }}
+ >
+ {isSubmitting ? (
+ <Loader2 size={16} className="animate-spin" />
+ ) : (
+ <>
+ {side === 'BUY' ? <TrendingUp size={16} /> : <TrendingDown size={16} />}
+ {side} {symbol}
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx
new file mode 100644
index 000000000..b933b4092
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx
@@ -0,0 +1,343 @@
+/**
+ * Stock Trading Chart
+ *
+ * Chart component for Indian stock brokers using ProChartWithToolkit
+ * Fetches historical OHLCV data from stock broker adapters (Fyers, Zerodha, etc.)
+ */
+
+import React, { useEffect, useState, useCallback } from 'react';
+import { Loader2, AlertCircle, RefreshCw, Clock } from 'lucide-react';
+
+import type { StockExchange, TimeFrame, OHLCV } from '@/brokers/stocks/types';
+import { useStockBrokerContext } from '@/contexts/StockBrokerContext';
+import { ProChartWithToolkit } from '../../trading/charts/ProChartWithToolkit';
+
+interface StockTradingChartProps {
+ symbol: string;
+ exchange: StockExchange;
+ interval?: TimeFrame;
+ height?: number;
+}
+
+// Available timeframes
+const TIMEFRAMES: { value: TimeFrame; label: string }[] = [
+ { value: '1m', label: '1m' },
+ { value: '3m', label: '3m' },
+ { value: '5m', label: '5m' },
+ { value: '15m', label: '15m' },
+ { value: '30m', label: '30m' },
+ { value: '1h', label: '1h' },
+ { value: '2h', label: '2h' },
+ { value: '4h', label: '4h' },
+ { value: '1d', label: '1D' },
+ { value: '1w', label: '1W' },
+];
+
+// Helper to convert TimeFrame to days for historical data range
+// For timeframes < 1d, show only past 7 days
+const timeframeToDays = (tf: TimeFrame): number => {
+ switch (tf) {
+ case '1m': return 7; // 1 min -> 7 days
+ case '3m': return 7; // 3 min -> 7 days
+ case '5m': return 7; // 5 min -> 7 days
+ case '10m': return 7; // 10 min -> 7 days
+ case '15m': return 7; // 15 min -> 7 days
+ case '30m': return 7; // 30 min -> 7 days
+ case '1h': return 7; // 1 hour -> 7 days
+ case '2h': return 7; // 2 hours -> 7 days
+ case '4h': return 7; // 4 hours -> 7 days
+ case '1d': return 365; // 1 day -> 1 year
+ case '1w': return 730; // 1 week -> 2 years
+ case '1M': return 1825; // 1 month -> 5 years
+ default: return 7;
+ }
+};
+
+export function StockTradingChart({
+ symbol,
+ exchange,
+ interval: initialInterval = '5m',
+ height
+}: StockTradingChartProps) {
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [selectedInterval, setSelectedInterval] = useState<TimeFrame>(initialInterval);
+ const [chartData, setChartData] = useState<Array<{
+ time: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+ }>>([]);
+
+ const { adapter, isAuthenticated } = useStockBrokerContext();
+
+ // Fetch historical data
+ const fetchHistoricalData = useCallback(async () => {
+ if (!symbol || !exchange) {
+ console.log('[StockTradingChart] No symbol or exchange selected');
+ setError('Please select a symbol');
+ setIsLoading(false);
+ return;
+ }
+
+ if (!adapter || !isAuthenticated) {
+ setError('Please authenticate with your broker to view charts');
+ setIsLoading(false);
+ return;
+ }
+
+ try {
+ setIsLoading(true);
+ setError(null);
+
+ console.log(`[StockTradingChart] Fetching historical data for ${exchange}:${symbol} (${selectedInterval})...`);
+
+ // Calculate date range based on timeframe
+ const to = new Date();
+ const from = new Date();
+ from.setDate(from.getDate() - timeframeToDays(selectedInterval));
+
+ console.log(`[StockTradingChart] Date range: ${from.toISOString()} to ${to.toISOString()}`);
+
+ // Fetch OHLCV data from stock broker adapter (Fyers, Zerodha, etc.)
+ const ohlcvData: OHLCV[] = await adapter.getOHLCV(
+ symbol,
+ exchange,
+ selectedInterval,
+ from,
+ to
+ );
+
+ console.log(`[StockTradingChart] Fetched ${ohlcvData.length} candles from ${adapter.brokerId}`);
+
+ if (ohlcvData.length === 0) {
+ setError('No historical data available. Check your API credentials and symbol format.');
+ setIsLoading(false);
+ return;
+ }
+
+ // Convert to ProChartWithToolkit format (timestamps in seconds, not milliseconds)
+ const formattedData = ohlcvData.map((candle) => ({
+ time: Math.floor(candle.timestamp / 1000), // Convert ms to seconds
+ open: candle.open,
+ high: candle.high,
+ low: candle.low,
+ close: candle.close,
+ volume: candle.volume,
+ }));
+
+ // Sort by time and remove duplicates (Lightweight Charts requires strictly ascending timestamps)
+ const sortedData = formattedData.sort((a, b) => a.time - b.time);
+
+ // Remove duplicate timestamps (keep the last one for each timestamp)
+ const uniqueData = sortedData.reduce((acc, current) => {
+ const lastItem = acc[acc.length - 1];
+ if (!lastItem || lastItem.time !== current.time) {
+ acc.push(current);
+ } else {
+ // Replace with current (keep last occurrence)
+ acc[acc.length - 1] = current;
+ }
+ return acc;
+ }, [] as typeof sortedData);
+
+ console.log('[StockTradingChart] ✓ Chart data prepared:', {
+ originalCount: ohlcvData.length,
+ formattedCount: formattedData.length,
+ uniqueCount: uniqueData.length,
+ duplicatesRemoved: formattedData.length - uniqueData.length,
+ firstCandle: uniqueData[0],
+ lastCandle: uniqueData[uniqueData.length - 1],
+ });
+
+ setChartData(uniqueData);
+ setIsLoading(false);
+ } catch (err) {
+ console.error('[StockTradingChart] Failed to fetch historical data:', err);
+ setError(err instanceof Error ? err.message : 'Failed to load chart data');
+ setIsLoading(false);
+ }
+ }, [adapter, isAuthenticated, symbol, exchange, selectedInterval]);
+
+ // Auto-fetch on mount and when dependencies change
+ useEffect(() => {
+ fetchHistoricalData();
+ }, [fetchHistoricalData]);
+
+ // Handle manual refresh
+ const handleRefresh = () => {
+ fetchHistoricalData();
+ };
+
+ // Not authenticated state
+ if (!isAuthenticated) {
+ return (
+ <div className="flex-1 flex items-center justify-center bg-[#0A0A0A]" style={{ height: height || '100%', minHeight: height || 300 }}>
+ <div className="text-center">
+ <AlertCircle className="w-16 h-16 mx-auto mb-4 text-[#FF8800]" />
+ <p className="text-lg text-white mb-2">Connect Your Broker</p>
+ <p className="text-sm text-gray-500">Authenticate to view historical charts</p>
+ </div>
+ </div>
+ );
+ }
+
+ // Loading state
+ if (isLoading && chartData.length === 0) {
+ return (
+ <div className="flex-1 flex items-center justify-center bg-[#0A0A0A]" style={{ height: height || '100%', minHeight: height || 300 }}>
+ <div className="text-center">
+ <Loader2 className="w-12 h-12 mx-auto mb-4 text-[#FF8800] animate-spin" />
+ <p className="text-sm text-gray-400">Loading chart data...</p>
+ </div>
+ </div>
+ );
+ }
+
+ // Error state
+ if (error && chartData.length === 0) {
+ return (
+ <div className="flex-1 flex items-center justify-center bg-[#0A0A0A]" style={{ height: height || '100%', minHeight: height || 300 }}>
+ <div className="text-center">
+ <AlertCircle className="w-12 h-12 mx-auto mb-4 text-red-500" />
+ <p className="text-sm text-red-400 mb-3">{error}</p>
+ <button
+ onClick={handleRefresh}
+ className="px-4 py-2 bg-[#FF8800] text-white rounded hover:bg-[#FF9920] transition-colors"
+ >
+ Retry
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ // Calculate price change for display
+ const latestCandle = chartData[chartData.length - 1];
+ const firstCandle = chartData[0];
+ const priceChange = latestCandle && firstCandle ? latestCandle.close - firstCandle.open : 0;
+ const priceChangePercent = latestCandle && firstCandle ? ((priceChange / firstCandle.open) * 100) : 0;
+
+ return (
+ <div className="flex-1 flex flex-col bg-[#0A0A0A]" style={{ height: height || '100%', minHeight: 0, overflow: 'hidden' }}>
+ {/* Combined Header - Symbol, OHLC, Timeframe, and Controls */}
+ <div className="flex items-center justify-between px-3 py-1 bg-[#000000] border-b border-[#2A2A2A]" style={{ flexShrink: 0, height: '28px' }}>
+ {/* Left: Symbol, OHLC, Change */}
+ <div className="flex items-center gap-4">
+ {/* Symbol */}
+ <span className="text-xs font-semibold text-[#FF8800] font-mono tracking-wide">
+ {exchange}:{symbol}
+ </span>
+
+ {/* OHLC Data */}
+ {latestCandle && (
+ <div className="flex items-center gap-3 text-[10px] font-mono">
+ <div className="flex items-center gap-1">
+ <span className="text-gray-500">O</span>
+ <span className="text-white">{latestCandle.open.toFixed(2)}</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <span className="text-gray-500">H</span>
+ <span className="text-white">{latestCandle.high.toFixed(2)}</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <span className="text-gray-500">L</span>
+ <span className="text-white">{latestCandle.low.toFixed(2)}</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <span className="text-gray-500">C</span>
+ <span className={`font-semibold ${latestCandle.close >= latestCandle.open ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}>
+ {latestCandle.close.toFixed(2)}
+ </span>
+ </div>
+
+ {/* Price Change & Percentage */}
+ <div className={`flex items-center gap-1 ${priceChange >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}>
+ <span>{priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)}</span>
+ <span>({priceChange >= 0 ? '+' : ''}{priceChangePercent.toFixed(2)}%)</span>
+ </div>
+
+ {/* Volume */}
+ <div className="flex items-center gap-1">
+ <span className="text-gray-500">Vol</span>
+ <span className="text-white">
+ {latestCandle.volume >= 1000000
+ ? `${(latestCandle.volume / 1000000).toFixed(2)}M`
+ : latestCandle.volume >= 1000
+ ? `${(latestCandle.volume / 1000).toFixed(2)}K`
+ : latestCandle.volume.toFixed(0)}
+ </span>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Right: Timeframe Selector & Refresh */}
+ <div className="flex items-center gap-3">
+ {/* Timeframe Buttons */}
+ <div className="flex items-center gap-1">
+ {TIMEFRAMES.map((tf) => (
+ <button
+ key={tf.value}
+ onClick={() => setSelectedInterval(tf.value)}
+ disabled={isLoading}
+ className={`px-2 py-0.5 text-[9px] font-medium rounded transition-colors disabled:opacity-50 ${
+ selectedInterval === tf.value
+ ? 'bg-[#FF8800] text-white'
+ : 'text-gray-400 hover:text-white hover:bg-[#1F1F1F]'
+ }`}
+ >
+ {tf.label}
+ </button>
+ ))}
+ </div>
+
+ {/* Refresh Button */}
+ <button
+ onClick={handleRefresh}
+ disabled={isLoading}
+ className="p-1 bg-[#0F0F0F] rounded border border-[#2A2A2A] hover:bg-[#1F1F1F] transition-colors disabled:opacity-50"
+ title="Refresh chart"
+ >
+ <RefreshCw className={`w-3 h-3 text-gray-400 ${isLoading ? 'animate-spin' : ''}`} />
+ </button>
+ </div>
+ </div>
+
+ {/* Chart Container - Full remaining height */}
+ <div className="flex-1 relative" style={{ minHeight: 0, overflow: 'hidden' }}>
+ {chartData.length > 0 && (
+ <div style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ <ProChartWithToolkit
+ data={chartData}
+ symbol={`${exchange}:${symbol}`}
+ showVolume={true}
+ showToolbar={true}
+ showHeader={false}
+ />
+ </div>
+ )}
+
+ {/* Loading Overlay */}
+ {isLoading && chartData.length > 0 && (
+ <div className="absolute bottom-2 left-1/2 -translate-x-1/2 bg-[#0F0F0F]/90 backdrop-blur-sm px-4 py-2 rounded border border-[#2A2A2A] z-10">
+ <div className="flex items-center gap-2">
+ <Loader2 className="w-4 h-4 text-[#FF8800] animate-spin" />
+ <span className="text-xs text-gray-400">Updating...</span>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/SymbolSearch.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/SymbolSearch.tsx
new file mode 100644
index 000000000..4cd670103
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/SymbolSearch.tsx
@@ -0,0 +1,572 @@
+/**
+ * SymbolSearch Component
+ *
+ * Professional symbol search dropdown using master contract database.
+ * Provides fast, offline-capable symbol search with relevance ranking.
+ */
+
+import React, { useState, useEffect, useRef, useCallback } from 'react';
+import { Search, Download, RefreshCw, ChevronDown, X, AlertCircle, Check, Loader2 } from 'lucide-react';
+import {
+ masterContractService,
+ type SymbolSearchResult,
+ type SupportedBroker,
+ type DownloadResult
+} from '@/services/trading/masterContractService';
+import type { StockExchange } from '@/brokers/stocks/types';
+
+// 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'
+};
+
+interface SymbolSearchProps {
+ /** Currently selected symbol */
+ selectedSymbol: string;
+ /** Currently selected exchange */
+ selectedExchange: StockExchange;
+ /** Callback when symbol is selected */
+ onSymbolSelect: (symbol: string, exchange: StockExchange, result?: SymbolSearchResult) => void;
+ /** Active broker ID */
+ brokerId: SupportedBroker;
+ /** Placeholder text */
+ placeholder?: string;
+ /** Whether to show download progress */
+ showDownloadStatus?: boolean;
+ /** Filter by exchange */
+ exchangeFilter?: string;
+ /** Filter by instrument type */
+ instrumentTypeFilter?: string;
+}
+
+export function SymbolSearch({
+ selectedSymbol,
+ selectedExchange,
+ onSymbolSelect,
+ brokerId,
+ placeholder = 'Search stocks...',
+ showDownloadStatus = true,
+ exchangeFilter,
+ instrumentTypeFilter
+}: SymbolSearchProps) {
+ // State
+ const [isOpen, setIsOpen] = useState(false);
+ const [query, setQuery] = useState('');
+ const [results, setResults] = useState<SymbolSearchResult[]>([]);
+ const [isSearching, setIsSearching] = useState(false);
+ const [symbolCount, setSymbolCount] = useState(0);
+ const [exchanges, setExchanges] = useState<string[]>([]);
+ const [selectedFilterExchange, setSelectedFilterExchange] = useState<string | undefined>(exchangeFilter);
+
+ // Download state
+ const [isDownloading, setIsDownloading] = useState(false);
+ const [downloadStatus, setDownloadStatus] = useState<'idle' | 'downloading' | 'success' | 'error'>('idle');
+ const [downloadMessage, setDownloadMessage] = useState('');
+
+ // Refs
+ const containerRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const searchTimeoutRef = useRef<number | null>(null);
+
+ // Check if master contract data exists on mount
+ useEffect(() => {
+ const checkData = async () => {
+ try {
+ const count = await masterContractService.getSymbolCount(brokerId);
+ setSymbolCount(count);
+
+ if (count > 0) {
+ const exchangeList = await masterContractService.getExchanges(brokerId);
+ setExchanges(exchangeList);
+ }
+ } catch (error) {
+ console.error('[SymbolSearch] Error checking symbol data:', error);
+ setSymbolCount(0);
+ }
+ };
+
+ checkData();
+ }, [brokerId]);
+
+ // Close dropdown when clicking outside
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
+ setIsOpen(false);
+ }
+ };
+
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }, []);
+
+ // Debounced search
+ const performSearch = useCallback(async (searchQuery: string) => {
+ if (!searchQuery || searchQuery.length < 1) {
+ setResults([]);
+ setIsSearching(false);
+ return;
+ }
+
+ setIsSearching(true);
+ try {
+ const searchResults = await masterContractService.safeSearch(brokerId, searchQuery, {
+ exchange: selectedFilterExchange,
+ instrumentType: instrumentTypeFilter,
+ limit: 50
+ });
+ setResults(searchResults);
+ } catch (error) {
+ console.error('[SymbolSearch] Search error:', error);
+ setResults([]);
+ } finally {
+ setIsSearching(false);
+ }
+ }, [brokerId, selectedFilterExchange, instrumentTypeFilter]);
+
+ // Handle query change with debounce
+ const handleQueryChange = (value: string) => {
+ setQuery(value);
+
+ if (searchTimeoutRef.current) {
+ clearTimeout(searchTimeoutRef.current);
+ }
+
+ searchTimeoutRef.current = window.setTimeout(() => {
+ performSearch(value);
+ }, 150);
+ };
+
+ // Handle symbol selection
+ const handleSelect = (result: SymbolSearchResult) => {
+ onSymbolSelect(result.symbol, result.exchange as StockExchange, result);
+ setQuery('');
+ setResults([]);
+ setIsOpen(false);
+ };
+
+ // Download master contract
+ const handleDownload = async () => {
+ setIsDownloading(true);
+ setDownloadStatus('downloading');
+ setDownloadMessage('Downloading symbol data...');
+
+ try {
+ const result = await masterContractService.downloadMasterContract(brokerId);
+
+ if (result.success) {
+ setDownloadStatus('success');
+ setDownloadMessage(`Downloaded ${result.symbol_count.toLocaleString()} symbols`);
+ setSymbolCount(result.symbol_count);
+
+ // Refresh exchanges
+ const exchangeList = await masterContractService.getExchanges(brokerId);
+ setExchanges(exchangeList);
+ } else {
+ setDownloadStatus('error');
+ setDownloadMessage(result.message || 'Download failed');
+ }
+ } catch (error: any) {
+ setDownloadStatus('error');
+ setDownloadMessage(error.message || 'Download failed');
+ } finally {
+ setIsDownloading(false);
+
+ // Reset status after 3 seconds
+ setTimeout(() => {
+ setDownloadStatus('idle');
+ setDownloadMessage('');
+ }, 3000);
+ }
+ };
+
+ // Focus input when dropdown opens
+ useEffect(() => {
+ if (isOpen && inputRef.current) {
+ inputRef.current.focus();
+ }
+ }, [isOpen]);
+
+ return (
+ <div ref={containerRef} style={{ position: 'relative', minWidth: '220px' }}>
+ {/* Trigger Button */}
+ <div
+ onClick={() => setIsOpen(!isOpen)}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${isOpen ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ cursor: 'pointer',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ transition: 'border-color 0.2s'
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{
+ fontSize: '13px',
+ fontWeight: 700,
+ color: selectedSymbol ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY
+ }}>
+ {selectedSymbol || 'Select Symbol'}
+ </span>
+ {selectedSymbol && (
+ <span style={{ fontSize: '10px', color: BLOOMBERG.GRAY }}>{selectedExchange}</span>
+ )}
+ </div>
+ <ChevronDown
+ size={12}
+ color={BLOOMBERG.GRAY}
+ style={{
+ transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
+ transition: 'transform 0.2s'
+ }}
+ />
+ </div>
+
+ {/* Dropdown */}
+ {isOpen && (
+ <div style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ right: 0,
+ marginTop: '4px',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ maxHeight: '450px',
+ overflow: 'hidden',
+ zIndex: 1000,
+ boxShadow: `0 4px 16px ${BLOOMBERG.DARK_BG}80`,
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Search Input */}
+ <div style={{ padding: '8px', borderBottom: `1px solid ${BLOOMBERG.BORDER}` }}>
+ <div style={{ position: 'relative' }}>
+ <Search
+ size={14}
+ color={BLOOMBERG.GRAY}
+ style={{ position: 'absolute', left: '8px', top: '50%', transform: 'translateY(-50%)' }}
+ />
+ <input
+ ref={inputRef}
+ type="text"
+ placeholder={placeholder}
+ value={query}
+ onChange={(e) => handleQueryChange(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '8px 32px 8px 32px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ color: BLOOMBERG.WHITE,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ fontSize: '11px',
+ outline: 'none'
+ }}
+ />
+ {query && (
+ <X
+ size={14}
+ color={BLOOMBERG.GRAY}
+ style={{
+ position: 'absolute',
+ right: '8px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ cursor: 'pointer'
+ }}
+ onClick={(e) => {
+ e.stopPropagation();
+ setQuery('');
+ setResults([]);
+ }}
+ />
+ )}
+ </div>
+
+ {/* Exchange Filter */}
+ {exchanges.length > 0 && (
+ <div style={{
+ marginTop: '8px',
+ display: 'flex',
+ gap: '4px',
+ flexWrap: 'wrap'
+ }}>
+ <button
+ onClick={() => setSelectedFilterExchange(undefined)}
+ style={{
+ padding: '3px 8px',
+ backgroundColor: !selectedFilterExchange ? BLOOMBERG.ORANGE : 'transparent',
+ border: `1px solid ${!selectedFilterExchange ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ color: !selectedFilterExchange ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 600
+ }}
+ >
+ ALL
+ </button>
+ {exchanges.slice(0, 6).map(exch => (
+ <button
+ key={exch}
+ onClick={() => setSelectedFilterExchange(exch === selectedFilterExchange ? undefined : exch)}
+ style={{
+ padding: '3px 8px',
+ backgroundColor: selectedFilterExchange === exch ? BLOOMBERG.ORANGE : 'transparent',
+ border: `1px solid ${selectedFilterExchange === exch ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ color: selectedFilterExchange === exch ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 600
+ }}
+ >
+ {exch}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Status/Download Bar */}
+ {showDownloadStatus && (
+ <div style={{
+ padding: '6px 12px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ fontSize: '9px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ {downloadStatus === 'downloading' && (
+ <Loader2 size={12} color={BLOOMBERG.CYAN} className="animate-spin" />
+ )}
+ {downloadStatus === 'success' && (
+ <Check size={12} color={BLOOMBERG.GREEN} />
+ )}
+ {downloadStatus === 'error' && (
+ <AlertCircle size={12} color={BLOOMBERG.RED} />
+ )}
+
+ <span style={{
+ color: downloadStatus === 'error' ? BLOOMBERG.RED :
+ downloadStatus === 'success' ? BLOOMBERG.GREEN : BLOOMBERG.GRAY
+ }}>
+ {downloadMessage || (symbolCount > 0
+ ? `${symbolCount.toLocaleString()} symbols loaded`
+ : 'No symbols loaded'
+ )}
+ </span>
+ </div>
+
+ <button
+ onClick={handleDownload}
+ disabled={isDownloading}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: isDownloading ? BLOOMBERG.MUTED : BLOOMBERG.CYAN,
+ cursor: isDownloading ? 'not-allowed' : 'pointer',
+ fontSize: '9px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ transition: 'all 0.2s'
+ }}
+ >
+ {isDownloading ? (
+ <RefreshCw size={10} className="animate-spin" />
+ ) : (
+ <Download size={10} />
+ )}
+ {symbolCount > 0 ? 'REFRESH' : 'DOWNLOAD'}
+ </button>
+ </div>
+ )}
+
+ {/* Results */}
+ <div style={{ flex: 1, overflow: 'auto', maxHeight: '340px' }}>
+ {isSearching ? (
+ <div style={{
+ padding: '20px',
+ textAlign: 'center',
+ color: BLOOMBERG.GRAY,
+ fontSize: '11px'
+ }}>
+ <Loader2 size={16} className="animate-spin" style={{ margin: '0 auto 8px' }} />
+ Searching...
+ </div>
+ ) : results.length > 0 ? (
+ results.map((result, idx) => (
+ <div
+ key={`${result.symbol}-${result.exchange}-${result.token}`}
+ onClick={() => handleSelect(result)}
+ style={{
+ padding: '10px 12px',
+ cursor: 'pointer',
+ fontSize: '11px',
+ backgroundColor: 'transparent',
+ borderLeft: '3px solid transparent',
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}20`
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;
+ e.currentTarget.style.borderLeftColor = BLOOMBERG.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.borderLeftColor = 'transparent';
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.WHITE, fontWeight: 700, fontSize: '12px' }}>
+ {result.symbol}
+ </span>
+ <span style={{
+ padding: '2px 4px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ color: BLOOMBERG.CYAN,
+ fontSize: '8px',
+ fontWeight: 600
+ }}>
+ {result.exchange}
+ </span>
+ {result.instrument_type && result.instrument_type !== 'EQ' && (
+ <span style={{
+ padding: '2px 4px',
+ backgroundColor: BLOOMBERG.PURPLE + '30',
+ color: BLOOMBERG.PURPLE,
+ fontSize: '8px',
+ fontWeight: 600
+ }}>
+ {result.instrument_type}
+ </span>
+ )}
+ </div>
+ {result.token && (
+ <span style={{ color: BLOOMBERG.MUTED, fontSize: '9px', fontFamily: 'monospace' }}>
+ {result.token}
+ </span>
+ )}
+ </div>
+ {result.name && (
+ <div style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '10px',
+ marginTop: '4px',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis'
+ }}>
+ {result.name}
+ </div>
+ )}
+ {result.expiry && (
+ <div style={{
+ display: 'flex',
+ gap: '12px',
+ marginTop: '4px',
+ fontSize: '9px',
+ color: BLOOMBERG.MUTED
+ }}>
+ <span>Expiry: {result.expiry}</span>
+ {result.strike && <span>Strike: {result.strike}</span>}
+ {result.lot_size && <span>Lot: {result.lot_size}</span>}
+ </div>
+ )}
+ </div>
+ ))
+ ) : query.length > 0 ? (
+ <div style={{
+ padding: '20px',
+ textAlign: 'center',
+ color: BLOOMBERG.GRAY,
+ fontSize: '11px'
+ }}>
+ No symbols found for "{query}"
+ </div>
+ ) : symbolCount === 0 ? (
+ <div style={{
+ padding: '30px 20px',
+ textAlign: 'center',
+ color: BLOOMBERG.GRAY
+ }}>
+ <Download size={32} color={BLOOMBERG.MUTED} style={{ margin: '0 auto 12px' }} />
+ <div style={{ fontSize: '12px', marginBottom: '8px' }}>
+ No symbol data available
+ </div>
+ <div style={{ fontSize: '10px', color: BLOOMBERG.MUTED, marginBottom: '16px' }}>
+ Download master contract to enable symbol search
+ </div>
+ <button
+ onClick={handleDownload}
+ disabled={isDownloading}
+ style={{
+ padding: '8px 16px',
+ backgroundColor: BLOOMBERG.ORANGE,
+ border: 'none',
+ color: BLOOMBERG.DARK_BG,
+ cursor: isDownloading ? 'not-allowed' : 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}
+ >
+ {isDownloading ? (
+ <RefreshCw size={12} className="animate-spin" />
+ ) : (
+ <Download size={12} />
+ )}
+ DOWNLOAD SYMBOLS
+ </button>
+ </div>
+ ) : (
+ <div style={{
+ padding: '16px',
+ textAlign: 'center',
+ color: BLOOMBERG.MUTED,
+ fontSize: '10px'
+ }}>
+ Type to search {symbolCount.toLocaleString()} symbols
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Spinner animation CSS */}
+ <style>{`
+ @keyframes spin {
+ from { transform: rotate(0deg); }
+ to { transform: rotate(360deg); }
+ }
+ .animate-spin {
+ animation: spin 1s linear infinite;
+ }
+ `}</style>
+ </div>
+ );
+}
+
+export default SymbolSearch;
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.ts
new file mode 100644
index 000000000..7ede454cd
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.ts
@@ -0,0 +1,18 @@
+/**
+ * Equity Trading Components
+ *
+ * Export all stock trading UI components
+ */
+
+export { BrokerSelector } from './BrokerSelector';
+export { BrokerAuthPanel } from './BrokerAuthPanel';
+export { BrokerConfigPanel } from './BrokerConfigPanel';
+export { BrokerSetupPanel } from './BrokerSetupPanel';
+export { StockOrderForm } from './StockOrderForm';
+export { PositionsPanel } from './PositionsPanel';
+export { HoldingsPanel } from './HoldingsPanel';
+export { OrdersPanel } from './OrdersPanel';
+export { FundsPanel } from './FundsPanel';
+export { StockTradingChart } from './StockTradingChart';
+export { SymbolSearch } from './SymbolSearch';
+export { MasterContractManager } from './MasterContractManager';
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-trading/index.ts
new file mode 100644
index 000000000..67b89b627
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/index.ts
@@ -0,0 +1,8 @@
+/**
+ * Equity Trading Module
+ *
+ * Unified stock trading interface for all brokers
+ */
+
+export { EquityTradingTab, default } from './EquityTradingTab';
+export * from './components';
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/AgentMediatorNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/AgentMediatorNode.tsx
index 4a1b9dfa6..97e6d5f13 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/AgentMediatorNode.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/AgentMediatorNode.tsx
@@ -2,7 +2,17 @@
import React, { useState, useEffect } from 'react';
import { Handle, Position } from 'reactflow';
import { MessageSquare, Settings, CheckCircle, AlertCircle, Loader, Brain } from 'lucide-react';
-import { sqliteService, LLMConfig } from '@/services/core/sqliteService';
+import { sqliteService, LLMConfig, LLMModelConfig } from '@/services/core/sqliteService';
+
+// Combined LLM option for display
+interface LLMOption {
+ id: string;
+ provider: string;
+ model: string;
+ displayName: string;
+ type: 'provider' | 'model' | 'fincept';
+ isActive?: boolean;
+}
interface AgentMediatorNodeProps {
id: string;
@@ -22,7 +32,7 @@ interface AgentMediatorNodeProps {
const AgentMediatorNode: React.FC<AgentMediatorNodeProps> = ({ id, data, selected }) => {
const [showSettings, setShowSettings] = useState(false);
- const [availableProviders, setAvailableProviders] = useState<LLMConfig[]>([]);
+ const [availableProviders, setAvailableProviders] = useState<LLMOption[]>([]);
const [localProvider, setLocalProvider] = useState(data.selectedProvider || 'active');
const [localPrompt, setLocalPrompt] = useState(data.customPrompt || '');
@@ -37,14 +47,76 @@ const AgentMediatorNode: React.FC<AgentMediatorNodeProps> = ({ id, data, selecte
const RED = '#ef4444';
const BLUE = '#3b82f6';
- // Load available LLM providers
+ // Load available LLM providers (both LLMConfig and LLMModelConfig)
useEffect(() => {
const loadProviders = async () => {
try {
- const configs = await sqliteService.getLLMConfigs();
- setAvailableProviders(configs);
+ const options: LLMOption[] = [];
+
+ // Load provider-level configs (LLMConfig)
+ const providerConfigs = await sqliteService.getLLMConfigs();
+ for (const config of providerConfigs) {
+ // Fincept is special - always show it prominently
+ if (config.provider === 'fincept') {
+ options.unshift({
+ id: 'fincept',
+ provider: 'fincept',
+ model: config.model || 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: config.is_active
+ });
+ } else {
+ options.push({
+ id: config.provider,
+ provider: config.provider,
+ model: config.model,
+ displayName: `${config.provider.toUpperCase()} - ${config.model}`,
+ type: 'provider',
+ isActive: config.is_active
+ });
+ }
+ }
+
+ // Load custom model configs (LLMModelConfig) from Settings
+ const modelConfigs = await sqliteService.getLLMModelConfigs();
+ for (const model of modelConfigs) {
+ if (model.is_enabled) {
+ options.push({
+ id: model.id,
+ provider: model.provider,
+ model: model.model_id,
+ displayName: `${model.display_name} (${model.provider.toUpperCase()})`,
+ type: 'model',
+ isActive: model.is_default
+ });
+ }
+ }
+
+ // If Fincept wasn't in provider configs, add it as default
+ if (!options.find(o => o.provider === 'fincept')) {
+ options.unshift({
+ id: 'fincept',
+ provider: 'fincept',
+ model: 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: true
+ });
+ }
+
+ setAvailableProviders(options);
} catch (error) {
console.error('Failed to load LLM providers:', error);
+ // Default to Fincept if loading fails
+ setAvailableProviders([{
+ id: 'fincept',
+ provider: 'fincept',
+ model: 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: true
+ }]);
}
};
loadProviders();
@@ -80,8 +152,8 @@ const AgentMediatorNode: React.FC<AgentMediatorNodeProps> = ({ id, data, selecte
if (!data.selectedProvider || data.selectedProvider === 'active') {
return 'Active Provider';
}
- const provider = availableProviders.find(p => p.provider === data.selectedProvider);
- return provider ? `${provider.provider.toUpperCase()} - ${provider.model}` : data.selectedProvider;
+ const provider = availableProviders.find(p => p.id === data.selectedProvider);
+ return provider ? provider.displayName : data.selectedProvider;
};
return (
@@ -298,15 +370,17 @@ const AgentMediatorNode: React.FC<AgentMediatorNodeProps> = ({ id, data, selecte
backgroundColor: PANEL_BG,
border: `1px solid ${BORDER}`,
color: WHITE,
- padding: '4px',
- fontSize: '8px',
+ padding: '6px',
+ fontSize: '10px',
borderRadius: '3px'
}}
>
- <option value="active">Use Active Provider</option>
+ <option value="active">Use Active Provider (from Settings)</option>
{availableProviders.map(provider => (
- <option key={provider.provider} value={provider.provider}>
- {provider.provider.toUpperCase()} - {provider.model}
+ <option key={provider.id} value={provider.id} style={{
+ backgroundColor: provider.type === 'fincept' ? '#1a3a1a' : undefined
+ }}>
+ {provider.displayName}{provider.isActive ? ' ✓' : ''}
</option>
))}
</select>
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/NodeConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/NodeConfigPanel.tsx
deleted file mode 100644
index ab5437498..000000000
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/NodeConfigPanel.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-/**
- * Node Configuration Panel
- *
- * Displays and allows editing of all parameters for a selected node.
- * Renders the parameter input UI using NodeParameterInput component.
- *
- * Features:
- * - Dynamic parameter rendering based on node type
- * - Expression support for all parameters
- * - Parameter validation
- * - Conditional parameters (displayOptions)
- * - Collection and FixedCollection support
- * - Real-time parameter updates
- */
-
-import React, { useCallback, useMemo } from 'react';
-import type {
- INode,
- INodeProperties,
- NodeParameterValue,
- INodeType,
-} from '@/services/nodeSystem';
-import { NodeRegistry } from '@/services/nodeSystem';
-import NodeParameterInput from './NodeParameterInput';
-import { Settings2, X, Info, AlertCircle } from 'lucide-react';
-
-interface NodeConfigPanelProps {
- node: INode | null;
- onNodeUpdate: (nodeId: string, parameters: Record<string, any>) => void;
- onClose: () => void;
-}
-
-export const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
- node,
- onNodeUpdate,
- onClose,
-}) => {
- // Get node type definition
- const nodeType = useMemo<INodeType | null>(() => {
- if (!node) return null;
- try {
- return NodeRegistry.getNodeType(node.type, node.typeVersion);
- } catch (error) {
- console.error('Failed to get node type:', error);
- return null;
- }
- }, [node]);
-
- // Filter parameters based on displayOptions
- const visibleParameters = useMemo(() => {
- if (!nodeType?.description?.properties) return [];
-
- return nodeType.description.properties.filter((param) => {
- if (!param.displayOptions) return true;
-
- // Check show conditions
- if (param.displayOptions.show) {
- for (const [paramName, allowedValues] of Object.entries(param.displayOptions.show)) {
- const currentValue = node?.parameters[paramName];
- const values = Array.isArray(allowedValues) ? allowedValues : [allowedValues];
-
- if (!values.includes(currentValue as any)) {
- return false;
- }
- }
- }
-
- // Check hide conditions
- if (param.displayOptions.hide) {
- for (const [paramName, hiddenValues] of Object.entries(param.displayOptions.hide)) {
- const currentValue = node?.parameters[paramName];
- const values = Array.isArray(hiddenValues) ? hiddenValues : [hiddenValues];
-
- if (values.includes(currentValue as any)) {
- return false;
- }
- }
- }
-
- return true;
- });
- }, [nodeType, node?.parameters]);
-
- // Handle parameter change
- const handleParameterChange = useCallback(
- (paramName: string, value: NodeParameterValue) => {
- if (!node) return;
-
- const updatedParameters = {
- ...node.parameters,
- [paramName]: value,
- };
-
- onNodeUpdate(node.name, updatedParameters);
- },
- [node, onNodeUpdate]
- );
-
- if (!node) {
- return (
- <div className="w-96 bg-gray-900 border-l border-gray-800 flex items-center justify-center">
- <div className="text-center text-gray-500">
- <Settings2 size={48} className="mx-auto mb-4 opacity-30" />
- <p>Select a node to configure</p>
- </div>
- </div>
- );
- }
-
- if (!nodeType) {
- return (
- <div className="w-96 bg-gray-900 border-l border-gray-800 flex items-center justify-center">
- <div className="text-center text-red-400">
- <AlertCircle size={48} className="mx-auto mb-4" />
- <p>Node type not found</p>
- <p className="text-sm text-gray-500 mt-2">{node.type}</p>
- </div>
- </div>
- );
- }
-
- return (
- <div className="w-96 bg-gray-900 border-l border-gray-800 flex flex-col h-full">
- {/* Panel Header */}
- <div className="border-b border-gray-800 p-4 flex items-center justify-between">
- <div className="flex items-center gap-3">
- <div
- className="w-10 h-10 rounded flex items-center justify-center"
- style={{
- background: `${nodeType.description.defaults.color}20`,
- border: `2px solid ${nodeType.description.defaults.color}40`,
- }}
- >
- <Settings2 size={20} style={{ color: nodeType.description.defaults.color }} />
- </div>
- <div>
- <h3 className="text-sm font-semibold text-gray-200">
- {nodeType.description.displayName}
- </h3>
- <p className="text-xs text-gray-500">{node.name}</p>
- </div>
- </div>
- <button
- onClick={onClose}
- className="p-1.5 hover:bg-gray-800 rounded transition-colors"
- title="Close"
- >
- <X size={18} className="text-gray-400" />
- </button>
- </div>
-
- {/* Node Description */}
- {nodeType.description.description && (
- <div className="p-4 bg-blue-500/10 border-b border-gray-800">
- <div className="flex items-start gap-2">
- <Info size={16} className="text-blue-400 mt-0.5 flex-shrink-0" />
- <p className="text-xs text-blue-300">{nodeType.description.description}</p>
- </div>
- </div>
- )}
-
- {/* Parameters List */}
- <div className="flex-1 overflow-y-auto p-4 space-y-4">
- {visibleParameters.length === 0 ? (
- <div className="text-center text-gray-500 py-8">
- <Settings2 size={32} className="mx-auto mb-2 opacity-30" />
- <p className="text-sm">No parameters to configure</p>
- </div>
- ) : (
- visibleParameters.map((param) => (
- <div key={param.name} className="pb-4 border-b border-gray-800 last:border-0">
- <NodeParameterInput
- parameter={param}
- value={node.parameters[param.name] ?? param.default}
- onChange={(value) => handleParameterChange(param.name, value)}
- disabled={node.disabled}
- />
- </div>
- ))
- )}
- </div>
-
- {/* Panel Footer */}
- <div className="border-t border-gray-800 p-4 bg-gray-900">
- <div className="flex items-center justify-between text-xs text-gray-500">
- <span>Node ID: {node.name}</span>
- <span>
- {node.disabled ? (
- <span className="text-yellow-500">Disabled</span>
- ) : (
- <span className="text-green-500">Active</span>
- )}
- </span>
- </div>
- </div>
- </div>
- );
-};
-
-export default NodeConfigPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/NodePalette.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/NodePalette.tsx
deleted file mode 100644
index 47e3d6efa..000000000
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/NodePalette.tsx
+++ /dev/null
@@ -1,268 +0,0 @@
-/**
- * Node Palette Component
- *
- * Displays available nodes from the NodeRegistry that can be added to the workflow.
- * Organized by category with search functionality.
- *
- * Features:
- * - Search nodes by name
- * - Filter by category
- * - Drag and drop to canvas
- * - Node descriptions on hover
- * - Category-based organization
- */
-
-import React, { useState, useMemo } from 'react';
-import { NodeRegistry } from '@/services/nodeSystem';
-import type { INodeTypeDescription } from '@/services/nodeSystem';
-import {
- Search,
- Database,
- Workflow,
- FileText,
- Code,
- GitBranch,
- Filter,
- Settings,
- ChevronRight,
- ChevronDown,
-} from 'lucide-react';
-
-interface NodePaletteProps {
- onNodeAdd: (nodeType: string) => void;
- onDragStart?: (nodeType: string, event: React.DragEvent) => void;
-}
-
-export const NodePalette: React.FC<NodePaletteProps> = ({
- onNodeAdd,
- onDragStart,
-}) => {
- const [searchQuery, setSearchQuery] = useState('');
- const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
- new Set(['Core'])
- );
-
- // Get all registered nodes
- const allNodes = useMemo(() => {
- return NodeRegistry.getAllNodes();
- }, []);
-
- // Group nodes by category
- const nodesByCategory = useMemo(() => {
- const grouped = new Map<string, INodeTypeDescription[]>();
-
- for (const node of allNodes) {
- const category = node.group || ['Uncategorized'];
- const categoryName = Array.isArray(category) ? category[0] : category;
-
- if (!grouped.has(categoryName)) {
- grouped.set(categoryName, []);
- }
-
- grouped.get(categoryName)!.push(node);
- }
-
- // Sort each category alphabetically
- for (const nodes of grouped.values()) {
- nodes.sort((a, b) => a.displayName.localeCompare(b.displayName));
- }
-
- return grouped;
- }, [allNodes]);
-
- // Filter nodes based on search query
- const filteredCategories = useMemo(() => {
- if (!searchQuery.trim()) {
- return nodesByCategory;
- }
-
- const query = searchQuery.toLowerCase();
- const filtered = new Map<string, INodeTypeDescription[]>();
-
- for (const [category, nodes] of nodesByCategory.entries()) {
- const matchingNodes = nodes.filter(
- (node) =>
- node.displayName.toLowerCase().includes(query) ||
- node.name.toLowerCase().includes(query) ||
- node.description?.toLowerCase().includes(query)
- );
-
- if (matchingNodes.length > 0) {
- filtered.set(category, matchingNodes);
- }
- }
-
- return filtered;
- }, [nodesByCategory, searchQuery]);
-
- // Toggle category expansion
- const toggleCategory = (category: string) => {
- const newExpanded = new Set(expandedCategories);
- if (newExpanded.has(category)) {
- newExpanded.delete(category);
- } else {
- newExpanded.add(category);
- }
- setExpandedCategories(newExpanded);
- };
-
- // Get category icon
- const getCategoryIcon = (category: string) => {
- switch (category.toLowerCase()) {
- case 'core':
- return <Workflow size={16} />;
- case 'data':
- return <Database size={16} />;
- case 'transform':
- return <Filter size={16} />;
- case 'control':
- return <GitBranch size={16} />;
- case 'output':
- return <FileText size={16} />;
- case 'developer':
- return <Code size={16} />;
- default:
- return <Settings size={16} />;
- }
- };
-
- // Get node icon color
- const getNodeColor = (node: INodeTypeDescription) => {
- return node.defaults?.color || '#888888';
- };
-
- // Handle drag start
- const handleDragStart = (nodeType: string, event: React.DragEvent) => {
- event.dataTransfer.setData('application/reactflow', nodeType);
- event.dataTransfer.effectAllowed = 'move';
- onDragStart?.(nodeType, event);
- };
-
- return (
- <div className="w-80 bg-gray-900 border-r border-gray-800 flex flex-col h-full">
- {/* Palette Header */}
- <div className="p-4 border-b border-gray-800">
- <h3 className="text-sm font-semibold text-gray-200 mb-3 flex items-center gap-2">
- <Database size={16} className="text-blue-400" />
- Node Palette
- </h3>
-
- {/* Search Input */}
- <div className="relative">
- <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
- <input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Search nodes..."
- className="w-full pl-10 pr-3 py-2 bg-gray-800 border border-gray-700 rounded text-sm text-gray-200 placeholder-gray-500 focus:border-blue-500 focus:outline-none"
- />
- </div>
-
- <div className="text-xs text-gray-500 mt-2">
- {allNodes.length} nodes available
- </div>
- </div>
-
- {/* Node Categories */}
- <div className="flex-1 overflow-y-auto">
- {Array.from(filteredCategories.entries()).map(([category, nodes]) => (
- <div key={category} className="border-b border-gray-800 last:border-0">
- {/* Category Header */}
- <button
- onClick={() => toggleCategory(category)}
- className="w-full px-4 py-3 flex items-center justify-between hover:bg-gray-800/50 transition-colors"
- >
- <div className="flex items-center gap-2 text-sm text-gray-300">
- {getCategoryIcon(category)}
- <span className="font-medium">{category}</span>
- <span className="text-xs text-gray-600">({nodes.length})</span>
- </div>
- {expandedCategories.has(category) ? (
- <ChevronDown size={16} className="text-gray-500" />
- ) : (
- <ChevronRight size={16} className="text-gray-500" />
- )}
- </button>
-
- {/* Category Nodes */}
- {expandedCategories.has(category) && (
- <div className="pb-2">
- {nodes.map((node) => (
- <div
- key={node.name}
- draggable
- onDragStart={(e) => handleDragStart(node.name, e)}
- onClick={() => onNodeAdd(node.name)}
- className="mx-2 mb-1 p-3 bg-gray-800/30 hover:bg-gray-800 rounded cursor-pointer transition-colors group"
- title={node.description}
- >
- <div className="flex items-start gap-3">
- {/* Node Icon */}
- <div
- className="w-8 h-8 rounded flex items-center justify-center flex-shrink-0 mt-0.5"
- style={{
- background: `${getNodeColor(node)}20`,
- border: `1px solid ${getNodeColor(node)}40`,
- }}
- >
- <div
- className="text-xs font-bold"
- style={{ color: getNodeColor(node) }}
- >
- {node.displayName[0]}
- </div>
- </div>
-
- {/* Node Info */}
- <div className="flex-1 min-w-0">
- <div
- className="text-sm font-medium mb-0.5"
- style={{ color: getNodeColor(node) }}
- >
- {node.displayName}
- </div>
-
- {node.description && (
- <div className="text-xs text-gray-500 line-clamp-2">
- {node.description}
- </div>
- )}
-
- {node.version && (
- <div className="text-xs text-gray-600 mt-1">
- v{node.version}
- </div>
- )}
- </div>
- </div>
- </div>
- ))}
- </div>
- )}
- </div>
- ))}
-
- {/* No Results */}
- {filteredCategories.size === 0 && (
- <div className="p-8 text-center">
- <Search size={32} className="mx-auto mb-2 text-gray-600" />
- <p className="text-sm text-gray-500">No nodes found</p>
- <p className="text-xs text-gray-600 mt-1">
- Try a different search term
- </p>
- </div>
- )}
- </div>
-
- {/* Palette Footer */}
- <div className="p-4 border-t border-gray-800 bg-gray-900">
- <div className="text-xs text-gray-500 text-center">
- Drag nodes to the canvas or click to add
- </div>
- </div>
- </div>
- );
-};
-
-export default NodePalette;
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/NodeParameterInput.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/NodeParameterInput.tsx
index 012983b94..c85d7900d 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/NodeParameterInput.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/NodeParameterInput.tsx
@@ -1,5 +1,5 @@
/**
- * Node Parameter Input Component
+ * Node Parameter Input Component - Bloomberg Terminal Style
*
* Universal parameter input component that renders the appropriate UI control
* based on the parameter type from the node system.
@@ -20,10 +20,50 @@ import type {
NodeParameterValue,
NodePropertyType,
INodePropertyOptions,
- INodePropertyCollectionValue,
} from '@/services/nodeSystem';
-import { ExpressionEngine, isExpression } from '@/services/nodeSystem';
-import { Check, Code2, Calendar, Hash, Type, List, Settings2, Palette } from 'lucide-react';
+import { isExpression } from '@/services/nodeSystem';
+import { Check, Code2, Calendar, Hash, Type, List, Settings2, Palette, ChevronDown } from 'lucide-react';
+
+// Bloomberg Terminal Style Constants
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ YELLOW: '#FFD700',
+ CYAN: '#00E5FF',
+ GRAY: '#BBBBBB',
+ MUTED: '#888888',
+ DARK_BG: '#000000',
+ PANEL_BG: '#141414',
+ INPUT_BG: '#1A1A1A',
+ BORDER: '#3A3A3A',
+ FONT: '"IBM Plex Mono", "Consolas", monospace',
+};
+
+const inputBaseStyle: React.CSSProperties = {
+ width: '100%',
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '10px 12px',
+ color: BLOOMBERG.WHITE,
+ fontSize: '13px',
+ fontFamily: BLOOMBERG.FONT,
+ outline: 'none',
+ transition: 'all 0.15s ease',
+};
+
+const labelStyle: React.CSSProperties = {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ color: BLOOMBERG.GRAY,
+ fontSize: '12px',
+ fontWeight: 600,
+ marginBottom: '8px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+};
interface NodeParameterInputProps {
parameter: INodeProperties;
@@ -41,12 +81,11 @@ export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
onChange,
onExpressionChange,
disabled = false,
- itemIndex = 0,
- expressionContext,
}) => {
const [isExpressionMode, setIsExpressionMode] = useState(
typeof value === 'string' && isExpression(value)
);
+ const [isFocused, setIsFocused] = useState(false);
const handleToggleExpression = useCallback(() => {
const newMode = !isExpressionMode;
@@ -54,10 +93,8 @@ export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
onExpressionChange?.(newMode);
if (newMode) {
- // Convert to expression
onChange(`={{${value}}}`);
} else {
- // Convert back to regular value
const strValue = String(value);
if (strValue.startsWith('={{') && strValue.endsWith('}}')) {
onChange(strValue.slice(3, -2));
@@ -65,8 +102,13 @@ export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
}
}, [isExpressionMode, value, onChange, onExpressionChange]);
+ const getFocusStyle = (): React.CSSProperties => ({
+ borderColor: isFocused ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER,
+ boxShadow: isFocused ? `0 0 8px ${BLOOMBERG.ORANGE}30` : 'none',
+ backgroundColor: isFocused ? BLOOMBERG.PANEL_BG : BLOOMBERG.INPUT_BG,
+ });
+
const renderInput = () => {
- // Expression mode - show code editor
if (isExpressionMode) {
return (
<textarea
@@ -74,47 +116,43 @@ export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
placeholder="={{$json.field}}"
- className="w-full px-3 py-2 bg-gray-800 border border-yellow-500/30 rounded text-yellow-400 font-mono text-sm resize-y min-h-[60px]"
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ color: BLOOMBERG.YELLOW,
+ minHeight: '60px',
+ resize: 'vertical',
+ }}
/>
);
}
- // Regular input based on type
switch (parameter.type) {
case 'string' as NodePropertyType:
return renderStringInput();
-
case 'number' as NodePropertyType:
return renderNumberInput();
-
case 'boolean' as NodePropertyType:
return renderBooleanInput();
-
case 'options' as NodePropertyType:
return renderOptionsInput();
-
case 'multiOptions' as NodePropertyType:
return renderMultiOptionsInput();
-
case 'color' as NodePropertyType:
return renderColorInput();
-
case 'dateTime' as NodePropertyType:
return renderDateTimeInput();
-
case 'json' as NodePropertyType:
case 'code' as NodePropertyType:
return renderCodeInput();
-
case 'collection' as NodePropertyType:
return renderCollectionInput();
-
case 'fixedCollection' as NodePropertyType:
return renderFixedCollectionInput();
-
case 'resourceLocator' as NodePropertyType:
return renderResourceLocatorInput();
-
default:
return renderStringInput();
}
@@ -126,53 +164,144 @@ export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
value={String(value || '')}
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
- placeholder={parameter.placeholder}
- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
+ placeholder={parameter.placeholder || 'Enter value...'}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ }}
/>
);
const renderNumberInput = () => (
- <input
- type="number"
- value={Number(value || 0)}
- onChange={(e) => onChange(Number(e.target.value))}
- disabled={disabled}
- placeholder={parameter.placeholder}
- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
- />
- );
-
- const renderBooleanInput = () => (
- <label className="flex items-center gap-2 cursor-pointer">
+ <div style={{ display: 'flex', alignItems: 'stretch' }}>
+ <div style={{
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${isFocused ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ borderRight: 'none',
+ padding: '0 10px',
+ display: 'flex',
+ alignItems: 'center',
+ color: BLOOMBERG.ORANGE,
+ fontSize: '13px',
+ transition: 'all 0.15s ease',
+ }}>
+ <Hash size={14} />
+ </div>
<input
- type="checkbox"
- checked={Boolean(value)}
- onChange={(e) => onChange(e.target.checked)}
+ type="number"
+ value={Number(value || 0)}
+ onChange={(e) => onChange(Number(e.target.value))}
disabled={disabled}
- className="w-4 h-4 rounded border-gray-700 bg-gray-800 text-blue-500 focus:ring-blue-500"
+ placeholder={parameter.placeholder}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ borderLeft: 'none',
+ flex: 1,
+ }}
/>
- <span className="text-sm text-gray-300">
- {parameter.description || 'Enable'}
+ </div>
+ );
+
+ const renderBooleanInput = () => (
+ <div
+ onClick={() => !disabled && onChange(!Boolean(value))}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ padding: '8px 10px',
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ transition: 'all 0.15s ease',
+ }}
+ onMouseEnter={(e) => {
+ if (!disabled) e.currentTarget.style.borderColor = BLOOMBERG.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;
+ }}
+ >
+ <div style={{
+ width: '32px',
+ height: '16px',
+ backgroundColor: Boolean(value) ? BLOOMBERG.GREEN : BLOOMBERG.MUTED,
+ borderRadius: '8px',
+ position: 'relative',
+ transition: 'all 0.15s ease',
+ }}>
+ <div style={{
+ position: 'absolute',
+ top: '2px',
+ left: Boolean(value) ? '16px' : '2px',
+ width: '12px',
+ height: '12px',
+ backgroundColor: BLOOMBERG.WHITE,
+ borderRadius: '50%',
+ transition: 'all 0.15s ease',
+ }} />
+ </div>
+ <span style={{
+ color: Boolean(value) ? BLOOMBERG.GREEN : BLOOMBERG.GRAY,
+ fontSize: '13px',
+ fontFamily: BLOOMBERG.FONT,
+ fontWeight: 600,
+ textTransform: 'uppercase',
+ }}>
+ {Boolean(value) ? 'ENABLED' : 'DISABLED'}
</span>
- </label>
+ </div>
);
const renderOptionsInput = () => {
const options = parameter.options as INodePropertyOptions[] | undefined;
return (
- <select
- value={String(value || parameter.default || '')}
- onChange={(e) => onChange(e.target.value)}
- disabled={disabled}
- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
- >
- {options?.map((option) => (
- <option key={String(option.value)} value={String(option.value)}>
- {option.name}
- </option>
- ))}
- </select>
+ <div style={{ position: 'relative' }}>
+ <select
+ value={String(value || parameter.default || '')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ appearance: 'none',
+ paddingRight: '28px',
+ cursor: 'pointer',
+ }}
+ >
+ {options?.map((option) => (
+ <option
+ key={String(option.value)}
+ value={String(option.value)}
+ style={{
+ backgroundColor: BLOOMBERG.DARK_BG,
+ color: BLOOMBERG.WHITE,
+ }}
+ >
+ {option.name}
+ </option>
+ ))}
+ </select>
+ <ChevronDown
+ size={16}
+ style={{
+ position: 'absolute',
+ right: '12px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ color: BLOOMBERG.ORANGE,
+ pointerEvents: 'none',
+ }}
+ />
+ </div>
);
};
@@ -181,56 +310,121 @@ export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
const selectedValues = Array.isArray(value) ? value : [];
return (
- <div className="space-y-2">
+ <div style={{
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px',
+ }}>
{options?.map((option) => (
- <label key={String(option.value)} className="flex items-center gap-2 cursor-pointer">
- <input
- type="checkbox"
- checked={selectedValues.includes(option.value)}
- onChange={(e) => {
- const newValues = e.target.checked
- ? [...selectedValues, option.value]
- : selectedValues.filter((v) => v !== option.value);
- onChange(newValues);
- }}
- disabled={disabled}
- className="w-4 h-4 rounded border-gray-700 bg-gray-800 text-blue-500"
- />
- <span className="text-sm text-gray-300">{option.name}</span>
- </label>
+ <div
+ key={String(option.value)}
+ onClick={() => {
+ if (disabled) return;
+ const newValues = selectedValues.includes(option.value)
+ ? selectedValues.filter((v) => v !== option.value)
+ : [...selectedValues, option.value];
+ onChange(newValues);
+ }}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '6px 8px',
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ backgroundColor: selectedValues.includes(option.value) ? `${BLOOMBERG.ORANGE}15` : 'transparent',
+ marginBottom: '4px',
+ transition: 'all 0.15s ease',
+ }}
+ >
+ <div style={{
+ width: '18px',
+ height: '18px',
+ border: `2px solid ${selectedValues.includes(option.value) ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ backgroundColor: selectedValues.includes(option.value) ? BLOOMBERG.ORANGE : 'transparent',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}>
+ {selectedValues.includes(option.value) && (
+ <Check size={14} style={{ color: BLOOMBERG.DARK_BG }} />
+ )}
+ </div>
+ <span style={{
+ color: selectedValues.includes(option.value) ? BLOOMBERG.WHITE : BLOOMBERG.GRAY,
+ fontSize: '13px',
+ fontFamily: BLOOMBERG.FONT,
+ }}>
+ {option.name}
+ </span>
+ </div>
))}
</div>
);
};
const renderColorInput = () => (
- <div className="flex items-center gap-2">
+ <div style={{ display: 'flex', alignItems: 'stretch', gap: '8px' }}>
<input
type="color"
- value={String(value || '#000000')}
+ value={String(value || '#FF8800')}
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
- className="w-12 h-10 rounded border border-gray-700 bg-gray-800 cursor-pointer"
+ style={{
+ width: '40px',
+ height: '32px',
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ cursor: 'pointer',
+ padding: '2px',
+ }}
/>
<input
type="text"
- value={String(value || '#000000')}
+ value={String(value || '#FF8800')}
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
- placeholder="#000000"
- className="flex-1 px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm font-mono focus:border-blue-500 focus:outline-none"
+ placeholder="#FF8800"
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ flex: 1,
+ textTransform: 'uppercase',
+ }}
/>
</div>
);
const renderDateTimeInput = () => (
- <input
- type="datetime-local"
- value={value ? new Date(value as string | number).toISOString().slice(0, 16) : ''}
- onChange={(e) => onChange(new Date(e.target.value).toISOString())}
- disabled={disabled}
- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
- />
+ <div style={{ display: 'flex', alignItems: 'stretch' }}>
+ <div style={{
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${isFocused ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ borderRight: 'none',
+ padding: '0 10px',
+ display: 'flex',
+ alignItems: 'center',
+ color: BLOOMBERG.ORANGE,
+ transition: 'all 0.15s ease',
+ }}>
+ <Calendar size={14} />
+ </div>
+ <input
+ type="datetime-local"
+ value={value ? new Date(value as string | number).toISOString().slice(0, 16) : ''}
+ onChange={(e) => onChange(new Date(e.target.value).toISOString())}
+ disabled={disabled}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ borderLeft: 'none',
+ flex: 1,
+ }}
+ />
+ </div>
);
const renderCodeInput = () => (
@@ -239,101 +433,170 @@ export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
onChange={(e) => onChange(e.target.value)}
disabled={disabled}
placeholder={parameter.placeholder || '// Enter code here'}
- className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded text-green-400 font-mono text-sm resize-y min-h-[120px] focus:border-blue-500 focus:outline-none"
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ color: BLOOMBERG.GREEN,
+ minHeight: '100px',
+ resize: 'vertical',
+ lineHeight: '1.5',
+ }}
/>
);
const renderCollectionInput = () => (
- <div className="p-3 bg-gray-800/50 border border-gray-700 rounded">
- <div className="text-sm text-gray-400 mb-2">Collection (Advanced)</div>
+ <div style={{
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '12px',
+ }}>
+ <div style={{
+ color: BLOOMBERG.CYAN,
+ fontSize: '12px',
+ fontWeight: 700,
+ marginBottom: '10px',
+ textTransform: 'uppercase',
+ }}>
+ COLLECTION (JSON)
+ </div>
<textarea
value={JSON.stringify(value, null, 2)}
onChange={(e) => {
try {
onChange(JSON.parse(e.target.value));
} catch {
- // Invalid JSON, keep as string
+ // Invalid JSON
}
}}
disabled={disabled}
- className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded text-gray-200 font-mono text-xs resize-y min-h-[100px]"
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ minHeight: '80px',
+ resize: 'vertical',
+ fontSize: '12px',
+ }}
/>
</div>
);
const renderFixedCollectionInput = () => (
- <div className="p-3 bg-gray-800/50 border border-gray-700 rounded">
- <div className="text-sm text-gray-400 mb-2">Fixed Collection</div>
- <div className="text-xs text-gray-500">
- Complex input - configure in advanced editor
+ <div style={{
+ backgroundColor: BLOOMBERG.INPUT_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '14px',
+ textAlign: 'center',
+ }}>
+ <Settings2 size={20} style={{ color: BLOOMBERG.MUTED, margin: '0 auto 10px' }} />
+ <div style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '12px',
+ textTransform: 'uppercase',
+ }}>
+ ADVANCED CONFIGURATION
+ </div>
+ <div style={{ color: BLOOMBERG.MUTED, fontSize: '11px', marginTop: '6px' }}>
+ Configure in advanced editor
</div>
</div>
);
const renderResourceLocatorInput = () => {
- // ResourceLocator typically has mode selector and value input
const resourceValue = (value as any) || { mode: 'id', value: '' };
return (
- <div className="space-y-2">
- <select
- value={resourceValue.mode || 'id'}
- onChange={(e) => onChange({ ...resourceValue, mode: e.target.value })}
- disabled={disabled}
- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm"
- >
- <option value="id">By ID</option>
- <option value="url">By URL</option>
- <option value="list">From List</option>
- </select>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ <div style={{ position: 'relative' }}>
+ <select
+ value={resourceValue.mode || 'id'}
+ onChange={(e) => onChange({ ...resourceValue, mode: e.target.value })}
+ disabled={disabled}
+ style={{
+ ...inputBaseStyle,
+ appearance: 'none',
+ paddingRight: '28px',
+ cursor: 'pointer',
+ }}
+ >
+ <option value="id" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>BY ID</option>
+ <option value="url" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>BY URL</option>
+ <option value="list" style={{ backgroundColor: BLOOMBERG.DARK_BG }}>FROM LIST</option>
+ </select>
+ <ChevronDown
+ size={16}
+ style={{
+ position: 'absolute',
+ right: '12px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ color: BLOOMBERG.ORANGE,
+ pointerEvents: 'none',
+ }}
+ />
+ </div>
<input
type="text"
value={resourceValue.value || ''}
onChange={(e) => onChange({ ...resourceValue, value: e.target.value })}
disabled={disabled}
placeholder={`Enter ${resourceValue.mode || 'ID'}...`}
- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-gray-200 text-sm focus:border-blue-500 focus:outline-none"
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ }}
/>
</div>
);
};
const getParameterIcon = () => {
+ const iconStyle = { color: BLOOMBERG.ORANGE };
switch (parameter.type) {
case 'string' as NodePropertyType:
- return <Type size={14} />;
+ return <Type size={14} style={iconStyle} />;
case 'number' as NodePropertyType:
- return <Hash size={14} />;
+ return <Hash size={14} style={iconStyle} />;
case 'boolean' as NodePropertyType:
- return <Check size={14} />;
+ return <Check size={14} style={iconStyle} />;
case 'options' as NodePropertyType:
case 'multiOptions' as NodePropertyType:
- return <List size={14} />;
+ return <List size={14} style={iconStyle} />;
case 'color' as NodePropertyType:
- return <Palette size={14} />;
+ return <Palette size={14} style={iconStyle} />;
case 'dateTime' as NodePropertyType:
- return <Calendar size={14} />;
+ return <Calendar size={14} style={iconStyle} />;
case 'json' as NodePropertyType:
case 'code' as NodePropertyType:
- return <Code2 size={14} />;
+ return <Code2 size={14} style={iconStyle} />;
case 'collection' as NodePropertyType:
case 'fixedCollection' as NodePropertyType:
- return <Settings2 size={14} />;
+ return <Settings2 size={14} style={iconStyle} />;
default:
- return <Type size={14} />;
+ return <Type size={14} style={iconStyle} />;
}
};
return (
- <div className="space-y-2">
+ <div style={{ marginBottom: '4px' }}>
{/* Parameter Header */}
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <span className="text-gray-400">{getParameterIcon()}</span>
- <label className="text-sm font-medium text-gray-200">
- {parameter.displayName}
- {parameter.required && <span className="text-red-400 ml-1">*</span>}
- </label>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '6px',
+ }}>
+ <div style={labelStyle}>
+ {getParameterIcon()}
+ <span>{parameter.displayName}</span>
+ {parameter.required && (
+ <span style={{ color: BLOOMBERG.RED, marginLeft: '2px' }}>*</span>
+ )}
</div>
{/* Expression Toggle */}
@@ -341,22 +604,38 @@ export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
<button
onClick={handleToggleExpression}
disabled={disabled}
- className={`px-2 py-1 text-xs rounded flex items-center gap-1 transition-colors ${
- isExpressionMode
- ? 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30'
- : 'bg-gray-800 text-gray-400 border border-gray-700 hover:border-yellow-500/50'
- }`}
- title="Toggle expression mode"
+ style={{
+ padding: '4px 8px',
+ fontSize: '10px',
+ fontFamily: BLOOMBERG.FONT,
+ fontWeight: 600,
+ border: `1px solid ${isExpressionMode ? BLOOMBERG.YELLOW : BLOOMBERG.BORDER}`,
+ backgroundColor: isExpressionMode ? `${BLOOMBERG.YELLOW}20` : 'transparent',
+ color: isExpressionMode ? BLOOMBERG.YELLOW : BLOOMBERG.GRAY,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ textTransform: 'uppercase',
+ transition: 'all 0.15s ease',
+ }}
>
<Code2 size={12} />
- {isExpressionMode ? 'Expression' : 'Fixed'}
+ {isExpressionMode ? 'EXPR' : 'FIXED'}
</button>
)}
</div>
{/* Parameter Description */}
{parameter.description && (
- <div className="text-xs text-gray-500">{parameter.description}</div>
+ <div style={{
+ fontSize: '11px',
+ color: BLOOMBERG.MUTED,
+ marginBottom: '8px',
+ lineHeight: '1.5',
+ }}>
+ {parameter.description}
+ </div>
)}
{/* Parameter Input */}
@@ -364,43 +643,15 @@ export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
{/* Expression Hint */}
{isExpressionMode && (
- <div className="text-xs text-yellow-500/70">
- Use expressions like: <code className="bg-gray-900 px-1 rounded">{'{{$json.field}}'}</code> or{' '}
- <code className="bg-gray-900 px-1 rounded">={'{{1 + 2}}'}</code>
+ <div style={{
+ fontSize: '8px',
+ color: `${BLOOMBERG.YELLOW}90`,
+ marginTop: '4px',
+ fontFamily: BLOOMBERG.FONT,
+ }}>
+ SYNTAX: <code style={{ backgroundColor: BLOOMBERG.PANEL_BG, padding: '1px 4px' }}>{'{{$json.field}}'}</code>
</div>
)}
-
- {/* Validation Error */}
- {parameter.validateType && value && (
- <ValidationMessage parameter={parameter} value={value} />
- )}
- </div>
- );
-};
-
-/**
- * Validation Message Component
- */
-const ValidationMessage: React.FC<{ parameter: INodeProperties; value: NodeParameterValue }> = ({
- parameter,
- value,
-}) => {
- const { validateParameterValue } = require('@/services/nodeSystem');
-
- if (!parameter.validateType || parameter.ignoreValidationDuringExecution) {
- return null;
- }
-
- const validation = validateParameterValue(value, parameter.validateType);
-
- if (validation.valid) {
- return null;
- }
-
- return (
- <div className="text-xs text-red-400 flex items-center gap-1">
- <span>[WARN]️</span>
- <span>{validation.error}</span>
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/PythonAgentNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/PythonAgentNode.tsx
index 7843159bc..712bbe2d4 100644
--- a/fincept-terminal-desktop/src/components/tabs/node-editor/PythonAgentNode.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/PythonAgentNode.tsx
@@ -2,7 +2,17 @@
import React, { useState, useEffect } from 'react';
import { Handle, Position } from 'reactflow';
import { Play, Settings, CheckCircle, AlertCircle, Loader, TrendingUp, Brain } from 'lucide-react';
-import { sqliteService, LLMConfig } from '@/services/core/sqliteService';
+import { sqliteService, LLMConfig, LLMModelConfig } from '@/services/core/sqliteService';
+
+// Combined LLM option for display
+interface LLMOption {
+ id: string;
+ provider: string;
+ model: string;
+ displayName: string;
+ type: 'provider' | 'model' | 'fincept';
+ isActive?: boolean;
+}
interface PythonAgentNodeProps {
id: string;
@@ -26,17 +36,79 @@ interface PythonAgentNodeProps {
const PythonAgentNode: React.FC<PythonAgentNodeProps> = ({ id, data, selected }) => {
const [showSettings, setShowSettings] = useState(false);
- const [availableLLMs, setAvailableLLMs] = useState<LLMConfig[]>([]);
+ const [availableLLMs, setAvailableLLMs] = useState<LLMOption[]>([]);
const [selectedLLM, setSelectedLLM] = useState(data.selectedLLM || 'active');
- // Load available LLM providers from Settings
+ // Load available LLM providers from Settings (both LLMConfig and LLMModelConfig)
useEffect(() => {
const loadLLMs = async () => {
try {
- const configs = await sqliteService.getLLMConfigs();
- setAvailableLLMs(configs);
+ const options: LLMOption[] = [];
+
+ // Load provider-level configs (LLMConfig)
+ const providerConfigs = await sqliteService.getLLMConfigs();
+ for (const config of providerConfigs) {
+ // Fincept is special - always show it prominently
+ if (config.provider === 'fincept') {
+ options.unshift({
+ id: 'fincept',
+ provider: 'fincept',
+ model: config.model || 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: config.is_active
+ });
+ } else {
+ options.push({
+ id: config.provider,
+ provider: config.provider,
+ model: config.model,
+ displayName: `${config.provider.toUpperCase()} - ${config.model}`,
+ type: 'provider',
+ isActive: config.is_active
+ });
+ }
+ }
+
+ // Load custom model configs (LLMModelConfig) from Settings
+ const modelConfigs = await sqliteService.getLLMModelConfigs();
+ for (const model of modelConfigs) {
+ if (model.is_enabled) {
+ options.push({
+ id: model.id,
+ provider: model.provider,
+ model: model.model_id,
+ displayName: `${model.display_name} (${model.provider.toUpperCase()})`,
+ type: 'model',
+ isActive: model.is_default
+ });
+ }
+ }
+
+ // If Fincept wasn't in provider configs, add it as default
+ if (!options.find(o => o.provider === 'fincept')) {
+ options.unshift({
+ id: 'fincept',
+ provider: 'fincept',
+ model: 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: true
+ });
+ }
+
+ setAvailableLLMs(options);
} catch (error) {
console.error('Failed to load LLM configs:', error);
+ // Default to Fincept if loading fails
+ setAvailableLLMs([{
+ id: 'fincept',
+ provider: 'fincept',
+ model: 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: true
+ }]);
}
};
loadLLMs();
@@ -260,7 +332,10 @@ const PythonAgentNode: React.FC<PythonAgentNodeProps> = ({ id, data, selected })
color: WHITE,
fontSize: '8px'
}}>
- {selectedLLM === 'active' ? 'Active Provider' : selectedLLM.toUpperCase()}
+ {selectedLLM === 'active'
+ ? 'Active Provider'
+ : (availableLLMs.find(l => l.id === selectedLLM)?.displayName || selectedLLM.toUpperCase())
+ }
</div>
</div>
@@ -302,15 +377,17 @@ const PythonAgentNode: React.FC<PythonAgentNodeProps> = ({ id, data, selected })
backgroundColor: PANEL_BG,
border: `1px solid ${BORDER}`,
color: WHITE,
- padding: '4px',
- fontSize: '8px',
+ padding: '6px',
+ fontSize: '10px',
borderRadius: '3px'
}}
>
<option value="active">Use Active Provider (from Settings)</option>
{availableLLMs.map(llm => (
- <option key={llm.provider} value={llm.provider}>
- {llm.provider.toUpperCase()} - {llm.model}
+ <option key={llm.id} value={llm.id} style={{
+ backgroundColor: llm.type === 'fincept' ? '#1a3a1a' : undefined
+ }}>
+ {llm.displayName}{llm.isActive ? ' ✓' : ''}
</option>
))}
</select>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx
index 55e5aa239..9d20f706c 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx
@@ -60,9 +60,10 @@ export function ProChartWithToolkit({
useEffect(() => {
if (!chartContainerRef.current) return;
+ const containerHeight = chartContainerRef.current.clientHeight || height;
const chart = createChart(chartContainerRef.current, {
width: chartContainerRef.current.clientWidth,
- height: height,
+ height: containerHeight,
layout: {
background: { type: ColorType.Solid, color: '#0a0a0a' },
textColor: '#d1d5db',
@@ -219,10 +220,11 @@ export function ProChartWithToolkit({
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('mouseup', handleMouseUp);
- // Handle resize
+ // Handle resize - use container height if no fixed height provided
const handleResize = () => {
if (chartContainerRef.current && chartRef.current) {
- chartRef.current.resize(chartContainerRef.current.clientWidth, height, true);
+ const containerHeight = chartContainerRef.current.clientHeight || height;
+ chartRef.current.resize(chartContainerRef.current.clientWidth, containerHeight, true);
}
};
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridConfigPanel.tsx
new file mode 100644
index 000000000..eea2e1456
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridConfigPanel.tsx
@@ -0,0 +1,429 @@
+/**
+ * Grid Configuration Panel
+ *
+ * UI for configuring and creating new grid trading bots.
+ * Works with both crypto and stock brokers.
+ */
+
+import React, { useState, useMemo, useCallback } from 'react';
+import {
+ Grid, TrendingUp, TrendingDown, Minus, DollarSign,
+ ArrowUpRight, ArrowDownRight, AlertCircle, Info, Calculator,
+ ChevronDown, Check,
+} from 'lucide-react';
+import type { GridConfig, GridType, GridDirection, GridCalculation } from '../../../../services/gridTrading/types';
+import { calculateGridDetails, validateGridConfig } from '../../../../services/gridTrading';
+
+// Bloomberg-style colors
+const COLORS = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#0F0F0F',
+ PANEL_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ MUTED: '#4A4A4A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+};
+
+interface GridConfigPanelProps {
+ symbol: string;
+ exchange?: string;
+ currentPrice: number;
+ brokerType: 'crypto' | 'stock';
+ brokerId: string;
+ availableBalance: number;
+ onCreateGrid: (config: GridConfig) => void;
+ onCancel?: () => void;
+}
+
+export function GridConfigPanel({
+ symbol,
+ exchange,
+ currentPrice,
+ brokerType,
+ brokerId,
+ availableBalance,
+ onCreateGrid,
+ onCancel,
+}: GridConfigPanelProps) {
+ // Form state
+ const [upperPrice, setUpperPrice] = useState(currentPrice * 1.1);
+ const [lowerPrice, setLowerPrice] = useState(currentPrice * 0.9);
+ const [gridLevels, setGridLevels] = useState(10);
+ const [gridType, setGridType] = useState<GridType>('arithmetic');
+ const [totalInvestment, setTotalInvestment] = useState(1000);
+ const [direction, setDirection] = useState<GridDirection>('neutral');
+ const [stopLoss, setStopLoss] = useState<number | undefined>(undefined);
+ const [takeProfit, setTakeProfit] = useState<number | undefined>(undefined);
+ const [productType, setProductType] = useState('CASH'); // For stocks
+
+ // Validation
+ const [errors, setErrors] = useState<string[]>([]);
+
+ // Calculate grid details
+ const gridCalculation = useMemo<GridCalculation | null>(() => {
+ try {
+ const config: Partial<GridConfig> = {
+ symbol,
+ exchange,
+ upperPrice,
+ lowerPrice,
+ gridLevels,
+ gridType,
+ totalInvestment,
+ direction,
+ brokerType,
+ brokerId,
+ };
+
+ const validationErrors = validateGridConfig(config);
+ if (validationErrors.length > 0) {
+ setErrors(validationErrors);
+ return null;
+ }
+
+ setErrors([]);
+ return calculateGridDetails(config as GridConfig);
+ } catch (error) {
+ return null;
+ }
+ }, [symbol, exchange, upperPrice, lowerPrice, gridLevels, gridType, totalInvestment, direction, brokerType, brokerId]);
+
+ // Handle form submission
+ const handleCreate = useCallback(() => {
+ const config: GridConfig = {
+ id: `grid_${Date.now()}`,
+ symbol,
+ exchange,
+ upperPrice,
+ lowerPrice,
+ gridLevels,
+ gridType,
+ totalInvestment,
+ quantityPerGrid: gridCalculation?.quantityPerLevel || 0,
+ direction,
+ stopLoss,
+ takeProfit,
+ brokerType,
+ brokerId,
+ productType: brokerType === 'stock' ? productType : undefined,
+ };
+
+ const validationErrors = validateGridConfig(config);
+ if (validationErrors.length > 0) {
+ setErrors(validationErrors);
+ return;
+ }
+
+ onCreateGrid(config);
+ }, [symbol, exchange, upperPrice, lowerPrice, gridLevels, gridType, totalInvestment, direction, stopLoss, takeProfit, brokerType, brokerId, productType, gridCalculation, onCreateGrid]);
+
+ // Quick presets
+ const applyPreset = (preset: 'conservative' | 'moderate' | 'aggressive') => {
+ switch (preset) {
+ case 'conservative':
+ setUpperPrice(currentPrice * 1.05);
+ setLowerPrice(currentPrice * 0.95);
+ setGridLevels(5);
+ break;
+ case 'moderate':
+ setUpperPrice(currentPrice * 1.10);
+ setLowerPrice(currentPrice * 0.90);
+ setGridLevels(10);
+ break;
+ case 'aggressive':
+ setUpperPrice(currentPrice * 1.20);
+ setLowerPrice(currentPrice * 0.80);
+ setGridLevels(20);
+ break;
+ }
+ };
+
+ return (
+ <div className="bg-[#0F0F0F] border border-[#2A2A2A] rounded-lg p-4">
+ {/* Header */}
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-2">
+ <Grid className="w-5 h-5 text-[#FF8800]" />
+ <span className="text-white font-semibold">Grid Trading Configuration</span>
+ </div>
+ <div className="text-sm text-[#787878]">
+ {symbol} @ {currentPrice.toFixed(2)}
+ </div>
+ </div>
+
+ {/* Quick Presets */}
+ <div className="mb-4">
+ <div className="text-xs text-[#787878] mb-2">Quick Presets</div>
+ <div className="flex gap-2">
+ <button
+ onClick={() => applyPreset('conservative')}
+ className="px-3 py-1.5 text-xs bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#00D66F] border border-[#00D66F]/30 rounded transition-colors"
+ >
+ Conservative (5%)
+ </button>
+ <button
+ onClick={() => applyPreset('moderate')}
+ className="px-3 py-1.5 text-xs bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#FF8800] border border-[#FF8800]/30 rounded transition-colors"
+ >
+ Moderate (10%)
+ </button>
+ <button
+ onClick={() => applyPreset('aggressive')}
+ className="px-3 py-1.5 text-xs bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#FF3B3B] border border-[#FF3B3B]/30 rounded transition-colors"
+ >
+ Aggressive (20%)
+ </button>
+ </div>
+ </div>
+
+ {/* Price Range */}
+ <div className="grid grid-cols-2 gap-4 mb-4">
+ <div>
+ <label className="block text-xs text-[#787878] mb-1">Upper Price</label>
+ <div className="relative">
+ <input
+ type="number"
+ value={upperPrice}
+ onChange={e => setUpperPrice(parseFloat(e.target.value) || 0)}
+ className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ step="0.01"
+ />
+ <ArrowUpRight className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#00D66F]" />
+ </div>
+ <div className="text-xs text-[#787878] mt-1">
+ +{(((upperPrice - currentPrice) / currentPrice) * 100).toFixed(1)}%
+ </div>
+ </div>
+ <div>
+ <label className="block text-xs text-[#787878] mb-1">Lower Price</label>
+ <div className="relative">
+ <input
+ type="number"
+ value={lowerPrice}
+ onChange={e => setLowerPrice(parseFloat(e.target.value) || 0)}
+ className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ step="0.01"
+ />
+ <ArrowDownRight className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#FF3B3B]" />
+ </div>
+ <div className="text-xs text-[#787878] mt-1">
+ {(((lowerPrice - currentPrice) / currentPrice) * 100).toFixed(1)}%
+ </div>
+ </div>
+ </div>
+
+ {/* Grid Settings */}
+ <div className="grid grid-cols-2 gap-4 mb-4">
+ <div>
+ <label className="block text-xs text-[#787878] mb-1">Grid Levels</label>
+ <input
+ type="number"
+ value={gridLevels}
+ onChange={e => setGridLevels(parseInt(e.target.value) || 2)}
+ min={2}
+ max={200}
+ className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ />
+ </div>
+ <div>
+ <label className="block text-xs text-[#787878] mb-1">Grid Type</label>
+ <select
+ value={gridType}
+ onChange={e => setGridType(e.target.value as GridType)}
+ className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ >
+ <option value="arithmetic">Arithmetic (Equal Price)</option>
+ <option value="geometric">Geometric (Equal %)</option>
+ </select>
+ </div>
+ </div>
+
+ {/* Investment */}
+ <div className="mb-4">
+ <label className="block text-xs text-[#787878] mb-1">Total Investment</label>
+ <div className="relative">
+ <input
+ type="number"
+ value={totalInvestment}
+ onChange={e => setTotalInvestment(parseFloat(e.target.value) || 0)}
+ className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ step="10"
+ />
+ <DollarSign className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#787878]" />
+ </div>
+ <div className="text-xs text-[#787878] mt-1">
+ Available: ${availableBalance.toFixed(2)}
+ </div>
+ </div>
+
+ {/* Direction */}
+ <div className="mb-4">
+ <label className="block text-xs text-[#787878] mb-1">Trading Direction</label>
+ <div className="grid grid-cols-3 gap-2">
+ <button
+ onClick={() => setDirection('long')}
+ className={`flex items-center justify-center gap-1 px-3 py-2 rounded text-sm transition-colors ${
+ direction === 'long'
+ ? 'bg-[#00D66F]/20 border border-[#00D66F] text-[#00D66F]'
+ : 'bg-[#1A1A1A] border border-[#2A2A2A] text-[#787878] hover:text-white'
+ }`}
+ >
+ <TrendingUp className="w-4 h-4" />
+ Long
+ </button>
+ <button
+ onClick={() => setDirection('neutral')}
+ className={`flex items-center justify-center gap-1 px-3 py-2 rounded text-sm transition-colors ${
+ direction === 'neutral'
+ ? 'bg-[#FF8800]/20 border border-[#FF8800] text-[#FF8800]'
+ : 'bg-[#1A1A1A] border border-[#2A2A2A] text-[#787878] hover:text-white'
+ }`}
+ >
+ <Minus className="w-4 h-4" />
+ Neutral
+ </button>
+ <button
+ onClick={() => setDirection('short')}
+ className={`flex items-center justify-center gap-1 px-3 py-2 rounded text-sm transition-colors ${
+ direction === 'short'
+ ? 'bg-[#FF3B3B]/20 border border-[#FF3B3B] text-[#FF3B3B]'
+ : 'bg-[#1A1A1A] border border-[#2A2A2A] text-[#787878] hover:text-white'
+ }`}
+ >
+ <TrendingDown className="w-4 h-4" />
+ Short
+ </button>
+ </div>
+ </div>
+
+ {/* Stop Loss / Take Profit */}
+ <div className="grid grid-cols-2 gap-4 mb-4">
+ <div>
+ <label className="block text-xs text-[#787878] mb-1">Stop Loss (Optional)</label>
+ <input
+ type="number"
+ value={stopLoss || ''}
+ onChange={e => setStopLoss(e.target.value ? parseFloat(e.target.value) : undefined)}
+ placeholder={`< ${lowerPrice.toFixed(2)}`}
+ className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF3B3B] focus:outline-none placeholder-[#4A4A4A]"
+ step="0.01"
+ />
+ </div>
+ <div>
+ <label className="block text-xs text-[#787878] mb-1">Take Profit (Optional)</label>
+ <input
+ type="number"
+ value={takeProfit || ''}
+ onChange={e => setTakeProfit(e.target.value ? parseFloat(e.target.value) : undefined)}
+ placeholder={`> ${upperPrice.toFixed(2)}`}
+ className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#00D66F] focus:outline-none placeholder-[#4A4A4A]"
+ step="0.01"
+ />
+ </div>
+ </div>
+
+ {/* Stock-specific: Product Type */}
+ {brokerType === 'stock' && (
+ <div className="mb-4">
+ <label className="block text-xs text-[#787878] mb-1">Product Type</label>
+ <select
+ value={productType}
+ onChange={e => setProductType(e.target.value)}
+ className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ >
+ <option value="CASH">Cash (Delivery)</option>
+ <option value="INTRADAY">Intraday (MIS)</option>
+ <option value="MARGIN">Margin</option>
+ </select>
+ </div>
+ )}
+
+ {/* Grid Calculation Summary */}
+ {gridCalculation && (
+ <div className="bg-[#1A1A1A] rounded p-3 mb-4">
+ <div className="flex items-center gap-2 mb-2">
+ <Calculator className="w-4 h-4 text-[#00E5FF]" />
+ <span className="text-sm text-white">Grid Summary</span>
+ </div>
+ <div className="grid grid-cols-2 gap-2 text-xs">
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Grid Spacing:</span>
+ <span className="text-white">
+ {gridType === 'arithmetic'
+ ? `$${gridCalculation.gridSpacing.toFixed(2)}`
+ : `${gridCalculation.gridSpacing.toFixed(2)}%`}
+ </span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Qty/Level:</span>
+ <span className="text-white">{gridCalculation.quantityPerLevel.toFixed(4)}</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Total Qty:</span>
+ <span className="text-white">{gridCalculation.totalQuantity.toFixed(4)}</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Break-even:</span>
+ <span className="text-white">${gridCalculation.breakEvenPrice.toFixed(2)}</span>
+ </div>
+ <div className="flex justify-between col-span-2">
+ <span className="text-[#787878]">Potential Profit/Cycle:</span>
+ <span className="text-[#00D66F]">${gridCalculation.potentialProfit.toFixed(2)}</span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Errors */}
+ {errors.length > 0 && (
+ <div className="bg-[#FF3B3B]/10 border border-[#FF3B3B]/30 rounded p-3 mb-4">
+ <div className="flex items-center gap-2 text-[#FF3B3B] text-sm mb-1">
+ <AlertCircle className="w-4 h-4" />
+ Validation Errors
+ </div>
+ <ul className="text-xs text-[#FF3B3B] list-disc list-inside">
+ {errors.map((error, i) => (
+ <li key={i}>{error}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {/* Actions */}
+ <div className="flex gap-2">
+ {onCancel && (
+ <button
+ onClick={onCancel}
+ className="flex-1 py-2 bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#787878] hover:text-white rounded transition-colors text-sm"
+ >
+ Cancel
+ </button>
+ )}
+ <button
+ onClick={handleCreate}
+ disabled={errors.length > 0 || !gridCalculation}
+ className="flex-1 py-2 bg-[#FF8800] hover:bg-[#FF9900] disabled:bg-[#4A4A4A] disabled:cursor-not-allowed text-black font-semibold rounded transition-colors text-sm flex items-center justify-center gap-2"
+ >
+ <Grid className="w-4 h-4" />
+ Create Grid
+ </button>
+ </div>
+
+ {/* Info */}
+ <div className="mt-4 flex items-start gap-2 text-xs text-[#787878]">
+ <Info className="w-4 h-4 flex-shrink-0 mt-0.5" />
+ <p>
+ Grid trading places buy orders below and sell orders above the current price.
+ When orders fill, opposite orders are placed to capture profits from price oscillations.
+ </p>
+ </div>
+ </div>
+ );
+}
+
+export default GridConfigPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridStatusPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridStatusPanel.tsx
new file mode 100644
index 000000000..cb5de2896
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridStatusPanel.tsx
@@ -0,0 +1,295 @@
+/**
+ * Grid Status Panel
+ *
+ * Shows grid status, statistics, and controls for managing running grids.
+ */
+
+import React from 'react';
+import {
+ Grid, Play, Pause, Square, Trash2, TrendingUp, TrendingDown,
+ DollarSign, Activity, BarChart3, Clock, AlertCircle, RefreshCw,
+} from 'lucide-react';
+import type { GridState } from '../../../../services/gridTrading/types';
+
+interface GridStatusPanelProps {
+ grid: GridState;
+ onStart: () => void;
+ onPause: () => void;
+ onStop: () => void;
+ onDelete: () => void;
+}
+
+export function GridStatusPanel({
+ grid,
+ onStart,
+ onPause,
+ onStop,
+ onDelete,
+}: GridStatusPanelProps) {
+ const { config, status, currentPrice, levels } = grid;
+
+ // Calculate statistics
+ const openOrders = levels.filter(l => l.status === 'open').length;
+ const filledOrders = levels.filter(l => l.status === 'filled').length;
+ const pendingOrders = levels.filter(l => l.status === 'pending').length;
+ const buyOrders = levels.filter(l => l.side === 'buy' && l.status === 'open').length;
+ const sellOrders = levels.filter(l => l.side === 'sell' && l.status === 'open').length;
+
+ // Price position in grid
+ const pricePosition = ((currentPrice - config.lowerPrice) / (config.upperPrice - config.lowerPrice)) * 100;
+
+ // Status colors
+ const getStatusColor = () => {
+ switch (status) {
+ case 'running': return '#00D66F';
+ case 'paused': return '#FFD700';
+ case 'stopped': return '#787878';
+ case 'error': return '#FF3B3B';
+ default: return '#787878';
+ }
+ };
+
+ const formatDuration = (ms: number): string => {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) return `${days}d ${hours % 24}h`;
+ if (hours > 0) return `${hours}h ${minutes % 60}m`;
+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
+ return `${seconds}s`;
+ };
+
+ const runningTime = grid.startedAt ? Date.now() - grid.startedAt : 0;
+
+ return (
+ <div className="bg-[#0F0F0F] border border-[#2A2A2A] rounded-lg p-4">
+ {/* Header */}
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-2">
+ <Grid className="w-5 h-5 text-[#FF8800]" />
+ <span className="text-white font-semibold">{config.symbol}</span>
+ <div
+ className="px-2 py-0.5 rounded text-xs font-medium"
+ style={{
+ backgroundColor: `${getStatusColor()}20`,
+ color: getStatusColor(),
+ }}
+ >
+ {status.toUpperCase()}
+ </div>
+ </div>
+ <div className="text-xs text-[#787878]">
+ {config.brokerId}
+ </div>
+ </div>
+
+ {/* Controls */}
+ <div className="flex gap-2 mb-4">
+ {(status === 'draft' || status === 'paused') && (
+ <button
+ onClick={onStart}
+ className="flex-1 flex items-center justify-center gap-1 py-2 bg-[#00D66F] hover:bg-[#00E57F] text-black font-semibold rounded transition-colors"
+ >
+ <Play className="w-4 h-4" />
+ {status === 'draft' ? 'Start' : 'Resume'}
+ </button>
+ )}
+ {status === 'running' && (
+ <button
+ onClick={onPause}
+ className="flex-1 flex items-center justify-center gap-1 py-2 bg-[#FFD700] hover:bg-[#FFE030] text-black font-semibold rounded transition-colors"
+ >
+ <Pause className="w-4 h-4" />
+ Pause
+ </button>
+ )}
+ {(status === 'running' || status === 'paused') && (
+ <button
+ onClick={onStop}
+ className="flex-1 flex items-center justify-center gap-1 py-2 bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#FF3B3B] border border-[#FF3B3B]/30 rounded transition-colors"
+ >
+ <Square className="w-4 h-4" />
+ Stop
+ </button>
+ )}
+ <button
+ onClick={onDelete}
+ className="p-2 bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#FF3B3B] border border-[#2A2A2A] hover:border-[#FF3B3B]/30 rounded transition-colors"
+ >
+ <Trash2 className="w-4 h-4" />
+ </button>
+ </div>
+
+ {/* Price Info */}
+ <div className="bg-[#1A1A1A] rounded p-3 mb-4">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs text-[#787878]">Current Price</span>
+ <span className="text-lg text-white font-mono">${currentPrice.toFixed(2)}</span>
+ </div>
+ {/* Price position bar */}
+ <div className="relative h-2 bg-[#2A2A2A] rounded-full overflow-hidden">
+ <div
+ className="absolute top-0 left-0 h-full bg-gradient-to-r from-[#FF3B3B] via-[#FFD700] to-[#00D66F]"
+ style={{ width: '100%' }}
+ />
+ <div
+ className="absolute top-0 h-full w-1 bg-white shadow-lg"
+ style={{ left: `${Math.max(0, Math.min(100, pricePosition))}%`, transform: 'translateX(-50%)' }}
+ />
+ </div>
+ <div className="flex justify-between mt-1 text-xs text-[#787878]">
+ <span>${config.lowerPrice.toFixed(2)}</span>
+ <span>${config.upperPrice.toFixed(2)}</span>
+ </div>
+ </div>
+
+ {/* Statistics Grid */}
+ <div className="grid grid-cols-2 gap-3 mb-4">
+ {/* P&L */}
+ <div className="bg-[#1A1A1A] rounded p-3">
+ <div className="flex items-center gap-1 text-xs text-[#787878] mb-1">
+ <DollarSign className="w-3 h-3" />
+ Total P&L
+ </div>
+ <div className={`text-lg font-mono ${grid.totalPnl >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}>
+ {grid.totalPnl >= 0 ? '+' : ''}{grid.totalPnl.toFixed(2)}
+ </div>
+ <div className="text-xs text-[#787878]">
+ Realized: {grid.realizedPnl >= 0 ? '+' : ''}{grid.realizedPnl.toFixed(2)}
+ </div>
+ </div>
+
+ {/* Grid Profit */}
+ <div className="bg-[#1A1A1A] rounded p-3">
+ <div className="flex items-center gap-1 text-xs text-[#787878] mb-1">
+ <BarChart3 className="w-3 h-3" />
+ Grid Profit
+ </div>
+ <div className="text-lg font-mono text-[#00D66F]">
+ +{grid.gridProfit.toFixed(2)}
+ </div>
+ <div className="text-xs text-[#787878]">
+ {grid.totalBuys + grid.totalSells} trades
+ </div>
+ </div>
+
+ {/* Position */}
+ <div className="bg-[#1A1A1A] rounded p-3">
+ <div className="flex items-center gap-1 text-xs text-[#787878] mb-1">
+ <Activity className="w-3 h-3" />
+ Position
+ </div>
+ <div className={`text-lg font-mono ${
+ grid.currentPosition > 0 ? 'text-[#00D66F]' :
+ grid.currentPosition < 0 ? 'text-[#FF3B3B]' : 'text-white'
+ }`}>
+ {grid.currentPosition > 0 ? '+' : ''}{grid.currentPosition.toFixed(4)}
+ </div>
+ <div className="text-xs text-[#787878]">
+ Avg: ${grid.averageEntryPrice.toFixed(2)}
+ </div>
+ </div>
+
+ {/* Running Time */}
+ <div className="bg-[#1A1A1A] rounded p-3">
+ <div className="flex items-center gap-1 text-xs text-[#787878] mb-1">
+ <Clock className="w-3 h-3" />
+ Running Time
+ </div>
+ <div className="text-lg font-mono text-white">
+ {formatDuration(runningTime)}
+ </div>
+ <div className="text-xs text-[#787878]">
+ Started: {grid.startedAt ? new Date(grid.startedAt).toLocaleDateString() : 'N/A'}
+ </div>
+ </div>
+ </div>
+
+ {/* Order Status */}
+ <div className="bg-[#1A1A1A] rounded p-3 mb-4">
+ <div className="text-xs text-[#787878] mb-2">Order Status</div>
+ <div className="grid grid-cols-4 gap-2 text-center">
+ <div>
+ <div className="text-lg font-mono text-[#00E5FF]">{openOrders}</div>
+ <div className="text-xs text-[#787878]">Open</div>
+ </div>
+ <div>
+ <div className="text-lg font-mono text-[#00D66F]">{filledOrders}</div>
+ <div className="text-xs text-[#787878]">Filled</div>
+ </div>
+ <div>
+ <div className="text-lg font-mono text-[#787878]">{pendingOrders}</div>
+ <div className="text-xs text-[#787878]">Pending</div>
+ </div>
+ <div>
+ <div className="text-lg font-mono text-white">{config.gridLevels}</div>
+ <div className="text-xs text-[#787878]">Total</div>
+ </div>
+ </div>
+ <div className="flex justify-center gap-4 mt-2 text-xs">
+ <div className="flex items-center gap-1">
+ <TrendingUp className="w-3 h-3 text-[#00D66F]" />
+ <span className="text-[#787878]">{buyOrders} buys open</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <TrendingDown className="w-3 h-3 text-[#FF3B3B]" />
+ <span className="text-[#787878]">{sellOrders} sells open</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Error Display */}
+ {grid.lastError && (
+ <div className="bg-[#FF3B3B]/10 border border-[#FF3B3B]/30 rounded p-3">
+ <div className="flex items-center gap-2 text-[#FF3B3B] text-sm">
+ <AlertCircle className="w-4 h-4" />
+ Last Error
+ </div>
+ <div className="text-xs text-[#FF3B3B] mt-1">{grid.lastError}</div>
+ <div className="text-xs text-[#787878] mt-1">
+ Total errors: {grid.errorCount}
+ </div>
+ </div>
+ )}
+
+ {/* Grid Config Summary */}
+ <div className="mt-4 pt-4 border-t border-[#2A2A2A]">
+ <div className="text-xs text-[#787878] mb-2">Grid Configuration</div>
+ <div className="grid grid-cols-2 gap-1 text-xs">
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Type:</span>
+ <span className="text-white capitalize">{config.gridType}</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Direction:</span>
+ <span className="text-white capitalize">{config.direction}</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Investment:</span>
+ <span className="text-white">${config.totalInvestment}</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Qty/Grid:</span>
+ <span className="text-white">{config.quantityPerGrid}</span>
+ </div>
+ {config.stopLoss && (
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Stop Loss:</span>
+ <span className="text-[#FF3B3B]">${config.stopLoss}</span>
+ </div>
+ )}
+ {config.takeProfit && (
+ <div className="flex justify-between">
+ <span className="text-[#787878]">Take Profit:</span>
+ <span className="text-[#00D66F]">${config.takeProfit}</span>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default GridStatusPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridTradingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridTradingPanel.tsx
new file mode 100644
index 000000000..525e10d0f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridTradingPanel.tsx
@@ -0,0 +1,368 @@
+/**
+ * Grid Trading Panel
+ *
+ * Main component for grid trading that integrates all grid trading sub-components.
+ * Can be embedded in TradingTab or used standalone.
+ */
+
+import React, { useState, useEffect, useCallback } from 'react';
+import { Grid, Plus, List, BarChart3, Settings, X, ChevronDown, AlertCircle } from 'lucide-react';
+import { GridConfigPanel } from './GridConfigPanel';
+import { GridStatusPanel } from './GridStatusPanel';
+import { GridVisualization } from './GridVisualization';
+import {
+ getGridTradingService,
+ CryptoGridAdapter,
+ StockGridAdapter,
+} from '../../../../services/gridTrading';
+import type {
+ GridConfig,
+ GridState,
+ IGridBrokerAdapter,
+} from '../../../../services/gridTrading/types';
+import type { IExchangeAdapter } from '../../../../brokers/crypto/types';
+import type { IStockBrokerAdapter } from '../../../../brokers/stocks/types';
+
+interface GridTradingPanelProps {
+ // Current symbol/price context
+ symbol: string;
+ exchange?: string;
+ currentPrice: number;
+
+ // Broker info
+ brokerType: 'crypto' | 'stock';
+ brokerId: string;
+
+ // Broker adapters - pass one of these
+ cryptoAdapter?: IExchangeAdapter;
+ stockAdapter?: IStockBrokerAdapter;
+
+ // Layout
+ variant?: 'compact' | 'full';
+
+ // Callbacks
+ onGridCreated?: (grid: GridState) => void;
+ onGridStarted?: (gridId: string) => void;
+ onGridStopped?: (gridId: string) => void;
+}
+
+type View = 'list' | 'create' | 'details';
+
+export function GridTradingPanel({
+ symbol,
+ exchange,
+ currentPrice,
+ brokerType,
+ brokerId,
+ cryptoAdapter,
+ stockAdapter,
+ variant = 'full',
+ onGridCreated,
+ onGridStarted,
+ onGridStopped,
+}: GridTradingPanelProps) {
+ const [view, setView] = useState<View>('list');
+ const [grids, setGrids] = useState<GridState[]>([]);
+ const [selectedGridId, setSelectedGridId] = useState<string | null>(null);
+ const [availableBalance, setAvailableBalance] = useState(0);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const service = getGridTradingService();
+
+ // Register adapter on mount
+ useEffect(() => {
+ let adapter: IGridBrokerAdapter | null = null;
+
+ if (brokerType === 'crypto' && cryptoAdapter) {
+ adapter = new CryptoGridAdapter(cryptoAdapter);
+ } else if (brokerType === 'stock' && stockAdapter) {
+ adapter = new StockGridAdapter(stockAdapter);
+ }
+
+ if (adapter) {
+ service.registerAdapter(adapter);
+
+ // Fetch available balance
+ adapter.getAvailableBalance().then(balance => {
+ setAvailableBalance(balance);
+ }).catch(console.error);
+ }
+
+ return () => {
+ if (adapter) {
+ service.unregisterAdapter(adapter.brokerId);
+ if ('dispose' in adapter) {
+ (adapter as any).dispose();
+ }
+ }
+ };
+ }, [brokerType, cryptoAdapter, stockAdapter, service]);
+
+ // Load grids for this broker
+ useEffect(() => {
+ const loadGrids = () => {
+ const allGrids = service.getGridsForBroker(brokerId);
+ setGrids(allGrids);
+ };
+
+ loadGrids();
+
+ // Subscribe to updates
+ const unsubscribe = service.onGridUpdate((grid) => {
+ if (grid.config.brokerId === brokerId) {
+ loadGrids();
+ }
+ });
+
+ return unsubscribe;
+ }, [brokerId, service]);
+
+ // Get selected grid
+ const selectedGrid = selectedGridId ? grids.find(g => g.config.id === selectedGridId) : null;
+
+ // Handlers
+ const handleCreateGrid = useCallback(async (config: GridConfig) => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const grid = await service.createGrid(config);
+ setGrids(service.getGridsForBroker(brokerId));
+ setSelectedGridId(grid.config.id);
+ setView('details');
+ onGridCreated?.(grid);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to create grid');
+ } finally {
+ setIsLoading(false);
+ }
+ }, [service, brokerId, onGridCreated]);
+
+ const handleStartGrid = useCallback(async (gridId: string) => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ await service.startGrid(gridId);
+ setGrids(service.getGridsForBroker(brokerId));
+ onGridStarted?.(gridId);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to start grid');
+ } finally {
+ setIsLoading(false);
+ }
+ }, [service, brokerId, onGridStarted]);
+
+ const handlePauseGrid = useCallback(async (gridId: string) => {
+ try {
+ await service.pauseGrid(gridId);
+ setGrids(service.getGridsForBroker(brokerId));
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to pause grid');
+ }
+ }, [service, brokerId]);
+
+ const handleStopGrid = useCallback(async (gridId: string) => {
+ try {
+ await service.stopGrid(gridId);
+ setGrids(service.getGridsForBroker(brokerId));
+ onGridStopped?.(gridId);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to stop grid');
+ }
+ }, [service, brokerId, onGridStopped]);
+
+ const handleDeleteGrid = useCallback(async (gridId: string) => {
+ try {
+ await service.deleteGrid(gridId);
+ setGrids(service.getGridsForBroker(brokerId));
+ if (selectedGridId === gridId) {
+ setSelectedGridId(null);
+ setView('list');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to delete grid');
+ }
+ }, [service, brokerId, selectedGridId]);
+
+ // Render list view
+ const renderList = () => (
+ <div className="space-y-3">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Grid className="w-5 h-5 text-[#FF8800]" />
+ <span className="text-white font-semibold">Grid Bots</span>
+ <span className="text-xs text-[#787878]">({grids.length})</span>
+ </div>
+ <button
+ onClick={() => setView('create')}
+ className="flex items-center gap-1 px-3 py-1.5 bg-[#FF8800] hover:bg-[#FF9900] text-black text-sm font-semibold rounded transition-colors"
+ >
+ <Plus className="w-4 h-4" />
+ New Grid
+ </button>
+ </div>
+
+ {/* Grid list */}
+ {grids.length === 0 ? (
+ <div className="bg-[#1A1A1A] rounded-lg p-8 text-center">
+ <Grid className="w-12 h-12 text-[#4A4A4A] mx-auto mb-3" />
+ <div className="text-white mb-1">No Grid Bots</div>
+ <div className="text-sm text-[#787878] mb-4">
+ Create your first grid trading bot to automate trading
+ </div>
+ <button
+ onClick={() => setView('create')}
+ className="px-4 py-2 bg-[#FF8800] hover:bg-[#FF9900] text-black font-semibold rounded transition-colors"
+ >
+ Create Grid Bot
+ </button>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {grids.map(grid => (
+ <div
+ key={grid.config.id}
+ onClick={() => {
+ setSelectedGridId(grid.config.id);
+ setView('details');
+ }}
+ className="bg-[#1A1A1A] hover:bg-[#2A2A2A] border border-[#2A2A2A] rounded-lg p-3 cursor-pointer transition-colors"
+ >
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-2">
+ <span className="text-white font-medium">{grid.config.symbol}</span>
+ <div
+ className="px-2 py-0.5 rounded text-xs font-medium"
+ style={{
+ backgroundColor: grid.status === 'running' ? '#00D66F20' : '#78787820',
+ color: grid.status === 'running' ? '#00D66F' : '#787878',
+ }}
+ >
+ {grid.status.toUpperCase()}
+ </div>
+ </div>
+ <ChevronDown className="w-4 h-4 text-[#787878] -rotate-90" />
+ </div>
+ <div className="grid grid-cols-3 gap-2 text-xs">
+ <div>
+ <div className="text-[#787878]">P&L</div>
+ <div className={grid.totalPnl >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}>
+ {grid.totalPnl >= 0 ? '+' : ''}{grid.totalPnl.toFixed(2)}
+ </div>
+ </div>
+ <div>
+ <div className="text-[#787878]">Trades</div>
+ <div className="text-white">{grid.totalBuys + grid.totalSells}</div>
+ </div>
+ <div>
+ <div className="text-[#787878]">Levels</div>
+ <div className="text-white">{grid.config.gridLevels}</div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+
+ // Render create view
+ const renderCreate = () => (
+ <div>
+ <div className="flex items-center gap-2 mb-4">
+ <button
+ onClick={() => setView('list')}
+ className="p-1 hover:bg-[#2A2A2A] rounded transition-colors"
+ >
+ <X className="w-5 h-5 text-[#787878]" />
+ </button>
+ <span className="text-white font-semibold">Create Grid Bot</span>
+ </div>
+ <GridConfigPanel
+ symbol={symbol}
+ exchange={exchange}
+ currentPrice={currentPrice}
+ brokerType={brokerType}
+ brokerId={brokerId}
+ availableBalance={availableBalance}
+ onCreateGrid={handleCreateGrid}
+ onCancel={() => setView('list')}
+ />
+ </div>
+ );
+
+ // Render details view
+ const renderDetails = () => {
+ if (!selectedGrid) {
+ setView('list');
+ return null;
+ }
+
+ return (
+ <div>
+ <div className="flex items-center gap-2 mb-4">
+ <button
+ onClick={() => {
+ setSelectedGridId(null);
+ setView('list');
+ }}
+ className="p-1 hover:bg-[#2A2A2A] rounded transition-colors"
+ >
+ <X className="w-5 h-5 text-[#787878]" />
+ </button>
+ <span className="text-white font-semibold">Grid Details</span>
+ </div>
+
+ <div className={variant === 'full' ? 'grid grid-cols-2 gap-4' : 'space-y-4'}>
+ <GridStatusPanel
+ grid={selectedGrid}
+ onStart={() => handleStartGrid(selectedGrid.config.id)}
+ onPause={() => handlePauseGrid(selectedGrid.config.id)}
+ onStop={() => handleStopGrid(selectedGrid.config.id)}
+ onDelete={() => handleDeleteGrid(selectedGrid.config.id)}
+ />
+ {variant === 'full' && (
+ <GridVisualization grid={selectedGrid} height={400} />
+ )}
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div className="bg-[#0F0F0F] border border-[#2A2A2A] rounded-lg p-4">
+ {/* Error display */}
+ {error && (
+ <div className="bg-[#FF3B3B]/10 border border-[#FF3B3B]/30 rounded p-3 mb-4 flex items-start gap-2">
+ <AlertCircle className="w-4 h-4 text-[#FF3B3B] flex-shrink-0 mt-0.5" />
+ <div className="flex-1">
+ <div className="text-sm text-[#FF3B3B]">{error}</div>
+ </div>
+ <button
+ onClick={() => setError(null)}
+ className="text-[#FF3B3B] hover:text-white"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+ )}
+
+ {/* Loading overlay */}
+ {isLoading && (
+ <div className="absolute inset-0 bg-black/50 flex items-center justify-center z-10">
+ <div className="animate-spin w-8 h-8 border-2 border-[#FF8800] border-t-transparent rounded-full" />
+ </div>
+ )}
+
+ {/* Content */}
+ {view === 'list' && renderList()}
+ {view === 'create' && renderCreate()}
+ {view === 'details' && renderDetails()}
+ </div>
+ );
+}
+
+export default GridTradingPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridVisualization.tsx b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridVisualization.tsx
new file mode 100644
index 000000000..450b1e345
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridVisualization.tsx
@@ -0,0 +1,249 @@
+/**
+ * Grid Visualization Component
+ *
+ * Visual representation of grid levels, orders, and price movement.
+ */
+
+import React, { useMemo } from 'react';
+import { ArrowUp, ArrowDown, Circle, CheckCircle, XCircle, Clock, AlertCircle } from 'lucide-react';
+import type { GridState, GridLevel, GridLevelStatus } from '../../../../services/gridTrading/types';
+
+interface GridVisualizationProps {
+ grid: GridState;
+ height?: number;
+}
+
+export function GridVisualization({ grid, height = 400 }: GridVisualizationProps) {
+ const { levels, currentPrice, config } = grid;
+
+ // Calculate visualization dimensions
+ const visualization = useMemo(() => {
+ const priceRange = config.upperPrice - config.lowerPrice;
+ const padding = priceRange * 0.1;
+ const minPrice = config.lowerPrice - padding;
+ const maxPrice = config.upperPrice + padding;
+ const totalRange = maxPrice - minPrice;
+
+ // Map price to Y position
+ const priceToY = (price: number): number => {
+ return ((maxPrice - price) / totalRange) * height;
+ };
+
+ // Current price position
+ const currentPriceY = priceToY(currentPrice);
+
+ // Level positions
+ const levelPositions = levels.map(level => ({
+ ...level,
+ y: priceToY(level.price),
+ }));
+
+ // Stop loss and take profit positions
+ const stopLossY = config.stopLoss ? priceToY(config.stopLoss) : null;
+ const takeProfitY = config.takeProfit ? priceToY(config.takeProfit) : null;
+
+ return {
+ minPrice,
+ maxPrice,
+ priceToY,
+ currentPriceY,
+ levelPositions,
+ stopLossY,
+ takeProfitY,
+ };
+ }, [levels, currentPrice, config, height]);
+
+ // Get status icon and color
+ const getStatusVisual = (status: GridLevelStatus) => {
+ switch (status) {
+ case 'pending':
+ return { icon: Clock, color: '#787878' };
+ case 'open':
+ return { icon: Circle, color: '#00E5FF' };
+ case 'filled':
+ return { icon: CheckCircle, color: '#00D66F' };
+ case 'cancelled':
+ return { icon: XCircle, color: '#FF3B3B' };
+ case 'error':
+ return { icon: AlertCircle, color: '#FF3B3B' };
+ default:
+ return { icon: Circle, color: '#787878' };
+ }
+ };
+
+ return (
+ <div className="bg-[#0F0F0F] border border-[#2A2A2A] rounded-lg p-4">
+ {/* Header */}
+ <div className="flex items-center justify-between mb-4">
+ <span className="text-sm text-white font-semibold">Grid Visualization</span>
+ <div className="flex items-center gap-4 text-xs">
+ <div className="flex items-center gap-1">
+ <div className="w-3 h-3 rounded-full bg-[#00D66F]" />
+ <span className="text-[#787878]">Buy</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <div className="w-3 h-3 rounded-full bg-[#FF3B3B]" />
+ <span className="text-[#787878]">Sell</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Visualization */}
+ <div className="relative" style={{ height }}>
+ {/* Grid background */}
+ <div className="absolute inset-0 flex flex-col justify-between">
+ {[...Array(10)].map((_, i) => (
+ <div key={i} className="border-t border-[#1A1A1A]" />
+ ))}
+ </div>
+
+ {/* Price scale */}
+ <div className="absolute left-0 top-0 bottom-0 w-16 flex flex-col justify-between text-xs text-[#787878] pr-2">
+ <span>{visualization.maxPrice.toFixed(2)}</span>
+ <span>{((visualization.maxPrice + visualization.minPrice) / 2).toFixed(2)}</span>
+ <span>{visualization.minPrice.toFixed(2)}</span>
+ </div>
+
+ {/* Grid content area */}
+ <div className="absolute left-16 right-0 top-0 bottom-0">
+ {/* Upper bound line */}
+ <div
+ className="absolute left-0 right-0 border-t-2 border-dashed border-[#FF8800]/50"
+ style={{ top: visualization.priceToY(config.upperPrice) }}
+ >
+ <span className="absolute right-0 -top-4 text-xs text-[#FF8800]">
+ Upper: {config.upperPrice.toFixed(2)}
+ </span>
+ </div>
+
+ {/* Lower bound line */}
+ <div
+ className="absolute left-0 right-0 border-t-2 border-dashed border-[#FF8800]/50"
+ style={{ top: visualization.priceToY(config.lowerPrice) }}
+ >
+ <span className="absolute right-0 top-1 text-xs text-[#FF8800]">
+ Lower: {config.lowerPrice.toFixed(2)}
+ </span>
+ </div>
+
+ {/* Stop Loss line */}
+ {visualization.stopLossY !== null && (
+ <div
+ className="absolute left-0 right-0 border-t-2 border-dashed border-[#FF3B3B]"
+ style={{ top: visualization.stopLossY }}
+ >
+ <span className="absolute right-0 top-1 text-xs text-[#FF3B3B]">
+ SL: {config.stopLoss?.toFixed(2)}
+ </span>
+ </div>
+ )}
+
+ {/* Take Profit line */}
+ {visualization.takeProfitY !== null && (
+ <div
+ className="absolute left-0 right-0 border-t-2 border-dashed border-[#00D66F]"
+ style={{ top: visualization.takeProfitY }}
+ >
+ <span className="absolute right-0 -top-4 text-xs text-[#00D66F]">
+ TP: {config.takeProfit?.toFixed(2)}
+ </span>
+ </div>
+ )}
+
+ {/* Grid levels */}
+ {visualization.levelPositions.map((level, index) => {
+ const { icon: Icon, color } = getStatusVisual(level.status);
+ const isBuy = level.side === 'buy';
+
+ return (
+ <div
+ key={index}
+ className="absolute left-0 right-0 flex items-center group"
+ style={{ top: level.y - 10 }}
+ >
+ {/* Level line */}
+ <div
+ className={`absolute left-0 right-0 h-0.5 ${
+ isBuy ? 'bg-[#00D66F]/30' : 'bg-[#FF3B3B]/30'
+ }`}
+ />
+
+ {/* Level indicator */}
+ <div
+ className={`absolute left-4 flex items-center gap-2 px-2 py-1 rounded ${
+ isBuy ? 'bg-[#00D66F]/20' : 'bg-[#FF3B3B]/20'
+ }`}
+ >
+ {isBuy ? (
+ <ArrowUp className="w-3 h-3 text-[#00D66F]" />
+ ) : (
+ <ArrowDown className="w-3 h-3 text-[#FF3B3B]" />
+ )}
+ <span className={`text-xs ${isBuy ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}>
+ {level.price.toFixed(2)}
+ </span>
+ <Icon className="w-3 h-3" style={{ color }} />
+ </div>
+
+ {/* Quantity badge */}
+ <div className="absolute right-4 text-xs text-[#787878]">
+ {level.quantity.toFixed(4)}
+ </div>
+
+ {/* Tooltip on hover */}
+ <div className="absolute left-24 hidden group-hover:block bg-[#1A1A1A] border border-[#2A2A2A] rounded px-2 py-1 z-10 whitespace-nowrap">
+ <div className="text-xs">
+ <div className="text-white">
+ Level {level.levelIndex + 1}: {level.side.toUpperCase()} @ {level.price.toFixed(2)}
+ </div>
+ <div className="text-[#787878]">
+ Status: {level.status} | Qty: {level.quantity}
+ </div>
+ {level.filledPrice && (
+ <div className="text-[#00D66F]">
+ Filled @ {level.filledPrice.toFixed(2)}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+
+ {/* Current price line */}
+ <div
+ className="absolute left-0 right-0 flex items-center"
+ style={{ top: visualization.currentPriceY }}
+ >
+ <div className="absolute left-0 right-0 h-0.5 bg-[#FFFFFF]" />
+ <div className="absolute right-0 bg-white text-black text-xs px-2 py-0.5 rounded font-semibold">
+ {currentPrice.toFixed(2)}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Legend */}
+ <div className="mt-4 flex items-center justify-center gap-6 text-xs text-[#787878]">
+ <div className="flex items-center gap-1">
+ <Clock className="w-3 h-3" />
+ <span>Pending</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <Circle className="w-3 h-3 text-[#00E5FF]" />
+ <span>Open</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <CheckCircle className="w-3 h-3 text-[#00D66F]" />
+ <span>Filled</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <XCircle className="w-3 h-3 text-[#FF3B3B]" />
+ <span>Cancelled</span>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default GridVisualization;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/index.ts
new file mode 100644
index 000000000..625377c88
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/index.ts
@@ -0,0 +1,20 @@
+/**
+ * Grid Trading Components
+ *
+ * UI components for grid trading functionality.
+ */
+
+export { GridConfigPanel } from './GridConfigPanel';
+export { GridVisualization } from './GridVisualization';
+export { GridStatusPanel } from './GridStatusPanel';
+export { GridTradingPanel } from './GridTradingPanel';
+
+// Re-export types for convenience
+export type {
+ GridConfig,
+ GridState,
+ GridLevel,
+ GridType,
+ GridDirection,
+ GridStatus,
+} from '../../../../services/gridTrading/types';
diff --git a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
new file mode 100644
index 000000000..11f3a5f8e
--- /dev/null
+++ b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
@@ -0,0 +1,1175 @@
+/**
+ * Stock Broker Context
+ *
+ * Unified state management for stock brokers globally
+ * Separate from crypto BrokerContext to maintain clean architecture
+ */
+
+import React, {
+ createContext,
+ useContext,
+ useState,
+ useEffect,
+ useCallback,
+ useMemo,
+ useRef,
+ ReactNode,
+} from 'react';
+
+import {
+ STOCK_BROKER_REGISTRY,
+ getAllStockBrokers,
+ getStockBrokerMetadata,
+ createStockBrokerAdapter,
+ getStockBrokersByRegion,
+ stockBrokerSupportsFeature,
+ stockBrokerSupportsTradingFeature,
+ getStockBrokerDefaultSymbols,
+} from '../brokers/stocks';
+
+import type {
+ IStockBrokerAdapter,
+ StockBrokerMetadata,
+ Region,
+ BrokerCredentials,
+ AuthResponse,
+ Position,
+ Holding,
+ Funds,
+ Order,
+ Trade,
+} from '../brokers/stocks/types';
+
+import { saveSetting, getSetting } from '@/services/core/sqliteService';
+import {
+ initTradingSession,
+ switchTradingMode as switchUnifiedTradingMode,
+ getPositions as getUnifiedPositions,
+ getOrders as getUnifiedOrders,
+ getPaperFunds,
+ getPaperTrades,
+ type TradingMode,
+ type UnifiedPosition,
+ type PaperOrder,
+} from '@/services/unifiedTradingService';
+
+// ============================================================================
+// CONSTANTS
+// ============================================================================
+
+const CONNECTION_TIMEOUT = 15000; // 15 seconds for stock brokers (may need OAuth)
+const CONNECTION_RETRY_ATTEMPTS = 2;
+const CONNECTION_RETRY_DELAY = 3000;
+
+// Storage keys
+const STORAGE_KEYS = {
+ ACTIVE_STOCK_BROKER: 'active_stock_broker',
+ STOCK_TRADING_MODE: 'stock_trading_mode',
+ LAST_CONNECTED_BROKERS: 'last_connected_stock_brokers',
+} as const;
+
+// ============================================================================
+// HELPERS
+// ============================================================================
+
+function validateTradingMode(value: string | null): 'live' | 'paper' | null {
+ if (value === 'live' || value === 'paper') return value;
+ return null;
+}
+
+async function safeStorageGet(key: string): Promise<string | null> {
+ try {
+ return await getSetting(key);
+ } catch (error) {
+ console.error(`[StockBrokerContext] Failed to get storage key "${key}":`, error);
+ return null;
+ }
+}
+
+async function safeStorageSet(key: string, value: string): Promise<void> {
+ try {
+ await saveSetting(key, value, 'stock_broker');
+ } catch (error) {
+ console.error(`[StockBrokerContext] Failed to set storage key "${key}":`, error);
+ }
+}
+
+function createTimeout(ms: number): Promise<never> {
+ return new Promise((_, reject) =>
+ setTimeout(() => reject(new Error(`Connection timeout after ${ms}ms`)), ms)
+ );
+}
+
+async function retryConnect(
+ connectFn: () => Promise<void>,
+ attempts: number = CONNECTION_RETRY_ATTEMPTS,
+ delay: number = CONNECTION_RETRY_DELAY
+): Promise<void> {
+ for (let i = 0; i < attempts; i++) {
+ try {
+ await Promise.race([connectFn(), createTimeout(CONNECTION_TIMEOUT)]);
+ return;
+ } catch (error) {
+ if (i === attempts - 1) throw error;
+ await new Promise((resolve) => setTimeout(resolve, delay * (i + 1)));
+ }
+ }
+}
+
+// ============================================================================
+// CONTEXT TYPES
+// ============================================================================
+
+interface StockBrokerContextType {
+ // Active broker
+ activeBroker: string | null;
+ activeBrokerMetadata: StockBrokerMetadata | null;
+ setActiveBroker: (brokerId: string) => Promise<void>;
+
+ // Available brokers
+ availableBrokers: StockBrokerMetadata[];
+ getBrokersByRegion: (region: Region) => StockBrokerMetadata[];
+
+ // Trading mode
+ tradingMode: 'live' | 'paper';
+ setTradingMode: (mode: 'live' | 'paper') => void;
+
+ // Adapter instance
+ adapter: IStockBrokerAdapter | null;
+
+ // Authentication
+ isAuthenticated: boolean;
+ authenticate: (credentials: BrokerCredentials) => Promise<AuthResponse>;
+ logout: () => Promise<void>;
+ getAuthUrl: () => Promise<string | null>;
+
+ // Broker capabilities (shortcuts)
+ supportsFeature: (feature: keyof StockBrokerMetadata['features']) => boolean;
+ supportsTradingFeature: (feature: keyof StockBrokerMetadata['tradingFeatures']) => boolean;
+
+ // Default symbols for selected broker
+ defaultSymbols: string[];
+
+ // Cached data
+ positions: Position[];
+ holdings: Holding[];
+ orders: Order[];
+ trades: Trade[];
+ funds: Funds | null;
+
+ // Data refresh
+ refreshPositions: () => Promise<void>;
+ refreshHoldings: () => Promise<void>;
+ refreshOrders: () => Promise<void>;
+ refreshTrades: () => Promise<void>;
+ refreshFunds: () => Promise<void>;
+ refreshAll: () => Promise<void>;
+
+ // Loading states
+ isLoading: boolean;
+ isConnecting: boolean;
+ isRefreshing: boolean;
+
+ // Error state
+ error: string | null;
+ clearError: () => void;
+}
+
+const StockBrokerContext = createContext<StockBrokerContextType | null>(null);
+
+// ============================================================================
+// PROVIDER COMPONENT
+// ============================================================================
+
+interface StockBrokerProviderProps {
+ children: ReactNode;
+}
+
+export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
+ // Core state
+ const [activeBroker, setActiveBrokerState] = useState<string | null>(null);
+ const [tradingMode, setTradingModeState] = useState<'live' | 'paper'>('paper');
+ const [adapter, setAdapter] = useState<IStockBrokerAdapter | null>(null);
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
+
+ // Loading states
+ const [isLoading, setIsLoading] = useState(true);
+ const [isConnecting, setIsConnecting] = useState(false);
+ const [isRefreshing, setIsRefreshing] = useState(false);
+
+ // Error state
+ const [error, setError] = useState<string | null>(null);
+
+ // Cached trading data
+ const [positions, setPositions] = useState<Position[]>([]);
+ const [holdings, setHoldings] = useState<Holding[]>([]);
+ const [orders, setOrders] = useState<Order[]>([]);
+ const [trades, setTrades] = useState<Trade[]>([]);
+ const [funds, setFunds] = useState<Funds | null>(null);
+
+ // Refs
+ const abortControllerRef = useRef<AbortController | null>(null);
+ const hasInitializedRef = useRef(false);
+
+ // ============================================================================
+ // COMPUTED VALUES (Memoized)
+ // ============================================================================
+
+ const availableBrokers = useMemo(() => {
+ return getAllStockBrokers();
+ }, []);
+
+ const activeBrokerMetadata = useMemo(() => {
+ if (!activeBroker) return null;
+ return getStockBrokerMetadata(activeBroker) || null;
+ }, [activeBroker]);
+
+ const defaultSymbols = useMemo(() => {
+ if (!activeBroker) return [];
+ return getStockBrokerDefaultSymbols(activeBroker);
+ }, [activeBroker]);
+
+ // ============================================================================
+ // CAPABILITY CHECKERS
+ // ============================================================================
+
+ const supportsFeature = useCallback(
+ (feature: keyof StockBrokerMetadata['features']): boolean => {
+ if (!activeBroker) return false;
+ return stockBrokerSupportsFeature(activeBroker, feature);
+ },
+ [activeBroker]
+ );
+
+ const supportsTradingFeature = useCallback(
+ (feature: keyof StockBrokerMetadata['tradingFeatures']): boolean => {
+ if (!activeBroker) return false;
+ return stockBrokerSupportsTradingFeature(activeBroker, feature);
+ },
+ [activeBroker]
+ );
+
+ const getBrokersByRegion = useCallback((region: Region): StockBrokerMetadata[] => {
+ return getStockBrokersByRegion(region);
+ }, []);
+
+ // ============================================================================
+ // INITIALIZATION
+ // ============================================================================
+
+ useEffect(() => {
+ const loadSavedPreferences = async () => {
+ if (hasInitializedRef.current) return;
+ hasInitializedRef.current = true;
+
+ setIsLoading(true);
+
+ try {
+ // Load saved broker preference
+ const savedBroker = await safeStorageGet(STORAGE_KEYS.ACTIVE_STOCK_BROKER);
+ if (savedBroker && STOCK_BROKER_REGISTRY[savedBroker]) {
+ setActiveBrokerState(savedBroker);
+ }
+
+ // Load saved trading mode
+ const savedModeStr = await safeStorageGet(STORAGE_KEYS.STOCK_TRADING_MODE);
+ const savedMode = validateTradingMode(savedModeStr);
+ if (savedMode) {
+ setTradingModeState(savedMode);
+ }
+
+ console.log('[StockBrokerContext] Preferences loaded', {
+ broker: savedBroker,
+ mode: savedMode,
+ });
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to load preferences:', err);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ loadSavedPreferences();
+ }, []);
+
+ // Auto-create adapter when broker changes (including on startup)
+ useEffect(() => {
+ const initializeAdapter = async () => {
+ if (!activeBroker || adapter?.brokerId === activeBroker) return;
+
+ console.log(`[StockBrokerContext] Initializing adapter for: ${activeBroker}`);
+
+ try {
+ const newAdapter = createStockBrokerAdapter(activeBroker);
+ console.log(`[StockBrokerContext] Created adapter for: ${activeBroker}`);
+
+ // Load credentials from database
+ try {
+ console.log(`[StockBrokerContext] Loading credentials from database...`);
+ const storedCreds = await (newAdapter as any).loadCredentials();
+
+ if (storedCreds && storedCreds.apiKey) {
+ console.log(`[StockBrokerContext] Found stored credentials, loading into adapter memory...`);
+
+ // Set API credentials in adapter memory
+ if (newAdapter.setCredentials) {
+ newAdapter.setCredentials(storedCreds.apiKey, storedCreds.apiSecret || '');
+ console.log(`[StockBrokerContext] ✓ Credentials loaded into adapter memory`);
+ }
+
+ // If access_token exists, attempt auto-restore session
+ if (storedCreds.accessToken && typeof (newAdapter as any).initFromStorage === 'function') {
+ console.log(`[StockBrokerContext] Access token found, attempting auto-restore...`);
+ const restored = await (newAdapter as any).initFromStorage();
+
+ if (restored) {
+ console.log(`[StockBrokerContext] ✓ Session restored successfully`);
+ setIsAuthenticated(true);
+
+ // Initialize unified trading session
+ try {
+ await initTradingSession(activeBroker, tradingMode);
+ console.log(`[StockBrokerContext] ✓ Trading session initialized`);
+ } catch (sessionErr) {
+ console.error('[StockBrokerContext] Failed to init trading session:', sessionErr);
+ }
+
+ // Note: Data will be auto-loaded by the useEffect that watches isAuthenticated
+ } else {
+ console.log(`[StockBrokerContext] Session restore failed (token may be expired)`);
+ }
+ } else {
+ console.log(`[StockBrokerContext] No access token found, manual OAuth required`);
+ }
+ } else {
+ console.log(`[StockBrokerContext] No stored credentials found`);
+ }
+ } catch (loadErr) {
+ console.log('[StockBrokerContext] Failed to load credentials:', loadErr);
+ }
+
+ setAdapter(newAdapter);
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to create adapter:', err);
+ }
+ };
+
+ initializeAdapter();
+ }, [activeBroker, tradingMode]);
+
+ // ============================================================================
+ // BROKER MANAGEMENT
+ // ============================================================================
+
+ const setActiveBroker = useCallback(async (brokerId: string) => {
+ if (!STOCK_BROKER_REGISTRY[brokerId]) {
+ throw new Error(`Stock broker "${brokerId}" is not registered`);
+ }
+
+ // Abort any ongoing connection
+ abortControllerRef.current?.abort();
+
+ // Clean up existing adapter (DON'T logout - preserves credentials in DB)
+ if (adapter && adapter.brokerId !== brokerId) {
+ console.log(`[StockBrokerContext] Switching from ${adapter.brokerId} to ${brokerId}, preserving credentials`);
+ // Don't call logout() - it deletes credentials from database
+ // Just reset the adapter instance
+ }
+
+ // Reset state
+ setAdapter(null);
+ setIsAuthenticated(false);
+ setPositions([]);
+ setHoldings([]);
+ setOrders([]);
+ setTrades([]);
+ setFunds(null);
+ setError(null);
+
+ // Set new broker
+ setActiveBrokerState(brokerId);
+ await safeStorageSet(STORAGE_KEYS.ACTIVE_STOCK_BROKER, brokerId);
+
+ // Adapter will be created by useEffect watching activeBroker
+ console.log(`[StockBrokerContext] Active broker set to: ${brokerId}`);
+ }, [adapter]);
+
+ const setTradingMode = useCallback(async (mode: 'live' | 'paper') => {
+ setTradingModeState(mode);
+ await safeStorageSet(STORAGE_KEYS.STOCK_TRADING_MODE, mode);
+
+ // Switch mode in unified trading service
+ try {
+ await switchUnifiedTradingMode(mode);
+ console.log(`[StockBrokerContext] Trading mode switched to: ${mode}`);
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to switch unified trading mode:', err);
+ }
+ }, []);
+
+ // ============================================================================
+ // AUTHENTICATION
+ // ============================================================================
+
+ const getAuthUrl = useCallback(async (): Promise<string | null> => {
+ if (!activeBroker) return null;
+
+ try {
+ // Use existing adapter if available, otherwise create temporary one
+ const brokerAdapter = adapter || createStockBrokerAdapter(activeBroker);
+
+ // Load credentials before generating auth URL
+ try {
+ console.log('[StockBrokerContext] Attempting to load credentials...');
+ const storedCreds = await (brokerAdapter as any).loadCredentials();
+ console.log('[StockBrokerContext] loadCredentials result:', {
+ hasCredentials: !!storedCreds,
+ hasApiKey: !!(storedCreds && storedCreds.apiKey),
+ hasApiSecret: !!(storedCreds && storedCreds.apiSecret),
+ apiKeyLength: storedCreds?.apiKey?.length || 0,
+ });
+
+ if (storedCreds && storedCreds.apiKey && brokerAdapter.setCredentials) {
+ console.log('[StockBrokerContext] Setting credentials on adapter');
+ brokerAdapter.setCredentials(storedCreds.apiKey, storedCreds.apiSecret || '');
+ console.log('[StockBrokerContext] ✓ Credentials loaded and set for auth URL generation');
+ } else {
+ console.warn('[StockBrokerContext] No valid credentials found', storedCreds);
+ }
+ } catch (loadErr) {
+ console.error('[StockBrokerContext] Failed to load credentials:', loadErr);
+ }
+
+ if (brokerAdapter.getAuthUrl) {
+ return brokerAdapter.getAuthUrl();
+ }
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to get auth URL:', err);
+ }
+
+ return null;
+ }, [activeBroker, adapter]);
+
+ const authenticate = useCallback(
+ async (credentials: BrokerCredentials): Promise<AuthResponse> => {
+ if (!activeBroker) {
+ return {
+ success: false,
+ message: 'No broker selected',
+ errorCode: 'NO_BROKER',
+ };
+ }
+
+ // Abort any existing connection
+ abortControllerRef.current?.abort();
+ abortControllerRef.current = new AbortController();
+
+ setIsConnecting(true);
+ setError(null);
+
+ try {
+ // Use existing adapter or create new one
+ const adapterToUse = adapter || createStockBrokerAdapter(activeBroker);
+
+ // Authenticate
+ const response = await adapterToUse.authenticate(credentials);
+
+ if (response.success) {
+ // Update adapter if we created a new one
+ if (!adapter) {
+ setAdapter(adapterToUse);
+ }
+ setIsAuthenticated(true);
+
+ // Initialize unified trading session
+ try {
+ await initTradingSession(activeBroker, tradingMode);
+ console.log(`[StockBrokerContext] Initialized trading session: broker=${activeBroker}, mode=${tradingMode}`);
+ } catch (sessionErr) {
+ console.error('[StockBrokerContext] Failed to init trading session:', sessionErr);
+ }
+
+ // Fetch initial data
+ await refreshAllData(adapterToUse);
+
+ console.log(`[StockBrokerContext] Successfully authenticated with ${activeBroker}`);
+ } else {
+ setError(response.message || 'Authentication failed');
+ }
+
+ return response;
+ } catch (err) {
+ const errorMessage = err instanceof Error ? err.message : 'Authentication failed';
+ setError(errorMessage);
+
+ return {
+ success: false,
+ message: errorMessage,
+ errorCode: 'AUTH_ERROR',
+ };
+ } finally {
+ setIsConnecting(false);
+ }
+ },
+ [activeBroker, tradingMode, adapter]
+ );
+
+ const logout = useCallback(async () => {
+ if (!adapter) return;
+
+ try {
+ await adapter.logout();
+ } catch (err) {
+ console.error('[StockBrokerContext] Logout error:', err);
+ }
+
+ // Reset state
+ setAdapter(null);
+ setIsAuthenticated(false);
+ setPositions([]);
+ setHoldings([]);
+ setOrders([]);
+ setTrades([]);
+ setFunds(null);
+
+ console.log('[StockBrokerContext] Logged out');
+ }, [adapter]);
+
+ // ============================================================================
+ // DATA REFRESH FUNCTIONS
+ // ============================================================================
+
+ const refreshAllData = async (adapterInstance: IStockBrokerAdapter, mode: 'live' | 'paper' = tradingMode) => {
+ setIsRefreshing(true);
+
+ try {
+ if (mode === 'paper') {
+ // Paper mode: fetch from unified trading service
+ console.log('[StockBrokerContext] refreshAllData: Paper mode - fetching paper trading data');
+
+ const [positionsData, ordersData, tradesData, fundsData] = await Promise.allSettled([
+ getUnifiedPositions(),
+ getUnifiedOrders(),
+ getPaperTrades(),
+ getPaperFunds(),
+ ]);
+
+ // Convert and set positions
+ if (positionsData.status === 'fulfilled') {
+ const convertedPositions: Position[] = positionsData.value.map((p) => ({
+ symbol: p.symbol,
+ exchange: p.exchange as Position['exchange'],
+ productType: 'CNC' as Position['productType'],
+ quantity: p.quantity,
+ buyQuantity: p.side === 'long' ? p.quantity : 0,
+ sellQuantity: p.side === 'short' ? p.quantity : 0,
+ buyValue: p.side === 'long' ? p.entry_price * p.quantity : 0,
+ sellValue: p.side === 'short' ? p.entry_price * p.quantity : 0,
+ averagePrice: p.entry_price,
+ lastPrice: p.current_price,
+ pnl: p.unrealized_pnl,
+ pnlPercent: p.entry_price > 0 ? ((p.current_price - p.entry_price) / p.entry_price) * 100 : 0,
+ dayPnl: 0,
+ }));
+ setPositions(convertedPositions);
+ }
+
+ // Paper trading has no holdings (demat positions)
+ setHoldings([]);
+
+ // Convert and set orders
+ if (ordersData.status === 'fulfilled') {
+ const mapStatus = (status: string): Order['status'] => {
+ switch (status) {
+ case 'pending': return 'PENDING';
+ case 'filled': return 'FILLED';
+ case 'partial': return 'PARTIALLY_FILLED';
+ case 'cancelled': return 'CANCELLED';
+ default: return 'PENDING';
+ }
+ };
+ const convertedOrders: Order[] = ordersData.value.map((o) => ({
+ orderId: o.id,
+ symbol: o.symbol,
+ exchange: 'NSE' as Order['exchange'],
+ side: o.side as Order['side'],
+ quantity: o.quantity,
+ filledQuantity: o.filled_qty,
+ pendingQuantity: o.quantity - o.filled_qty,
+ price: o.price || 0,
+ averagePrice: o.avg_price || 0,
+ triggerPrice: o.stop_price || undefined,
+ orderType: o.order_type as Order['orderType'],
+ productType: 'CNC' as Order['productType'],
+ validity: 'DAY' as Order['validity'],
+ status: mapStatus(o.status),
+ statusMessage: '',
+ placedAt: new Date(o.created_at),
+ updatedAt: o.filled_at ? new Date(o.filled_at) : undefined,
+ }));
+ setOrders(convertedOrders);
+ }
+
+ // Convert and set trades
+ if (tradesData.status === 'fulfilled') {
+ const convertedTrades: Trade[] = tradesData.value.map((t: PaperOrder) => ({
+ tradeId: t.id,
+ orderId: t.id,
+ symbol: t.symbol,
+ exchange: 'NSE' as Trade['exchange'],
+ side: t.side as Trade['side'],
+ quantity: t.filled_qty,
+ price: t.avg_price || t.price || 0,
+ productType: 'CNC' as Trade['productType'],
+ tradedAt: t.filled_at ? new Date(t.filled_at) : new Date(t.created_at),
+ }));
+ setTrades(convertedTrades);
+ }
+
+ // Convert and set funds
+ if (fundsData.status === 'fulfilled' && fundsData.value) {
+ const paperFundsData = fundsData.value;
+ // Map currency string to Currency type (default to INR if unknown)
+ const currencyMap: Record<string, Funds['currency']> = {
+ INR: 'INR', USD: 'USD', EUR: 'EUR', GBP: 'GBP', JPY: 'JPY', AUD: 'AUD', CAD: 'CAD', SGD: 'SGD', HKD: 'HKD'
+ };
+ const mappedCurrency = currencyMap[paperFundsData.currency] || 'INR';
+ const convertedFunds: Funds = {
+ totalBalance: paperFundsData.totalBalance,
+ availableCash: paperFundsData.availableCash,
+ usedMargin: paperFundsData.usedMargin,
+ availableMargin: paperFundsData.availableMargin,
+ collateral: 0,
+ unrealizedPnl: 0,
+ realizedPnl: 0,
+ currency: mappedCurrency,
+ };
+ setFunds(convertedFunds);
+ }
+ } else {
+ // Live mode: fetch from broker adapter
+ console.log('[StockBrokerContext] refreshAllData: Live mode - fetching broker data');
+
+ const [positionsData, holdingsData, ordersData, tradesData, fundsData] = await Promise.allSettled([
+ adapterInstance.getPositions(),
+ adapterInstance.getHoldings(),
+ adapterInstance.getOrders(),
+ adapterInstance.getTradeBook(),
+ adapterInstance.getFunds(),
+ ]);
+
+ if (positionsData.status === 'fulfilled') {
+ setPositions(positionsData.value);
+ }
+ if (holdingsData.status === 'fulfilled') {
+ setHoldings(holdingsData.value);
+ }
+ if (ordersData.status === 'fulfilled') {
+ setOrders(ordersData.value);
+ }
+ if (tradesData.status === 'fulfilled') {
+ setTrades(tradesData.value);
+ }
+ if (fundsData.status === 'fulfilled') {
+ setFunds(fundsData.value);
+ }
+ }
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to refresh data:', err);
+ } finally {
+ setIsRefreshing(false);
+ }
+ };
+
+ const refreshPositions = useCallback(async () => {
+ if (!isAuthenticated) return;
+
+ try {
+ if (tradingMode === 'paper') {
+ // Fetch from unified trading service (paper positions)
+ const unifiedPositions = await getUnifiedPositions();
+ // Convert UnifiedPosition to Position format
+ const convertedPositions: Position[] = unifiedPositions.map((p) => ({
+ symbol: p.symbol,
+ exchange: p.exchange as Position['exchange'],
+ productType: 'CNC' as Position['productType'],
+ quantity: p.quantity,
+ buyQuantity: p.side === 'long' ? p.quantity : 0,
+ sellQuantity: p.side === 'short' ? p.quantity : 0,
+ buyValue: p.side === 'long' ? p.entry_price * p.quantity : 0,
+ sellValue: p.side === 'short' ? p.entry_price * p.quantity : 0,
+ averagePrice: p.entry_price,
+ lastPrice: p.current_price,
+ pnl: p.unrealized_pnl,
+ pnlPercent: p.entry_price > 0 ? ((p.current_price - p.entry_price) / p.entry_price) * 100 : 0,
+ dayPnl: 0,
+ }));
+ setPositions(convertedPositions);
+ } else if (adapter) {
+ // Fetch from live broker
+ const data = await adapter.getPositions();
+ setPositions(data);
+ }
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to refresh positions:', err);
+ }
+ }, [adapter, isAuthenticated, tradingMode]);
+
+ const refreshHoldings = useCallback(async () => {
+ if (!isAuthenticated) return;
+
+ try {
+ if (tradingMode === 'paper') {
+ // Paper trading doesn't have long-term holdings (delivery positions)
+ // Holdings are actual shares held in demat account, which paper trading doesn't have
+ setHoldings([]);
+ console.log('[StockBrokerContext] Paper mode: Holdings cleared (paper trading has no demat holdings)');
+ } else if (adapter) {
+ // Fetch from live broker
+ const data = await adapter.getHoldings();
+ setHoldings(data);
+ }
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to refresh holdings:', err);
+ }
+ }, [adapter, isAuthenticated, tradingMode]);
+
+ const refreshOrders = useCallback(async () => {
+ if (!isAuthenticated) return;
+
+ try {
+ if (tradingMode === 'paper') {
+ // Fetch from unified trading service (paper orders)
+ const paperOrders = await getUnifiedOrders();
+ // Map paper order status to Order status
+ const mapStatus = (status: string): Order['status'] => {
+ switch (status) {
+ case 'pending': return 'PENDING';
+ case 'filled': return 'FILLED';
+ case 'partial': return 'PARTIALLY_FILLED';
+ case 'cancelled': return 'CANCELLED';
+ default: return 'PENDING';
+ }
+ };
+ // Convert PaperOrder to Order format
+ const convertedOrders: Order[] = paperOrders.map((o) => ({
+ orderId: o.id,
+ symbol: o.symbol,
+ exchange: 'NSE' as Order['exchange'],
+ side: o.side as Order['side'],
+ quantity: o.quantity,
+ filledQuantity: o.filled_qty,
+ pendingQuantity: o.quantity - o.filled_qty,
+ price: o.price || 0,
+ averagePrice: o.avg_price || 0,
+ triggerPrice: o.stop_price || undefined,
+ orderType: o.order_type as Order['orderType'],
+ productType: 'CNC' as Order['productType'],
+ validity: 'DAY' as Order['validity'],
+ status: mapStatus(o.status),
+ statusMessage: '',
+ placedAt: new Date(o.created_at),
+ updatedAt: o.filled_at ? new Date(o.filled_at) : undefined,
+ }));
+ setOrders(convertedOrders);
+ } else if (adapter) {
+ // Fetch from live broker
+ const data = await adapter.getOrders();
+ setOrders(data);
+ }
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to refresh orders:', err);
+ }
+ }, [adapter, isAuthenticated, tradingMode]);
+
+ const refreshTrades = useCallback(async () => {
+ if (!isAuthenticated) return;
+
+ try {
+ if (tradingMode === 'paper') {
+ // Fetch filled orders from paper trading as "trades"
+ const paperTrades = await getPaperTrades();
+ // Convert PaperOrder to Trade format
+ const convertedTrades: Trade[] = paperTrades.map((t: PaperOrder) => ({
+ tradeId: t.id,
+ orderId: t.id,
+ symbol: t.symbol,
+ exchange: 'NSE' as Trade['exchange'],
+ side: t.side as Trade['side'],
+ quantity: t.filled_qty,
+ price: t.avg_price || t.price || 0,
+ productType: 'CNC' as Trade['productType'],
+ tradedAt: t.filled_at ? new Date(t.filled_at) : new Date(t.created_at),
+ }));
+ setTrades(convertedTrades);
+ console.log(`[StockBrokerContext] Paper mode: Loaded ${convertedTrades.length} paper trades`);
+ } else if (adapter) {
+ // Fetch from live broker
+ const data = await adapter.getTradeBook();
+ setTrades(data);
+ }
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to refresh trades:', err);
+ }
+ }, [adapter, isAuthenticated, tradingMode]);
+
+ const refreshFunds = useCallback(async () => {
+ if (!isAuthenticated) return;
+
+ try {
+ if (tradingMode === 'paper') {
+ // Fetch from paper trading portfolio
+ const paperFundsData = await getPaperFunds();
+ if (paperFundsData) {
+ // Map currency string to Currency type (default to INR if unknown)
+ const currencyMap: Record<string, Funds['currency']> = {
+ INR: 'INR', USD: 'USD', EUR: 'EUR', GBP: 'GBP', JPY: 'JPY', AUD: 'AUD', CAD: 'CAD', SGD: 'SGD', HKD: 'HKD'
+ };
+ const mappedCurrency = currencyMap[paperFundsData.currency] || 'INR';
+ // Convert paper funds to Funds format
+ const convertedFunds: Funds = {
+ totalBalance: paperFundsData.totalBalance,
+ availableCash: paperFundsData.availableCash,
+ usedMargin: paperFundsData.usedMargin,
+ availableMargin: paperFundsData.availableMargin,
+ collateral: 0,
+ unrealizedPnl: 0,
+ realizedPnl: 0,
+ currency: mappedCurrency,
+ };
+ setFunds(convertedFunds);
+ console.log(`[StockBrokerContext] Paper mode: Loaded paper funds - Balance: ${convertedFunds.availableCash} ${convertedFunds.currency}`);
+ } else {
+ setFunds(null);
+ }
+ } else if (adapter) {
+ // Fetch from live broker
+ const data = await adapter.getFunds();
+ setFunds(data);
+ }
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to refresh funds:', err);
+ }
+ }, [adapter, isAuthenticated, tradingMode]);
+
+ const refreshAll = useCallback(async () => {
+ if (!isAuthenticated) return;
+
+ setIsRefreshing(true);
+ try {
+ // Use individual refresh functions that already handle paper/live mode
+ await Promise.allSettled([
+ refreshPositions(),
+ refreshHoldings(),
+ refreshOrders(),
+ refreshTrades(),
+ refreshFunds(),
+ ]);
+ } catch (err) {
+ console.error('[StockBrokerContext] Failed to refresh all data:', err);
+ } finally {
+ setIsRefreshing(false);
+ }
+ }, [isAuthenticated, refreshPositions, refreshHoldings, refreshOrders, refreshTrades, refreshFunds]);
+
+ // ============================================================================
+ // AUTO-LOAD DATA ON AUTHENTICATION
+ // ============================================================================
+
+ useEffect(() => {
+ // Auto-load data when adapter becomes authenticated
+ if (adapter && isAuthenticated && !isRefreshing) {
+ // Check if we have any data already loaded
+ const hasData = positions.length > 0 || holdings.length > 0 || orders.length > 0 || funds !== null;
+
+ if (!hasData) {
+ console.log('[StockBrokerContext] Authenticated adapter detected, loading initial data...');
+ refreshAllData(adapter).catch((err) => {
+ console.error('[StockBrokerContext] Failed to auto-load data:', err);
+ });
+ }
+ }
+ }, [adapter, isAuthenticated]);
+
+ // ============================================================================
+ // REFRESH DATA ON TRADING MODE CHANGE
+ // ============================================================================
+
+ const previousTradingModeRef = useRef(tradingMode);
+
+ useEffect(() => {
+ // Refresh all data when trading mode changes (and we're authenticated)
+ if (isAuthenticated && previousTradingModeRef.current !== tradingMode) {
+ console.log(`[StockBrokerContext] Trading mode changed from ${previousTradingModeRef.current} to ${tradingMode}, refreshing data...`);
+ previousTradingModeRef.current = tradingMode;
+
+ // Clear current data first
+ setPositions([]);
+ setHoldings([]);
+ setOrders([]);
+ setTrades([]);
+ setFunds(null);
+
+ // Refresh with new mode
+ if (adapter) {
+ refreshAllData(adapter, tradingMode).catch((err) => {
+ console.error('[StockBrokerContext] Failed to refresh data after mode switch:', err);
+ });
+ }
+ }
+ }, [tradingMode, isAuthenticated, adapter]);
+
+ // ============================================================================
+ // ERROR HANDLING
+ // ============================================================================
+
+ const clearError = useCallback(() => {
+ setError(null);
+ }, []);
+
+ // ============================================================================
+ // CONTEXT VALUE
+ // ============================================================================
+
+ const contextValue = useMemo(
+ () => ({
+ // Active broker
+ activeBroker,
+ activeBrokerMetadata,
+ setActiveBroker,
+
+ // Available brokers
+ availableBrokers,
+ getBrokersByRegion,
+
+ // Trading mode
+ tradingMode,
+ setTradingMode,
+
+ // Adapter
+ adapter,
+
+ // Authentication
+ isAuthenticated,
+ authenticate,
+ logout,
+ getAuthUrl,
+
+ // Capabilities
+ supportsFeature,
+ supportsTradingFeature,
+
+ // Default symbols
+ defaultSymbols,
+
+ // Cached data
+ positions,
+ holdings,
+ orders,
+ trades,
+ funds,
+
+ // Refresh functions
+ refreshPositions,
+ refreshHoldings,
+ refreshOrders,
+ refreshTrades,
+ refreshFunds,
+ refreshAll,
+
+ // Loading states
+ isLoading,
+ isConnecting,
+ isRefreshing,
+
+ // Error
+ error,
+ clearError,
+ }),
+ [
+ activeBroker,
+ activeBrokerMetadata,
+ setActiveBroker,
+ availableBrokers,
+ getBrokersByRegion,
+ tradingMode,
+ setTradingMode,
+ adapter,
+ isAuthenticated,
+ authenticate,
+ logout,
+ getAuthUrl,
+ supportsFeature,
+ supportsTradingFeature,
+ defaultSymbols,
+ positions,
+ holdings,
+ orders,
+ trades,
+ funds,
+ refreshPositions,
+ refreshHoldings,
+ refreshOrders,
+ refreshTrades,
+ refreshFunds,
+ refreshAll,
+ isLoading,
+ isConnecting,
+ isRefreshing,
+ error,
+ clearError,
+ ]
+ );
+
+ return (
+ <StockBrokerContext.Provider value={contextValue}>
+ {children}
+ </StockBrokerContext.Provider>
+ );
+}
+
+// ============================================================================
+// HOOKS
+// ============================================================================
+
+/**
+ * Main hook for accessing stock broker context
+ */
+export function useStockBrokerContext(): StockBrokerContextType {
+ const context = useContext(StockBrokerContext);
+
+ if (!context) {
+ throw new Error('useStockBrokerContext must be used within a StockBrokerProvider');
+ }
+
+ return context;
+}
+
+/**
+ * Hook for broker selection
+ */
+export function useStockBrokerSelection() {
+ const {
+ activeBroker,
+ activeBrokerMetadata,
+ availableBrokers,
+ setActiveBroker,
+ getBrokersByRegion,
+ isLoading,
+ } = useStockBrokerContext();
+
+ return {
+ broker: activeBroker,
+ metadata: activeBrokerMetadata,
+ brokers: availableBrokers,
+ setBroker: setActiveBroker,
+ getBrokersByRegion,
+ isLoading,
+ };
+}
+
+/**
+ * Hook for authentication
+ */
+export function useStockBrokerAuth() {
+ const {
+ isAuthenticated,
+ authenticate,
+ logout,
+ getAuthUrl,
+ isConnecting,
+ error,
+ clearError,
+ adapter,
+ } = useStockBrokerContext();
+
+ return {
+ isAuthenticated,
+ authenticate,
+ logout,
+ getAuthUrl,
+ isConnecting,
+ error,
+ clearError,
+ adapter,
+ };
+}
+
+/**
+ * Hook for trading data
+ */
+export function useStockTradingData() {
+ const {
+ adapter,
+ positions,
+ holdings,
+ orders,
+ trades,
+ funds,
+ refreshPositions,
+ refreshHoldings,
+ refreshOrders,
+ refreshTrades,
+ refreshFunds,
+ refreshAll,
+ isRefreshing,
+ isAuthenticated,
+ } = useStockBrokerContext();
+
+ return {
+ adapter,
+ positions,
+ holdings,
+ orders,
+ trades,
+ funds,
+ refreshPositions,
+ refreshHoldings,
+ refreshOrders,
+ refreshTrades,
+ refreshFunds,
+ refreshAll,
+ isRefreshing,
+ isReady: isAuthenticated && adapter !== null,
+ };
+}
+
+/**
+ * Hook for broker capabilities
+ */
+export function useStockBrokerCapabilities() {
+ const {
+ activeBrokerMetadata,
+ supportsFeature,
+ supportsTradingFeature,
+ defaultSymbols,
+ } = useStockBrokerContext();
+
+ return {
+ metadata: activeBrokerMetadata,
+ supportsFeature,
+ supportsTradingFeature,
+ defaultSymbols,
+ // Quick access to common features
+ hasWebSocket: supportsFeature('webSocket'),
+ hasAMO: supportsFeature('amo'),
+ hasGTT: supportsFeature('gtt'),
+ hasBracketOrder: supportsFeature('bracketOrder'),
+ hasCoverOrder: supportsFeature('coverOrder'),
+ hasOptionsChain: supportsFeature('optionsChain'),
+ };
+}
+
+/**
+ * Hook for trading mode
+ */
+export function useStockTradingMode() {
+ const { tradingMode, setTradingMode } = useStockBrokerContext();
+
+ return {
+ mode: tradingMode,
+ setMode: setTradingMode,
+ isLive: tradingMode === 'live',
+ isPaper: tradingMode === 'paper',
+ };
+}
diff --git a/fincept-terminal-desktop/src/i18n/config.ts b/fincept-terminal-desktop/src/i18n/config.ts
index 918779a05..2b4f75c0d 100644
--- a/fincept-terminal-desktop/src/i18n/config.ts
+++ b/fincept-terminal-desktop/src/i18n/config.ts
@@ -99,7 +99,6 @@ i18next
i18next.on('languageChanged', async (lng) => {
try {
await invoke('storage_set', { key: 'i18nextLng', value: lng });
- console.log(`[i18n] Language saved to SQLite: ${lng}`);
} catch (error) {
console.error('[i18n] Failed to save language:', error);
}
diff --git a/fincept-terminal-desktop/src/services/core/sqliteService.ts b/fincept-terminal-desktop/src/services/core/sqliteService.ts
index ab4ec8f2d..1211d22c7 100644
--- a/fincept-terminal-desktop/src/services/core/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/core/sqliteService.ts
@@ -1111,28 +1111,47 @@ class SqliteService {
// LLM Model Configs
async getLLMModelConfigs(): Promise<LLMModelConfig[]> {
- // Stub - not implemented in Rust backend yet
- console.warn('[SqliteService] getLLMModelConfigs not implemented');
- return [];
+ try {
+ return await invoke<LLMModelConfig[]>('db_get_llm_model_configs');
+ } catch (error) {
+ console.error('[SqliteService] Failed to get LLM model configs:', error);
+ return [];
+ }
}
async saveLLMModelConfig(config: LLMModelConfig): Promise<{ success: boolean; message: string }> {
- console.warn('[SqliteService] saveLLMModelConfig not implemented');
- return { success: false, message: 'Not implemented' };
+ try {
+ return await invoke<{ success: boolean; message: string }>('db_save_llm_model_config', { config });
+ } catch (error) {
+ console.error('[SqliteService] Failed to save LLM model config:', error);
+ return { success: false, message: String(error) };
+ }
}
async deleteLLMModelConfig(id: string): Promise<{ success: boolean; message: string }> {
- console.warn('[SqliteService] deleteLLMModelConfig not implemented');
- return { success: false, message: 'Not implemented' };
+ try {
+ return await invoke<{ success: boolean; message: string }>('db_delete_llm_model_config', { id });
+ } catch (error) {
+ console.error('[SqliteService] Failed to delete LLM model config:', error);
+ return { success: false, message: String(error) };
+ }
}
async toggleLLMModelConfigEnabled(id: string): Promise<{ success: boolean; message: string }> {
- console.warn('[SqliteService] toggleLLMModelConfigEnabled not implemented');
- return { success: false, message: 'Not implemented' };
+ try {
+ return await invoke<{ success: boolean; message: string }>('db_toggle_llm_model_config_enabled', { id });
+ } catch (error) {
+ console.error('[SqliteService] Failed to toggle LLM model config:', error);
+ return { success: false, message: String(error) };
+ }
}
async setActiveLLMProvider(provider: string): Promise<void> {
- console.warn('[SqliteService] setActiveLLMProvider not implemented');
+ try {
+ await invoke('db_set_active_llm_provider', { provider });
+ } catch (error) {
+ console.error('[SqliteService] Failed to set active LLM provider:', error);
+ }
}
// Alpha Arena
diff --git a/fincept-terminal-desktop/src/services/gridTrading/GridEngine.ts b/fincept-terminal-desktop/src/services/gridTrading/GridEngine.ts
new file mode 100644
index 000000000..85decd8c7
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/gridTrading/GridEngine.ts
@@ -0,0 +1,495 @@
+/**
+ * Grid Trading Engine
+ *
+ * Core grid trading logic that is broker-agnostic.
+ * Calculates grid levels, manages state, and coordinates order placement.
+ */
+
+import type {
+ GridConfig,
+ GridState,
+ GridLevel,
+ GridType,
+ GridCalculation,
+ GridLevelStatus,
+ GridStatus,
+} from './types';
+
+// ============================================================================
+// GRID CALCULATION UTILITIES
+// ============================================================================
+
+/**
+ * Calculate grid price levels based on configuration
+ */
+export function calculateGridLevels(config: GridConfig): number[] {
+ const { upperPrice, lowerPrice, gridLevels, gridType } = config;
+
+ if (upperPrice <= lowerPrice) {
+ throw new Error('Upper price must be greater than lower price');
+ }
+
+ if (gridLevels < 2) {
+ throw new Error('Grid levels must be at least 2');
+ }
+
+ const levels: number[] = [];
+
+ if (gridType === 'arithmetic') {
+ // Equal price gaps
+ const step = (upperPrice - lowerPrice) / (gridLevels - 1);
+ for (let i = 0; i < gridLevels; i++) {
+ levels.push(lowerPrice + step * i);
+ }
+ } else {
+ // Geometric - equal percentage gaps
+ const ratio = Math.pow(upperPrice / lowerPrice, 1 / (gridLevels - 1));
+ for (let i = 0; i < gridLevels; i++) {
+ levels.push(lowerPrice * Math.pow(ratio, i));
+ }
+ }
+
+ return levels.map(price => roundPrice(price, getDecimalPlaces(lowerPrice)));
+}
+
+/**
+ * Calculate complete grid details
+ */
+export function calculateGridDetails(config: GridConfig): GridCalculation {
+ const levels = calculateGridLevels(config);
+ const { gridType, totalInvestment, gridLevels } = config;
+
+ // Calculate grid spacing
+ let gridSpacing: number;
+ if (gridType === 'arithmetic') {
+ gridSpacing = levels[1] - levels[0];
+ } else {
+ gridSpacing = ((levels[1] / levels[0]) - 1) * 100; // percentage
+ }
+
+ // Calculate quantity per level
+ const avgPrice = (config.upperPrice + config.lowerPrice) / 2;
+ const quantityPerLevel = config.quantityPerGrid || (totalInvestment / gridLevels / avgPrice);
+
+ // Calculate totals
+ const totalQuantity = quantityPerLevel * gridLevels;
+
+ // Calculate potential profit (sum of all grid profits)
+ let potentialProfit = 0;
+ for (let i = 0; i < levels.length - 1; i++) {
+ // Each completed grid cycle generates profit = (sell_price - buy_price) * quantity
+ potentialProfit += (levels[i + 1] - levels[i]) * quantityPerLevel;
+ }
+
+ // Break-even is the weighted average of all buy levels
+ const totalBuyValue = levels.slice(0, Math.ceil(levels.length / 2))
+ .reduce((sum, price) => sum + price * quantityPerLevel, 0);
+ const totalBuyQty = Math.ceil(levels.length / 2) * quantityPerLevel;
+ const breakEvenPrice = totalBuyValue / totalBuyQty;
+
+ return {
+ levels,
+ gridSpacing,
+ quantityPerLevel: roundQuantity(quantityPerLevel, 8),
+ totalQuantity: roundQuantity(totalQuantity, 8),
+ totalInvestment,
+ breakEvenPrice: roundPrice(breakEvenPrice, getDecimalPlaces(config.lowerPrice)),
+ potentialProfit: roundPrice(potentialProfit, 2),
+ };
+}
+
+/**
+ * Initialize grid levels based on current price
+ */
+export function initializeGridLevels(
+ config: GridConfig,
+ currentPrice: number,
+ calculation: GridCalculation
+): GridLevel[] {
+ const { levels, quantityPerLevel } = calculation;
+ const { direction } = config;
+
+ return levels.map((price, index) => {
+ // Determine side based on direction and price relative to current
+ let side: 'buy' | 'sell';
+
+ if (direction === 'neutral') {
+ // Neutral: buy below current price, sell above
+ side = price < currentPrice ? 'buy' : 'sell';
+ } else if (direction === 'long') {
+ // Long bias: more buys, fewer sells
+ side = price < currentPrice ? 'buy' : 'sell';
+ } else {
+ // Short bias: more sells, fewer buys
+ side = price > currentPrice ? 'sell' : 'buy';
+ }
+
+ return {
+ levelIndex: index,
+ price,
+ side,
+ quantity: quantityPerLevel,
+ status: 'pending' as GridLevelStatus,
+ };
+ });
+}
+
+/**
+ * Create initial grid state
+ */
+export function createInitialGridState(
+ config: GridConfig,
+ currentPrice: number
+): GridState {
+ const calculation = calculateGridDetails(config);
+ const levels = initializeGridLevels(config, currentPrice, calculation);
+
+ return {
+ config,
+ levels,
+ status: 'draft',
+ currentPrice,
+
+ // Statistics
+ totalBuys: 0,
+ totalSells: 0,
+ realizedPnl: 0,
+ unrealizedPnl: 0,
+ totalPnl: 0,
+ gridProfit: 0,
+
+ // Position
+ currentPosition: 0,
+ averageEntryPrice: 0,
+
+ // Timestamps
+ createdAt: Date.now(),
+ lastUpdatedAt: Date.now(),
+
+ // Error tracking
+ errorCount: 0,
+ };
+}
+
+// ============================================================================
+// GRID STATE UPDATES
+// ============================================================================
+
+/**
+ * Update grid state when price changes
+ */
+export function updateGridOnPriceChange(
+ grid: GridState,
+ newPrice: number
+): GridState {
+ // Calculate unrealized P&L
+ let unrealizedPnl = 0;
+ if (grid.currentPosition !== 0 && grid.averageEntryPrice > 0) {
+ unrealizedPnl = (newPrice - grid.averageEntryPrice) * grid.currentPosition;
+ }
+
+ return {
+ ...grid,
+ currentPrice: newPrice,
+ unrealizedPnl,
+ totalPnl: grid.realizedPnl + unrealizedPnl,
+ lastUpdatedAt: Date.now(),
+ };
+}
+
+/**
+ * Update grid level status
+ */
+export function updateGridLevelStatus(
+ grid: GridState,
+ levelIndex: number,
+ status: GridLevelStatus,
+ orderId?: string
+): GridState {
+ const levels = [...grid.levels];
+ levels[levelIndex] = {
+ ...levels[levelIndex],
+ status,
+ orderId,
+ createdAt: status === 'open' ? Date.now() : levels[levelIndex].createdAt,
+ };
+
+ return {
+ ...grid,
+ levels,
+ lastUpdatedAt: Date.now(),
+ };
+}
+
+/**
+ * Update grid when an order is filled
+ */
+export function updateGridOnFill(
+ grid: GridState,
+ levelIndex: number,
+ filledQuantity: number,
+ filledPrice: number
+): GridState {
+ const levels = [...grid.levels];
+ const level = levels[levelIndex];
+
+ // Update level
+ levels[levelIndex] = {
+ ...level,
+ status: 'filled',
+ filledQuantity,
+ filledPrice,
+ filledAt: Date.now(),
+ };
+
+ // Update position tracking
+ let newPosition = grid.currentPosition;
+ let newTotalBuys = grid.totalBuys;
+ let newTotalSells = grid.totalSells;
+ let newRealizedPnl = grid.realizedPnl;
+ let newGridProfit = grid.gridProfit;
+ let newAvgEntry = grid.averageEntryPrice;
+
+ if (level.side === 'buy') {
+ // Buy order filled
+ const oldPosition = newPosition;
+ newPosition += filledQuantity;
+ newTotalBuys += 1;
+
+ // Update average entry price
+ if (newPosition > 0) {
+ const oldValue = oldPosition > 0 ? oldPosition * newAvgEntry : 0;
+ const newValue = filledQuantity * filledPrice;
+ newAvgEntry = (oldValue + newValue) / newPosition;
+ }
+ } else {
+ // Sell order filled
+ newPosition -= filledQuantity;
+ newTotalSells += 1;
+
+ // Calculate realized P&L if closing position
+ if (grid.currentPosition > 0 && grid.averageEntryPrice > 0) {
+ const pnl = (filledPrice - grid.averageEntryPrice) * filledQuantity;
+ newRealizedPnl += pnl;
+ newGridProfit += pnl;
+ }
+ }
+
+ // Calculate unrealized P&L
+ let unrealizedPnl = 0;
+ if (newPosition !== 0 && newAvgEntry > 0) {
+ unrealizedPnl = (grid.currentPrice - newAvgEntry) * newPosition;
+ }
+
+ // Flip the grid level to opposite side for next trade
+ const oppositePrice = findNextOppositeLevel(levels, levelIndex, grid.config);
+ if (oppositePrice) {
+ levels[levelIndex] = {
+ ...levels[levelIndex],
+ side: level.side === 'buy' ? 'sell' : 'buy',
+ price: oppositePrice,
+ status: 'pending',
+ orderId: undefined,
+ filledQuantity: undefined,
+ filledPrice: undefined,
+ filledAt: undefined,
+ };
+ }
+
+ return {
+ ...grid,
+ levels,
+ currentPosition: newPosition,
+ averageEntryPrice: newAvgEntry,
+ totalBuys: newTotalBuys,
+ totalSells: newTotalSells,
+ realizedPnl: newRealizedPnl,
+ unrealizedPnl,
+ totalPnl: newRealizedPnl + unrealizedPnl,
+ gridProfit: newGridProfit,
+ lastUpdatedAt: Date.now(),
+ };
+}
+
+/**
+ * Find the next opposite level price for a filled order
+ */
+function findNextOppositeLevel(
+ levels: GridLevel[],
+ filledIndex: number,
+ config: GridConfig
+): number | null {
+ const calculation = calculateGridDetails(config);
+ const allPrices = calculation.levels;
+
+ // If it was a buy, look for the next sell level above
+ // If it was a sell, look for the next buy level below
+ const filledLevel = levels[filledIndex];
+
+ if (filledLevel.side === 'buy') {
+ // Find the next price level above
+ const nextIndex = filledIndex + 1;
+ if (nextIndex < allPrices.length) {
+ return allPrices[nextIndex];
+ }
+ } else {
+ // Find the next price level below
+ const nextIndex = filledIndex - 1;
+ if (nextIndex >= 0) {
+ return allPrices[nextIndex];
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Get pending levels that need orders placed
+ */
+export function getPendingLevels(grid: GridState): GridLevel[] {
+ return grid.levels.filter(level => level.status === 'pending');
+}
+
+/**
+ * Get open levels (orders placed, waiting to fill)
+ */
+export function getOpenLevels(grid: GridState): GridLevel[] {
+ return grid.levels.filter(level => level.status === 'open');
+}
+
+/**
+ * Check if grid should be stopped (stop loss or take profit hit)
+ */
+export function checkGridStopConditions(grid: GridState): {
+ shouldStop: boolean;
+ reason?: string;
+} {
+ const { config, currentPrice } = grid;
+
+ if (config.stopLoss && currentPrice <= config.stopLoss) {
+ return { shouldStop: true, reason: 'Stop loss triggered' };
+ }
+
+ if (config.takeProfit && currentPrice >= config.takeProfit) {
+ return { shouldStop: true, reason: 'Take profit triggered' };
+ }
+
+ return { shouldStop: false };
+}
+
+/**
+ * Validate grid configuration
+ */
+export function validateGridConfig(config: Partial<GridConfig>): string[] {
+ const errors: string[] = [];
+
+ if (!config.symbol) {
+ errors.push('Symbol is required');
+ }
+
+ if (!config.upperPrice || config.upperPrice <= 0) {
+ errors.push('Upper price must be greater than 0');
+ }
+
+ if (!config.lowerPrice || config.lowerPrice <= 0) {
+ errors.push('Lower price must be greater than 0');
+ }
+
+ if (config.upperPrice && config.lowerPrice && config.upperPrice <= config.lowerPrice) {
+ errors.push('Upper price must be greater than lower price');
+ }
+
+ if (!config.gridLevels || config.gridLevels < 2) {
+ errors.push('Grid levels must be at least 2');
+ }
+
+ if (config.gridLevels && config.gridLevels > 200) {
+ errors.push('Grid levels cannot exceed 200');
+ }
+
+ if (!config.totalInvestment || config.totalInvestment <= 0) {
+ errors.push('Total investment must be greater than 0');
+ }
+
+ if (!config.brokerId) {
+ errors.push('Broker ID is required');
+ }
+
+ if (config.stopLoss && config.lowerPrice && config.stopLoss >= config.lowerPrice) {
+ errors.push('Stop loss must be below lower price');
+ }
+
+ if (config.takeProfit && config.upperPrice && config.takeProfit <= config.upperPrice) {
+ errors.push('Take profit must be above upper price');
+ }
+
+ return errors;
+}
+
+// ============================================================================
+// UTILITY FUNCTIONS
+// ============================================================================
+
+/**
+ * Get decimal places from a price
+ */
+function getDecimalPlaces(price: number): number {
+ const priceStr = price.toString();
+ const decimalIndex = priceStr.indexOf('.');
+ if (decimalIndex === -1) return 0;
+ return priceStr.length - decimalIndex - 1;
+}
+
+/**
+ * Round price to specified decimal places
+ */
+function roundPrice(price: number, decimals: number): number {
+ const factor = Math.pow(10, decimals);
+ return Math.round(price * factor) / factor;
+}
+
+/**
+ * Round quantity to specified decimal places
+ */
+function roundQuantity(quantity: number, decimals: number): number {
+ const factor = Math.pow(10, decimals);
+ return Math.round(quantity * factor) / factor;
+}
+
+/**
+ * Generate a unique grid ID
+ */
+export function generateGridId(): string {
+ return `grid_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
+}
+
+/**
+ * Calculate profit per grid (expected profit when one buy-sell cycle completes)
+ */
+export function calculateProfitPerGrid(config: GridConfig): number {
+ const { upperPrice, lowerPrice, gridLevels, gridType, quantityPerGrid } = config;
+
+ let avgSpread: number;
+ if (gridType === 'arithmetic') {
+ avgSpread = (upperPrice - lowerPrice) / (gridLevels - 1);
+ } else {
+ const ratio = Math.pow(upperPrice / lowerPrice, 1 / (gridLevels - 1));
+ const avgPrice = (upperPrice + lowerPrice) / 2;
+ avgSpread = avgPrice * (ratio - 1);
+ }
+
+ return avgSpread * quantityPerGrid;
+}
+
+/**
+ * Estimate annual return based on grid parameters and trade frequency
+ */
+export function estimateAnnualReturn(
+ config: GridConfig,
+ tradesPerDay: number
+): number {
+ const profitPerTrade = calculateProfitPerGrid(config);
+ const dailyProfit = profitPerTrade * tradesPerDay;
+ const annualProfit = dailyProfit * 365;
+ return (annualProfit / config.totalInvestment) * 100;
+}
diff --git a/fincept-terminal-desktop/src/services/gridTrading/GridTradingService.ts b/fincept-terminal-desktop/src/services/gridTrading/GridTradingService.ts
new file mode 100644
index 000000000..d2fb21f11
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/gridTrading/GridTradingService.ts
@@ -0,0 +1,780 @@
+/**
+ * Grid Trading Service
+ *
+ * Main service for managing grid trading bots.
+ * Works with both crypto and stock brokers through unified adapters.
+ */
+
+import type {
+ GridConfig,
+ GridState,
+ GridLevel,
+ IGridTradingService,
+ IGridBrokerAdapter,
+ GridEvent,
+} from './types';
+import {
+ createInitialGridState,
+ updateGridOnPriceChange,
+ updateGridLevelStatus,
+ updateGridOnFill,
+ getPendingLevels,
+ getOpenLevels,
+ checkGridStopConditions,
+ validateGridConfig,
+ generateGridId,
+ calculateGridDetails,
+} from './GridEngine';
+
+type GridEventCallback = (event: GridEvent) => void;
+
+export class GridTradingService implements IGridTradingService {
+ private grids: Map<string, GridState> = new Map();
+ private adapters: Map<string, IGridBrokerAdapter> = new Map();
+ private priceUnsubscribers: Map<string, () => void> = new Map();
+ private orderPollers: Map<string, NodeJS.Timeout> = new Map();
+ private eventCallbacks: Set<GridEventCallback> = new Set();
+
+ // Individual event callbacks
+ private gridUpdateCallbacks: Set<(grid: GridState) => void> = new Set();
+ private orderFilledCallbacks: Set<(gridId: string, level: GridLevel) => void> = new Set();
+ private gridErrorCallbacks: Set<(gridId: string, error: string) => void> = new Set();
+
+ // Configuration
+ private orderPollInterval = 10000; // 10 seconds
+
+ constructor() {
+ // Load persisted grids on startup
+ this.loadPersistedGrids();
+ }
+
+ // ============================================================================
+ // ADAPTER MANAGEMENT
+ // ============================================================================
+
+ /**
+ * Register a broker adapter for use with grids
+ */
+ registerAdapter(adapter: IGridBrokerAdapter): void {
+ this.adapters.set(adapter.brokerId, adapter);
+ console.log(`[GridTradingService] Registered adapter: ${adapter.brokerId}`);
+ }
+
+ /**
+ * Unregister a broker adapter
+ */
+ unregisterAdapter(brokerId: string): void {
+ this.adapters.delete(brokerId);
+ console.log(`[GridTradingService] Unregistered adapter: ${brokerId}`);
+ }
+
+ /**
+ * Get adapter for a broker
+ */
+ private getAdapter(brokerId: string): IGridBrokerAdapter {
+ const adapter = this.adapters.get(brokerId);
+ if (!adapter) {
+ throw new Error(`Adapter not found for broker: ${brokerId}`);
+ }
+ return adapter;
+ }
+
+ // ============================================================================
+ // GRID LIFECYCLE
+ // ============================================================================
+
+ /**
+ * Create a new grid trading bot
+ */
+ async createGrid(config: GridConfig): Promise<GridState> {
+ // Validate configuration
+ const errors = validateGridConfig(config);
+ if (errors.length > 0) {
+ throw new Error(`Invalid grid configuration: ${errors.join(', ')}`);
+ }
+
+ // Assign ID if not provided
+ if (!config.id) {
+ config.id = generateGridId();
+ }
+
+ // Get adapter and current price
+ const adapter = this.getAdapter(config.brokerId);
+ if (!adapter.isConnected) {
+ throw new Error(`Broker ${config.brokerId} is not connected`);
+ }
+
+ const currentPrice = await adapter.getCurrentPrice(config.symbol, config.exchange);
+
+ // Create initial state
+ const grid = createInitialGridState(config, currentPrice);
+
+ // Store grid
+ this.grids.set(grid.config.id, grid);
+
+ // Emit event
+ this.emitEvent({ type: 'grid_created', grid });
+
+ // Persist
+ await this.persistGrid(grid);
+
+ console.log(`[GridTradingService] Created grid: ${grid.config.id}`);
+ return grid;
+ }
+
+ /**
+ * Start a grid trading bot
+ */
+ async startGrid(gridId: string): Promise<void> {
+ const grid = this.getGrid(gridId);
+ if (!grid) {
+ throw new Error(`Grid not found: ${gridId}`);
+ }
+
+ if (grid.status === 'running') {
+ console.log(`[GridTradingService] Grid already running: ${gridId}`);
+ return;
+ }
+
+ // Check trigger price
+ if (grid.config.triggerPrice && grid.currentPrice !== grid.config.triggerPrice) {
+ // Wait for trigger price
+ console.log(`[GridTradingService] Grid waiting for trigger price: ${grid.config.triggerPrice}`);
+ }
+
+ // Update status
+ const updatedGrid: GridState = {
+ ...grid,
+ status: 'running',
+ startedAt: Date.now(),
+ lastUpdatedAt: Date.now(),
+ };
+ this.grids.set(gridId, updatedGrid);
+
+ // Subscribe to price updates
+ await this.subscribeToPriceUpdates(updatedGrid);
+
+ // Place initial orders
+ await this.placeInitialOrders(updatedGrid);
+
+ // Start order monitoring
+ this.startOrderMonitoring(gridId);
+
+ // Emit event
+ this.emitEvent({ type: 'grid_started', gridId });
+
+ // Persist
+ await this.persistGrid(updatedGrid);
+
+ console.log(`[GridTradingService] Started grid: ${gridId}`);
+ }
+
+ /**
+ * Pause a grid trading bot
+ */
+ async pauseGrid(gridId: string): Promise<void> {
+ const grid = this.getGrid(gridId);
+ if (!grid) {
+ throw new Error(`Grid not found: ${gridId}`);
+ }
+
+ if (grid.status !== 'running') {
+ throw new Error(`Grid is not running: ${gridId}`);
+ }
+
+ // Update status
+ const updatedGrid: GridState = {
+ ...grid,
+ status: 'paused',
+ lastUpdatedAt: Date.now(),
+ };
+ this.grids.set(gridId, updatedGrid);
+
+ // Stop price subscription and order monitoring
+ this.stopPriceSubscription(gridId);
+ this.stopOrderMonitoring(gridId);
+
+ // Emit event
+ this.emitEvent({ type: 'grid_paused', gridId });
+
+ // Persist
+ await this.persistGrid(updatedGrid);
+
+ console.log(`[GridTradingService] Paused grid: ${gridId}`);
+ }
+
+ /**
+ * Resume a paused grid
+ */
+ async resumeGrid(gridId: string): Promise<void> {
+ const grid = this.getGrid(gridId);
+ if (!grid) {
+ throw new Error(`Grid not found: ${gridId}`);
+ }
+
+ if (grid.status !== 'paused') {
+ throw new Error(`Grid is not paused: ${gridId}`);
+ }
+
+ await this.startGrid(gridId);
+ }
+
+ /**
+ * Stop a grid trading bot
+ */
+ async stopGrid(gridId: string): Promise<void> {
+ const grid = this.getGrid(gridId);
+ if (!grid) {
+ throw new Error(`Grid not found: ${gridId}`);
+ }
+
+ // Cancel all open orders
+ await this.cancelAllGridOrders(grid);
+
+ // Stop price subscription and order monitoring
+ this.stopPriceSubscription(gridId);
+ this.stopOrderMonitoring(gridId);
+
+ // Update status
+ const updatedGrid: GridState = {
+ ...grid,
+ status: 'stopped',
+ lastUpdatedAt: Date.now(),
+ };
+ this.grids.set(gridId, updatedGrid);
+
+ // Emit event
+ this.emitEvent({ type: 'grid_stopped', gridId });
+
+ // Persist
+ await this.persistGrid(updatedGrid);
+
+ console.log(`[GridTradingService] Stopped grid: ${gridId}`);
+ }
+
+ /**
+ * Delete a grid trading bot
+ */
+ async deleteGrid(gridId: string): Promise<void> {
+ const grid = this.getGrid(gridId);
+ if (!grid) {
+ throw new Error(`Grid not found: ${gridId}`);
+ }
+
+ // Stop if running
+ if (grid.status === 'running' || grid.status === 'paused') {
+ await this.stopGrid(gridId);
+ }
+
+ // Remove from storage
+ this.grids.delete(gridId);
+
+ // Remove persisted data
+ await this.deletePersistedGrid(gridId);
+
+ console.log(`[GridTradingService] Deleted grid: ${gridId}`);
+ }
+
+ // ============================================================================
+ // GRID MANAGEMENT
+ // ============================================================================
+
+ /**
+ * Get a grid by ID
+ */
+ getGrid(gridId: string): GridState | undefined {
+ return this.grids.get(gridId);
+ }
+
+ /**
+ * Get all grids
+ */
+ getAllGrids(): GridState[] {
+ return Array.from(this.grids.values());
+ }
+
+ /**
+ * Get active (running) grids
+ */
+ getActiveGrids(): GridState[] {
+ return this.getAllGrids().filter(g => g.status === 'running');
+ }
+
+ /**
+ * Get grids for a specific broker
+ */
+ getGridsForBroker(brokerId: string): GridState[] {
+ return this.getAllGrids().filter(g => g.config.brokerId === brokerId);
+ }
+
+ // ============================================================================
+ // REAL-TIME UPDATES
+ // ============================================================================
+
+ /**
+ * Update grid when price changes
+ */
+ async updateGridPrice(gridId: string, price: number): Promise<void> {
+ const grid = this.getGrid(gridId);
+ if (!grid || grid.status !== 'running') {
+ return;
+ }
+
+ // Update grid state
+ const updatedGrid = updateGridOnPriceChange(grid, price);
+ this.grids.set(gridId, updatedGrid);
+
+ // Check stop conditions
+ const stopCheck = checkGridStopConditions(updatedGrid);
+ if (stopCheck.shouldStop) {
+ console.log(`[GridTradingService] Stop condition triggered: ${stopCheck.reason}`);
+ await this.stopGrid(gridId);
+ return;
+ }
+
+ // Emit price update event
+ this.emitEvent({ type: 'price_update', gridId, price });
+
+ // Check if we need to place any new orders
+ await this.checkAndPlaceOrders(updatedGrid);
+ }
+
+ /**
+ * Process a filled order
+ */
+ async processFilledOrder(
+ gridId: string,
+ orderId: string,
+ filledQty: number,
+ filledPrice: number
+ ): Promise<void> {
+ const grid = this.getGrid(gridId);
+ if (!grid) {
+ return;
+ }
+
+ // Find the level with this order
+ const levelIndex = grid.levels.findIndex(l => l.orderId === orderId);
+ if (levelIndex === -1) {
+ console.warn(`[GridTradingService] Order not found in grid: ${orderId}`);
+ return;
+ }
+
+ // Update grid state
+ const updatedGrid = updateGridOnFill(grid, levelIndex, filledQty, filledPrice);
+ this.grids.set(gridId, updatedGrid);
+
+ // Emit events
+ this.emitEvent({ type: 'level_filled', gridId, level: updatedGrid.levels[levelIndex] });
+ this.emitEvent({ type: 'grid_updated', grid: updatedGrid });
+
+ // Notify callbacks
+ this.orderFilledCallbacks.forEach(cb => {
+ try {
+ cb(gridId, updatedGrid.levels[levelIndex]);
+ } catch (error) {
+ console.error('[GridTradingService] Order filled callback error:', error);
+ }
+ });
+
+ // Place the opposite order
+ if (updatedGrid.status === 'running') {
+ await this.placeOrderForLevel(updatedGrid, levelIndex);
+ }
+
+ // Persist
+ await this.persistGrid(updatedGrid);
+ }
+
+ // ============================================================================
+ // ORDER MANAGEMENT
+ // ============================================================================
+
+ /**
+ * Place initial orders for a grid
+ */
+ private async placeInitialOrders(grid: GridState): Promise<void> {
+ const pendingLevels = getPendingLevels(grid);
+
+ for (const level of pendingLevels) {
+ await this.placeOrderForLevel(grid, level.levelIndex);
+ }
+ }
+
+ /**
+ * Place order for a specific grid level
+ */
+ private async placeOrderForLevel(grid: GridState, levelIndex: number): Promise<void> {
+ const level = grid.levels[levelIndex];
+ if (level.status !== 'pending') {
+ return;
+ }
+
+ const adapter = this.getAdapter(grid.config.brokerId);
+
+ try {
+ const result = await adapter.placeGridOrder({
+ symbol: grid.config.symbol,
+ exchange: grid.config.exchange,
+ side: level.side,
+ quantity: level.quantity,
+ price: level.price,
+ type: 'limit',
+ productType: grid.config.productType,
+ tag: `grid_${grid.config.id}_${levelIndex}`,
+ });
+
+ if (result.success && result.orderId) {
+ // Update level status
+ const updatedGrid = updateGridLevelStatus(grid, levelIndex, 'open', result.orderId);
+ this.grids.set(grid.config.id, updatedGrid);
+
+ this.emitEvent({
+ type: 'level_placed',
+ gridId: grid.config.id,
+ level: updatedGrid.levels[levelIndex],
+ });
+
+ console.log(`[GridTradingService] Placed ${level.side} order at ${level.price}: ${result.orderId}`);
+ } else {
+ // Order failed
+ const updatedGrid = updateGridLevelStatus(grid, levelIndex, 'error');
+ updatedGrid.lastError = result.message;
+ updatedGrid.errorCount += 1;
+ this.grids.set(grid.config.id, updatedGrid);
+
+ this.emitGridError(grid.config.id, result.message || 'Order placement failed');
+ }
+ } catch (error) {
+ const errorMsg = error instanceof Error ? error.message : 'Unknown error';
+ const updatedGrid = updateGridLevelStatus(grid, levelIndex, 'error');
+ updatedGrid.lastError = errorMsg;
+ updatedGrid.errorCount += 1;
+ this.grids.set(grid.config.id, updatedGrid);
+
+ this.emitGridError(grid.config.id, errorMsg);
+ }
+ }
+
+ /**
+ * Check and place any necessary orders
+ */
+ private async checkAndPlaceOrders(grid: GridState): Promise<void> {
+ const pendingLevels = getPendingLevels(grid);
+
+ for (const level of pendingLevels) {
+ // Only place orders for levels that are near current price
+ const priceDistance = Math.abs(level.price - grid.currentPrice) / grid.currentPrice;
+ if (priceDistance < 0.1) { // Within 10% of current price
+ await this.placeOrderForLevel(grid, level.levelIndex);
+ }
+ }
+ }
+
+ /**
+ * Cancel all open orders for a grid
+ */
+ private async cancelAllGridOrders(grid: GridState): Promise<void> {
+ const openLevels = getOpenLevels(grid);
+ const adapter = this.getAdapter(grid.config.brokerId);
+
+ for (const level of openLevels) {
+ if (level.orderId) {
+ try {
+ await adapter.cancelGridOrder(level.orderId, grid.config.symbol);
+ const updatedGrid = updateGridLevelStatus(
+ this.grids.get(grid.config.id)!,
+ level.levelIndex,
+ 'cancelled'
+ );
+ this.grids.set(grid.config.id, updatedGrid);
+
+ this.emitEvent({
+ type: 'level_cancelled',
+ gridId: grid.config.id,
+ level: updatedGrid.levels[level.levelIndex],
+ });
+ } catch (error) {
+ console.error(`[GridTradingService] Failed to cancel order ${level.orderId}:`, error);
+ }
+ }
+ }
+ }
+
+ // ============================================================================
+ // PRICE SUBSCRIPTION
+ // ============================================================================
+
+ /**
+ * Subscribe to price updates for a grid
+ */
+ private async subscribeToPriceUpdates(grid: GridState): Promise<void> {
+ const adapter = this.getAdapter(grid.config.brokerId);
+
+ const unsubscribe = adapter.subscribeToPrice(
+ grid.config.symbol,
+ (price: number) => {
+ this.updateGridPrice(grid.config.id, price);
+ },
+ grid.config.exchange
+ );
+
+ this.priceUnsubscribers.set(grid.config.id, unsubscribe);
+ }
+
+ /**
+ * Stop price subscription for a grid
+ */
+ private stopPriceSubscription(gridId: string): void {
+ const unsubscribe = this.priceUnsubscribers.get(gridId);
+ if (unsubscribe) {
+ unsubscribe();
+ this.priceUnsubscribers.delete(gridId);
+ }
+ }
+
+ // ============================================================================
+ // ORDER MONITORING
+ // ============================================================================
+
+ /**
+ * Start monitoring orders for a grid
+ */
+ private startOrderMonitoring(gridId: string): void {
+ // Stop existing poller if any
+ this.stopOrderMonitoring(gridId);
+
+ // Start new poller
+ const interval = setInterval(async () => {
+ await this.pollOrderStatuses(gridId);
+ }, this.orderPollInterval);
+
+ this.orderPollers.set(gridId, interval);
+ }
+
+ /**
+ * Stop order monitoring for a grid
+ */
+ private stopOrderMonitoring(gridId: string): void {
+ const interval = this.orderPollers.get(gridId);
+ if (interval) {
+ clearInterval(interval);
+ this.orderPollers.delete(gridId);
+ }
+ }
+
+ /**
+ * Poll order statuses for a grid
+ */
+ private async pollOrderStatuses(gridId: string): Promise<void> {
+ const grid = this.getGrid(gridId);
+ if (!grid || grid.status !== 'running') {
+ return;
+ }
+
+ const adapter = this.getAdapter(grid.config.brokerId);
+ const openLevels = getOpenLevels(grid);
+
+ for (const level of openLevels) {
+ if (!level.orderId) continue;
+
+ try {
+ const status = await adapter.getOrderStatus(level.orderId, grid.config.symbol);
+
+ if (status.status === 'filled') {
+ await this.processFilledOrder(
+ gridId,
+ level.orderId,
+ status.filledQuantity,
+ status.averagePrice
+ );
+ } else if (status.status === 'cancelled' || status.status === 'rejected') {
+ const updatedGrid = updateGridLevelStatus(
+ this.grids.get(gridId)!,
+ level.levelIndex,
+ 'cancelled'
+ );
+ this.grids.set(gridId, updatedGrid);
+ }
+ } catch (error) {
+ // Ignore polling errors
+ }
+ }
+ }
+
+ // ============================================================================
+ // EVENTS
+ // ============================================================================
+
+ /**
+ * Subscribe to all grid events
+ */
+ onEvent(callback: GridEventCallback): () => void {
+ this.eventCallbacks.add(callback);
+ return () => this.eventCallbacks.delete(callback);
+ }
+
+ /**
+ * Subscribe to grid updates
+ */
+ onGridUpdate(callback: (grid: GridState) => void): () => void {
+ this.gridUpdateCallbacks.add(callback);
+ return () => this.gridUpdateCallbacks.delete(callback);
+ }
+
+ /**
+ * Subscribe to order filled events
+ */
+ onOrderFilled(callback: (gridId: string, level: GridLevel) => void): () => void {
+ this.orderFilledCallbacks.add(callback);
+ return () => this.orderFilledCallbacks.delete(callback);
+ }
+
+ /**
+ * Subscribe to grid errors
+ */
+ onGridError(callback: (gridId: string, error: string) => void): () => void {
+ this.gridErrorCallbacks.add(callback);
+ return () => this.gridErrorCallbacks.delete(callback);
+ }
+
+ /**
+ * Emit an event to all subscribers
+ */
+ private emitEvent(event: GridEvent): void {
+ this.eventCallbacks.forEach(cb => {
+ try {
+ cb(event);
+ } catch (error) {
+ console.error('[GridTradingService] Event callback error:', error);
+ }
+ });
+
+ // Also trigger specific callbacks
+ if (event.type === 'grid_updated') {
+ this.gridUpdateCallbacks.forEach(cb => {
+ try {
+ cb(event.grid);
+ } catch (error) {
+ console.error('[GridTradingService] Grid update callback error:', error);
+ }
+ });
+ }
+ }
+
+ /**
+ * Emit a grid error
+ */
+ private emitGridError(gridId: string, error: string): void {
+ this.emitEvent({ type: 'grid_error', gridId, error });
+
+ this.gridErrorCallbacks.forEach(cb => {
+ try {
+ cb(gridId, error);
+ } catch (err) {
+ console.error('[GridTradingService] Grid error callback error:', err);
+ }
+ });
+ }
+
+ // ============================================================================
+ // PERSISTENCE
+ // ============================================================================
+
+ /**
+ * Persist a grid to storage
+ */
+ private async persistGrid(grid: GridState): Promise<void> {
+ try {
+ const key = `grid_${grid.config.id}`;
+ localStorage.setItem(key, JSON.stringify(grid));
+ } catch (error) {
+ console.error('[GridTradingService] Failed to persist grid:', error);
+ }
+ }
+
+ /**
+ * Load persisted grids
+ */
+ private async loadPersistedGrids(): Promise<void> {
+ try {
+ for (let i = 0; i < localStorage.length; i++) {
+ const key = localStorage.key(i);
+ if (key?.startsWith('grid_')) {
+ const data = localStorage.getItem(key);
+ if (data) {
+ const grid: GridState = JSON.parse(data);
+ this.grids.set(grid.config.id, grid);
+
+ // Don't auto-start grids, just load them
+ if (grid.status === 'running') {
+ grid.status = 'paused'; // Pause on load, user can resume
+ }
+ }
+ }
+ }
+
+ console.log(`[GridTradingService] Loaded ${this.grids.size} persisted grids`);
+ } catch (error) {
+ console.error('[GridTradingService] Failed to load persisted grids:', error);
+ }
+ }
+
+ /**
+ * Delete persisted grid
+ */
+ private async deletePersistedGrid(gridId: string): Promise<void> {
+ try {
+ localStorage.removeItem(`grid_${gridId}`);
+ } catch (error) {
+ console.error('[GridTradingService] Failed to delete persisted grid:', error);
+ }
+ }
+
+ // ============================================================================
+ // CLEANUP
+ // ============================================================================
+
+ /**
+ * Dispose of all resources
+ */
+ dispose(): void {
+ // Stop all grids
+ for (const gridId of this.grids.keys()) {
+ this.stopPriceSubscription(gridId);
+ this.stopOrderMonitoring(gridId);
+ }
+
+ // Clear all callbacks
+ this.eventCallbacks.clear();
+ this.gridUpdateCallbacks.clear();
+ this.orderFilledCallbacks.clear();
+ this.gridErrorCallbacks.clear();
+ }
+}
+
+// ============================================================================
+// SINGLETON INSTANCE
+// ============================================================================
+
+let serviceInstance: GridTradingService | null = null;
+
+/**
+ * Get the singleton GridTradingService instance
+ */
+export function getGridTradingService(): GridTradingService {
+ if (!serviceInstance) {
+ serviceInstance = new GridTradingService();
+ }
+ return serviceInstance;
+}
+
+/**
+ * Reset the service (for testing)
+ */
+export function resetGridTradingService(): void {
+ if (serviceInstance) {
+ serviceInstance.dispose();
+ serviceInstance = null;
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/gridTrading/adapters/CryptoGridAdapter.ts b/fincept-terminal-desktop/src/services/gridTrading/adapters/CryptoGridAdapter.ts
new file mode 100644
index 000000000..2f3b0cb8b
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/gridTrading/adapters/CryptoGridAdapter.ts
@@ -0,0 +1,207 @@
+/**
+ * Crypto Grid Adapter
+ *
+ * Wraps IExchangeAdapter (crypto exchanges) for use with grid trading.
+ * Provides a unified interface for the GridTradingService.
+ */
+
+import type {
+ IGridBrokerAdapter,
+ GridOrderParams,
+ GridOrderResult,
+ GridOrderStatus,
+ BrokerType,
+} from '../types';
+import type { IExchangeAdapter, OrderType, OrderSide } from '../../../brokers/crypto/types';
+
+export class CryptoGridAdapter implements IGridBrokerAdapter {
+ private adapter: IExchangeAdapter;
+ private priceCallbacks: Map<string, Set<(price: number) => void>> = new Map();
+ private priceIntervals: Map<string, NodeJS.Timeout> = new Map();
+
+ public readonly brokerId: string;
+ public readonly brokerType: BrokerType = 'crypto';
+
+ constructor(adapter: IExchangeAdapter) {
+ this.adapter = adapter;
+ this.brokerId = adapter.id;
+ }
+
+ get isConnected(): boolean {
+ return this.adapter.isConnected();
+ }
+
+ /**
+ * Place a grid order
+ */
+ async placeGridOrder(params: GridOrderParams): Promise<GridOrderResult> {
+ try {
+ const order = await this.adapter.createOrder(
+ params.symbol,
+ 'limit' as OrderType,
+ params.side as OrderSide,
+ params.quantity,
+ params.price,
+ {
+ clientOrderId: params.tag,
+ }
+ );
+
+ return {
+ success: true,
+ orderId: order.id,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Failed to place order',
+ errorCode: 'ORDER_FAILED',
+ };
+ }
+ }
+
+ /**
+ * Cancel a grid order
+ */
+ async cancelGridOrder(orderId: string, symbol: string): Promise<boolean> {
+ try {
+ await this.adapter.cancelOrder(orderId, symbol);
+ return true;
+ } catch (error) {
+ console.error(`[CryptoGridAdapter] Failed to cancel order ${orderId}:`, error);
+ return false;
+ }
+ }
+
+ /**
+ * Get order status
+ */
+ async getOrderStatus(orderId: string, symbol: string): Promise<GridOrderStatus> {
+ try {
+ const order = await this.adapter.fetchOrder(orderId, symbol);
+
+ let status: GridOrderStatus['status'] = 'unknown';
+ if (order.status === 'open') status = 'open';
+ else if (order.status === 'closed') status = 'filled';
+ else if (order.status === 'canceled') status = 'cancelled';
+ else if (order.status === 'rejected') status = 'rejected';
+
+ const filled = order.filled || 0;
+ const remaining = order.remaining || (order.amount - filled);
+
+ if (order.status === 'open' && filled > 0) {
+ status = 'partial';
+ }
+
+ return {
+ orderId,
+ status,
+ filledQuantity: filled,
+ remainingQuantity: remaining,
+ averagePrice: order.average || order.price || 0,
+ };
+ } catch (error) {
+ return {
+ orderId,
+ status: 'unknown',
+ filledQuantity: 0,
+ remainingQuantity: 0,
+ averagePrice: 0,
+ };
+ }
+ }
+
+ /**
+ * Get current price for symbol
+ */
+ async getCurrentPrice(symbol: string): Promise<number> {
+ try {
+ const ticker = await this.adapter.fetchTicker(symbol);
+ return ticker.last || ticker.close || 0;
+ } catch (error) {
+ console.error(`[CryptoGridAdapter] Failed to get price for ${symbol}:`, error);
+ throw error;
+ }
+ }
+
+ /**
+ * Subscribe to price updates
+ */
+ subscribeToPrice(
+ symbol: string,
+ callback: (price: number) => void,
+ _exchange?: string
+ ): () => void {
+ // Add callback to set
+ if (!this.priceCallbacks.has(symbol)) {
+ this.priceCallbacks.set(symbol, new Set());
+ }
+ this.priceCallbacks.get(symbol)!.add(callback);
+
+ // Start polling if not already
+ if (!this.priceIntervals.has(symbol)) {
+ const interval = setInterval(async () => {
+ try {
+ const price = await this.getCurrentPrice(symbol);
+ const callbacks = this.priceCallbacks.get(symbol);
+ if (callbacks) {
+ callbacks.forEach(cb => cb(price));
+ }
+ } catch (error) {
+ // Ignore polling errors
+ }
+ }, 5000); // Poll every 5 seconds
+
+ this.priceIntervals.set(symbol, interval);
+ }
+
+ // Return unsubscribe function
+ return () => {
+ const callbacks = this.priceCallbacks.get(symbol);
+ if (callbacks) {
+ callbacks.delete(callback);
+ if (callbacks.size === 0) {
+ this.priceCallbacks.delete(symbol);
+ const interval = this.priceIntervals.get(symbol);
+ if (interval) {
+ clearInterval(interval);
+ this.priceIntervals.delete(symbol);
+ }
+ }
+ }
+ };
+ }
+
+ /**
+ * Get available balance
+ */
+ async getAvailableBalance(currency: string = 'USD'): Promise<number> {
+ try {
+ const balance = await this.adapter.fetchBalance();
+
+ // Try to find the currency in free balance
+ const free = balance.free as Record<string, number> | undefined;
+ const currencyBalance = free?.[currency] ||
+ free?.['USDT'] ||
+ free?.['USDC'] ||
+ 0;
+
+ return typeof currencyBalance === 'number' ? currencyBalance : 0;
+ } catch (error) {
+ console.error(`[CryptoGridAdapter] Failed to get balance:`, error);
+ return 0;
+ }
+ }
+
+ /**
+ * Clean up resources
+ */
+ dispose(): void {
+ // Clear all intervals
+ for (const interval of this.priceIntervals.values()) {
+ clearInterval(interval);
+ }
+ this.priceIntervals.clear();
+ this.priceCallbacks.clear();
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/gridTrading/adapters/StockGridAdapter.ts b/fincept-terminal-desktop/src/services/gridTrading/adapters/StockGridAdapter.ts
new file mode 100644
index 000000000..beec2b837
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/gridTrading/adapters/StockGridAdapter.ts
@@ -0,0 +1,243 @@
+/**
+ * Stock Grid Adapter
+ *
+ * Wraps IStockBrokerAdapter (stock brokers) for use with grid trading.
+ * Provides a unified interface for the GridTradingService.
+ */
+
+import type {
+ IGridBrokerAdapter,
+ GridOrderParams,
+ GridOrderResult,
+ GridOrderStatus,
+ BrokerType,
+} from '../types';
+import type {
+ IStockBrokerAdapter,
+ OrderType,
+ OrderSide,
+ ProductType,
+ StockExchange,
+} from '../../../brokers/stocks/types';
+
+export class StockGridAdapter implements IGridBrokerAdapter {
+ private adapter: IStockBrokerAdapter;
+ private priceCallbacks: Map<string, Set<(price: number) => void>> = new Map();
+ private tickUnsubscribers: Map<string, () => void> = new Map();
+
+ public readonly brokerId: string;
+ public readonly brokerType: BrokerType = 'stock';
+
+ constructor(adapter: IStockBrokerAdapter) {
+ this.adapter = adapter;
+ this.brokerId = adapter.brokerId;
+ }
+
+ get isConnected(): boolean {
+ return this.adapter.isConnected;
+ }
+
+ /**
+ * Place a grid order
+ */
+ async placeGridOrder(params: GridOrderParams): Promise<GridOrderResult> {
+ try {
+ const response = await this.adapter.placeOrder({
+ symbol: params.symbol,
+ exchange: (params.exchange || 'NSE') as StockExchange,
+ side: params.side.toUpperCase() as OrderSide,
+ quantity: params.quantity,
+ orderType: 'LIMIT' as OrderType,
+ productType: (params.productType || 'CASH') as ProductType,
+ price: params.price,
+ tag: params.tag,
+ });
+
+ return {
+ success: response.success,
+ orderId: response.orderId,
+ message: response.message,
+ errorCode: response.errorCode,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ message: error instanceof Error ? error.message : 'Failed to place order',
+ errorCode: 'ORDER_FAILED',
+ };
+ }
+ }
+
+ /**
+ * Cancel a grid order
+ */
+ async cancelGridOrder(orderId: string, _symbol: string): Promise<boolean> {
+ try {
+ const response = await this.adapter.cancelOrder(orderId);
+ return response.success;
+ } catch (error) {
+ console.error(`[StockGridAdapter] Failed to cancel order ${orderId}:`, error);
+ return false;
+ }
+ }
+
+ /**
+ * Get order status
+ */
+ async getOrderStatus(orderId: string, _symbol: string): Promise<GridOrderStatus> {
+ try {
+ const orders = await this.adapter.getOrders();
+ const order = orders.find(o => o.orderId === orderId);
+
+ if (!order) {
+ return {
+ orderId,
+ status: 'unknown',
+ filledQuantity: 0,
+ remainingQuantity: 0,
+ averagePrice: 0,
+ };
+ }
+
+ let status: GridOrderStatus['status'] = 'unknown';
+ switch (order.status) {
+ case 'OPEN':
+ case 'PENDING':
+ case 'TRIGGER_PENDING':
+ status = 'open';
+ break;
+ case 'FILLED':
+ status = 'filled';
+ break;
+ case 'PARTIALLY_FILLED':
+ status = 'partial';
+ break;
+ case 'CANCELLED':
+ case 'EXPIRED':
+ status = 'cancelled';
+ break;
+ case 'REJECTED':
+ status = 'rejected';
+ break;
+ }
+
+ return {
+ orderId,
+ status,
+ filledQuantity: order.filledQuantity,
+ remainingQuantity: order.pendingQuantity,
+ averagePrice: order.averagePrice,
+ };
+ } catch (error) {
+ return {
+ orderId,
+ status: 'unknown',
+ filledQuantity: 0,
+ remainingQuantity: 0,
+ averagePrice: 0,
+ };
+ }
+ }
+
+ /**
+ * Get current price for symbol
+ */
+ async getCurrentPrice(symbol: string, exchange: string = 'NSE'): Promise<number> {
+ try {
+ const quote = await this.adapter.getQuote(symbol, exchange as StockExchange);
+ return quote.lastPrice;
+ } catch (error) {
+ console.error(`[StockGridAdapter] Failed to get price for ${symbol}:`, error);
+ throw error;
+ }
+ }
+
+ /**
+ * Subscribe to price updates
+ */
+ subscribeToPrice(
+ symbol: string,
+ callback: (price: number) => void,
+ exchange: string = 'NSE'
+ ): () => void {
+ const key = `${exchange}:${symbol}`;
+
+ // Add callback to set
+ if (!this.priceCallbacks.has(key)) {
+ this.priceCallbacks.set(key, new Set());
+ }
+ this.priceCallbacks.get(key)!.add(callback);
+
+ // Set up WebSocket subscription if not already
+ if (!this.tickUnsubscribers.has(key)) {
+ // Create tick handler
+ const tickHandler = (tick: { symbol: string; exchange: string; lastPrice: number }) => {
+ if (tick.symbol === symbol && tick.exchange === exchange) {
+ const callbacks = this.priceCallbacks.get(key);
+ if (callbacks) {
+ callbacks.forEach(cb => cb(tick.lastPrice));
+ }
+ }
+ };
+
+ // Subscribe to ticks
+ this.adapter.onTick(tickHandler);
+
+ // Subscribe to symbol
+ this.adapter.subscribe(symbol, exchange as StockExchange, 'ltp')
+ .catch(err => console.error(`[StockGridAdapter] Subscribe error:`, err));
+
+ // Store unsubscriber
+ this.tickUnsubscribers.set(key, () => {
+ this.adapter.offTick(tickHandler);
+ this.adapter.unsubscribe(symbol, exchange as StockExchange)
+ .catch(err => console.error(`[StockGridAdapter] Unsubscribe error:`, err));
+ });
+ }
+
+ // Return unsubscribe function
+ return () => {
+ const callbacks = this.priceCallbacks.get(key);
+ if (callbacks) {
+ callbacks.delete(callback);
+ if (callbacks.size === 0) {
+ this.priceCallbacks.delete(key);
+ const unsubscribe = this.tickUnsubscribers.get(key);
+ if (unsubscribe) {
+ unsubscribe();
+ this.tickUnsubscribers.delete(key);
+ }
+ }
+ }
+ };
+ }
+
+ /**
+ * Get available balance
+ */
+ async getAvailableBalance(_currency?: string): Promise<number> {
+ try {
+ const funds = await this.adapter.getFunds();
+ return funds.availableCash;
+ } catch (error) {
+ console.error(`[StockGridAdapter] Failed to get balance:`, error);
+ return 0;
+ }
+ }
+
+ /**
+ * Clean up resources
+ */
+ dispose(): void {
+ // Unsubscribe from all
+ for (const unsubscribe of this.tickUnsubscribers.values()) {
+ try {
+ unsubscribe();
+ } catch (error) {
+ // Ignore cleanup errors
+ }
+ }
+ this.tickUnsubscribers.clear();
+ this.priceCallbacks.clear();
+ }
+}
diff --git a/fincept-terminal-desktop/src/services/gridTrading/adapters/index.ts b/fincept-terminal-desktop/src/services/gridTrading/adapters/index.ts
new file mode 100644
index 000000000..6f2622970
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/gridTrading/adapters/index.ts
@@ -0,0 +1,8 @@
+/**
+ * Grid Trading Adapters
+ *
+ * Export all broker adapters for grid trading
+ */
+
+export { CryptoGridAdapter } from './CryptoGridAdapter';
+export { StockGridAdapter } from './StockGridAdapter';
diff --git a/fincept-terminal-desktop/src/services/gridTrading/index.ts b/fincept-terminal-desktop/src/services/gridTrading/index.ts
new file mode 100644
index 000000000..b32d8ca57
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/gridTrading/index.ts
@@ -0,0 +1,87 @@
+/**
+ * Grid Trading Module
+ *
+ * Unified grid trading system that works with both crypto and stock brokers.
+ *
+ * Usage:
+ * ```typescript
+ * import { getGridTradingService, CryptoGridAdapter, StockGridAdapter } from '@/services/gridTrading';
+ *
+ * // Get service instance
+ * const service = getGridTradingService();
+ *
+ * // Register crypto adapter
+ * const cryptoAdapter = new CryptoGridAdapter(krakenExchangeAdapter);
+ * service.registerAdapter(cryptoAdapter);
+ *
+ * // Register stock adapter
+ * const stockAdapter = new StockGridAdapter(zerodhaAdapter);
+ * service.registerAdapter(stockAdapter);
+ *
+ * // Create and start a grid
+ * const grid = await service.createGrid({
+ * id: 'my-grid',
+ * symbol: 'BTC/USD',
+ * upperPrice: 50000,
+ * lowerPrice: 40000,
+ * gridLevels: 10,
+ * gridType: 'arithmetic',
+ * totalInvestment: 1000,
+ * quantityPerGrid: 0.01,
+ * direction: 'neutral',
+ * brokerType: 'crypto',
+ * brokerId: 'kraken',
+ * });
+ *
+ * await service.startGrid(grid.config.id);
+ * ```
+ */
+
+// Types
+export type {
+ GridType,
+ GridDirection,
+ GridStatus,
+ GridConfig,
+ GridLevel,
+ GridLevelStatus,
+ GridState,
+ IGridTradingService,
+ IGridBrokerAdapter,
+ GridOrderParams,
+ GridOrderResult,
+ GridOrderStatus,
+ GridCalculation,
+ GridEvent,
+ GridPersistence,
+ BrokerType,
+} from './types';
+
+// Engine functions
+export {
+ calculateGridLevels,
+ calculateGridDetails,
+ initializeGridLevels,
+ createInitialGridState,
+ updateGridOnPriceChange,
+ updateGridLevelStatus,
+ updateGridOnFill,
+ getPendingLevels,
+ getOpenLevels,
+ checkGridStopConditions,
+ validateGridConfig,
+ generateGridId,
+ calculateProfitPerGrid,
+ estimateAnnualReturn,
+} from './GridEngine';
+
+// Service
+export {
+ GridTradingService,
+ getGridTradingService,
+ resetGridTradingService,
+} from './GridTradingService';
+
+// Adapters
+export { CryptoGridAdapter } from './adapters/CryptoGridAdapter';
+export { StockGridAdapter } from './adapters/StockGridAdapter';
diff --git a/fincept-terminal-desktop/src/services/gridTrading/types.ts b/fincept-terminal-desktop/src/services/gridTrading/types.ts
new file mode 100644
index 000000000..a5b614b22
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/gridTrading/types.ts
@@ -0,0 +1,239 @@
+/**
+ * Grid Trading Types
+ *
+ * Unified types for grid trading that work with both:
+ * - Crypto exchanges (via IExchangeAdapter)
+ * - Stock brokers (via IStockBrokerAdapter)
+ */
+
+// ============================================================================
+// GRID CONFIGURATION TYPES
+// ============================================================================
+
+export type GridType =
+ | 'arithmetic' // Equal price gaps between levels
+ | 'geometric'; // Equal percentage gaps between levels
+
+export type GridDirection = 'long' | 'short' | 'neutral';
+
+export type GridStatus =
+ | 'draft' // Not started, being configured
+ | 'running' // Active and placing orders
+ | 'paused' // Temporarily stopped
+ | 'stopped' // Manually stopped
+ | 'completed' // All grid levels filled/closed
+ | 'error'; // Error state
+
+export type BrokerType = 'crypto' | 'stock';
+
+// ============================================================================
+// GRID CONFIGURATION
+// ============================================================================
+
+export interface GridConfig {
+ // Core grid parameters
+ id: string; // Unique grid ID
+ symbol: string; // Trading pair/symbol
+ exchange?: string; // Exchange for stocks (NSE, BSE, etc.)
+
+ // Price range
+ upperPrice: number; // Upper bound of grid
+ lowerPrice: number; // Lower bound of grid
+ gridLevels: number; // Number of grid lines
+ gridType: GridType; // Arithmetic or geometric
+
+ // Investment
+ totalInvestment: number; // Total amount to invest
+ quantityPerGrid: number; // Quantity per grid level
+
+ // Direction and limits
+ direction: GridDirection; // Long/Short/Neutral bias
+ stopLoss?: number; // Stop loss price
+ takeProfit?: number; // Take profit price
+
+ // Broker configuration
+ brokerType: BrokerType; // crypto or stock
+ brokerId: string; // Specific broker ID
+ productType?: string; // For stocks: CASH, INTRADAY, MARGIN
+
+ // Advanced options
+ triggerPrice?: number; // Price to start the grid
+ trailingUp?: boolean; // Trail upper bound up
+ trailingDown?: boolean; // Trail lower bound down
+ rebalanceOnTrend?: boolean; // Rebalance when price breaks range
+}
+
+// ============================================================================
+// GRID LEVEL & STATE
+// ============================================================================
+
+export interface GridLevel {
+ levelIndex: number; // 0-based level index
+ price: number; // Price at this level
+ side: 'buy' | 'sell'; // Order side
+ quantity: number; // Order quantity
+ status: GridLevelStatus; // Current status
+ orderId?: string; // Exchange order ID if placed
+ filledQuantity?: number; // Filled quantity
+ filledPrice?: number; // Average fill price
+ pnl?: number; // P&L for this level
+ createdAt?: number; // Timestamp when order was placed
+ filledAt?: number; // Timestamp when order was filled
+}
+
+export type GridLevelStatus =
+ | 'pending' // Waiting to be placed
+ | 'open' // Order placed, waiting to fill
+ | 'filled' // Order filled
+ | 'cancelled' // Order cancelled
+ | 'error'; // Error placing/monitoring order
+
+// ============================================================================
+// GRID STATE
+// ============================================================================
+
+export interface GridState {
+ config: GridConfig; // Grid configuration
+ levels: GridLevel[]; // All grid levels
+ status: GridStatus; // Current grid status
+ currentPrice: number; // Current market price
+
+ // Statistics
+ totalBuys: number; // Total buy orders filled
+ totalSells: number; // Total sell orders filled
+ realizedPnl: number; // Realized profit/loss
+ unrealizedPnl: number; // Unrealized profit/loss
+ totalPnl: number; // Total P&L
+ gridProfit: number; // Profit from grid trades
+
+ // Position
+ currentPosition: number; // Current net position
+ averageEntryPrice: number; // Average entry price
+
+ // Timestamps
+ createdAt: number; // Grid creation time
+ startedAt?: number; // Grid start time
+ lastUpdatedAt: number; // Last update time
+
+ // Error tracking
+ lastError?: string; // Last error message
+ errorCount: number; // Total error count
+}
+
+// ============================================================================
+// GRID TRADING SERVICE INTERFACE
+// ============================================================================
+
+export interface IGridTradingService {
+ // Grid lifecycle
+ createGrid(config: GridConfig): Promise<GridState>;
+ startGrid(gridId: string): Promise<void>;
+ pauseGrid(gridId: string): Promise<void>;
+ resumeGrid(gridId: string): Promise<void>;
+ stopGrid(gridId: string): Promise<void>;
+ deleteGrid(gridId: string): Promise<void>;
+
+ // Grid management
+ getGrid(gridId: string): GridState | undefined;
+ getAllGrids(): GridState[];
+ getActiveGrids(): GridState[];
+
+ // Real-time updates
+ updateGridPrice(gridId: string, price: number): Promise<void>;
+ processFilledOrder(gridId: string, orderId: string, filledQty: number, filledPrice: number): Promise<void>;
+
+ // Events
+ onGridUpdate(callback: (grid: GridState) => void): () => void;
+ onOrderFilled(callback: (gridId: string, level: GridLevel) => void): () => void;
+ onGridError(callback: (gridId: string, error: string) => void): () => void;
+}
+
+// ============================================================================
+// BROKER ADAPTER INTERFACE (abstraction for both crypto and stock)
+// ============================================================================
+
+export interface IGridBrokerAdapter {
+ // Identification
+ brokerId: string;
+ brokerType: BrokerType;
+ isConnected: boolean;
+
+ // Order operations
+ placeGridOrder(params: GridOrderParams): Promise<GridOrderResult>;
+ cancelGridOrder(orderId: string, symbol: string): Promise<boolean>;
+ getOrderStatus(orderId: string, symbol: string): Promise<GridOrderStatus>;
+
+ // Market data
+ getCurrentPrice(symbol: string, exchange?: string): Promise<number>;
+ subscribeToPrice(symbol: string, callback: (price: number) => void, exchange?: string): () => void;
+
+ // Account
+ getAvailableBalance(currency?: string): Promise<number>;
+}
+
+export interface GridOrderParams {
+ symbol: string;
+ exchange?: string; // For stocks
+ side: 'buy' | 'sell';
+ quantity: number;
+ price: number;
+ type: 'limit';
+ productType?: string; // For stocks: CASH, INTRADAY, etc.
+ tag?: string; // Order tag for identification
+}
+
+export interface GridOrderResult {
+ success: boolean;
+ orderId?: string;
+ message?: string;
+ errorCode?: string;
+}
+
+export interface GridOrderStatus {
+ orderId: string;
+ status: 'open' | 'filled' | 'partial' | 'cancelled' | 'rejected' | 'unknown';
+ filledQuantity: number;
+ remainingQuantity: number;
+ averagePrice: number;
+}
+
+// ============================================================================
+// GRID CALCULATION HELPERS
+// ============================================================================
+
+export interface GridCalculation {
+ levels: number[]; // Price levels
+ gridSpacing: number; // Spacing between levels (absolute or %)
+ quantityPerLevel: number; // Quantity per grid level
+ totalQuantity: number; // Total quantity across all levels
+ totalInvestment: number; // Total investment required
+ breakEvenPrice: number; // Break-even price
+ potentialProfit: number; // Potential profit if all grids execute
+}
+
+// ============================================================================
+// EVENTS
+// ============================================================================
+
+export type GridEvent =
+ | { type: 'grid_created'; grid: GridState }
+ | { type: 'grid_started'; gridId: string }
+ | { type: 'grid_paused'; gridId: string }
+ | { type: 'grid_stopped'; gridId: string }
+ | { type: 'grid_updated'; grid: GridState }
+ | { type: 'level_placed'; gridId: string; level: GridLevel }
+ | { type: 'level_filled'; gridId: string; level: GridLevel }
+ | { type: 'level_cancelled'; gridId: string; level: GridLevel }
+ | { type: 'grid_error'; gridId: string; error: string }
+ | { type: 'price_update'; gridId: string; price: number };
+
+// ============================================================================
+// PERSISTENCE
+// ============================================================================
+
+export interface GridPersistence {
+ saveGrid(grid: GridState): Promise<void>;
+ loadGrid(gridId: string): Promise<GridState | null>;
+ loadAllGrids(): Promise<GridState[]>;
+ deleteGrid(gridId: string): Promise<void>;
+}
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts b/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts
index bdc9940ad..903917b4d 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/NodeLoader.ts
@@ -35,8 +35,47 @@ import {
// Import market data nodes
import {
YFinanceNode,
+ GetQuoteNode,
+ GetHistoricalDataNode,
+ GetMarketDepthNode,
+ StreamQuotesNode,
+ GetFundamentalsNode,
+ GetTickerStatsNode,
} from './nodes/marketData';
+// Import trading nodes
+import {
+ PlaceOrderNode,
+ ModifyOrderNode,
+ CancelOrderNode,
+ GetPositionsNode,
+ GetHoldingsNode,
+ GetOrdersNode,
+ GetBalanceNode,
+ ClosePositionNode,
+} from './nodes/trading';
+
+// Import trigger nodes
+import {
+ ManualTriggerNode,
+ ScheduleTriggerNode,
+ PriceAlertTriggerNode,
+ NewsEventTriggerNode,
+ MarketEventTriggerNode,
+ WebhookTriggerNode,
+} from './nodes/triggers';
+
+// Import agent nodes
+import { AgentMediatorNode } from './nodes/agents/AgentMediatorNode';
+import { AgentNode } from './nodes/agents/AgentNode';
+import { MultiAgentNode } from './nodes/agents/MultiAgentNode';
+import { GeopoliticsAgentNode } from './nodes/agents/GeopoliticsAgentNode';
+import { HedgeFundAgentNode } from './nodes/agents/HedgeFundAgentNode';
+import { InvestorAgentNode } from './nodes/agents/InvestorAgentNode';
+
+// Import agent node generator for dynamic Python agent nodes
+import { generateAllAgentNodes, getAgentNodeStatistics } from './utils/AgentNodeGenerator';
+
// Import control flow nodes
import {
IfElseNode,
@@ -97,12 +136,9 @@ class NodeLoaderClass {
*/
async loadAll(): Promise<void> {
if (this.loaded) {
- console.log('[NodeLoader] Nodes already loaded, skipping...');
return;
}
- console.log('[NodeLoader] Starting node loading...');
-
// Load core nodes
await this.loadCoreNodes();
@@ -127,27 +163,22 @@ class NodeLoaderClass {
// Load transform nodes
await this.loadTransformNodes();
- // TODO: Load AI agent nodes when ready
- // await this.loadAIAgentNodes();
+ // Load trading nodes
+ await this.loadTradingNodes();
- this.loaded = true;
+ // Load trigger nodes
+ await this.loadTriggerNodes();
- // Print statistics
- const stats = NodeRegistry.getStatistics();
- console.log('[NodeLoader] Loading complete!');
- console.log(` - Total node types: ${stats.totalNodeTypes}`);
- console.log(` - Total versions: ${stats.totalVersions}`);
- console.log(' - Node types:');
- stats.nodeTypes.forEach((nt) => {
- console.log(` • ${nt.name} (${nt.versions} version${nt.versions > 1 ? 's' : ''})`);
- });
+ // Load AI agent nodes
+ await this.loadAgentNodes();
+
+ this.loaded = true;
}
/**
* Load core nodes (basic workflow nodes)
*/
private async loadCoreNodes(): Promise<void> {
- console.log('[NodeLoader] Loading core nodes...');
try {
// Filter Node - Remove items based on conditions
@@ -174,8 +205,6 @@ class NodeLoaderClass {
const codeNode = new CoreCodeNode();
NodeRegistry.registerNodeType(codeNode, 'CoreCodeNode');
this.loadedNodes.set('coreCode', codeNode);
-
- console.log('[NodeLoader] Core nodes loaded (5 nodes)');
} catch (error) {
console.error('[NodeLoader] Error loading core nodes:', error);
}
@@ -185,7 +214,6 @@ class NodeLoaderClass {
* Load finance-specific nodes
*/
private async loadFinanceNodes(): Promise<void> {
- console.log('[NodeLoader] Loading finance nodes...');
try {
// Stock Data Node
@@ -202,8 +230,6 @@ class NodeLoaderClass {
// - FundamentalAnalysis Node
// - SentimentAnalysis Node
// - EconomicData Node
-
- console.log('[NodeLoader] Finance nodes loaded (1 node)');
} catch (error) {
console.error('[NodeLoader] Error loading finance nodes:', error);
}
@@ -214,16 +240,10 @@ class NodeLoaderClass {
* TODO: Implement agent node generator
*/
private async loadAIAgentNodes(): Promise<void> {
- console.log('[NodeLoader] AI agent nodes not yet implemented, skipping...');
-
// TODO: Uncomment when agent generator is ready
/*
try {
const stats = await getAgentNodeStatistics();
- console.log(`[NodeLoader] Found ${stats.totalAgents} Python agents across ${stats.categories} categories:`);
- for (const [category, count] of Object.entries(stats.byCategory)) {
- console.log(` - ${category}: ${count} agents`);
- }
const agentNodes = await generateAllAgentNodes();
@@ -249,7 +269,6 @@ class NodeLoaderClass {
* Load analytics nodes (Phase 6)
*/
private async loadAnalyticsNodes(): Promise<void> {
- console.log('[NodeLoader] Loading analytics nodes...');
try {
const nodes = [
@@ -262,12 +281,10 @@ class NodeLoaderClass {
{ instance: new CorrelationMatrixNode(), name: 'CorrelationMatrixNode' },
];
- for (const { instance, name } of nodes) {
+ for (const { instance, name} of nodes) {
NodeRegistry.registerNodeType(instance, name);
this.loadedNodes.set(instance.description.name, instance);
}
-
- console.log(`[NodeLoader] Analytics nodes loaded (${nodes.length} nodes)`);
} catch (error) {
console.error('[NodeLoader] Error loading analytics nodes:', error);
}
@@ -277,19 +294,22 @@ class NodeLoaderClass {
* Load market data nodes
*/
private async loadMarketDataNodes(): Promise<void> {
- console.log('[NodeLoader] Loading market data nodes...');
try {
const nodes = [
{ instance: new YFinanceNode(), name: 'YFinanceNode' },
+ { instance: new GetQuoteNode(), name: 'GetQuoteNode' },
+ { instance: new GetHistoricalDataNode(), name: 'GetHistoricalDataNode' },
+ { instance: new GetMarketDepthNode(), name: 'GetMarketDepthNode' },
+ { instance: new StreamQuotesNode(), name: 'StreamQuotesNode' },
+ { instance: new GetFundamentalsNode(), name: 'GetFundamentalsNode' },
+ { instance: new GetTickerStatsNode(), name: 'GetTickerStatsNode' },
];
for (const { instance, name } of nodes) {
NodeRegistry.registerNodeType(instance, name);
this.loadedNodes.set(instance.description.name, instance);
}
-
- console.log(`[NodeLoader] Market data nodes loaded (${nodes.length} nodes)`);
} catch (error) {
console.error('[NodeLoader] Error loading market data nodes:', error);
}
@@ -299,7 +319,6 @@ class NodeLoaderClass {
* Load control flow nodes (Phase 7)
*/
private async loadControlFlowNodes(): Promise<void> {
- console.log('[NodeLoader] Loading control flow nodes...');
try {
const nodes = [
@@ -320,8 +339,6 @@ class NodeLoaderClass {
NodeRegistry.registerNodeType(instance, name);
this.loadedNodes.set(instance.description.name, instance);
}
-
- console.log(`[NodeLoader] Control flow nodes loaded (${nodes.length} nodes)`);
} catch (error) {
console.error('[NodeLoader] Error loading control flow nodes:', error);
}
@@ -331,7 +348,6 @@ class NodeLoaderClass {
* Load safety nodes (Phase 8)
*/
private async loadSafetyNodes(): Promise<void> {
- console.log('[NodeLoader] Loading safety nodes...');
try {
const nodes = [
@@ -345,8 +361,6 @@ class NodeLoaderClass {
NodeRegistry.registerNodeType(instance, name);
this.loadedNodes.set(instance.description.name, instance);
}
-
- console.log(`[NodeLoader] Safety nodes loaded (${nodes.length} nodes)`);
} catch (error) {
console.error('[NodeLoader] Error loading safety nodes:', error);
}
@@ -356,7 +370,6 @@ class NodeLoaderClass {
* Load notification nodes (Phase 9)
*/
private async loadNotificationNodes(): Promise<void> {
- console.log('[NodeLoader] Loading notification nodes...');
try {
const nodes = [
@@ -372,8 +385,6 @@ class NodeLoaderClass {
NodeRegistry.registerNodeType(instance, name);
this.loadedNodes.set(instance.description.name, instance);
}
-
- console.log(`[NodeLoader] Notification nodes loaded (${nodes.length} nodes)`);
} catch (error) {
console.error('[NodeLoader] Error loading notification nodes:', error);
}
@@ -383,7 +394,6 @@ class NodeLoaderClass {
* Load transform nodes (Phase 10)
*/
private async loadTransformNodes(): Promise<void> {
- console.log('[NodeLoader] Loading transform nodes...');
try {
const nodes = [
@@ -401,13 +411,118 @@ class NodeLoaderClass {
NodeRegistry.registerNodeType(instance, name);
this.loadedNodes.set(instance.description.name, instance);
}
-
- console.log(`[NodeLoader] Transform nodes loaded (${nodes.length} nodes)`);
} catch (error) {
console.error('[NodeLoader] Error loading transform nodes:', error);
}
}
+ /**
+ * Load trading nodes
+ */
+ private async loadTradingNodes(): Promise<void> {
+
+ try {
+ const nodes = [
+ { instance: new PlaceOrderNode(), name: 'PlaceOrderNode' },
+ { instance: new ModifyOrderNode(), name: 'ModifyOrderNode' },
+ { instance: new CancelOrderNode(), name: 'CancelOrderNode' },
+ { instance: new GetPositionsNode(), name: 'GetPositionsNode' },
+ { instance: new GetHoldingsNode(), name: 'GetHoldingsNode' },
+ { instance: new GetOrdersNode(), name: 'GetOrdersNode' },
+ { instance: new GetBalanceNode(), name: 'GetBalanceNode' },
+ { instance: new ClosePositionNode(), name: 'ClosePositionNode' },
+ ];
+
+ for (const { instance, name } of nodes) {
+ NodeRegistry.registerNodeType(instance, name);
+ this.loadedNodes.set(instance.description.name, instance);
+ }
+ } catch (error) {
+ console.error('[NodeLoader] Error loading trading nodes:', error);
+ }
+ }
+
+ /**
+ * Load trigger nodes
+ */
+ private async loadTriggerNodes(): Promise<void> {
+
+ try {
+ const nodes = [
+ { instance: new ManualTriggerNode(), name: 'ManualTriggerNode' },
+ { instance: new ScheduleTriggerNode(), name: 'ScheduleTriggerNode' },
+ { instance: new PriceAlertTriggerNode(), name: 'PriceAlertTriggerNode' },
+ { instance: new NewsEventTriggerNode(), name: 'NewsEventTriggerNode' },
+ { instance: new MarketEventTriggerNode(), name: 'MarketEventTriggerNode' },
+ { instance: new WebhookTriggerNode(), name: 'WebhookTriggerNode' },
+ ];
+
+ for (const { instance, name } of nodes) {
+ NodeRegistry.registerNodeType(instance, name);
+ this.loadedNodes.set(instance.description.name, instance);
+ }
+ } catch (error) {
+ console.error('[NodeLoader] Error loading trigger nodes:', error);
+ }
+ }
+
+ /**
+ * Load AI agent nodes (static + dynamic from Python agents)
+ */
+ private async loadAgentNodes(): Promise<void> {
+
+ let staticCount = 0;
+ let dynamicCount = 0;
+
+ // Load static agent nodes (TypeScript-defined)
+ try {
+ const staticNodes = [
+ { instance: new AgentMediatorNode(), name: 'AgentMediatorNode' },
+ { instance: new AgentNode(), name: 'AgentNode' },
+ { instance: new MultiAgentNode(), name: 'MultiAgentNode' },
+ { instance: new GeopoliticsAgentNode(), name: 'GeopoliticsAgentNode' },
+ { instance: new HedgeFundAgentNode(), name: 'HedgeFundAgentNode' },
+ { instance: new InvestorAgentNode(), name: 'InvestorAgentNode' },
+ ];
+
+ for (const { instance, name } of staticNodes) {
+ NodeRegistry.registerNodeType(instance, name);
+ this.loadedNodes.set(instance.description.name, instance);
+ staticCount++;
+ }
+ } catch (error) {
+ console.error('[NodeLoader] Error loading static agent nodes:', error);
+ }
+
+ // Load dynamic agent nodes (generated from Python agent metadata)
+ try {
+ // Get statistics first
+ const stats = await getAgentNodeStatistics();
+
+ if (stats.totalAgents > 0) {
+
+ // Generate and register dynamic agent nodes
+ const dynamicAgentNodes = await generateAllAgentNodes();
+
+ for (const [agentId, nodeType] of dynamicAgentNodes.entries()) {
+ try {
+ // Avoid duplicates - check if already registered
+ if (!this.loadedNodes.has(agentId)) {
+ NodeRegistry.registerNodeType(nodeType, `${agentId}AgentNode`);
+ this.loadedNodes.set(agentId, nodeType);
+ dynamicCount++;
+ }
+ } catch (regError) {
+ console.warn(`[NodeLoader] Failed to register dynamic agent node: ${agentId}`, regError);
+ }
+ }
+ }
+ } catch (error) {
+ // Dynamic agent loading is optional - don't fail the entire loading
+ console.warn('[NodeLoader] Dynamic agent node generation skipped:', error);
+ }
+ }
+
/**
* Get loaded node instance
*/
@@ -426,7 +541,6 @@ class NodeLoaderClass {
* Reload all nodes (for development)
*/
async reload(): Promise<void> {
- console.log('[NodeLoader] Reloading all nodes...');
this.loaded = false;
this.loadedNodes.clear();
NodeRegistry.clear();
@@ -449,11 +563,8 @@ export const NodeLoader = new NodeLoaderClass();
* Call this once during app startup
*/
export async function initializeNodeSystem(): Promise<void> {
- console.log('[NodeSystem] Initializing...');
-
try {
await NodeLoader.loadAll();
- console.log('[NodeSystem] Initialization complete!');
} catch (error) {
console.error('[NodeSystem] Initialization failed:', error);
throw error;
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/NodeRegistry.ts b/fincept-terminal-desktop/src/services/nodeSystem/NodeRegistry.ts
index 11439b49c..03bf36181 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/NodeRegistry.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/NodeRegistry.ts
@@ -60,10 +60,6 @@ class NodeRegistryClass {
}
this.loadedNodeTypes.add(nodeTypeName);
-
- console.log(
- `[NodeRegistry] Registered ${nodeTypeName} versions: ${versions.join(', ')}`
- );
}
/**
@@ -86,10 +82,6 @@ class NodeRegistryClass {
}
this.loadedNodeTypes.add(nodeTypeName);
-
- console.log(
- `[NodeRegistry] Registered versioned node ${nodeTypeName} versions: ${versions.join(', ')}`
- );
}
/**
@@ -203,7 +195,6 @@ class NodeRegistryClass {
unregisterNodeType(nodeTypeName: string): void {
delete this.registry[nodeTypeName];
this.loadedNodeTypes.delete(nodeTypeName);
- console.log(`[NodeRegistry] Unregistered ${nodeTypeName}`);
}
/**
@@ -212,7 +203,6 @@ class NodeRegistryClass {
clear(): void {
this.registry = {};
this.loadedNodeTypes.clear();
- console.log('[NodeRegistry] Cleared all node types');
}
/**
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/index.ts b/fincept-terminal-desktop/src/services/nodeSystem/index.ts
index 3621f8271..300753413 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/index.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/index.ts
@@ -81,6 +81,14 @@ export {
// Workflow Cache (caching and memoization)
export { WorkflowCache, globalWorkflowCache, hashData, memoize } from './WorkflowCache';
+// Agent Node Generator (dynamic Python agent node creation)
+export {
+ generateAgentNode,
+ generateAllAgentNodes,
+ generateAgentNodesByCategory,
+ getAgentNodeStatistics,
+} from './utils/AgentNodeGenerator';
+
// Re-export commonly used types with simpler names
export type {
INodeType as NodeType,
diff --git a/fincept-terminal-desktop/src/services/nodeSystem/utils/AgentNodeGenerator.ts b/fincept-terminal-desktop/src/services/nodeSystem/utils/AgentNodeGenerator.ts
index 44f3588c9..66165dfcb 100644
--- a/fincept-terminal-desktop/src/services/nodeSystem/utils/AgentNodeGenerator.ts
+++ b/fincept-terminal-desktop/src/services/nodeSystem/utils/AgentNodeGenerator.ts
@@ -184,7 +184,6 @@ export function generateAgentNode(agent: AgentMetadata): INodeType {
llm_config: llmConfig,
};
- console.log(`[${agent.name}] Executing with parameters:`, parameters);
// Execute Python agent
const result = await pythonAgentService.executeAgent(
@@ -245,7 +244,6 @@ export async function generateAllAgentNodes(): Promise<Map<string, INodeType>> {
// Get all available agents
const agents = await pythonAgentService.getAvailableAgents();
- console.log(`[AgentNodeGenerator] Generating nodes for ${agents.length} agents`);
// Generate a node for each agent
for (const agent of agents) {
@@ -253,7 +251,6 @@ export async function generateAllAgentNodes(): Promise<Map<string, INodeType>> {
agentNodes.set(agent.id, nodeType);
}
- console.log(`[AgentNodeGenerator] Successfully generated ${agentNodes.size} agent nodes`);
} catch (error) {
console.error('[AgentNodeGenerator] Failed to generate agent nodes:', error);
}
@@ -270,7 +267,6 @@ export async function generateAgentNodesByCategory(category: string): Promise<Ma
try {
const agents = await pythonAgentService.getAgentsByCategory(category);
- console.log(`[AgentNodeGenerator] Generating ${agents.length} nodes for category: ${category}`);
for (const agent of agents) {
const nodeType = generateAgentNode(agent);
diff --git a/fincept-terminal-desktop/src/services/trading/masterContractService.ts b/fincept-terminal-desktop/src/services/trading/masterContractService.ts
new file mode 100644
index 000000000..0a0ada126
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/trading/masterContractService.ts
@@ -0,0 +1,382 @@
+// Master Contract Service - Symbol Search & Management
+// Provides access to broker symbol data for fast search and offline access
+
+import { invoke } from '@tauri-apps/api/core';
+
+// ============================================================================
+// Types
+// ============================================================================
+
+/**
+ * Symbol search result from master contract database
+ */
+export interface SymbolSearchResult {
+ symbol: string;
+ br_symbol: string;
+ name: string | null;
+ exchange: string;
+ token: string;
+ expiry: string | null;
+ strike: number | null;
+ lot_size: number | null;
+ instrument_type: string | null;
+ tick_size: number | null;
+}
+
+/**
+ * Master contract download result
+ */
+export interface DownloadResult {
+ success: boolean;
+ message: string;
+ symbol_count: number;
+}
+
+/**
+ * Master contract cache metadata
+ */
+export interface MasterContractCache {
+ broker_id: string;
+ symbols_data: string;
+ symbol_count: number;
+ last_updated: number;
+ created_at: number;
+}
+
+/**
+ * Supported broker IDs for master contract
+ */
+export type SupportedBroker = 'angelone' | 'fyers' | 'zerodha';
+
+// ============================================================================
+// Master Contract Download
+// ============================================================================
+
+/**
+ * Download master contract for a specific broker
+ * Downloads symbol data from broker API and stores in local database
+ */
+export const downloadMasterContract = async (brokerId: SupportedBroker): Promise<DownloadResult> => {
+ return await invoke<DownloadResult>('download_master_contract', { brokerId });
+};
+
+/**
+ * Download Angel One master contract
+ * Downloads from https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json
+ */
+export const downloadAngelOneMasterContract = async (): Promise<DownloadResult> => {
+ return await invoke<DownloadResult>('download_angelone_master_contract');
+};
+
+/**
+ * Download Fyers master contract
+ * Downloads from https://public.fyers.in/sym_details/*.csv
+ */
+export const downloadFyersMasterContract = async (): Promise<DownloadResult> => {
+ return await invoke<DownloadResult>('download_fyers_master_contract');
+};
+
+// ============================================================================
+// Symbol Search
+// ============================================================================
+
+/**
+ * Search symbols in master contract database
+ * @param brokerId - Broker to search symbols for
+ * @param query - Search query (symbol, name, or token)
+ * @param exchange - Optional exchange filter (e.g., "NSE", "BSE", "NFO")
+ * @param instrumentType - Optional instrument type filter (e.g., "EQ", "OPTIDX", "FUTSTK")
+ * @param limit - Maximum number of results (default: 50)
+ * @returns Array of matching symbols ordered by relevance
+ */
+export const searchSymbols = async (
+ brokerId: SupportedBroker,
+ query: string,
+ exchange?: string,
+ instrumentType?: string,
+ limit: number = 50
+): Promise<SymbolSearchResult[]> => {
+ return await invoke<SymbolSearchResult[]>('search_symbols', {
+ brokerId,
+ query,
+ exchange: exchange || null,
+ instrumentType: instrumentType || null,
+ limit
+ });
+};
+
+/**
+ * Get symbol by exact match
+ * @param brokerId - Broker ID
+ * @param symbol - Exact symbol name
+ * @param exchange - Exchange name
+ */
+export const getSymbol = async (
+ brokerId: SupportedBroker,
+ symbol: string,
+ exchange: string
+): Promise<SymbolSearchResult | null> => {
+ return await invoke<SymbolSearchResult | null>('get_symbol', {
+ brokerId,
+ symbol,
+ exchange
+ });
+};
+
+/**
+ * Get symbol by broker token
+ * @param brokerId - Broker ID
+ * @param token - Broker-specific token
+ */
+export const getSymbolByToken = async (
+ brokerId: SupportedBroker,
+ token: string
+): Promise<SymbolSearchResult | null> => {
+ return await invoke<SymbolSearchResult | null>('get_symbol_by_token', {
+ brokerId,
+ token
+ });
+};
+
+// ============================================================================
+// Metadata Queries
+// ============================================================================
+
+/**
+ * Get total symbol count for a broker
+ */
+export const getSymbolCount = async (brokerId: SupportedBroker): Promise<number> => {
+ return await invoke<number>('get_symbol_count', { brokerId });
+};
+
+/**
+ * Get list of exchanges for a broker
+ */
+export const getExchanges = async (brokerId: SupportedBroker): Promise<string[]> => {
+ return await invoke<string[]>('get_exchanges', { brokerId });
+};
+
+/**
+ * Get list of expiries for derivatives
+ * @param brokerId - Broker ID
+ * @param exchange - Optional exchange filter
+ * @param underlying - Optional underlying symbol filter
+ */
+export const getExpiries = async (
+ brokerId: SupportedBroker,
+ exchange?: string,
+ underlying?: string
+): Promise<string[]> => {
+ return await invoke<string[]>('get_expiries', {
+ brokerId,
+ exchange: exchange || null,
+ underlying: underlying || null
+ });
+};
+
+// ============================================================================
+// Cache Management
+// ============================================================================
+
+/**
+ * Check if master contract data is available for a broker
+ */
+export const hasSymbolData = async (brokerId: SupportedBroker): Promise<boolean> => {
+ try {
+ const count = await getSymbolCount(brokerId);
+ return count > 0;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Get master contract cache metadata
+ */
+export const getMasterContractCache = async (brokerId: SupportedBroker): Promise<MasterContractCache | null> => {
+ return await invoke<MasterContractCache | null>('get_master_contract', { brokerId });
+};
+
+/**
+ * Check if cache is valid (not expired)
+ * @param brokerId - Broker ID
+ * @param ttlSeconds - Time to live in seconds (default: 24 hours)
+ */
+export const isCacheValid = async (
+ brokerId: SupportedBroker,
+ ttlSeconds: number = 86400
+): Promise<boolean> => {
+ return await invoke<boolean>('is_cache_valid', { brokerId, ttlSeconds });
+};
+
+/**
+ * Get cache age in seconds
+ */
+export const getCacheAge = async (brokerId: SupportedBroker): Promise<number | null> => {
+ return await invoke<number | null>('get_cache_age', { brokerId });
+};
+
+// ============================================================================
+// Utility Functions
+// ============================================================================
+
+/**
+ * Format symbol for display
+ */
+export const formatSymbolDisplay = (result: SymbolSearchResult): string => {
+ const parts = [result.symbol];
+ if (result.exchange) {
+ parts.push(`(${result.exchange})`);
+ }
+ if (result.expiry) {
+ parts.push(result.expiry);
+ }
+ if (result.strike) {
+ parts.push(`${result.strike}`);
+ }
+ return parts.join(' ');
+};
+
+/**
+ * Get broker-specific display name
+ */
+export const getBrokerDisplayName = (brokerId: SupportedBroker): string => {
+ const names: Record<SupportedBroker, string> = {
+ angelone: 'Angel One',
+ fyers: 'Fyers',
+ zerodha: 'Zerodha'
+ };
+ return names[brokerId] || brokerId;
+};
+
+/**
+ * Get exchange display name
+ */
+export const getExchangeDisplayName = (exchange: string): string => {
+ const names: Record<string, string> = {
+ NSE: 'NSE (Equity)',
+ BSE: 'BSE (Equity)',
+ NFO: 'NSE F&O',
+ BFO: 'BSE F&O',
+ MCX: 'MCX (Commodity)',
+ CDS: 'Currency Derivatives',
+ NSE_CM: 'NSE Cash',
+ NSE_FO: 'NSE F&O',
+ BSE_CM: 'BSE Cash',
+ BSE_FO: 'BSE F&O',
+ MCX_FO: 'MCX F&O'
+ };
+ return names[exchange] || exchange;
+};
+
+/**
+ * Map instrument type to display name
+ */
+export const getInstrumentTypeDisplayName = (instrumentType: string | null): string => {
+ if (!instrumentType) return 'Unknown';
+
+ const names: Record<string, string> = {
+ EQ: 'Equity',
+ EQUITY: 'Equity',
+ FUTSTK: 'Stock Futures',
+ FUTIDX: 'Index Futures',
+ OPTSTK: 'Stock Options',
+ OPTIDX: 'Index Options',
+ FUTCOM: 'Commodity Futures',
+ OPTCOM: 'Commodity Options',
+ FUTCUR: 'Currency Futures',
+ OPTCUR: 'Currency Options',
+ CE: 'Call Option',
+ PE: 'Put Option',
+ FUT: 'Futures'
+ };
+ return names[instrumentType.toUpperCase()] || instrumentType;
+};
+
+// ============================================================================
+// Service Class (for compatibility with existing patterns)
+// ============================================================================
+
+class MasterContractService {
+ // Download
+ downloadMasterContract = downloadMasterContract;
+ downloadAngelOneMasterContract = downloadAngelOneMasterContract;
+ downloadFyersMasterContract = downloadFyersMasterContract;
+
+ // Search
+ searchSymbols = searchSymbols;
+ getSymbol = getSymbol;
+ getSymbolByToken = getSymbolByToken;
+
+ // Metadata
+ getSymbolCount = getSymbolCount;
+ getExchanges = getExchanges;
+ getExpiries = getExpiries;
+
+ // Cache
+ hasSymbolData = hasSymbolData;
+ getMasterContractCache = getMasterContractCache;
+ isCacheValid = isCacheValid;
+ getCacheAge = getCacheAge;
+
+ // Utils
+ formatSymbolDisplay = formatSymbolDisplay;
+ getBrokerDisplayName = getBrokerDisplayName;
+ getExchangeDisplayName = getExchangeDisplayName;
+ getInstrumentTypeDisplayName = getInstrumentTypeDisplayName;
+
+ /**
+ * Initialize master contract for a broker
+ * Downloads if not available or cache is expired
+ */
+ async initializeBroker(brokerId: SupportedBroker): Promise<DownloadResult> {
+ const hasData = await this.hasSymbolData(brokerId);
+ const cacheValid = await this.isCacheValid(brokerId);
+
+ if (!hasData || !cacheValid) {
+ console.log(`[MasterContractService] Downloading master contract for ${brokerId}...`);
+ return await this.downloadMasterContract(brokerId);
+ }
+
+ const count = await this.getSymbolCount(brokerId);
+ return {
+ success: true,
+ message: 'Cache is valid',
+ symbol_count: count
+ };
+ }
+
+ /**
+ * Search with debounce-friendly interface
+ * Returns empty array on error instead of throwing
+ */
+ async safeSearch(
+ brokerId: SupportedBroker,
+ query: string,
+ options?: {
+ exchange?: string;
+ instrumentType?: string;
+ limit?: number;
+ }
+ ): Promise<SymbolSearchResult[]> {
+ if (!query || query.length < 1) {
+ return [];
+ }
+
+ try {
+ return await this.searchSymbols(
+ brokerId,
+ query,
+ options?.exchange,
+ options?.instrumentType,
+ options?.limit || 50
+ );
+ } catch (error) {
+ console.error('[MasterContractService] Search error:', error);
+ return [];
+ }
+ }
+}
+
+export const masterContractService = new MasterContractService();
+export default masterContractService;
diff --git a/fincept-terminal-desktop/src/services/unifiedTradingService.ts b/fincept-terminal-desktop/src/services/unifiedTradingService.ts
new file mode 100644
index 000000000..7cde2388a
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/unifiedTradingService.ts
@@ -0,0 +1,348 @@
+/**
+ * Unified Trading Service
+ *
+ * Handles both LIVE and PAPER trading modes for all stock brokers.
+ * Provides a unified API that routes to either real broker or paper trading engine.
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+
+// ============================================================================
+// Types
+// ============================================================================
+
+export type TradingMode = 'live' | 'paper';
+
+export interface TradingSession {
+ broker: string;
+ mode: TradingMode;
+ paper_portfolio_id: string | null;
+ is_connected: boolean;
+}
+
+export interface UnifiedOrder {
+ symbol: string;
+ exchange: string;
+ side: 'buy' | 'sell';
+ order_type: 'market' | 'limit' | 'stop' | 'stop_limit';
+ quantity: number;
+ price?: number;
+ stop_price?: number;
+ product_type?: 'CNC' | 'MIS' | 'NRML';
+}
+
+export interface UnifiedOrderResponse {
+ success: boolean;
+ order_id?: string;
+ message?: string;
+ mode: TradingMode;
+}
+
+export interface UnifiedPosition {
+ symbol: string;
+ exchange: string;
+ side: 'long' | 'short';
+ quantity: number;
+ entry_price: number;
+ current_price: number;
+ unrealized_pnl: number;
+ realized_pnl: number;
+ mode: TradingMode;
+}
+
+export interface PaperOrder {
+ id: string;
+ portfolio_id: string;
+ symbol: string;
+ side: string;
+ order_type: string;
+ quantity: number;
+ price: number | null;
+ stop_price: number | null;
+ filled_qty: number;
+ avg_price: number | null;
+ status: 'pending' | 'filled' | 'partial' | 'cancelled';
+ reduce_only: boolean;
+ created_at: string;
+ filled_at: string | null;
+}
+
+export interface PaperPortfolio {
+ id: string;
+ name: string;
+ initial_balance: number;
+ balance: number;
+ currency: string;
+ leverage: number;
+ margin_mode: string;
+ fee_rate: number;
+ created_at: string;
+}
+
+export interface PaperStats {
+ total_pnl: number;
+ win_rate: number;
+ total_trades: number;
+ winning_trades: number;
+ losing_trades: number;
+ largest_win: number;
+ largest_loss: number;
+}
+
+// ============================================================================
+// Session Management
+// ============================================================================
+
+/**
+ * Initialize a trading session for a broker
+ */
+export async function initTradingSession(
+ broker: string,
+ mode: TradingMode,
+ paperPortfolioId?: string
+): Promise<TradingSession> {
+ return invoke<TradingSession>('init_trading_session', {
+ broker,
+ mode,
+ paperPortfolioId,
+ });
+}
+
+/**
+ * Get current trading session
+ */
+export async function getTradingSession(): Promise<TradingSession | null> {
+ return invoke<TradingSession | null>('get_trading_session');
+}
+
+/**
+ * Switch between live and paper trading modes
+ */
+export async function switchTradingMode(mode: TradingMode): Promise<TradingSession> {
+ return invoke<TradingSession>('switch_trading_mode', { mode });
+}
+
+// ============================================================================
+// Order Management
+// ============================================================================
+
+/**
+ * Place an order (routes to live broker or paper trading based on mode)
+ */
+export async function placeOrder(order: UnifiedOrder): Promise<UnifiedOrderResponse> {
+ return invoke<UnifiedOrderResponse>('unified_place_order', { order });
+}
+
+/**
+ * Get positions (paper or live based on mode)
+ */
+export async function getPositions(): Promise<UnifiedPosition[]> {
+ return invoke<UnifiedPosition[]>('unified_get_positions');
+}
+
+/**
+ * Get orders (paper or live based on mode)
+ */
+export async function getOrders(status?: string): Promise<PaperOrder[]> {
+ return invoke<PaperOrder[]>('unified_get_orders', { status });
+}
+
+/**
+ * Cancel an order
+ */
+export async function cancelOrder(orderId: string): Promise<void> {
+ return invoke<void>('unified_cancel_order', { orderId });
+}
+
+// ============================================================================
+// Paper Trading Specific
+// ============================================================================
+
+/**
+ * Create a paper trading portfolio
+ */
+export async function createPaperPortfolio(
+ name: string,
+ balance: number,
+ currency = 'INR',
+ leverage = 1.0,
+ marginMode = 'cross',
+ feeRate = 0.0003
+): Promise<PaperPortfolio> {
+ return invoke<PaperPortfolio>('pt_create_portfolio', {
+ name,
+ balance,
+ currency,
+ leverage,
+ marginMode,
+ feeRate,
+ });
+}
+
+/**
+ * List all paper trading portfolios
+ */
+export async function listPaperPortfolios(): Promise<PaperPortfolio[]> {
+ return invoke<PaperPortfolio[]>('pt_list_portfolios');
+}
+
+/**
+ * Get paper trading statistics
+ */
+export async function getPaperStats(portfolioId: string): Promise<PaperStats> {
+ return invoke<PaperStats>('pt_get_stats', { portfolioId });
+}
+
+/**
+ * Get paper portfolio balance/funds info
+ */
+export async function getPaperFunds(): Promise<{
+ totalBalance: number;
+ availableCash: number;
+ usedMargin: number;
+ availableMargin: number;
+ currency: string;
+} | null> {
+ try {
+ const portfolios = await listPaperPortfolios();
+ if (portfolios.length === 0) {
+ // Create a default paper portfolio if none exists
+ const defaultPortfolio = await createPaperPortfolio('Default Paper Portfolio', 1000000, 'INR');
+ return {
+ totalBalance: defaultPortfolio.balance,
+ availableCash: defaultPortfolio.balance,
+ usedMargin: 0,
+ availableMargin: defaultPortfolio.balance,
+ currency: defaultPortfolio.currency,
+ };
+ }
+
+ // Use the first portfolio
+ const portfolio = portfolios[0];
+ const positions = await getPositions();
+
+ // Calculate used margin from open positions
+ const usedMargin = positions.reduce((acc, p) => acc + (p.entry_price * p.quantity), 0);
+
+ return {
+ totalBalance: portfolio.initial_balance,
+ availableCash: portfolio.balance,
+ usedMargin: usedMargin,
+ availableMargin: portfolio.balance,
+ currency: portfolio.currency,
+ };
+ } catch (err) {
+ console.error('[UnifiedTradingService] Failed to get paper funds:', err);
+ return null;
+ }
+}
+
+/**
+ * Get paper trades (filled orders)
+ */
+export async function getPaperTrades(): Promise<PaperOrder[]> {
+ try {
+ const orders = await getOrders('filled');
+ return orders;
+ } catch (err) {
+ console.error('[UnifiedTradingService] Failed to get paper trades:', err);
+ return [];
+ }
+}
+
+/**
+ * Reset a paper trading portfolio
+ */
+export async function resetPaperPortfolio(portfolioId: string): Promise<PaperPortfolio> {
+ return invoke<PaperPortfolio>('pt_reset_portfolio', { id: portfolioId });
+}
+
+/**
+ * Delete a paper trading portfolio
+ */
+export async function deletePaperPortfolio(portfolioId: string): Promise<void> {
+ return invoke<void>('pt_delete_portfolio', { id: portfolioId });
+}
+
+// ============================================================================
+// Helper Functions
+// ============================================================================
+
+/**
+ * Check if currently in paper trading mode
+ */
+export async function isPaperMode(): Promise<boolean> {
+ const session = await getTradingSession();
+ return session?.mode === 'paper';
+}
+
+/**
+ * Quick order helpers
+ */
+export async function buyMarket(
+ symbol: string,
+ exchange: string,
+ quantity: number,
+ productType: 'CNC' | 'MIS' | 'NRML' = 'CNC'
+): Promise<UnifiedOrderResponse> {
+ return placeOrder({
+ symbol,
+ exchange,
+ side: 'buy',
+ order_type: 'market',
+ quantity,
+ product_type: productType,
+ });
+}
+
+export async function sellMarket(
+ symbol: string,
+ exchange: string,
+ quantity: number,
+ productType: 'CNC' | 'MIS' | 'NRML' = 'CNC'
+): Promise<UnifiedOrderResponse> {
+ return placeOrder({
+ symbol,
+ exchange,
+ side: 'sell',
+ order_type: 'market',
+ quantity,
+ product_type: productType,
+ });
+}
+
+export async function buyLimit(
+ symbol: string,
+ exchange: string,
+ quantity: number,
+ price: number,
+ productType: 'CNC' | 'MIS' | 'NRML' = 'CNC'
+): Promise<UnifiedOrderResponse> {
+ return placeOrder({
+ symbol,
+ exchange,
+ side: 'buy',
+ order_type: 'limit',
+ quantity,
+ price,
+ product_type: productType,
+ });
+}
+
+export async function sellLimit(
+ symbol: string,
+ exchange: string,
+ quantity: number,
+ price: number,
+ productType: 'CNC' | 'MIS' | 'NRML' = 'CNC'
+): Promise<UnifiedOrderResponse> {
+ return placeOrder({
+ symbol,
+ exchange,
+ side: 'sell',
+ order_type: 'limit',
+ quantity,
+ price,
+ product_type: productType,
+ });
+}