HTML5 WebSocket

by gschutz

HTML

<script src="https://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/highcharts-vue.min.js"></script>

<div id="app">
  <div class="title-row">
    <p>Set the request data:</p>
    <input type="text" v-model="requestData">
    <button @click="request()">Send</button>
  </div>
  <highcharts :options="chartOptions"></highcharts>
</div>

<input id="message" />
<div id="output"></div>

JavaScript

var message = document.getElementById("message"),
    output = document.getElementById("output");
   
function sendMessage(message) {
    output.innerHTML += "<p>&gt; SENT: " + message + "</p>";
    websocket.send(message);
}


/* ---- EXAMPLE plotting ----- */

Vue.use(HighchartsVue.default)

var app = new Vue({
  el: "#app",
  data() {
    return {
      chartOptions: {
        chart: {
          type: 'spline'
        },
        title: {
          text: 'Entire title'
        },
        series: [{
          data: Array.from({
            length: 40
          }, () => Math.floor(Math.random() * 40))
        }]
      },
      title: ''
    }
  },
  methods: {
  	request: function() {
    	sendMessage(this.requestData);
    },
    updateChart: function(series) {
    	this.chartOptions.series = series;
      /* this.chartOptions.series.push({
        name: "Series " + this.chartOptions.series.length,
        data: Array.from({
          length: 40
        }, () => Math.floor(Math.random() * 40))
            }); */
    }
  },
  watch: {
    title2(newValue) {
      if (newValue === '') {
        this.chartOptions.title.text = 'Bloomberg Stocks'
      } else {
        this.chartOptions.title.text = newValue
      }

    }
  }
});



websocket = new WebSocket("ws://localhost:8766/");
websocket.onopen = function() {
    output.innerHTML += "<p>&gt; CONNECTED</p>";
};

websocket.onmessage = function(e) { 
    output.innerHTML += "<p style='color: blue;'>&gt; RESPONSE: </p>";
    var result = JSON.parse(e.data);
    var textResult = JSON.stringify(result, null, 4);
    output.innerHTML += "<pre>"+textResult+"</pre>";
    var series = [];
    result.results.forEach(function(msg) {
    	if (msg.securityData) {
      	var serie = {};
      	serie.data = msg.securityData.fieldData.map((d) => [d.date, d.PX_LAST]);
        serie.name = msg.securityData.security;
        series.push(serie);
      }
    })
    app.updateChart(series)
};

websocket.onerror = function(e) {
   ...