import {EventEmitter} from 'events'; import { Dashboard, Decimal, Market, SpotOrder, defaultDashboard, } from '@ex-master/core'; import {interval, merge, of} from 'rxjs'; import {exhaustMap} from 'rxjs/operators'; import {ZBSpotClient} from './zb-spot-client'; const TICK_INTERVAL = 1000; const RECHARGE_SIZE_DEBOUNCE_RATE = 0.1; export type ZBRechargerStatus = 'sufficient' | 'low' | 'insufficient'; export interface ZBRechargerOptions { moneyKey: string | string[]; max: number; min: number; dashboard?: Dashboard; } export class ZBRecharger extends EventEmitter { private markets: Market[]; private _amount = new Decimal(0); private _recharging = false; private openedOrder: SpotOrder | undefined; private dashboard = this.options.dashboard || defaultDashboard; private previousStatus: ZBRechargerStatus | undefined; get maxAmount(): number { return this.options.max; } get minAmount(): number { return this.options.min; } get amount(): number { return this._amount.toNumber(); } get recharging(): boolean { return this._recharging; } get status(): ZBRechargerStatus { if (this._amount.isZero()) { return 'insufficient'; } else if (this._amount.lessThan(this.minAmount)) { return 'low'; } else { return 'sufficient'; } } constructor( private spotClient: ZBSpotClient, private options: ZBRechargerOptions, ) { super(); let moneyKeys = typeof this.options.moneyKey === 'string' ? [this.options.moneyKey] : this.options.moneyKey; this.markets = moneyKeys.map(moneyKey => ({stock: 'zb', money: moneyKey})); merge(of(0), interval(TICK_INTERVAL)) .pipe( exhaustMap(async () => { try { await this.tick(); } catch (error) { this.dashboard.error(`ZB-RECHARGER ${error.message}`); } }), ) .subscribe(() => {}); } private async tick(): Promise { await this.spotClient.ready; const balances = await this.spotClient.getBalances(); let available = new Decimal(0); let frozen = new Decimal(0); for (const balance of balances) { if (balance.currency === 'zb') { available = balance.available; frozen = balance.frozen; break; } } let balance = available.add(frozen); let previousStatus = this.previousStatus; this._amount = balance; let currentStatus = this.status; if (previousStatus !== currentStatus) { this.emit('status-change', previousStatus, currentStatus); } this.previousStatus = currentStatus; if (!this._recharging && balance.greaterThanOrEqualTo(this.minAmount)) { return; } if ( (this._recharging && balance.lessThan(this.maxAmount)) || balance.lessThan(this.minAmount) ) { this.recharge(Decimal.sub(this.maxAmount, balance)).catch(error => console.error(error), ); } else if (this._recharging) { this._recharging = false; this.emit('recharged'); await this.cancel(); } } private async recharge(amount: Decimal): Promise { let market: Market | undefined; let price!: number; for (let targetMarket of this.markets) { let operationMoney = this.spotClient.getBalance(targetMarket.money) .available; if (operationMoney.isZero()) { continue; } if ( this.openedOrder && this.openedOrder.active && this.openedOrder.market.money === targetMarket.money ) { operationMoney = operationMoney.add( this.openedOrder.value.sub(this.openedOrder.filledValue), ); } const depth = await this.spotClient.getDepth(targetMarket, 1); price = depth.asks[0][0]; if (amount.mul(price).lessThan(operationMoney)) { market = targetMarket; break; } } if (!market) { await this.cancel(); return; } let orderSize = this.spotClient.ensureSizePrecision(market, amount, 'down'); let orderPrice = new Decimal(price); if ( orderSize .mul(orderPrice) .greaterThan(this.spotClient.getMinOrderValue(market)) ) { if (!this._recharging) { this._recharging = true; this.emit('recharging'); } let openedOrder = this.openedOrder; let minPriceDiff = this.spotClient.getMinPriceDiff(market).toNumber(); if ( openedOrder && openedOrder.market.money === market.money && openedOrder.active && openedOrder.price.sub(orderPrice).greaterThan(minPriceDiff) && Decimal.abs(openedOrder.size.sub(orderSize)).lessThanOrEqualTo( openedOrder.size.mul(RECHARGE_SIZE_DEBOUNCE_RATE), ) ) { return; } if (this.openedOrder) { await this.cancel(); return; } this.dashboard.info( `ZB-RECHARGER ${market.stock}-${market.money} bid ${orderPrice} x ${orderSize}`, ); this.openedOrder = await this.spotClient.order( market, 'bid', orderPrice, orderSize, ); } else { this._recharging = false; this.emit('recharged'); await this.cancel(); return; } } private async cancel(): Promise { const openedOrder = this.openedOrder; if (!openedOrder || !openedOrder.active) { this.openedOrder = undefined; return; } if (openedOrder) { try { this.dashboard.info( `ZB-RECHARGER cancel ${openedOrder.market.stock}-${openedOrder.market.money} ${openedOrder.id}`, ); await this.spotClient.cancelOrder({ market: openedOrder.market, id: openedOrder.id, }); this.openedOrder = undefined; } catch (error) { let openedOrders = await this.spotClient.getOpenOrders(); let canceled = true; for (let {id} of openedOrders) { if (openedOrder.id === id) { canceled = false; break; } } if (canceled) { this.openedOrder = undefined; } else { throw error; } } } } } export interface ZBRecharger { on(event: 'error', listener: (error: Error) => void): this; on( event: 'status-change', listener: (status: ZBRechargerStatus) => void, ): this; off(event: 'error', listener: (error: Error) => void): this; off( event: 'status-change', listener: (status: ZBRechargerStatus) => void, ): this; addEventListener(event: 'error', listener: (error: Error) => void): this; addEventListener( event: 'status-change', listener: (status: ZBRechargerStatus) => void, ): this; removeEventListener(event: 'error', listener: (error: Error) => void): this; removeEventListener( event: 'status-change', listener: (status: ZBRechargerStatus) => void, ): this; }