Risk Management
Examples for monitoring positions, setting stop losses, and managing risk.
Setup
typescript
import { HundredX, HundredXApiError } from '100x-sdk';
const sdk = await HundredX.create({
privateKey: process.env.PRIVATE_KEY!,
brokerId: Number(process.env.BROKER_ID!),
});Monitor Account State
typescript
async function printAccountSummary() {
const bp = await sdk.info.getBuyingPower();
const positions = await sdk.info.getPositions();
console.log('=== Account Summary ===');
console.log(`Buying Power: ${bp.totalBuyingPower}`);
console.log(`Positions: ${positions.positions.length}`);
for (const pos of positions.positions) {
console.log(
` Product ${pos.productID}: amount=${pos.vBalanceAmount}, ` +
`quote=${pos.vQuoteBalance}, leverage=${pos.leverage}`
);
}
}
await printAccountSummary();Set TP/SL on Entry
Place a position with take-profit and stop-loss in one call:
typescript
// Long ETH with 2:1 reward/risk
const result = await sdk.exchange.placeOrderWithTPSL({
marketId: 1,
isBuy: true,
amount: '1.0',
entryPrice: '2500.00',
takeProfitPrice: '2600.00',
stopLossPrice: '2450.00',
});
console.log(`Entry: ${result.entry.id} (${result.entry.status})`);
console.log(`TP: ${result.takeProfit.id} at 2600`);
console.log(`SL: ${result.stopLoss.id} at 2450`);Emergency Cancel All
Cancel all orders for a market:
typescript
async function emergencyCancel(marketId: number) {
console.log(`EMERGENCY: Canceling all orders for market ${marketId}...`);
const result = await sdk.exchange.cancelAllOrders(marketId);
console.log('Cancelled:', result.cancelledOrderIds);
}Position Size Limits
Enforce maximum position sizes before placing orders using sdk.safePlaceOrder(). Returns null if the order would exceed the limit:
typescript
// Max 10 ETH position — returns null if limit would be exceeded
const order = await sdk.safePlaceOrder(
{
marketId: 1,
isBuy: true,
amount: '2.0',
price: '2500.00',
orderType: 'LIMIT',
},
10.0, // max position size
);
if (order) {
console.log(`Order placed: ${order.id}`);
} else {
console.log('Order rejected — position limit exceeded');
}Periodic Health Check
Run a background health check loop:
typescript
async function healthCheckLoop(intervalMs: number = 30000) {
while (true) {
try {
const bp = await sdk.info.getBuyingPower();
const buyingPower = parseFloat(bp.totalBuyingPower);
const openOrders = await sdk.info.getUserOrders();
console.log(
`[Health] Buying power: ${buyingPower}, Open orders: ${openOrders.orders.length}`
);
if (buyingPower < 1000) {
console.warn('WARNING: Low buying power! Consider reducing positions.');
}
if (openOrders.orders.length > 50) {
console.warn('WARNING: Many open orders. Consider cleanup.');
}
} catch (error) {
console.error('Health check failed:', error);
}
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
}Graceful Shutdown
Handle process signals to clean up before exit:
typescript
const MARKET_ID = 1;
async function shutdown() {
console.log('Shutting down gracefully...');
try {
await sdk.exchange.cancelAllOrders(MARKET_ID);
console.log('All orders cancelled');
} catch (error) {
console.error('Failed to cancel orders on shutdown:', error);
}
sdk.disconnect();
process.exit(0);
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);