(symbol1: string, symbol2: string, type1: 'crypto' | 'fiat', type2: 'crypto' | 'fiat')
| 354 | |
| 355 | // 情况1: 加密货币 -> 加密货币 |
| 356 | if (type1 === 'crypto' && type2 === 'crypto') { |
| 357 | return await this.getCryptoCryptoPrice(s1, s2); |
| 358 | } |
| 359 | |
| 360 | // 情况2: 加密货币 -> 法币 |
| 361 | if (type1 === 'crypto' && type2 === 'fiat') { |
| 362 | return await this.getCryptoFiatPrice(s1, s2); |
| 363 | } |
| 364 | |
| 365 | // 情况3: 法币 -> 加密货币 |
| 366 | if (type1 === 'fiat' && type2 === 'crypto') { |
| 367 | try { |
| 368 | const cryptoToFiat = await this.getCryptoFiatPrice(s2, s1); |
| 369 | return { price: 1 / cryptoToFiat.price, lastUpdated: cryptoToFiat.lastUpdated }; |
| 370 | } catch (error) { |
| 371 | throw new Error(`无法获取 ${s2} 对 ${s1} 的价格来计算反向汇率`); |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | // 情况4: 法币 -> 法币 |
| 376 | if (type1 === 'fiat' && type2 === 'fiat') { |
| 377 | const rates = await this.fetchFiatRates(s1.toLowerCase()); |
| 378 | const rate = rates[s2.toLowerCase()]; |
| 379 | if (!rate) throw new Error(`无法获取 ${s1} 到 ${s2} 的汇率`); |
| 380 | return { price: rate, lastUpdated: new Date() }; |
| 381 | } |
| 382 | |
| 383 | throw new Error(`不支持的货币类型组合: ${type1} -> ${type2}`); |
| 384 | } |
| 385 | |
| 386 | // 加密货币对加密货币 |
| 387 | private async getCryptoCryptoPrice(crypto1: string, crypto2: string): Promise<{ price: number, lastUpdated: Date }> { |
| 388 | // 1. 直接交易对 |
| 389 | try { |
| 390 | const price = await this.fetchBinancePrice(`${crypto1}${crypto2}`); |
| 391 | return { price, lastUpdated: new Date() }; |
| 392 | } catch {} |
no test coverage detected