Download src/services/zerodhaService.ts from SherlockHolmes786/tradewithlive: direct link, hf CLI and curl.
- Browser
- Download file 9.35 kB
-
https://huggingface.co/SherlockHolmes786/tradewithlive/resolve/main/src/services/zerodhaService.ts
- Command line
-
hf download hf://SherlockHolmes786/tradewithlive/src/services/zerodhaService.ts
-
curl -L -o zerodhaService.ts https://huggingface.co/SherlockHolmes786/tradewithlive/resolve/main/src/services/zerodhaService.ts
9.35 kB
| import { BrokerCredentials, ZerodhaPosition, ZerodhaHolding, ZerodhaOrder, ZerodhaUserProfile } from '../types/broker'; | |
| import { getZerodhaConfig, RATE_LIMITS } from '../config/brokerConfig'; | |
| class ZerodhaService { | |
| private credentials: BrokerCredentials | null = null; | |
| private accessToken: string | null = null; | |
| private requestQueue: Array<() => Promise<any>> = []; | |
| private isProcessingQueue = false; | |
| private lastRequestTime = 0; | |
| private requestCount = 0; | |
| private requestCountMinute = 0; | |
| private lastMinuteReset = Date.now(); | |
| constructor(credentials?: BrokerCredentials) { | |
| if (credentials) { | |
| this.credentials = credentials; | |
| } | |
| } | |
| // Rate limiting helper | |
| private async waitForRateLimit(): Promise<void> { | |
| const now = Date.now(); | |
| // Reset minute counter if needed | |
| if (now - this.lastMinuteReset > 60000) { | |
| this.requestCountMinute = 0; | |
| this.lastMinuteReset = now; | |
| } | |
| // Check per-second limit | |
| const timeSinceLastRequest = now - this.lastRequestTime; | |
| if (timeSinceLastRequest < 1000 / RATE_LIMITS.requestsPerSecond) { | |
| const delay = (1000 / RATE_LIMITS.requestsPerSecond) - timeSinceLastRequest; | |
| await new Promise(resolve => setTimeout(resolve, delay)); | |
| } | |
| // Check per-minute limit | |
| if (this.requestCountMinute >= RATE_LIMITS.requestsPerMinute) { | |
| const timeUntilReset = 60000 - (now - this.lastMinuteReset); | |
| await new Promise(resolve => setTimeout(resolve, timeUntilReset)); | |
| this.requestCountMinute = 0; | |
| this.lastMinuteReset = Date.now(); | |
| } | |
| this.lastRequestTime = Date.now(); | |
| this.requestCount++; | |
| this.requestCountMinute++; | |
| } | |
| // Queue management for rate limiting | |
| private async addToQueue<T>(request: () => Promise<T>): Promise<T> { | |
| return new Promise((resolve, reject) => { | |
| this.requestQueue.push(async () => { | |
| try { | |
| const result = await request(); | |
| resolve(result); | |
| } catch (error) { | |
| reject(error); | |
| } | |
| }); | |
| this.processQueue(); | |
| }); | |
| } | |
| private async processQueue(): Promise<void> { | |
| if (this.isProcessingQueue || this.requestQueue.length === 0) { | |
| return; | |
| } | |
| this.isProcessingQueue = true; | |
| while (this.requestQueue.length > 0) { | |
| await this.waitForRateLimit(); | |
| const request = this.requestQueue.shift(); | |
| if (request) { | |
| await request(); | |
| } | |
| } | |
| this.isProcessingQueue = false; | |
| } | |
| // Authentication | |
| async authenticate(requestToken: string): Promise<string> { | |
| if (!this.credentials) { | |
| throw new Error('No credentials provided'); | |
| } | |
| const config = getZerodhaConfig(false); | |
| try { | |
| const response = await fetch(`${config.apiTokenUrl}`, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/x-www-form-urlencoded', | |
| }, | |
| body: new URLSearchParams({ | |
| api_key: this.credentials.apiKey, | |
| request_token: requestToken, | |
| checksum: this.generateChecksum(requestToken), | |
| }), | |
| }); | |
| if (!response.ok) { | |
| throw new Error(`Authentication failed: ${response.statusText}`); | |
| } | |
| const data = await response.json(); | |
| if (data.status === 'error') { | |
| throw new Error(data.message || 'Authentication failed'); | |
| } | |
| this.accessToken = data.data.access_token; | |
| if (this.credentials) { | |
| this.credentials.accessToken = this.accessToken || undefined; | |
| } | |
| return this.accessToken || ''; | |
| } catch (error) { | |
| console.error('Authentication error:', error); | |
| throw error; | |
| } | |
| } | |
| // Generate checksum for Zerodha (simplified - in production use proper crypto) | |
| private generateChecksum(requestToken: string): string { | |
| // In production, this should use proper HMAC-SHA256 | |
| // For now, return a placeholder | |
| return `${this.credentials?.apiKey}:${requestToken}:${this.credentials?.apiSecret}`; | |
| } | |
| // Generic API request method | |
| private async apiRequest<T>(endpoint: string, options: RequestInit = {}): Promise<T> { | |
| if (!this.accessToken) { | |
| throw new Error('Not authenticated. Call authenticate() first.'); | |
| } | |
| const config = getZerodhaConfig(false); | |
| const url = `${config.baseUrl}${endpoint}`; | |
| const defaultOptions: RequestInit = { | |
| headers: { | |
| 'Authorization': `Bearer ${this.accessToken}`, | |
| 'Content-Type': 'application/json', | |
| ...options.headers, | |
| }, | |
| ...options, | |
| }; | |
| return this.addToQueue(async () => { | |
| try { | |
| const response = await fetch(url, defaultOptions); | |
| if (!response.ok) { | |
| if (response.status === 401) { | |
| throw new Error('Session expired. Please re-authenticate.'); | |
| } | |
| if (response.status === 429) { | |
| throw new Error('Rate limit exceeded. Please try again later.'); | |
| } | |
| throw new Error(`API request failed: ${response.statusText}`); | |
| } | |
| const data = await response.json(); | |
| if (data.status === 'error') { | |
| throw new Error(data.message || 'API request failed'); | |
| } | |
| return data.data as T; | |
| } catch (error) { | |
| console.error('API request error:', error); | |
| throw error; | |
| } | |
| }); | |
| } | |
| // Get user profile | |
| async getUserProfile(): Promise<ZerodhaUserProfile> { | |
| return this.apiRequest<ZerodhaUserProfile>('/api/user/profile'); | |
| } | |
| // Get positions | |
| async getPositions(): Promise<ZerodhaPosition[]> { | |
| return this.apiRequest<ZerodhaPosition[]>('/api/portfolio/positions'); | |
| } | |
| // Get holdings | |
| async getHoldings(): Promise<ZerodhaHolding[]> { | |
| return this.apiRequest<ZerodhaHolding[]>('/api/portfolio/holdings'); | |
| } | |
| // Get orders | |
| async getOrders(): Promise<ZerodhaOrder[]> { | |
| return this.apiRequest<ZerodhaOrder[]>('/api/orders'); | |
| } | |
| // Get order history | |
| async getOrderHistory(orderId: string): Promise<ZerodhaOrder[]> { | |
| return this.apiRequest<ZerodhaOrder[]>(`/api/orders/${orderId}`); | |
| } | |
| // Get quote for instruments | |
| async getQuote(instruments: string[]): Promise<any> { | |
| const instrumentParam = instruments.join(','); | |
| return this.apiRequest<any>(`/api/quote/${instrumentParam}`); | |
| } | |
| // Get order book (L2 data) | |
| async getOrderBook(instrumentToken: number): Promise<any> { | |
| return this.apiRequest<any>(`/api/orderbook/${instrumentToken}`); | |
| } | |
| // Convert Zerodha position to our Position format | |
| convertZerodhaPosition(position: ZerodhaPosition) { | |
| const isLong = position.quantity > 0; | |
| const leverage = this.calculateLeverage(position); | |
| return { | |
| id: `zerodha_${position.instrument_token}`, | |
| symbol: position.tradingsymbol, | |
| type: isLong ? ('LONG' as const) : ('SHORT' as const), | |
| leverage: leverage, | |
| entryPrice: position.buy_price || position.price, | |
| markPrice: position.last_price || position.price, | |
| pnlDollars: position.pnl || position.unrealised, | |
| pnlPercent: this.calculatePnlPercent(position), | |
| size: Math.abs(position.quantity).toString(), | |
| }; | |
| } | |
| // Calculate leverage (simplified) | |
| private calculateLeverage(position: ZerodhaPosition): string { | |
| // This is a simplified calculation | |
| // In production, calculate based on product type (NRML, MIS, CO) | |
| const productMultipliers: { [key: string]: string } = { | |
| 'NRML': '1x', | |
| 'MIS': '5x', | |
| 'CO': '3x', | |
| }; | |
| return productMultipliers[position.product] || '1x'; | |
| } | |
| // Calculate P&L percentage | |
| private calculatePnlPercent(position: ZerodhaPosition): number { | |
| if (!position.buy_price || position.buy_price === 0) return 0; | |
| const currentPrice = position.last_price || position.price; | |
| return ((currentPrice - position.buy_price) / position.buy_price) * 100; | |
| } | |
| // Convert Zerodha holdings to our format | |
| convertZerodhaHolding(holding: ZerodhaHolding) { | |
| const pnlPercent = holding.price > 0 | |
| ? ((holding.last_price - holding.price) / holding.price) * 100 | |
| : 0; | |
| return { | |
| id: `zerodha_holding_${holding.instrument_token}`, | |
| symbol: holding.tradingsymbol, | |
| type: 'LONG' as const, | |
| leverage: '1x', | |
| entryPrice: holding.price, | |
| markPrice: holding.last_price, | |
| pnlDollars: holding.pnl, | |
| pnlPercent, | |
| size: holding.quantity.toString(), | |
| }; | |
| } | |
| // Logout | |
| async logout(): Promise<void> { | |
| if (!this.accessToken) { | |
| return; | |
| } | |
| const config = getZerodhaConfig(false); | |
| try { | |
| await fetch(`${config.logoutUrl}`, { | |
| method: 'POST', | |
| headers: { | |
| 'Authorization': `Bearer ${this.accessToken}`, | |
| }, | |
| }); | |
| } catch (error) { | |
| console.error('Logout error:', error); | |
| } finally { | |
| this.accessToken = null; | |
| if (this.credentials) { | |
| this.credentials.accessToken = undefined; | |
| } | |
| } | |
| } | |
| // Update credentials | |
| updateCredentials(credentials: BrokerCredentials): void { | |
| this.credentials = credentials; | |
| this.accessToken = credentials.accessToken || null; | |
| } | |
| // Check if authenticated | |
| isAuthenticated(): boolean { | |
| return this.accessToken !== null; | |
| } | |
| } | |
| // Export singleton instance | |
| export const zerodhaService = new ZerodhaService(); | |
| // Export class for creating new instances | |
| export { ZerodhaService }; | |