feat!: persist T-Bank data and synchronize reads
Backend security / security (push) Successful in 8s
Backend verify / verify (push) Failing after 10m45s
Conventional commits / commits (pull_request) Successful in 29s
Backend security / security (pull_request) Successful in 8s
Backend verify / verify (pull_request) Failing after 10m37s

Store account membership, portfolio, operations, forecasts and market sources in SQLite.
Coalesce scoped refreshes, fence connection revisions, preserve complete financial
snapshots and stabilize operation period state.

BREAKING CHANGE: investment reads return data/meta resource envelopes and locally
persisted snapshots; consumers must use the matching OpenAPI contract and explicit
synchronization endpoints.
This commit is contained in:
2026-09-26 21:29:15 +03:00
parent 0862d56c4e
commit d6e6c4ace5
116 changed files with 18321 additions and 5409 deletions
@@ -0,0 +1,481 @@
import { planInvestmentScreen } from '../../investment-sync-plan';
import { StructuredLogger } from '../../../../common/logging/structured-logger.service';
import {
Injectable,
NotFoundException,
ServiceUnavailableException,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { MILLISECONDS_PER_DAY } from '../../../../common/time';
import { formatDecimal } from '../../../../common/decimal';
import { decimal } from '../../../../integrations/tbank/decimal';
import {
TbankAccessService,
TbankClient,
type TbankShare,
} from '../../../../integrations/tbank/tbank.api';
import type { TbankSyncAttempt } from '../../../../integrations/tbank/tbank-access.service';
import { investmentResourceMeta } from '../../investment-resource.mapper';
import { CatalogEnrichmentService } from './catalog-enrichment.service';
import { CandleRepository } from '../infrastructure/candle.repository';
import {
candleGaps,
candleWindows,
utcDay,
type CandleRange,
} from '../domain/candle-coverage';
import { timestamp } from './instrument-market';
type CandleInput = {
uid: string;
instrumentType: 'share' | 'bond';
period: 'month' | 'halfYear' | 'year' | 'all';
range?: CandleRange;
};
type Producer = {
input: CandleInput;
attempt: TbankSyncAttempt;
now: Date;
force: boolean;
priority: number;
observers: TbankSyncAttempt[];
ranges?: CandleRange[];
nextWindow?: number;
};
const months = { month: 1, halfYear: 6, year: 12 };
const tailFreshForMs = 60_000;
const prefetchReadBatchSize = 100;
function scope(input: CandleInput) {
return `candles:${input.uid}:${input.period}${input.range ? `:${input.range.from.toISOString()}/${input.range.to.toISOString()}` : ''}`;
}
function rangeFor(
input: CandleInput,
instrument: TbankShare,
now: Date,
): CandleRange {
if (input.range) return input.range;
const from = utcDay(now);
const history = timestamp(instrument.first_1dayCandleDate);
if (input.period === 'all') {
if (!history)
throw new ServiceUnavailableException({
code:
input.instrumentType === 'share'
? 'STOCK_HISTORY_START_UNAVAILABLE'
: 'BOND_HISTORY_START_UNAVAILABLE',
});
from.setTime(utcDay(new Date(history)).valueOf());
} else {
from.setUTCMonth(from.getUTCMonth() - months[input.period]);
if (history && Date.parse(history) > from.valueOf())
from.setTime(utcDay(new Date(history)).valueOf());
}
return { from, to: new Date(utcDay(now).valueOf() + MILLISECONDS_PER_DAY) };
}
@Injectable()
export class CandleService {
private readonly runId = randomUUID();
private readonly active = new Set<string>();
private readonly producers = new Map<string, Producer>();
private readonly queue: Producer[] = [];
private reservations: Promise<unknown> = Promise.resolve();
private running = false;
private readonly prefetches = new Map<string, Promise<void>>();
constructor(
private readonly repository: CandleRepository,
private readonly sources: CatalogEnrichmentService,
private readonly access: TbankAccessService,
private readonly tbank: TbankClient,
private readonly logger: StructuredLogger,
) {}
async read(userId: string, input: CandleInput, observe = false) {
const { revision } = await this.access.local(userId);
const [detail] = await this.sources.readMany(
userId,
input.instrumentType,
[input.uid],
true,
['detail'],
);
if (detail.meta.availability === 'complete' && !detail.instrument)
throw new NotFoundException();
const now = new Date();
const range = detail.instrument
? rangeFor(input, detail.instrument, now)
: null;
const saved = range ? await this.repository.read(input.uid, range) : null;
const gaps = range && saved ? candleGaps(range, saved.coverage, now) : [];
if (!observe && (!saved || gaps.length))
await this.request(userId, revision, input, now);
const work = await this.repository.work(userId, revision, scope(input));
const fetchedAt =
saved?.coverage
.map((row) => row.fetchedAt)
.sort((a, b) => a.valueOf() - b.valueOf())[0] ?? null;
const covered = saved?.coverage.length ? true : false;
const completeCoverage = (saved?.coverage ?? [])
.filter((row) => row.isComplete || row.from >= utcDay(now))
.map((row) => ({ ...row, isComplete: true }));
const missing = range ? candleGaps(range, completeCoverage, now) : [];
const complete = Boolean(saved && range && !missing.length);
const publicRange = (value: CandleRange) => ({
from: value.from.toISOString(),
to: value.to.toISOString(),
});
return {
data:
!saved || !covered
? null
: {
candles: saved.data,
currency:
input.instrumentType === 'share'
? detail.instrument?.currency?.toUpperCase() || null
: null,
historyFrom: timestamp(detail?.instrument?.first_1dayCandleDate),
observedAt: fetchedAt?.toISOString() ?? now.toISOString(),
},
meta: investmentResourceMeta({
resourceKey: scope(input),
dataRevision: saved?.dataRevision ?? '0',
availability: !covered ? 'missing' : complete ? 'complete' : 'partial',
fetchedAt,
freshForMs: Number.POSITIVE_INFINITY,
work,
coverage: {
requested: range ? [publicRange(range)] : [],
completeRanges: range
? completeCoverage.flatMap((row) => {
const from = new Date(
Math.max(row.from.valueOf(), range.from.valueOf()),
);
const to = new Date(
Math.min(row.to.valueOf(), range.to.valueOf()),
);
return from < to ? [publicRange({ from, to })] : [];
})
: [],
missingRanges: missing.map(publicRange),
asOf: fetchedAt?.toISOString() ?? null,
historyBoundary: timestamp(detail?.instrument?.first_1dayCandleDate)
? 'known'
: 'unknown',
historyState: complete
? 'complete'
: work?.state === 'failed'
? 'failed'
: work?.state === 'running'
? 'loading'
: covered
? 'partial'
: 'missing',
},
dependencies: [
detail.meta,
...(saved?.coverage ?? []).map((row) =>
investmentResourceMeta({
resourceKey: `${scope(input)}/${row.from.toISOString()}/${row.to.toISOString()}`,
dataRevision: String(row.dataRevision),
availability: 'complete',
fetchedAt: row.fetchedAt,
freshForMs: row.isComplete
? Number.POSITIVE_INFINITY
: tailFreshForMs,
work: null,
}),
),
],
}),
};
}
prefetch(
userId: string,
revision: string,
positions: { instrumentUid?: string | null; type: string }[],
) {
const key = JSON.stringify([
userId,
revision,
positions
.map((position) => [position.instrumentUid, position.type])
.sort(),
]);
const existing = this.prefetches.get(key);
if (existing) return existing;
const work = this.prefetchPositions(userId, revision, positions).finally(
() => this.prefetches.delete(key),
);
this.prefetches.set(key, work);
return work;
}
private async prefetchPositions(
userId: string,
revision: string,
positions: { instrumentUid?: string | null; type: string }[],
) {
const now = new Date();
const unique = new Map(
positions
.filter(
(position) =>
position.instrumentUid && ['STOCK', 'BOND'].includes(position.type),
)
.map((position) => [position.instrumentUid ?? '', position]),
);
const details: Awaited<ReturnType<CatalogEnrichmentService['readMany']>> =
[];
const coverage: Awaited<ReturnType<CandleRepository['coverage']>> = [];
for (const instrumentType of ['share', 'bond'] as const) {
const uids = [...unique]
.filter(
([, position]) =>
position.type === (instrumentType === 'share' ? 'STOCK' : 'BOND'),
)
.map(([uid]) => uid);
for (
let offset = 0;
offset < uids.length;
offset += prefetchReadBatchSize
) {
const batch = uids.slice(offset, offset + prefetchReadBatchSize);
details.push(
...(await this.sources.readMany(userId, instrumentType, batch, true, [
'detail',
])),
);
coverage.push(...(await this.repository.coverage(batch)));
}
}
const byUid = new Map(details.map((detail) => [detail.input.uid, detail]));
for (const [uid, position] of unique) {
const instrumentType: CandleInput['instrumentType'] =
position.type === 'STOCK' ? 'share' : 'bond';
const detail = byUid.get(uid);
const history = timestamp(detail?.instrument?.first_1dayCandleDate);
const plan = planInvestmentScreen(
{ screen: 'account' },
{
membershipKnown: true,
accounts: [],
instruments: [
{
uid,
type: position.type as 'STOCK' | 'BOND',
historyFrom: history ? new Date(history) : null,
},
],
},
now,
);
if (
!detail?.instrument ||
plan.sources.some((source) => source.kind === 'candles')
) {
const input = { uid, instrumentType, period: 'all' as const };
const range =
detail?.instrument && history
? rangeFor(input, detail.instrument, now)
: null;
if (
!range ||
candleGaps(
range,
coverage.filter((row) => row.instrumentUid === uid),
now,
).length
)
await this.request(userId, revision, input, now, false, 2);
}
}
}
request(
userId: string,
revision: string,
input: CandleInput,
now = new Date(),
force = false,
priority = 1,
) {
const pending = this.reservations.then(async () => {
const reserved = await this.repository.reserve(
{ userId, revision },
scope(input),
{
uid: input.uid,
instrumentType: input.instrumentType,
ranges: [],
period: input.period,
now: now.toISOString(),
force,
},
this.runId,
this.active,
priority,
);
if (!reserved) return null;
const attempt = {
userId,
revision,
id: reserved.work.id,
attemptId: reserved.work.attemptId,
};
if (reserved.launch) {
this.active.add(attempt.attemptId);
const producer = this.producers.get(scope(input));
if (producer) producer.observers.push(attempt);
else {
const next = { input, attempt, now, force, priority, observers: [] };
this.producers.set(scope(input), next);
this.queue.push(next);
}
if (!this.running) {
this.running = true;
setImmediate(() => {
void this.drain();
});
}
}
return attempt.id;
});
this.reservations = pending.catch(() => undefined);
return pending;
}
private async load(producer: Producer) {
const { input, attempt, now } = producer;
const instrument = await this.sources.ensureDetail(
attempt.userId,
attempt.revision,
input.instrumentType,
input.uid,
);
if (!instrument) throw new NotFoundException();
const range = rangeFor(input, instrument, now);
if (!producer.ranges) {
const saved = await this.repository.read(input.uid, range);
producer.ranges = (
producer.force ? [range] : candleGaps(range, saved.coverage, now)
)
.flatMap(candleWindows)
.reverse();
producer.nextWindow = 0;
}
const ranges = producer.ranges;
const index = producer.nextWindow ?? 0;
let window = ranges[index];
if (window && !producer.force) {
const latest = await this.repository.read(input.uid, window);
const gaps = candleGaps(window, latest.coverage, now)
.flatMap(candleWindows)
.reverse();
ranges.splice(index, 1, ...gaps);
window = ranges[index];
}
if (window) {
const token = await this.access.tokenForAttempt(attempt);
if (!token) return false;
const candles = await this.tbank.getCandles(
token,
input.uid,
window.from,
new Date(Math.min(window.to.valueOf(), now.valueOf())),
);
const rows = candles.flatMap((candle) => {
const time = timestamp(candle.time);
if (!time || !candle.close) throw new Error('Invalid candle response');
return [
{
time,
close: formatDecimal(decimal(candle.close)),
isComplete: candle.isComplete === true,
},
];
});
if (!(await this.repository.stage(attempt, window, rows, now)))
return false;
if (
!producer.force &&
!(await this.repository.publish(
attempt,
{ uid: input.uid, ranges: [window] },
false,
))
)
return false;
producer.nextWindow = index + 1;
if (producer.nextWindow < ranges.length) return null;
}
return this.repository.publish(attempt, {
uid: input.uid,
ranges: producer.force ? ranges : [],
});
}
private async drain() {
try {
while (this.queue.length) {
this.queue.sort((a, b) => a.priority - b.priority);
const producer = this.queue.shift();
if (!producer) break;
let success = false;
let code = 'TBANK_UNAVAILABLE';
try {
const result = await this.load(producer);
if (result === null) {
this.queue.push(producer);
continue;
}
success = result;
} catch (error) {
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN')
await this.access.rejectMembershipToken(producer.attempt);
if (error instanceof ServiceUnavailableException) {
const response = error.getResponse();
if (
typeof response === 'object' &&
'code' in response &&
typeof response.code === 'string'
)
code = response.code;
}
}
if (!success) await this.repository.fail(producer.attempt, code);
this.active.delete(producer.attempt.attemptId);
for (const observer of producer.observers) {
if (
!success ||
!(await this.repository.completeObserver(
observer,
producer.attempt,
))
)
await this.repository.fail(observer, code);
this.active.delete(observer.attemptId);
}
this.producers.delete(scope(producer.input));
if (success && !producer.force && producer.input.period !== 'all')
await this.request(
producer.attempt.userId,
producer.attempt.revision,
{ ...producer.input, period: 'all' },
producer.now,
false,
2,
);
}
} catch {
this.logger.event('error', 'candles.persistence-failed', {
code: 'TBANK_UNAVAILABLE',
});
} finally {
this.active.clear();
this.producers.clear();
this.queue.length = 0;
this.running = false;
}
}
}
@@ -0,0 +1,390 @@
import { CatalogEnrichmentService } from './catalog-enrichment.service';
import {
Injectable,
NotFoundException,
ConflictException,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { StructuredLogger } from '../../../../common/logging/structured-logger.service';
import {
TbankAccessService,
TbankClient,
tbankSourceNeedsRefresh,
tbankSourceTtlMs,
} from '../../../../integrations/tbank/tbank.api';
import type { TbankSyncAttempt } from '../../../../integrations/tbank/tbank-access.service';
import { investmentResourceMeta } from '../../investment-resource.mapper';
import {
CatalogDiscoveryRepository,
catalogQuery,
catalogScope,
type CatalogQuery,
} from '../infrastructure/catalog-discovery.repository';
import {
catalogSearchLimit,
selectCatalogInstruments,
} from './catalog-selection';
const tickerAmbiguityLimit = 2;
type Producer = {
input: CatalogQuery;
attempt: TbankSyncAttempt;
observers: TbankSyncAttempt[];
force: boolean;
};
@Injectable()
export class CatalogDiscoveryService {
private readonly runId = randomUUID();
private readonly active = new Set<string>();
private readonly producers = new Map<string, Producer>();
private readonly queue: Producer[] = [];
private reservations: Promise<unknown> = Promise.resolve();
private running = false;
private readonly completions = new Map<
string,
{ workId: string; done: Promise<void>; resolve: () => void }
>();
constructor(
private readonly repository: CatalogDiscoveryRepository,
private readonly access: TbankAccessService,
private readonly tbank: TbankClient,
private readonly logger: StructuredLogger,
private readonly enrichment: CatalogEnrichmentService,
) {}
async read(userId: string, input: CatalogQuery, observe = false) {
input = catalogQuery(input);
const connection = await this.access.local(userId);
const saved = await this.repository.read(input);
if (!observe) await this.request(userId, connection.revision, input);
return {
data: saved.data,
meta: investmentResourceMeta({
resourceKey: catalogScope(input),
dataRevision: saved.dataRevision,
availability: saved.data === null ? 'missing' : 'complete',
fetchedAt: saved.fetchedAt,
freshForMs: tbankSourceTtlMs.catalog,
work: await this.repository.work(userId, connection.revision, input),
}),
};
}
async search(userId: string, input: CatalogQuery, observe = false) {
const discovery = await this.read(userId, input, observe);
const sources = discovery.data
? await this.enrichment.readMany(
userId,
input.instrumentType,
discovery.data.map((item) => item.uid),
observe,
)
: [];
const dependencies = [
discovery.meta,
...sources.map((source) => source.meta),
];
return {
data:
discovery.data?.map((short) => ({
...short,
detail:
sources.find(
(source) =>
source.input.uid === short.uid &&
source.input.kind === 'detail',
)?.instrument ?? null,
price:
sources.find(
(source) =>
source.input.uid === short.uid &&
source.input.kind === 'last-price',
)?.price ?? null,
})) ?? null,
meta: investmentResourceMeta({
resourceKey: `search:${catalogScope(catalogQuery(input))}`,
dataRevision: dependencies
.map((dependency) => dependency.dataRevision)
.join('/'),
availability:
discovery.data === null
? 'missing'
: sources.every((source) => source.meta.availability === 'complete')
? 'complete'
: 'partial',
fetchedAt: discovery.meta.lastSuccessfulAt
? new Date(discovery.meta.lastSuccessfulAt)
: null,
freshForMs: tbankSourceTtlMs.catalog,
work: discovery.meta.sync.id
? {
id: discovery.meta.sync.id,
state: discovery.meta.sync.state,
errorCode: discovery.meta.sync.errorCode,
}
: null,
dependencies,
}),
};
}
async detail(
userId: string,
instrumentType: 'share' | 'bond',
uid: string,
observe = false,
) {
const sources = await this.enrichment.readMany(
userId,
instrumentType,
[uid],
observe,
['detail'],
);
const source = sources[0];
if (source.meta.availability === 'complete' && !source.instrument)
throw new NotFoundException();
const instrument = source.instrument;
let slug = uid;
const dependencies = [source.meta];
if (
instrument?.ticker &&
/^[A-Za-z0-9][A-Za-z0-9._@+-]{0,79}$/.test(instrument.ticker)
) {
const alias = await this.read(
userId,
{ instrumentType, query: instrument.ticker, exactTicker: true },
observe,
);
if (alias.data?.length === 1 && alias.data[0].uid === uid)
slug = instrument.ticker.toUpperCase();
dependencies.push(alias.meta);
}
return {
data: instrument ? { ...instrument, uid, slug } : null,
meta: investmentResourceMeta({
resourceKey: `${instrumentType}/detail/${uid}`,
dataRevision: dependencies
.map((dependency) => dependency.dataRevision)
.join('/'),
availability: source.meta.availability,
fetchedAt: source.meta.lastSuccessfulAt
? new Date(source.meta.lastSuccessfulAt)
: null,
freshForMs: tbankSourceTtlMs.metadata,
work: source.meta.sync.id
? {
id: source.meta.sync.id,
state: source.meta.sync.state,
errorCode: source.meta.sync.errorCode,
}
: null,
dependencies,
}),
};
}
async byTicker(
userId: string,
instrumentType: 'share' | 'bond',
ticker: string,
observe = false,
) {
const lookup = await this.read(
userId,
{ instrumentType, query: ticker, exactTicker: true },
observe,
);
if (lookup.data?.length === 0) throw new NotFoundException();
if (lookup.data && lookup.data.length > 1)
throw new ConflictException({
code:
instrumentType === 'share'
? 'STOCK_TICKER_AMBIGUOUS'
: 'BOND_TICKER_AMBIGUOUS',
});
const result = lookup.data
? await this.detail(userId, instrumentType, lookup.data[0].uid, observe)
: null;
const dependencies = [lookup.meta, ...(result ? [result.meta] : [])];
return {
data: result?.data
? { ...result.data, slug: ticker.trim().toUpperCase() }
: null,
meta: investmentResourceMeta({
resourceKey: `${instrumentType}/ticker/${ticker.trim().toUpperCase()}`,
dataRevision: dependencies
.map((dependency) => dependency.dataRevision)
.join('/'),
availability: result?.meta.availability ?? 'missing',
fetchedAt: lookup.meta.lastSuccessfulAt
? new Date(lookup.meta.lastSuccessfulAt)
: null,
freshForMs: tbankSourceTtlMs.metadata,
work: lookup.meta.sync.id
? {
id: lookup.meta.sync.id,
state: lookup.meta.sync.state,
errorCode: lookup.meta.sync.errorCode,
}
: null,
dependencies,
}),
};
}
request(
userId: string,
revision: string,
query: CatalogQuery,
force = false,
) {
const input = catalogQuery(query);
const reserved = this.reservations.then(async () => {
const saved = await this.repository.read(input);
if (
!tbankSourceNeedsRefresh('catalog', saved.fetchedAt, new Date(), force)
)
return null;
const reservation = await this.repository.reserve(
{ userId, revision },
input,
this.runId,
this.active,
);
if (!reservation) return null;
const { id, attemptId } = reservation.work;
if (!reservation.launch) {
const current = this.producers.get(catalogScope(input));
if (current) current.force ||= force;
return id;
}
const attempt = { userId, revision, id, attemptId };
this.active.add(attemptId);
let resolve = () => {};
const done = new Promise<void>((finish) => {
resolve = finish;
});
this.completions.set(attemptId, { workId: id, done, resolve });
const key = catalogScope(input);
const producer = this.producers.get(key);
if (producer) {
producer.observers.push(attempt);
producer.force ||= force;
} else {
const queued = { input, attempt, observers: [], force };
this.producers.set(key, queued);
this.queue.push(queued);
}
if (!this.running) {
this.running = true;
setImmediate(() => {
void this.drain();
});
}
return id;
});
this.reservations = reserved.catch(() => undefined);
return reserved;
}
async refresh(userId: string, revision: string, query: CatalogQuery) {
const id = await this.request(userId, revision, query, true);
if (id)
await Promise.all(
[...this.completions.values()]
.filter((entry) => entry.workId === id)
.map((entry) => entry.done),
);
const saved = await this.repository.read(catalogQuery(query));
const sources = await this.enrichment.readMany(
userId,
query.instrumentType,
saved.data?.map((item) => item.uid) ?? [],
true,
);
return [
...(id ? [id] : []),
...sources.flatMap((source) =>
source.meta.sync.id ? [source.meta.sync.id] : [],
),
];
}
private async drain() {
try {
while (this.queue.length) {
const producer = this.queue.shift();
if (!producer) break;
const { input, attempt } = producer;
let success = false;
try {
const token = await this.access.tokenForAttempt(attempt);
if (token) {
const found =
input.instrumentType === 'share'
? await this.tbank.findShares(token, input.query)
: await this.tbank.findBonds(token, input.query);
success = await this.repository.publish(
attempt,
input,
selectCatalogInstruments(
input.exactTicker
? found.filter(
(item) =>
item.ticker?.trim().toUpperCase() === input.query,
)
: found,
input.query,
input.instrumentType,
).slice(
0,
input.exactTicker ? tickerAmbiguityLimit : catalogSearchLimit,
),
new Date(),
);
}
} catch (error) {
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN')
await this.access.rejectMembershipToken(attempt);
else
this.logger.event('warn', 'catalog-discovery.failed', {
code: 'TBANK_UNAVAILABLE',
});
}
if (success) {
const saved = await this.repository.read(input);
for (const observer of [attempt, ...producer.observers])
if (!input.exactTicker || saved.data?.length === 1)
await this.enrichment.requestMany(
observer.userId,
observer.revision,
input.instrumentType,
saved.data?.map((item) => item.uid) ?? [],
producer.force,
input.exactTicker ? ['detail'] : ['last-price', 'detail'],
);
}
this.producers.delete(catalogScope(input));
for (const observer of [attempt, ...producer.observers]) {
await this.repository.finish(observer, success);
this.active.delete(observer.attemptId);
this.completions.get(observer.attemptId)?.resolve();
this.completions.delete(observer.attemptId);
}
}
} catch {
for (const completion of this.completions.values()) completion.resolve();
this.completions.clear();
this.active.clear();
this.producers.clear();
this.queue.length = 0;
this.logger.event('error', 'catalog-discovery.persistence-failed', {
code: 'TBANK_UNAVAILABLE',
});
} finally {
this.running = false;
}
}
}
@@ -0,0 +1,665 @@
import type { TbankDividend } from '../../../../integrations/tbank/tbank.api';
import type { MoexBondEvent } from '../../../../integrations/moex/moex.api';
import { CandleRepository } from '../infrastructure/candle.repository';
import { candleGaps, utcDay } from '../domain/candle-coverage';
import {
decimalFromString,
divide,
formatDecimal,
} from '../../../../common/decimal';
import { decimal } from '../../../../integrations/tbank/decimal';
import {
MILLISECONDS_PER_DAY,
MILLISECONDS_PER_SECOND,
} from '../../../../common/time';
import { MoexClient } from '../../../../integrations/moex/moex.api';
import { NcrRatingsClient } from '../../../../integrations/ncr/ncr.api';
import type {
TbankCandle,
TbankFundamentals,
} from '../../../../integrations/tbank/tbank.api';
import type { TbankCoupon } from '../../../../integrations/tbank/tbank-market.types';
import { previousClose, timestamp } from './instrument-market';
import { Injectable, NotFoundException } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { StructuredLogger } from '../../../../common/logging/structured-logger.service';
import {
TbankAccessService,
TbankClient,
tbankSourceNeedsRefresh,
tbankSourceTtlMs,
type TbankBond,
type TbankShare,
} from '../../../../integrations/tbank/tbank.api';
import type { TbankLastPrice } from '../../../../integrations/tbank/tbank-market.types';
import type { TbankSyncAttempt } from '../../../../integrations/tbank/tbank-access.service';
import { investmentResourceMeta } from '../../investment-resource.mapper';
import {
CatalogDiscoveryRepository,
catalogScope,
type CatalogSource,
} from '../infrastructure/catalog-discovery.repository';
import { catalogSearchLimit } from './catalog-selection';
type Producer = {
input: CatalogSource;
attempt: TbankSyncAttempt;
observers: { attempt: TbankSyncAttempt; input: CatalogSource }[];
};
@Injectable()
export class CatalogEnrichmentService {
private readonly runId = randomUUID();
private readonly active = new Set<string>();
private readonly producers = new Map<string, Producer>();
private readonly queue: Producer[] = [];
private reservations: Promise<unknown> = Promise.resolve();
private running = false;
private readonly completions = new Map<
string,
{ workId: string; done: Promise<void>; resolve: () => void }
>();
async ensureDetail(
userId: string,
revision: string,
instrumentType: 'share' | 'bond',
uid: string,
) {
const ids = await this.requestMany(
userId,
revision,
instrumentType,
[uid],
false,
['detail'],
);
await Promise.all(
[...this.completions.values()]
.filter((entry) => ids.includes(entry.workId))
.map((entry) => entry.done),
);
const rows = await this.repository.readSources([
{ instrumentType, uid, kind: 'detail' },
]);
if (!rows.length) throw new Error('Instrument dependency missing');
return (rows[0].payload as CatalogPayload).instrument ?? null;
}
constructor(
private readonly repository: CatalogDiscoveryRepository,
private readonly access: TbankAccessService,
private readonly tbank: TbankClient,
private readonly logger: StructuredLogger,
private readonly moex: MoexClient,
private readonly ratings: NcrRatingsClient,
private readonly candles: CandleRepository,
) {}
async readMany(
userId: string,
instrumentType: 'share' | 'bond',
uids: string[],
observe: boolean,
kinds: CatalogSource['kind'][] = ['last-price', 'detail'],
range?: {
from: string;
to: string;
ticker?: string;
tickers?: Record<string, string>;
},
) {
const { revision } = await this.access.local(userId);
const inputs = sourceInputs(instrumentType, uids, kinds, range);
const rows = inputs.length ? await this.repository.readSources(inputs) : [];
if (!observe)
await this.requestMany(
userId,
revision,
instrumentType,
uids,
false,
kinds,
range,
);
const work = inputs.length
? await this.repository.workMany(userId, revision, inputs)
: [];
const byScope = new Map(work.map((row) => [row.scopeKey, row]));
return inputs.map((input) => {
const row = rows.find(
(entry) =>
entry.instrumentUid === input.uid && entry.kind === input.kind,
);
const payload = row?.payload as CatalogPayload | undefined;
return {
input,
version: row
? {
instrumentUid: row.instrumentUid,
source: row.source,
kind: row.kind,
rangeKey: row.rangeKey,
dataRevision: row.dataRevision,
fetchedAt: row.fetchedAt,
}
: null,
payload,
instrument: payload?.instrument ?? null,
price: payload?.price ?? null,
meta: investmentResourceMeta({
resourceKey: catalogScope(input),
dataRevision: String(row?.dataRevision ?? 0),
availability: row ? 'complete' : 'missing',
fetchedAt: row?.fetchedAt ?? null,
freshForMs: tbankSourceTtlMs[sourcePolicy(input.kind)],
work: byScope.get(catalogScope(input)) ?? null,
}),
};
});
}
requestMany(
userId: string,
revision: string,
instrumentType: 'share' | 'bond',
uids: string[],
force = false,
kinds: CatalogSource['kind'][] = ['last-price', 'detail'],
range?: {
from: string;
to: string;
ticker?: string;
tickers?: Record<string, string>;
},
) {
const inputs = sourceInputs(instrumentType, uids, kinds, range);
const reservation = this.reservations.then(async () => {
const rows = inputs.length
? await this.repository.readSources(inputs)
: [];
const ids: string[] = [];
for (const input of inputs) {
const row = rows.find(
(entry) =>
entry.instrumentUid === input.uid && entry.kind === input.kind,
);
if (
!tbankSourceNeedsRefresh(
sourcePolicy(input.kind),
row?.fetchedAt ?? null,
new Date(),
force,
)
)
continue;
const reserved = await this.repository.reserve(
{ userId, revision },
input,
this.runId,
this.active,
);
if (!reserved) continue;
const { id, attemptId } = reserved.work;
ids.push(id);
if (!reserved.launch) continue;
const attempt = { userId, revision, id, attemptId };
this.active.add(attemptId);
let resolve = () => {};
const done = new Promise<void>((finish) => {
resolve = finish;
});
this.completions.set(attemptId, { workId: id, done, resolve });
const key = producerKey(input);
const producer = this.producers.get(key);
if (producer) producer.observers.push({ attempt, input });
else {
const queued = { input, attempt, observers: [] };
this.producers.set(key, queued);
this.queue.push(queued);
}
}
if (this.queue.length && !this.running) {
this.running = true;
setImmediate(() => {
void this.drain();
});
}
return ids;
});
this.reservations = reservation.catch(() => undefined);
return reservation;
}
async section(
userId: string,
instrumentType: 'share' | 'bond',
uid: string,
section: 'quote' | 'company' | 'metrics',
observe = false,
) {
const kinds: CatalogSource['kind'][] =
section === 'company'
? ['detail', 'description', 'fundamentals']
: [
...(instrumentType === 'bond'
? ['bond-current' as const]
: ['detail' as const]),
'last-price',
'trading-status',
'comparison',
...(section === 'metrics'
? ['coupons' as const, 'yield' as const, 'rating' as const]
: []),
];
const sources = await this.readMany(
userId,
instrumentType,
[uid],
observe,
kinds,
);
const first = sources[0];
if (first.meta.availability === 'complete' && !first.instrument)
throw new NotFoundException();
const values = sources.reduce<CatalogPayload>(
(result, source) => ({ ...result, ...source.payload }),
{},
);
const dependencies = sources.map((source) => source.meta);
const complete = dependencies.every(
(dependency) => dependency.availability === 'complete',
);
const meta = investmentResourceMeta({
resourceKey: `${instrumentType}/${section}/${uid}`,
dataRevision: dependencies
.map((dependency) => dependency.dataRevision)
.join('/'),
availability: !first.instrument
? 'missing'
: complete
? 'complete'
: 'partial',
fetchedAt: first.meta.lastSuccessfulAt
? new Date(first.meta.lastSuccessfulAt)
: null,
freshForMs:
section === 'company'
? tbankSourceTtlMs.company
: tbankSourceTtlMs.quote,
work: null,
dependencies,
});
return {
values,
meta,
unavailable: sources
.filter(
(source) =>
source.meta.availability !== 'complete' ||
source.meta.sync.state === 'failed',
)
.map((source) => source.input.kind),
observedAt: meta.lastSuccessfulAt ?? new Date().toISOString(),
};
}
private async load(
input: CatalogSource,
token: string,
attempt: TbankSyncAttempt,
): Promise<CatalogPayload> {
if (input.kind === 'detail' || input.kind === 'bond-current') {
const instrument =
input.instrumentType === 'share'
? await this.tbank.getShare(token, input.uid)
: await this.tbank.getBond(token, input.uid);
if (instrument && instrument.uid !== input.uid)
throw new Error('Catalog UID mismatch');
if (instrument === undefined) throw new Error('Missing catalog response');
return { instrument: instrument ? publicInstrument(instrument) : null };
}
if (input.kind === 'trading-status')
return {
tradingStatus: await this.tbank.getTradingStatus(token, input.uid),
};
if (input.kind === 'comparison') {
const prices = await this.repository.readSources([
{ ...input, kind: 'last-price', rangeKey: undefined },
]);
if (!prices.length) throw new Error('Price dependency missing');
const price = (prices[0].payload as CatalogPayload).price;
const priceAt = timestamp(price?.time);
if (!priceAt) return { candle: null };
const now = new Date();
const range = {
from: utcDay(new Date(Date.parse(priceAt) - previousCloseLookbackMs)),
to: new Date(priceAt),
};
const saved = await this.candles.read(input.uid, range);
const gaps = candleGaps(range, saved.coverage, now);
for (const gap of gaps) {
const response = await this.tbank.getCandles(
token,
input.uid,
gap.from,
gap.to,
);
const rows = response.map((candle) => {
const time = timestamp(candle.time);
if (!time || !candle.close)
throw new Error('Invalid candle response');
return {
time,
close: formatDecimal(decimal(candle.close)),
isComplete: candle.isComplete === true,
};
});
if (!(await this.candles.stage(attempt, gap, rows, now)))
throw new Error('Cancelled candle comparison');
}
if (
gaps.length &&
!(await this.candles.publish(
attempt,
{ uid: input.uid, ranges: gaps },
false,
))
)
throw new Error('Cancelled candle comparison');
const values = (await this.candles.read(input.uid, range)).data.map(
(row) => {
const value = divide(
decimalFromString(row.close),
decimalFromString('1'),
quotationScale,
).value;
return {
time: {
seconds: String(Date.parse(row.time) / MILLISECONDS_PER_SECOND),
},
close: {
units: String(value / quotationUnits),
nano: Number(value % quotationUnits),
},
isComplete: row.isComplete,
};
},
);
return { candle: previousClose(values, priceAt) };
}
const details = await this.repository.readSources([
{ ...input, kind: 'detail', rangeKey: undefined },
...(input.instrumentType === 'bond'
? [{ ...input, kind: 'bond-current' as const, rangeKey: undefined }]
: []),
]);
const instrument = details
.map((row) => (row.payload as CatalogPayload).instrument)
.find(Boolean);
if (
!instrument &&
!['dividends', 'coupons', 'bond-events'].includes(input.kind)
)
throw new Error('Instrument dependency missing');
if (input.kind === 'description')
return {
description: instrument?.assetUid
? await this.tbank.getAssetDescription(token, instrument?.assetUid)
: null,
};
if (input.kind === 'fundamentals')
return {
fundamentals: instrument?.assetUid
? await this.tbank.getFundamentals(token, instrument?.assetUid)
: null,
};
if (input.kind === 'coupons' || input.kind === 'dividends') {
const year = Number(input.rangeKey);
const [from, to] = input.rangeKey?.startsWith('[')
? (JSON.parse(input.rangeKey) as [string, string])
: [
`${year - payoutHistoryYears}-01-01`,
`${year + payoutFutureYears}-01-01`,
];
return input.kind === 'coupons'
? {
coupons: await this.tbank.getBondCoupons(
token,
input.uid,
from,
to,
),
}
: {
dividends: await this.tbank.getDividends(
token,
input.uid,
from,
to,
),
};
}
if (input.kind === 'bond-events') {
const ticker = instrument?.ticker || input.ticker;
if (!ticker) throw new Error('Bond ticker missing');
return { bondEvents: await this.moex.bondEvents(ticker) };
}
if (input.kind === 'yield')
return {
effectiveYield:
instrument?.ticker && instrument.isin && instrument.classCode
? await this.moex.bondYield(
instrument.ticker,
instrument.isin,
instrument.classCode,
)
: null,
};
if (input.kind === 'rating')
return {
creditRating: instrument?.isin
? await this.ratings.rating(instrument.isin)
: null,
};
throw new Error('Unsupported catalog source');
}
private async drain() {
try {
while (this.queue.length) {
const producer = this.queue.shift();
if (!producer) break;
const batch = [producer];
// One batch RPC for queued prices sharing the same authorized producer.
if (producer.input.kind === 'last-price') {
for (
let i = 0;
i < this.queue.length && batch.length < catalogSearchLimit;
) {
const next = this.queue[i];
if (
next.input.kind === 'last-price' &&
next.attempt.userId === producer.attempt.userId &&
next.attempt.revision === producer.attempt.revision
) {
batch.push(next);
this.queue.splice(i, 1);
} else i++;
}
}
let prices: TbankLastPrice[] | undefined;
let payload: CatalogPayload | undefined;
let failed = false;
try {
const token = await this.access.tokenForAttempt(producer.attempt);
if (!token) failed = true;
else if (producer.input.kind === 'last-price')
prices = await this.tbank.getLastPrices(
token,
batch.map((item) => item.input.uid),
);
else
payload = await this.load(producer.input, token, producer.attempt);
} catch (error) {
failed = true;
if (error instanceof Error && error.message === 'INVALID_TBANK_TOKEN')
await this.access.rejectMembershipToken(producer.attempt);
else
this.logger.event('warn', 'catalog-enrichment.failed', {
code: 'TBANK_UNAVAILABLE',
});
}
for (const item of batch) {
const price =
prices?.find((entry) => entry.instrumentUid === item.input.uid) ??
null;
const value =
item.input.kind === 'last-price'
? {
price: price
? {
instrumentUid: item.input.uid,
price: price.price,
time: price.time,
}
: null,
}
: payload;
// Keep accepting observers while publication awaits SQLite.
item.observers.unshift({ attempt: item.attempt, input: item.input });
for (const observer of item.observers) {
const success =
!failed &&
value !== undefined &&
(await this.repository.publishSource(
observer.attempt,
observer.input,
value,
new Date(),
producer.attempt,
));
await this.repository.finish(observer.attempt, success);
this.active.delete(observer.attempt.attemptId);
this.completions.get(observer.attempt.attemptId)?.resolve();
this.completions.delete(observer.attempt.attemptId);
}
this.producers.delete(producerKey(item.input));
}
}
} catch {
for (const completion of this.completions.values()) completion.resolve();
this.completions.clear();
this.active.clear();
this.producers.clear();
this.queue.length = 0;
this.logger.event('error', 'catalog-enrichment.persistence-failed', {
code: 'TBANK_UNAVAILABLE',
});
} finally {
this.running = false;
}
}
}
function sourceInputs(
instrumentType: 'share' | 'bond',
uids: string[],
kinds: CatalogSource['kind'][],
range?: {
from: string;
to: string;
ticker?: string;
tickers?: Record<string, string>;
},
): CatalogSource[] {
return kinds.flatMap((kind) =>
[...new Set(uids)].map((uid) => ({
instrumentType,
uid,
kind,
...(kind === 'bond-events' && (range?.tickers?.[uid] || range?.ticker)
? { ticker: range?.tickers?.[uid] || range?.ticker }
: {}),
...(['coupons', 'dividends'].includes(kind)
? {
rangeKey: range
? JSON.stringify([range.from, range.to])
: String(new Date().getUTCFullYear()),
}
: {}),
})),
);
}
function publicInstrument(value: TbankShare | TbankBond) {
const bond = value as TbankBond;
return {
uid: value.uid,
figi: value.figi,
assetUid: value.assetUid,
name: value.name,
ticker: value.ticker,
isin: value.isin,
classCode: value.classCode,
realExchange: value.realExchange,
apiTradeAvailableFlag: value.apiTradeAvailableFlag,
currency: value.currency,
shareType: (value as TbankShare).shareType,
sector: value.sector,
lot: value.lot,
brand: value.brand ? { logoName: value.brand.logoName } : undefined,
first_1dayCandleDate: value.first_1dayCandleDate,
nominal: bond.nominal,
initialNominal: bond.initialNominal,
aciValue: bond.aciValue,
maturityDate: bond.maturityDate,
callDate: bond.callDate,
couponQuantityPerYear: bond.couponQuantityPerYear,
floatingCouponFlag: bond.floatingCouponFlag,
perpetualFlag: bond.perpetualFlag,
amortizationFlag: bond.amortizationFlag,
subordinatedFlag: bond.subordinatedFlag,
bondType: bond.bondType,
riskLevel: bond.riskLevel,
};
}
const previousCloseLookbackDays = 20;
const previousCloseLookbackMs =
previousCloseLookbackDays * MILLISECONDS_PER_DAY;
const payoutHistoryYears = 5;
const payoutFutureYears = 2;
export type CatalogPayload = {
instrument?: TbankShare | TbankBond | null;
price?: TbankLastPrice | null;
candle?: TbankCandle | null;
tradingStatus?: string | null;
description?: string | null;
fundamentals?: TbankFundamentals | null;
coupons?: TbankCoupon[];
dividends?: TbankDividend[];
bondEvents?: MoexBondEvent[];
effectiveYield?: Awaited<ReturnType<MoexClient['bondYield']>>;
creditRating?: Awaited<ReturnType<NcrRatingsClient['rating']>>;
};
function sourcePolicy(kind: CatalogSource['kind']) {
if (
[
'last-price',
'bond-current',
'trading-status',
'comparison',
'yield',
].includes(kind)
)
return 'quote';
if (kind === 'description' || kind === 'fundamentals') return 'company';
if (['coupons', 'dividends', 'bond-events'].includes(kind)) return 'calendar';
return 'metadata';
}
function producerKey(input: CatalogSource) {
return input.instrumentType === 'bond' &&
(input.kind === 'detail' || input.kind === 'bond-current')
? `bond-metadata:${input.uid}`
: catalogScope(input);
}
const quotationScale = 9;
const quotationUnits = 1_000_000_000n;
@@ -0,0 +1,39 @@
import type { TbankShare } from '../../../../integrations/tbank/tbank.api';
export const catalogSearchLimit = 30;
export function selectCatalogInstruments<T extends TbankShare>(
found: T[],
query: string,
instrumentType: 'share' | 'bond',
): (T & { uid: string })[] {
const seen = new Set<string>();
const kind =
instrumentType === 'share'
? 'INSTRUMENT_TYPE_SHARE'
: 'INSTRUMENT_TYPE_BOND';
const preferredClass = instrumentType === 'share' ? 'TQBR' : 'TQOB';
return found
.filter(
(instrument): instrument is T & { uid: string } =>
Boolean(instrument.uid?.trim()) && instrument.instrumentKind === kind,
)
.sort(
(a, b) =>
Number(b.apiTradeAvailableFlag === true) -
Number(a.apiTradeAvailableFlag === true) ||
Number(b.ticker?.toUpperCase() === query.toUpperCase()) -
Number(a.ticker?.toUpperCase() === query.toUpperCase()) ||
Number(b.classCode === preferredClass) -
Number(a.classCode === preferredClass) ||
a.uid.localeCompare(b.uid),
)
.filter((instrument) => {
const key = instrument.isin?.trim()
? `isin:${instrument.isin.trim().toUpperCase()}`
: `uid:${instrument.uid}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
@@ -1,205 +1,85 @@
import {
ConflictException,
Injectable,
NotFoundException,
ServiceUnavailableException,
} from '@nestjs/common';
import { LRUCache } from 'lru-cache';
import { CatalogDiscoveryService } from '../../application/catalog-discovery.service';
import { Injectable } from '@nestjs/common';
import { formatDecimal } from '../../../../../common/decimal';
import type { TbankBond } from '../../../../../integrations/tbank/tbank.api';
import {
TbankAccessService,
TbankClient,
type TbankConnectionContext,
} from '../../../../../integrations/tbank/tbank.api';
import { decimal } from '../../../../../integrations/tbank/decimal';
import { optional, timestamp } from '../../application/instrument-market';
import { BondDto, BondSearchResultDto } from '../presentation/bond.dto';
import { timestamp } from '../../application/instrument-market';
import {
BondDto,
BondResourceDto,
BondSearchResourceDto,
} from '../presentation/bond.dto';
type IdentifiedBond = TbankBond & { uid: string };
import { money } from '../infrastructure/bond-money.mapper';
const SEARCH_RESULTS_LIMIT = 30;
@Injectable()
export class BondCatalogService {
private readonly cache = new LRUCache<string, Promise<object>>({
max: 300,
ttl: 30_000,
});
constructor(
private readonly access: TbankAccessService,
private readonly tbank: TbankClient,
) {}
search(userId: string, query: string): Promise<BondSearchResultDto[]> {
return this.cached(userId, `search:${query}`, async (connection) => {
const { token } = connection;
const found = await this.tbank.findBonds(token, query);
const bonds = selectBonds(found, query).slice(0, SEARCH_RESULTS_LIMIT);
if (!bonds.length) return [];
// Batch prices and share metadata with detail sections. Resolve readable
// aliases only when an issue is opened, not for every search result.
const [details, prices] = await Promise.all([
Promise.all(
bonds.map(
async (bond) =>
(await optional(
() =>
this.bond(userId, connection, bond.uid)
.then(toBond)
.catch((error: unknown) => {
if (error instanceof NotFoundException)
return toBond(bond);
throw error;
}),
'details',
[],
)) ?? toBond(bond),
),
),
optional(
() =>
this.tbank.getLastPrices(
token,
bonds.map((bond) => bond.uid),
),
'prices',
[],
),
]);
return details.map((detail, index) => {
const short = toBond(bonds[index]);
const last = prices?.find(
(price) => price.instrumentUid === detail.instrumentUid,
);
return {
...detail,
classCode: detail.classCode ?? short.classCode,
isin: detail.isin ?? short.isin,
apiTradeAvailable: short.apiTradeAvailable,
pricePercent: last?.price ? formatDecimal(decimal(last.price)) : null,
priceAt: timestamp(last?.time),
};
});
});
}
get(userId: string, uid: string): Promise<BondDto> {
return this.cached(userId, `bond:${uid}`, async (connection) => {
const result = toBond(await this.bond(userId, connection, uid));
if (
!result.ticker ||
!/^[A-Za-z0-9][A-Za-z0-9._@+-]{0,79}$/.test(result.ticker)
)
return result;
try {
const match = await this.tickerMatch(userId, result.ticker);
if (match.uid === uid) result.slug = result.ticker.toUpperCase();
} catch (error) {
// A readable alias is optional for an exact UID URL, never a reason to substitute another listing.
if (
!(error instanceof NotFoundException) &&
!(error instanceof ConflictException) &&
!(error instanceof ServiceUnavailableException)
)
throw error;
}
return result;
});
}
async getByTicker(userId: string, ticker: string): Promise<BondDto> {
const match = await this.tickerMatch(userId, ticker);
constructor(private readonly discovery: CatalogDiscoveryService) {}
async search(
userId: string,
query: string,
observe = false,
): Promise<BondSearchResourceDto> {
const result = await this.discovery.search(
userId,
{ instrumentType: 'bond', query },
observe,
);
return {
...(await this.get(userId, match.uid)),
slug: ticker.trim().toUpperCase(),
...result,
data:
result.data?.map((item) => {
const short = toBond(item);
const detail = item.detail
? toBond({ ...item.detail, uid: item.uid })
: short;
const last = item.price;
return {
...detail,
classCode: detail.classCode ?? short.classCode,
isin: detail.isin ?? short.isin,
apiTradeAvailable: short.apiTradeAvailable,
pricePercent: last?.price
? formatDecimal(decimal(last.price))
: null,
priceAt: timestamp(last?.time),
};
}) ?? null,
};
}
private tickerMatch(userId: string, ticker: string): Promise<IdentifiedBond> {
const normalized = ticker.trim().toUpperCase();
return this.cached(userId, `ticker:${normalized}`, async (connection) => {
const { token } = connection;
const found = await this.tbank.findBonds(token, normalized);
const matches = selectBonds(
found.filter(
(item) => item.ticker?.trim().toUpperCase() === normalized,
),
normalized,
);
if (!matches.length) throw new NotFoundException();
if (matches.length > 1)
throw new ConflictException({ code: 'BOND_TICKER_AMBIGUOUS' });
return matches[0];
});
}
bond(
async get(
userId: string,
connection: TbankConnectionContext,
uid: string,
): Promise<IdentifiedBond> {
return this.cachedForConnection(
observe = false,
): Promise<BondResourceDto> {
const result = await this.discovery.detail(userId, 'bond', uid, observe);
return {
...result,
data: result.data
? { ...toBond(result.data), slug: result.data.slug }
: null,
};
}
async getByTicker(
userId: string,
ticker: string,
observe = false,
): Promise<BondResourceDto> {
const result = await this.discovery.byTicker(
userId,
connection,
`metadata:${uid}`,
async () => {
const bond = await this.tbank.getBond(connection.token, uid);
if (!bond || bond.uid !== uid) throw new NotFoundException();
return { ...bond, uid };
},
'bond',
ticker,
observe,
);
return {
...result,
data: result.data
? { ...toBond(result.data), slug: result.data.slug }
: null,
};
}
cached<T extends object>(
userId: string,
key: string,
operation: (connection: TbankConnectionContext) => Promise<T>,
): Promise<T> {
return this.access.withConnection(userId, (connection) =>
this.cachedForConnection(userId, connection, key, () =>
operation(connection),
),
);
}
cachedForConnection<T extends object>(
userId: string,
{ generation }: TbankConnectionContext,
key: string,
operation: () => Promise<T>,
): Promise<T> {
const cacheKey = JSON.stringify([userId, generation, key]);
const cached = this.cache.get(cacheKey);
if (cached) return cached as Promise<T>;
const pending = operation();
this.cache.set(cacheKey, pending);
return pending.catch((error) => {
if (this.cache.get(cacheKey) === pending) this.cache.delete(cacheKey);
throw error;
});
}
}
function selectBonds(found: TbankBond[], query: string): IdentifiedBond[] {
const seen = new Set<string>();
return found
.filter(
(bond): bond is IdentifiedBond =>
Boolean(bond.uid) && bond.instrumentKind === 'INSTRUMENT_TYPE_BOND',
)
.sort(
(a, b) =>
Number(b.apiTradeAvailableFlag === true) -
Number(a.apiTradeAvailableFlag === true) ||
Number(b.ticker?.toUpperCase() === query.toUpperCase()) -
Number(a.ticker?.toUpperCase() === query.toUpperCase()) ||
Number(b.classCode === 'TQOB') - Number(a.classCode === 'TQOB') ||
a.uid.localeCompare(b.uid),
)
.filter((bond) => {
// A missing ISIN must not collapse unrelated catalog instruments.
const key = bond.isin?.trim()
? `isin:${bond.isin.trim().toUpperCase()}`
: `uid:${bond.uid}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
function toBond(bond: IdentifiedBond): BondDto {
@@ -1,208 +1,251 @@
import { Injectable } from '@nestjs/common';
import { Injectable, NotFoundException } from '@nestjs/common';
import {
decimalFromString,
divide,
formatDecimal,
multiply,
divide,
} from '../../../../../common/decimal';
import { MoexClient } from '../../../../../integrations/moex/moex.api';
import { NcrRatingsClient } from '../../../../../integrations/ncr/ncr.api';
import {
TbankClient,
type TbankConnectionContext,
TbankAccessService,
type TbankCoupon,
type TbankBond,
} from '../../../../../integrations/tbank/tbank.api';
import { PortfolioService } from '../../../portfolio/portfolio.api';
import {
moscowDay,
optional,
timestamp,
} from '../../application/instrument-market';
PortfolioService,
ForecastService,
} from '../../../portfolio/portfolio.api';
import {
CatalogEnrichmentService,
type CatalogPayload,
} from '../../application/catalog-enrichment.service';
import { moscowDay, timestamp } from '../../application/instrument-market';
import { instrumentPosition } from '../../application/instrument-position';
import {
BondCouponsDto,
BondMetricsDto,
BondCouponsResourceDto,
BondPositionDto,
BondMetricsDto,
BondMetricsResourceDto,
} from '../presentation/bond.dto';
import { BondMarketService } from './bond-market.service';
import { money } from '../infrastructure/bond-money.mapper';
import { BondCatalogService } from './bond-catalog.service';
import { bondQuote } from './bond-market.service';
const ISO_YEAR_LENGTH = 4;
const INCOME_HISTORY_YEARS = 5;
const COUPON_YIELD_DECIMAL_PLACES = 4;
@Injectable()
export class BondIncomeService {
constructor(
private readonly catalog: BondCatalogService,
private readonly tbank: TbankClient,
private readonly portfolios: PortfolioService,
private readonly market: BondMarketService,
private readonly moex: MoexClient,
private readonly ratings: NcrRatingsClient,
private readonly sources: CatalogEnrichmentService,
private readonly access: TbankAccessService,
private readonly forecasts: ForecastService,
) {}
metrics(userId: string, uid: string): Promise<BondMetricsDto> {
return this.catalog.cached(userId, `metrics:${uid}`, async (connection) => {
const instrument = await this.catalog.bond(userId, connection, uid);
const { ticker, isin, classCode } = instrument;
const today = moscowDay(new Date().toISOString());
const from = `${Number(today.slice(0, ISO_YEAR_LENGTH)) - INCOME_HISTORY_YEARS}${today.slice(ISO_YEAR_LENGTH)}`;
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
const unavailable: string[] = [];
const [events, quote, effectiveYield, creditRating] = await Promise.all([
optional(
() => this.couponEvents(userId, connection, uid, from, to),
'coupons',
unavailable,
),
optional(() => this.market.quote(userId, uid), 'quote', unavailable),
ticker && isin && classCode
? optional(
() => this.moex.bondYield(ticker, isin, classCode),
'yield',
unavailable,
)
: null,
isin
? optional(() => this.ratings.rating(isin), 'rating', unavailable)
: null,
]);
const next = events
?.filter((event) => {
const date = timestamp(event.couponDate)?.slice(0, 10);
return date && date >= today;
})
.sort(
(a, b) =>
Number(a.couponDate?.seconds) - Number(b.couponDate?.seconds),
)[0];
const coupon = money(next?.payOneBond);
const period = next?.couponPeriod;
const couponPeriodDays =
period && Number.isInteger(period) && period > 0 ? period : null;
const clean = quote?.cleanPrice;
const couponYieldPercent =
coupon &&
couponPeriodDays &&
clean &&
coupon.currency === clean.currency &&
decimalFromString(coupon.value).value >= 0n &&
decimalFromString(clean.value).value > 0n
? formatDecimal(
divide(
multiply(
decimalFromString(coupon.value),
decimalFromString('36500'),
),
multiply(
decimalFromString(String(couponPeriodDays)),
decimalFromString(clean.value),
),
COUPON_YIELD_DECIMAL_PLACES,
),
)
: null;
const couponType =
next?.couponType && next.couponType !== 'COUPON_TYPE_UNSPECIFIED'
? next.couponType
: instrument.floatingCouponFlag === true
? 'COUPON_TYPE_FLOATING'
: null;
return {
creditRating,
coupon,
couponDate: timestamp(next?.couponDate)?.slice(0, 10) ?? null,
couponType,
couponPeriodDays,
couponYieldPercent,
couponYieldPriceAt:
couponYieldPercent !== null ? (quote?.priceAt ?? null) : null,
effectiveYield,
unavailable,
observedAt: new Date().toISOString(),
};
});
}
private couponEvents(
async metrics(
userId: string,
connection: TbankConnectionContext,
uid: string,
from: string,
to: string,
) {
return this.catalog.cachedForConnection(
observe = false,
): Promise<BondMetricsResourceDto> {
const result = await this.sources.section(
userId,
connection,
`coupon-events:${uid}:${from}:${to}`,
() => this.tbank.getBondCoupons(connection.token, uid, from, to),
'bond',
uid,
'metrics',
observe,
);
return {
data: result.values.instrument
? bondMetrics(result.values, result.unavailable, result.observedAt)
: null,
meta: result.meta,
};
}
coupons(userId: string, uid: string): Promise<BondCouponsDto> {
return this.catalog.cached(userId, `coupons:${uid}`, async (connection) => {
await this.catalog.bond(userId, connection, uid);
const today = moscowDay(new Date().toISOString());
const from = `${Number(today.slice(0, ISO_YEAR_LENGTH)) - INCOME_HISTORY_YEARS}${today.slice(ISO_YEAR_LENGTH)}`;
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
const unavailable: string[] = [];
const [events, position] = await Promise.all([
this.couponEvents(userId, connection, uid, from, to),
optional(() => this.position(userId, uid), 'position', unavailable),
]);
const quantity =
position?.accounts.length &&
position.accounts.every((p) => decimalFromString(p.quantity).value > 0n)
? decimalFromString(position.quantity)
: null;
const coupons = events
.map((event) => {
const paymentDate = timestamp(event.couponDate)?.slice(0, 10) ?? null;
const recordDate = timestamp(event.fixDate)?.slice(0, 10) ?? null;
const perBond = money(event.payOneBond);
const timing = !paymentDate
? ('undated' as const)
: paymentDate >= today
? ('upcoming' as const)
: ('past' as const);
return {
number: event.couponNumber ?? null,
paymentDate,
recordDate,
perBond,
couponType: event.couponType ?? null,
periodDays: event.couponPeriod ?? null,
timing,
estimatedAmount:
quantity &&
perBond &&
timing === 'upcoming' &&
recordDate &&
recordDate >= today
? {
currency: perBond.currency,
value: formatDecimal(
multiply(quantity, decimalFromString(perBond.value)),
),
}
: null,
};
})
.sort((a, b) =>
(a.paymentDate ?? '').localeCompare(b.paymentDate ?? ''),
);
return {
coupons,
from,
to,
observedAt: new Date().toISOString(),
positionAt: quantity ? (position?.observedAt ?? null) : null,
estimateUnavailable: unavailable.length > 0,
positionIsStale: position?.isStale ?? false,
};
async readPosition(userId: string, uid: string, observe = false) {
const saved = await this.portfolios.read(userId, 'all', observe);
return {
data: saved.data ? instrumentPosition(saved.data, uid, 'BOND') : null,
meta: { ...saved.meta, resourceKey: `bond/position/${uid}` },
};
}
async coupons(
userId: string,
uid: string,
observe = false,
): Promise<BondCouponsResourceDto> {
const connection = await this.access.local(userId);
const today = moscowDay(new Date().toISOString());
const from = `${Number(today.slice(0, ISO_YEAR_LENGTH)) - INCOME_HISTORY_YEARS}${today.slice(ISO_YEAR_LENGTH)}`;
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
const portfolio = await this.portfolios.read(userId, 'all', observe);
const sources = await this.sources.readMany(
userId,
'bond',
[uid],
observe,
['detail', 'coupons'],
{ from, to },
);
if (sources[0].meta.availability === 'complete' && !sources[0].instrument)
throw new NotFoundException();
const events = sources[1].payload?.coupons;
const position = portfolio.data
? instrumentPosition(portfolio.data, uid, 'BOND')
: null;
const projected = events
? bondCoupons(
events,
position,
{ from, to, today },
sources[1].meta.lastSuccessfulAt ?? new Date().toISOString(),
!portfolio.data,
)
: undefined;
const result = await this.forecasts.result({
userId,
revision: connection.revision,
membershipRevision: connection.membershipRevision,
scopeKey: `bond/coupons/${JSON.stringify([uid, from, to])}`,
portfolio: portfolio.meta,
sources,
candidate:
portfolio.data && sources[0].instrument ? projected : undefined,
});
}
async position(userId: string, uid: string): Promise<BondPositionDto> {
return this.catalog.cached(userId, `position:${uid}`, async () =>
instrumentPosition(await this.portfolios.getAll(userId), uid, 'BOND'),
);
return result.data || !projected
? result
: {
data: bondCoupons(
events ?? [],
null,
{ from, to, today },
projected.observedAt,
true,
),
meta: { ...result.meta, availability: 'partial' },
};
}
}
export function bondCoupons(
events: TbankCoupon[],
position: BondPositionDto | null,
window: { from: string; to: string; today: string },
observedAt: string,
positionUnavailable: boolean,
): BondCouponsDto {
const { from, to, today } = window;
const quantity =
position?.accounts.length &&
position.accounts.every((p) => decimalFromString(p.quantity).value > 0n)
? decimalFromString(position.quantity)
: null;
const coupons = events
.map((event) => {
const paymentDate = timestamp(event.couponDate)?.slice(0, 10) ?? null;
const recordDate = timestamp(event.fixDate)?.slice(0, 10) ?? null;
const perBond = money(event.payOneBond);
const timing = !paymentDate
? ('undated' as const)
: paymentDate >= today
? ('upcoming' as const)
: ('past' as const);
return {
number: event.couponNumber ?? null,
paymentDate,
recordDate,
perBond,
couponType: event.couponType ?? null,
periodDays: event.couponPeriod ?? null,
timing,
estimatedAmount:
quantity &&
perBond &&
timing === 'upcoming' &&
recordDate &&
recordDate >= today
? {
currency: perBond.currency,
value: formatDecimal(
multiply(quantity, decimalFromString(perBond.value)),
),
}
: null,
};
})
.sort((a, b) => (a.paymentDate ?? '').localeCompare(b.paymentDate ?? ''));
return {
coupons,
from,
to,
observedAt: observedAt,
positionAt: quantity ? (position?.observedAt ?? null) : null,
estimateUnavailable: positionUnavailable,
positionIsStale: position?.isStale ?? false,
};
}
export function bondMetrics(
values: CatalogPayload,
unavailable: string[],
observedAt: string,
): BondMetricsDto {
const instrument = values.instrument as TbankBond;
const events = values.coupons;
const quote = bondQuote(values, unavailable, observedAt);
const effectiveYield = values.effectiveYield ?? null;
const creditRating = values.creditRating ?? null;
const today = moscowDay(new Date().toISOString());
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
const next = events
?.filter((event) => {
const date = timestamp(event.couponDate)?.slice(0, 10);
return date && date >= today && date <= to;
})
.sort(
(a, b) => Number(a.couponDate?.seconds) - Number(b.couponDate?.seconds),
)[0];
const coupon = money(next?.payOneBond);
const period = next?.couponPeriod;
const couponPeriodDays =
period && Number.isInteger(period) && period > 0 ? period : null;
const clean = quote?.cleanPrice;
const couponYieldPercent =
coupon &&
couponPeriodDays &&
clean &&
coupon.currency === clean.currency &&
decimalFromString(coupon.value).value >= 0n &&
decimalFromString(clean.value).value > 0n
? formatDecimal(
divide(
multiply(
decimalFromString(coupon.value),
decimalFromString('36500'),
),
multiply(
decimalFromString(String(couponPeriodDays)),
decimalFromString(clean.value),
),
COUPON_YIELD_DECIMAL_PLACES,
),
)
: null;
const couponType =
next?.couponType && next.couponType !== 'COUPON_TYPE_UNSPECIFIED'
? next.couponType
: instrument.floatingCouponFlag === true
? 'COUPON_TYPE_FLOATING'
: null;
return {
creditRating,
coupon,
couponDate: timestamp(next?.couponDate)?.slice(0, 10) ?? null,
couponType,
couponPeriodDays,
couponYieldPercent,
couponYieldPriceAt:
couponYieldPercent !== null ? (quote?.priceAt ?? null) : null,
effectiveYield,
unavailable,
observedAt,
};
}
@@ -1,4 +1,10 @@
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
import { CandleService } from '../../application/candle.service';
import type { TbankBond } from '../../../../../integrations/tbank/tbank.api';
import {
CatalogEnrichmentService,
type CatalogPayload,
} from '../../application/catalog-enrichment.service';
import { Injectable } from '@nestjs/common';
import {
add,
decimalFromString,
@@ -7,192 +13,110 @@ import {
multiply,
subtract,
} from '../../../../../common/decimal';
import { TbankClient } from '../../../../../integrations/tbank/tbank.api';
import { decimal } from '../../../../../integrations/tbank/decimal';
import { timestamp } from '../../application/instrument-market';
import {
optional,
previousClose,
timestamp,
} from '../../application/instrument-market';
import {
BondCandlesDto,
BondCandlesQueryDto,
BondQuoteDto,
BondQuoteResourceDto,
} from '../presentation/bond.dto';
const dayMs = 86_400_000;
import { money } from '../infrastructure/bond-money.mapper';
import { BondCatalogService } from './bond-catalog.service';
const PREVIOUS_CLOSE_LOOKBACK_DAYS = 20;
const HALF_YEAR_MONTHS = 6;
const YEAR_MONTHS = 12;
const CANDLE_WINDOW_DAYS = 365;
const PRICE_DECIMAL_PLACES = 9;
@Injectable()
export class BondMarketService {
constructor(
private readonly catalog: BondCatalogService,
private readonly tbank: TbankClient,
private readonly history: CandleService,
private readonly sources: CatalogEnrichmentService,
) {}
quote(userId: string, uid: string): Promise<BondQuoteDto> {
return this.catalog.cached(userId, `quote:${uid}`, async (connection) => {
const { token } = connection;
const instrument = await this.catalog.bond(userId, connection, 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 pricePercent = last?.price
? formatDecimal(decimal(last.price))
: null;
const nominal = money(instrument.nominal);
const aci = money(instrument.aciValue);
const cleanPrice =
pricePercent !== null &&
nominal &&
decimalFromString(nominal.value).value > 0n
? {
currency: nominal.currency,
value: formatDecimal(
divide(
multiply(
decimalFromString(pricePercent),
decimalFromString(nominal.value),
),
decimalFromString('100'),
PRICE_DECIMAL_PLACES,
),
),
}
: null;
const dirtyPrice =
cleanPrice && aci && aci.currency === cleanPrice.currency
? {
currency: cleanPrice.currency,
value: formatDecimal(
add(
decimalFromString(cleanPrice.value),
decimalFromString(aci.value),
),
),
}
: null;
const previous = priceAt
? await optional(
async () =>
previousClose(
await this.tbank.getCandles(
token,
uid,
new Date(
Date.parse(priceAt) - PREVIOUS_CLOSE_LOOKBACK_DAYS * dayMs,
),
new Date(priceAt),
),
priceAt,
),
'comparison',
unavailable,
)
: null;
return {
pricePercent,
cleanPrice,
aci,
dirtyPrice,
priceAt,
tradingStatus,
changePercentagePoints:
last?.price && previous?.close
? formatDecimal(
subtract(decimal(last.price), decimal(previous.close)),
)
: null,
previousCloseDate: timestamp(previous?.time)?.slice(0, 10) ?? null,
unavailable,
observedAt: new Date().toISOString(),
};
});
async quote(
userId: string,
uid: string,
observe = false,
): Promise<BondQuoteResourceDto> {
const result = await this.sources.section(
userId,
'bond',
uid,
'quote',
observe,
);
return {
data: result.values.instrument
? bondQuote(result.values, result.unavailable, result.observedAt)
: null,
meta: result.meta,
};
}
candles(
userId: string,
uid: string,
period: BondCandlesQueryDto['period'] = 'month',
): Promise<BondCandlesDto> {
return this.catalog.cached(
observe = false,
) {
return this.history.read(
userId,
`candles:${uid}:${period}`,
async (connection) => {
const { token } = connection;
const bond = await this.catalog.bond(userId, connection, uid);
const historyFrom = timestamp(bond.first_1dayCandleDate);
const to = new Date();
const from = new Date(to);
from.setUTCMonth(
from.getUTCMonth() -
(period === 'month'
? 1
: period === 'halfYear'
? HALF_YEAR_MONTHS
: YEAR_MONTHS),
);
if (period === 'all') {
if (!historyFrom)
throw new ServiceUnavailableException({
code: 'BOND_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, BondCandlesDto['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 + CANDLE_WINDOW_DAYS * 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: null,
historyFrom,
observedAt: new Date().toISOString(),
};
},
{ uid, instrumentType: 'bond', period },
observe,
);
}
}
export function bondQuote(
values: CatalogPayload,
unavailable: string[],
observedAt: string,
): BondQuoteDto {
const { price: last, candle: previous, tradingStatus = null } = values;
const instrument = values.instrument as TbankBond | undefined;
const priceAt = timestamp(last?.time);
const pricePercent = last?.price ? formatDecimal(decimal(last.price)) : null;
const nominal = money(instrument?.nominal);
const aci = money(instrument?.aciValue);
const cleanPrice =
pricePercent !== null &&
nominal &&
decimalFromString(nominal.value).value > 0n
? {
currency: nominal.currency,
value: formatDecimal(
divide(
multiply(
decimalFromString(pricePercent),
decimalFromString(nominal.value),
),
decimalFromString('100'),
PRICE_DECIMAL_PLACES,
),
),
}
: null;
const dirtyPrice =
cleanPrice && aci && aci.currency === cleanPrice.currency
? {
currency: cleanPrice.currency,
value: formatDecimal(
add(
decimalFromString(cleanPrice.value),
decimalFromString(aci.value),
),
),
}
: null;
return {
pricePercent,
cleanPrice,
aci,
dirtyPrice,
priceAt,
tradingStatus,
changePercentagePoints:
last?.price && previous?.close
? formatDecimal(subtract(decimal(last.price), decimal(previous.close)))
: null,
previousCloseDate: timestamp(previous?.time)?.slice(0, 10) ?? null,
unavailable,
observedAt,
};
}
@@ -1,24 +1,12 @@
import {
ConflictException,
NotFoundException,
ServiceUnavailableException,
UnauthorizedException,
} from '@nestjs/common';
import assert from 'node:assert/strict';
import { MoexClient } from '../../../../../integrations/moex/moex.client';
import { NcrRatingsClient } from '../../../../../integrations/ncr/ncr-ratings.client';
import { TbankAccessService } from '../../../../../integrations/tbank/tbank-access.service';
import { TbankClient } from '../../../../../integrations/tbank/tbank.client';
import { PortfolioService } from '../../../portfolio/application/portfolio.service';
import { BondIncomeService } from './bond-income.service';
import { BondMarketService } from './bond-market.service';
import { BondCatalogService } from './bond-catalog.service';
jest.mock('../../../../../integrations/tbank/tbank-access.service', () => ({
TbankAccessService: class TbankAccessService {},
import { bondCoupons, bondMetrics } from './bond-income.service';
import { bondQuote } from './bond-market.service';
import { instrumentPosition } from '../../application/instrument-position';
import type { PortfolioDto } from '../../../portfolio/portfolio.api';
jest.mock('../../../../../prisma/prisma.service', () => ({
PrismaService: class {},
}));
const time = (value: string) => ({ seconds: String(Date.parse(value) / 1000) });
const money = (units: string, currency = 'rub') => ({ units, currency });
const cacheClock = performance;
const bond = {
uid: 'uid',
ticker: 'BOND',
@@ -30,469 +18,160 @@ const bond = {
amortizationFlag: true,
first_1dayCandleDate: time('2024-01-01'),
};
function setup() {
let generation = 'a';
const tbank = {
findBonds: jest.fn().mockResolvedValue([bond]),
getBond: jest.fn().mockResolvedValue(bond),
getLastPrice: jest.fn().mockResolvedValue({
instrumentUid: 'uid',
price: { units: '98', nano: 125000000 },
time: time('2026-09-10T10:00:00Z'),
}),
getLastPrices: jest.fn().mockResolvedValue([]),
getTradingStatus: jest
.fn()
.mockResolvedValue('SECURITY_TRADING_STATUS_NORMAL_TRADING'),
getCandles: jest.fn().mockResolvedValue([
{ time: time('2026-09-09'), close: { units: '99' }, isComplete: true },
{ time: time('2026-09-10'), close: { units: '100' }, isComplete: true },
]),
getBondCoupons: jest.fn().mockResolvedValue([]),
};
const access = {
withConnection: jest.fn(
(user: string, handler: (context: unknown) => unknown) =>
handler({ token: user, generation }),
),
};
const portfolios = {
getAll: jest.fn().mockResolvedValue({
positions: [],
lastSuccessfulAt: '2026-09-10T00:00:00Z',
isStale: false,
}),
};
const ratings = { rating: jest.fn().mockResolvedValue(null) };
const moex = { bondYield: jest.fn().mockResolvedValue(null) };
const service = new BondCatalogService(
access as unknown as TbankAccessService,
tbank as unknown as TbankClient,
describe('bond financial projections', () => {
beforeEach(() =>
jest.useFakeTimers().setSystemTime(new Date('2026-09-10T10:00:00Z')),
);
const market = new BondMarketService(
service,
tbank as unknown as TbankClient,
);
const income = new BondIncomeService(
service,
tbank as unknown as TbankClient,
portfolios as unknown as PortfolioService,
market,
moex as unknown as MoexClient,
ratings as unknown as NcrRatingsClient,
);
return {
market,
income,
service,
ratings,
moex,
tbank,
access,
portfolios,
changeGeneration: () => {
generation = 'b';
},
};
}
describe('bond market use case', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2026-09-10T10:00:00Z'));
jest.spyOn(cacheClock, 'now').mockImplementation(() => Date.now());
});
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
it('shows the next coupon and its annualized current yield without extra T-Bank calls', async () => {
const { tbank, moex, market, income } = setup();
tbank.getBond.mockResolvedValue({ ...bond, classCode: 'TQOB' });
tbank.getBondCoupons.mockResolvedValue([
{
couponDate: time('2026-12-10'),
payOneBond: money('40'),
couponPeriod: 91,
couponType: 'COUPON_TYPE_VARIABLE',
},
{
couponDate: time('2026-10-10'),
payOneBond: money('30'),
couponPeriod: 90,
couponType: 'COUPON_TYPE_FIX',
},
{
couponDate: time('2026-09-01'),
payOneBond: money('90'),
couponPeriod: 90,
},
]);
const effectiveYield = {
value: '15.6262',
pricePercent: '53.384',
date: '2041-05-15',
dateType: 'MATDATE',
tradeAt: '2026-09-10T18:49:39Z',
};
moex.bondYield.mockResolvedValue(effectiveYield);
const [metrics] = await Promise.all([
income.metrics('user', 'uid'),
income.coupons('user', 'uid'),
market.quote('user', 'uid'),
]);
expect(metrics).toMatchObject({
coupon: { value: '30', currency: 'RUB' },
couponDate: '2026-10-10',
couponType: 'COUPON_TYPE_FIX',
couponPeriodDays: 90,
couponYieldPercent: '24.7983',
effectiveYield,
});
expect(moex.bondYield).toHaveBeenCalledWith('BOND', 'ISIN', 'TQOB');
expect(tbank.getBond).toHaveBeenCalledTimes(1);
expect(tbank.getBondCoupons).toHaveBeenCalledTimes(1);
expect(tbank.getLastPrice).toHaveBeenCalledTimes(1);
});
it.each(['unknown', 'currency', 'period', 'zero-price'])(
'does not invent coupon yield with %s inputs',
async (scenario) => {
const { tbank, income } = setup();
tbank.getBondCoupons.mockResolvedValue([
{
couponDate: time('2026-10-10'),
payOneBond:
scenario === 'unknown'
? undefined
: money('30', scenario === 'currency' ? 'usd' : 'rub'),
couponPeriod: scenario === 'period' ? 0 : 90,
},
{
couponDate: time('2026-12-10'),
payOneBond: money('50'),
couponPeriod: 90,
},
]);
if (scenario === 'zero-price')
tbank.getLastPrice.mockResolvedValue({ price: { units: '0' } });
expect(await income.metrics('user', 'uid')).toMatchObject({
couponDate: '2026-10-10',
couponYieldPercent: null,
});
},
);
it('keeps coupons when MOEX fails and never substitutes a risk level for a credit rating', async () => {
const { tbank, moex, income } = setup();
tbank.getBond.mockResolvedValue({
...bond,
classCode: 'TQOB',
floatingCouponFlag: true,
riskLevel: 'RISK_LEVEL_LOW',
});
moex.bondYield.mockRejectedValue(new ServiceUnavailableException());
expect(await income.metrics('user', 'uid')).toMatchObject({
effectiveYield: null,
coupon: null,
couponType: 'COUPON_TYPE_FLOATING',
couponYieldPercent: null,
unavailable: ['yield'],
});
tbank.getBondCoupons.mockRejectedValue(new UnauthorizedException());
await expect(income.metrics('other', 'uid')).rejects.toBeInstanceOf(
UnauthorizedException,
);
});
it('returns only the rating of the exact issue and isolates a registry outage', async () => {
const { ratings, income } = setup();
const creditRating = {
agency: 'NCR',
value: 'AAA.ru',
status: 'active',
date: '2026-04-17',
sourceUrl: 'https://ratings.ru/ratings/issues/123/',
observedAt: '2026-09-10T10:00:00Z',
};
ratings.rating.mockResolvedValue(creditRating);
expect(await income.metrics('user', 'uid')).toMatchObject({
creditRating,
});
expect(ratings.rating).toHaveBeenCalledWith('ISIN');
ratings.rating.mockRejectedValue(new ServiceUnavailableException());
expect(await income.metrics('other', 'uid')).toMatchObject({
creditRating: null,
unavailable: ['rating'],
});
});
it('opens concurrent sections within one upstream metadata request budget', async () => {
const { service, tbank, market, income } = setup();
tbank.getBond
.mockReset()
.mockResolvedValueOnce(bond)
.mockRejectedValue(
new ServiceUnavailableException({ code: 'TBANK_UNAVAILABLE' }),
);
await expect(
Promise.all([
service.getByTicker('user', 'BOND'),
market.quote('user', 'uid'),
market.candles('user', 'uid'),
income.coupons('user', 'uid'),
income.metrics('user', 'uid'),
]),
).resolves.toHaveLength(5);
expect(tbank.getBond).toHaveBeenCalledTimes(1);
expect(tbank.findBonds).toHaveBeenCalledTimes(1);
});
it('searches thirty issues without a separate ticker lookup for each result', async () => {
const { service, tbank, market, income } = setup();
const issues = Array.from({ length: 30 }, (_, index) => ({
...bond,
uid: `uid-${index}`,
isin: `ISIN-${index}`,
ticker: `BOND-${index}`,
}));
tbank.findBonds.mockResolvedValue(issues);
tbank.getBond.mockImplementation((_token: string, uid: string) =>
Promise.resolve(issues.find((item) => item.uid === uid)),
);
expect(await service.search('user', 'BOND')).toHaveLength(30);
expect(tbank.findBonds).toHaveBeenCalledTimes(1);
expect(tbank.getBond).toHaveBeenCalledTimes(30);
expect(tbank.getLastPrices).toHaveBeenCalledTimes(1);
await service.getByTicker('user', 'BOND-0');
await Promise.all([
market.quote('user', 'uid-0'),
market.candles('user', 'uid-0'),
income.coupons('user', 'uid-0'),
]);
expect(tbank.getBond).toHaveBeenCalledTimes(30);
expect(tbank.findBonds).toHaveBeenCalledTimes(2);
});
it('refreshes current nominal and accrued interest after the metadata TTL', async () => {
const { service, tbank, market } = setup();
await service.get('user', 'uid');
await jest.advanceTimersByTimeAsync(30_001);
tbank.getBond.mockResolvedValue({
...bond,
nominal: money('400'),
aciValue: money('3'),
});
expect(await market.quote('user', 'uid')).toMatchObject({
cleanPrice: { value: '392.5' },
dirtyPrice: { value: '395.5' },
});
expect(tbank.getBond).toHaveBeenCalledTimes(2);
});
it('keeps late metadata responses within their original connection generation', async () => {
const { tbank, changeGeneration, market } = setup();
let resolveOld: ((value: typeof bond) => void) | undefined;
tbank.getBond.mockReturnValueOnce(
new Promise((resolve) => {
resolveOld = resolve;
}),
);
const oldQuote = market.quote('user', 'uid');
changeGeneration();
tbank.getBond.mockResolvedValue({ ...bond, nominal: money('400') });
expect(await market.quote('user', 'uid')).toMatchObject({
cleanPrice: { value: '392.5' },
});
assert.ok(resolveOld);
resolveOld(bond);
await oldQuote;
expect(await market.quote('user', 'uid')).toMatchObject({
cleanPrice: { value: '392.5' },
});
expect(tbank.getBond).toHaveBeenCalledTimes(2);
});
it('keeps percent quotes separate from money and uses current amortized nominal', async () => {
const { market } = setup();
expect(await market.quote('user', 'uid')).toMatchObject({
pricePercent: '98.125',
cleanPrice: { value: '490.625', currency: 'RUB' },
aci: { value: '12', currency: 'RUB' },
dirtyPrice: { value: '502.625', currency: 'RUB' },
changePercentagePoints: '-0.875',
previousCloseDate: '2026-09-09',
});
});
it('does not invent dirty prices or mix currencies when accrued interest is absent or mismatched', async () => {
const { tbank, market } = setup();
tbank.getBond.mockResolvedValueOnce({ ...bond, aciValue: undefined });
expect(await market.quote('user', 'uid')).toMatchObject({
aci: null,
dirtyPrice: null,
});
tbank.getBond.mockResolvedValueOnce({
...bond,
aciValue: money('12', 'usd'),
});
expect(await market.quote('other', 'uid')).toMatchObject({
dirtyPrice: null,
});
tbank.getBond.mockResolvedValueOnce({ ...bond, nominal: undefined });
expect(await market.quote('third', 'uid')).toMatchObject({
pricePercent: '98.125',
cleanPrice: null,
dirtyPrice: null,
});
});
it('preserves absent coupon flags and dates without reporting false or zero', async () => {
const { service } = setup();
expect(await service.get('user', 'uid')).toMatchObject({
floatingCoupon: null,
perpetual: null,
couponQuantityPerYear: null,
maturityDate: null,
nominal: { value: '500', currency: 'RUB' },
amortization: true,
});
});
it('keeps distinct issues, deduplicates ISIN listings, and prices the selected exact UID', async () => {
const { service, tbank } = setup();
const listings = [
{ ...bond, uid: 'off', apiTradeAvailableFlag: false },
{ ...bond, uid: 'uid', apiTradeAvailableFlag: true },
{ ...bond, uid: 'second', isin: 'OTHER', ticker: 'OTHER' },
{ ...bond, uid: 'share', instrumentKind: 'INSTRUMENT_TYPE_SHARE' },
{ ...bond, uid: undefined },
{ ...bond, uid: '' },
];
tbank.findBonds.mockResolvedValue(listings);
tbank.getBond.mockImplementation((_token: string, uid: string) =>
Promise.resolve(listings.find((b) => b.uid === uid)),
);
tbank.getLastPrices.mockResolvedValue([
{ instrumentUid: 'uid', price: { units: '99' } },
{ instrumentUid: 'off', price: { units: '1' } },
]);
const results = await service.search('user', 'BOND');
expect(results.map((x) => x.instrumentUid)).toEqual(['uid', 'second']);
expect(results[0]).toMatchObject({ pricePercent: '99', slug: 'uid' });
expect((await service.get('user', 'off')).slug).toBe('off');
});
it('rejects ambiguous tickers and wrong instrument identities', async () => {
const { service, tbank } = setup();
tbank.findBonds.mockResolvedValue([
bond,
{ ...bond, uid: 'other', isin: 'OTHER' },
]);
await expect(service.getByTicker('user', 'bond')).rejects.toBeInstanceOf(
ConflictException,
);
tbank.getBond.mockResolvedValue({ ...bond, uid: 'other' });
await expect(service.get('user', 'uid')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('preserves catalog results on enrichment outage but never suppresses auth failures', async () => {
const { service, tbank } = setup();
tbank.getBond.mockRejectedValue(new ServiceUnavailableException());
tbank.getLastPrices.mockRejectedValue(new ServiceUnavailableException());
expect(await service.search('user', 'BOND')).toMatchObject([
{ instrumentUid: 'uid', pricePercent: null, nominal: { value: '500' } },
]);
tbank.getBond.mockRejectedValue(new UnauthorizedException());
await expect(service.search('other', 'BOND')).rejects.toBeInstanceOf(
UnauthorizedException,
);
});
it('keeps daily candles in percent, deduplicates boundaries and requires an all-history start', async () => {
const { tbank, market } = setup();
const history = await market.candles('user', 'uid', 'all');
expect(history.currency).toBeNull();
expect(history.candles.map((c) => c.close)).toEqual(['99', '100']);
for (const [, , from, to] of tbank.getCandles.mock.calls as [
string,
string,
Date,
Date,
][])
expect(to.valueOf() - from.valueOf()).toBeLessThanOrEqual(365 * 86400000);
tbank.getBond.mockResolvedValue({
...bond,
first_1dayCandleDate: undefined,
});
await expect(market.candles('other', 'uid', 'all')).rejects.toBeInstanceOf(
ServiceUnavailableException,
);
});
it('isolates caches by user and connection generation and retries failures', async () => {
const { service, tbank, changeGeneration } = setup();
await Promise.all([service.get('a', 'uid'), service.get('a', 'uid')]);
expect(tbank.getBond).toHaveBeenCalledTimes(1);
await service.get('b', 'uid');
changeGeneration();
await service.get('a', 'uid');
expect(tbank.getBond).toHaveBeenCalledTimes(3);
tbank.getBond.mockRejectedValueOnce(new ServiceUnavailableException());
await expect(service.get('c', 'uid')).rejects.toBeInstanceOf(
ServiceUnavailableException,
);
await expect(service.get('c', 'uid')).resolves.toMatchObject({
instrumentUid: 'uid',
});
});
it('estimates only future unfixed coupons from positive exact-UID bond holdings', async () => {
const { tbank, portfolios, income } = setup();
afterEach(() => jest.useRealTimers());
it('estimates only future unfixed payouts from exact UID holdings', () => {
const holding = {
instrumentUid: 'uid',
type: 'BOND',
quantity: '2',
averagePurchasePrice: { value: '490', currency: 'RUB' },
averagePurchasePrice: null,
currentValue: { value: '981.25', currency: 'RUB' },
absoluteReturn: { value: '1.25', currency: 'RUB' },
absoluteReturn: null,
};
portfolios.getAll.mockResolvedValue({
positions: [
holding,
{ ...holding, instrumentUid: 'other', quantity: '99' },
{ ...holding, type: 'STOCK', quantity: '999' },
const position = instrumentPosition(
{
positions: [
holding,
{ ...holding, instrumentUid: 'other', quantity: '99' },
{ ...holding, type: 'STOCK', quantity: '999' },
],
lastSuccessfulAt: '2026-09-10T00:00:00Z',
isStale: true,
} as PortfolioDto,
'uid',
'BOND',
);
const result = bondCoupons(
[
{
couponNumber: '1',
couponDate: time('2026-10-01'),
fixDate: time('2026-09-29'),
payOneBond: money('10'),
},
{
couponNumber: '2',
couponDate: time('2026-10-01'),
fixDate: time('2026-09-09'),
payOneBond: money('10'),
},
{
couponNumber: '3',
couponDate: time('2026-10-01'),
payOneBond: money('10'),
},
{
couponNumber: '4',
couponDate: time('2026-10-01'),
fixDate: time('2026-09-29'),
},
],
lastSuccessfulAt: '2026-09-10T00:00:00Z',
isStale: true,
position,
{ from: '2021-09-10', to: '2027-09-10', today: '2026-09-10' },
'source-time',
false,
);
expect(result.coupons[0].estimatedAmount).toEqual({
value: '20',
currency: 'RUB',
});
tbank.getBondCoupons.mockResolvedValue([
{
couponNumber: '1',
couponDate: time('2026-10-01'),
fixDate: time('2026-09-29'),
payOneBond: money('10'),
},
{
couponNumber: '2',
couponDate: time('2026-10-01'),
fixDate: time('2026-09-09'),
payOneBond: money('10'),
},
{
couponNumber: '3',
couponDate: time('2026-10-01'),
payOneBond: money('10'),
},
{
couponNumber: '4',
couponDate: time('2026-10-01'),
fixDate: time('2026-09-29'),
},
{
couponNumber: '5',
couponDate: time('2025-10-01'),
payOneBond: money('10'),
},
]);
const result = await income.coupons('user', 'uid');
expect(
result.coupons.find((c) => c.number === '1')?.estimatedAmount,
).toEqual({ value: '20', currency: 'RUB' });
expect(
result.coupons
.filter((c) => c.number !== '1')
.every((c) => c.estimatedAmount === null),
result.coupons.slice(1).every((row) => row.estimatedAmount === null),
).toBe(true);
expect(result.coupons.find((c) => c.number === '4')?.perBond).toBeNull();
expect(result.coupons[3].perBond).toBeNull();
expect(result.positionIsStale).toBe(true);
expect(await income.position('user', 'uid')).toMatchObject({
quantity: '2',
currentValue: { value: '981.25' },
expect(position.quantity).toBe('2');
});
it('preserves amortized nominal, ACI, percent quotes and annualized coupon yield', () => {
const values = {
instrument: bond,
price: { price: { units: '98', nano: 125000000 } },
candle: { close: { units: '99' } },
coupons: [
{
couponDate: time('2026-10-10'),
payOneBond: money('30'),
couponPeriod: 90,
},
],
};
expect(bondQuote(values, [], 'time')).toMatchObject({
pricePercent: '98.125',
cleanPrice: { currency: 'RUB', value: '490.625' },
dirtyPrice: { currency: 'RUB', value: '502.625' },
changePercentagePoints: '-0.875',
});
expect(bondMetrics(values, [], 'time')).toMatchObject({
couponDate: '2026-10-10',
couponYieldPercent: '24.7983',
creditRating: null,
});
});
it.each(['unknown', 'currency', 'period', 'zero-price'])(
'does not invent coupon yield with %s inputs',
(scenario) => {
const result = bondMetrics(
{
instrument: bond,
price: { price: { units: scenario === 'zero-price' ? '0' : '100' } },
coupons: [
{
couponDate: time('2026-10-10'),
payOneBond:
scenario === 'unknown'
? undefined
: money('30', scenario === 'currency' ? 'usd' : 'rub'),
couponPeriod: scenario === 'period' ? 0 : 90,
},
],
},
[],
'time',
);
expect(result.couponYieldPercent).toBeNull();
},
);
it('keeps absent and mismatched ACI unknown and never substitutes risk level for a rating', () => {
expect(
bondQuote(
{
instrument: { ...bond, aciValue: money('1', 'usd') },
price: { price: { units: '100' } },
},
[],
'time',
).dirtyPrice,
).toBeNull();
expect(
bondQuote(
{
instrument: { ...bond, aciValue: undefined },
price: { price: { units: '100' } },
},
[],
'time',
).dirtyPrice,
).toBeNull();
expect(
bondMetrics(
{
instrument: {
...bond,
riskLevel: 'RISK_LEVEL_LOW',
floatingCouponFlag: true,
},
},
['yield'],
'time',
),
).toMatchObject({
creditRating: null,
couponType: 'COUPON_TYPE_FLOATING',
couponYieldPercent: null,
});
});
});
@@ -1,3 +1,4 @@
import { InvestmentReadQueryDto } from '../../../investment-resource.dto';
import {
Controller,
Get,
@@ -14,15 +15,15 @@ import { AccessPayload, JwtAuthGuard } from '../../../../auth/auth.api';
import { BondIncomeService } from '../application/bond-income.service';
import { BondMarketService } from '../application/bond-market.service';
import {
BondCandlesDto,
BondCandlesResourceDto,
BondCandlesQueryDto,
BondCouponsDto,
BondDto,
BondMetricsDto,
BondPositionDto,
BondQuoteDto,
BondCouponsResourceDto,
BondResourceDto,
BondMetricsResourceDto,
BondPositionResourceDto,
BondQuoteResourceDto,
BondSearchQueryDto,
BondSearchResultDto,
BondSearchResourceDto,
BondTickerParamsDto,
} from './bond.dto';
import { BondCatalogService } from '../application/bond-catalog.service';
@@ -39,68 +40,91 @@ export class BondController {
private readonly income: BondIncomeService,
) {}
@Get(':uid/metrics')
@ApiOkResponse({ type: BondMetricsDto })
@ApiOkResponse({ type: BondMetricsResourceDto })
metrics(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.income.metrics(request.user.sub, uid);
return this.income.metrics(request.user.sub, uid, query.sync === 'observe');
}
@Get()
@ApiOkResponse({ type: [BondSearchResultDto] })
@ApiOkResponse({ type: BondSearchResourceDto })
search(
@Req() request: Request & { user: AccessPayload },
@Query() query: BondSearchQueryDto,
) {
return this.bonds.search(request.user.sub, query.query);
return this.bonds.search(
request.user.sub,
query.query,
query.sync === 'observe',
);
}
@Get('by-ticker/:ticker')
@ApiOkResponse({ type: BondDto })
@ApiOkResponse({ type: BondResourceDto })
getByTicker(
@Req() request: Request & { user: AccessPayload },
@Param() params: BondTickerParamsDto,
@Query() query: InvestmentReadQueryDto,
) {
return this.bonds.getByTicker(request.user.sub, params.ticker);
return this.bonds.getByTicker(
request.user.sub,
params.ticker,
query.sync === 'observe',
);
}
@Get(':uid')
@ApiOkResponse({ type: BondDto })
@ApiOkResponse({ type: BondResourceDto })
get(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.bonds.get(request.user.sub, uid);
return this.bonds.get(request.user.sub, uid, query.sync === 'observe');
}
@Get(':uid/quote')
@ApiOkResponse({ type: BondQuoteDto })
@ApiOkResponse({ type: BondQuoteResourceDto })
quote(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.market.quote(request.user.sub, uid);
return this.market.quote(request.user.sub, uid, query.sync === 'observe');
}
@Get(':uid/candles')
@ApiOkResponse({ type: BondCandlesDto })
@ApiOkResponse({ type: BondCandlesResourceDto })
candles(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: BondCandlesQueryDto,
) {
return this.market.candles(request.user.sub, uid, query.period);
return this.market.candles(
request.user.sub,
uid,
query.period,
query.sync === 'observe',
);
}
@Get(':uid/position')
@ApiOkResponse({ type: BondPositionDto })
@ApiOkResponse({ type: BondPositionResourceDto })
position(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.income.position(request.user.sub, uid);
return this.income.readPosition(
request.user.sub,
uid,
query.sync === 'observe',
);
}
@Get(':uid/coupons')
@ApiOkResponse({ type: BondCouponsDto })
@ApiOkResponse({ type: BondCouponsResourceDto })
coupons(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.income.coupons(request.user.sub, uid);
return this.income.coupons(request.user.sub, uid, query.sync === 'observe');
}
}
@@ -1,3 +1,4 @@
import { InvestmentResourceMetaDto } from '../../../investment-resource.dto';
import { ApiProperty } from '@nestjs/swagger';
import { MoneyDto } from '../../../../../common/money.dto';
@@ -175,3 +176,51 @@ export class BondMetricsDto {
@ApiProperty({ type: [String] }) declare unavailable: string[];
@ApiProperty({ format: 'date-time' }) declare observedAt: string;
}
export class BondPositionResourceDto {
@ApiProperty({ type: BondPositionDto, nullable: true })
declare data: BondPositionDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class BondSearchResourceDto {
@ApiProperty({ type: BondSearchResultDto, isArray: true, nullable: true })
declare data: BondSearchResultDto[] | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class BondResourceDto {
@ApiProperty({ type: BondDto, nullable: true }) declare data: BondDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class BondQuoteResourceDto {
@ApiProperty({ type: BondQuoteDto, nullable: true })
declare data: BondQuoteDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class BondMetricsResourceDto {
@ApiProperty({ type: BondMetricsDto, nullable: true })
declare data: BondMetricsDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class BondCandlesResourceDto {
@ApiProperty({ type: BondCandlesDto, nullable: true })
declare data: BondCandlesDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class BondCouponsResourceDto {
@ApiProperty({ type: BondCouponsDto, nullable: true })
declare data: BondCouponsDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
@@ -0,0 +1,73 @@
import {
candleGaps,
candleWindows,
confirmedCandleCoverage,
} from './candle-coverage';
const date = (value: string) => new Date(value);
describe('source-confirmed daily candle coverage', () => {
it('retains closed empty coverage while yesterday incomplete and open empty ranges require rereading after midnight', () => {
const range = { from: date('2026-09-20Z'), to: date('2026-09-26Z') };
const now = date('2026-09-25T23:59:50Z');
const coverage = confirmedCandleCoverage(
range,
[
{
time: '2026-09-24T00:00:00Z',
close: '1.000000001',
isComplete: false,
},
],
now,
);
expect(
coverage.map((row) => [
row.from.toISOString().slice(0, 10),
row.to.toISOString().slice(0, 10),
row.isComplete,
]),
).toEqual([
['2026-09-20', '2026-09-24', true],
['2026-09-24', '2026-09-25', false],
['2026-09-25', '2026-09-26', false],
]);
expect(candleGaps(range, coverage, date('2026-09-25T23:59:59Z'))).toEqual(
[],
);
expect(candleGaps(range, coverage, date('2026-09-26T00:00:01Z'))).toEqual([
{ from: date('2026-09-24Z'), to: range.to },
]);
expect(
candleGaps(
range,
confirmedCandleCoverage(range, [], date('2026-09-27Z')),
date('2030-01-01Z'),
),
).toEqual([]);
});
it('expires the mutable empty current day at exactly one minute', () => {
const range = { from: date('2026-09-25Z'), to: date('2026-09-26Z') };
const covered = confirmedCandleCoverage(
range,
[],
date('2026-09-25T08:00:00Z'),
);
expect(candleGaps(range, covered, date('2026-09-25T08:00:59Z'))).toEqual(
[],
);
expect(candleGaps(range, covered, date('2026-09-25T08:01:00Z'))).toEqual([
range,
]);
});
it('splits leap-year history into contiguous windows of at most 365 days', () => {
const range = { from: date('2020-01-01Z'), to: date('2026-09-25Z') };
const windows = candleWindows(range);
expect(windows[0].from).toEqual(range.from);
expect(windows.at(-1)?.to).toEqual(range.to);
windows.forEach((window, index) => {
expect(window.to.valueOf() - window.from.valueOf()).toBeLessThanOrEqual(
365 * 86400000,
);
if (index) expect(window.from).toEqual(windows[index - 1].to);
});
});
});
@@ -0,0 +1,90 @@
import { MILLISECONDS_PER_DAY } from '../../../../common/time';
export type CandleRange = { from: Date; to: Date };
export type CandleCoverage = CandleRange & {
isComplete: boolean;
fetchedAt: Date;
};
export type SavedCandle = {
time: string;
close: string;
isComplete: boolean;
};
const windowDays = 365;
const tailFreshForMs = 60_000;
export function utcDay(value: Date): Date {
return new Date(
Math.floor(value.valueOf() / MILLISECONDS_PER_DAY) * MILLISECONDS_PER_DAY,
);
}
// A clock transition never turns an unconfirmed range into closed coverage.
export function candleGaps(
range: CandleRange,
coverage: CandleCoverage[],
now: Date,
): CandleRange[] {
let gaps = [range];
for (const covered of coverage) {
if (
!covered.isComplete &&
(now.valueOf() - covered.fetchedAt.valueOf() >= tailFreshForMs ||
utcDay(now).valueOf() !== utcDay(covered.fetchedAt).valueOf())
)
continue;
gaps = gaps.flatMap((gap) => {
if (covered.to <= gap.from || covered.from >= gap.to) return [gap];
return [
...(covered.from > gap.from
? [{ from: gap.from, to: covered.from }]
: []),
...(covered.to < gap.to ? [{ from: covered.to, to: gap.to }] : []),
];
});
}
return gaps.filter((gap) => gap.from < gap.to);
}
export function candleWindows(range: CandleRange): CandleRange[] {
const windows: CandleRange[] = [];
for (let start = range.from.valueOf(); start < range.to.valueOf();) {
const end = Math.min(
start + windowDays * MILLISECONDS_PER_DAY,
range.to.valueOf(),
);
windows.push({ from: new Date(start), to: new Date(end) });
start = end;
}
return windows;
}
export function confirmedCandleCoverage(
range: CandleRange,
candles: SavedCandle[],
fetchedAt: Date,
): CandleCoverage[] {
const boundaries = new Set([range.from.valueOf(), range.to.valueOf()]);
const midnight = utcDay(fetchedAt).valueOf();
const incompleteDays = new Set(
candles
.filter((candle) => !candle.isComplete)
.map((candle) => utcDay(new Date(candle.time)).valueOf()),
);
for (const boundary of [
midnight,
...[...incompleteDays].flatMap((day) => [day, day + MILLISECONDS_PER_DAY]),
])
if (boundary > range.from.valueOf() && boundary < range.to.valueOf())
boundaries.add(boundary);
const sorted = [...boundaries].sort((a, b) => a - b);
return sorted.slice(1).map((to, index) => {
const from = sorted[index];
return {
from: new Date(from),
to: new Date(to),
fetchedAt,
isComplete:
to <= midnight && !incompleteDays.has(utcDay(new Date(from)).valueOf()),
};
});
}
@@ -0,0 +1,306 @@
import { Injectable } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { createHash } from 'node:crypto';
import type { Prisma } from '../../../../../generated/prisma/client';
import { PrismaService } from '../../../../prisma/prisma.service';
import type { TbankSyncAttempt } from '../../../../integrations/tbank/tbank-access.service';
import {
confirmedCandleCoverage,
type CandleRange,
type SavedCandle,
} from '../domain/candle-coverage';
const provider = 'tbank';
const interval = 'day';
type CandleIntent = {
instrumentType?: 'share' | 'bond';
uid: string;
ranges: CandleRange[];
period?: string;
now?: string;
force?: boolean;
};
@Injectable()
export class CandleRepository {
constructor(private readonly prisma: PrismaService) {}
read(uid: string, range: CandleRange) {
const identity = { provider, instrumentUid: uid, interval };
return this.prisma.$transaction(async (tx) => {
const candles = await tx.tbankCandle.findMany({
where: { ...identity, time: { gte: range.from, lt: range.to } },
orderBy: { time: 'asc' },
});
const coverage = await tx.tbankCandleCoverage.findMany({
where: { ...identity, from: { lt: range.to }, to: { gt: range.from } },
orderBy: [{ from: 'asc' }, { to: 'asc' }],
});
const data = candles.map((row) => ({
time: row.time.toISOString(),
close: row.close,
isComplete: row.isComplete,
}));
return {
data,
coverage,
dataRevision: createHash('sha256')
.update(JSON.stringify(data))
.digest('base64url'),
};
});
}
coverage(uids: string[]) {
return this.prisma.tbankCandleCoverage.findMany({
where: { provider, instrumentUid: { in: uids }, interval },
});
}
reserve(
owner: { userId: string; revision: string },
scopeKey: string,
intent: CandleIntent,
runId: string,
active: ReadonlySet<string>,
priority = 1,
) {
return this.prisma.$transaction(async (tx) => {
const current = await tx.tbankConnection.updateMany({
where: { ...owner, invalidToken: false },
data: { membershipRevision: { increment: 0 } },
});
if (!current.count) return null;
const scope = { ...owner, scopeKey };
const previous = await tx.tbankSyncWork.findUnique({
where: { userId_revision_scopeKey: scope },
});
if (
previous?.state === 'running' &&
previous.processRunId === runId &&
active.has(previous.attemptId)
)
return { work: previous, launch: false };
if (previous)
await tx.tbankSyncStage.deleteMany({ where: { workId: previous.id } });
const data = {
attemptId: randomUUID(),
processRunId: runId,
state: 'running',
priority,
intent: JSON.parse(JSON.stringify(intent)) as Prisma.InputJsonObject,
progress: {},
errorCode: null,
};
const work = await tx.tbankSyncWork.upsert({
where: { userId_revision_scopeKey: scope },
create: { ...scope, ...data, id: randomUUID() },
update: data,
});
return { work, launch: true };
});
}
work(userId: string, revision: string, scopeKey: string) {
return this.prisma.tbankSyncWork.findUnique({
where: { userId_revision_scopeKey: { userId, revision, scopeKey } },
});
}
stage(
attempt: TbankSyncAttempt,
range: CandleRange,
candles: SavedCandle[],
fetchedAt: Date,
) {
// Reject malformed financial input instead of publishing a false empty range.
for (const candle of candles)
if (
!Number.isFinite(Date.parse(candle.time)) ||
!/^-?\d+(?:\.\d+)?$/.test(candle.close)
)
throw new Error('Invalid candle');
const key = `${range.from.toISOString()}/${range.to.toISOString()}`;
const rows = [
...new Map(
candles
.filter(
(candle) =>
new Date(candle.time) >= range.from &&
new Date(candle.time) < range.to,
)
.map((candle) => [candle.time, candle]),
).values(),
];
return this.prisma.$transaction(async (tx) => {
const valid = await tx.tbankSyncWork.updateMany({
where: {
...attempt,
state: 'running',
connection: { invalidToken: false },
},
data: { progress: { lastWindow: key } },
});
if (!valid.count) return false;
const identity = {
workId: attempt.id,
attemptId: attempt.attemptId,
sourceKey: 'candles',
itemKey: key,
};
const payload = JSON.parse(
JSON.stringify({ range, candles: rows, fetchedAt }),
) as Prisma.InputJsonObject;
await tx.tbankSyncStage.upsert({
where: { workId_attemptId_sourceKey_itemKey: identity },
create: { ...identity, payload },
update: { payload },
});
return true;
});
}
publish(
attempt: TbankSyncAttempt,
intent: CandleIntent,
completeWork = true,
) {
return this.prisma.$transaction(async (tx) => {
const claimed = await tx.tbankSyncWork.updateMany({
where: {
...attempt,
state: 'running',
connection: { invalidToken: false },
},
data: {
...(completeWork ? { state: 'complete' } : {}),
errorCode: null,
},
});
if (!claimed.count) return false;
const staged = await tx.tbankSyncStage.findMany({
where: {
workId: attempt.id,
attemptId: attempt.attemptId,
sourceKey: 'candles',
},
});
if (
intent.ranges.some(
(range) =>
!staged.some(
(row) =>
row.itemKey ===
`${range.from.toISOString()}/${range.to.toISOString()}`,
),
)
)
throw new Error('Incomplete candle reconciliation');
const identity = { provider, instrumentUid: intent.uid, interval };
for (const range of intent.ranges) {
const row = staged.find(
(entry) =>
entry.itemKey ===
`${range.from.toISOString()}/${range.to.toISOString()}`,
);
if (!row) throw new Error('Incomplete candle reconciliation');
const payload = row.payload as {
candles: SavedCandle[];
fetchedAt: string;
};
const fetchedAt = new Date(payload.fetchedAt);
const old = await tx.tbankCandleCoverage.findMany({
where: {
...identity,
from: { lt: range.to },
to: { gt: range.from },
},
});
await tx.tbankCandleCoverage.deleteMany({
where: {
...identity,
from: { lt: range.to },
to: { gt: range.from },
},
});
// Preserve coverage outside the requested reconciliation boundaries.
for (const previous of old) {
for (const part of [
...(previous.from < range.from
? [{ from: previous.from, to: range.from }]
: []),
...(previous.to > range.to
? [{ from: range.to, to: previous.to }]
: []),
])
await tx.tbankCandleCoverage.create({
data: { ...previous, ...part },
});
}
await tx.tbankCandle.deleteMany({
where: { ...identity, time: { gte: range.from, lt: range.to } },
});
for (const candle of payload.candles)
await tx.tbankCandle.create({
data: {
...identity,
time: new Date(candle.time),
close: candle.close,
isComplete: candle.isComplete,
payload: candle,
fetchedAt,
},
});
for (const covered of confirmedCandleCoverage(
range,
payload.candles,
fetchedAt,
))
await tx.tbankCandleCoverage.create({
data: { ...identity, ...covered },
});
}
await tx.tbankSyncStage.deleteMany({
where: { workId: attempt.id, attemptId: attempt.attemptId },
});
return true;
});
}
completeObserver(attempt: TbankSyncAttempt, initiator: TbankSyncAttempt) {
return this.prisma.$transaction(async (tx) => {
const origin = await tx.tbankSyncWork.findFirst({
where: {
...initiator,
state: 'complete',
connection: { invalidToken: false },
},
});
if (!origin) return false;
const result = await tx.tbankSyncWork.updateMany({
where: {
...attempt,
state: 'running',
connection: { invalidToken: false },
},
data: { state: 'complete', errorCode: null },
});
return result.count > 0;
});
}
fail(attempt: TbankSyncAttempt, errorCode: string) {
return this.prisma.$transaction(async (tx) => {
await tx.tbankSyncWork.updateMany({
where: {
...attempt,
state: 'running',
connection: { invalidToken: false },
},
data: { state: 'failed', errorCode },
});
await tx.tbankSyncStage.deleteMany({
where: { workId: attempt.id, attemptId: attempt.attemptId },
});
});
}
}
@@ -0,0 +1,480 @@
import { Injectable } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import type { Prisma } from '../../../../../generated/prisma/client';
import { PrismaService } from '../../../../prisma/prisma.service';
import type { TbankSyncAttempt } from '../../../../integrations/tbank/tbank-access.service';
import type {
TbankBond,
TbankShare,
} from '../../../../integrations/tbank/tbank.api';
export type CatalogQuery = {
instrumentType: 'share' | 'bond';
query: string;
exactTicker?: boolean;
};
export type CatalogSource = {
instrumentType: 'share' | 'bond';
uid: string;
kind:
| 'detail'
| 'last-price'
| 'bond-current'
| 'description'
| 'fundamentals'
| 'trading-status'
| 'comparison'
| 'coupons'
| 'yield'
| 'rating'
| 'dividends'
| 'bond-events';
rangeKey?: string;
ticker?: string;
};
export type CatalogWork = CatalogQuery | CatalogSource;
export type CatalogInstrument = (TbankShare | TbankBond) & { uid: string };
const provider = 'tbank';
export function catalogQuery(input: CatalogQuery): CatalogQuery {
return {
instrumentType: input.instrumentType,
query: input.query.trim().toUpperCase(),
...(input.exactTicker ? { exactTicker: true } : {}),
};
}
export function catalogScope(input: CatalogWork) {
if ('uid' in input)
return `catalog-source:${JSON.stringify([
input.kind,
input.kind === 'detail' ? input.instrumentType : null,
input.rangeKey ?? '',
input.uid,
])}`;
return `${input.exactTicker ? 'ticker' : 'catalog'}:${JSON.stringify([input.instrumentType, input.query])}`;
}
@Injectable()
export class CatalogDiscoveryRepository {
constructor(private readonly prisma: PrismaService) {}
read(input: CatalogQuery) {
return this.prisma.$transaction(async (tx) => {
const alias = input.exactTicker
? await tx.tbankInstrumentLookup.findUnique({
where: {
provider_identifierType_identifier: {
provider,
identifierType: `${input.instrumentType}-ticker`,
identifier: input.query,
},
},
})
: null;
const discovery = input.exactTicker
? alias
? {
instrumentUids: alias.matchedUids,
fetchedAt: alias.fetchedAt,
dataRevision: alias.dataRevision,
}
: null
: await tx.tbankCatalogDiscovery.findUnique({
where: {
provider_instrumentType_query: {
provider,
instrumentType: input.instrumentType,
query: input.query,
},
},
});
if (!discovery) return { data: null, fetchedAt: null, dataRevision: '0' };
const uids = discovery.instrumentUids as string[];
const rows = await tx.tbankInstrumentSource.findMany({
where: {
provider,
instrumentUid: { in: uids },
source: provider,
kind: 'catalog',
rangeKey: input.instrumentType,
},
});
const byUid = new Map(rows.map((row) => [row.instrumentUid, row]));
// A damaged/missing dependency is unknown, never a confirmed empty search.
if (uids.some((uid) => !byUid.has(uid)))
return {
data: null,
fetchedAt: null,
dataRevision: String(discovery.dataRevision),
};
return {
data: uids.map((uid) => byUid.get(uid)?.payload as CatalogInstrument),
fetchedAt: discovery.fetchedAt,
dataRevision: [
discovery.dataRevision,
...uids.map((uid) => byUid.get(uid)?.dataRevision),
].join('/'),
};
});
}
readSources(inputs: CatalogSource[]) {
return this.prisma.tbankInstrumentSource.findMany({
where: {
provider,
OR: inputs.map((input) => ({
instrumentUid: input.uid,
kind: input.kind,
source: sourceProvider(input),
rangeKey:
input.kind === 'detail'
? input.instrumentType
: (input.rangeKey ?? ''),
})),
},
});
}
publishSource(
attempt: TbankSyncAttempt,
input: CatalogSource,
value: object,
now: Date,
initiator: TbankSyncAttempt = attempt,
) {
return this.prisma.$transaction(async (tx) => {
const origin = await tx.tbankSyncWork.updateMany({
where: {
...initiator,
state: { in: ['running', 'complete'] },
connection: { invalidToken: false },
},
data: { progress: {} },
});
if (!origin.count) return false;
const claimed = await tx.tbankSyncWork.updateMany({
where: {
...attempt,
state: 'running',
connection: { invalidToken: false },
},
data: { state: 'complete', progress: {} },
});
if (!claimed.count) return false;
const payload = JSON.parse(
JSON.stringify(value),
) as Prisma.InputJsonObject;
const identity = { provider, uid: input.uid };
await tx.tbankInstrument.upsert({
where: { provider_uid: identity },
update: {},
create: {
...identity,
metadata: {},
instrumentType: input.instrumentType,
fetchedAt: now,
},
});
const instrument = (
value as { instrument?: TbankShare | TbankBond | null }
).instrument;
if (
(input.kind === 'detail' || input.kind === 'bond-current') &&
instrument &&
(instrument.name?.trim() || instrument.ticker?.trim())
) {
const previous = await tx.tbankInstrument.findUniqueOrThrow({
where: { provider_uid: identity },
});
const metadata = JSON.parse(
JSON.stringify({
...instrument,
instrumentType: input.instrumentType,
}),
) as Prisma.InputJsonObject;
await tx.tbankInstrument.update({
where: { provider_uid: identity },
data: {
metadata,
instrumentType: input.instrumentType,
figi: instrument.figi ?? null,
ticker: instrument.ticker ?? null,
fetchedAt: now,
dataRevision: {
increment: isDeepStrictEqual(previous.metadata, metadata) ? 0 : 1,
},
},
});
for (const [identifierType, identifier] of [
['uid', input.uid],
['figi', instrument.figi],
] as const) {
if (!identifier) continue;
const alias = { provider, identifierType, identifier };
const previousAlias = await tx.tbankInstrumentLookup.findUnique({
where: { provider_identifierType_identifier: alias },
});
const matchedUids = [input.uid];
await tx.tbankInstrumentLookup.upsert({
where: { provider_identifierType_identifier: alias },
create: { ...alias, matchedUids, fetchedAt: now },
update: {
matchedUids,
fetchedAt: now,
dataRevision: {
increment: isDeepStrictEqual(
previousAlias?.matchedUids,
matchedUids,
)
? 0
: 1,
},
},
});
}
}
const key = {
provider,
instrumentUid: input.uid,
source: sourceProvider(input),
kind: input.kind,
rangeKey:
input.kind === 'detail'
? input.instrumentType
: (input.rangeKey ?? ''),
};
const previous = await tx.tbankInstrumentSource.findUnique({
where: { provider_instrumentUid_source_kind_rangeKey: key },
});
await tx.tbankInstrumentSource.upsert({
where: { provider_instrumentUid_source_kind_rangeKey: key },
create: { ...key, payload, fetchedAt: now },
update: {
payload,
fetchedAt: now,
dataRevision: {
increment: isDeepStrictEqual(previous?.payload, payload) ? 0 : 1,
},
},
});
return true;
});
}
reserve(
owner: { userId: string; revision: string },
input: CatalogWork,
runId: string,
active: ReadonlySet<string>,
) {
return this.prisma.$transaction(async (tx) => {
const current = await tx.tbankConnection.updateMany({
where: { ...owner, invalidToken: false },
data: { membershipRevision: { increment: 0 } },
});
if (!current.count) return null;
const scope = { ...owner, scopeKey: catalogScope(input) };
const previous = await tx.tbankSyncWork.findUnique({
where: { userId_revision_scopeKey: scope },
});
if (
previous?.state === 'running' &&
previous.processRunId === runId &&
active.has(previous.attemptId)
)
return { work: previous, launch: false };
const data = {
attemptId: randomUUID(),
processRunId: runId,
state: 'running',
priority: 1,
intent: { source: 'catalog', ...input },
progress: {},
errorCode: null,
};
const work = await tx.tbankSyncWork.upsert({
where: { userId_revision_scopeKey: scope },
create: { ...scope, ...data, id: randomUUID() },
update: data,
});
return { work, launch: true };
});
}
workMany(userId: string, revision: string, inputs: CatalogWork[]) {
return this.prisma.tbankSyncWork.findMany({
where: { userId, revision, scopeKey: { in: inputs.map(catalogScope) } },
select: { scopeKey: true, id: true, state: true, errorCode: true },
});
}
work(userId: string, revision: string, input: CatalogWork) {
return this.prisma.tbankSyncWork.findUnique({
where: {
userId_revision_scopeKey: {
userId,
revision,
scopeKey: catalogScope(input),
},
},
select: { id: true, state: true, errorCode: true },
});
}
publish(
attempt: TbankSyncAttempt,
input: CatalogQuery,
instruments: CatalogInstrument[],
now: Date,
) {
return this.prisma.$transaction(async (tx) => {
const claimed = await tx.tbankSyncWork.updateMany({
where: {
...attempt,
state: 'running',
connection: { invalidToken: false },
},
data: { state: 'complete', progress: {} },
});
if (!claimed.count) return false;
for (const instrument of instruments) {
// Discovery can create a minimal identity, but cannot overwrite verified metadata.
const identity = { provider, uid: instrument.uid };
const payload = JSON.parse(
JSON.stringify({
uid: instrument.uid,
figi: instrument.figi,
ticker: instrument.ticker,
name: instrument.name,
isin: instrument.isin,
classCode: instrument.classCode,
instrumentKind: instrument.instrumentKind,
apiTradeAvailableFlag: instrument.apiTradeAvailableFlag,
currency: instrument.currency,
brand: instrument.brand
? { logoName: instrument.brand.logoName }
: undefined,
}),
) as Prisma.InputJsonObject;
await tx.tbankInstrument.upsert({
where: { provider_uid: identity },
update: {},
create: {
...identity,
metadata: payload,
instrumentType: input.instrumentType,
figi: instrument.figi,
ticker: instrument.ticker,
fetchedAt: now,
},
});
const key = {
provider,
instrumentUid: instrument.uid,
source: provider,
kind: 'catalog',
rangeKey: input.instrumentType,
};
const previous = await tx.tbankInstrumentSource.findUnique({
where: { provider_instrumentUid_source_kind_rangeKey: key },
});
await tx.tbankInstrumentSource.upsert({
where: { provider_instrumentUid_source_kind_rangeKey: key },
create: { ...key, payload, fetchedAt: now },
update: {
payload,
fetchedAt: now,
dataRevision: {
increment: isDeepStrictEqual(previous?.payload, payload) ? 0 : 1,
},
},
});
}
const instrumentUids = instruments.map((instrument) => instrument.uid);
if (input.exactTicker) {
const key = {
provider,
identifierType: `${input.instrumentType}-ticker`,
identifier: input.query,
};
const previous = await tx.tbankInstrumentLookup.findUnique({
where: { provider_identifierType_identifier: key },
});
await tx.tbankInstrumentLookup.upsert({
where: { provider_identifierType_identifier: key },
create: { ...key, matchedUids: instrumentUids, fetchedAt: now },
update: {
matchedUids: instrumentUids,
fetchedAt: now,
dataRevision: {
increment: isDeepStrictEqual(
previous?.matchedUids,
instrumentUids,
)
? 0
: 1,
},
},
});
return true;
}
const key = {
provider,
instrumentType: input.instrumentType,
query: input.query,
};
const previous = await tx.tbankCatalogDiscovery.findUnique({
where: { provider_instrumentType_query: key },
});
await tx.tbankCatalogDiscovery.upsert({
where: { provider_instrumentType_query: key },
create: { ...key, instrumentUids, fetchedAt: now },
update: {
instrumentUids,
fetchedAt: now,
dataRevision: {
increment: isDeepStrictEqual(
previous?.instrumentUids,
instrumentUids,
)
? 0
: 1,
},
},
});
return true;
});
}
finish(attempt: TbankSyncAttempt, success: boolean) {
return this.prisma.$transaction(async (tx) => {
await tx.tbankSyncWork.updateMany({
where: {
...attempt,
state: 'running',
connection: { invalidToken: true },
},
data: { state: 'failed', errorCode: 'INVALID_TBANK_TOKEN' },
});
await tx.tbankSyncWork.updateMany({
where: {
...attempt,
state: 'running',
connection: { invalidToken: false },
},
data: {
state: success ? 'complete' : 'failed',
errorCode: success ? null : 'TBANK_UNAVAILABLE',
},
});
});
}
}
function sourceProvider(input: CatalogSource) {
return input.kind === 'yield' || input.kind === 'bond-events'
? 'moex'
: input.kind === 'rating'
? 'ncr'
: 'tbank';
}
@@ -0,0 +1,2 @@
export { StockIncomeService } from './stocks/application/stock-income.service';
export { BondIncomeService } from './bonds/application/bond-income.service';
@@ -0,0 +1,22 @@
import { Module } from '@nestjs/common';
import { MoexModule } from '../../../integrations/moex/moex.module';
import { NcrModule } from '../../../integrations/ncr/ncr.module';
import { TbankModule } from '../../../integrations/tbank/tbank.module';
import { CandleService } from './application/candle.service';
import { CandleRepository } from './infrastructure/candle.repository';
import { CatalogEnrichmentService } from './application/catalog-enrichment.service';
import { CatalogDiscoveryService } from './application/catalog-discovery.service';
import { CatalogDiscoveryRepository } from './infrastructure/catalog-discovery.repository';
@Module({
imports: [TbankModule, MoexModule, NcrModule],
providers: [
CandleService,
CandleRepository,
CatalogEnrichmentService,
CatalogDiscoveryService,
CatalogDiscoveryRepository,
],
exports: [CandleService, CatalogEnrichmentService, CatalogDiscoveryService],
})
export class InstrumentSourcesModule {}
@@ -0,0 +1,5 @@
export { CandleService } from './application/candle.service';
export { CatalogEnrichmentService } from './application/catalog-enrichment.service';
export type { CatalogPayload } from './application/catalog-enrichment.service';
export { CatalogDiscoveryService } from './application/catalog-discovery.service';
@@ -1,6 +1,5 @@
import { InstrumentSourcesModule } from './instrument-sources.module';
import { Module } from '@nestjs/common';
import { MoexModule } from '../../../integrations/moex/moex.module';
import { NcrModule } from '../../../integrations/ncr/ncr.module';
import { TbankModule } from '../../../integrations/tbank/tbank.module';
import { AuthModule } from '../../auth/auth.module';
import { PortfolioModule } from '../portfolio/portfolio.module';
@@ -15,8 +14,9 @@ import { StockController } from './stocks/presentation/stock.controller';
import { StockCatalogService } from './stocks/application/stock-catalog.service';
@Module({
imports: [AuthModule, TbankModule, MoexModule, NcrModule, PortfolioModule],
imports: [AuthModule, TbankModule, InstrumentSourcesModule, PortfolioModule],
controllers: [StockController, BondController],
exports: [StockIncomeService, BondIncomeService],
providers: [
BondIncomeService,
BondMarketService,
@@ -1,50 +1,42 @@
import { Injectable } from '@nestjs/common';
import type { TbankFundamentals } from '../../../../../integrations/tbank/tbank.api';
import { TbankClient } from '../../../../../integrations/tbank/tbank.api';
import { optional } from '../../application/instrument-market';
import { StockCompanyDto, StockMetricDto } from '../presentation/stock.dto';
import { StockCatalogService } from './stock-catalog.service';
import { CatalogEnrichmentService } from '../../application/catalog-enrichment.service';
import {
StockCompanyResourceDto,
StockMetricDto,
} from '../presentation/stock.dto';
@Injectable()
export class GetStockCompanyUseCase {
constructor(
private readonly catalog: StockCatalogService,
private readonly tbank: TbankClient,
) {}
execute(userId: string, uid: string): Promise<StockCompanyDto> {
return this.catalog.cached(userId, `company:${uid}`, async (token) => {
const share = await this.catalog.share(token, uid);
const unavailable: string[] = [];
const assetUid = share.assetUid;
if (!assetUid)
return {
description: null,
metrics: [],
unavailable,
observedAt: new Date().toISOString(),
};
const [description, fundamentals] = await Promise.all([
optional(
() => this.tbank.getAssetDescription(token, assetUid),
'description',
unavailable,
),
optional(
() => this.tbank.getFundamentals(token, assetUid),
'fundamentals',
unavailable,
),
]);
return {
description,
metrics: metrics(fundamentals, share.sector),
unavailable,
observedAt: new Date().toISOString(),
};
});
constructor(private readonly sources: CatalogEnrichmentService) {}
async execute(
userId: string,
uid: string,
observe = false,
): Promise<StockCompanyResourceDto> {
const result = await this.sources.section(
userId,
'share',
uid,
'company',
observe,
);
return {
data: result.values.instrument
? {
description: result.values.description ?? null,
metrics: metrics(
result.values.fundamentals ?? null,
result.values.instrument.sector,
),
unavailable: result.unavailable,
observedAt: result.observedAt,
}
: null,
meta: result.meta,
};
}
}
function metrics(
export function metrics(
values: TbankFundamentals | null,
sector?: string,
): StockMetricDto[] {
@@ -1,185 +1,87 @@
import {
ConflictException,
Injectable,
NotFoundException,
ServiceUnavailableException,
} from '@nestjs/common';
import { LRUCache } from 'lru-cache';
import { CatalogDiscoveryService } from '../../application/catalog-discovery.service';
import { Injectable } from '@nestjs/common';
import { formatDecimal } from '../../../../../common/decimal';
import type { TbankShare } from '../../../../../integrations/tbank/tbank.api';
import {
TbankAccessService,
TbankClient,
} from '../../../../../integrations/tbank/tbank.api';
import { decimal } from '../../../../../integrations/tbank/decimal';
import { optional, timestamp } from '../../application/instrument-market';
import { StockDto, StockSearchResultDto } from '../presentation/stock.dto';
const SEARCH_RESULTS_LIMIT = 30;
import { timestamp } from '../../application/instrument-market';
import {
StockDto,
StockResourceDto,
StockSearchResourceDto,
} from '../presentation/stock.dto';
type IdentifiedShare = TbankShare & { uid: string };
@Injectable()
export class StockCatalogService {
private readonly cache = new LRUCache<string, Promise<object>>({
max: 300,
ttl: 30_000,
});
constructor(
private readonly access: TbankAccessService,
private readonly tbank: TbankClient,
) {}
search(userId: string, query: string): Promise<StockSearchResultDto[]> {
return this.cached(userId, `search:${query}`, async (token) => {
const found = await this.tbank.findShares(token, query);
const shares = selectShares(found, query).slice(0, SEARCH_RESULTS_LIMIT);
if (!shares.length) return [];
// One market-data request for the list; failed enrichment must not hide a catalog result.
const [details, prices] = await Promise.all([
Promise.all(
shares.map(
async (share) =>
(await optional(
() =>
this.get(userId, share.uid).catch((error: unknown) => {
if (error instanceof NotFoundException) return stock(share);
throw error;
}),
'details',
[],
)) ?? stock(share),
),
),
optional(
() =>
this.tbank.getLastPrices(
token,
shares.map((share) => share.uid),
),
'prices',
[],
),
]);
return details.map((detail, index) => {
const short = stock(shares[index]);
const last = prices?.find(
(price) => price.instrumentUid === detail.instrumentUid,
);
return {
...detail,
classCode: detail.classCode ?? short.classCode,
isin: detail.isin ?? short.isin,
apiTradeAvailable: short.apiTradeAvailable,
price:
last?.price && detail.currency
? {
currency: detail.currency,
value: formatDecimal(decimal(last.price)),
}
: null,
priceAt: timestamp(last?.time),
};
});
});
}
get(userId: string, uid: string): Promise<StockDto> {
return this.cached(userId, `share:${uid}`, async (token) => {
const result = stock(await this.share(token, uid));
if (
!result.ticker ||
!/^[A-Za-z0-9][A-Za-z0-9._@+-]{0,79}$/.test(result.ticker)
)
return result;
try {
const match = await this.tickerMatch(userId, result.ticker);
if (match.uid === uid) result.slug = result.ticker.toUpperCase();
} catch (error) {
// A readable alias is optional for an exact UID URL, never a reason to substitute another listing.
if (
!(error instanceof NotFoundException) &&
!(error instanceof ConflictException) &&
!(error instanceof ServiceUnavailableException)
)
throw error;
}
return result;
});
}
async getByTicker(userId: string, ticker: string): Promise<StockDto> {
const match = await this.tickerMatch(userId, ticker);
constructor(private readonly discovery: CatalogDiscoveryService) {}
async search(
userId: string,
query: string,
observe = false,
): Promise<StockSearchResourceDto> {
const result = await this.discovery.search(
userId,
{ instrumentType: 'share', query },
observe,
);
return {
...(await this.get(userId, match.uid)),
slug: ticker.trim().toUpperCase(),
...result,
data:
result.data?.map((item) => {
const short = stock(item);
const detail = item.detail
? stock({ ...item.detail, uid: item.uid })
: short;
const last = item.price;
return {
...detail,
classCode: detail.classCode ?? short.classCode,
isin: detail.isin ?? short.isin,
apiTradeAvailable: short.apiTradeAvailable,
price:
last?.price && detail.currency
? {
currency: detail.currency,
value: formatDecimal(decimal(last.price)),
}
: null,
priceAt: timestamp(last?.time),
};
}) ?? null,
};
}
private tickerMatch(
async get(
userId: string,
uid: string,
observe = false,
): Promise<StockResourceDto> {
const result = await this.discovery.detail(userId, 'share', uid, observe);
return {
...result,
data: result.data
? { ...stock(result.data), slug: result.data.slug }
: null,
};
}
async getByTicker(
userId: string,
ticker: string,
): Promise<IdentifiedShare> {
const normalized = ticker.trim().toUpperCase();
return this.cached(userId, `ticker:${normalized}`, async (token) => {
const found = await this.tbank.findShares(token, normalized);
const matches = selectShares(
found.filter(
(item) => item.ticker?.trim().toUpperCase() === normalized,
),
normalized,
);
if (!matches.length) throw new NotFoundException();
if (matches.length > 1)
throw new ConflictException({ code: 'STOCK_TICKER_AMBIGUOUS' });
return matches[0];
});
observe = false,
): Promise<StockResourceDto> {
const result = await this.discovery.byTicker(
userId,
'share',
ticker,
observe,
);
return {
...result,
data: result.data
? { ...stock(result.data), slug: result.data.slug }
: null,
};
}
async share(token: string, uid: string): Promise<IdentifiedShare> {
const share = await this.tbank.getShare(token, uid);
if (!share || share.uid !== uid) throw new NotFoundException();
return { ...share, uid };
}
cached<T extends object>(
userId: string,
key: string,
operation: (token: string) => Promise<T>,
): Promise<T> {
return this.access.withConnection(userId, ({ token, generation }) => {
const cacheKey = JSON.stringify([userId, generation, key]);
const cached = this.cache.get(cacheKey);
if (cached) return cached as Promise<T>;
const pending = operation(token);
this.cache.set(cacheKey, pending);
return pending.catch((error) => {
if (this.cache.get(cacheKey) === pending) this.cache.delete(cacheKey);
throw error;
});
});
}
}
function selectShares(found: TbankShare[], query: string): IdentifiedShare[] {
const seen = new Set<string>();
return found
.filter(
(share): share is IdentifiedShare =>
Boolean(share.uid) && share.instrumentKind === 'INSTRUMENT_TYPE_SHARE',
)
.sort(
(a, b) =>
Number(b.apiTradeAvailableFlag === true) -
Number(a.apiTradeAvailableFlag === true) ||
Number(b.ticker?.toUpperCase() === query.toUpperCase()) -
Number(a.ticker?.toUpperCase() === query.toUpperCase()) ||
Number(b.classCode === 'TQBR') - Number(a.classCode === 'TQBR') ||
a.uid.localeCompare(b.uid),
)
.filter((share) => {
// A missing ISIN must not collapse unrelated catalog instruments.
const key = share.isin?.trim()
? `isin:${share.isin.trim().toUpperCase()}`
: `uid:${share.uid}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
function stock(share: IdentifiedShare): StockDto {
@@ -1,109 +1,165 @@
import { Injectable } from '@nestjs/common';
import { Injectable, NotFoundException } from '@nestjs/common';
import {
decimalFromString,
formatDecimal,
multiply,
} from '../../../../../common/decimal';
import { TbankClient } from '../../../../../integrations/tbank/tbank.api';
import { decimal } from '../../../../../integrations/tbank/decimal';
import { PortfolioService } from '../../../portfolio/portfolio.api';
import {
moscowDay,
optional,
timestamp,
} from '../../application/instrument-market';
import { stockPosition } from './stock-position';
TbankAccessService,
type TbankDividend,
} from '../../../../../integrations/tbank/tbank.api';
import {
PortfolioService,
ForecastService,
} from '../../../portfolio/portfolio.api';
import { CatalogEnrichmentService } from '../../application/catalog-enrichment.service';
import { moscowDay, timestamp } from '../../application/instrument-market';
import { instrumentPosition } from '../../application/instrument-position';
import {
StockDividendDto,
StockDividendsDto,
StockDividendsResourceDto,
StockPositionDto,
StockDividendDto,
} from '../presentation/stock.dto';
import { StockCatalogService } from './stock-catalog.service';
import { decimal } from '../../../../../integrations/tbank/decimal';
const ISO_YEAR_LENGTH = 4;
const INCOME_HISTORY_YEARS = 5;
@Injectable()
export class StockIncomeService {
constructor(
private readonly catalog: StockCatalogService,
private readonly tbank: TbankClient,
private readonly portfolios: PortfolioService,
private readonly sources: CatalogEnrichmentService,
private readonly access: TbankAccessService,
private readonly forecasts: ForecastService,
) {}
async position(userId: string, uid: string): Promise<StockPositionDto> {
return this.catalog.cached(userId, `position:${uid}`, async () =>
stockPosition(await this.portfolios.getAll(userId), uid),
);
async readPosition(userId: string, uid: string, observe = false) {
const saved = await this.portfolios.read(userId, 'all', observe);
return {
data: saved.data ? instrumentPosition(saved.data, uid, 'STOCK') : null,
meta: { ...saved.meta, resourceKey: `stock/position/${uid}` },
};
}
dividends(userId: string, uid: string): Promise<StockDividendsDto> {
return this.catalog.cached(userId, `dividends:${uid}`, async (token) => {
await this.catalog.share(token, uid);
const today = moscowDay(new Date().toISOString());
const from = `${Number(today.slice(0, ISO_YEAR_LENGTH)) - INCOME_HISTORY_YEARS}${today.slice(ISO_YEAR_LENGTH)}`;
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
const unavailable: string[] = [];
const [events, position] = await Promise.all([
this.tbank.getDividends(token, uid, from, to),
optional(() => this.position(userId, uid), 'position', unavailable),
]);
const quantity =
position &&
position.accounts.length &&
position.accounts.every((p) => decimalFromString(p.quantity).value > 0n)
? decimalFromString(position.quantity)
: null;
const dividends: StockDividendDto[] = events
.filter((event) => event.dividendType?.toLowerCase() !== 'cancelled')
.map((event) => {
const recordDate = timestamp(event.recordDate)?.slice(0, 10) ?? null;
const paymentDate =
timestamp(event.paymentDate)?.slice(0, 10) ?? null;
const lastBuyDate =
timestamp(event.lastBuyDate)?.slice(0, 10) ?? null;
const currency = event.dividendNet?.currency?.toUpperCase();
const perShare =
currency && event.dividendNet
? { currency, value: formatDecimal(decimal(event.dividendNet)) }
: null;
// A future payment can have an already-fixed register: keep the event, but do not estimate entitlement from today's holding.
const eventDate = paymentDate ?? recordDate;
const timing: StockDividendDto['timing'] = eventDate
? eventDate >= today
? 'upcoming'
: 'past'
: 'undated';
const estimatedAmount =
quantity &&
perShare &&
recordDate &&
recordDate >= today &&
timing === 'upcoming'
? {
currency: perShare.currency,
value: formatDecimal(
multiply(quantity, decimalFromString(perShare.value)),
),
}
: null;
return {
perShare,
recordDate,
lastBuyDate,
paymentDate,
timing,
estimatedAmount,
};
})
.sort((a, b) => (b.recordDate ?? '').localeCompare(a.recordDate ?? ''));
return {
dividends,
from,
to,
observedAt: new Date().toISOString(),
positionAt: quantity ? (position?.observedAt ?? null) : null,
estimateUnavailable: unavailable.length > 0,
positionIsStale: position?.isStale ?? false,
};
async dividends(
userId: string,
uid: string,
observe = false,
): Promise<StockDividendsResourceDto> {
const connection = await this.access.local(userId);
const today = moscowDay(new Date().toISOString());
const from = `${Number(today.slice(0, ISO_YEAR_LENGTH)) - INCOME_HISTORY_YEARS}${today.slice(ISO_YEAR_LENGTH)}`;
const to = `${Number(today.slice(0, ISO_YEAR_LENGTH)) + 1}${today.slice(ISO_YEAR_LENGTH)}`;
const portfolio = await this.portfolios.read(userId, 'all', observe);
const sources = await this.sources.readMany(
userId,
'share',
[uid],
observe,
['detail', 'dividends'],
{ from, to },
);
if (sources[0].meta.availability === 'complete' && !sources[0].instrument)
throw new NotFoundException();
const events = sources[1].payload?.dividends;
const position = portfolio.data
? instrumentPosition(portfolio.data, uid, 'STOCK')
: null;
const projected = events
? stockDividends(
events,
position,
{ from, to, today },
sources[1].meta.lastSuccessfulAt ?? new Date().toISOString(),
!portfolio.data,
)
: undefined;
const result = await this.forecasts.result({
userId,
revision: connection.revision,
membershipRevision: connection.membershipRevision,
scopeKey: `stock/dividends/${JSON.stringify([uid, from, to])}`,
portfolio: portfolio.meta,
sources,
candidate:
portfolio.data && sources[0].instrument ? projected : undefined,
});
return result.data || !projected
? result
: {
data: stockDividends(
events ?? [],
null,
{ from, to, today },
projected.observedAt,
true,
),
meta: { ...result.meta, availability: 'partial' },
};
}
}
export function stockDividends(
events: TbankDividend[],
position: StockPositionDto | null,
window: { from: string; to: string; today: string },
observedAt: string,
positionUnavailable: boolean,
): StockDividendsDto {
const { from, to, today } = window;
const quantity =
position &&
position.accounts.length &&
position.accounts.every((p) => decimalFromString(p.quantity).value > 0n)
? decimalFromString(position.quantity)
: null;
const dividends: StockDividendDto[] = events
.filter((event) => event.dividendType?.toLowerCase() !== 'cancelled')
.map((event) => {
const recordDate = timestamp(event.recordDate)?.slice(0, 10) ?? null;
const paymentDate = timestamp(event.paymentDate)?.slice(0, 10) ?? null;
const lastBuyDate = timestamp(event.lastBuyDate)?.slice(0, 10) ?? null;
const currency = event.dividendNet?.currency?.toUpperCase();
const perShare =
currency && event.dividendNet
? { currency, value: formatDecimal(decimal(event.dividendNet)) }
: null;
// A future payment can have an already-fixed register: keep the event, but do not estimate entitlement from today's holding.
const eventDate = paymentDate ?? recordDate;
const timing: StockDividendDto['timing'] = eventDate
? eventDate >= today
? 'upcoming'
: 'past'
: 'undated';
const estimatedAmount =
quantity &&
perShare &&
recordDate &&
recordDate >= today &&
timing === 'upcoming'
? {
currency: perShare.currency,
value: formatDecimal(
multiply(quantity, decimalFromString(perShare.value)),
),
}
: null;
return {
perShare,
recordDate,
lastBuyDate,
paymentDate,
timing,
estimatedAmount,
};
})
.sort((a, b) => (b.recordDate ?? '').localeCompare(a.recordDate ?? ''));
return {
dividends,
from,
to,
observedAt: observedAt,
positionAt: quantity ? (position?.observedAt ?? null) : null,
estimateUnavailable: positionUnavailable,
positionIsStale: position?.isStale ?? false,
};
}
@@ -1,4 +1,9 @@
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
import { CandleService } from '../../application/candle.service';
import {
CatalogEnrichmentService,
type CatalogPayload,
} from '../../application/catalog-enrichment.service';
import { Injectable } from '@nestjs/common';
import {
decimalFromString,
divide,
@@ -6,180 +11,101 @@ import {
multiply,
subtract,
} from '../../../../../common/decimal';
import { TbankClient } from '../../../../../integrations/tbank/tbank.api';
import { decimal } from '../../../../../integrations/tbank/decimal';
import { timestamp } from '../../application/instrument-market';
import {
optional,
previousClose,
timestamp,
} from '../../application/instrument-market';
import {
StockCandlesDto,
StockCandlesQueryDto,
StockQuoteDto,
StockQuoteResourceDto,
} from '../presentation/stock.dto';
const dayMs = 86_400_000;
import { StockCatalogService } from './stock-catalog.service';
const PREVIOUS_CLOSE_LOOKBACK_DAYS = 20;
const HALF_YEAR_MONTHS = 6;
const YEAR_MONTHS = 12;
const CANDLE_WINDOW_DAYS = 365;
const CHANGE_PERCENT_DECIMAL_PLACES = 6;
@Injectable()
export class StockMarketService {
constructor(
private readonly catalog: StockCatalogService,
private readonly tbank: TbankClient,
private readonly history: CandleService,
private readonly sources: CatalogEnrichmentService,
) {}
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() - PREVIOUS_CLOSE_LOOKBACK_DAYS * 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),
CHANGE_PERCENT_DECIMAL_PLACES,
),
)
: null,
unavailable,
observedAt: new Date().toISOString(),
};
});
async quote(
userId: string,
uid: string,
observe = false,
): Promise<StockQuoteResourceDto> {
const result = await this.sources.section(
userId,
'share',
uid,
'quote',
observe,
);
return {
data: result.values.instrument
? stockQuote(result.values, result.unavailable, result.observedAt)
: null,
meta: result.meta,
};
}
candles(
userId: string,
uid: string,
period: StockCandlesQueryDto['period'] = 'month',
): Promise<StockCandlesDto> {
return this.catalog.cached(
observe = false,
) {
return this.history.read(
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'
? HALF_YEAR_MONTHS
: YEAR_MONTHS),
);
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 + CANDLE_WINDOW_DAYS * 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(),
};
},
{ uid, instrumentType: 'share', period },
observe,
);
}
}
export function stockQuote(
values: CatalogPayload,
unavailable: string[],
observedAt: string,
): StockQuoteDto {
const { price: last, candle: previous, tradingStatus = null } = values;
const share = values.instrument;
const priceAt = timestamp(last?.time);
const currency = share?.currency?.toUpperCase();
const price =
last?.price && currency
? { currency, value: formatDecimal(decimal(last.price)) }
: 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),
CHANGE_PERCENT_DECIMAL_PLACES,
),
)
: null,
unavailable,
observedAt,
};
}
@@ -1,375 +1,70 @@
import {
ConflictException,
NotFoundException,
ServiceUnavailableException,
UnauthorizedException,
} from '@nestjs/common';
import { TbankAccessService } from '../../../../../integrations/tbank/tbank-access.service';
import { TbankClient } from '../../../../../integrations/tbank/tbank.client';
import { PortfolioService } from '../../../portfolio/application/portfolio.service';
import { GetStockCompanyUseCase } from './get-stock-company.use-case';
import { StockIncomeService } from './stock-income.service';
import { StockMarketService } from './stock-market.service';
import { StockCatalogService } from './stock-catalog.service';
import { metrics } from './get-stock-company.use-case';
import { stockDividends } from './stock-income.service';
import { stockQuote } from './stock-market.service';
import { previousClose } from '../../application/instrument-market';
jest.mock('../../../../../integrations/tbank/tbank-access.service', () => ({
TbankAccessService: class TbankAccessService {},
jest.mock('../../../../../prisma/prisma.service', () => ({
PrismaService: class {},
}));
const time = (date: string) => ({ seconds: String(Date.parse(date) / 1000) });
const share = {
uid: 'uid',
assetUid: 'asset',
currency: 'rub',
sector: 'financial',
first_1dayCandleDate: time('2025-11-20'),
};
function setup() {
let generation = 'a';
const tbank = {
findShares: jest.fn().mockResolvedValue([]),
getLastPrices: jest.fn().mockResolvedValue([]),
getShare: jest.fn().mockResolvedValue(share),
getCandles: jest.fn().mockResolvedValue([]),
getAssetDescription: jest.fn().mockResolvedValue('Company'),
getFundamentals: jest.fn().mockResolvedValue({
assetUid: 'asset',
currency: 'rub',
peRatioTtm: 6,
netIncomeTtm: 10,
}),
getDividends: jest.fn().mockResolvedValue([]),
};
const access = {
withConnection: jest.fn(
(user: string, handler: (context: unknown) => unknown) =>
handler({ token: user, generation }),
),
};
const portfolios = {
getAll: jest.fn().mockResolvedValue({
positions: [],
lastSuccessfulAt: '2026-09-10T00:00:00Z',
isStale: false,
}),
};
const service = new StockCatalogService(
access as unknown as TbankAccessService,
tbank as unknown as TbankClient,
);
const market = new StockMarketService(
service,
tbank as unknown as TbankClient,
);
const income = new StockIncomeService(
service,
tbank as unknown as TbankClient,
portfolios as unknown as PortfolioService,
);
const companyInfo = new GetStockCompanyUseCase(
service,
tbank as unknown as TbankClient,
);
return {
market,
income,
companyInfo,
service,
tbank,
portfolios,
changeGeneration: () => {
generation = 'b';
},
};
}
describe('stock market use case', () => {
beforeEach(() =>
jest.useFakeTimers().setSystemTime(new Date('2026-09-10T10:00:00Z')),
);
afterEach(() => jest.useRealTimers());
it('returns unique ISINs, keeps preferred shares separate and matches prices by selected UID', async () => {
const { service, tbank } = setup();
const listings = [
{
uid: 'special',
ticker: 'SBER',
classCode: 'SPEQ',
apiTradeAvailableFlag: false,
},
{
uid: 'preferred',
ticker: 'SBERP',
classCode: 'TQBR',
apiTradeAvailableFlag: true,
},
{
uid: 'common',
ticker: 'SBER',
classCode: 'TQBR',
apiTradeAvailableFlag: true,
},
].map((item) => ({
...item,
name: 'Сбербанк',
isin: item.uid === 'preferred' ? 'ISINP' : 'ISIN',
instrumentKind: 'INSTRUMENT_TYPE_SHARE',
}));
tbank.findShares.mockResolvedValue([
...listings,
{ uid: 'bond', instrumentKind: 'INSTRUMENT_TYPE_BOND' },
{ instrumentKind: 'INSTRUMENT_TYPE_SHARE' },
{ uid: '', instrumentKind: 'INSTRUMENT_TYPE_SHARE' },
]);
tbank.getShare.mockImplementation((_token: string, uid: string) =>
Promise.resolve({
...listings.find((item) => item.uid === uid),
currency: 'rub',
brand: { logoName: 'sber.png' },
shareType:
uid === 'preferred' ? 'SHARE_TYPE_PREFERRED' : 'SHARE_TYPE_COMMON',
}),
const time = (value: string) => ({ seconds: String(Date.parse(value) / 1000) });
describe('stock financial projections', () => {
it('keeps raw public payouts when holdings are unavailable and omits cancelled events', () => {
const result = stockDividends(
[
{
dividendNet: { currency: 'rub', units: '32', nano: 880000000 },
recordDate: time('2026-10-13'),
paymentDate: time('2026-10-27'),
},
{ dividendType: 'Cancelled', recordDate: time('2026-10-14') },
],
null,
{ from: '2021-09-10', to: '2027-09-10', today: '2026-09-10' },
'source-time',
true,
);
tbank.getLastPrices.mockResolvedValue([
expect(result.dividends).toEqual([
{
instrumentUid: 'preferred',
price: { units: '305' },
time: time('2026-09-09'),
},
{
instrumentUid: 'common',
price: { units: '306', nano: 120000000 },
time: time('2026-09-10'),
perShare: { currency: 'RUB', value: '32.88' },
recordDate: '2026-10-13',
paymentDate: '2026-10-27',
lastBuyDate: null,
timing: 'upcoming',
estimatedAmount: null,
},
]);
const result = await service.search('user', 'SBER');
expect(result.map((item) => item.instrumentUid)).toEqual([
'common',
'preferred',
]);
expect(result[0]).toMatchObject({
classCode: 'TQBR',
isin: 'ISIN',
logoName: 'sber.png',
price: { currency: 'RUB', value: '306.12' },
priceAt: '2026-09-10T00:00:00.000Z',
});
expect(result[1]).toMatchObject({
shareType: 'SHARE_TYPE_PREFERRED',
price: { value: '305' },
});
expect(tbank.getLastPrices).toHaveBeenCalledTimes(1);
expect(result.estimateUnavailable).toBe(true);
expect(result.observedAt).toBe('source-time');
});
it('prefers TQBR among equally available listings, deduplicates before the limit and keeps missing ISINs separate', async () => {
const { service, tbank } = setup();
const hit = {
instrumentKind: 'INSTRUMENT_TYPE_SHARE',
ticker: 'SBER',
apiTradeAvailableFlag: true,
};
tbank.findShares.mockResolvedValue([
...Array.from({ length: 35 }, (_, i) => ({
...hit,
uid: `alternate-${i}`,
isin: ' isin ',
classCode: 'SPEQ',
})),
{ ...hit, uid: 'common', isin: 'ISIN', classCode: 'TQBR' },
{
...hit,
uid: 'preferred',
ticker: 'SBERP',
isin: 'ISINP',
classCode: 'TQBR',
},
{ ...hit, uid: 'unknown-a', isin: '' },
{ ...hit, uid: 'unknown-b' },
]);
tbank.getShare.mockResolvedValue(null);
const result = await service.search('user', 'SBER');
expect(result.map((item) => item.instrumentUid)).toEqual([
'common',
'unknown-a',
'unknown-b',
'preferred',
]);
expect(tbank.getShare).toHaveBeenCalledTimes(4);
});
it('retains catalog identity when enrichment is unavailable, but propagates auth errors', async () => {
const { service, tbank } = setup();
tbank.findShares.mockResolvedValue([
{
uid: 'uid',
ticker: 'SBER',
classCode: 'TQBR',
instrumentKind: 'INSTRUMENT_TYPE_SHARE',
},
]);
tbank.getShare.mockRejectedValue(new ServiceUnavailableException());
tbank.getLastPrices.mockRejectedValue(new ServiceUnavailableException());
expect(await service.search('user', 'SBER')).toEqual([
expect.objectContaining({
instrumentUid: 'uid',
classCode: 'TQBR',
price: null,
logoName: null,
}),
]);
tbank.getShare.mockResolvedValue(null);
expect(await service.search('user', 'sber')).toEqual([
expect.objectContaining({ instrumentUid: 'uid' }),
]);
tbank.getShare.mockRejectedValue(new UnauthorizedException());
await expect(service.search('another-user', 'SBER')).rejects.toBeInstanceOf(
UnauthorizedException,
);
});
it('skips enrichment for an empty catalog result', async () => {
const { service, tbank } = setup();
expect(await service.search('user', 'none')).toEqual([]);
expect(tbank.getShare).not.toHaveBeenCalled();
expect(tbank.getLastPrices).not.toHaveBeenCalled();
});
it('resolves an exact ticker, preserves other listing UIDs and does not confuse SBER with SBERP', async () => {
const { service, tbank } = setup();
const listings = [
{
uid: 'common',
ticker: 'SBER',
isin: 'COMMON',
classCode: 'TQBR',
apiTradeAvailableFlag: true,
},
{
uid: 'special',
ticker: 'SBER',
isin: 'COMMON',
classCode: 'SPEQ',
apiTradeAvailableFlag: false,
},
{
uid: 'preferred',
ticker: 'SBERP',
isin: 'PREFERRED',
classCode: 'TQBR',
apiTradeAvailableFlag: true,
},
].map((item) => ({ ...item, instrumentKind: 'INSTRUMENT_TYPE_SHARE' }));
tbank.findShares.mockResolvedValue(listings);
tbank.getShare.mockImplementation((_token: string, uid: string) =>
Promise.resolve(listings.find((item) => item.uid === uid)),
);
expect(await service.getByTicker('user', 'sberp')).toMatchObject({
instrumentUid: 'preferred',
slug: 'SBERP',
});
expect(await service.get('user', 'common')).toMatchObject({
instrumentUid: 'common',
slug: 'SBER',
});
expect(await service.get('user', 'special')).toMatchObject({
instrumentUid: 'special',
slug: 'special',
});
await expect(service.getByTicker('user', 'SB')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('refuses ambiguous tickers while keeping exact UID pages accessible', async () => {
const { service, tbank } = setup();
const listings = ['one', 'two'].map((uid) => ({
uid,
ticker: 'SAME',
isin: uid,
instrumentKind: 'INSTRUMENT_TYPE_SHARE',
}));
tbank.findShares.mockResolvedValue(listings);
tbank.getShare.mockResolvedValue(listings[0]);
await expect(service.getByTicker('user', 'SAME')).rejects.toBeInstanceOf(
ConflictException,
);
expect(await service.get('user', 'one')).toMatchObject({
instrumentUid: 'one',
slug: 'one',
});
});
it('keeps exact pages if alias lookup fails and partitions ticker resolution by connection', async () => {
const { service, tbank, changeGeneration } = setup();
tbank.getShare.mockResolvedValue({ ...share, ticker: 'F' });
tbank.findShares.mockRejectedValueOnce(new ServiceUnavailableException());
expect(await service.get('user', 'uid')).toMatchObject({ slug: 'uid' });
tbank.findShares.mockResolvedValue([
{ ...share, ticker: 'F', instrumentKind: 'INSTRUMENT_TYPE_SHARE' },
]);
expect(await service.getByTicker('user', 'F')).toMatchObject({
instrumentUid: 'uid',
slug: 'F',
});
changeGeneration();
expect(await service.getByTicker('user', 'F')).toMatchObject({ slug: 'F' });
expect(tbank.findShares).toHaveBeenCalledTimes(3);
});
it('uses a complete previous trading day, never today’s main close', () => {
it('uses the last complete previous trading day', () => {
const candles = [
{ time: time('2026-09-09'), close: { units: '10' }, isComplete: true },
{ time: time('2026-09-10'), close: { units: '11' }, isComplete: true },
{ time: time('2026-09-08'), close: { units: '9' }, isComplete: false },
{ time: time('2026-09-10'), close: { units: '11' }, isComplete: false },
];
expect(previousClose(candles, '2026-09-10T18:00:00Z')).toEqual(candles[0]);
expect(previousClose(candles, '2026-09-09T22:00:00Z')).toEqual(candles[0]);
});
it('starts all-history at listing, keeps incomplete candles and deduplicates boundaries', async () => {
const { tbank, market } = setup();
tbank.getCandles.mockResolvedValue([
{ time: time('2026-09-09'), close: { units: '10' }, isComplete: false },
]);
const result = await market.candles('user', 'uid', 'all');
expect(tbank.getCandles).toHaveBeenCalledWith(
'user',
'uid',
new Date('2025-11-20'),
expect.any(Date),
);
expect(result.candles).toHaveLength(1);
expect(result.candles[0].isComplete).toBe(false);
});
it('does not manufacture zero fundamentals and isolates optional failures', async () => {
const { tbank, companyInfo } = setup();
tbank.getAssetDescription.mockRejectedValue(
new ServiceUnavailableException(),
);
const result = await companyInfo.execute('user', 'uid');
expect(result.description).toBeNull();
expect(result.unavailable).toEqual(['description']);
expect(result.metrics.map((item) => item.key)).toEqual([
'peRatioTtm',
'netIncomeTtm',
]);
});
it('isolates cache by user and connection generation', async () => {
const { service, tbank, changeGeneration } = setup();
await service.get('a', 'uid');
await service.get('a', 'uid');
expect(tbank.getShare).toHaveBeenCalledTimes(1);
await service.get('b', 'uid');
changeGeneration();
await service.get('a', 'uid');
expect(tbank.getShare).toHaveBeenCalledTimes(3);
});
it('keeps public dividends when there is no holding or position retrieval fails', async () => {
const { tbank, portfolios, income } = setup();
portfolios.getAll.mockRejectedValue(new ServiceUnavailableException());
tbank.getDividends.mockResolvedValue([
{
dividendNet: { currency: 'rub', units: '32', nano: 880000000 },
recordDate: time('2026-10-13'),
paymentDate: time('2026-10-27'),
},
]);
const result = await income.dividends('user', 'uid');
expect(result.estimateUnavailable).toBe(true);
expect(result.dividends[0]).toMatchObject({
perShare: { currency: 'RUB', value: '32.88' },
estimatedAmount: null,
timing: 'upcoming',
it('retains stock price precision and percent change without inventing unavailable fundamentals', () => {
expect(
stockQuote(
{
instrument: { currency: 'rub' },
price: { price: { units: '11', nano: 1 } },
candle: { close: { units: '10' } },
},
[],
'time',
),
).toMatchObject({
price: { currency: 'RUB', value: '11.000000001' },
change: { currency: 'RUB', value: '1.000000001' },
changePercent: '10',
});
expect(metrics(null, 'financial')).toEqual([]);
expect(
metrics(
{ peRatioTtm: 6, netIncomeTtm: 10, revenueTtm: 100, currency: 'rub' },
'financial',
).map((item) => item.key),
).toEqual(['peRatioTtm', 'netIncomeTtm']);
expect(metrics({ netIncomeTtm: 10 })).toEqual([]);
});
});
@@ -1,3 +1,4 @@
import { InvestmentReadQueryDto } from '../../../investment-resource.dto';
import {
Controller,
Get,
@@ -15,15 +16,15 @@ import { GetStockCompanyUseCase } from '../application/get-stock-company.use-cas
import { StockIncomeService } from '../application/stock-income.service';
import { StockMarketService } from '../application/stock-market.service';
import {
StockCandlesDto,
StockCandlesResourceDto,
StockCandlesQueryDto,
StockCompanyDto,
StockDividendsDto,
StockDto,
StockPositionDto,
StockQuoteDto,
StockCompanyResourceDto,
StockDividendsResourceDto,
StockResourceDto,
StockPositionResourceDto,
StockQuoteResourceDto,
StockSearchQueryDto,
StockSearchResultDto,
StockSearchResourceDto,
StockTickerParamsDto,
} from './stock.dto';
import { StockCatalogService } from '../application/stock-catalog.service';
@@ -41,68 +42,99 @@ export class StockController {
private readonly companyInfo: GetStockCompanyUseCase,
) {}
@Get()
@ApiOkResponse({ type: [StockSearchResultDto] })
@ApiOkResponse({ type: StockSearchResourceDto })
search(
@Req() request: Request & { user: AccessPayload },
@Query() query: StockSearchQueryDto,
) {
return this.stocks.search(request.user.sub, query.query);
return this.stocks.search(
request.user.sub,
query.query,
query.sync === 'observe',
);
}
@Get('by-ticker/:ticker')
@ApiOkResponse({ type: StockDto })
@ApiOkResponse({ type: StockResourceDto })
getByTicker(
@Req() request: Request & { user: AccessPayload },
@Param() params: StockTickerParamsDto,
@Query() query: InvestmentReadQueryDto,
) {
return this.stocks.getByTicker(request.user.sub, params.ticker);
return this.stocks.getByTicker(
request.user.sub,
params.ticker,
query.sync === 'observe',
);
}
@Get(':uid')
@ApiOkResponse({ type: StockDto })
@ApiOkResponse({ type: StockResourceDto })
get(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.stocks.get(request.user.sub, uid);
return this.stocks.get(request.user.sub, uid, query.sync === 'observe');
}
@Get(':uid/quote')
@ApiOkResponse({ type: StockQuoteDto })
@ApiOkResponse({ type: StockQuoteResourceDto })
quote(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.market.quote(request.user.sub, uid);
return this.market.quote(request.user.sub, uid, query.sync === 'observe');
}
@Get(':uid/candles')
@ApiOkResponse({ type: StockCandlesDto })
@ApiOkResponse({ type: StockCandlesResourceDto })
candles(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: StockCandlesQueryDto,
) {
return this.market.candles(request.user.sub, uid, query.period);
return this.market.candles(
request.user.sub,
uid,
query.period,
query.sync === 'observe',
);
}
@Get(':uid/position')
@ApiOkResponse({ type: StockPositionDto })
@ApiOkResponse({ type: StockPositionResourceDto })
position(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.income.position(request.user.sub, uid);
return this.income.readPosition(
request.user.sub,
uid,
query.sync === 'observe',
);
}
@Get(':uid/company')
@ApiOkResponse({ type: StockCompanyDto })
@ApiOkResponse({ type: StockCompanyResourceDto })
company(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.companyInfo.execute(request.user.sub, uid);
return this.companyInfo.execute(
request.user.sub,
uid,
query.sync === 'observe',
);
}
@Get(':uid/dividends')
@ApiOkResponse({ type: StockDividendsDto })
@ApiOkResponse({ type: StockDividendsResourceDto })
dividends(
@Req() request: Request & { user: AccessPayload },
@Param('uid', new ParseUUIDPipe()) uid: string,
@Query() query: InvestmentReadQueryDto,
) {
return this.income.dividends(request.user.sub, uid);
return this.income.dividends(
request.user.sub,
uid,
query.sync === 'observe',
);
}
}
@@ -1,3 +1,7 @@
import {
InvestmentReadQueryDto,
InvestmentResourceMetaDto,
} from '../../../investment-resource.dto';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import {
@@ -13,7 +17,7 @@ import { PortfolioPositionDto } from '../../../portfolio/portfolio.api';
const MAX_INSTRUMENT_QUERY_LENGTH = 80;
export class StockSearchQueryDto {
export class StockSearchQueryDto extends InvestmentReadQueryDto {
@ApiProperty({ minLength: 2, maxLength: MAX_INSTRUMENT_QUERY_LENGTH })
@Transform(({ value }: { value: unknown }) =>
typeof value === 'string' ? value.trim() : value,
@@ -35,7 +39,7 @@ export class StockTickerParamsDto {
@Matches(/^[A-Za-z0-9][A-Za-z0-9._@+-]*$/)
declare ticker: string;
}
export class StockCandlesQueryDto {
export class StockCandlesQueryDto extends InvestmentReadQueryDto {
@ApiPropertyOptional({
enum: ['month', 'halfYear', 'year', 'all'],
default: 'month',
@@ -168,3 +172,52 @@ export class StockDividendsDto {
@ApiProperty() declare estimateUnavailable: boolean;
@ApiProperty() declare positionIsStale: boolean;
}
export class StockPositionResourceDto {
@ApiProperty({ type: StockPositionDto, nullable: true })
declare data: StockPositionDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class StockSearchResourceDto {
@ApiProperty({ type: StockSearchResultDto, isArray: true, nullable: true })
declare data: StockSearchResultDto[] | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class StockResourceDto {
@ApiProperty({ type: StockDto, nullable: true })
declare data: StockDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class StockQuoteResourceDto {
@ApiProperty({ type: StockQuoteDto, nullable: true })
declare data: StockQuoteDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class StockCompanyResourceDto {
@ApiProperty({ type: StockCompanyDto, nullable: true })
declare data: StockCompanyDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class StockCandlesResourceDto {
@ApiProperty({ type: StockCandlesDto, nullable: true })
declare data: StockCandlesDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}
export class StockDividendsResourceDto {
@ApiProperty({ type: StockDividendsDto, nullable: true })
declare data: StockDividendsDto | null;
@ApiProperty({ type: InvestmentResourceMetaDto })
declare meta: InvestmentResourceMetaDto;
}