blofin-core
v0.3.1
Published
[](https://github.com/blofin/blofin-core/actions/workflows/ci.yml) [](https://github.co
Readme
blofin-core
TypeScript SDK for the BloFin crypto futures API. Provides a typed HTTP client, 30 AI-friendly tools with smart endpoint routing, Zod schema validation, and a three-tier risk model — all with zero runtime dependencies beyond zod.
Install
npm install blofin-coreQuick Start
import { loadConfig, BlofinClient, buildTools } from "blofin-core";
const config = loadConfig();
const client = new BlofinClient(config);
// Direct API calls
const tickers = await client.publicGet("/api/v1/market/tickers", {
instId: "BTC-USDT",
});
// Or use the tool system
const tools = buildTools(config);
const getTickers = tools.find(t => t.name === "get_tickers")!;
const result = await getTickers.handler(
{ instId: "BTC-USDT" },
{ client, config },
);Environment Variables
export BLOFIN_API_KEY="your-api-key"
export BLOFIN_API_SECRET="your-api-secret"
export BLOFIN_PASSPHRASE="your-passphrase"
# Optional
export BLOFIN_BASE_URL="https://openapi.blofin.com" # default: demo trading
export BLOFIN_BROKER_ID="your-broker-id" # default: autoConfiguration
import { loadConfig, BlofinClient } from "blofin-core";
// Override via code
const config = loadConfig({
baseUrl: "https://openapi.blofin.com",
modules: ["public", "account"], // filter available modules
readOnly: true, // only expose read tools
});Tools
30 tools across 4 modules, with intelligent merging that routes to the right API endpoint based on parameters.
Public Module (7 tools) — no auth required
| Tool | Description |
|------|-------------|
| get_instruments | List available trading instruments |
| get_tickers | Get ticker data (price, volume, 24h change) |
| get_order_book | Get order book depth |
| get_market_trades | Get recent trades |
| get_mark_price | Get mark price for an instrument |
| get_candlesticks | Get OHLCV candlestick data |
| get_funding_rate | Get current or historical funding rate (auto-routed by params) |
Account Module (6 tools)
| Tool | Description |
|------|-------------|
| get_balance | Get account balance |
| get_positions | Get open positions |
| get_account_config | Get account configuration |
| manage_leverage | Query or set leverage (auto-routed: query if no leverage param, set if provided) |
| manage_margin_mode | Query or set margin mode (auto-routed) |
| manage_position_mode | Query or set position mode (auto-routed) |
Trading Module (11 tools)
| Tool | Risk | Description |
|------|------|-------------|
| get_orders | read | Get order detail / pending / history (auto-routed by orderId or status) |
| get_fills_history | read | Get trade fill history |
| get_tpsl_orders | read | Get active or historical TP/SL orders (auto-routed by state) |
| get_algo_orders | read | Get active or historical algo orders (auto-routed by state) |
| place_tpsl | write | Place take-profit / stop-loss order |
| cancel_tpsl | write | Cancel a TP/SL order |
| place_algo_order | write | Place an algo order (trigger, trailing, etc.) |
| cancel_algo_order | write | Cancel an algo order |
| place_order | dangerous | Place single or batch orders (auto-routed by orders array) |
| cancel_order | dangerous | Cancel single or batch orders (auto-routed by orders array) |
| close_position | dangerous | Close a position |
Asset Module (6 tools)
| Tool | Risk | Description |
|------|------|-------------|
| get_asset_balances | read | Get asset balances by account type |
| get_transfer_history | read | Get internal transfer history |
| get_deposit_history | read | Get deposit history |
| get_withdrawal_history | read | Get withdrawal history |
| get_apikey_info | read | Get API key permissions |
| fund_transfer | dangerous | Transfer funds between accounts |
Smart Tool Merging
8 tools intelligently merge multiple API endpoints into one, routing by parameters:
| Tool | Routing Logic |
|------|---------------|
| get_orders | orderId → detail; no status → pending; status=filled → history |
| place_order | single object → one order; orders array → batch |
| cancel_order | orderId → single; orders array → batch |
| manage_leverage | only instId → GET; with leverage → POST |
| manage_margin_mode | no params → GET; with marginMode → POST |
| manage_position_mode | no params → GET; with positionMode → POST |
| get_funding_rate | only instId → current; with before/after → history |
| get_tpsl_orders | no state → active; with state → history |
Full mapping: docs/api-mapping.md
Safety Model
Three-tier risk levels:
| Risk Level | Description |
|------------|-------------|
| read | Safe, read-only operations |
| write | State-changing but recoverable (e.g. set leverage, place TP/SL) |
| dangerous | Irreversible or high-impact (e.g. place order, transfer funds) |
Use readOnly: true in config to filter out all write/dangerous tools (19 read-only tools remain).
Architecture
external/blofin-api-docs (submodule)
↓
parse-api-docs.ts → api-spec/blofin-api.json
↓
generate-types.ts → src/generated/types.ts
generate-schemas.ts → src/generated/schemas.ts
↓
src/tools/ (30 tools using generated schemas)
↓
src/index.ts (public API)Exports
// SDK
export { BlofinClient, loadConfig, buildTools, RateLimiter };
export { generateSignature, createAuthHeaders };
// Errors
export { BlofinError, ConfigError, ValidationError, AuthenticationError,
RateLimitError, NetworkError, BlofinApiError };
export { toToolResponse, toToolError, sanitizeMessage };
// Types
export type { BlofinConfig, ConfigOverrides, ModuleId,
ToolSpec, ToolContext, RiskLevel };Development
pnpm install
pnpm run build # Build with tsup
pnpm run test # Run all tests
pnpm run typecheck # Type check
pnpm run smoke-test # Smoke test against live API
pnpm run smoke-test -- --mock # Smoke test against mock serverCode Generation
When BloFin updates their API:
pnpm run sync-docs # Pull latest API docs (git submodule)
pnpm run generate # Regenerate types + schemas from api-spec
pnpm run test # Verify nothing brokeLicense
MIT
