-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathactive-symbols-processor.service.ts
More file actions
405 lines (348 loc) · 14.3 KB
/
Copy pathactive-symbols-processor.service.ts
File metadata and controls
405 lines (348 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import { tradingTimesService } from '../components/shared/services/trading-times-service';
import { generateDisplayName, MARKET_MAPPINGS } from '../components/shared/utils/common-data';
import { activeSymbolCategorizationService } from './active-symbol-categorization.service';
// API Response Interfaces for better type safety
export interface TradingTimesSymbol {
symbol: string;
display_name: string;
underlying_symbol?: string;
}
export interface TradingTimesSubmarket {
name: string;
symbols?: TradingTimesSymbol[];
}
export interface TradingTimesMarket {
name: string;
submarkets?: TradingTimesSubmarket[];
}
export interface TradingTimesResponse {
markets: TradingTimesMarket[];
}
export interface ActiveSymbolInput {
symbol: string;
underlying_symbol?: string;
display_name?: string;
market: string;
market_display_name?: string;
submarket: string;
submarket_display_name?: string;
subgroup?: string;
pip_size?: number;
pip?: number;
symbol_type?: string;
underlying_symbol_type?: string;
is_trading_suspended?: boolean;
exchange_is_open?: boolean;
}
export interface ProcessedActiveSymbol {
symbol: string;
underlying_symbol: string;
display_name: string;
market: string;
market_display_name: string;
submarket: string;
submarket_display_name: string;
subgroup?: string;
subgroup_display_name?: string;
pip_size?: number;
pip?: number;
symbol_type?: string;
underlying_symbol_type?: string;
underlying_symbol_display_name?: string;
symbol_display_name?: string;
is_trading_suspended?: boolean;
exchange_is_open?: boolean;
}
export interface PipSizes {
[symbol: string]: number;
}
/**
* Active Symbols Processor Service
*
* Handles all active symbol processing including:
* - Pip size calculation
* - Symbol enrichment with trading times data
* - Display name generation
* - Backward compatibility
*/
export class ActiveSymbolsProcessorService {
private static instance: ActiveSymbolsProcessorService;
// Constants for timeouts and cache duration
private readonly ENRICHMENT_TIMEOUT_MS = 10000;
private constructor() {}
public static getInstance(): ActiveSymbolsProcessorService {
if (!ActiveSymbolsProcessorService.instance) {
ActiveSymbolsProcessorService.instance = new ActiveSymbolsProcessorService();
}
return ActiveSymbolsProcessorService.instance;
}
/**
* Process pip sizes from active symbols
*/
public processPipSizes(activeSymbols: ActiveSymbolInput[]): PipSizes {
const pipSizes: PipSizes = {};
activeSymbols.forEach((symbol: ActiveSymbolInput) => {
const underlyingSymbol = symbol.underlying_symbol || symbol.symbol;
const pipSize = symbol.pip_size || symbol.pip;
if (underlyingSymbol && pipSize) {
// Calculate decimal places from pip size (e.g., 0.01 -> 2, 0.0001 -> 4)
// This converts pip size to exponential notation and extracts the exponent
const exponent = +(+pipSize).toExponential().substring(3);
pipSizes[underlyingSymbol] = Math.abs(exponent);
}
});
return pipSizes;
}
/**
* Get market mapping from common data
*/
private getMarketMapping(): Map<string, string> {
return MARKET_MAPPINGS.MARKET_DISPLAY_NAMES;
}
/**
* Get submarket mapping from common data
*/
private getSubmarketMapping(): Map<string, string> {
return MARKET_MAPPINGS.SUBMARKET_DISPLAY_NAMES;
}
/**
* Create lookup maps from trading times data
*/
private async createLookupMaps() {
try {
const tradingTimes = await tradingTimesService.getTradingTimes();
if (!tradingTimes?.markets || !Array.isArray(tradingTimes.markets)) {
throw new Error('Invalid trading times data structure');
}
return this.processTradingTimesData(tradingTimes);
} catch (error) {
console.warn('Failed to create lookup maps from trading times, using fallback mappings:', error);
// Return fallback maps with basic market mappings when trading times API fails
const marketDisplayNames = new Map<string, string>();
const submarketDisplayNames = new Map<string, string>();
const symbolDisplayNames = new Map<string, string>();
// Add basic market mappings from common data
const marketMapping = this.getMarketMapping();
const submarketMapping = this.getSubmarketMapping();
// Populate with basic mappings
marketMapping.forEach((displayName, code) => {
marketDisplayNames.set(code, displayName);
});
submarketMapping.forEach((displayName, code) => {
submarketDisplayNames.set(code, displayName);
});
return {
marketDisplayNames,
submarketDisplayNames,
symbolDisplayNames,
};
}
}
/**
* Process trading times data into lookup maps
*/
private processTradingTimesData(tradingTimes: TradingTimesResponse) {
const marketDisplayNames = new Map<string, string>();
const submarketDisplayNames = new Map<string, string>();
const symbolDisplayNames = new Map<string, string>();
const marketMapping = this.getMarketMapping();
const submarketMapping = this.getSubmarketMapping();
// Process markets and submarkets
tradingTimes.markets.forEach((market: TradingTimesMarket) => {
if (market.name) {
const translatedMarketName = activeSymbolCategorizationService.translateMarketCategory(market.name);
marketDisplayNames.set(market.name, translatedMarketName);
// Create reverse mapping for market codes
marketMapping.forEach((name, code) => {
if (name === market.name) {
marketDisplayNames.set(code, translatedMarketName);
}
});
}
if (market.submarkets) {
market.submarkets.forEach((submarket: TradingTimesSubmarket) => {
if (submarket.name && market.name) {
const translatedSubmarketName = activeSymbolCategorizationService.translateMarketCategory(
submarket.name
);
const key = `${market.name}_${submarket.name}`;
submarketDisplayNames.set(key, translatedSubmarketName);
submarketDisplayNames.set(submarket.name, translatedSubmarketName);
// Create mapping for market codes and submarket codes
marketMapping.forEach((name, code) => {
if (name === market.name) {
const codeKey = `${code}_${submarket.name}`;
submarketDisplayNames.set(codeKey, translatedSubmarketName);
}
});
}
// Process symbols
if (submarket.symbols) {
submarket.symbols.forEach((symbolInfo: TradingTimesSymbol) => {
if (symbolInfo.symbol && symbolInfo.display_name) {
symbolDisplayNames.set(symbolInfo.symbol, symbolInfo.display_name);
}
if (symbolInfo.underlying_symbol && symbolInfo.display_name) {
symbolDisplayNames.set(symbolInfo.underlying_symbol, symbolInfo.display_name);
}
});
}
});
}
});
// Add direct submarket code mappings
submarketMapping.forEach((submarketName, submarketCode) => {
submarketDisplayNames.set(submarketCode, submarketName);
// Also add with market prefixes
marketMapping.forEach((_, marketCode) => {
const key = `${marketCode}_${submarketCode}`;
submarketDisplayNames.set(key, submarketName);
});
});
return {
marketDisplayNames,
submarketDisplayNames,
symbolDisplayNames,
};
}
/**
* Enrich a single symbol with display names and additional data
*/
private enrichSymbol(
symbol: ActiveSymbolInput,
lookupMaps: {
marketDisplayNames: Map<string, string>;
submarketDisplayNames: Map<string, string>;
symbolDisplayNames: Map<string, string>;
}
): ProcessedActiveSymbol {
const enrichedSymbol: Partial<ProcessedActiveSymbol> = { ...symbol };
// Add market display name
if (symbol.market) {
enrichedSymbol.market_display_name =
lookupMaps.marketDisplayNames.get(symbol.market) ||
activeSymbolCategorizationService.translateMarketCategory(symbol.market);
}
// Add submarket display name
if (symbol.submarket) {
enrichedSymbol.submarket_display_name = activeSymbolCategorizationService.getSubmarketDisplayName(
symbol.submarket
);
}
// Add subgroup display name
if (symbol.subgroup) {
let subgroupDisplayName = symbol.subgroup;
// Try with market prefix
if (symbol.market) {
const subgroupKey = `${symbol.market}_${symbol.subgroup}`;
subgroupDisplayName = lookupMaps.submarketDisplayNames.get(subgroupKey) || subgroupDisplayName;
}
// Try direct subgroup code lookup
subgroupDisplayName = lookupMaps.submarketDisplayNames.get(symbol.subgroup) || subgroupDisplayName;
enrichedSymbol.subgroup_display_name = subgroupDisplayName;
}
// Add symbol display name
const symbolCode = symbol.underlying_symbol || symbol.symbol;
if (symbolCode) {
const symbolDisplayName = lookupMaps.symbolDisplayNames.get(symbolCode);
if (symbolDisplayName) {
enrichedSymbol.display_name = symbolDisplayName;
} else {
enrichedSymbol.display_name = this.generateFallbackDisplayName(symbolCode, symbol);
}
}
// Add underlying_symbol display name
if (symbol.underlying_symbol) {
const underlyingSymbolDisplayName = lookupMaps.symbolDisplayNames.get(symbol.underlying_symbol);
if (underlyingSymbolDisplayName) {
enrichedSymbol.underlying_symbol_display_name = underlyingSymbolDisplayName;
}
}
// Add symbol field display name
if (symbol.symbol) {
const symbolFieldDisplayName = lookupMaps.symbolDisplayNames.get(symbol.symbol);
if (symbolFieldDisplayName) {
enrichedSymbol.symbol_display_name = symbolFieldDisplayName;
}
}
// Handle backward compatibility
this.ensureBackwardCompatibility(enrichedSymbol);
return enrichedSymbol as ProcessedActiveSymbol;
}
/**
* Ensure backward compatibility for symbol fields
*/
private ensureBackwardCompatibility(symbol: Partial<ProcessedActiveSymbol>): void {
// Handle new API field names
if (symbol.symbol_type && !symbol.underlying_symbol_type) {
symbol.underlying_symbol_type = symbol.symbol_type;
}
// Ensure we have both symbol and underlying_symbol
if (symbol.underlying_symbol && !symbol.symbol) {
symbol.symbol = symbol.underlying_symbol;
} else if (symbol.symbol && !symbol.underlying_symbol) {
symbol.underlying_symbol = symbol.symbol;
}
}
/**
* Generate fallback display name for symbols not found in trading times
*/
private generateFallbackDisplayName(symbolCode: string, symbol: ActiveSymbolInput): string {
return generateDisplayName(symbolCode, symbol);
}
/**
* Enrich active symbols with trading times data
*/
public async enrichActiveSymbolsWithTradingTimes(
activeSymbols: ActiveSymbolInput[]
): Promise<ProcessedActiveSymbol[]> {
if (!activeSymbols || activeSymbols.length === 0) {
return [];
}
try {
const lookupMaps = await this.createLookupMaps();
return activeSymbols.map(symbol => {
// Validate symbol structure before processing
if (!symbol || typeof symbol !== 'object') {
console.warn('Invalid symbol structure:', symbol);
return symbol;
}
return this.enrichSymbol(symbol, lookupMaps);
});
} catch (error) {
console.error('Error enriching active symbols:', error);
// Return symbols as-is with minimal processing for error case
return activeSymbols.map(symbol => ({
...symbol,
underlying_symbol: symbol.underlying_symbol || symbol.symbol,
display_name: symbol.display_name || symbol.symbol,
market_display_name: symbol.market_display_name || symbol.market,
submarket_display_name: symbol.submarket_display_name || symbol.submarket,
})) as ProcessedActiveSymbol[];
}
}
/**
* Process active symbols - complete processing pipeline
*/
public async processActiveSymbols(activeSymbols: ActiveSymbolInput[]): Promise<{
enrichedSymbols: ProcessedActiveSymbol[];
pipSizes: PipSizes;
}> {
if (!activeSymbols || !activeSymbols.length) {
return {
enrichedSymbols: [],
pipSizes: {},
};
}
// Process pip sizes
const pipSizes = this.processPipSizes(activeSymbols);
// Enrich symbols with trading times data
const enrichedSymbols = await this.enrichActiveSymbolsWithTradingTimes(activeSymbols);
return {
enrichedSymbols,
pipSizes,
};
}
}
// Export singleton instance
export const activeSymbolsProcessorService = ActiveSymbolsProcessorService.getInstance();