Client Classes
Auth, Data, Trading, Stream — khởi tạo và sử dụng
SDK cung cấp 4 client chuyên biệt. Tất cả method API đều là async và trả về Promise.
Auth
Client gốc — quản lý REST client, xác thực, và token. Tất cả client khác nhận Auth làm tham số.
import { Auth, Config } from '@ssi.developer/ssi-sdk';
const config = new Config({
clientId: 'YOUR_CLIENT_ID',
apiKey: 'YOUR_API_KEY',
apiSecret: 'YOUR_API_SECRET',
privateKey: 'YOUR_PRIVATE_KEY',
});
const auth = new Auth(config);
const token = await auth.authenticate('YOUR_OTP');
console.log(`Token hết hạn lúc (epoch giây): ${token.expiresAt}`);Các method xác thực
// Yêu cầu gửi OTP (kiểu rõ ràng: OTPResponse { message, transactionId? })
await auth.requestOtpTyped();
// Xác thực với OTP
const token = await auth.authenticate('YOUR_OTP');
// Xác thực không cần OTP (chỉ dữ liệu thị trường)
const token = await auth.authenticate();
// Làm mới token
const token = await auth.refresh();
// Đảm bảo xác thực (tự refresh nếu hết hạn)
await auth.ensureAuthenticated('YOUR_OTP');ensureAuthenticated ném ReauthenticationRequired khi không refresh được phiên và không có OTP (xem Xử lý lỗi). Chi tiết từng method xem API Services.
Approve OTP (Smart OTP push-approval)
Tài khoản đã kích hoạt Smart OTP có thể duyệt trực tiếp trên app thay vì nhập mã. Gọi requestOtpTyped() để gửi yêu cầu, lấy transactionId, rồi truyền vào ensureAuthenticated() — SDK tự poll cho đến khi user bấm duyệt.
// Bước 1: gửi yêu cầu duyệt, nhận transactionId (chỉ có với Smart OTP)
const otp = await auth.requestOtpTyped();
// Bước 2: SDK tự poll cho đến khi user bấm duyệt trên app Smart OTP
// (otp truyền undefined vì đang dùng transactionId)
const token = await auth.ensureAuthenticated(undefined, otp.transactionId);Trong lúc chờ, server trả HTTP 202 + code 401114 ("Push-approval is pending") — SDK tự xử lý. Nếu hết số lần poll mà vẫn chưa duyệt, ensureAuthenticated reject với lỗi xác thực (SmartOTPPendingError hoặc SmartOTPRejectedError, xem Xử lý lỗi). Bạn cũng có thể đọc mã trực tiếp trên app Smart OTP rồi truyền vào authenticate('YOUR_OTP').
Trạng thái token
auth.getToken(); // lấy token hiện tại
auth.setToken(t); // thiết lập token (cache)
auth.isTokenExpired; // boolean
auth.hasRefreshToken; // boolean
auth.canRefresh; // refresh token còn dùng được?Data
Client dữ liệu thị trường. Không cần OTP — chỉ cần auth.authenticate().
import { Auth, Data, Config } from '@ssi.developer/ssi-sdk';
const auth = new Auth(config);
await auth.authenticate();
const data = new Data(auth);
const ohlc = await data.marketData.getOhlc1Minute('SSI');
const indexes = await data.marketData.getIndexes();
const info = await data.marketData.getSecuritiesInfo('SSI');Service: data.marketData (MarketDataService) — OHLC, chỉ số, chứng khoán.
Trading
Client giao dịch, tài khoản, và danh mục. Cần OTP.
import { Auth, Trading, Config, OrderSide } from '@ssi.developer/ssi-sdk';
const auth = new Auth(config);
await auth.authenticate('YOUR_OTP');
const trading = new Trading(auth);
// Tài khoản
const accounts = await trading.account.getAccountInfo();
// Danh mục
const balance = await trading.portfolio.getEquityBalance('YOUR_ACCOUNT_NO');
const positions = await trading.portfolio.getEquityPositions('YOUR_ACCOUNT_NO');
const orders = await trading.portfolio.getTodayOrders('YOUR_ACCOUNT_NO');
// Giao dịch
const result = await trading.trading.placeLimitOrder(
'YOUR_ACCOUNT_NO', 'SSI', OrderSide.BUY, 100, 66000,
);Services:
trading.account(AccountService) — thông tin tài khoản.trading.portfolio(PortfolioService) — số dư, vị thế, sổ lệnh, PPMMR.trading.trading(TradingService) — đặt/sửa/huỷ lệnh, đặt/huỷ lô lệnh (Batch), sức mua/bán, lệnh điều kiện (FCO).
Đặt/huỷ nhiều lệnh trong một request đã ký: xem Batch Orders. Batch cần Config.privateKey, giới hạn số lệnh mỗi lô là Config.maxBatchOrders (xem Cấu hình).
Trading WebSocket
Trading WebSocket được export từ package chính @ssi.developer/ssi-sdk. Hàm khởi tạo asyncTradingWs(auth, options?) (alias tradingWs) không phải method của Auth/Data/Trading/Stream: Trading và Stream không bao giờ tự kết nối tới nó, bạn phải gọi hàm này một cách tường minh. Hàm nhận một Auth đã xác thực OTP và trả về TradingWSService. Chi tiết, ví dụ và các lưu ý ở API Services, mục 7.
import { Auth, asyncTradingWs } from '@ssi.developer/ssi-sdk';
const ws = await asyncTradingWs(auth);
// ... dùng ws ...
await ws.close();Stream
Client streaming realtime qua WebSocket. Cần OTP.
import { Auth, Stream, Config } from '@ssi.developer/ssi-sdk';
const auth = new Auth(config);
await auth.authenticate('YOUR_OTP');
const stream = new Stream(auth);
// Đăng ký callback
stream.streaming.onData = (msg) => {
console.log('[DATA]', msg);
};
stream.streaming.onTrading = (msg) => {
console.log('[TRADING]', msg);
};
stream.streaming.onHeartbeat = (msg) => {
console.log('[HEARTBEAT]', msg);
};
// Kết nối và subscribe
await stream.streaming.connect();
await stream.streaming.subscribeSymbol(['SSI', 'HPG']);
await stream.streaming.subscribeOrderStatus();
await stream.streaming.wait();Service: stream.streaming (StreamingService) — subscribe/unsubscribe dữ liệu realtime. Mọi method subscribe/unsubscribe trả về Promise<void>, luôn dùng await.
Callbacks:
| Property | Kiểu | Mô tả |
|---|---|---|
onData | (msg: DataMessage) => void | Nhận dữ liệu thị trường |
onTrading | (msg: TradingMessage) => void | Nhận sự kiện giao dịch (trạng thái lệnh thường, lệnh điều kiện FCO, danh mục) |
onHeartbeat | (msg: HeartbeatMessage) => void | Nhận heartbeat |
onMarketFlag | (msg: MarketFlagMessage) => void | Cờ phiên thị trường (cần subscribeMarketFlag()) |
onIndexSummary | (msg: IndexSummaryMessage) => void | Tổng hợp chỉ số (subscribeIndexSummary) |
onOrder, onOrderMatch, onPortfolio | callback có kiểu | Sự kiện lệnh, khớp lệnh, danh mục |
onConnection | (event: ConnectionEvent) => void | Trạng thái kết nối: connected, reconnected, disconnected, failed |
Đặt callback không tự subscribe gì cả. Với Config.autoReconnect bật (mặc định), SDK tự reconnect và subscribe lại, xem API Services, mục 6.8. Dữ liệu của chính chỉ số (tick, nến 1m/5m, tổng hợp) nằm ở mục 6.7.
Cập nhật token:
// Cập nhật token cho stream sau khi refresh (truyền access token mới)
stream.updateToken(auth.accessToken);Ví dụ đầy đủ
import { Auth, Data, Trading, Stream, Config, OrderSide } from '@ssi.developer/ssi-sdk';
const config = new Config({
clientId: 'YOUR_CLIENT_ID',
apiKey: 'YOUR_API_KEY',
apiSecret: 'YOUR_API_SECRET',
privateKey: 'YOUR_PRIVATE_KEY',
});
const auth = new Auth(config);
await auth.authenticate('YOUR_OTP');
// Dữ liệu thị trường
const data = new Data(auth);
const ohlc = await data.marketData.getOhlc1Minute('SSI');
console.log(ohlc);
// Giao dịch
const trading = new Trading(auth);
const accounts = await trading.account.getAccountInfo();
console.log(accounts);
// Streaming
const stream = new Stream(auth);
stream.streaming.onData = (msg) => {
console.log('[DATA]', msg);
};
stream.streaming.onTrading = (msg) => {
console.log('[TRADING]', msg);
};
await stream.streaming.connect();
await stream.streaming.subscribeSymbol(['SSI', 'HPG']);
await stream.streaming.subscribeOrderStatus();
await stream.streaming.wait();
await stream.disconnect();Ghi chú
- Tất cả method API đều là
async— dùngawaithoặc.then(). - Tất cả client dùng chung HTTP connection qua
Auth. - Gọi
await stream.disconnect()để dọn dẹp tài nguyên WebSocket. - Lỗi thường gặp:
AuthenticationError(xác thực, gồmSmartOTPPendingError,SmartOTPRejectedError,ReauthenticationRequired),WebSocketError(stream và Trading WebSocket),APIError(lỗi HTTP),RateLimitError,ValidationError,ConfigurationError.AuthenticationErrorkhông kế thừaAPIError, xem Xử lý lỗi.