npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@max89701/ctrader-layer

v1.4.6

Published

A Node.js communication layer for the cTrader Open API.

Readme

cTrader Layer

Node.js слой для работы с cTrader Open API. Реализация создана и поддерживается Reiryoku Technologies и контрибьюторами.

Установка

npm install @max89701/ctrader-layer

Использование

Подробная документация по cTrader Open API: Open API Documentation.

Подключение к серверу

const { CTraderConnection } = require("@max89701/ctrader-layer");

const connection = new CTraderConnection({
    host: "demo.ctraderapi.com",
    port: 5035,
});

await connection.open();

Отправка команд

Метод sendCommand отправляет команду и возвращает Promise, который разрешается при получении ответа от сервера. При ошибке (наличие errorCode в ответе) Promise отклоняется.

const response = await connection.sendCommand("ProtoOAVersionReq", {});
console.log(response.version);

Обработка ошибок

try {
    await connection.sendCommand("ProtoOANewOrderReq", { /* ... */ });
} catch (error) {
    // error содержит payload с errorCode и description
    console.error("Ошибка:", error.errorCode, error.description);
}

// Без выброса исключения:
const result = await connection.trySendCommand("ProtoOANewOrderReq", {});
if (result === undefined) {
    console.log("Команда не выполнена");
}

Аутентификация приложения

await connection.sendCommand("ProtoOAApplicationAuthReq", {
    clientId: "your-client-id",
    clientSecret: "your-client-secret",
});

Аутентификация аккаунта

await connection.sendCommand("ProtoOAAccountAuthReq", {
    ctidTraderAccountId: 12345678,
    accessToken: "your-access-token",
});

Поддержание соединения (heartbeat)

Отправляйте heartbeat каждые 25 секунд:

setInterval(() => connection.sendHeartbeat(), 25000);

Переподключение и переподписки

При разрыве соединения можно включить автоматическое переподключение с повторной аутентификацией и подписками:

const { CTraderConnection } = require("@max89701/ctrader-layer");

const connection = new CTraderConnection({
    host: "demo.ctraderapi.com",
    port: 5035,
    autoReconnect: true,
    maxReconnectAttempts: 5,
    reconnectDelayMs: 1000,
});

// Обработчик для повторной аутентификации и подписок после переподключения
connection.addReconnectHandler(async (conn) => {
    await conn.sendCommand("ProtoOAApplicationAuthReq", {
        clientId: "your-client-id",
        clientSecret: "your-client-secret",
    });
    await conn.sendCommand("ProtoOAAccountAuthReq", {
        ctidTraderAccountId: 12345678,
        accessToken: "your-access-token",
    });
    await conn.sendCommand("ProtoOASubscribeSpotsReq", {
        ctidTraderAccountId: 12345678,
        symbolId: [1, 2, 3],
    });
});

connection.on("reconnected", () => {
    console.log("Переподключение выполнено");
});

connection.on("reconnectFailed", (err) => {
    console.error("Не удалось переподключиться:", err);
});

Закрытие соединения

connection.close();

Подписка на события

События можно подписывать по имени сообщения или по числовому payloadType. Тип payload выводится автоматически по имени события из маппинга CTraderEventMap:

import { CTraderConnection } from "@max89701/ctrader-layer";

// Тип payload выводится автоматически — ProtoOASpotEventPayload
connection.on("ProtoOASpotEvent", (payload) => {
    // payload.ctidTraderAccountId, payload.symbolId, payload.bid, payload.ask — типизированы
    console.log("Спот:", payload.bid, payload.ask);
});

connection.on("ProtoOAExecutionEvent", (payload) => {
    // payload.executionType, payload.errorCode и т.д.
    console.log("Исполнение:", payload.executionType);
});

// По числовому payload type — payload: CTraderPayload
connection.on("2131", (payload) => {
    console.log("Спот:", payload);
});

Для расширения маппинга используйте module augmentation:

declare module "@max89701/ctrader-layer" {
    interface CTraderEventMap {
        MyCustomEvent: { customField: string };
    }
}

Получение профиля и аккаунтов по access token (HTTP API)

const profile = await CTraderConnection.getAccessTokenProfile("access-token");
const accounts = await CTraderConnection.getAccessTokenAccounts("access-token");

События соединения

| Событие | Описание | |---------|----------| | open | Соединение установлено | | close | Соединение закрыто | | error | Ошибка (передаётся объект Error) | | reconnecting | Начата попытка переподключения | | reconnected | Переподключение успешно | | reconnectFailed | Исчерпаны попытки переподключения |

Требования

  • Node.js 12+

Contribution

Создайте PR или откройте issue для сообщений об ошибках и предложений.