File size: 8,140 Bytes
66b7a93
 
 
a66b025
66b7a93
 
 
 
 
 
ebfcd8b
66b7a93
 
 
 
 
 
 
 
 
 
 
 
 
a87a76b
 
 
 
66b7a93
 
 
 
a66b025
66b7a93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebfcd8b
 
66b7a93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebfcd8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66b7a93
 
 
 
 
 
 
 
 
 
 
 
ba1d9b3
66b7a93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebfcd8b
 
 
 
 
66b7a93
 
 
 
 
 
 
 
 
 
 
ebfcd8b
66b7a93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * dataManager.js
 * Unified data interface that routes historical and real-time data requests
 * to the correct provider (Binance or Yahoo Finance) based on the symbol.
 */

import { fetchKlines, fetchTickerPrice }  from './binanceAPI.js';
import { BinanceStream }              from './binanceWebSocket.js';
import { fetchCandles as fetchYahooCandles, fetchQuote as fetchYahooQuote } from './yahooFinanceAPI.js';
import { YahooStream }                from './yahooWebSocket.js';
import { ServerStream }               from './serverStream.js';

/* -------------------------------------------------------------------- */
/*  Configuration maps                                                  */
/* -------------------------------------------------------------------- */

/**
 * Per-symbol configuration.
 * `provider`    – which API back-end to use
 * `wsSymbol`    – symbol string expected by the WebSocket layer
 * `displayName` – human-readable label for the UI
 * `type`        – asset class
 */
export const SYMBOL_CONFIG = {
  BTCUSDT: { provider: 'yahoo',   wsSymbol: 'BTC-USD',        displayName: 'BTC/USDT', type: 'crypto'    },
  XAUUSD:  { provider: 'yahoo',   wsSymbol: 'GC=F',           displayName: 'XAU/USD',  type: 'commodity' },
  GBPUSD:  { provider: 'yahoo',   wsSymbol: 'GBPUSD=X',       displayName: 'GBP/USD',  type: 'forex'     },
  USDCAD:  { provider: 'yahoo',   wsSymbol: 'USDCAD=X',       displayName: 'USD/CAD',  type: 'forex'     },
};

/**
 * Maps the app's timeframe labels to each provider's native format
 * and stores the duration in seconds.
 */
export const TIMEFRAME_MAP = {
  '1m':  { binance: '1m',  finnhub: '1',   seconds: 60     },
  '5m':  { binance: '5m',  finnhub: '5',   seconds: 300    },
  '15m': { binance: '15m', finnhub: '15',  seconds: 900    },
  '1H':  { binance: '1h',  finnhub: '60',  seconds: 3600   },
  '4H':  { binance: '4h',  finnhub: '240', seconds: 14400  },
  '1D':  { binance: '1d',  finnhub: 'D',   seconds: 86400  },
};

/* -------------------------------------------------------------------- */
/*  DataManager class                                                   */
/* -------------------------------------------------------------------- */

const HISTORY_CANDLES = 500; // number of candles to load

export default class DataManager {
  constructor() {
    /** @type {BinanceStream} */
    this._binanceStream = new BinanceStream();
    /** @type {YahooStream} */
    this._yahooStream = new YahooStream();
    /** @type {ServerStream} */
    this._serverStream = new ServerStream();
  }

  /* ------------------------------------------------------------------ */
  /*  Historical data                                                   */
  /* ------------------------------------------------------------------ */

  /**
   * Load historical OHLCV candles for the given symbol and timeframe.
   *
   * @param {string} symbol    - e.g. 'BTCUSDT', 'XAUUSD'
   * @param {string} timeframe - e.g. '1m', '1H', '1D'
   * @returns {Promise<Array<{time:number, open:number, high:number, low:number, close:number, volume:number}>>}
   */
  async loadHistory(symbol, timeframe) {
    const config = this._requireSymbol(symbol);
    const tf     = this._requireTimeframe(timeframe);

    if (config.provider === 'binance') {
      return this._loadBinanceHistory(symbol, tf);
    }

    return this._loadYahooHistory(symbol, timeframe);
  }

  /** @private */
  async _loadBinanceHistory(symbol, tf) {
    console.log(`[DataManager] Loading Binance history: ${symbol} ${tf.binance}`);
    return fetchKlines(symbol, tf.binance, HISTORY_CANDLES);
  }

