refactor: organize backend by business responsibility
This commit is contained in:
@@ -0,0 +1,170 @@
|
||||
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
|
||||
import {
|
||||
decimalFromString,
|
||||
divide,
|
||||
formatDecimal,
|
||||
multiply,
|
||||
subtract,
|
||||
} from '../../../../../common/decimal';
|
||||
import { TbankClient } from '../../../../../integrations/tbank/tbank.api';
|
||||
import { decimal } from '../../../../../integrations/tbank/decimal';
|
||||
import {
|
||||
optional,
|
||||
previousClose,
|
||||
timestamp,
|
||||
} from '../../application/instrument-market';
|
||||
import {
|
||||
StockCandlesDto,
|
||||
StockCandlesQueryDto,
|
||||
StockQuoteDto,
|
||||
} from '../presentation/stock.dto';
|
||||
|
||||
const dayMs = 86_400_000;
|
||||
|
||||
import { StockCatalogService } from './stock-catalog.service';
|
||||
@Injectable()
|
||||
export class StockMarketService {
|
||||
constructor(
|
||||
private readonly catalog: StockCatalogService,
|
||||
private readonly tbank: TbankClient,
|
||||
) {}
|
||||
quote(userId: string, uid: string): Promise<StockQuoteDto> {
|
||||
return this.catalog.cached(userId, `quote:${uid}`, async (token) => {
|
||||
const share = await this.catalog.share(token, uid);
|
||||
const unavailable: string[] = [];
|
||||
const [last, tradingStatus] = await Promise.all([
|
||||
optional(
|
||||
() => this.tbank.getLastPrice(token, uid),
|
||||
'price',
|
||||
unavailable,
|
||||
),
|
||||
optional(
|
||||
() => this.tbank.getTradingStatus(token, uid),
|
||||
'status',
|
||||
unavailable,
|
||||
),
|
||||
]);
|
||||
const priceAt = timestamp(last?.time);
|
||||
const currency = share.currency?.toUpperCase();
|
||||
const price =
|
||||
last?.price && currency
|
||||
? { currency, value: formatDecimal(decimal(last.price)) }
|
||||
: null;
|
||||
const previous = priceAt
|
||||
? await optional(
|
||||
async () => {
|
||||
const end = new Date(priceAt);
|
||||
return previousClose(
|
||||
await this.tbank.getCandles(
|
||||
token,
|
||||
uid,
|
||||
new Date(end.valueOf() - 20 * dayMs),
|
||||
end,
|
||||
),
|
||||
priceAt,
|
||||
);
|
||||
},
|
||||
'comparison',
|
||||
unavailable,
|
||||
)
|
||||
: null;
|
||||
const previousPrice =
|
||||
previous?.close && currency
|
||||
? { currency, value: formatDecimal(decimal(previous.close)) }
|
||||
: null;
|
||||
const difference =
|
||||
price && previousPrice
|
||||
? subtract(
|
||||
decimalFromString(price.value),
|
||||
decimalFromString(previousPrice.value),
|
||||
)
|
||||
: null;
|
||||
return {
|
||||
price,
|
||||
priceAt,
|
||||
tradingStatus,
|
||||
previousCloseDate: timestamp(previous?.time)?.slice(0, 10) ?? null,
|
||||
previousClose: previousPrice,
|
||||
change:
|
||||
difference && currency
|
||||
? { currency, value: formatDecimal(difference) }
|
||||
: null,
|
||||
changePercent:
|
||||
difference &&
|
||||
previousPrice &&
|
||||
decimalFromString(previousPrice.value).value > 0n
|
||||
? formatDecimal(
|
||||
divide(
|
||||
multiply(difference, decimalFromString('100')),
|
||||
decimalFromString(previousPrice.value),
|
||||
6,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
unavailable,
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
}
|
||||
candles(
|
||||
userId: string,
|
||||
uid: string,
|
||||
period: StockCandlesQueryDto['period'] = 'month',
|
||||
): Promise<StockCandlesDto> {
|
||||
return this.catalog.cached(
|
||||
userId,
|
||||
`candles:${uid}:${period}`,
|
||||
async (token) => {
|
||||
const share = await this.catalog.share(token, uid);
|
||||
const historyFrom = timestamp(share.first_1dayCandleDate);
|
||||
const to = new Date();
|
||||
const from = new Date(to);
|
||||
from.setUTCMonth(
|
||||
from.getUTCMonth() -
|
||||
(period === 'month' ? 1 : period === 'halfYear' ? 6 : 12),
|
||||
);
|
||||
if (period === 'all') {
|
||||
if (!historyFrom)
|
||||
throw new ServiceUnavailableException({
|
||||
code: 'STOCK_HISTORY_START_UNAVAILABLE',
|
||||
});
|
||||
from.setTime(Date.parse(historyFrom));
|
||||
} else if (historyFrom && Date.parse(historyFrom) > from.valueOf())
|
||||
from.setTime(Date.parse(historyFrom));
|
||||
const collected = new Map<string, StockCandlesDto['candles'][number]>();
|
||||
// Conservative one-year windows also work with older deployed RPC limits.
|
||||
for (let start = from.valueOf(); start < to.valueOf();) {
|
||||
const end = Math.min(start + 365 * dayMs, to.valueOf());
|
||||
for (const candle of await this.tbank.getCandles(
|
||||
token,
|
||||
uid,
|
||||
new Date(start),
|
||||
new Date(end),
|
||||
)) {
|
||||
const time = timestamp(candle.time);
|
||||
if (
|
||||
time &&
|
||||
candle.close &&
|
||||
Date.parse(time) >= from.valueOf() - dayMs &&
|
||||
Date.parse(time) <= to.valueOf()
|
||||
)
|
||||
collected.set(time, {
|
||||
time,
|
||||
close: formatDecimal(decimal(candle.close)),
|
||||
isComplete: candle.isComplete === true,
|
||||
});
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
return {
|
||||
candles: [...collected.values()].sort((a, b) =>
|
||||
a.time.localeCompare(b.time),
|
||||
),
|
||||
currency: share.currency?.toUpperCase() || null,
|
||||
historyFrom,
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user