@woodger/t-invest-node-sdk 0.5.7 → 0.5.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -4
- package/NOTICE +2 -2
- package/dist/application/dto/t-invest-options.d.ts +8 -6
- package/dist/application/dto/t-invest-options.js +4 -4
- package/dist/application/dto/t-invest-services.d.ts +24 -0
- package/dist/application/errors/sdk-error.d.ts +12 -7
- package/dist/application/errors/sdk-error.js +16 -23
- package/dist/application/reports/asset.report.d.ts +5 -0
- package/dist/application/reports/broker-report.report.d.ts +8 -0
- package/dist/application/reports/dividends-foreign-issuer.report.d.ts +8 -0
- package/dist/application/reports/sandbox-account.report.d.ts +6 -0
- package/dist/application/services/unary-limiter.d.ts +14 -13
- package/dist/application/services/unary-limiter.js +20 -12
- package/dist/bootstrap/args/command-options.d.ts +5 -0
- package/dist/bootstrap/args/command-options.js +24 -15
- package/dist/bootstrap/args/instrument-id-options.d.ts +8 -4
- package/dist/bootstrap/args/instruments-args.d.ts +2 -2
- package/dist/bootstrap/args/sdk-options.d.ts +7 -4
- package/dist/bootstrap/args/sdk-options.js +3 -4
- package/dist/bootstrap/args/side-effect-args.js +4 -2
- package/dist/bootstrap/cli/domains.d.ts +11 -9
- package/dist/bootstrap/cli/error.d.ts +5 -0
- package/dist/bootstrap/cli/error.js +9 -2
- package/dist/bootstrap/cli/help-catalog.d.ts +3 -1
- package/dist/bootstrap/cli/help.d.ts +3 -3
- package/dist/bootstrap/cli/registry.d.ts +287 -287
- package/dist/bootstrap/cli/registry.js +2 -6
- package/dist/bootstrap/cli/runner.js +12 -31
- package/dist/bootstrap/commands/accounts/cli.d.ts +4 -4
- package/dist/bootstrap/commands/accounts/cli.js +15 -21
- package/dist/bootstrap/commands/accounts/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/accrued-interests/cli.d.ts +14 -14
- package/dist/bootstrap/commands/accrued-interests/cli.js +12 -20
- package/dist/bootstrap/commands/accrued-interests/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/asset/cli.d.ts +11 -11
- package/dist/bootstrap/commands/asset/cli.js +12 -20
- package/dist/bootstrap/commands/asset/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/assets/cli.d.ts +14 -14
- package/dist/bootstrap/commands/assets/cli.js +12 -20
- package/dist/bootstrap/commands/assets/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/bond/cli.d.ts +4 -4
- package/dist/bootstrap/commands/bond/cli.js +17 -23
- package/dist/bootstrap/commands/bond/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/bond-coupons/cli.d.ts +14 -14
- package/dist/bootstrap/commands/bond-coupons/cli.js +12 -20
- package/dist/bootstrap/commands/bond-coupons/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/bonds/cli.d.ts +4 -4
- package/dist/bootstrap/commands/bonds/cli.js +17 -23
- package/dist/bootstrap/commands/bonds/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/brand/cli.d.ts +11 -11
- package/dist/bootstrap/commands/brand/cli.js +12 -20
- package/dist/bootstrap/commands/brand/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/brands/cli.d.ts +4 -4
- package/dist/bootstrap/commands/brands/cli.js +15 -21
- package/dist/bootstrap/commands/brands/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/broker-report/cli.d.ts +23 -23
- package/dist/bootstrap/commands/broker-report/cli.js +12 -20
- package/dist/bootstrap/commands/broker-report/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/cancel-order/cli.d.ts +8 -8
- package/dist/bootstrap/commands/cancel-order/cli.js +26 -34
- package/dist/bootstrap/commands/cancel-order/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/cancel-stop-order/cli.d.ts +14 -14
- package/dist/bootstrap/commands/cancel-stop-order/cli.js +14 -21
- package/dist/bootstrap/commands/cancel-stop-order/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/candles/cli.d.ts +20 -20
- package/dist/bootstrap/commands/candles/cli.js +12 -20
- package/dist/bootstrap/commands/candles/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/close-prices/cli.d.ts +11 -11
- package/dist/bootstrap/commands/close-prices/cli.js +12 -20
- package/dist/bootstrap/commands/close-prices/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/countries/cli.d.ts +4 -4
- package/dist/bootstrap/commands/countries/cli.js +15 -21
- package/dist/bootstrap/commands/countries/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/currencies/cli.d.ts +4 -4
- package/dist/bootstrap/commands/currencies/cli.js +17 -23
- package/dist/bootstrap/commands/currencies/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/currency/cli.d.ts +4 -4
- package/dist/bootstrap/commands/currency/cli.js +17 -23
- package/dist/bootstrap/commands/currency/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/dividends/cli.d.ts +14 -14
- package/dist/bootstrap/commands/dividends/cli.js +12 -20
- package/dist/bootstrap/commands/dividends/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/dividends-foreign-issuer/cli.d.ts +23 -23
- package/dist/bootstrap/commands/dividends-foreign-issuer/cli.js +12 -23
- package/dist/bootstrap/commands/dividends-foreign-issuer/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/edit-favorites/cli.d.ts +11 -11
- package/dist/bootstrap/commands/edit-favorites/cli.js +14 -21
- package/dist/bootstrap/commands/edit-favorites/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/etf/cli.d.ts +4 -4
- package/dist/bootstrap/commands/etf/cli.js +17 -23
- package/dist/bootstrap/commands/etf/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/etfs/cli.d.ts +4 -4
- package/dist/bootstrap/commands/etfs/cli.js +17 -23
- package/dist/bootstrap/commands/etfs/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/favorites/cli.d.ts +4 -4
- package/dist/bootstrap/commands/favorites/cli.js +15 -21
- package/dist/bootstrap/commands/favorites/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/find-instrument/cli.d.ts +20 -20
- package/dist/bootstrap/commands/find-instrument/cli.js +12 -20
- package/dist/bootstrap/commands/find-instrument/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/future/cli.d.ts +4 -4
- package/dist/bootstrap/commands/future/cli.js +17 -23
- package/dist/bootstrap/commands/future/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/futures/cli.d.ts +4 -4
- package/dist/bootstrap/commands/futures/cli.js +17 -23
- package/dist/bootstrap/commands/futures/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/futures-margin/cli.d.ts +8 -8
- package/dist/bootstrap/commands/futures-margin/cli.js +12 -20
- package/dist/bootstrap/commands/futures-margin/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/help/cli.js +1 -4
- package/dist/bootstrap/commands/instrument/cli.d.ts +4 -4
- package/dist/bootstrap/commands/instrument/cli.js +17 -23
- package/dist/bootstrap/commands/instrument/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/last-prices/cli.d.ts +11 -11
- package/dist/bootstrap/commands/last-prices/cli.js +12 -20
- package/dist/bootstrap/commands/last-prices/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/last-trades/cli.d.ts +17 -17
- package/dist/bootstrap/commands/last-trades/cli.js +12 -20
- package/dist/bootstrap/commands/last-trades/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/margin-attributes/cli.d.ts +11 -11
- package/dist/bootstrap/commands/margin-attributes/cli.js +12 -20
- package/dist/bootstrap/commands/margin-attributes/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/operations/cli.d.ts +20 -20
- package/dist/bootstrap/commands/operations/cli.js +34 -45
- package/dist/bootstrap/commands/operations/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/operations/request.mapper.d.ts +6 -6
- package/dist/bootstrap/commands/operations-by-cursor/cli.d.ts +42 -42
- package/dist/bootstrap/commands/operations-by-cursor/cli.js +55 -73
- package/dist/bootstrap/commands/operations-by-cursor/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/operations-by-cursor/request.mapper.d.ts +6 -6
- package/dist/bootstrap/commands/operations-by-cursor/request.mapper.js +8 -3
- package/dist/bootstrap/commands/option/cli.d.ts +4 -4
- package/dist/bootstrap/commands/option/cli.js +17 -23
- package/dist/bootstrap/commands/option/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/options-by/cli.d.ts +14 -14
- package/dist/bootstrap/commands/options-by/cli.js +12 -20
- package/dist/bootstrap/commands/options-by/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/order-book/cli.d.ts +20 -20
- package/dist/bootstrap/commands/order-book/cli.js +16 -27
- package/dist/bootstrap/commands/order-book/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/order-state/cli.d.ts +8 -8
- package/dist/bootstrap/commands/order-state/cli.js +24 -33
- package/dist/bootstrap/commands/order-state/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/orders/cli.d.ts +6 -6
- package/dist/bootstrap/commands/orders/cli.js +20 -29
- package/dist/bootstrap/commands/orders/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/portfolio/cli.d.ts +10 -10
- package/dist/bootstrap/commands/portfolio/cli.js +25 -34
- package/dist/bootstrap/commands/portfolio/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/portfolio/request.mapper.d.ts +4 -4
- package/dist/bootstrap/commands/positions/cli.d.ts +6 -6
- package/dist/bootstrap/commands/positions/cli.js +20 -29
- package/dist/bootstrap/commands/positions/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/post-order/cli.d.ts +16 -16
- package/dist/bootstrap/commands/post-order/cli.js +47 -55
- package/dist/bootstrap/commands/post-order/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/post-order/request.mapper.d.ts +9 -9
- package/dist/bootstrap/commands/post-stop-order/cli.d.ts +32 -32
- package/dist/bootstrap/commands/post-stop-order/cli.js +14 -21
- package/dist/bootstrap/commands/post-stop-order/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/replace-order/cli.d.ts +14 -14
- package/dist/bootstrap/commands/replace-order/cli.js +43 -51
- package/dist/bootstrap/commands/replace-order/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/replace-order/request.mapper.d.ts +4 -4
- package/dist/bootstrap/commands/sandbox-accounts/cli.d.ts +4 -5
- package/dist/bootstrap/commands/sandbox-accounts/cli.js +15 -25
- package/dist/bootstrap/commands/sandbox-cancel-order/cli.d.ts +8 -43
- package/dist/bootstrap/commands/sandbox-cancel-order/cli.js +26 -38
- package/dist/bootstrap/commands/sandbox-close-account/cli.d.ts +11 -11
- package/dist/bootstrap/commands/sandbox-close-account/cli.js +14 -21
- package/dist/bootstrap/commands/sandbox-close-account/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/sandbox-open-account/cli.d.ts +4 -5
- package/dist/bootstrap/commands/sandbox-open-account/cli.js +17 -27
- package/dist/bootstrap/commands/sandbox-open-account/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/sandbox-operations/cli.d.ts +16 -63
- package/dist/bootstrap/commands/sandbox-operations/cli.js +34 -47
- package/dist/bootstrap/commands/sandbox-operations-by-cursor/cli.d.ts +30 -93
- package/dist/bootstrap/commands/sandbox-operations-by-cursor/cli.js +55 -72
- package/dist/bootstrap/commands/sandbox-order-state/cli.d.ts +8 -40
- package/dist/bootstrap/commands/sandbox-order-state/cli.js +24 -37
- package/dist/bootstrap/commands/sandbox-orders/cli.d.ts +6 -34
- package/dist/bootstrap/commands/sandbox-orders/cli.js +20 -33
- package/dist/bootstrap/commands/sandbox-pay-in/cli.d.ts +20 -20
- package/dist/bootstrap/commands/sandbox-pay-in/cli.js +14 -21
- package/dist/bootstrap/commands/sandbox-pay-in/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/sandbox-portfolio/cli.d.ts +12 -45
- package/dist/bootstrap/commands/sandbox-portfolio/cli.js +25 -38
- package/dist/bootstrap/commands/sandbox-positions/cli.d.ts +6 -34
- package/dist/bootstrap/commands/sandbox-positions/cli.js +20 -33
- package/dist/bootstrap/commands/sandbox-post-order/cli.d.ts +20 -79
- package/dist/bootstrap/commands/sandbox-post-order/cli.js +47 -59
- package/dist/bootstrap/commands/sandbox-replace-order/cli.d.ts +16 -71
- package/dist/bootstrap/commands/sandbox-replace-order/cli.js +43 -55
- package/dist/bootstrap/commands/sandbox-withdraw-limits/cli.d.ts +6 -34
- package/dist/bootstrap/commands/sandbox-withdraw-limits/cli.js +20 -36
- package/dist/bootstrap/commands/share/cli.d.ts +4 -4
- package/dist/bootstrap/commands/share/cli.js +17 -23
- package/dist/bootstrap/commands/share/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/shares/cli.d.ts +4 -4
- package/dist/bootstrap/commands/shares/cli.js +17 -23
- package/dist/bootstrap/commands/shares/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/stop-orders/cli.d.ts +11 -11
- package/dist/bootstrap/commands/stop-orders/cli.js +12 -20
- package/dist/bootstrap/commands/stop-orders/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/stream-run/cli.d.ts +4 -3
- package/dist/bootstrap/commands/stream-run/cli.js +8 -15
- package/dist/bootstrap/commands/stream-run/config.d.ts +18 -1
- package/dist/bootstrap/commands/stream-run/config.js +12 -11
- package/dist/bootstrap/commands/stream-run/reporter.d.ts +6 -1
- package/dist/bootstrap/commands/stream-run/stream-session.d.ts +15 -0
- package/dist/bootstrap/commands/stream-run/stream-session.js +14 -14
- package/dist/bootstrap/commands/trading-schedules/cli.d.ts +17 -17
- package/dist/bootstrap/commands/trading-schedules/cli.js +12 -20
- package/dist/bootstrap/commands/trading-schedules/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/trading-status/cli.d.ts +11 -11
- package/dist/bootstrap/commands/trading-status/cli.js +12 -20
- package/dist/bootstrap/commands/trading-status/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/trading-statuses/cli.d.ts +11 -11
- package/dist/bootstrap/commands/trading-statuses/cli.js +12 -20
- package/dist/bootstrap/commands/trading-statuses/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/user-info/cli.d.ts +4 -4
- package/dist/bootstrap/commands/user-info/cli.js +15 -21
- package/dist/bootstrap/commands/user-info/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/user-tariff/cli.d.ts +4 -4
- package/dist/bootstrap/commands/user-tariff/cli.js +15 -21
- package/dist/bootstrap/commands/user-tariff/reporter.d.ts +2 -1
- package/dist/bootstrap/commands/withdraw-limits/cli.d.ts +10 -6
- package/dist/bootstrap/commands/withdraw-limits/cli.js +27 -29
- package/dist/bootstrap/commands/withdraw-limits/reporter.d.ts +2 -1
- package/dist/bootstrap/generated-exports.d.ts +1 -1
- package/dist/bootstrap/generated-exports.js +14 -11
- package/dist/bootstrap/index.js +5 -2
- package/dist/bootstrap/proto/compile-proto.js +2 -0
- package/dist/bootstrap/sdk-config.d.ts +9 -7
- package/dist/bootstrap/sdk-config.js +8 -7
- package/dist/bootstrap/t-invest-node-sdk.d.ts +5 -5
- package/dist/bootstrap/t-invest-node-sdk.js +8 -7
- package/dist/bootstrap/unary-limit-config.d.ts +13 -14
- package/dist/bootstrap/unary-limit-config.js +12 -13
- package/dist/config.d.ts +9 -10
- package/dist/config.js +9 -10
- package/dist/config.types.d.ts +18 -19
- package/dist/config.types.js +6 -6
- package/dist/generated/common.d.ts +1 -0
- package/dist/generated/common.js +3 -2
- package/dist/generated/google/api/field_behavior.d.ts +1 -0
- package/dist/generated/google/api/field_behavior.js +3 -2
- package/dist/generated/google/protobuf/descriptor.d.ts +1 -0
- package/dist/generated/google/protobuf/descriptor.js +26 -16
- package/dist/generated/google/protobuf/timestamp.d.ts +1 -0
- package/dist/generated/google/protobuf/timestamp.js +20 -2
- package/dist/generated/instruments.d.ts +1 -0
- package/dist/generated/instruments.js +59 -55
- package/dist/generated/marketdata.d.ts +1 -0
- package/dist/generated/marketdata.js +10 -7
- package/dist/generated/operations.d.ts +1 -0
- package/dist/generated/operations.js +10 -7
- package/dist/generated/orders.d.ts +5 -2
- package/dist/generated/orders.js +29 -7
- package/dist/generated/sandbox.d.ts +1 -0
- package/dist/generated/sandbox.js +3 -2
- package/dist/generated/signals.d.ts +1 -0
- package/dist/generated/signals.js +3 -2
- package/dist/generated/stoporders.d.ts +1 -0
- package/dist/generated/stoporders.js +3 -2
- package/dist/generated/users.d.ts +1 -0
- package/dist/generated/users.js +9 -6
- package/dist/infrastructure/interceptor/warning-interceptor.d.ts +1 -0
- package/dist/infrastructure/report-values.js +5 -1
- package/dist/infrastructure/transport/grpc/call-callback-boundary.d.ts +23 -0
- package/dist/infrastructure/transport/grpc/call-callback-boundary.js +56 -0
- package/dist/infrastructure/transport/grpc/sdk-call-error.js +13 -7
- package/dist/infrastructure/transport/grpc/sdk-channel.d.ts +5 -5
- package/dist/infrastructure/transport/grpc/sdk-channel.js +5 -5
- package/dist/infrastructure/transport/grpc/sdk-client.d.ts +4 -3
- package/dist/infrastructure/transport/grpc/sdk-client.js +4 -3
- package/dist/infrastructure/transport/grpc/sdk-middleware.d.ts +20 -12
- package/dist/infrastructure/transport/grpc/sdk-middleware.js +96 -110
- package/dist/infrastructure/transport/grpc/unary-limit-resolver.d.ts +3 -3
- package/dist/infrastructure/transport/grpc/unary-limit-resolver.js +3 -3
- package/docs/architecture.md +30 -39
- package/docs/bundled-ca.md +11 -12
- package/docs/clean-architecture/adapters.md +14 -14
- package/docs/clean-architecture/api-commands.md +16 -19
- package/docs/clean-architecture/application.md +20 -18
- package/docs/clean-architecture/cli-output-boundaries.md +26 -20
- package/docs/clean-architecture/dto.md +18 -18
- package/docs/clean-architecture/index.md +7 -10
- package/docs/cli-reference.md +15 -15
- package/docs/cli-stream-configuration.md +31 -15
- package/docs/cli-stream-reference.md +16 -16
- package/docs/examples/custom-unary-limiter.md +42 -36
- package/docs/examples/deprecated-fields.md +5 -5
- package/docs/examples/errors-and-lifecycle.md +24 -12
- package/docs/examples/getting-started.md +6 -6
- package/docs/examples/index.md +29 -20
- package/docs/examples/instrument-lookup.md +35 -0
- package/docs/examples/market-data-recovery.md +159 -105
- package/docs/examples/operations-pagination.md +47 -0
- package/docs/examples/order-state-stream.md +39 -0
- package/docs/examples/sandbox-orders.md +88 -0
- package/docs/examples/streams-and-cancellation.md +91 -10
- package/docs/examples/testing-with-service-definitions.md +7 -5
- package/docs/examples/unary-calls.md +27 -15
- package/docs/examples/unary-limits.md +12 -9
- package/docs/index.md +16 -20
- package/docs/limits-policy.md +16 -13
- package/docs/tls-policy.md +10 -8
- package/package.json +5 -5
- package/readme.md +19 -142
package/docs/examples/index.md
CHANGED
|
@@ -1,34 +1,43 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Выбрать пример для задачи SDK
|
|
2
2
|
|
|
3
3
|
> Type: Navigation. Выберите пример по задаче, которую решает приложение.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Получить данные через SDK
|
|
6
6
|
|
|
7
|
-
- [
|
|
8
|
-
- [
|
|
7
|
+
- [Получить список счетов и закрыть SDK](./getting-started.md) — выбрать счёт для следующего запроса.
|
|
8
|
+
- [Найти инструмент и получить UID](./instrument-lookup.md) — найти инструмент по тикеру и классу для следующих запросов.
|
|
9
|
+
- [Выполнить связанные одиночные gRPC-запросы](./unary-calls.md) — получить портфель, свечи или активные сигналы с ограничением времени.
|
|
10
|
+
- [Догрузить свечную историю окнами](./market-data-recovery.md#догрузить-историю) — прочитать завершённые минутные свечи за большой период.
|
|
11
|
+
- [Прочитать операции по страницам](./operations-pagination.md) — пройти историю счёта по курсору.
|
|
9
12
|
|
|
10
|
-
##
|
|
13
|
+
## Работать с заявками
|
|
11
14
|
|
|
12
|
-
- [
|
|
13
|
-
- [
|
|
14
|
-
- [Ошибки и lifecycle](./errors-and-lifecycle.md) — проверка `SdkError`, различение причин ошибок, закрытие SDK и условия повторного запроса.
|
|
15
|
+
- [Выполнить цикл заявки в песочнице](./sandbox-orders.md) — создать тестовый счёт, пополнить его, выставить заявку и отменить активный остаток.
|
|
16
|
+
- [Следить за состоянием заявки](./order-state-stream.md) — подписаться на события счёта и выделить сообщения по клиентскому ключу заявки.
|
|
15
17
|
|
|
16
|
-
##
|
|
18
|
+
## Читать и восстанавливать потоки
|
|
17
19
|
|
|
18
|
-
- [
|
|
19
|
-
- [
|
|
20
|
+
- [Читать поток и завершать его](./streams-and-cancellation.md) — подписаться на события, отменить чтение через `AbortSignal` и закрыть SDK.
|
|
21
|
+
- [Изменить подписку во время чтения](./streams-and-cancellation.md#изменить-подписку-во-время-чтения) — отправить подписку и отписку в одном двустороннем потоке.
|
|
22
|
+
- [Восстановить поток закрытых свечей](./market-data-recovery.md) — повторно подписаться, догрузить историю и сохранить прогресс.
|
|
23
|
+
- [Обработать ошибки и закрыть SDK](./errors-and-lifecycle.md) — проверить `SdkError`, различить причины и решить вопрос о повторе.
|
|
20
24
|
|
|
21
|
-
##
|
|
25
|
+
## Ограничить одиночные gRPC-запросы
|
|
22
26
|
|
|
23
|
-
- [
|
|
27
|
+
- [Ограничить частоту одиночных gRPC-запросов](./unary-limits.md) — подключить готовый ограничитель, переопределить квоты и выделить их долю.
|
|
28
|
+
- [Реализовать свой ограничитель одиночных gRPC-запросов](./custom-unary-limiter.md) — написать ограничитель, обработать отмену и координировать квоты.
|
|
24
29
|
|
|
25
|
-
##
|
|
30
|
+
## Перейти с устаревших полей
|
|
26
31
|
|
|
27
|
-
- [
|
|
32
|
+
- [Перейти с устаревших полей провайдера](./deprecated-fields.md) — сохранить совместимость CLI и перенести изменения в модель приложения.
|
|
28
33
|
|
|
29
|
-
##
|
|
34
|
+
## Проверить приложение
|
|
30
35
|
|
|
31
|
-
- [
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
36
|
+
- [Проверить приложение с тестовым gRPC-сервером](./testing-with-service-definitions.md) — выполнить тест без брокера через публичные `*ServiceDefinition`.
|
|
37
|
+
|
|
38
|
+
## Найти справочные сведения
|
|
39
|
+
|
|
40
|
+
- [Учесть лимиты T-Invest API](../limits-policy.md) — сверить квоты запросов и соединений.
|
|
41
|
+
- [Запустить потоковую команду CLI](../cli-stream-reference.md) — прочитать формат событий и коды завершения.
|
|
42
|
+
- [Настроить потоковую команду CLI](../cli-stream-configuration.md) — описать поток и подписки в JSON.
|
|
43
|
+
- [Выбрать документацию по задаче](../index.md) — перейти к настройкам и материалам для разработки.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Найти инструмент и получить UID
|
|
2
|
+
|
|
3
|
+
Чтобы получить UID по тикеру, укажите также класс инструмента — `classCode`. Пример находит акцию `SBER` в классе `TQBR` и выводит её UID. Замените токен, тикер и класс своими значениями.
|
|
4
|
+
|
|
5
|
+
`instrument-lookup.ts`
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { InstrumentIdType, TInvestNodeSDK } from '@woodger/t-invest-node-sdk';
|
|
9
|
+
|
|
10
|
+
const sdk = new TInvestNodeSDK({
|
|
11
|
+
token: 'YOUR_TOKEN',
|
|
12
|
+
endpoint: 'invest-public-api.tbank.ru:443'
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
try {
|
|
16
|
+
const { instrument } = await sdk.instruments.getInstrumentBy({
|
|
17
|
+
idType: InstrumentIdType.INSTRUMENT_ID_TYPE_TICKER,
|
|
18
|
+
id: 'SBER',
|
|
19
|
+
classCode: 'TQBR'
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
if (!instrument) {
|
|
23
|
+
throw new Error('Instrument was not returned');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
console.log(instrument.uid);
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
sdk.close();
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Передавайте `instrument.uid` в `instrumentId` запросов котировок и заявок. В `instrument` также доступны размер лота (`lot`), валюта (`currency`) и шаг цены (`minPriceIncrement`) — они пригодятся для [заявки в песочнице](./sandbox-orders.md).
|
|
34
|
+
|
|
35
|
+
Если известна только часть названия или тикера, начните с `sdk.instruments.findInstrument({ query })`. Параметры запросов описаны в [контрактах инструментов](../../contracts/instruments.proto), а ограничение времени вызова — в [руководстве по unary-запросам](./unary-calls.md).
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Восстановить поток закрытых свечей
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Используйте этот пример, когда разрыв потокового соединения не должен приводить к пропуску закрытых минутных свечей. Приложение повторно подписывается, дочитывает историю через `GetCandles` и сохраняет checkpoint после записи свечи. В итоге оно продолжает обработку с последней сохранённой позиции, не выдавая незавершённые свечи.
|
|
4
4
|
|
|
5
5
|
Переподключением управляет приложение. Пример использует публичные методы SDK; фасад SDK и `stream run` не повторяют подключения автоматически.
|
|
6
6
|
|
|
7
|
-
##
|
|
7
|
+
## Выполнить восстановление после разрыва
|
|
8
8
|
|
|
9
9
|
1. Открыть поток и получить успешное подтверждение подписки с `waitingClose: true`.
|
|
10
10
|
2. Через `GetCandles` прочитать историю от первой ещё не обработанной минуты до начала текущей минуты.
|
|
@@ -18,21 +18,22 @@
|
|
|
18
18
|
|
|
19
19
|
Исправления ранее опубликованной истории и задержки её появления требуют периодической сверки в приложении. Ограничения периодов `GetCandles` описаны в [официальной документации](https://developer.tbank.ru/invest/services/quotes/faq_marketdata/).
|
|
20
20
|
|
|
21
|
-
##
|
|
21
|
+
## Разделить пример на файлы
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
Ниже показаны четыре файла одного приложения. Разместите их в одном каталоге: `read-candle-history.ts` читает историю, `watch-candle-updates.ts` открывает одну подписку, `recover-closed-candles.ts` управляет восстановлением, а `main.ts` сохраняет данные и управляет временем жизни SDK.
|
|
24
|
+
|
|
25
|
+
Пример предполагает, что API возвращает корректные данные для запрошенных параметров.
|
|
26
|
+
|
|
27
|
+
## Догрузить историю
|
|
28
|
+
|
|
29
|
+
Функция принимает границы `from` и `until` в миллисекундах UTC и читает историю окнами не больше суток с `limit: 2400`, что покрывает минутные свечи одного окна. Она сортирует свечи, пропускает повторы и останавливается на первой незавершённой свече. Вместе со свечой выдаётся время её начала для продвижения checkpoint.
|
|
30
|
+
|
|
31
|
+
`read-candle-history.ts`
|
|
24
32
|
|
|
25
33
|
```ts
|
|
26
|
-
import { setTimeout as delay } from 'node:timers/promises';
|
|
27
34
|
import {
|
|
28
35
|
CandleInterval,
|
|
29
|
-
CandleSource,
|
|
30
36
|
GetCandlesRequest_CandleSource,
|
|
31
|
-
isSdkError,
|
|
32
|
-
SdkErrorCode,
|
|
33
|
-
SubscriptionAction,
|
|
34
|
-
SubscriptionInterval,
|
|
35
|
-
SubscriptionStatus,
|
|
36
37
|
type HistoricCandle,
|
|
37
38
|
type TInvestNodeSDK
|
|
38
39
|
} from '@woodger/t-invest-node-sdk';
|
|
@@ -40,125 +41,176 @@ import {
|
|
|
40
41
|
const minuteMs = 60_000;
|
|
41
42
|
const dayMs = 24 * 60 * minuteMs;
|
|
42
43
|
|
|
43
|
-
export async function*
|
|
44
|
-
sdk: Pick<TInvestNodeSDK, 'marketData'
|
|
44
|
+
export async function* readCandleHistory(
|
|
45
|
+
sdk: Pick<TInvestNodeSDK, 'marketData'>,
|
|
45
46
|
instrumentUid: string,
|
|
46
|
-
from:
|
|
47
|
+
from: number,
|
|
48
|
+
until: number,
|
|
47
49
|
signal: AbortSignal
|
|
48
|
-
): AsyncGenerator<HistoricCandle> {
|
|
49
|
-
let
|
|
50
|
-
let
|
|
51
|
-
|
|
50
|
+
): AsyncGenerator<{ candle: HistoricCandle; time: number }> {
|
|
51
|
+
let cursor = from;
|
|
52
|
+
let windowStart = from;
|
|
53
|
+
|
|
54
|
+
while (windowStart < until) {
|
|
55
|
+
signal.throwIfAborted();
|
|
56
|
+
|
|
57
|
+
const windowEnd = Math.min(windowStart + dayMs, until);
|
|
58
|
+
const { candles } = await sdk.marketData.getCandles({
|
|
59
|
+
instrumentId: instrumentUid,
|
|
60
|
+
from: new Date(windowStart),
|
|
61
|
+
to: new Date(windowEnd),
|
|
62
|
+
interval: CandleInterval.CANDLE_INTERVAL_1_MIN,
|
|
63
|
+
candleSourceType: GetCandlesRequest_CandleSource.CANDLE_SOURCE_EXCHANGE,
|
|
64
|
+
limit: 2400
|
|
65
|
+
}, { signal });
|
|
66
|
+
const ordered = candles.map((candle) => {
|
|
67
|
+
const time = candle.time?.getTime();
|
|
68
|
+
|
|
69
|
+
if (time === undefined) {
|
|
70
|
+
throw new Error('Missing candle time');
|
|
71
|
+
}
|
|
52
72
|
|
|
53
|
-
|
|
54
|
-
|
|
73
|
+
return { candle, time };
|
|
74
|
+
}).sort((a, b) => a.time - b.time);
|
|
75
|
+
|
|
76
|
+
for (const { candle, time } of ordered) {
|
|
77
|
+
signal.throwIfAborted();
|
|
78
|
+
|
|
79
|
+
if (time < cursor || time >= until) {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (!candle.isComplete) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
yield { candle, time };
|
|
88
|
+
|
|
89
|
+
cursor = time + minuteMs;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
windowStart = windowEnd;
|
|
55
93
|
}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Получать уведомления
|
|
98
|
+
|
|
99
|
+
Функция открывает одну подписку и выдаёт верхнюю границу для догрузки истории в миллисекундах UTC. После подтверждения подписки это начало текущей минуты, а при получении свечи — конец её интервала. Ошибка или завершение потока передаются координатору восстановления.
|
|
56
100
|
|
|
57
|
-
|
|
58
|
-
async function* readHistory(
|
|
59
|
-
until: number,
|
|
60
|
-
attemptSignal: AbortSignal
|
|
61
|
-
): AsyncGenerator<HistoricCandle> {
|
|
62
|
-
let windowStart = nextMinute;
|
|
101
|
+
`watch-candle-updates.ts`
|
|
63
102
|
|
|
64
|
-
|
|
65
|
-
|
|
103
|
+
```ts
|
|
104
|
+
import {
|
|
105
|
+
GetCandlesRequest_CandleSource,
|
|
106
|
+
SubscriptionAction,
|
|
107
|
+
SubscriptionInterval,
|
|
108
|
+
SubscriptionStatus,
|
|
109
|
+
type TInvestNodeSDK
|
|
110
|
+
} from '@woodger/t-invest-node-sdk';
|
|
66
111
|
|
|
67
|
-
|
|
68
|
-
|
|
112
|
+
const minuteMs = 60_000;
|
|
113
|
+
|
|
114
|
+
export async function* watchCandleUpdates(
|
|
115
|
+
sdk: Pick<TInvestNodeSDK, 'marketdataStream'>,
|
|
116
|
+
instrumentUid: string,
|
|
117
|
+
signal: AbortSignal
|
|
118
|
+
): AsyncGenerator<number> {
|
|
119
|
+
let subscribed = false;
|
|
120
|
+
const responses = sdk.marketdataStream.marketDataServerSideStream({
|
|
121
|
+
subscribeCandlesRequest: {
|
|
122
|
+
subscriptionAction: SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
|
|
123
|
+
instruments: [{
|
|
69
124
|
instrumentId: instrumentUid,
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const ordered = candles.map((candle) => {
|
|
77
|
-
const time = candle.time?.getTime();
|
|
78
|
-
|
|
79
|
-
if (time === undefined || !Number.isFinite(time)
|
|
80
|
-
|| time % minuteMs !== 0 || time < windowStart || time > windowEnd
|
|
81
|
-
|| candle.candleSource !== CandleSource.CANDLE_SOURCE_EXCHANGE) {
|
|
82
|
-
throw new Error('Unexpected historical candle');
|
|
83
|
-
}
|
|
125
|
+
interval: SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
|
|
126
|
+
}],
|
|
127
|
+
waitingClose: true,
|
|
128
|
+
candleSourceType: GetCandlesRequest_CandleSource.CANDLE_SOURCE_EXCHANGE
|
|
129
|
+
}
|
|
130
|
+
}, { signal });
|
|
84
131
|
|
|
85
|
-
|
|
86
|
-
|
|
132
|
+
for await (const response of responses) {
|
|
133
|
+
signal.throwIfAborted();
|
|
87
134
|
|
|
88
|
-
|
|
89
|
-
|
|
135
|
+
if (!subscribed && response.subscribeCandlesResponse) {
|
|
136
|
+
const subscription = response.subscribeCandlesResponse.candlesSubscriptions.find(
|
|
137
|
+
(item) => item.instrumentUid === instrumentUid
|
|
138
|
+
&& item.interval === SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
|
|
139
|
+
);
|
|
90
140
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
141
|
+
if (subscription?.subscriptionStatus !== SubscriptionStatus.SUBSCRIPTION_STATUS_SUCCESS
|
|
142
|
+
|| !subscription.waitingClose) {
|
|
143
|
+
throw new Error('Closed-candle subscription was rejected');
|
|
144
|
+
}
|
|
94
145
|
|
|
95
|
-
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
146
|
+
subscribed = true;
|
|
98
147
|
|
|
99
|
-
|
|
148
|
+
yield Math.floor(Date.now() / minuteMs) * minuteMs;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (response.candle) {
|
|
152
|
+
if (!subscribed) {
|
|
153
|
+
throw new Error('Candle received before subscription confirmation');
|
|
154
|
+
}
|
|
100
155
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
156
|
+
const time = response.candle.time?.getTime();
|
|
157
|
+
|
|
158
|
+
if (time === undefined) {
|
|
159
|
+
throw new Error('Missing candle time');
|
|
105
160
|
}
|
|
106
161
|
|
|
107
|
-
|
|
162
|
+
yield time + minuteMs;
|
|
108
163
|
}
|
|
109
164
|
}
|
|
165
|
+
}
|
|
166
|
+
```
|
|
110
167
|
|
|
111
|
-
|
|
112
|
-
const attempt = new AbortController();
|
|
113
|
-
const attemptSignal = AbortSignal.any([signal, attempt.signal]);
|
|
114
|
-
|
|
115
|
-
try {
|
|
116
|
-
let subscribed = false;
|
|
117
|
-
const responses = sdk.marketdataStream.marketDataServerSideStream({
|
|
118
|
-
subscribeCandlesRequest: {
|
|
119
|
-
subscriptionAction: SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
|
|
120
|
-
instruments: [{
|
|
121
|
-
instrumentId: instrumentUid,
|
|
122
|
-
interval: SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
|
|
123
|
-
}],
|
|
124
|
-
waitingClose: true,
|
|
125
|
-
candleSourceType: GetCandlesRequest_CandleSource.CANDLE_SOURCE_EXCHANGE
|
|
126
|
-
}
|
|
127
|
-
}, { signal: attemptSignal });
|
|
168
|
+
## Восстановить чтение
|
|
128
169
|
|
|
129
|
-
|
|
130
|
-
attemptSignal.throwIfAborted();
|
|
170
|
+
`from` задаёт начало первой ещё не обработанной минуты по UTC. Координатор догружает историю до полученной границы и выдаёт свечи потребителю. Он хранит `nextMinute` между подключениями и сбрасывает счётчик неудач после обработки свечи. Прогресс продвигается после возобновления из `yield`, чтобы потребитель успел сохранить свечу.
|
|
131
171
|
|
|
132
|
-
|
|
133
|
-
const subscription = response.subscribeCandlesResponse.candlesSubscriptions.find(
|
|
134
|
-
(item) => item.instrumentUid === instrumentUid
|
|
135
|
-
&& item.interval === SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE
|
|
136
|
-
);
|
|
172
|
+
`recover-closed-candles.ts`
|
|
137
173
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
174
|
+
```ts
|
|
175
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
176
|
+
import {
|
|
177
|
+
isSdkError,
|
|
178
|
+
SdkErrorCode,
|
|
179
|
+
type HistoricCandle,
|
|
180
|
+
type TInvestNodeSDK
|
|
181
|
+
} from '@woodger/t-invest-node-sdk';
|
|
182
|
+
import { readCandleHistory } from './read-candle-history.js';
|
|
183
|
+
import { watchCandleUpdates } from './watch-candle-updates.js';
|
|
142
184
|
|
|
143
|
-
|
|
185
|
+
const minuteMs = 60_000;
|
|
144
186
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
187
|
+
export async function* recoverClosedCandles(
|
|
188
|
+
sdk: Pick<TInvestNodeSDK, 'marketData' | 'marketdataStream'>,
|
|
189
|
+
instrumentUid: string,
|
|
190
|
+
from: Date,
|
|
191
|
+
signal: AbortSignal
|
|
192
|
+
): AsyncGenerator<HistoricCandle> {
|
|
193
|
+
let nextMinute = from.getTime();
|
|
194
|
+
let failures = 0;
|
|
195
|
+
const maxRetries = 5;
|
|
148
196
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
197
|
+
if (!Number.isFinite(nextMinute) || nextMinute % minuteMs !== 0) {
|
|
198
|
+
throw new Error('from must identify a UTC minute boundary');
|
|
199
|
+
}
|
|
152
200
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|| candle.candleSourceType !== CandleSource.CANDLE_SOURCE_EXCHANGE) {
|
|
157
|
-
throw new Error('Unexpected stream candle');
|
|
158
|
-
}
|
|
201
|
+
while (!signal.aborted) {
|
|
202
|
+
const attempt = new AbortController();
|
|
203
|
+
const attemptSignal = AbortSignal.any([signal, attempt.signal]);
|
|
159
204
|
|
|
160
|
-
|
|
161
|
-
|
|
205
|
+
try {
|
|
206
|
+
for await (const until of watchCandleUpdates(sdk, instrumentUid, attemptSignal)) {
|
|
207
|
+
for await (const { candle, time } of readCandleHistory(
|
|
208
|
+
sdk, instrumentUid, nextMinute, until, attemptSignal
|
|
209
|
+
)) {
|
|
210
|
+
yield candle;
|
|
211
|
+
|
|
212
|
+
nextMinute = time + minuteMs;
|
|
213
|
+
failures = 0;
|
|
162
214
|
}
|
|
163
215
|
}
|
|
164
216
|
}
|
|
@@ -210,10 +262,12 @@ export async function* recoverClosedCandles(
|
|
|
210
262
|
|
|
211
263
|
Вызов `GetCandles` на уведомление выбран намеренно: закрытая свеча в потоке может появиться раньше соответствующей записи в истории. Если история ещё не содержит завершённую свечу, checkpoint для неё не продвигается; следующее уведомление или переподключение повторит чтение. Если новых уведомлений долго нет, периодическую догрузку и проверку `ping` должно организовать приложение.
|
|
212
264
|
|
|
213
|
-
##
|
|
265
|
+
## Сохранить свечу и завершить работу
|
|
214
266
|
|
|
215
267
|
Демонстрация хранит данные и checkpoint в памяти. В приложении замените обновление `Map` и checkpoint одной транзакцией своего хранилища и загружайте checkpoint перед стартом. Ключ записи должен включать инструмент, интервал, источник и время свечи; повторная запись по тому же ключу должна быть безопасной.
|
|
216
268
|
|
|
269
|
+
`main.ts`
|
|
270
|
+
|
|
217
271
|
```ts
|
|
218
272
|
import {
|
|
219
273
|
createInMemoryUnaryLimiter,
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Прочитать операции по страницам
|
|
2
|
+
|
|
3
|
+
`getOperationsByCursor` возвращает историю счёта по страницам. Начните с пустого курсора и передавайте `nextCursor` следующему запросу, пока `hasNext` равен `true`. Подставьте токен, [ID счёта](./getting-started.md) и нужный период.
|
|
4
|
+
|
|
5
|
+
`operations-pagination.ts`
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { TInvestNodeSDK } from '@woodger/t-invest-node-sdk';
|
|
9
|
+
|
|
10
|
+
const sdk = new TInvestNodeSDK({
|
|
11
|
+
token: 'YOUR_TOKEN',
|
|
12
|
+
endpoint: 'invest-public-api.tbank.ru:443'
|
|
13
|
+
});
|
|
14
|
+
const request = {
|
|
15
|
+
accountId: 'YOUR_ACCOUNT_ID',
|
|
16
|
+
from: new Date('2026-01-01T00:00:00Z'),
|
|
17
|
+
to: new Date('2026-02-01T00:00:00Z'),
|
|
18
|
+
limit: 100
|
|
19
|
+
};
|
|
20
|
+
let cursor = '';
|
|
21
|
+
|
|
22
|
+
try {
|
|
23
|
+
while (true) {
|
|
24
|
+
const page = await sdk.operations.getOperationsByCursor({
|
|
25
|
+
...request,
|
|
26
|
+
cursor
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
for (const operation of page.items) {
|
|
30
|
+
console.log(operation);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (!page.hasNext) {
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
cursor = page.nextCursor;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
sdk.close();
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
При переходе между страницами меняйте только курсор: счёт, период и фильтры должны оставаться прежними. Пустой массив `items` не означает конец истории — проверяйте `hasNext`. Размер страницы здесь равен `100`; особенности метода описаны в [документации провайдера](https://developer.tbank.ru/invest/services/operations/operations_problems), фильтры — в [контракте операций](../../contracts/operations.proto). В песочнице используйте `sdk.sandbox.getSandboxOperationsByCursor`.
|
|
46
|
+
|
|
47
|
+
Для большого числа страниц подключите [ограничитель частоты запросов](./unary-limits.md). Как задать срок ожидания или отмену вызова, показано в [руководстве по unary-запросам](./unary-calls.md).
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Следить за состоянием заявки
|
|
2
|
+
|
|
3
|
+
`orderStateStream` передаёт изменения всех заявок выбранного счёта. Чтобы следить за одной заявкой, отбирайте события по `orderRequestId` — UUID, переданному в поле `orderId` при её выставлении. Первый `orderState.orderId` ещё может быть внутренним номером заявки.
|
|
4
|
+
|
|
5
|
+
Фрагмент использует готовый `sdk`, подключённый к песочнице, и `signal` для остановки чтения. Их создание, обработка отмены и закрытие SDK показаны в [общем примере потоков](./streams-and-cancellation.md#открыть-серверный-поток). Подставьте ID существующего счёта песочницы и сохранённый ключ заявки.
|
|
6
|
+
|
|
7
|
+
`order-state-stream.ts`
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { ResultSubscriptionStatus } from '@woodger/t-invest-node-sdk';
|
|
11
|
+
|
|
12
|
+
const accountId = 'YOUR_SANDBOX_ACCOUNT_ID';
|
|
13
|
+
const orderRequestId = 'YOUR_ORDER_REQUEST_ID';
|
|
14
|
+
const responses = sdk.ordersStream.orderStateStream({
|
|
15
|
+
accounts: [accountId]
|
|
16
|
+
}, { signal });
|
|
17
|
+
|
|
18
|
+
for await (const response of responses) {
|
|
19
|
+
if (response.subscription) {
|
|
20
|
+
if (response.subscription.status !== ResultSubscriptionStatus.RESULT_SUBSCRIPTION_STATUS_OK) {
|
|
21
|
+
throw new Error('Order-state subscription was rejected');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
console.log('Подписка на состояния заявок подтверждена');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const state = response.orderState;
|
|
28
|
+
|
|
29
|
+
if (state?.orderRequestId === orderRequestId) {
|
|
30
|
+
console.log(state);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Для новой заявки откройте поток и дождитесь подтверждения подписки до её выставления. Подготовка счёта и заявки разобрана в [цикле песочницы](./sandbox-orders.md); чтобы продолжить работу со счётом, закройте его в конце своего сценария.
|
|
36
|
+
|
|
37
|
+
Текущее состояние существующей заявки и состояние после разрыва соединения сверяйте через `getOrderState` или `getSandboxOrderState`: поток не восстанавливает пропущенные события.
|
|
38
|
+
|
|
39
|
+
После частичного исполнения отменённая заявка может остаться в потоковом статусе `PARTIALLYFILL`. Поэтому чтение продолжается до отмены `signal` или завершения потока. Особенности идентификаторов и статусов описаны в [документации провайдера](https://developer.tbank.ru/invest/services/orders/orders_state_stream).
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Выполнить цикл заявки в песочнице
|
|
2
|
+
|
|
3
|
+
Пример создаёт и пополняет тестовый счёт, выставляет лимитную заявку, проверяет её состояние и отменяет активный остаток. В `finally` закрывается только созданный им счёт.
|
|
4
|
+
|
|
5
|
+
Замените `YOUR_TOKEN` токеном для [песочницы](https://developer.tbank.ru/invest/intro/developer/sandbox), а `YOUR_INSTRUMENT_UID` — UID рублёвой акции из [примера поиска инструмента](./instrument-lookup.md).
|
|
6
|
+
|
|
7
|
+
В коде цена `100.25` рубля записана как `{ units: 100, nano: 250_000_000 }`. Укажите цену, кратную шагу цены инструмента. Поле `quantity` содержит количество лотов; один лот включает `instrument.lot` бумаг. Пополнение счёта в примере задано в рублях.
|
|
8
|
+
|
|
9
|
+
`sandbox-orders.ts`
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { randomUUID } from 'node:crypto';
|
|
13
|
+
import {
|
|
14
|
+
OrderDirection,
|
|
15
|
+
OrderExecutionReportStatus,
|
|
16
|
+
OrderIdType,
|
|
17
|
+
OrderType,
|
|
18
|
+
PriceType,
|
|
19
|
+
TInvestNodeSDK
|
|
20
|
+
} from '@woodger/t-invest-node-sdk';
|
|
21
|
+
|
|
22
|
+
const sdk = new TInvestNodeSDK({
|
|
23
|
+
token: 'YOUR_TOKEN',
|
|
24
|
+
endpoint: 'sandbox-invest-public-api.tbank.ru:443'
|
|
25
|
+
});
|
|
26
|
+
const instrumentUid = 'YOUR_INSTRUMENT_UID';
|
|
27
|
+
const quantity = 1;
|
|
28
|
+
const price = { units: 100, nano: 250_000_000 };
|
|
29
|
+
const initialBalance = { currency: 'rub', units: 100_000, nano: 0 };
|
|
30
|
+
const orderRequestId = randomUUID();
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
const { accountId } = await sdk.sandbox.openSandboxAccount({
|
|
34
|
+
name: 'SDK example'
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
await sdk.sandbox.sandboxPayIn({ accountId, amount: initialBalance });
|
|
39
|
+
|
|
40
|
+
console.log({ accountId, orderRequestId });
|
|
41
|
+
|
|
42
|
+
const placed = await sdk.sandbox.postSandboxOrder({
|
|
43
|
+
accountId,
|
|
44
|
+
instrumentId: instrumentUid,
|
|
45
|
+
quantity,
|
|
46
|
+
price,
|
|
47
|
+
direction: OrderDirection.ORDER_DIRECTION_BUY,
|
|
48
|
+
orderType: OrderType.ORDER_TYPE_LIMIT,
|
|
49
|
+
priceType: PriceType.PRICE_TYPE_CURRENCY,
|
|
50
|
+
orderId: orderRequestId
|
|
51
|
+
});
|
|
52
|
+
const order = {
|
|
53
|
+
accountId,
|
|
54
|
+
orderId: placed.orderId,
|
|
55
|
+
orderIdType: OrderIdType.ORDER_ID_TYPE_EXCHANGE,
|
|
56
|
+
priceType: PriceType.PRICE_TYPE_CURRENCY
|
|
57
|
+
};
|
|
58
|
+
let state = await sdk.sandbox.getSandboxOrderState(order);
|
|
59
|
+
|
|
60
|
+
if (
|
|
61
|
+
state.executionReportStatus === OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_NEW
|
|
62
|
+
|| state.executionReportStatus
|
|
63
|
+
=== OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_PARTIALLYFILL
|
|
64
|
+
) {
|
|
65
|
+
await sdk.sandbox.cancelSandboxOrder({
|
|
66
|
+
accountId,
|
|
67
|
+
orderId: placed.orderId,
|
|
68
|
+
orderIdType: OrderIdType.ORDER_ID_TYPE_EXCHANGE
|
|
69
|
+
});
|
|
70
|
+
state = await sdk.sandbox.getSandboxOrderState(order);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
console.log(state);
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
await sdk.sandbox.closeSandboxAccount({ accountId });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
sdk.close();
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Клиентский `orderRequestId` передаётся при выставлении заявки как `orderId`; при повторе того же поручения сохраняйте этот ключ. Идентификатор из ответа `placed.orderId` используется для проверки состояния и отмены. SDK не повторяет запросы автоматически.
|
|
85
|
+
|
|
86
|
+
Отменяется только новая или частично исполненная заявка. Между проверкой и отменой она может исполниться, и провайдер отклонит отмену. Ошибка передаётся вызывающему коду, `finally` выполняется; после такой ошибки уточните состояние заявки. Параметры и статусы определены в [контракте заявок](../../contracts/orders.proto).
|
|
87
|
+
|
|
88
|
+
Для дальнейших экспериментов со счётом перенесите его закрытие в конец своего сценария. Изменения состояния заявки можно получать [через поток](./order-state-stream.md).
|