  /** @private */
  async _loadYahooHistory(symbol, timeframe) {
    // For the server's native 15m timeframe, prefer the server's cached candles so
    // the browser doesn't hit Yahoo directly. Fall back to Yahoo if the cache is cold.
    if (timeframe === '15m') {
      try {
        const res = await fetch(`/api/market-data?symbol=${encodeURIComponent(symbol)}`);
        if (res.ok) {
          const data = await res.json();
          if (data.candles && data.candles.length > 50) {
            console.log(`[DataManager] Loaded ${data.candles.length} candles from server cache: ${symbol}`);
            return data.candles;
          }
        }
      } catch (err) {
        console.warn(`[DataManager] Server cache unavailable for ${symbol}, falling back to Yahoo:`, err.message);
      }
    }
    console.log(`[DataManager] Loading Yahoo history: ${symbol} ${timeframe}`);
    return fetchYahooCandles(symbol, timeframe);
  }

  /**
   * Fetch current market price for a symbol (lightweight REST query).
   *
   * @param {string} symbol
   * @returns {Promise<number>}
   */
  async fetchCurrentPrice(symbol) {
    const config = this._requireSymbol(symbol);

    if (config.provider === 'binance') {
      return fetchTickerPrice(symbol);
    } else {
      const quote = await fetchYahooQuote(symbol);
      return quote.current;
    }
  }

  /* ------------------------------------------------------------------ */
  /*  Real-time streaming                                               */
  /* ------------------------------------------------------------------ */

  /**
   * Subscribe to real-time updates for the given symbol and timeframe.
   *
   * @param {string} symbol    - e.g. 'BTCUSDT', 'XAUUSD'
   * @param {string} timeframe - e.g. '1m', '1H'
   * @param {{ onCandleUpdate?: (candle: object) => void, onTick?: (price: number) => void }} callbacks
   */
  subscribeRealtime(symbol, timeframe, callbacks) {
    const config = this._requireSymbol(symbol);
    const tf     = this._requireTimeframe(timeframe);

    if (config.provider === 'binance') {
      console.log(`[DataManager] Subscribing Binance stream: ${config.wsSymbol} ${tf.binance}`);
      this._binanceStream.subscribe(config.wsSymbol, tf.binance, callbacks);
    } else if (timeframe === '15m') {
      // Default timeframe served from the server's shared cache so each browser
      // doesn't poll Yahoo directly (server is the single upstream poller).
      console.log(`[DataManager] Subscribing server-cache stream: ${symbol} ${timeframe}`);
      this._serverStream.subscribe(symbol, timeframe, callbacks);
    } else {
      console.log(`[DataManager] Subscribing Yahoo stream: ${symbol} ${timeframe}`);
      this._yahooStream.subscribe(symbol, timeframe, callbacks);
    }
  }

  /** Disconnect all active WebSocket streams. */
  unsubscribeAll() {
    console.log('[DataManager] Unsubscribing all streams');
    this._binanceStream.unsubscribe();
    this._yahooStream.unsubscribe();
    this._serverStream.unsubscribe();
  }

  /* ------------------------------------------------------------------ */
  /*  Accessors                                                         */
  /* ------------------------------------------------------------------ */

  /**
   * Get the configuration object for a symbol.
   * @param {string} symbol
   * @returns {{ provider: string, wsSymbol: string, displayName: string, type: string }}
   */
  getSymbolConfig(symbol) {
    return SYMBOL_CONFIG[symbol] ?? null;
  }

  /**
   * List all supported symbol keys.
   * @returns {string[]}
   */
  getSymbols() {
    return Object.keys(SYMBOL_CONFIG);
  }

  /**
   * List all supported timeframe keys.
   * @returns {string[]}
   */
  getTimeframes() {
    return Object.keys(TIMEFRAME_MAP);
  }

  /* ------------------------------------------------------------------ */
  /*  Validation helpers                                                */
  /* ------------------------------------------------------------------ */

  /** @private */
  _requireSymbol(symbol) {
    const config = SYMBOL_CONFIG[symbol];
    if (!config) {
      throw new Error(`[DataManager] Unknown symbol: "${symbol}". Available: ${this.getSymbols().join(', ')}`);
    }
    return config;
  }

  /** @private */
  _requireTimeframe(timeframe) {
    const tf = TIMEFRAME_MAP[timeframe];
    if (!tf) {
      throw new Error(`[DataManager] Unknown timeframe: "${timeframe}". Available: ${this.getTimeframes().join(', ')}`);
    }
    return tf;
  }
}