@zufan_devops/coinbase-sdk
v0.1.18
Published
Unofficial Coinbase REST API SDK built with modern tooling.
Downloads
69
Maintainers
Readme
@zufan_devops/coinbase-sdk
Unofficial TypeScript SDK for the Coinbase Advanced Trade APIs. The initial milestone concentrates on the REST endpoints documented in AI-Doc/CB_Endpoints.md; WebSocket coverage described in AI-Doc/CB_ WebSocket.md will follow once the REST surface is stable.
Status: Active development. Expect rapid iteration and breaking changes until the REST client is feature complete.
Why this SDK
- TypeScript-first design that ships
.d.tsfiles for editor autocomplete. - Strict (and pragmatic) Zod validation that accepts Coinbase response quirks (e.g.,
nulltimestamps, numeric strings, missing tickers) without crashing your app. - Axios-based HTTP transport with dependency injection hooks for testing.
- ES256 JWT signing that mirrors the example in
AI-Doc/Example/code/example.js. - Chalk-powered terminal messaging (usage patterns to be finalized).
Installation
Requirements
- Node.js 18 or newer (ES2020 features and
crypto/Uint8Arraysupport). - npm 9+ or pnpm/yarn at comparable versions.
Install from npm
npm install @zufan_devops/coinbase-sdkBecause the package is TypeScript-native, importing it from JavaScript or TypeScript automatically enables IDE autocomplete through the published definitions in dist/types/index.d.ts.
Configure credentials
Create a Coinbase Advanced Trade API key/secret pair in the Coinbase UI and export them as environment variables before running any code. The secret is a PEM-encoded ES256 private key.
export COINBASE_API_KEY="cbkey_xxxxx"
export COINBASE_API_SECRET="$(cat path/to/private-key.pem)"Additional configuration (such as key versioning or passphrases) will be surfaced through typed schemas in src/schemas/ as the REST surface grows.
Quick start
import { CoinbaseClient } from '@zufan_devops/coinbase-sdk';
if (!process.env.COINBASE_API_KEY || !process.env.COINBASE_API_SECRET) {
throw new Error('Missing Coinbase Advanced Trade credentials');
}
const client = new CoinbaseClient({
apiKey: process.env.COINBASE_API_KEY,
apiSecret: process.env.COINBASE_API_SECRET,
});
const { accounts } = await client.accounts.list();
console.log(`Found ${accounts.length} accounts`);
const account = await client.accounts.get({
accountId: accounts[0]?.uuid ?? '',
});
console.log(account.name);
const preview = await client.orders.preview({
product_id: 'BTC-USD',
side: 'BUY',
order_configuration: {
limit_limit_gtc: { base_size: '0.1', limit_price: '45000' },
},
});
console.log(preview);
const ticker = await client.marketData.getTicker({ product_id: 'BTC-USD' });
console.log(`Latest BTC price: ${ticker.price}`);- The constructor Zod-validates credentials and optional transport overrides.
- A short-lived ES256 JWT (2 minute TTL) is minted per request and attached as the
Authorization: Bearerheader. - REST services are mirrored at the top level (
client.accounts,client.orders, etc.) withclient.restretained for compatibility.
Usage examples
Examples assume the
clientvariable from the quick start section is in scope.
Accounts
const { accounts } = await client.accounts.list({ limit: 50 });
const firstAccountId = accounts[0]?.uuid;
if (firstAccountId) {
const account = await client.accounts.get({ accountId: firstAccountId });
console.log(account.available_balance?.value);
}Orders
const preview = await client.orders.preview({
product_id: 'ETH-USD',
side: 'SELL',
order_configuration: {
limit_limit_gtc: { base_size: '1', limit_price: '3500' },
},
});
const created = await client.orders.create({
client_order_id: preview.previews?.[0]?.preview_id,
product_id: 'ETH-USD',
side: 'SELL',
order_configuration: {
limit_limit_gtc: { base_size: '1', limit_price: '3500' },
},
});
if (created.order_id) {
await client.orders.cancel({ order_ids: [created.order_id] });
}Market data
const { products } = await client.marketData.listProducts({ limit: 10 });
const bestBidAsk = await client.marketData.getBestBidAsk({ product_ids: ['BTC-USD'] });
const ticker = await client.marketData.getTicker({ product_id: 'BTC-USD' });
console.log(products.length, bestBidAsk.pricebooks[0], ticker.price);Transactions
const summary = await client.transactions.getSummary({
start_date: '2024-01-01T00:00:00Z',
end_date: '2024-01-31T23:59:59Z',
});
console.log(summary.total_volume);Conversions
const quote = await client.conversions.createQuote({
from_account: 'USD',
to_account: 'USDC',
amount: '1000',
});
if (quote.quote.quote_id) {
await client.conversions.commit({
tradeId: quote.quote.trade_id ?? quote.quote.quote_id,
quote_id: quote.quote.quote_id,
});
}Portfolios
const portfolios = await client.portfolios.list();
const portfolioId = portfolios.portfolios?.[0]?.uuid;
if (portfolioId) {
const breakdown = await client.portfolios.getBreakdown({ portfolioUuid: portfolioId });
console.log(breakdown.positions?.length);
}Futures
const balance = await client.futures.getBalanceSummary();
const positions = await client.futures.listPositions();
console.log(balance.total?.value, positions.positions?.length);Perpetuals
const portfolioUuid = 'your-portfolio-uuid';
const summary = await client.perpetuals.getPortfolioSummary({ portfolioUuid });
const positions = await client.perpetuals.listPositions({ portfolioUuid });
console.log(summary.portfolio?.equity, positions.positions?.length);Payment methods
const paymentMethods = await client.paymentMethods.list();
const fundingId = paymentMethods.payment_methods?.[0]?.id;
if (fundingId) {
const paymentMethod = await client.paymentMethods.get({ paymentMethodId: fundingId });
console.log(paymentMethod.name);
}Utility
const permissions = await client.utility.getApiKeyPermissions();
console.log(permissions.permissions?.map((perm) => perm.permission));Handling API response quirks
Coinbase occasionally omits or reshapes fields in REST payloads. The SDK smooths over the most common cases, so you can keep working with predictable types:
client.accounts.list()treatsdeleted_atas nullable.client.orders.list()coercesnumber_of_fillsinto a number even when the API returns a string.client.marketData.getTicker()tolerates sparse snapshots and backfills the requestedproduct_idwhen Coinbase omits it.
If you encounter other mismatches, open an issue with a redacted payload and we will extend the schemas accordingly.
Documentation for AI assistants
The package can act as a Model Context Protocol (MCP) documentation server so AI coding assistants can stream SDK references on demand.
npx @zufan_devops/coinbase-sdk --serve-docs- Speaks MCP JSON-RPC over stdin/stdout and understands
initialize,listTopics,getDocumentation,ping,shutdown, andexit. - Serves the package README and all generated Markdown files under
docs/. - Stop the process with
Ctrl+Cor send the MCPshutdown/exitcommands from the host assistant.
Authentication blueprint
Until the SDK helpers are published, you can experiment with the signing flow showcased in AI-Doc/Example/code/example.js. The outline is:
- Build the canonical request string (
${METHOD} api.coinbase.com${path}) for the Advanced Trade API. - Sign a JWT with ES256 using your Coinbase private key (
COINBASE_API_SECRET), include thekidheader (COINBASE_API_KEY), and a randomnonce. - Attach the token to the
Authorizationheader and call the REST resource with Axios or your preferred HTTP client. - Compare your response payload with the fixture in
AI-Doc/Example/data/example.response.jsonto validate the flow.
The SDK will encapsulate these steps in reusable utilities so application code never has to manage JWT plumbing directly.
SDK layout
CoinbaseClient– Public entry point instantiated withnew CoinbaseClient(config). Holds shared config (API key/secret, base URLs, Axios instance) and exposes both the flattened conveniences (client.accounts,client.orders, etc.) and the legacy namespace (client.rest), plus the websocket client (client.websocket).AdvancedTradeSigner– Internal helper class responsible for Zod-validating credential material and minting ES256 JWTs. Injected into REST/WebSocket modules.RestClient– Aggregates REST domain services, ensures every call flows through a single request pipeline, handles retries/logging, and delegates to feature-specific classes. Exposed viaclient.restfor backwards compatibility.AccountsService,OrdersService,MarketDataService, etc. – Thin service classes per resource group mirroringAI-Doc/CB_Endpoints.md. Each depends onRestClientfor HTTP dispatch and on Zod schemas fromsrc/schemas/.CoinbaseWebSocketClient– Wrapper around Coinbase streaming APIs perAI-Doc/CB_ WebSocket.md. Provides connection lifecycle management, subscription helpers, and message validation.ConsoleReporter– Wrapper around Chalk for opinionated terminal output (e.g., warnings on schema validation failures or rate-limit notices). Injected where human-readable messaging is required.
Modules will be arranged under src/coinbase/** and src/shared/** to keep concerns isolated and maintain tree-shakeability.
Project structure
src/– TypeScript source (strict mode). Schemas live insrc/schemas/.dist/– Webpack bundle (index.js+ source map) and emitted declaration files (dist/types/).AI-Doc/– Reference material, endpoint definitions, examples, and design notes. Treat as read-only input when implementing features.docs/– Generated Markdown documentation (to be produced vianpm run docin a future update).tests/– Reserved for integration fixtures once the test runner is in place.
The Notes/ directory is intentionally off-limits according to the project guidelines.
Development workflow
npm run typecheck– Validate strict TypeScript settings without emitting code.npm run build– Bundle the SDK intodist/index.jsusing Webpack.npm run build:types– Emit declaration files todist/types/for downstream consumers.npm run test– Execute Vitest unit tests for the SDK.
Run the build before pushing any branch and especially after changing the public API shape.
Roadmap
- ✅ Bootstrap TypeScript, Webpack, and linting pipeline.
- ✅ Implement authenticated REST clients for List Accounts, Get Account, Create Order, Cancel Orders, List Orders, List Fills, Get Order, Preview Orders, List Products, Get Product, Get Product Candles, Get Product Ticker, Get Best Bid/Ask, and Get Product Book.
- ▢ Model comprehensive request/response types and Zod schemas for all private and public endpoints.
- ▢ Emit Markdown docs (
npm run doc) sourced from JSDoc blocks. - ▢ Layer in WebSocket subscriptions based on
AI-Doc/CB_ WebSocket.md. - ▢ Provide fixtures and Jest-powered unit tests that mock Coinbase responses.
Contributing & workflow
- Branch off
mainusing the enforced naming convention (feature/<name>,fix/<name>,chore/<name>). - Keep commits focused and descriptive; never commit directly to
main. - Sanitize secrets—never check API keys or real responses into git.
- Prefer dependency injection for HTTP clients to simplify testing.
- Request build + typecheck to stay green before opening a pull request.
Security considerations
- Load credentials from environment variables or secret managers; do not hard-code them.
- Rotate API keys regularly and scope permissions to the minimum required (see the tables in
AI-Doc/CB_Endpoints.md). - Audit dependencies periodically (
npm audit) and refresh sensitive packages (e.g. Axios) promptly.
License
ISC © zufans
