docs: sync backend docs with refactored MOEX, health envelope, and operations/sync endpoint

This commit is contained in:
Sergey Krylov 2026-06-25 22:00:44 +03:00
parent b87ed761ed
commit 0e7ecbb1ef
3 changed files with 48 additions and 30 deletions

View File

@ -92,9 +92,17 @@
**Response:**
```json
{
"status": "ok",
"timestamp": "2026-06-13T12:00:00.000Z",
"uptime": 1234.56
"data": {
"status": "ok",
"timestamp": "2026-06-25T12:00:00.000Z",
"uptime": 1234.56,
"checks": [
{ "name": "database", "status": "ok" },
{ "name": "moex", "status": "ok" },
{ "name": "tbank", "status": "ok" }
]
},
"meta": { "fromCache": false, "cachedAt": null }
}
```
@ -403,5 +411,5 @@ codegen types.
| `/api/v1/broker/accounts/:accountId/portfolio` | GET | Портфель счёта: позиции, cash, метаданные |
| `/api/v1/broker/accounts/:accountId/events` | GET | События и будущие выплаты (дивиденды, купоны) с фильтром по датам |
| `/api/v1/broker/accounts/:accountId/operations` | GET | История операций (cursor pagination) |
| `/api/v1/broker/accounts/:accountId/operations/refresh` | POST | Принудительная синхронизация операций из T-Bank |
| `/api/v1/broker/accounts/:accountId/operations/sync` | POST | Принудительная синхронизация операций из T-Bank |
| `/api/v1/broker/accounts/:accountId/positions` | GET | Позиции счёта (с пагинацией) |

View File

@ -25,20 +25,20 @@ flowchart TB
PrismaService["PrismaService"]
CacheService["CacheService"]
MoexClientService["MoexClientService"]
MoexHttpClient["MoexHttpClient"]
TBankClientService["TBankClientService"]
PrismaModule --> PrismaService
CacheModule --> CacheService
MoexClientModule --> MoexClientService
MoexClientModule --> MoexHttpClient
AuthModule --> PrismaService
PortfolioModule --> PrismaService
PortfolioModule --> CacheService
PortfolioModule --> MoexClientService
PortfolioModule --> MoexHttpClient
MarketModules --> CacheService
MarketModules --> MoexClientService
MarketModules --> MoexHttpClient
TBankModule --> CacheService
TBankModule --> PrismaService
@ -79,17 +79,17 @@ flowchart TB
### MoexClientModule
Глобальный HTTP-клиент для MOEX ISS.
Глобальный модуль для MOEX ISS, разделённый на `MoexHttpClient` и domain-specific клиенты.
- Rate limiter: p-queue (10 req/s по умолчанию, настраивается через `MOEX_RATE_LIMIT`)
- Circuit breaker: открывается после 5 ошибок, сбрасывается через 30s
- Все ответы нормализуются из табличного формата MOEX в доменные типы
- `MoexHttpClient` — rate limiter (p-queue, 10 req/s), circuit breaker (5 errors → 30s open), ISS JSON parsing.
- Domain clients — `MoexSecuritiesClient`, `MoexMarketDataClient`, `MoexCandlesClient`, `MoexHistoryClient`, `MoexDividendsClient`.
- Все ответы нормализуются из табличного формата MOEX в доменные типы.
### HealthModule
Проверка состояния сервиса.
- `GET /api/v1/health``{ status: 'ok', timestamp, uptime }`
- `GET /api/v1/health``{ data: { status, timestamp, uptime, checks }, meta }`
### AuthModule

View File

@ -2,9 +2,21 @@
## Обзор
`MoexClientService` (`apps/backend/src/modules/moex-client/moex-client.service.ts`) — HTTP-клиент для MOEX ISS API.
MOEX integration is split into a shared HTTP infrastructure client and focused domain clients under
`apps/backend/src/modules/moex-client/`:
## Rate limiting
- `MoexHttpClient` — request queue, rate limiting, circuit breaker, ISS JSON parsing.
- `MoexSecuritiesClient` — security search and descriptions.
- `MoexMarketDataClient` — share/bond market data and batch position enrichment.
- `MoexCandlesClient` — candle history.
- `MoexHistoryClient` — share and bond history.
- `MoexDividendsClient` — dividend calendar.
## `MoexHttpClient`
Базовый HTTP-клиент, используемый всеми domain-клиентами. Реализован в `moex-http-client.service.ts`.
### Rate limiting
Использует `p-queue`:
@ -17,7 +29,7 @@ this.queue = new PQueue({
Все запросы к MOEX проходят через очередь — не более `MOEX_RATE_LIMIT` запросов в секунду.
## Circuit breaker
### Circuit breaker
Состояние: закрыт → открыт → полуоткрыт (через таймаут).
@ -30,7 +42,7 @@ private circuitErrorCount = 0;
- В открытом состоянии все запросы мгновенно падают с ошибкой `"Circuit breaker is open"`
- Через `MOEX_CIRCUIT_BREAKER_RESET_SECONDS` (30) автоматически сбрасывается
## Метод request
### Метод request
```typescript
private async request<T>(path: string, params?: Record<string, string>): Promise<T>
@ -40,7 +52,7 @@ private async request<T>(path: string, params?: Record<string, string>): Promise
- Устанавливает `iss.meta=off` (отключает метаданные)
- Таймаут: 10s
## Разбор response
### Разбор response
MOEX возвращает данные в табличном формате:
@ -55,19 +67,17 @@ MOEX возвращает данные в табличном формате:
Метод `extractTable` преобразует это в массив объектов по колонкам.
## Доступные методы MOEX
## Domain clients
| Метод | MOEX path | Описание |
|---|---|---|
| `searchSecurities` | `/securities?q=` | Поиск инструментов |
| `getSecurityDescription` | `/securities/{secid}` | Спецификация |
| `getShareMarketData` | `/engines/stock/markets/shares/securities/{secid}` | Рыночные данные акции (board: TQBR) |
| `getBondData` | `/engines/stock/markets/bonds/securities/{secid}` | Данные облигации (board: TQCB) |
| `getBondMarketData` | `/engines/stock/markets/bonds/securities/{secid}` | Рыночные данные облигации |
| `getDividends` | `/securities/{secid}/dividends` | Дивиденды |
| `getCandles` | `/engines/{engine}/markets/{market}/securities/{secid}/candles` | Свечи |
| `getHistory` | `/engines/stock/markets/shares/securities/{secid}` | История акций |
| `getBondHistory` | `/engines/stock/markets/bonds/securities/{secid}` | История облигаций |
Каждый domain-клиент использует `MoexHttpClient` для HTTP и предоставляет свои методы:
| Client | Методы |
|---|---|
| `MoexSecuritiesClient` | `searchSecurities`, `getSecurityDescription` |
| `MoexMarketDataClient` | `getShareMarketData`, `getBondMarketData`, `batchPositions` |
| `MoexCandlesClient` | `getCandles` |
| `MoexHistoryClient` | `getShareHistory`, `getBondHistory` |
| `MoexDividendsClient` | `getDividends` |
## MOEX ISS types