678 lines
24 KiB
TypeScript
678 lines
24 KiB
TypeScript
/**
|
||
* T-Invest API (sandbox или реальный контур): счета, история исполненных
|
||
* операций, последние цены, справочник акций, свечи.
|
||
*
|
||
* Основа — проверенный клиент старого проекта (legacy/tinkoff.ts); известные
|
||
* особенности SDK учтены:
|
||
* - Quotation {units, nano}: units — строка или число;
|
||
* - protobuf Timestamp {seconds, nanos}: seconds — строка / число /
|
||
* Long-объект / RFC3339 (см. protoTimestampToMs);
|
||
* - quantity/volume — строки, числа или Long;
|
||
* - gRPC-ошибки приходят объектом {code, details/message};
|
||
* - после каждого вызова — пауза (рейт-лимиты API).
|
||
*/
|
||
import { randomUUID } from 'node:crypto';
|
||
import { OpenAPIClient } from '@tinkoff/invest-js';
|
||
import { config, hasTinkoffToken } from './config.js';
|
||
import type { Candle, CandleInterval, ShareMeta } from './types.js';
|
||
|
||
/** Пауза между последовательными запросами к API, мс (рейт-лимиты). */
|
||
const DEFAULT_DELAY_MS = Number(process.env.TINKOFF_DELAY_MS ?? 350);
|
||
|
||
/** Таймаут одного gRPC-вызова, мс (защита от зависших callback'ов SDK). */
|
||
const REQUEST_TIMEOUT_MS = Number(process.env.TINKOFF_REQUEST_TIMEOUT_MS ?? 30000);
|
||
|
||
// ---------- Конвертация protobuf -> JS (из legacy/tinkoff.ts) ----------
|
||
|
||
function describeError(err: unknown): string {
|
||
const e = err as { code?: number; details?: string; message?: string };
|
||
return `T-Invest API: ${e?.code ?? ''} ${e?.details ?? e?.message ?? String(err)}`;
|
||
}
|
||
|
||
function sleep(ms: number): Promise<void> {
|
||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||
}
|
||
|
||
function toTimestamp(ms: number): { seconds: number; nanos: number } {
|
||
return { seconds: Math.floor(ms / 1000), nanos: 0 };
|
||
}
|
||
|
||
/**
|
||
* protobuf Timestamp -> epoch ms. seconds может быть строкой, числом,
|
||
* Long-объектом (toNumber), весь Timestamp — RFC3339-строкой.
|
||
*/
|
||
export function protoTimestampToMs(ts: unknown): number {
|
||
if (ts !== null && typeof ts === 'object') {
|
||
const t = ts as { seconds?: unknown; nanos?: unknown; toDate?: unknown };
|
||
// Некоторые сборки SDK дают Timestamp.toDate()
|
||
if (typeof t.toDate === 'function') {
|
||
return (t.toDate as () => Date).call(t).getTime();
|
||
}
|
||
const nanosMs = Math.round(Number(t.nanos ?? 0) / 1e6);
|
||
const s = t.seconds;
|
||
// Long-объект
|
||
if (
|
||
s !== null &&
|
||
typeof s === 'object' &&
|
||
typeof (s as { toNumber?: unknown }).toNumber === 'function'
|
||
) {
|
||
return (s as { toNumber(): number }).toNumber() * 1000 + nanosMs;
|
||
}
|
||
const n = Number(s);
|
||
// Строка или число
|
||
if (typeof s === 'string' && s.trim() !== '' && Number.isFinite(n)) {
|
||
return n * 1000 + nanosMs;
|
||
}
|
||
if (typeof s === 'number' && Number.isFinite(s)) {
|
||
return s * 1000 + nanosMs;
|
||
}
|
||
// Последний шанс: весь объект — RFC3339 (нестандартно, но подстрахуемся)
|
||
return new Date(String(ts)).getTime();
|
||
}
|
||
if (typeof ts === 'number' && Number.isFinite(ts)) return ts * 1000;
|
||
if (typeof ts === 'string') {
|
||
if (ts.trim() === '') return NaN;
|
||
const n = Number(ts);
|
||
if (Number.isFinite(n)) return n * 1000;
|
||
return new Date(ts).getTime();
|
||
}
|
||
return NaN;
|
||
}
|
||
|
||
/** Quotation {units: "258", nano: 490000000} -> 258.49. Знак — по строке units. */
|
||
export function quotationToNumber(q: { units: string | number; nano: number }): number {
|
||
const unitsStr = String(q.units);
|
||
const sign = unitsStr.startsWith('-') ? -1 : 1;
|
||
const unitsAbs = Math.abs(Number(unitsStr));
|
||
const frac = Math.abs(Number(q.nano)) / 1e9;
|
||
return Number((sign * (unitsAbs + frac)).toFixed(6));
|
||
}
|
||
|
||
/** Число из SDK: number | Long-объект | строка | bigint. NaN, если не число. */
|
||
function toNumber(v: unknown): number {
|
||
if (typeof v === 'number') return v;
|
||
if (typeof v === 'bigint') return Number(v);
|
||
if (
|
||
v !== null &&
|
||
typeof v === 'object' &&
|
||
typeof (v as { toNumber?: unknown }).toNumber === 'function'
|
||
) {
|
||
return (v as { toNumber(): number }).toNumber();
|
||
}
|
||
if (typeof v === 'string') {
|
||
const n = Number(v);
|
||
if (Number.isFinite(n)) return n;
|
||
}
|
||
return NaN;
|
||
}
|
||
|
||
// ---------- Клиент ----------
|
||
|
||
let cachedClient: OpenAPIClient | null = null;
|
||
|
||
function getClient(): OpenAPIClient {
|
||
if (!hasTinkoffToken()) {
|
||
throw new Error('TINKOFF_TOKEN не задан в .env (см. .env.example)');
|
||
}
|
||
if (!cachedClient) {
|
||
// sandbox-контур определяется самим токеном; url — только для отладки
|
||
const urlOverride = process.env.TINKOFF_URL;
|
||
cachedClient = new OpenAPIClient({
|
||
token: config.tinkoffToken,
|
||
...(urlOverride ? { url: urlOverride } : {}),
|
||
});
|
||
}
|
||
return cachedClient;
|
||
}
|
||
|
||
/**
|
||
* Тот же клиент для стримов (priceStream.ts): авторизация уже вшита в credentials
|
||
* канала (MetadataGenerator), поэтому stream-вызовы не передают токен отдельно.
|
||
*/
|
||
export function getGrpcClient(): OpenAPIClient {
|
||
return getClient();
|
||
}
|
||
|
||
/** Обёртка над callback-API SDK: Promise + таймаут + троттлинг (паттерн legacy). */
|
||
function request(fn: (cb: (err: unknown, res?: unknown) => void) => void): Promise<unknown> {
|
||
return new Promise<unknown>((resolve, reject) => {
|
||
const timeout = setTimeout(
|
||
() => reject(new Error(`T-Invest API timeout after ${REQUEST_TIMEOUT_MS}ms`)),
|
||
REQUEST_TIMEOUT_MS,
|
||
);
|
||
fn((err, res) => {
|
||
clearTimeout(timeout);
|
||
if (err) {
|
||
reject(new Error(describeError(err)));
|
||
return;
|
||
}
|
||
resolve(res);
|
||
});
|
||
}).finally(() => sleep(DEFAULT_DELAY_MS));
|
||
}
|
||
|
||
// ---------- Счета ----------
|
||
|
||
export interface AccountInfo {
|
||
id: string;
|
||
name: string;
|
||
type: string;
|
||
status: string;
|
||
/** Дата открытия (epoch ms) — нижняя граница истории операций. */
|
||
openedMs: number | null;
|
||
}
|
||
|
||
interface RawAccount {
|
||
id?: unknown;
|
||
name?: string;
|
||
type?: unknown;
|
||
status?: unknown;
|
||
openedDate?: unknown;
|
||
}
|
||
|
||
/** Счета: sandbox или реальный контур — по флагу TINKOFF_SANDBOX из .env. */
|
||
export async function getAccounts(): Promise<AccountInfo[]> {
|
||
const client = getClient();
|
||
const res = (await request((cb) =>
|
||
config.tinkoffSandbox
|
||
? client.sandbox.getSandboxAccounts({}, cb)
|
||
: client.usersService.getAccounts({}, cb),
|
||
)) as { accounts?: RawAccount[] };
|
||
return (res.accounts ?? [])
|
||
.map((a) => ({
|
||
id: String(a.id ?? ''),
|
||
name: a.name ?? '',
|
||
type: String(a.type ?? ''),
|
||
status: String(a.status ?? ''),
|
||
openedMs: a.openedDate ? protoTimestampToMs(a.openedDate) : null,
|
||
}))
|
||
.filter((a) => a.id !== '');
|
||
}
|
||
|
||
// ---------- История операций ----------
|
||
|
||
export interface ExecutedTrade {
|
||
figi: string;
|
||
type: 'buy' | 'sell';
|
||
/** Число инструментов в сделке, шт. */
|
||
qty: number;
|
||
/** Цена сделки за штуку. */
|
||
price: number;
|
||
dateMs: number;
|
||
currency: string | null;
|
||
}
|
||
|
||
interface RawOperation {
|
||
/** Человекочитаемое описание на русском («Сделка покупки») — НЕ фильтруем по нему. */
|
||
type?: unknown;
|
||
/** Enum операции: OPERATION_TYPE_BUY / OPERATION_TYPE_SELL / OPERATION_TYPE_BROKER_FEE / ... */
|
||
operationType?: unknown;
|
||
figi?: unknown;
|
||
quantity?: unknown;
|
||
price?: { units: string | number; nano: number } | undefined;
|
||
date?: unknown;
|
||
currency?: unknown;
|
||
}
|
||
|
||
/**
|
||
* Исполненные сделки BUY/SELL по счёту за период (Operations API).
|
||
* Комиссии, дивиденды, купоны, вводы/выводы не интересуют — этап 1
|
||
* считает среднюю цены позиции только по сделкам купли/продажи.
|
||
*/
|
||
export async function getExecutedTrades(
|
||
accountId: string,
|
||
fromMs: number,
|
||
toMs: number,
|
||
/** Опционально: только операции одного инструмента (фильтр на стороне API). */
|
||
figiFilter?: string,
|
||
): Promise<ExecutedTrade[]> {
|
||
const client = getClient();
|
||
const req = {
|
||
accountId,
|
||
from: toTimestamp(fromMs),
|
||
to: toTimestamp(toMs),
|
||
state: 'OPERATION_STATE_EXECUTED' as const,
|
||
...(figiFilter === undefined ? {} : { figi: figiFilter }),
|
||
};
|
||
// ВАЖНО: sandbox-счёт виден только через SandboxService — обычный
|
||
// OperationsService отвечает UNAUTHENTICATED (16 40003).
|
||
const res = (await request((cb) =>
|
||
config.tinkoffSandbox
|
||
? client.sandbox.getSandboxOperations(req, cb)
|
||
: client.operations.getOperations(req, cb),
|
||
)) as { operations?: RawOperation[] };
|
||
|
||
const trades: ExecutedTrade[] = [];
|
||
for (const op of res.operations ?? []) {
|
||
// ВАЖНО: enum операции — в operationType (type — русское описание).
|
||
const type = String(op.operationType ?? op.type ?? '');
|
||
if (type !== 'OPERATION_TYPE_BUY' && type !== 'OPERATION_TYPE_SELL') continue;
|
||
const figi = op.figi ? String(op.figi) : '';
|
||
if (!figi) continue;
|
||
const price = op.price ? quotationToNumber(op.price) : NaN;
|
||
const qty = Math.abs(toNumber(op.quantity));
|
||
const dateMs = protoTimestampToMs(op.date);
|
||
if (!Number.isFinite(price) || !Number.isFinite(qty) || qty <= 0 || !Number.isFinite(dateMs)) {
|
||
continue;
|
||
}
|
||
trades.push({
|
||
figi,
|
||
type: type === 'OPERATION_TYPE_BUY' ? 'buy' : 'sell',
|
||
qty,
|
||
price,
|
||
dateMs,
|
||
currency: op.currency ? String(op.currency) : null,
|
||
});
|
||
}
|
||
trades.sort((a, b) => a.dateMs - b.dateMs);
|
||
return trades;
|
||
}
|
||
|
||
// ---------- Портфель: текущие открытые позиции ----------
|
||
|
||
/** Итог портфеля счёта: стоимость в рублях, дневной P&L, ожид. доходность. */
|
||
export interface PortfolioTotal {
|
||
/** Оценка портфеля в рублях — totalAmountPortfolio (фолбэк: сумма компонентов). */
|
||
totalAmount: number | null;
|
||
/** Дневной P&L в рублях (dailyYield). */
|
||
dailyYield: number | null;
|
||
/**
|
||
* Ожидаемая доходность ОТНОСИТЕЛЬНЫМ коэффициентом (1.0 = без изменения) —
|
||
* это НЕ рубли, в API v2 поле expectedYield.
|
||
*/
|
||
expectedYield: number | null;
|
||
}
|
||
|
||
/**
|
||
* Суммарная оценка портфеля и P&L счёта.
|
||
*
|
||
* ВАЖНО (проверено сырым запросом к API): в PortfolioResponse НЕТ поля
|
||
* `totalAmount` — итог лежит в `totalAmountPortfolio`, а по классам активов
|
||
* идёт разбивка `totalAmountShares` / `totalAmountBonds` / `totalAmountEtf`
|
||
* (без «s»!) / `totalAmountCurrencies` / `totalAmountFutures` /
|
||
* `totalAmountOptions` / `totalAmountSp`. Дени на счёт — отрицательные
|
||
* `totalAmountCurrencies`, они обязаны входить в итог.
|
||
*/
|
||
export async function getPortfolioTotal(accountId: string): Promise<PortfolioTotal> {
|
||
const client = getClient();
|
||
const res = (await request((cb) =>
|
||
config.tinkoffSandbox
|
||
? client.sandbox.getSandboxPortfolio({ accountId }, cb)
|
||
: client.operations.getPortfolio({ accountId }, cb),
|
||
)) as Record<string, unknown>;
|
||
/** MoneyValue | Quotation | число -> number; null, если поля нет или оно не число. */
|
||
const amount = (key: string): number | null => {
|
||
const v = res[key];
|
||
if (v === null || v === undefined) return null;
|
||
if (typeof v === 'object' && 'units' in (v as object)) {
|
||
return quotationToNumber(v as { units: string | number; nano: number });
|
||
}
|
||
const n = toNumber(v);
|
||
return Number.isFinite(n) ? n : null;
|
||
};
|
||
const parts = [
|
||
amount('totalAmountShares'),
|
||
amount('totalAmountBonds'),
|
||
amount('totalAmountEtf'),
|
||
amount('totalAmountCurrencies'),
|
||
amount('totalAmountFutures'),
|
||
amount('totalAmountOptions'),
|
||
amount('totalAmountSp'),
|
||
].filter((v): v is number => v !== null);
|
||
const sum = amount('totalAmountPortfolio') ?? (parts.length > 0 ? parts.reduce((a, b) => a + b, 0) : null);
|
||
return {
|
||
totalAmount: sum === null ? null : Math.round(sum * 100) / 100,
|
||
dailyYield: amount('dailyYield'),
|
||
expectedYield: amount('expectedYield'),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* FIGI инструментов, открытых СЕЙЧАС (по портфелю брокера), — отправная точка
|
||
* для загрузки истории «от последнего ордера назад до нуля»: кампании по
|
||
* инструментам вне этого списка всё равно закрыты и не интересуют.
|
||
*/
|
||
export async function getOpenPositionFigis(accountId: string): Promise<string[]> {
|
||
const client = getClient();
|
||
// sandbox-счёт виден только через SandboxService (см. грабли #1 в progress.md)
|
||
const res = (await request((cb) =>
|
||
config.tinkoffSandbox
|
||
? client.sandbox.getSandboxPortfolio({ accountId }, cb)
|
||
: client.operations.getPortfolio({ accountId }, cb),
|
||
)) as {
|
||
positions?: Array<{ figi?: unknown; quantity?: unknown }>;
|
||
};
|
||
const figis = new Set<string>();
|
||
for (const p of res.positions ?? []) {
|
||
// quantity — Quotation {units, nano} или number; Long-объекты SDK не вариант
|
||
let qty = NaN;
|
||
const raw = p.quantity as unknown;
|
||
if (raw !== null && typeof raw === 'object' && 'units' in (raw as object)) {
|
||
qty = quotationToNumber(raw as { units: string | number; nano: number });
|
||
} else {
|
||
qty = toNumber(raw);
|
||
}
|
||
if (!p.figi || !Number.isFinite(qty) || Math.abs(qty) < 1e-6) continue;
|
||
figis.add(String(p.figi));
|
||
}
|
||
return [...figis];
|
||
}
|
||
|
||
// ---------- Последние цены ----------
|
||
|
||
/** Последние цены по списку FIGI одним запросом; недоступные пропускаются. */
|
||
export async function getLastPrices(figis: string[]): Promise<Map<string, number>> {
|
||
const map = new Map<string, number>();
|
||
if (figis.length === 0) return map;
|
||
const client = getClient();
|
||
const res = (await request((cb) =>
|
||
client.marketData.getLastPrices({ figi: figis }, cb),
|
||
)) as {
|
||
lastPrices?: Array<{
|
||
figi?: unknown;
|
||
price?: { units: string | number; nano: number } | undefined;
|
||
}>;
|
||
};
|
||
for (const lp of res.lastPrices ?? []) {
|
||
if (!lp.figi || !lp.price) continue;
|
||
const price = quotationToNumber(lp.price);
|
||
if (Number.isFinite(price)) map.set(String(lp.figi), price);
|
||
}
|
||
return map;
|
||
}
|
||
|
||
// ---------- Справочник акций ----------
|
||
|
||
const MOEX_SHARE_BOARD = 'TQBR';
|
||
|
||
interface RawShare {
|
||
figi?: string;
|
||
ticker?: string;
|
||
name?: string;
|
||
lot?: unknown;
|
||
currency?: unknown;
|
||
classCode?: string;
|
||
minPriceIncrement?: { units: string | number; nano: number } | undefined;
|
||
}
|
||
|
||
const instrumentMetaCache = new Map<string, ShareMeta | null>();
|
||
|
||
function rawToMeta(s: RawShare | undefined): ShareMeta | null {
|
||
if (!s?.figi) return null;
|
||
return {
|
||
figi: s.figi,
|
||
ticker: String(s.ticker ?? ''),
|
||
name: String(s.name ?? ''),
|
||
lot: Number.isFinite(Number(s.lot)) ? Number(s.lot) : 1,
|
||
currency: s.currency ? String(s.currency) : '',
|
||
minPriceIncrement: s.minPriceIncrement ? quotationToNumber(s.minPriceIncrement) : 0.01,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Метаданные инструмента по FIGI: пробуем акцию -> облигацию -> фонд.
|
||
* Служебные figi (валюты и т.п.) и ошибки -> null.
|
||
*/
|
||
export async function getInstrumentMetaByFigi(figi: string): Promise<ShareMeta | null> {
|
||
if (instrumentMetaCache.has(figi)) return instrumentMetaCache.get(figi) ?? null;
|
||
const client = getClient();
|
||
const reqArg = { idType: 'INSTRUMENT_ID_TYPE_FIGI' as const, id: figi };
|
||
const probes: Array<(cb: (err: unknown, res?: unknown) => void) => void> = [
|
||
(cb) => client.instruments.shareBy(reqArg, cb),
|
||
(cb) => client.instruments.bondBy(reqArg, cb),
|
||
(cb) => client.instruments.etfBy(reqArg, cb),
|
||
];
|
||
let meta: ShareMeta | null = null;
|
||
for (const probe of probes) {
|
||
try {
|
||
const res = (await request(probe)) as { instrument?: RawShare };
|
||
meta = rawToMeta(res.instrument);
|
||
if (meta) break;
|
||
} catch {
|
||
// Не этот тип инструмента (или ошибка) — пробуем следующий.
|
||
}
|
||
}
|
||
instrumentMetaCache.set(figi, meta);
|
||
return meta;
|
||
}
|
||
|
||
/** Все акции основного режима MOEX (TQBR) — ~250 инструментов. */
|
||
export async function listShares(): Promise<ShareMeta[]> {
|
||
const client = getClient();
|
||
const res = (await request((cb) =>
|
||
client.instruments.shares({ instrumentStatus: 'INSTRUMENT_STATUS_BASE' }, cb),
|
||
)) as { instruments?: RawShare[] };
|
||
return (res.instruments ?? [])
|
||
.filter((s) => s.figi && s.ticker && s.classCode === MOEX_SHARE_BOARD)
|
||
.map((s) => ({
|
||
figi: s.figi as string,
|
||
ticker: String(s.ticker),
|
||
name: String(s.name ?? s.ticker ?? ''),
|
||
lot: Number.isFinite(Number(s.lot)) ? Number(s.lot) : 1,
|
||
currency: s.currency ? String(s.currency) : '',
|
||
minPriceIncrement: s.minPriceIncrement ? quotationToNumber(s.minPriceIncrement) : 0.01,
|
||
}));
|
||
}
|
||
|
||
/** Поиск акции по тикеру MOEX (для демо-скрипта). null, если не найдена. */
|
||
export async function findShareByTicker(ticker: string): Promise<ShareMeta | null> {
|
||
const all = await listShares();
|
||
return all.find((s) => s.ticker.toUpperCase() === ticker.toUpperCase()) ?? null;
|
||
}
|
||
|
||
// ---------- Свечи ----------
|
||
|
||
const INTERVAL_MAP = {
|
||
'1m': 'CANDLE_INTERVAL_1_MIN',
|
||
'5m': 'CANDLE_INTERVAL_5_MIN',
|
||
'15m': 'CANDLE_INTERVAL_15_MIN',
|
||
'1h': 'CANDLE_INTERVAL_HOUR',
|
||
'1d': 'CANDLE_INTERVAL_DAY',
|
||
} as const satisfies Record<CandleInterval, string>;
|
||
|
||
/**
|
||
* Размер чанка запроса свечей, дней. Лимиты окна T-Invest API:
|
||
* 1м — максимум сутки на запрос (иначе gRPC 30014), старше — больше.
|
||
*/
|
||
const CANDLE_CHUNK_DAYS: Record<CandleInterval, number> = {
|
||
'1m': 1,
|
||
'5m': 7,
|
||
'15m': 7,
|
||
'1h': 30,
|
||
'1d': 120,
|
||
};
|
||
|
||
interface RawHistoricCandle {
|
||
time: unknown;
|
||
open: { units: string | number; nano: number };
|
||
high: { units: string | number; nano: number };
|
||
low: { units: string | number; nano: number };
|
||
close: { units: string | number; nano: number };
|
||
volume?: unknown;
|
||
}
|
||
|
||
async function getCandlesWindow(
|
||
figi: string,
|
||
interval: CandleInterval,
|
||
fromMs: number,
|
||
toMs: number,
|
||
): Promise<Candle[]> {
|
||
const client = getClient();
|
||
const res = (await request((cb) =>
|
||
client.marketData.getCandles(
|
||
{
|
||
figi,
|
||
from: toTimestamp(fromMs),
|
||
to: toTimestamp(toMs),
|
||
interval: INTERVAL_MAP[interval],
|
||
},
|
||
cb,
|
||
),
|
||
)) as { candles?: RawHistoricCandle[] };
|
||
return (res.candles ?? []).map((c) => {
|
||
const ms = protoTimestampToMs(c.time);
|
||
if (!Number.isFinite(ms)) {
|
||
throw new Error(`getCandles: не удалось распарсить time=${JSON.stringify(c.time)}`);
|
||
}
|
||
return {
|
||
time: new Date(ms).toISOString(),
|
||
open: quotationToNumber(c.open),
|
||
high: quotationToNumber(c.high),
|
||
low: quotationToNumber(c.low),
|
||
close: quotationToNumber(c.close),
|
||
volume: toNumber(c.volume) || 0,
|
||
};
|
||
});
|
||
}
|
||
|
||
/** Свечи за период: чанкование по лимитам окна, дедуп по времени, сортировка. */
|
||
export async function getCandles(
|
||
figi: string,
|
||
interval: CandleInterval,
|
||
fromMs: number,
|
||
toMs: number,
|
||
): Promise<Candle[]> {
|
||
const chunkMs = CANDLE_CHUNK_DAYS[interval] * 86_400_000;
|
||
const out: Candle[] = [];
|
||
const seen = new Set<string>();
|
||
for (let cursor = fromMs; cursor < toMs; cursor += chunkMs) {
|
||
const end = Math.min(cursor + chunkMs, toMs);
|
||
for (const c of await getCandlesWindow(figi, interval, cursor, end)) {
|
||
if (seen.has(c.time)) continue;
|
||
seen.add(c.time);
|
||
out.push(c);
|
||
}
|
||
}
|
||
out.sort((a, b) => a.time.localeCompare(b.time));
|
||
return out;
|
||
}
|
||
|
||
// ---------- Sandbox-утилиты (демо-скрипт; только TINKOFF_SANDBOX=true) ----------
|
||
|
||
/** Пополнить sandbox-счёт виртуальными деньгами. */
|
||
export async function sandboxPayIn(accountId: string, amountRub: number): Promise<void> {
|
||
const client = getClient();
|
||
await request((cb) =>
|
||
client.sandbox.sandboxPayIn(
|
||
{
|
||
accountId,
|
||
amount: {
|
||
units: Math.floor(amountRub),
|
||
nano: Math.round((amountRub % 1) * 1e9),
|
||
currency: 'rub',
|
||
},
|
||
},
|
||
cb,
|
||
),
|
||
);
|
||
}
|
||
|
||
/** Открыть новый sandbox-счёт. */
|
||
export async function sandboxOpenAccount(): Promise<void> {
|
||
const client = getClient();
|
||
await request((cb) => client.sandbox.openSandboxAccount({}, cb));
|
||
}
|
||
|
||
export interface SandboxOrderResult {
|
||
orderId: string;
|
||
executionReportStatus: string;
|
||
lotsExecuted: number | null;
|
||
message: string;
|
||
}
|
||
|
||
/**
|
||
* Ордер в песочнице: MARKET, либо LIMIT при заданном limitPrice.
|
||
* quantity — в лотах.
|
||
*/
|
||
export async function sandboxPostOrder(params: {
|
||
accountId: string;
|
||
figi: string;
|
||
quantity: number;
|
||
direction: 'buy' | 'sell';
|
||
/** Если задана — лимитный ордер по этой цене (шаг цены — из справочника). */
|
||
limitPrice?: number;
|
||
}): Promise<SandboxOrderResult> {
|
||
const client = getClient();
|
||
const res = (await request((cb) =>
|
||
client.sandbox.postSandboxOrder(
|
||
{
|
||
figi: params.figi,
|
||
quantity: params.quantity,
|
||
direction: params.direction === 'buy' ? 'ORDER_DIRECTION_BUY' : 'ORDER_DIRECTION_SELL',
|
||
accountId: params.accountId,
|
||
orderType: params.limitPrice === undefined ? 'ORDER_TYPE_MARKET' : 'ORDER_TYPE_LIMIT',
|
||
...(params.limitPrice === undefined
|
||
? {}
|
||
: {
|
||
price: {
|
||
units: Math.floor(params.limitPrice),
|
||
nano: Math.round((params.limitPrice % 1) * 1e9),
|
||
},
|
||
}),
|
||
orderId: randomUUID(),
|
||
},
|
||
cb,
|
||
),
|
||
)) as {
|
||
orderId?: unknown;
|
||
executionReportStatus?: unknown;
|
||
lotsExecuted?: unknown;
|
||
message?: unknown;
|
||
};
|
||
return {
|
||
orderId: String(res.orderId ?? ''),
|
||
executionReportStatus: String(res.executionReportStatus ?? ''),
|
||
lotsExecuted: Number.isFinite(Number(res.lotsExecuted))
|
||
? Number(res.lotsExecuted)
|
||
: null,
|
||
message: String(res.message ?? ''),
|
||
};
|
||
}
|
||
|
||
/** Отменить активный ордер песочницы. */
|
||
export async function sandboxCancelOrder(
|
||
accountId: string,
|
||
orderId: string,
|
||
): Promise<void> {
|
||
const client = getClient();
|
||
await request((cb) => client.sandbox.cancelSandboxOrder({ accountId, orderId }, cb));
|
||
}
|
||
|
||
|
||
// ---------- Диагностика sandbox (npm run sandbox-diag) ----------
|
||
|
||
/** Активные ордера sandbox-счёта (сырой ответ). */
|
||
export async function getSandboxOrders(accountId: string): Promise<unknown[]> {
|
||
const client = getClient();
|
||
const res = (await request((cb) =>
|
||
client.sandbox.getSandboxOrders({ accountId }, cb),
|
||
)) as { orders?: unknown[] };
|
||
return res.orders ?? [];
|
||
}
|
||
|
||
/** Портфель sandbox-счёта (сырой ответ). */
|
||
export async function getSandboxPortfolio(accountId: string): Promise<unknown> {
|
||
const client = getClient();
|
||
return request((cb) => client.sandbox.getSandboxPortfolio({ accountId }, cb));
|
||
}
|
||
|
||
/** Все операции sandbox-счёта без фильтра по статусу (сырой ответ). */
|
||
export async function getSandboxOperationsRaw(
|
||
accountId: string,
|
||
fromMs: number,
|
||
toMs: number,
|
||
): Promise<unknown[]> {
|
||
const client = getClient();
|
||
const res = (await request((cb) =>
|
||
client.sandbox.getSandboxOperations(
|
||
{ accountId, from: toTimestamp(fromMs), to: toTimestamp(toMs) },
|
||
cb,
|
||
),
|
||
)) as { operations?: unknown[] };
|
||
return res.operations ?? [];
|
||
}
|
||
|
||
|
||
|
||
|