| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- const graph = new Vue({
- el: "#graph",
- data: {
- candles: [],
- latest: undefined
- },
- methods: {
- addCandle: (candle) => {
- graph.candles.push({
- date: candle[0],
- value: candle[2]
- });
- graph.latest = new Date(candle[0]);
- }
- },
- watch: {
- candles: (values) => {
- sorted = values.slice();
- sorted.sort((a, b) => {
- if (a.date < b.date) return -1;
- if (a.date > b.date) return 1;
- return 0;
- });
- dates = sorted.map((d) => d.date);
- for (let i=0; i<30; i++) {
- last = dates[dates.length - 1];
- dates.push(last + 60000);
- }
- d3.select("#data").select("g").remove();
- element = document.querySelector("#chart-space");
- margin = {
- top: 10,
- right: 30,
- bottom: 100,
- left: 60
- }
- height = element.clientHeight - margin.top - margin.bottom;
- width = element.clientWidth - margin.left - margin.right;
- svg = d3.select("#data")
- .append("g")
- .attr("transform", `translate(${margin.left}, ${margin.top})`);
- x = d3.scaleTime()
- .domain(d3.extent(dates, (d) => { return d }))
- .range([ 0, width ]);
- svg.append("g")
- .attr("transform", `translate(0, ${height})`)
- .call(d3.axisBottom(x));
- y = d3.scaleLinear()
- .domain([0, d3.max(sorted, (d) => { return +d.value })])
- .range([ height, 0 ]);
- svg.append("g")
- .call(d3.axisLeft(y));
- svg.append("path")
- .datum(sorted)
- .attr("fill", "none")
- .attr("stroke", "black")
- .attr("stroke-width", 2)
- .attr("d", d3.line().x((d) => {
- return x(d.date);
- }).y((d) => {
- return y(d.value);
- }));
- }
- }
- });
- const websocket = new Vue({
- el: "#websocket",
- created: () => {
- this.socket = new WebSocket("wss://api-pub.bitfinex.com/ws/2")
- this.socket.onopen = () => {
- websocket.connected = true
- };
- this.socket.onclose = () => {
- websocket.info = "";
- websocket.connected = false;
- };
- this.socket.onmessage = (message) => {
- json = JSON.parse(message.data);
- if (json.event == "info") websocket.info = `Server ${json.serverId} v${json.version}`;
- if (Array.isArray(json) && json[1] !== "hb") websocket.processValues(json);
- };
- },
- data: {
- connected: false,
- info: "",
- socket: undefined
- },
- methods: {
- processCandle: (candle) => {
- graph.addCandle(candle);
- },
- processValues: (json) => {
- if (Array.isArray(json[1][0])) {
- json[1].forEach((data) => websocket.processCandle(data));
- } else {
- websocket.processCandle(json[1]);
- }
- }
- },
- watch: {
- connected: (connected) => {
- if (connected === true) this.socket.send('{"event":"subscribe","channel":"candles","key":"trade:1m:tBTCUSD"}');
- }
- }
- });
|