Official JavaScript SDK for Exchange Adapter - Binance-compatible API wrapper with blockchain integration
npm install yamata-adapter-sdk


The Yamata Adapter SDK is a JavaScript library that provides an interface to the Yamata trading platform. It acts as a bridge between your applications and Yamata's blockchain-powered trading infrastructure, offering:
- Familiar Binance API patterns for easy migration
- Blockchain integration for secure trading operations
- Real-time market data and WebSocket streaming
- Account management and API key handling
- API key management and permissions
- Trading Bots: Build automated trading strategies
- Portfolio Management: Monitor and manage trading positions
- Market Analysis: Access real-time market data and analytics
- Exchange Integration: Connect existing applications to Yamata
- DeFi Applications: Integrate with blockchain-based trading
- HMAC-SHA256 signature authentication
- API key management with granular permissions
- Secure secret key handling
- Timestamp validation and replay attack prevention
- Real-time ticker information
- Order book depth data
- Historical candlestick data (klines)
- Recent trades and market activity
- Exchange information and symbol details
- Account information and balances
- Trade history and order tracking
- Account status monitoring
- API key listing and statistics
- Permission management
- Key status monitoring
- WebSocket support for live data
- Event-driven architecture
- Automatic reconnection handling
- Low-latency market updates
- Secure private key storage and management
- Ethereum provider and wallet initialization
- Dynamic private key setting and clearing
- Private key status checking
- Enhanced security for blockchain operations
- Wallet address access
- Node.js 18+
- npm or yarn package manager
``bash
npm install yamata-adapter-sdk
Integration Checklist
Before you start, ensure you have:
- [ ] API Keys: Valid Yamata API key (starts with
ymta_)
- [ ] Secret Key: Corresponding secret key for signature generation
- [ ] Private Key: Private key for blockchain operations (required)
- [ ] RPC URL: Ethereum RPC URL for blockchain operations (required)
- [ ] Base URL: Yamata adapter service URL (default: http://localhost:3080)
- [ ] User ID: Valid user ID for API key creation (if needed)
- [ ] Network Access: Connection to Yamata adapter serviceSDK Initialization
$3
`javascript
import { YamataAdapterSDK } from "yamata-adapter-sdk";// Initialize with configuration
const sdk = new YamataAdapterSDK({
apiKey: "ymta_your_api_key_here",
secretKey: "your_secret_key_here",
privateKey: "your_private_key_here",
// Required for blockchain operations
privateKey: process.env.YAMATA_PRIVATE_KEY,
rpcUrl: process.env.YAMATA_RPC_URL,
debug: process.env.NODE_ENV === "development",
timeout: 30000,
recvWindow: 5000,
retries: 3,
retryDelay: 1000,
});
`Liquidity Provider (LP) Tutorial
$3
This guide shows you how to become a liquidity provider on Yamata. As a LP, you'll place orders that provide liquidity to the market.
$3
#### 1. Setup
Install the SDK and configure your environment:
`bash
npm install yamata-adapter-sdk
`Create a
.env file with your credentials:`env
Maker credentials
YAMATA_USER_API_KEY=your_maker_api_key
YAMATA_USER_API_SECRET=your_maker_secret
YAMATA_USER_PRIVATE_KEY=your_maker_private_keyTaker credentials (if using separate account)
YAMATA_TAKER_USER_API_KEY=your_taker_api_key
YAMATA_TAKER_USER_API_SECRET=your_taker_secret
YAMATA_TAKER_USER_PRIVATE_KEY=your_taker_private_keyYamata configuration
YAMATA_RPC_URL=your_rpc_url
YAMATA_BASE_URL=http://localhost:3000
`#### 2. Initialize the SDK
`javascript
import YamataAdapterSDK from "yamata-adapter-sdk";const lpSDK = new YamataAdapterSDK({
apiKey: process.env.YAMATA_USER_API_KEY,
secretKey: process.env.YAMATA_USER_API_SECRET,
privateKey: process.env.YAMATA_USER_PRIVATE_KEY,
rpcUrl: process.env.YAMATA_RPC_URL,
baseUrl: process.env.YAMATA_BASE_URL,
chain: "somnia", // one of "somnia" | "monad"
debug: true, // See request details
});
`#### 3. Place LP Orders
Use the
createOrderLP() method to place orders:`javascript
// Get current market price
const symbol = "BTCUSDT"; // No underscore for API calls
const priceData = await lpSDK.getTickerPrice(symbol);
const marketPrice = parseFloat(priceData.price);// Place a maker buy order (below market price)
const buyOrder = await lpSDK.createOrderLP({
symbol: "BTC_USDT", // Underscore for trading pair
side: "buy",
price: marketPrice * 0.995, // 0.5% below market
amount: 0.01, // BTC amount
});
console.log("Buy order placed:", buyOrder.id);
// Place a maker sell order (above market price)
const sellOrder = await lpSDK.createOrderLP({
symbol: "BTC_USDT",
side: "sell",
price: marketPrice * 1.005, // 0.5% above market
amount: 0.01,
});
console.log("Sell order placed:", sellOrder.id);
`$3
Here's a basic market making loop:
`javascript
async function runMarketMaker() {
const SPREAD = 0.005; // 0.5% spread
const ORDER_SIZE = 0.01; // BTC
const INTERVAL = 5000; // 5 seconds setInterval(async () => {
try {
// Fetch current price
const priceData = await lpSDK.getTickerPrice("BTCUSDT");
const mid = parseFloat(priceData.price);
// Place orders on both sides
await lpSDK.createOrderLP({
symbol: "BTC_USDT",
side: "buy",
price: mid * (1 - SPREAD),
amount: ORDER_SIZE,
});
await lpSDK.createOrderLP({
symbol: "BTC_USDT",
side: "sell",
price: mid * (1 + SPREAD),
amount: ORDER_SIZE,
});
console.log(
✅ Orders placed at ${mid});
} catch (error) {
console.error("Error:", error.message);
}
}, INTERVAL);
}runMarketMaker();
`$3
For more sophisticated strategies, use separate maker and taker accounts:
`javascript
// Maker: Places resting orders
const maker = new YamataAdapterSDK({
apiKey: process.env.YAMATA_USER_API_KEY,
secretKey: process.env.YAMATA_USER_API_SECRET,
privateKey: process.env.YAMATA_USER_PRIVATE_KEY,
// ... other config
});// Taker: Matches orders to provide activity
const taker = new YamataAdapterSDK({
apiKey: process.env.YAMATA_TAKER_USER_API_KEY,
secretKey: process.env.YAMATA_TAKER_USER_API_SECRET,
privateKey: process.env.YAMATA_TAKER_USER_PRIVATE_KEY,
// ... other config
});
// Maker places orders
await maker.createOrderLP({
symbol: "BTC_USDT",
side: "buy",
price: 49500,
amount: 0.1,
});
// Taker crosses spread to match
await taker.createOrderLP({
symbol: "BTC_USDT",
side: "sell",
price: 49500, // Match the buy order
amount: 0.05,
});
`📚 API Reference & Usage Examples
$3
#### Public APIs (No Authentication Required)
1. Health & Connectivity APIs
- 1.1 Health Check
- 1.2 Ping
- 1.3 Get Clients
- 1.4 Get Time
2. Exchange Information APIs
- 2.1 Get Exchange Info
- 2.2 Get Cached Symbols
3. Market Data APIs
- 3.1 Get 24hr Ticker (All Symbols)
- 3.2 Get 24hr Ticker (Specific Symbol)
- 3.3 Get Ticker Price (All Symbols)
- 3.4 Get Ticker Price (Specific Symbol)
4. Order Book APIs
- 4.1 Get Depth (Order Book)
- 4.2 Clear Depth Cache
5. Recent Trades APIs
- 5.1 Get Recent Trades
6. Candlestick Data APIs
- 6.1 Get Klines (Candlesticks)
#### Authenticated APIs (Requires API Key)
7. Account Management APIs
- 7.1 Get Account Information
- 7.2 Get Account Balance
- 7.3 Get Account Status
- 7.4 Get My Trades
8. API Key Management APIs
- 8.1 Get API Keys
- 8.2 Get Active API Keys
- 8.3 Get API Key by Name
- 8.4 Get API Key Statistics
9. Private Key Management APIs ⭐ NEW
- 11.1 Check Private Key Status
- 11.2 Get Private Key
- 11.3 Set Private Key
- 11.4 Get Ethereum Provider
- 11.5 Get Ethereum Wallet
- 11.6 Get Wallet Address
- 11.7 Clear Private Key
---
$3
#### 1.1 Health Check
Check if the Yamata adapter service is running and healthy.
`javascript
try {
const health = await sdk.getHealth();
console.log("Service Status:", health);
// Output: { status: 'ok', timestamp: '2025-08-16T05:06:33.350Z' }
} catch (error) {
console.error("Health check failed:", error.message);
}
`#### 1.2 Ping
Simple ping to test connectivity and response time.
`javascript
try {
const ping = await sdk.ping();
console.log("Ping Response:", ping);
// Output: { pong: true, timestamp: 1755320793351 }
} catch (error) {
console.error("Ping failed:", error.message);
}
`#### 1.3 Get Clients
Retrieve information about connected clients and services.
`javascript
try {
const clients = await sdk.getClients();
console.log("Connected Clients:", clients);
// Output: { clients: [...], services: [...], timestamp: ... }
} catch (error) {
console.error("Failed to get clients:", error.message);
}
`#### 1.4 Get Time
Get the current server time for timestamp synchronization.
`javascript
try {
const serverTime = await sdk.getTime();
console.log("Server Time:", serverTime);
// Output: { serverTime: 1755320793351, timezone: 'UTC' }
} catch (error) {
console.error("Failed to get server time:", error.message);
}
`$3
#### 2.1 Get Exchange Info
Retrieve comprehensive exchange information including symbols, filters, and trading rules.
`javascript
try {
const exchangeInfo = await sdk.getExchangeInfo();
console.log("Exchange Info:", exchangeInfo);
// Output: {
// timezone: 'UTC',
// serverTime: 1755320793351,
// symbols: [
// {
// symbol: 'BTCUSDT',
// status: 'TRADING',
// baseAsset: 'BTC',
// quoteAsset: 'USDT',
// filters: [...]
// }
// ]
// }
} catch (error) {
console.error("Failed to get exchange info:", error.message);
}
`#### 2.2 Get Cached Symbols
Get a list of cached trading symbols for quick reference.
`javascript
try {
const cachedSymbols = await sdk.getCachedSymbols();
console.log("Cached Symbols:", cachedSymbols);
// Output: ['BTCUSDT', 'ETHUSDT', 'ADAUSDT', ...]
} catch (error) {
console.error("Failed to get cached symbols:", error.message);
}
`$3
#### 3.1 Get 24hr Ticker (All Symbols)
Get 24-hour price change statistics for all symbols.
`javascript
try {
const ticker24hr = await sdk.getTicker24hr();
console.log("24hr Ticker (All):", ticker24hr);
// Output: [
// {
// symbol: 'BTCUSDT',
// priceChange: '1234.56',
// priceChangePercent: '2.5',
// weightedAvgPrice: '50000.00',
// prevClosePrice: '48765.44',
// lastPrice: '50000.00',
// volume: '1234.5678'
// }
// ]
} catch (error) {
console.error("Failed to get 24hr ticker:", error.message);
}
`#### 3.2 Get 24hr Ticker (Specific Symbol)
Get 24-hour price change statistics for a specific symbol.
`javascript
try {
const btcTicker = await sdk.getTicker24hr("BTCUSDT");
console.log("BTC 24hr Ticker:", btcTicker);
// Output: {
// symbol: 'BTCUSDT',
// priceChange: '1234.56',
// priceChangePercent: '2.5',
// lastPrice: '50000.00',
// volume: '1234.5678'
// }
} catch (error) {
console.error("Failed to get BTC ticker:", error.message);
}
`#### 3.3 Get Ticker Price (All Symbols)
Get current price for all symbols.
`javascript
try {
const allPrices = await sdk.getTickerPrice();
console.log("All Prices:", allPrices);
// Output: [
// { symbol: 'BTCUSDT', price: '50000.00' },
// { symbol: 'ETHUSDT', price: '3000.00' }
// ]
} catch (error) {
console.error("Failed to get all prices:", error.message);
}
`#### 3.4 Get Ticker Price (Specific Symbol)
Get current price for a specific symbol.
`javascript
try {
const btcPrice = await sdk.getTickerPrice("BTCUSDT");
console.log("BTC Price:", btcPrice);
// Output: { symbol: 'BTCUSDT', price: '50000.00' }
} catch (error) {
console.error("Failed to get BTC price:", error.message);
}
`$3
#### 4.1 Get Depth (Order Book)
Retrieve order book depth for a symbol with customizable limit.
`javascript
try {
// Get depth with 5 levels
const depth5 = await sdk.getDepth("BTCUSDT", 5);
console.log("Depth (5 levels):", depth5);
// Output: {
// lastUpdateId: 123456789,
// bids: [['50000.00', '1.234'], ['49999.00', '0.567']],
// asks: [['50001.00', '0.789'], ['50002.00', '1.123']]
// } // Get depth with 20 levels
const depth20 = await sdk.getDepth("BTCUSDT", 20);
console.log("Depth (20 levels):", depth20);
} catch (error) {
console.error("Failed to get depth:", error.message);
}
`#### 4.2 Clear Depth Cache
Clear cached depth data to get fresh order book information.
`javascript
try {
const clearResult = await sdk.clearDepthCache();
console.log("Cache cleared:", clearResult);
// Output: { success: true, message: 'Depth cache cleared' }
} catch (error) {
console.error("Failed to clear cache:", error.message);
}
`$3
#### 5.1 Get Recent Trades
Retrieve recent trades for a symbol with customizable limit.
`javascript
try {
// Get 5 recent trades
const trades5 = await sdk.getTrades("BTCUSDT", 5);
console.log("Recent Trades (5):", trades5);
// Output: [
// {
// id: 123456,
// price: '50000.00',
// qty: '0.001',
// quoteQty: '50.00',
// time: 1755320793351,
// isBuyerMaker: false,
// isBestMatch: false
// }
// ] // Get 10 recent trades
const trades10 = await sdk.getTrades("BTCUSDT", 10);
console.log("Recent Trades (10):", trades10);
} catch (error) {
console.error("Failed to get trades:", error.message);
}
`$3
#### 6.1 Get Klines (Candlesticks)
Retrieve historical candlestick data for technical analysis.
`javascript
try {
// Get 1-minute klines (5 candles)
const klines1m = await sdk.getKlines("BTCUSDT", "1m", 5);
console.log("1m Klines:", klines1m);
// Output: [
// {
// openTime: 1755320760000,
// open: '50000.00',
// high: '50010.00',
// low: '49990.00',
// close: '50005.00',
// volume: '123.456',
// closeTime: 1755320819999
// }
// ] // Get 1-hour klines (5 candles)
const klines1h = await sdk.getKlines("BTCUSDT", "1h", 5);
console.log("1h Klines:", klines1h);
// Get daily klines (5 candles)
const klines1d = await sdk.getKlines("BTCUSDT", "1d", 5);
console.log("1d Klines:", klines1d);
} catch (error) {
console.error("Failed to get klines:", error.message);
}
`Available Intervals:
-
1m - 1 minute
- 3m - 3 minutes
- 5m - 5 minutes
- 15m - 15 minutes
- 30m - 30 minutes
- 1h - 1 hour
- 2h - 2 hours
- 4h - 4 hours
- 6h - 6 hours
- 8h - 8 hours
- 12h - 12 hours
- 1d - 1 day
- 3d - 3 days
- 1w - 1 week
- 1M - 1 month$3
#### 7.1 Get Account Information
Retrieve comprehensive account information including balances and permissions.
`javascript
try {
const account = await sdk.getAccount();
console.log("Account Info:", account);
// Output: {
// makerCommission: 15,
// takerCommission: 15,
// buyerCommission: 0,
// sellerCommission: 0,
// canTrade: true,
// canWithdraw: true,
// canDeposit: true,
// updateTime: 0,
// accountType: 'SPOT',
// balances: [
// {
// asset: 'BTC',
// free: '1.00000000',
// locked: '0.00000000'
// }
// ]
// }
} catch (error) {
console.error("Failed to get account:", error.message);
}
`#### 7.2 Get Account Balance
Get simplified balance information for all assets.
`javascript
try {
const balance = await sdk.getBalance();
console.log("Account Balance:", balance);
// Output: [
// {
// asset: 'BTC',
// free: '1.00000000',
// locked: '0.00000000',
// total: '1.00000000'
// }
// ]
} catch (error) {
console.error("Failed to get balance:", error.message);
}
`#### 7.3 Get Account Status
Check account status and trading permissions.
`javascript
try {
const status = await sdk.getAccountStatus();
console.log("Account Status:", status);
// Output: {
// canTrade: true,
// canWithdraw: true,
// canDeposit: true,
// updateTime: 0
// }
} catch (error) {
console.error("Failed to get account status:", error.message);
}
`#### 7.4 Get My Trades
Retrieve your trading history with optional filtering.
`javascript
try {
// Get all trades
const allTrades = await sdk.getMyTrades();
console.log("All My Trades:", allTrades); // Get trades for specific symbol
const btcTrades = await sdk.getMyTrades({ symbol: "BTCUSDT" });
console.log("BTC Trades:", btcTrades);
// Get trades with limit
const recentTrades = await sdk.getMyTrades({ limit: 10 });
console.log("Recent Trades:", recentTrades);
// Get trades with symbol and limit
const btcRecentTrades = await sdk.getMyTrades({
symbol: "BTCUSDT",
limit: 5,
});
console.log("BTC Recent Trades:", btcRecentTrades);
} catch (error) {
console.error("Failed to get my trades:", error.message);
}
`$3
#### 8.1 Get API Keys
Retrieve all API keys associated with your account.
`javascript
try {
const apiKeys = await sdk.getApiKeys();
console.log("API Keys:", apiKeys);
// Output: [
// {
// id: 'key_id_123',
// name: 'Trading Bot Key',
// apiKey: 'ymta_...',
// permissions: { read: true, write: true },
// createdAt: '2025-08-16T05:00:00Z',
// lastUsed: '2025-08-16T05:30:00Z'
// }
// ]
} catch (error) {
console.error("Failed to get API keys:", error.message);
}
`#### 8.2 Get Active API Keys
Get only active (non-revoked) API keys.
`javascript
try {
const activeKeys = await sdk.getActiveApiKeys();
console.log("Active API Keys:", activeKeys);
} catch (error) {
console.error("Failed to get active API keys:", error.message);
}
`#### 8.3 Get API Key by Name
Find a specific API key by its name.
`javascript
try {
const keyByName = await sdk.getApiKeyByName("Trading Bot Key");
console.log("API Key by Name:", keyByName);
} catch (error) {
console.error("Failed to get API key by name:", error.message);
}
`#### 8.4 Create API Key
Create a new API key with specific permissions.
`javascript
try {
const newKey = await sdk.createApiKey({
name: "My Trading Bot",
userId: "user_123",
permissions: {
read: true,
write: true,
trading: true,
},
});
console.log("New API Key:", newKey);
// Output: {
// id: 'new_key_id',
// name: 'My Trading Bot',
// apiKey: 'ymta_new_api_key_...',
// secretKey: 'new_secret_key_...',
// permissions: { read: true, write: true, trading: true }
// }
} catch (error) {
console.error("Failed to create API key:", error.message);
}
`#### 8.5 Revoke API Key
Revoke (delete) an existing API key.
`javascript
try {
const revokeResult = await sdk.revokeApiKey("key_id_123");
console.log("API Key Revoked:", revokeResult);
// Output: { success: true, message: 'API key revoked successfully' }
} catch (error) {
console.error("Failed to revoke API key:", error.message);
}
`#### 8.6 Update API Key Permissions
Modify permissions for an existing API key.
`javascript
try {
const updateResult = await sdk.updateApiKeyPermissions("key_id_123", {
read: true,
write: false,
trading: true,
});
console.log("Permissions Updated:", updateResult);
} catch (error) {
console.error("Failed to update permissions:", error.message);
}
`#### 8.7 Get API Key Statistics
Get usage statistics for an API key.
`javascript
try {
const stats = await sdk.getApiKeyStats("key_id_123");
console.log("API Key Stats:", stats);
// Output: {
// totalRequests: 1500,
// successfulRequests: 1480,
// failedRequests: 20,
// lastUsed: '2025-08-16T05:30:00Z',
// createdAt: '2025-08-16T05:00:00Z'
// }
} catch (error) {
console.error("Failed to get API key stats:", error.message);
}
`$3
The SDK now supports private key management for blockchain operations with Ethereum provider and wallet initialization. Both private key and RPC URL are required parameters.
#### 11.1 Check Private Key Status
Check if a private key is currently set in the SDK.
`javascript
try {
const hasPrivateKey = sdk.hasPrivateKey();
console.log("Private Key Available:", hasPrivateKey);
// Output: true or false
} catch (error) {
console.error("Failed to check private key status:", error.message);
}
`#### 11.2 Get Private Key
Retrieve the current private key (returns null if not set).
`javascript
try {
const privateKey = sdk.getPrivateKey();
console.log("Private Key Set:", privateKey !== null);
// Output: The private key string or null
} catch (error) {
console.error("Failed to get private key:", error.message);
}
`#### 11.3 Set Private Key
Set a private key after SDK initialization.
`javascript
try {
sdk.setPrivateKey("your_private_key_here");
console.log("Private Key Set Successfully"); // Verify it was set
const hasKey = sdk.hasPrivateKey();
console.log("Private Key Available:", hasKey); // true
} catch (error) {
console.error("Failed to set private key:", error.message);
}
`#### 11.4 Get Ethereum Provider
Get the Ethereum provider instance for blockchain operations.
`javascript
try {
const provider = sdk.getProvider();
if (provider) {
console.log("Provider available:", provider.connection.url);
} else {
console.log("Provider not initialized");
}
} catch (error) {
console.error("Failed to get provider:", error.message);
}
`#### 11.5 Get Ethereum Wallet
Get the Ethereum wallet instance for blockchain operations.
`javascript
try {
const wallet = sdk.getWallet();
if (wallet) {
console.log("Wallet address:", wallet.address);
console.log(
"Wallet connected to provider:",
wallet.provider.connection.url
);
} else {
console.log("Wallet not initialized");
}
} catch (error) {
console.error("Failed to get wallet:", error.message);
}
`#### 11.6 Get Wallet Address
Get the wallet address directly.
`javascript
try {
const address = sdk.getWalletAddress();
if (address) {
console.log("Wallet address:", address);
} else {
console.log("Wallet not initialized");
}
} catch (error) {
console.error("Failed to get wallet address:", error.message);
}
`#### 11.7 Clear Private Key
Remove the currently stored private key and blockchain components.
`javascript
try {
sdk.clearPrivateKey();
console.log("Private Key and blockchain components cleared"); // Verify they were cleared
const hasKey = sdk.hasPrivateKey();
const hasProvider = sdk.getProvider() !== null;
const hasWallet = sdk.getWallet() !== null;
console.log("Private Key Available:", hasKey); // false
console.log("Provider Available:", hasProvider); // false
console.log("Wallet Available:", hasWallet); // false
} catch (error) {
console.error("Failed to clear private key:", error.message);
}
`#### Private Key Configuration
Both private key and RPC URL are required for blockchain operations:
`javascript
const sdk = new YamataAdapterSDK({
apiKey: "ymta_your_api_key",
secretKey: "your_secret_key",
privateKey: "your_private_key_here", // Required
rpcUrl: "https://eth-mainnet.g.alchemy.com/v2/your-api-key", // Required
baseUrl: "http://localhost:3080",
debug: true,
});// Or set it later (both parameters required)
sdk.setPrivateKey(
"new_private_key",
"https://eth-mainnet.g.alchemy.com/v2/new-api-key"
);
`---
🔄 WebSocket Support
The Yamata Adapter SDK provides comprehensive WebSocket support for real-time data streaming, compatible with the Yamata adapter service WebSocket gateway.
$3
- Real-time Market Data: Live trade, depth, and ticker updates
- User Data Streams: Account updates, order executions, and balance changes
- Authentication: Secure WebSocket authentication with API keys
- Auto-reconnection: Automatic reconnection with configurable retry logic
- Event-driven Architecture: Rich event system for handling different data types
- Heartbeat Management: Built-in ping/pong heartbeat system
$3
`javascript
import { YamataAdapterSDK } from "yamata-adapter-sdk";const sdk = new YamataAdapterSDK({
apiKey: "ymta_your_api_key",
secretKey: "your_secret_key",
baseUrl: "http://localhost:3080",
debug: true,
autoReconnect: true,
maxReconnectAttempts: 5,
reconnectInterval: 3000,
});
// Connect to WebSocket
await sdk.connectWebSocket();
// Test connection with ping
const pong = await sdk.pingWebSocket();
console.log("Ping successful:", pong);
// Disconnect
sdk.disconnectWebSocket();
`$3
`javascript
// Authenticate with WebSocket server
try {
const authResult = await sdk.authenticateWebSocket();
console.log("Authenticated:", authResult);
// Output: {
// apiKey: 'ymta_your_api_key',
// authorizedSince: 1755320793351,
// connectedSince: 1755320793351,
// returnRateLimits: false,
// serverTime: 1755320793351,
// userDataStream: true
// }
} catch (error) {
console.error("Authentication failed:", error.message);
}
`$3
#### Subscribe to Market Data
`javascript
// Subscribe to multiple streams
const streams = [
"btcusdt@trade", // Real-time trades
"btcusdt@depth@100ms", // Order book updates
"ethusdt@trade", // ETH trades
"ethusdt@depth@100ms", // ETH order book
];await sdk.subscribeToStreams(streams);
// Set up event listeners
sdk.onWebSocketEvent("btcusdt@trade", (data) => {
console.log("BTC Trade:", {
symbol: data.s,
price: data.p,
quantity: data.q,
time: new Date(data.T).toISOString(),
});
});
sdk.onWebSocketEvent("btcusdt@depth@100ms", (data) => {
console.log("BTC Depth Update:", {
symbol: data.s,
firstUpdateId: data.U,
finalUpdateId: data.u,
bids: data.b.length,
asks: data.a.length,
});
});
// Unsubscribe from specific streams
await sdk.unsubscribeFromStreams(["ethusdt@trade", "ethusdt@depth@100ms"]);
`#### Available Stream Types
-
{symbol}@trade: Real-time trade data
- {symbol}@depth@100ms: Order book depth updates
- {symbol}@ticker: 24hr ticker updates (if available)$3
#### Start User Data Stream
`javascript
// Start user data stream (requires API key)
const listenKey = await sdk.startUserDataStream(["userData"]);
console.log("User data stream started:", listenKey);// Subscribe to user data stream (requires authentication)
if (sdk.getWebSocketAuthStatus()) {
await sdk.subscribeToUserDataStream();
// Listen for user data events
sdk.onWebSocketEvent("outboundAccountPosition", (data) => {
console.log("Account Position Update:", {
eventTime: new Date(data.E).toISOString(),
balances: data.B.length,
});
});
sdk.onWebSocketEvent("executionReport", (data) => {
console.log("Order Execution:", {
symbol: data.s,
side: data.S,
orderType: data.o,
status: data.X,
price: data.p,
quantity: data.q,
});
});
// Unsubscribe when done
await sdk.unsubscribeFromUserDataStream();
}
// Stop user data stream
await sdk.stopUserDataStream(listenKey);
`#### User Data Event Types
-
outboundAccountPosition: Account balance updates
- executionReport: Order execution reports
- listenKeyExpired: Listen key expiration notification$3
`javascript
// Start automatic heartbeat (30 second interval)
sdk.startHeartbeat(30000);// Manual ping
const pong = await sdk.pingWebSocket();
console.log("Manual ping response:", pong);
// Stop heartbeat
sdk.stopHeartbeat();
`$3
#### Connection Events
`javascript
// Connection events
sdk.onWebSocketEvent("connect", () => {
console.log("WebSocket connected");
});sdk.onWebSocketEvent("disconnect", (event) => {
console.log("WebSocket disconnected:", event.code, event.reason);
});
sdk.onWebSocketEvent("error", (error) => {
console.error("WebSocket error:", error);
});
`#### Authentication Events
`javascript
sdk.onWebSocketEvent("authenticated", (data) => {
console.log("WebSocket authenticated:", data);
});
`#### Subscription Events
`javascript
sdk.onWebSocketEvent("subscribed", (data) => {
console.log("Subscribed to stream:", data);
});sdk.onWebSocketEvent("unsubscribed", (data) => {
console.log("Unsubscribed from stream:", data);
});
`$3
`javascript
// Get connection status
console.log("Connected:", sdk.getWebSocketStatus());
console.log("Authenticated:", sdk.getWebSocketAuthStatus());
console.log("Subscriptions:", sdk.getWebSocketSubscriptions());
console.log("Listen Key:", sdk.getWebSocketListenKey());
console.log("User ID:", sdk.getWebSocketUserId());
`$3
`javascript
async function advancedWebSocketExample() {
const sdk = new YamataAdapterSDK({
apiKey: process.env.YAMATA_API_KEY,
secretKey: process.env.YAMATA_SECRET_KEY,
baseUrl: process.env.YAMATA_BASE_URL,
debug: true,
autoReconnect: true,
}); try {
// Connect and authenticate
await sdk.connectWebSocket();
await sdk.authenticateWebSocket();
// Set up event listeners
let tradeCount = 0;
sdk.onWebSocketEvent("btcusdt@trade", (data) => {
tradeCount++;
if (tradeCount % 10 === 0) {
console.log(
Trade #${tradeCount}: ${data.s} @ ${data.p} (${data.q}));
}
}); // Subscribe to streams
await sdk.subscribeToStreams(["btcusdt@trade", "btcusdt@depth@100ms"]);
// Start heartbeat
sdk.startHeartbeat(30000);
// Run for 30 seconds
await new Promise((resolve) => setTimeout(resolve, 30000));
// Cleanup
sdk.stopHeartbeat();
sdk.disconnectWebSocket();
console.log(
Received ${tradeCount} trades);
} catch (error) {
console.error("WebSocket example failed:", error);
}
}
`$3
`bash
Run WebSocket example
npm run test:websocketOr run directly
node examples/websocket-example.js
`🛠️ Error Handling
$3
`javascript
try {
const result = await sdk.getAccount();
console.log("Success:", result);
} catch (error) {
switch (error.code) {
case "AUTH_ERROR":
console.error("Authentication failed:", error.message);
break;
case "RATE_LIMIT":
console.error("Rate limit exceeded:", error.message);
break;
case "INVALID_PARAMETER":
console.error("Invalid parameter:", error.message);
break;
case "NETWORK_ERROR":
console.error("Network error:", error.message);
break;
default:
console.error("Unexpected error:", error.message);
} // Access detailed error information
console.log("Error details:", {
status: error.status,
code: error.code,
timestamp: error.timestamp,
details: error.details,
});
}
`$3
-
AuthenticationError: Invalid API key, signature, or timestamp
- RateLimitError: Too many requests
- ValidationError: Invalid parameters
- NetworkError: Connection issues
- ServerError: Server-side errors📊 Testing
$3
`bash
Test all public endpoints
npm run test:publicOr run directly
node test-all-get-apis.js
`$3
`bash
Test all authenticated endpoints (requires valid API keys)
npm run test:authOr run directly
node test-authenticated-apis.js
`$3
`bash
Test basic SDK functions
node test-sdk-functions.js
`📖 Examples
$3
`bash
Run basic usage example
npm run exampleOr run directly
node examples/basic-usage.js
`$3
`bash
Run comprehensive GET APIs example
npm run example:get-apisOr run directly
node examples/get-apis-example.js
`$3
`bash
Run comprehensive GET APIs example
npm run example:get-apisOr run directly
node example/place-order.js
`$3
`bash
Run WebSocket example
node examples/websocket-example.js
`$3
-
examples/basic-usage.js - Basic SDK functionality demonstration
- examples/get-apis-example.js - Comprehensive GET APIs testing and demonstration
- examples/websocket-example.js - Real-time WebSocket data streaming
- examples/place-order.js - Create an order on the exchangeStrategies
The SDK provides a pre-built market-making strategy. The strategy continuously places orders on both sides (buy & sell) to create market liquidity
`javascript
/**
* Create market making orders (buy and sell around market price)
*/
async createMarketMakingOrders() {
try {
// Fetch current market price first
await this.fetchMarketPrice(); if (!this.lastMarketPrice) {
throw new Error('Market price not available');
}
const spreadMultiplier = this.spreadPercentage / 100;
const buyPrice = this.lastMarketPrice * (1 - spreadMultiplier);
const sellPrice = this.lastMarketPrice * (1 + spreadMultiplier);
console.log('📊 Creating market making orders:');
console.log(
Buy Order: ${this.orderAmount} @ $${buyPrice.toFixed(2)} (${this.spreadPercentage}% below market));
console.log( Sell Order: ${this.orderAmount} @ $${sellPrice.toFixed(2)} (${this.spreadPercentage}% above market)); // Create buy order
const buyOrder = await this.sdk.createOrder({
amount: this.orderAmount,
price: buyPrice,
side: 'buy',
symbol: this.tradingPair
});
// Extract the real order ID from the response
const buyOrderId = buyOrder.id || buyOrder.orderId || buyOrder.order_id;
if (buyOrderId) {
this.activeOrders[buyOrderId] = {
orderId: buyOrderId,
side: 'buy',
price: buyPrice,
amount: this.orderAmount,
symbol: this.tradingPair,
status: 'pending',
originalResponse: buyOrder
};
console.log('✅ Buy order created:', buyOrderId);
} else {
console.error('❌ Buy order creation failed - no order ID returned:', buyOrder);
}
// Create sell order
const sellOrder = await this.sdk.createOrder({
amount: this.orderAmount,
price: sellPrice,
side: 'sell',
symbol: this.tradingPair
});
// Extract the real order ID from the response
const sellOrderId = sellOrder.id || sellOrder.orderId || sellOrder.order_id;
if (sellOrderId) {
this.activeOrders[sellOrderId] = {
orderId: sellOrderId,
side: 'sell',
price: sellPrice,
amount: this.orderAmount,
symbol: this.tradingPair,
status: 'pending',
originalResponse: sellOrder
};
console.log('✅ Sell order created:', sellOrderId);
} else {
console.error('❌ Sell order creation failed - no order ID returned:', sellOrder);
}
} catch (error) {
console.error('❌ Failed to create market making orders:', error.message);
}
}
`To test it run
`bash
npm run strategyor
node src/strategy/pure-market-making.js
`🚀 Performance Optimization
$3
1. Reuse SDK Instance: Create one SDK instance and reuse it
2. Batch Requests: Group related requests when possible
3. Use WebSocket: For real-time data instead of polling
4. Implement Caching: Cache frequently accessed data
5. Handle Rate Limits: Implement exponential backoff
$3
`javascript
import { YamataAdapterSDK } from "yamata-adapter-sdk";class TradingBot {
constructor() {
this.sdk = new YamataAdapterSDK({
apiKey: process.env.YAMATA_API_KEY,
secretKey: process.env.YAMATA_SECRET_KEY,
baseUrl: process.env.YAMATA_BASE_URL,
debug: process.env.NODE_ENV === "development",
});
this.cache = new Map();
this.cacheTimeout = 5000; // 5 seconds
}
async getCachedPrice(symbol) {
const cacheKey =
price_${symbol};
const cached = this.cache.get(cacheKey); if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
return cached.data;
}
const price = await this.sdk.getTickerPrice(symbol);
this.cache.set(cacheKey, {
data: price,
timestamp: Date.now(),
});
return price;
}
async monitorPrices(symbols) {
await this.sdk.connectWebSocket();
symbols.forEach((symbol) => {
this.sdk.subscribeToTicker(symbol, (data) => {
console.log(
${symbol} price: ${data.price});
this.cache.set(price_${symbol}, {
data: { symbol, price: data.price },
timestamp: Date.now(),
});
});
});
}
}
`📝 API Key Format & Security
$3
- Prefix: Must start with
ymta_
- Length: Minimum 32 characters
- Format: Alphanumeric with underscores
- Example: ymta_trading_bot_key_1234567890abcdef`1. Never expose secret keys in client-side code
2. Use environment variables for sensitive data
3. Implement proper key rotation
4. Monitor API key usage regularly
5. Use minimal permissions for each key
---
Made with ❤️ by the Yamata Team