Skip to content

Commit a7f926e

Browse files
committed
async migrations
1 parent 57ba40e commit a7f926e

File tree

13 files changed

+403
-491
lines changed

13 files changed

+403
-491
lines changed

src/exchange/bitfinex.ts

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -199,26 +199,20 @@ export class Bitfinex {
199199
}
200200

201201
async getPositions(): Promise<Position[]> {
202-
return new Promise(resolve => {
203-
const positions = Object.values(this.positions).map(position =>
204-
position.entry && this.tickers[position.symbol]
205-
? Position.createProfitUpdate(
206-
position,
207-
(position.side === Position.SIDE_LONG
208-
? this.tickers[position.symbol].bid / position.entry - 1
209-
: position.entry / this.tickers[position.symbol].ask - 1) * 100
210-
)
211-
: position
212-
);
213-
resolve(positions);
214-
});
202+
return Object.values(this.positions).map(position =>
203+
position.entry && this.tickers[position.symbol]
204+
? Position.createProfitUpdate(
205+
position,
206+
(position.side === Position.SIDE_LONG
207+
? this.tickers[position.symbol].bid / position.entry - 1
208+
: position.entry / this.tickers[position.symbol].ask - 1) * 100
209+
)
210+
: position
211+
);
215212
}
216213

217-
getPositionForSymbol(symbol: string): Promise<Position | undefined> {
218-
return new Promise(resolve => {
219-
const position = Object.values(this.positions).find(pos => pos.symbol === symbol);
220-
resolve(position);
221-
});
214+
async getPositionForSymbol(symbol: string): Promise<Position | undefined> {
215+
return Object.values(this.positions).find(pos => pos.symbol === symbol);
222216
}
223217

224218
async cancelOrder(id: string | number): Promise<ExchangeOrder | undefined> {

src/exchange/bitmex.ts

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -522,30 +522,24 @@ export class Bitmex {
522522
}
523523
}
524524

525-
getOrders(): Promise<ExchangeOrder[]> {
526-
return new Promise(resolve => {
527-
const orders: ExchangeOrder[] = [];
525+
async getOrders(): Promise<ExchangeOrder[]> {
526+
const orders: ExchangeOrder[] = [];
528527

529-
for (const key in this.orders) {
530-
if (this.orders[key].status === 'open') {
531-
orders.push(this.orders[key]);
532-
}
528+
for (const key in this.orders) {
529+
if (this.orders[key].status === 'open') {
530+
orders.push(this.orders[key]);
533531
}
532+
}
534533

535-
resolve(orders);
536-
});
534+
return orders;
537535
}
538536

539-
findOrderById(id: string | number): Promise<ExchangeOrder | undefined> {
540-
return new Promise(async resolve => {
541-
resolve((await this.getOrders()).find(order => order.id === id || order.id == id));
542-
});
537+
async findOrderById(id: string | number): Promise<ExchangeOrder | undefined> {
538+
return (await this.getOrders()).find(order => order.id === id || order.id == id);
543539
}
544540

545-
getOrdersForSymbol(symbol: string): Promise<ExchangeOrder[]> {
546-
return new Promise(async resolve => {
547-
resolve((await this.getOrders()).filter(order => order.symbol === symbol));
548-
});
541+
async getOrdersForSymbol(symbol: string): Promise<ExchangeOrder[]> {
542+
return (await this.getOrders()).filter(order => order.symbol === symbol);
549543
}
550544

551545
async getPositions(): Promise<Position[]> {

src/exchange/bybit.ts

Lines changed: 43 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -560,60 +560,56 @@ export class Bybit {
560560
* @param order
561561
* @returns {Promise<ExchangeOrder | undefined>}
562562
*/
563-
validatePlacedOrder(order: ExchangeOrder): Promise<ExchangeOrder | undefined> {
564-
return new Promise(resolve => {
565-
setTimeout(async () => {
566-
// calling a direct "order_id" is not given any result
567-
// we fetch latest order and find our id
568-
const parameters2: Record<string, any> = {
569-
api_key: this.apiKey,
570-
timestamp: new Date().getTime(),
571-
symbol: order.symbol,
572-
limit: 5
573-
};
574-
575-
const parametersSorted2: Record<string, any> = {};
576-
Object.keys(parameters2)
577-
.sort()
578-
.forEach((key: string) => (parametersSorted2[key] = parameters2[key]));
563+
async validatePlacedOrder(order: ExchangeOrder): Promise<ExchangeOrder | undefined> {
564+
await new Promise(resolve => setTimeout(resolve, 1000));
579565

580-
parametersSorted2.sign = crypto.createHmac('sha256', this.apiSecret!).update(querystring.stringify(parametersSorted2)).digest('hex');
566+
// calling a direct "order_id" is not given any result
567+
// we fetch latest order and find our id
568+
const parameters2: Record<string, any> = {
569+
api_key: this.apiKey,
570+
timestamp: new Date().getTime(),
571+
symbol: order.symbol,
572+
limit: 5
573+
};
581574

582-
const url1 = `${this.getBaseUrl()}/v2/private/order/list?${querystring.stringify(parametersSorted2)}`;
583-
const placedOrder = await this.requestClient.executeRequestRetry(
584-
{
585-
method: 'GET',
586-
url: url1,
587-
headers: {
588-
'Content-Type': 'application/json',
589-
Accept: 'application/json'
590-
}
591-
},
592-
(r: any) => {
593-
return r && r.response && r.response.statusCode >= 500;
594-
}
595-
);
575+
const parametersSorted2: Record<string, any> = {};
576+
Object.keys(parameters2)
577+
.sort()
578+
.forEach((key: string) => (parametersSorted2[key] = parameters2[key]));
596579

597-
const { body } = placedOrder;
580+
parametersSorted2.sign = crypto.createHmac('sha256', this.apiSecret!).update(querystring.stringify(parametersSorted2)).digest('hex');
598581

599-
const json = JSON.parse(body);
600-
if (!json.result || !json.result.data) {
601-
this.logger.error(`Bybit: Invalid order body:${JSON.stringify({ body: body })}`);
602-
resolve(undefined);
603-
return;
582+
const url1 = `${this.getBaseUrl()}/v2/private/order/list?${querystring.stringify(parametersSorted2)}`;
583+
const placedOrder = await this.requestClient.executeRequestRetry(
584+
{
585+
method: 'GET',
586+
url: url1,
587+
headers: {
588+
'Content-Type': 'application/json',
589+
Accept: 'application/json'
604590
}
591+
},
592+
(r: any) => {
593+
return r && r.response && r.response.statusCode >= 500;
594+
}
595+
);
605596

606-
const find = json.result.data.find((o: any) => (o.order_id = order.id));
607-
if (!find) {
608-
this.logger.error(`Bybit: Order not found:${JSON.stringify({ body: body })}`);
609-
resolve(undefined);
610-
return;
611-
}
597+
const { body } = placedOrder;
612598

613-
const orders = Bybit.createOrders([find]);
614-
resolve(orders[0]);
615-
}, 1000);
616-
});
599+
const json = JSON.parse(body);
600+
if (!json.result || !json.result.data) {
601+
this.logger.error(`Bybit: Invalid order body:${JSON.stringify({ body: body })}`);
602+
return undefined;
603+
}
604+
605+
const find = json.result.data.find((o: any) => (o.order_id = order.id));
606+
if (!find) {
607+
this.logger.error(`Bybit: Order not found:${JSON.stringify({ body: body })}`);
608+
return undefined;
609+
}
610+
611+
const orders = Bybit.createOrders([find]);
612+
return orders[0];
617613
}
618614

619615
/**

src/exchange/coinbase_pro.ts

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -271,30 +271,24 @@ export class CoinbasePro {
271271
return this.candlesFromTrades.onTrade(this.getName(), trade, symbols);
272272
}
273273

274-
getOrders(): Promise<ExchangeOrder[]> {
275-
return new Promise(resolve => {
276-
const orders: ExchangeOrder[] = [];
274+
async getOrders(): Promise<ExchangeOrder[]> {
275+
const orders: ExchangeOrder[] = [];
277276

278-
for (const key in this.orders) {
279-
if (this.orders[key].status === 'open') {
280-
orders.push(this.orders[key]);
281-
}
277+
for (const key in this.orders) {
278+
if (this.orders[key].status === 'open') {
279+
orders.push(this.orders[key]);
282280
}
281+
}
283282

284-
resolve(orders);
285-
});
283+
return orders;
286284
}
287285

288-
findOrderById(id: string | number): Promise<ExchangeOrder | undefined> {
289-
return new Promise(async resolve => {
290-
resolve((await this.getOrders()).find(order => order.id === id || order.id == id));
291-
});
286+
async findOrderById(id: string | number): Promise<ExchangeOrder | undefined> {
287+
return (await this.getOrders()).find(order => order.id === id || order.id == id);
292288
}
293289

294-
getOrdersForSymbol(symbol: string): Promise<ExchangeOrder[]> {
295-
return new Promise(async resolve => {
296-
resolve((await this.getOrders()).filter(order => order.symbol === symbol));
297-
});
290+
async getOrdersForSymbol(symbol: string): Promise<ExchangeOrder[]> {
291+
return (await this.getOrders()).filter(order => order.symbol === symbol);
298292
}
299293

300294
/**

src/exchange/utils/order_bag.ts

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -34,30 +34,24 @@ export class OrderBag {
3434
this.orders[String(order.id)] = order;
3535
}
3636

37-
getOrders(): Promise<ExchangeOrder[]> {
38-
return new Promise(resolve => {
39-
const orders: ExchangeOrder[] = [];
40-
41-
for (const key in this.orders) {
42-
if (this.orders[key].status === 'open') {
43-
orders.push(this.orders[key]);
44-
}
37+
async getOrders(): Promise<ExchangeOrder[]> {
38+
const orders: ExchangeOrder[] = [];
39+
40+
for (const key in this.orders) {
41+
if (this.orders[key].status === 'open') {
42+
orders.push(this.orders[key]);
4543
}
44+
}
4645

47-
resolve(orders);
48-
});
46+
return orders;
4947
}
5048

51-
findOrderById(id: string | number): Promise<ExchangeOrder | undefined> {
52-
return new Promise(async resolve => {
53-
resolve((await this.getOrders()).find(order => order.id === id || order.id == id));
54-
});
49+
async findOrderById(id: string | number): Promise<ExchangeOrder | undefined> {
50+
return (await this.getOrders()).find(order => order.id === id || order.id == id);
5551
}
5652

57-
getOrdersForSymbol(symbol: string): Promise<ExchangeOrder[]> {
58-
return new Promise(async resolve => {
59-
resolve((await this.getOrders()).filter(order => order.symbol === symbol));
60-
});
53+
async getOrdersForSymbol(symbol: string): Promise<ExchangeOrder[]> {
54+
return (await this.getOrders()).filter(order => order.symbol === symbol);
6155
}
6256

6357
delete(id: string | number): void {

src/modules/order/stop_loss_calculator.ts

Lines changed: 40 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -16,63 +16,50 @@ export class StopLossCalculator {
1616
}
1717

1818
async calculateForOpenPosition(exchange: string, position: Position, options: StopLossOptions = { percent: 3 }): Promise<number | undefined> {
19-
const { tickers } = this;
20-
21-
return new Promise(resolve => {
22-
if (!position.entry) {
23-
this.logger.info(`Invalid position entry for stop loss:${JSON.stringify(position)}`);
24-
resolve(undefined);
25-
26-
return;
27-
}
28-
29-
let price: number | undefined;
30-
if (position.side === 'long') {
31-
if (options.percent) {
32-
price = position.entry * (1 - options.percent / 100);
33-
}
34-
} else if (options.percent) {
35-
price = position.entry * (1 + options.percent / 100);
36-
}
37-
38-
// invalid price no value
39-
if (!price) {
40-
this.logger.info(`Empty price for stop loss:${JSON.stringify(position)}`);
41-
42-
return resolve(undefined);
19+
if (!position.entry) {
20+
this.logger.info(`Invalid position entry for stop loss:${JSON.stringify(position)}`);
21+
return undefined;
22+
}
23+
24+
let price: number | undefined;
25+
if (position.side === 'long') {
26+
if (options.percent) {
27+
price = position.entry * (1 - options.percent / 100);
4328
}
44-
45-
const ticker = tickers.get(exchange, position.symbol);
46-
47-
if (!ticker) {
48-
this.logger.info(`Ticker not found for stop loss:${JSON.stringify(position)}`);
49-
50-
resolve(undefined);
51-
return;
29+
} else if (options.percent) {
30+
price = position.entry * (1 + options.percent / 100);
31+
}
32+
33+
// invalid price no value
34+
if (!price) {
35+
this.logger.info(`Empty price for stop loss:${JSON.stringify(position)}`);
36+
return undefined;
37+
}
38+
39+
const ticker = this.tickers.get(exchange, position.symbol);
40+
41+
if (!ticker) {
42+
this.logger.info(`Ticker not found for stop loss:${JSON.stringify(position)}`);
43+
return undefined;
44+
}
45+
46+
if (position.side === 'long') {
47+
if (price > ticker.ask) {
48+
this.logger.info(`Ticker out of range stop loss (long): ${JSON.stringify(position)}${JSON.stringify(ticker)}`);
49+
return undefined;
5250
}
53-
54-
if (position.side === 'long') {
55-
if (price > ticker.ask) {
56-
this.logger.info(`Ticker out of range stop loss (long): ${JSON.stringify(position)}${JSON.stringify(ticker)}`);
57-
58-
resolve(undefined);
59-
return;
60-
}
61-
} else if (position.side === 'short') {
62-
if (price < ticker.bid) {
63-
this.logger.info(`Ticker out of range stop loss (short): ${JSON.stringify(position)}${JSON.stringify(ticker)}`);
64-
65-
resolve(undefined);
66-
return;
67-
}
51+
} else if (position.side === 'short') {
52+
if (price < ticker.bid) {
53+
this.logger.info(`Ticker out of range stop loss (short): ${JSON.stringify(position)}${JSON.stringify(ticker)}`);
54+
return undefined;
6855
}
56+
}
6957

70-
// inverse price for lose long position via sell
71-
if (position.side === 'long') {
72-
price *= -1;
73-
}
58+
// inverse price for lose long position via sell
59+
if (position.side === 'long') {
60+
price *= -1;
61+
}
7462

75-
resolve(price);
76-
});
63+
return price;
7764
}
7865
}

0 commit comments

Comments
 (0)