aster_ws_example.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import 'dotenv/config'
  2. import { AsterWsClient } from '../src/exchanges/aster/wsClient'
  3. import { loadAsterConfig, toAsterWsConfig, toAsterAuthConfig } from '../src/config/asterConfig'
  4. async function main() {
  5. console.log('🚀 开始 Aster WebSocket 示例...\n')
  6. try {
  7. // 从环境变量加载配置
  8. const config = loadAsterConfig()
  9. const wsConfig = toAsterWsConfig(config)
  10. const authConfig = toAsterAuthConfig(config)
  11. console.log('📋 配置信息:')
  12. console.log(` WS URL: ${config.ws.url}`)
  13. console.log(` User: ${config.auth.user}`)
  14. console.log(` Signer: ${config.auth.signer}`)
  15. console.log(` 订阅交易对: ${config.subscribe.symbols.join(', ')}`)
  16. console.log('')
  17. const client = new AsterWsClient(wsConfig, authConfig)
  18. client.on('open', () => console.log('Aster WS connected'))
  19. client.on('close', (c, r) => console.log('Aster WS closed', c, r))
  20. client.on('error', e => console.error('Aster WS error', e))
  21. client.on('ticker', t => console.log('ticker', t))
  22. client.on('trade', t => console.log('trade', t))
  23. client.on('depth', d => console.log('depth', d.symbol, d.bids.length, d.asks.length))
  24. client.on('kline', k => console.log('kline', k.symbol, k.interval, k.close))
  25. client.connect()
  26. // 订阅:根据配置的交易对进行订阅(按照 Aster 文档格式)
  27. const subscriptions: any[] = []
  28. for (const symbol of config.subscribe.symbols) {
  29. subscriptions.push(
  30. { channel: 'aggTrade', symbol }, // 归集交易
  31. { channel: 'markPrice', symbol }, // 标记价格
  32. { channel: 'depth', symbol, depth: 20 }, // 深度数据
  33. )
  34. }
  35. client.subscribe(subscriptions)
  36. // 运行 10 秒后退出
  37. setTimeout(() => {
  38. try {
  39. client.unsubscribe(subscriptions)
  40. client.disconnect()
  41. console.log('🎉 Aster WebSocket 示例完成!')
  42. } finally {
  43. process.exit(0)
  44. }
  45. }, 10000)
  46. } catch (error) {
  47. console.error('❌ 配置加载失败:', error)
  48. process.exit(1)
  49. }
  50. }
  51. main().catch(console.error)