// 2023年07月06日13:40:33 import dayjs from 'dayjs'; import { Trader } from '.'; import { ExchangeX, OrderX } from '../exchange'; import { Market } from 'ccxt'; export class FullTrader extends Trader { public constructor( private name: string, private exchange: ExchangeX, assets: { [name: string]: number } = { }, private message?: (data: any) => void, ) { super(assets); } private valuation(symbol: string, price: number) { const market: Market = this.exchange.Exchange.market(symbol); return this.Get(market.base) * price + this.Get(market.quote); } private sendOrderMessage(order: OrderX) { const data = { name: this.name, time: dayjs(order.timestamp).format('HH:mm:ss.SSS'), symbol: order.symbol, side: order.side, in_amount: order.side === 'buy' ? order.cost : order.amount, out_amount: order.side === 'buy' ? order.amount : order.cost, final_price: order.price, assets: this.Assets(), valuation: this.valuation(order.symbol, order.price), order_time: `${(order.end_time - order.start_time) / 1000}s`, }; this.message?.(JSON.stringify(data, null, 2)); } public async MarketOpenFull(symbol: string) { try { const market = this.exchange.Exchange.market(symbol); if (this.Get(market.quote) <= 0) return; const order = await this.exchange.MarketOpen(symbol, this.Get(market.quote)); this.Send(market.quote, order.cost); this.Receive(market.base, order.amount); order.fee_list.forEach((fee) => this.Send(fee.currency, fee.cost)); this.sendOrderMessage(order); return order; } catch (e) { this.message?.(JSON.stringify(e, null, 2)); } } public async MarketCloseFull(symbol: string) { try { const market = this.exchange.Exchange.market(symbol); if (this.Get(market.base) <= 0) return; const order = await this.exchange.MarketClose(symbol, this.Get(market.base)); this.Send(market.base, order.amount); this.Receive(market.quote, order.cost); order.fee_list.forEach((fee) => this.Send(fee.currency, fee.cost)); this.sendOrderMessage(order); return order; } catch (e) { this.message?.(JSON.stringify(e, null, 2)); } } }