Skip to content

Instantly share code, notes, and snippets.

@clintonyeb
Created May 19, 2020 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clintonyeb/7dcb01c4c7193febf3ce34aeb976db88 to your computer and use it in GitHub Desktop.
Save clintonyeb/7dcb01c4c7193febf3ce34aeb976db88 to your computer and use it in GitHub Desktop.
import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
currency = '';
currencies;
tickCount = 0;
pipDiff = 0;
buyOrSell = '';
ticker = 0;
movavg = 0;
webSocket;
averages;
constructor(private appService: AppService) {}
ngOnInit(): void {
this.appService.getCcyPair().subscribe((data: Array<any>) => {
this.currencies = data.map((d) => d['currency_name']);
this.currency = this.currencies[0];
});
}
handleSubmit() {
this.wsSend({
currencyPair: this.currency,
});
}
wsSend(message) {
if (this.webSocket) {
this.webSocket.close();
}
this.averages = [];
const messageValue = JSON.stringify(message);
this.webSocket = this.initializeWS(messageValue);
}
initializeWS(message) {
const webSocket = new WebSocket('wss://stocksimulator.coderiq.io');
webSocket.onopen = (evt) => {
console.log('Connected to WebSocket...');
webSocket.send(message);
console.log('SENT: ' + message);
};
webSocket.onclose = (evt) => {
console.log('Disconnected from WebSocket...');
};
webSocket.onerror = (evt) => {
console.log('Error in WebSocket: ');
};
function getAvg(arr): number {
let sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += parseFloat(arr[i]); //don't forget to add the base
}
const avg = Number(sum / arr.length);
return Math.round(avg * 10000) / 10000;
}
webSocket.onmessage = (evt) => {
console.log('message');
const pipDiff = this.pipDiff;
const tickCount = this.tickCount - 1;
const averages = this.averages.slice(-1 * tickCount);
averages.push(evt.data);
if (averages.length >= tickCount) {
const avg = getAvg(averages);
const price = Math.round(evt.data * 10000) / 10000;
const diff = (avg - price) * 10000;
let buyOrSell = '';
if (Math.abs(diff) > pipDiff) {
if (price > avg) {
buyOrSell = 'SELL';
} else {
buyOrSell = 'BUY';
}
} else {
buyOrSell = '';
}
this.movavg = avg;
this.ticker = price;
this.buyOrSell = buyOrSell;
console.log(this.movavg, this.ticker, this.buyOrSell);
}
this.averages = averages;
};
return webSocket;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment