coinbase-at-api
v1.0.10
Published
A lightweight, event-driven Node.js SDK for Coinbase Advanced Trade API with paper trading and real-time balance tracking.
Readme
coinbase-at-api
A lightweight, event-driven Node.js SDK for Coinbase Advanced Trade API with paper trading and real-time balance tracking.
Features
- 🔐 JWT Authentication (ES256) for Coinbase Advanced Trade API
- 📡 Real-time WebSocket market data (public feed)
- 💰 Live Balance Tracking via private WebSocket + REST polling
- 📊 Paper Trading Engine with configurable fees, slippage, and P&L tracking
- 🚀 Event-Driven Architecture for building trading bots
- 🛡️ Production-ready and battle-tested
Installation
npm install coinbase-at-apiQuick Start
Paper Trading
import { CoinbaseAT } from 'coinbase-at-api';
const bot = new CoinbaseAT({
apiKey: process.env.COINBASE_API_KEY,
privateKey: process.env.COINBASE_API_SECRET,
mode: 'paper',
paper: {
startingCash: 10000,
feeBps: 60,
slippageBps: 5
}
});
bot.ws.connect();
bot.ws.on('open', () => bot.ws.subscribe(['BTC-USD']));
bot.ws.on('ticker', async (data) => {
console.log(`${data.product_id}: $${data.price}`);
if (parseFloat(data.price) < 95000) {
await bot.orders.marketBuy('BTC-USD', { quoteSize: 1000 });
}
});
bot.paper.on('fill', (order) => {
console.log(`Filled: ${order.side} ${order.amount} @ $${order.price}`);
});
bot.paper.on('pnl', (snap) => {
console.log(`Equity: $${snap.equity.toFixed(2)} | P&L: ${snap.returnPct.toFixed(2)}%`);
});Live Trading
import { CoinbaseAT } from 'coinbase-at-api';
const bot = new CoinbaseAT({
apiKey: process.env.COINBASE_API_KEY,
privateKey: process.env.COINBASE_API_SECRET,
mode: 'live'
});
await bot.initialize();
bot.balances.on('balances', (balances) => {
console.log('Balances:', balances);
});
const accounts = await bot.rest.getAccounts();
console.log(accounts);Configuration
Constructor Options
new CoinbaseAT({
apiKey: string, // Required: Your Coinbase API key
privateKey: string, // Required: Your EC private key (PEM format)
mode: 'paper' | 'live', // Default: 'paper'
paper: {
startingCash: number, // Default: 10000
feeBps: number, // Default: 60 (0.6%)
slippageBps: number // Default: 5 (0.05%)
}
})API Reference
WebSocket (Market Data)
bot.ws.connect() // Connect to public feed
bot.ws.subscribe(['BTC-USD']) // Subscribe to products
bot.ws.on('ticker', (data) => {}) // Listen to price updates
bot.ws.close() // Close connectionPaper Trading
// Market Buy
await bot.orders.marketBuy('BTC-USD', { quoteSize: 1000 })
await bot.orders.marketBuy('BTC-USD', { baseSize: 0.01 })
// Market Sell
await bot.orders.marketSell('BTC-USD', { baseSize: 0.01 })
// Get portfolio
const portfolio = bot.paper.getPortfolio()
// Returns: { cash, positions, lastPrices }Paper Trading Events
bot.paper.on('fill', (order) => {
// order: { side, product_id, amount, price, fee, timestamp }
})
bot.paper.on('pnl', (snapshot) => {
// snapshot: { cash, positions, unrealizedValue, equity, totalPnL, returnPct }
})Balance Manager (Live Mode)
await bot.initialize() // Must call first in live mode
bot.balances.on('balances', (balances) => {
// balances: { USD: { available, hold, uuid }, BTC: {...}, ... }
})
bot.balances.on('balance_update', (event) => {
// Real-time WebSocket updates
})
await bot.balances.refreshBalances()
const usdBalance = bot.balances.getBalance('USD')REST API
const accounts = await bot.rest.getAccounts()
const product = await bot.rest.getProduct('BTC-USD')
const orders = await bot.rest.getOrders()
await bot.rest.cancelOrder(orderId)Environment Variables
Create a .env file:
COINBASE_API_KEY=organizations/YOUR_ORG/apiKeys/YOUR_KEY_ID
COINBASE_API_SECRET="-----BEGIN EC PRIVATE KEY-----\nYOUR_PRIVATE_KEY\n-----END EC PRIVATE KEY-----"Architecture
coinbase-at-api/
├── src/
│ ├── index.js # Main entry point
│ ├── balanceManager.js # Real-time balance tracking
│ ├── client/
│ │ ├── auth.js # JWT signer (ES256)
│ │ ├── rest.js # REST API client
│ │ ├── ws.js # Public WebSocket
│ │ └── wsPrivate.js # Private WebSocket
│ └── brokers/
│ ├── paper.js # Paper trading engine
│ └── live.js # Live trading
├── .env # Your API credentials
└── package.jsonSecurity Best Practices
- Never commit
.envto version control - Use API keys with minimal permissions
- Rotate keys regularly if exposed
- Test with paper trading first before going live
- Store private keys securely in environment variables
Roadmap
- Live order execution (LiveBroker)
- Limit orders support
- Stop-loss / take-profit helpers
- Backtesting engine
- TypeScript definitions
- More exchange integrations
Disclaimer
This software is for educational purposes only. Trading cryptocurrencies involves substantial risk of loss. The authors are not responsible for any financial losses incurred while using this library.
Always test with paper trading before using real funds.
License
MIT © 2026 Zephirex Technologies LLC
Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Built with ❤️ for algorithmic traders
