app.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const websocket = new Vue({
  2. el: "#websocket",
  3. created: () => {
  4. this.socket = new WebSocket("wss://api-pub.bitfinex.com/ws/2")
  5. this.socket.onopen = () => {
  6. websocket.connected = true
  7. };
  8. this.socket.onclose = () => {
  9. websocket.info = "";
  10. websocket.connected = false;
  11. };
  12. this.socket.onmessage = (message) => {
  13. json = JSON.parse(message.data);
  14. if (json.event == "info") websocket.info = `Server ${json.serverId} v${json.version}`;
  15. if (Array.isArray(json) && json[1] !== "hb") websocket.processValues(json);
  16. };
  17. },
  18. data: {
  19. connected: false,
  20. info: "",
  21. socket: undefined
  22. },
  23. methods: {
  24. processCandle: (candle) => {
  25. console.log(candle);
  26. },
  27. processValues: (json) => {
  28. if (Array.isArray(json[1][0])) {
  29. json[1].forEach((data) => websocket.processCandle(data));
  30. } else {
  31. websocket.processCandle(json[1]);
  32. }
  33. }
  34. },
  35. watch: {
  36. connected: (connected) => {
  37. if (connected === true) this.socket.send('{"event":"subscribe","channel":"candles","key":"trade:1m:tBTCUSD"}');
  38. }
  39. }
  40. });