-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataManager.ts
More file actions
258 lines (238 loc) · 9.04 KB
/
dataManager.ts
File metadata and controls
258 lines (238 loc) · 9.04 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
import { fetchCandlestickData, fetchBinanceExchangeInfo, createWebSocketConnection, fetchGreedAndFearIndex } from './api';
import { calculateRSIForSymbol, calculateMACDForSymbol, calculateEMAForSymbol, calculateSMAForSymbol, calculateSMA200ForSymbol, calculateEMA200ForSymbol, checkEMA50200Crossover, checkSMA50200Crossover, calculateADXForSymbol, calculateVWAPForSymbol, calculateBollingerBands, calculateOBV, calculateFibonacciRetracement, checkSMA2050Crossover, checkEMA2050Crossover, calculateCMF, calculateIchimokuCloud, calculateATR, calculateStochastic } from './calculator';
import WebSocket from 'ws';
// Define the type for the data we'll be displaying
export interface RSIData {
symbol: string;
rsi: number | null;
macd: {
MACD: number | null;
signal: number | null;
histogram: number | null;
previousMACD1: number | null;
previousSignal1: number | null;
previousHistogram1: number | null;
previousMACD2: number | null;
previousSignal2: number | null;
previousHistogram2: number | null;
};
moving_averages: number;
oscillators: number;
sma10: number | null;
sma20: number | null;
sma50: number | null;
sma100: number | null;
sma200: number | null;
isCrossoverSMA2050: boolean | null;
isCrossoverSMA50200: boolean | null;
ema10: number | null;
ema20: number | null;
ema50: number | null;
ema100: number | null;
ema200: number | null;
isCrossoverEMA2050: boolean | null;
isCrossoverEMA50200: boolean | null;
price: number | null;
timeframe: Timeframe;
adx: {
adx: number | null;
plusDI: number | null;
minusDI: number | null;
};
vwap: number | null;
bollingerBands: {
upper: number | null;
middle: number | null;
lower: number | null;
};
obv: {
obv: number | null;
obvSma: number | null;
};
fibonacci: {
levels: {
[key: string]: number | null;
'0': number | null;
'0.236': number | null;
'0.382': number | null;
'0.5': number | null;
'0.618': number | null;
'0.786': number | null;
'1': number | null;
};
high: number | null;
low: number | null;
};
cmf: number | null;
ichimoku: {
conversion: number | null;
base: number | null;
spanA: number | null;
spanB: number | null;
leadingSpanA: number | null;
leadingSpanB: number | null;
};
atr: number | null;
stochastic: {
k: number | null;
d: number | null;
};
}
export type Timeframe = '1h' | '4h' | '1d' | '1w';
export const ALL_TIMEFRAMES: Timeframe[] = ['1h', '4h', '1d', '1w'];
type WsWebSocket = WebSocket;
// Cache for symbols to avoid repeated API calls
let symbolsCache: string[] | null = null;
let symbolsCacheExpiry: number = 0;
const SYMBOLS_CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
export const fetchBinanceSymbols = async (): Promise<string[]> => {
const now = Date.now();
// Return cached symbols if they're still valid
if (symbolsCache && symbolsCacheExpiry > now) {
return symbolsCache;
}
try {
const exchangeInfo = await fetchBinanceExchangeInfo();
if (exchangeInfo && exchangeInfo.symbols) {
const usdtSymbols = exchangeInfo.symbols
.filter(symbol =>
symbol.symbol.endsWith('USDT') &&
symbol.status === 'TRADING' &&
!symbol.symbol.includes('_') && // Exclude special pairs
!symbol.symbol.includes('DOWN') && // Exclude leveraged tokens
!symbol.symbol.includes('UP') &&
!symbol.symbol.includes('BULL') &&
!symbol.symbol.includes('BEAR')
)
.map(symbol => symbol.symbol);
// Update cache
symbolsCache = usdtSymbols;
symbolsCacheExpiry = now + SYMBOLS_CACHE_DURATION;
return usdtSymbols;
}
throw new Error('Invalid exchange info data');
} catch (error) {
console.error('Error fetching Binance symbols:', error);
// Return basic symbols as fallback
return ['BTCUSDT', 'ETHUSDT', 'BNBUSDT'];
}
};
export const fetchDataForSymbolAndTimeframe = async (symbol: string, timeframe: Timeframe, historicalData?: any[]): Promise<RSIData> => {
try {
// Use provided historical data or fetch new data
const candlestickData = historicalData || await fetchCandlestickData(symbol, timeframe);
if (!candlestickData || candlestickData.length < 2) {
throw new Error('Insufficient candlestick data');
}
// Get the latest price from the last candlestick
const lastCandle = candlestickData[candlestickData.length - 1];
const price = Array.isArray(lastCandle) && lastCandle.length >= 6 ? parseFloat(lastCandle[4]) : null;
// Calculate all indicators in parallel
const [rsi, macd, smaResults, emaResults, adx, vwap, bollingerBands, obv, fibonacci, cmf, ichimoku, atr, stochastic] = await Promise.all([
calculateRSIForSymbol(candlestickData),
calculateMACDForSymbol(candlestickData),
Promise.all([
calculateSMAForSymbol(candlestickData, 10),
calculateSMAForSymbol(candlestickData, 20),
calculateSMAForSymbol(candlestickData, 50),
calculateSMAForSymbol(candlestickData, 100),
calculateSMA200ForSymbol(candlestickData)
]),
Promise.all([
calculateEMAForSymbol(candlestickData, 10),
calculateEMAForSymbol(candlestickData, 20),
calculateEMAForSymbol(candlestickData, 50),
calculateEMAForSymbol(candlestickData, 100),
calculateEMA200ForSymbol(candlestickData)
]),
calculateADXForSymbol(candlestickData),
calculateVWAPForSymbol(candlestickData),
calculateBollingerBands(candlestickData),
calculateOBV(candlestickData),
calculateFibonacciRetracement(candlestickData),
calculateCMF(candlestickData),
calculateIchimokuCloud(candlestickData),
calculateATR(candlestickData),
calculateStochastic(candlestickData)
]);
const [sma10, sma20, sma50, sma100, sma200] = smaResults;
const [ema10, ema20, ema50, ema100, ema200] = emaResults;
// Calculate crossovers in parallel
const [isCrossoverSMA50200, isCrossoverEMA50200, isCrossoverSMA2050, isCrossoverEMA2050] = await Promise.all([
checkSMA50200Crossover(candlestickData),
checkEMA50200Crossover(candlestickData),
checkSMA2050Crossover(candlestickData),
checkEMA2050Crossover(candlestickData)
]);
let oscillators = 0;
let moving_averages = 0;
// RSI check
if (rsi <= 30) oscillators += 1;
else if (rsi >= 70) oscillators -= 1;
// MACD check
if (macd.histogram > 0) oscillators += 1;
else if (macd.histogram < 0) oscillators -= 1;
// Efficient SMA/EMA calculations using arrays
const indicators = [
{ value: sma10, price },
{ value: sma20, price },
{ value: sma50, price },
{ value: sma100, price },
{ value: sma200, price },
{ value: ema10, price },
{ value: ema20, price },
{ value: ema50, price },
{ value: ema100, price },
{ value: ema200, price },
];
moving_averages += indicators.reduce((acc, { value, price }) =>
value !== null ? (price! > value ? acc + 1 : acc - 1) : acc, 0);
return {
symbol,
rsi,
macd,
sma10,
sma20,
sma50,
sma100,
sma200,
isCrossoverSMA2050,
isCrossoverSMA50200,
moving_averages,
oscillators,
ema10,
ema20,
ema50,
ema100,
ema200,
isCrossoverEMA2050,
isCrossoverEMA50200,
price,
timeframe,
adx,
vwap,
bollingerBands,
obv,
fibonacci,
cmf,
ichimoku,
atr,
stochastic
};
} catch (error) {
console.error(`Error fetching data for ${symbol} ${timeframe}:`, error);
throw error;
}
};
export const createWebSocket = (symbols: string[], onMessage: (data: any) => void, onError: (error: any) => void): WsWebSocket | null => {
return createWebSocketConnection(symbols, onMessage, onError);
};
export const fetchGreedFear = async (): Promise<number | null> => {
try {
const index = await fetchGreedAndFearIndex();
return index;
} catch (error) {
console.error('Error fetching Greed and Fear Index:', error);
return null;
}
};