Commit 00545c54 authored by Cranky Kernel's avatar Cranky Kernel

webapp: dead code removal and reorg

parent a8d36254
Pipeline #53799906 passed with stage
in 13 minutes and 27 seconds
......@@ -14,99 +14,57 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import {Injectable} from "@angular/core";
import {HttpHeaders, HttpParams} from "@angular/common/http";
import {catchError, map} from "rxjs/operators";
import {Observable} from "rxjs";
import {throwError} from "rxjs/internal/observable/throwError";
import {OpenTradeOptions} from "./binance.service";
import {Observer} from "rxjs/Observer";
import {MakerApiService} from "./maker-api.service";
const API_ROOT = "/proxy/binance";
const STREAM_ROOT = "wss://stream.binance.com:9443";
@Injectable()
export class BinanceApiService {
constructor(private makerApi: MakerApiService) {
}
private get(path: string, params: HttpParams = null): Observable<Object> {
const url = `${API_ROOT}${path}`;
if (params == null) {
params = new HttpParams();
}
return this.makerApi.get(url, {
params: params,
});
openStream(path: string): Observable<any> {
const url = `${STREAM_ROOT}${path}`;
return makeWebSocketObservable(url);
}
}
private post(path: string, options?: {
params?: HttpParams;
headers?: HttpHeaders;
}, body: any = null) {
const headers = options && options.headers || new HttpHeaders();
const params = options && options.params || new HttpParams();
return this.makerApi.post(path, body, {
params: params,
headers: headers,
}).pipe(catchError((error) => {
if (error.error instanceof ErrorEvent) {
console.log("A client side error occurred: ");
console.log(error);
return throwError(error);
} else {
return throwError(error);
}
}));
}
function makeWebSocketObservable(url: string): Observable<any> {
return Observable.create((observer: Observer<any>) => {
private delete(path: string, params: HttpParams = null): Observable<any> {
return this.makerApi.delete(path, {
params: params,
});
}
let ws: WebSocket = null;
let closeRequested = false;
getAccountInfo(): Observable<BinanceAccountInfo> {
return this.makerApi.get("/api/binance/proxy/getAccount")
.pipe(map((restResponse: BinanceRestAccountInfoResrponse) => {
const accountInfo = BinanceAccountInfo.fromRest(restResponse);
return accountInfo;
}));
}
const openWebSocket = () => {
console.log(`websocket: connecting to ${url}.`);
ws = new WebSocket(url);
getExchangeInfo(): Observable<ExchangeInfo> {
const endpoint = "/api/v1/exchangeInfo";
return this.get(endpoint, null).pipe(map((info: RestExchangeInfoResponse) => {
return ExchangeInfo.fromRest(info);
}));
}
ws.onmessage = (event) => {
observer.next(JSON.parse(event.data));
};
postBuyOrder(body: OpenTradeOptions = null): Observable<BuyOrderResponse> {
const endpoint = "/api/binance/buy";
return <Observable<BuyOrderResponse>>this.post(endpoint, null, body);
}
ws.onerror = (event) => {
console.log(`websocket: error: ${url}: ${JSON.stringify(event)}`);
console.log(event);
observer.error(event);
};
cancelSellOrder(tradeId: string): Observable<CancelOrderResponse> {
const endpoint = "/api/binance/sell";
const params = new HttpParams().set("trade_id", tradeId);
return this.delete(endpoint, params);
}
ws.onclose = () => {
console.log(`websocket: closed ${url}.`);
if (!closeRequested) {
openWebSocket();
}
};
};
cancelBuy(tradeId: string): Observable<CancelOrderResponse> {
const endpoint = "/api/binance/buy";
const params = new HttpParams()
.set("trade_id", tradeId);
return this.delete(endpoint, params);
}
openWebSocket();
openStream(path: string): Observable<any> {
const url = `${STREAM_ROOT}${path}`;
return makeWebSocketObservable(url);
}
return () => {
closeRequested = true;
if (ws != null) {
ws.close();
}
};
});
}
/**
......@@ -199,7 +157,7 @@ export interface RestSymbolInfo {
filters: any[];
}
interface RestExchangeInfoResponse {
export interface RestExchangeInfoResponse {
symbols: RestSymbolInfo[];
}
......@@ -345,44 +303,3 @@ export function buildTickerFromStream(raw: StreamTicker): PriceTicker {
percentChange24: +raw.P,
};
}
function makeWebSocketObservable(url: string): Observable<any> {
return Observable.create((observer: Observer<any>) => {
let ws: WebSocket = null;
let closeRequested = false;
const openWebSocket = () => {
console.log(`websocket: connecting to ${url}.`);
ws = new WebSocket(url);
ws.onmessage = (event) => {
observer.next(JSON.parse(event.data));
};
ws.onerror = (event) => {
console.log(`websocket: error: ${url}: ${JSON.stringify(event)}`);
console.log(event);
observer.error(event);
};
ws.onclose = () => {
console.log(`websocket: closed ${url}.`);
if (!closeRequested) {
openWebSocket();
}
};
};
openWebSocket();
return () => {
closeRequested = true;
if (ws != null) {
ws.close();
}
};
});
}
......@@ -14,7 +14,8 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import {Component, OnInit} from '@angular/core';
import {BinanceAccountInfo, BinanceApiService, BinanceBalance} from "../binance-api.service";
import {BinanceAccountInfo, BinanceBalance} from "../binance-api.service";
import {BinanceProxyService} from "../binance-proxy.service";
@Component({
selector: 'app-binance-balances',
......@@ -27,7 +28,7 @@ export class BinanceBalancesComponent implements OnInit {
balances: BalanceEntry[] = [];
constructor(private binanceApi: BinanceApiService) {
constructor(private binanceProxy: BinanceProxyService) {
}
ngOnInit() {
......@@ -35,7 +36,7 @@ export class BinanceBalancesComponent implements OnInit {
}
refresh() {
this.binanceApi.getAccountInfo().subscribe((accountInfo) => {
this.binanceProxy.getAccountInfo().subscribe((accountInfo) => {
this.accountInfo = accountInfo;
this.balances = accountInfo.balances
.map((binanceBalance) => {
......
......@@ -17,30 +17,50 @@ import {Injectable} from '@angular/core';
import {HttpParams} from "@angular/common/http";
import {Observable} from "rxjs";
import {MakerApiService} from "./maker-api.service";
const REST_API_ROOT = "/proxy/binance";
import {map} from "rxjs/operators";
import {
BinanceAccountInfo,
BinanceRestAccountInfoResrponse,
ExchangeInfo,
RestExchangeInfoResponse
} from "./binance-api.service";
@Injectable({
providedIn: 'root'
})
export class BinanceRestApiService {
export class BinanceProxyService {
constructor(private makerApi: MakerApiService) {
}
private get(path: string, params: HttpParams = new HttpParams()): Observable<Object> {
const url = `${REST_API_ROOT}${path}`;
const url = `${path}`;
return this.makerApi.get(url, {
params: params,
});
}
getTicker24h(symbol: string): Observable<Ticker24hResponse> {
const endpoint = "/api/v1/ticker/24hr";
const endpoint = "/proxy/binance/api/v1/ticker/24hr";
const params = new HttpParams().set("symbol", symbol);
return <Observable<Ticker24hResponse>>this.get(endpoint, params);
}
getAccountInfo(): Observable<BinanceAccountInfo> {
return this.makerApi.get("/api/binance/proxy/getAccount")
.pipe(map((restResponse: BinanceRestAccountInfoResrponse) => {
const accountInfo = BinanceAccountInfo.fromRest(restResponse);
return accountInfo;
}));
}
getExchangeInfo(): Observable<ExchangeInfo> {
const endpoint = "/proxy/binance/api/v1/exchangeInfo";
return this.get(endpoint, null).pipe(map((info: RestExchangeInfoResponse) => {
return ExchangeInfo.fromRest(info);
}));
}
}
export interface Ticker24hResponse {
......
......@@ -18,11 +18,11 @@ import {BinanceApiService, buildTickerFromStream, ExchangeInfo, PriceTicker, Sym
import {map, multicast, refCount, take, tap} from "rxjs/operators";
import {Observable, Subject} from "rxjs";
import {ReplaySubject} from "rxjs/ReplaySubject";
import {Logger, LoggerService} from "./logger.service";
import {MakerService} from "./maker.service";
import {MakerApiService} from "./maker-api.service";
import {ToastrService} from "./toastr.service";
import {LoginService} from "./login.service";
import {BinanceProxyService} from "./binance-proxy.service";
/**
* Enum of types that can be used as a price source.
......@@ -66,17 +66,16 @@ export class BinanceService {
streams$: { [key: string]: Observable<any> } = {};
private isReadySubject: Subject<boolean> = null;
public isReady$: Observable<boolean> = null;
private logger: Logger = null;
public isReady$: Observable<boolean> = null;
constructor(private api: BinanceApiService,
private maker: MakerService,
private makerApi: MakerApiService,
private toastr: ToastrService,
private loginService: LoginService,
logger: LoggerService) {
this.logger = logger.getLogger("binance.service");
private binanceProxy: BinanceProxyService,
) {
this.isReadySubject = new ReplaySubject<boolean>(1);
this.isReady$ = this.isReadySubject.pipe(take(1));
this.loginService.$onLogin.asObservable().pipe(take(1))
......@@ -86,19 +85,14 @@ export class BinanceService {
}
private init() {
console.log("BinanceServer.init()");
// Get config then do initialization that depends on config.
this.makerApi.getConfig().subscribe((config) => {
this.makerApi.getConfig().subscribe(() => {
this.updateExchangeInfo().subscribe(() => {
this.isReadySubject.next(true);
});
});
}
postBuyOrder(body: OpenTradeOptions) {
return this.api.postBuyOrder(body);
}
subscribeToTicker(symbol: string): Observable<PriceTicker> {
const stream = `${symbol.toLowerCase()}@ticker`;
if (!this.streams$[stream]) {
......@@ -116,7 +110,7 @@ export class BinanceService {
}
updateExchangeInfo(): Observable<ExchangeInfo> {
return this.api.getExchangeInfo().pipe(tap((exchangeInfo) => {
return this.binanceProxy.getExchangeInfo().pipe(tap((exchangeInfo) => {
const quoteAssets: any = {};
exchangeInfo.symbols.forEach((symbol) => {
......
......@@ -17,19 +17,19 @@ import {Injectable} from "@angular/core";
import {BehaviorSubject} from "rxjs/BehaviorSubject";
import {Subject} from "rxjs/Subject";
import {
BinanceAccountInfo,
AggTrade,
BinanceAccountInfo,
BinanceApiService,
buildAggTradeFromStream,
CancelOrderResponse,
BinanceStreamAccountInfoResponse,
buildAggTradeFromStream, BuyOrderResponse,
CancelOrderResponse,
StreamAggTrade
} from "./binance-api.service";
import {HttpParams} from "@angular/common/http";
import {Logger, LoggerService} from "./logger.service";
import {Observable} from "rxjs";
import {ToastrService} from './toastr.service';
import {LimitSellType} from './binance.service';
import {LimitSellType, OpenTradeOptions} from './binance.service';
import {GIT_REVISION, VERSION} from "../environments/version";
import {take} from "rxjs/operators";
import {LoginService} from "./login.service";
......@@ -186,15 +186,22 @@ export class MakerService {
});
}
cancelBuy(trade: TradeState) {
this.binanceApi.cancelBuy(trade.TradeID).subscribe((response) => {
}, (error) => {
console.log("Failed to cancel buy order: " + JSON.stringify(error));
});
cancelBuy(tradeId: string): Observable<CancelOrderResponse> {
const endpoint = "/api/binance/buy";
const params = new HttpParams()
.set("trade_id", tradeId);
return this.makerApi.delete(endpoint, params);
}
cancelSell(trade: TradeState): Observable<CancelOrderResponse> {
return this.binanceApi.cancelSellOrder(trade.TradeID);
const endpoint = "/api/binance/sell";
const params = new HttpParams().set("trade_id", trade.TradeID);
return this.makerApi.delete(endpoint, params);
}
postBuyOrder(body: OpenTradeOptions): Observable<BuyOrderResponse> {
const endpoint = "/api/binance/buy";
return <Observable<BuyOrderResponse>>this.makerApi.post(endpoint, body, null);
}
limitSellByPercent(trade: TradeState, percent: number) {
......
......@@ -25,6 +25,7 @@ import {Logger, LoggerService} from "../logger.service";
import {ToastrService} from "../toastr.service";
import {AppTradeState} from '../trade-table/trade-table.component';
import * as $ from "jquery";
import {BinanceApiService} from "../binance-api.service";
interface SellAtPriceModel {
price: number;
......@@ -113,6 +114,7 @@ export class TradeTableRowComponent implements OnInit, OnDestroy, AfterViewInit
constructor(public maker: MakerService,
private toastr: ToastrService,
private binanceApi: BinanceApiService,
logger: LoggerService) {
this.logger = logger.getLogger("TradeTableRowComponent");
}
......@@ -145,7 +147,10 @@ export class TradeTableRowComponent implements OnInit, OnDestroy, AfterViewInit
}
cancelBuy() {
this.maker.cancelBuy(this.trade);
this.maker.cancelBuy(this.trade.TradeID).subscribe(() => {
}, (error) => {
console.log("Failed to cancel buy order: " + JSON.stringify(error));
});
}
cancelSell() {
......
......@@ -29,7 +29,7 @@ import {FormBuilder, FormGroup} from "@angular/forms";
import {ToastrService} from "../toastr.service";
import {TradeTableComponent} from '../trade-table/trade-table.component';
import {ActivatedRoute, Router} from '@angular/router';
import {BinanceRestApiService} from "../binance-rest-api.service";
import {BinanceProxyService} from "../binance-proxy.service";
declare var window: any;
......@@ -141,7 +141,7 @@ export class TradeComponent implements OnInit, OnDestroy, AfterViewInit {
private route: ActivatedRoute,
private router: Router,
logger: LoggerService,
private binanceRestApi: BinanceRestApiService,
private binanceProxy: BinanceProxyService,
) {
this.logger = logger.getLogger("trade-component");
}
......@@ -276,7 +276,7 @@ export class TradeComponent implements OnInit, OnDestroy, AfterViewInit {
}
private updateAccountInfo(): Observable<BinanceAccountInfo> {
return this.api.getAccountInfo().pipe(tap((accountInfo) => {
return this.binanceProxy.getAccountInfo().pipe(tap((accountInfo) => {
console.log("Updating account info.");
this.updateBalances(accountInfo);
}));
......@@ -341,7 +341,7 @@ export class TradeComponent implements OnInit, OnDestroy, AfterViewInit {
return;
}
this.binanceRestApi.getTicker24h(symbol).subscribe((response) => {
this.binanceProxy.getTicker24h(symbol).subscribe((response) => {
this.ticker.last = +response.lastPrice;
this.ticker.percentChange24 = +response.priceChangePercent;
this.ticker.vol24 = +response.quoteVolume;
......@@ -434,7 +434,7 @@ export class TradeComponent implements OnInit, OnDestroy, AfterViewInit {
options.limitSellPrice = +this.orderForm.limitSellPrice;
}
this.binance.postBuyOrder(options).subscribe(() => {
this.maker.postBuyOrder(options).subscribe(() => {
}, (error) => {
console.log("Failed to post order:");
console.log(error);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment