MiniApp API
Simple API Reference
The Simple API provides an easy-to-use, strongly-typed interface for building MiniApps. This guide covers all available methods, events, and configuration options with practical examples.
Table of Contents
Quick Start
Configuration
Connection Management
Permission Management
Trading Operations
Market Data
Account Information
Event System
Error Handling
Complete Example: DCA Bot
Quick Start
import { createSimpleMiniApp } from '@basedone/miniapp-sdk/simple';
const miniApp = createSimpleMiniApp({
appId: 'my-trading-bot',
autoConnect: true
});
// Subscribe to market data
await miniApp.subscribeToMarketData(['ETH', 'BTC']);
// Place a quick buy order
await miniApp.quickBuy('ETH', 0.1);
// Listen for events
miniApp.on('marketData', (data) => {
console.log(`${data.symbol}: $${data.price}`);
});
Configuration
SimpleConfig Interface
interface SimpleConfig {
/** Unique identifier for your MiniApp */
appId: string;
/** Automatically connect on initialization (default: false) */
autoConnect?: boolean;
/** Enable debug logging (default: false) */
debug?: boolean;
/** Connection timeout in milliseconds (default: 10000) */
connectionTimeout?: number;
/** Number of reconnection attempts (default: 5) */
reconnectAttempts?: number;
/** Delay between reconnection attempts in ms (default: 1000) */
reconnectDelay?: number;
/** Permissions to request automatically */
requestedPermissions?: SimplePermission[];
}
Configuration Examples
// Minimal configuration
const miniApp = createSimpleMiniApp({ appId: 'simple-bot' });
// Production configuration
const miniApp = createSimpleMiniApp({
appId: 'production-bot',
autoConnect: true,
debug: false,
connectionTimeout: 15000,
reconnectAttempts: 3,
reconnectDelay: 5000,
requestedPermissions: ['trading_read', 'trading_write', 'market_data_read']
});
// Development configuration
const miniApp = createSimpleMiniApp({
appId: 'dev-bot',
autoConnect: true,
debug: true,
connectionTimeout: 5000,
reconnectAttempts: 10,
reconnectDelay: 1000
});
Connection Management
connect()
Establishes connection to the Based.One terminal.
await miniApp.connect();
disconnect()
Closes the connection to the terminal.
await miniApp.disconnect();
waitForConnection()
Waits for the connection to be established (useful with autoConnect).
await miniApp.waitForConnection();
console.log('Connected!');
isConnected()
Returns the current connection status.
if (miniApp.isConnected()) {
console.log('Connected to terminal');
} else {
console.log('Not connected');
}
Connection Events
// Connection established
miniApp.on('connected', () => {
console.log('Successfully connected to terminal');
});
// Connection lost
miniApp.on('disconnected', () => {
console.log('Connection lost');
});
// Connection error
miniApp.on('connectionError', (error) => {
console.error('Connection error:', error);
});
// Reconnecting
miniApp.on('reconnecting', (attempt) => {
console.log(`Reconnecting... attempt ${attempt}`);
});
Permission Management
SimplePermission Types
type SimplePermission =
| 'market_data_read' // Access to market data
| 'trading_read' // View orders and positions
| 'trading_write' // Place orders
| 'trading_cancel' // Cancel orders
| 'account_read' // View balances and history
| 'account_write' // Transfer funds (limited)
| 'advanced_trading'; // Margin, futures, options
requestPermission()
Requests a specific permission from the user.
const granted = await miniApp.requestPermission('trading_write');
if (granted) {
console.log('Trading permission granted!');
}
requestTradingPermissions()
Convenience method to request all common trading permissions.
await miniApp.requestTradingPermissions();
// Requests: trading_read, trading_write, trading_cancel, market_data_read
hasPermission()
Checks if a specific permission is granted.
if (await miniApp.hasPermission('trading_write')) {
await miniApp.placeOrder(orderData);
} else {
console.log('Trading permission required');
}
getPermissions()
Returns all granted permissions.
const permissions = await miniApp.getPermissions();
console.log('Granted permissions:', permissions);
Trading Operations
placeOrder()
Places a trading order with full control over parameters.
interface SimpleOrderData {
symbol: string; // Trading pair (e.g., 'ETH', 'BTC')
side: 'buy' | 'sell'; // Order side
type: 'market' | 'limit' | 'stop' | 'stop_limit'; // Order type
quantity: number; // Order quantity
price?: number; // Limit price (required for limit orders)
stopPrice?: number; // Stop price (required for stop orders)
timeInForce?: 'GTC' | 'IOC' | 'FOK'; // Time in force
reduceOnly?: boolean; // Reduce position only
}
// Market order
await miniApp.placeOrder({
symbol: 'ETH',
side: 'buy',
type: 'market',
quantity: 0.1
});
// Limit order
await miniApp.placeOrder({
symbol: 'BTC',
side: 'sell',
type: 'limit',
quantity: 0.01,
price: 45000,
timeInForce: 'GTC'
});
// Stop loss order
await miniApp.placeOrder({
symbol: 'ETH',
side: 'sell',
type: 'stop',
quantity: 0.1,
stopPrice: 2400
});
quickBuy() / quickSell()
Convenience methods for market orders.
// Quick buy 0.1 ETH at market price
const buyOrder = await miniApp.quickBuy('ETH', 0.1);
// Quick sell 0.01 BTC at market price
const sellOrder = await miniApp.quickSell('BTC', 0.01);
limitOrder()
Convenience method for limit orders.
// Buy 0.1 ETH at $2500
const limitBuy = await miniApp.limitOrder('ETH', 'buy', 0.1, 2500);
// Sell 0.01 BTC at $45000
const limitSell = await miniApp.limitOrder('BTC', 'sell', 0.01, 45000);
cancelOrder()
Cancels a specific order by ID.
await miniApp.cancelOrder('order-id-123');
cancelAllOrders()
Cancels all open orders, optionally filtered by symbol.
// Cancel all orders
await miniApp.cancelAllOrders();
// Cancel all ETH orders
await miniApp.cancelAllOrders('ETH');
Trading Events
// Order confirmation
miniApp.on('orderConfirmation', (order) => {
console.log(`Order ${order.id} executed: ${order.side} ${order.quantity} ${order.symbol}`);
});
// Order rejection
miniApp.on('orderRejection', (rejection) => {
console.error(`Order rejected: ${rejection.reason}`);
});
// Order cancellation
miniApp.on('orderCancelled', (orderId) => {
console.log(`Order ${orderId} cancelled`);
});
// Trade execution
miniApp.on('tradeExecution', (trade) => {
console.log(`Trade executed: ${trade.quantity} ${trade.symbol} at $${trade.price}`);
});
Market Data
subscribeToMarketData()
Subscribe to real-time market data for specified symbols.
// Subscribe to single symbol
await miniApp.subscribeToMarketData(['ETH']);
// Subscribe to multiple symbols
await miniApp.subscribeToMarketData(['ETH', 'BTC', 'SOL', 'AVAX']);
unsubscribeFromMarketData()
Unsubscribe from market data.
// Unsubscribe from specific symbols
await miniApp.unsubscribeFromMarketData(['ETH']);
// Unsubscribe from all
await miniApp.unsubscribeFromMarketData();
getMarketData()
Get current market data for symbols.
const marketData = await miniApp.getMarketData(['ETH', 'BTC']);
console.log('ETH price:', marketData.ETH.price);
Market Data Events
// Real-time price updates
miniApp.on('marketData', (data: SimpleMarketData) => {
console.log(`${data.symbol}: $${data.price} (${data.change24h > 0 ? '+' : ''}${data.change24h}%)`);
});
// Order book updates
miniApp.on('orderBook', (orderBook) => {
console.log(`${orderBook.symbol} - Best bid: $${orderBook.bestBid}, Best ask: $${orderBook.bestAsk}`);
});
// Trade updates
miniApp.on('trades', (trades) => {
trades.forEach(trade => {
console.log(`Trade: ${trade.quantity} ${trade.symbol} at $${trade.price}`);
});
});
SimpleMarketData Interface
interface SimpleMarketData {
symbol: string; // Trading symbol
price: number; // Current price
change24h: number; // 24h price change percentage
volume24h: number; // 24h trading volume
high24h: number; // 24h high price
low24h: number; // 24h low price
timestamp: number; // Last update timestamp
bestBid?: number; // Best bid price
bestAsk?: number; // Best ask price
}
Account Information
getBalance()
Get account balance information.
// Get all balances
const balances = await miniApp.getBalance();
// Get specific asset balance
const ethBalance = await miniApp.getBalance('ETH');
console.log('ETH Balance:', ethBalance.available);
getPositions()
Get current trading positions.
const positions = await miniApp.getPositions();
positions.forEach(position => {
console.log(`${position.symbol}: ${position.size} (P&L: $${position.unrealizedPnl})`);
});
// Get positions for specific symbol
const ethPositions = await miniApp.getPositions('ETH');
getOrders()
Get current open orders.
// Get all open orders
const orders = await miniApp.getOrders();
// Get orders for specific symbol
const ethOrders = await miniApp.getOrders('ETH');
getTrades()
Get recent trade history.
// Get recent trades
const trades = await miniApp.getTrades();
// Get trades for specific symbol
const ethTrades = await miniApp.getTrades('ETH');
// Get trades with pagination
const oldTrades = await miniApp.getTrades(undefined, { limit: 50, offset: 100 });
Account Events
// Balance updates
miniApp.on('balanceUpdate', (balances) => {
console.log('Balance updated:', balances);
});
// Position updates
miniApp.on('positionUpdate', (positions) => {
console.log('Positions updated:', positions);
});
// Order updates
miniApp.on('orderUpdate', (orders) => {
console.log('Orders updated:', orders);
});
Event System
Event Types
type SimpleEventType =
| 'connected' // Connection established
| 'disconnected' // Connection lost
| 'connectionError' // Connection error
| 'reconnecting' // Attempting to reconnect
| 'marketData' // Market data update
| 'orderBook' // Order book update
| 'trades' // Trade feed update
| 'orderConfirmation' // Order executed
| 'orderRejection' // Order rejected
| 'orderCancelled' // Order cancelled
| 'tradeExecution' // Trade executed
| 'balanceUpdate' // Balance changed
| 'positionUpdate' // Position changed
| 'orderUpdate' // Order status changed
| 'error'; // General error
Event Methods
// Add event listener
miniApp.on('marketData', (data) => {
console.log('Market data:', data);
});
// Add one-time listener
miniApp.once('connected', () => {
console.log('Connected for the first time!');
});
// Remove specific listener
const handler = (data) => console.log(data);
miniApp.on('marketData', handler);
miniApp.off('marketData', handler);
// Remove all listeners for an event
miniApp.off('marketData');
// Remove all listeners
miniApp.removeAllListeners();
Error Handling
Error Types
enum SimpleErrorType {
CONNECTION_ERROR = 'connection',
PERMISSION_ERROR = 'permission',
VALIDATION_ERROR = 'validation',
TRADING_ERROR = 'trading',
NETWORK_ERROR = 'network'
}
class SimpleError extends Error {
constructor(
public type: SimpleErrorType,
message: string,
public code?: string,
public recoverable = true
) {
super(message);
this.name = 'SimpleError';
}
}
Error Handling Patterns
// Try-catch pattern
try {
await miniApp.placeOrder(orderData);
} catch (error) {
if (error instanceof SimpleError) {
switch (error.type) {
case SimpleErrorType.PERMISSION_ERROR:
console.log('Need permissions:', error.message);
await miniApp.requestTradingPermissions();
break;
case SimpleErrorType.TRADING_ERROR:
console.error('Trading error:', error.message);
break;
default:
console.error('Unknown error:', error.message);
}
}
}
// Global error handler
miniApp.on('error', (error: SimpleError) => {
console.error(`${error.type}: ${error.message}`);
if (error.recoverable) {
// Implement recovery logic
console.log('Attempting to recover...');
}
});
// Specific error handlers
miniApp.on('connectionError', async (error) => {
console.log('Connection lost, attempting to reconnect...');
// The SDK handles reconnection automatically
});
miniApp.on('orderRejection', (rejection) => {
console.error('Order rejected:', rejection.reason);
// Handle specific rejection reasons
switch (rejection.code) {
case 'INSUFFICIENT_BALANCE':
console.log('Not enough balance for this order');
break;
case 'PRICE_TOO_HIGH':
console.log('Order price is too high');
break;
}
});
Complete Example: DCA Bot
Here's a complete example of a Dollar Cost Averaging (DCA) bot using the Simple API:
import { createSimpleMiniApp, SimpleMarketData, SimpleError } from '@basedone/miniapp-sdk/simple';
class DCABot {
private miniApp;
private dcaConfig = {
symbol: 'ETH',
buyAmount: 0.01, // Buy 0.01 ETH each time
intervalMs: 3600000, // Every hour
maxPrice: 3000, // Don't buy above $3000
minPrice: 1500, // Don't buy below $1500 (might be a crash)
};
private intervalId?: NodeJS.Timeout;
private currentPrice = 0;
constructor() {
this.miniApp = createSimpleMiniApp({
appId: 'dca-bot',
autoConnect: true,
debug: true,
reconnectAttempts: 5,
requestedPermissions: [
'trading_read',
'trading_write',
'market_data_read',
'account_read'
]
});
this.setupEventHandlers();
}
private setupEventHandlers() {
// Connection events
this.miniApp.on('connected', () => {
console.log('π’ DCA Bot connected to terminal');
});
this.miniApp.on('disconnected', () => {
console.log('π΄ DCA Bot disconnected');
this.stop(); // Stop DCA when disconnected
});
// Market data events
this.miniApp.on('marketData', (data: SimpleMarketData) => {
if (data.symbol === this.dcaConfig.symbol) {
this.currentPrice = data.price;
console.log(`π ${data.symbol} price: $${data.price}`);
}
});
// Trading events
this.miniApp.on('orderConfirmation', (order) => {
console.log(`β
DCA order executed: ${order.side} ${order.quantity} ${order.symbol} @ $${order.price}`);
this.logPortfolioStatus();
});
this.miniApp.on('orderRejection', (rejection) => {
console.error(`β DCA order rejected: ${rejection.reason}`);
});
// Error handling
this.miniApp.on('error', (error: SimpleError) => {
console.error(`π¨ Error: ${error.type} - ${error.message}`);
if (!error.recoverable) {
this.stop();
}
});
}
async start() {
try {
console.log('π Starting DCA Bot...');
// Wait for connection
await this.miniApp.waitForConnection();
// Request permissions
await this.miniApp.requestTradingPermissions();
console.log('β
Trading permissions granted');
// Subscribe to market data
await this.miniApp.subscribeToMarketData([this.dcaConfig.symbol]);
console.log(`β
Subscribed to ${this.dcaConfig.symbol} market data`);
// Log initial status
await this.logPortfolioStatus();
// Start DCA interval
this.startDCAInterval();
console.log(`π― DCA Bot started! Buying $${this.dcaConfig.buyAmount} ${this.dcaConfig.symbol} every ${this.dcaConfig.intervalMs / 1000}s`);
} catch (error) {
console.error('β Failed to start DCA Bot:', error);
}
}
private startDCAInterval() {
this.intervalId = setInterval(async () => {
await this.executeDCABuy();
}, this.dcaConfig.intervalMs);
// Execute first buy immediately
setTimeout(() => this.executeDCABuy(), 5000);
}
private async executeDCABuy() {
try {
console.log('π° Executing DCA buy...');
// Check if price is within acceptable range
if (this.currentPrice > this.dcaConfig.maxPrice) {
console.log(`βΈοΈ Skipping buy - price $${this.currentPrice} above max $${this.dcaConfig.maxPrice}`);
return;
}
if (this.currentPrice < this.dcaConfig.minPrice) {
console.log(`βΈοΈ Skipping buy - price $${this.currentPrice} below min $${this.dcaConfig.minPrice}`);
return;
}
// Check available balance
const balance = await this.miniApp.getBalance('USDT');
const requiredBalance = this.dcaConfig.buyAmount * this.currentPrice;
if (balance.available < requiredBalance) {
console.log(`βΈοΈ Insufficient balance: need $${requiredBalance.toFixed(2)}, have $${balance.available.toFixed(2)}`);
return;
}
// Execute buy order
const order = await this.miniApp.quickBuy(this.dcaConfig.symbol, this.dcaConfig.buyAmount);
console.log(`π DCA buy order placed: ${order.id}`);
} catch (error) {
console.error('β DCA buy failed:', error);
}
}
private async logPortfolioStatus() {
try {
const [positions, balance] = await Promise.all([
this.miniApp.getPositions(),
this.miniApp.getBalance()
]);
const ethPosition = positions.find(p => p.symbol === this.dcaConfig.symbol);
const usdtBalance = balance.find(b => b.asset === 'USDT');
console.log('π Portfolio Status:');
console.log(` ${this.dcaConfig.symbol} Holdings: ${ethPosition?.size || 0} (Value: $${(ethPosition?.marketValue || 0).toFixed(2)})`);
console.log(` USDT Balance: $${(usdtBalance?.available || 0).toFixed(2)}`);
if (ethPosition && ethPosition.unrealizedPnl !== 0) {
console.log(` Unrealized P&L: $${ethPosition.unrealizedPnl.toFixed(2)}`);
}
} catch (error) {
console.error('β Failed to get portfolio status:', error);
}
}
async stop() {
console.log('βΉοΈ Stopping DCA Bot...');
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
await this.miniApp.unsubscribeFromMarketData([this.dcaConfig.symbol]);
await this.miniApp.disconnect();
console.log('β
DCA Bot stopped');
}
// Update DCA configuration
updateConfig(newConfig: Partial<typeof this.dcaConfig>) {
this.dcaConfig = { ...this.dcaConfig, ...newConfig };
console.log('β
DCA configuration updated:', this.dcaConfig);
// Restart interval with new timing
if (newConfig.intervalMs && this.intervalId) {
clearInterval(this.intervalId);
this.startDCAInterval();
}
}
// Get current status
getStatus() {
return {
connected: this.miniApp.isConnected(),
currentPrice: this.currentPrice,
config: this.dcaConfig,
nextBuyIn: this.intervalId ? 'Running' : 'Stopped'
};
}
}
// Usage
const dcaBot = new DCABot();
// Start the bot
dcaBot.start();
// Update configuration while running
setTimeout(() => {
dcaBot.updateConfig({
buyAmount: 0.02, // Increase buy amount
maxPrice: 3500 // Increase max price
});
}, 10000);
// Log status every 30 seconds
setInterval(() => {
console.log('π Bot Status:', dcaBot.getStatus());
}, 30000);
API Reference Summary
Core Methods
createSimpleMiniApp(config)
- Create MiniApp instanceconnect()
- Connect to terminaldisconnect()
- Disconnect from terminalwaitForConnection()
- Wait for connection
Permissions
requestPermission(permission)
- Request specific permissionrequestTradingPermissions()
- Request all trading permissionshasPermission(permission)
- Check permission statusgetPermissions()
- Get all permissions
Trading
placeOrder(orderData)
- Place order with full controlquickBuy(symbol, quantity)
- Market buy orderquickSell(symbol, quantity)
- Market sell orderlimitOrder(symbol, side, quantity, price)
- Limit ordercancelOrder(orderId)
- Cancel specific ordercancelAllOrders(symbol?)
- Cancel all orders
Market Data
subscribeToMarketData(symbols)
- Subscribe to pricesunsubscribeFromMarketData(symbols?)
- UnsubscribegetMarketData(symbols)
- Get current prices
Account
getBalance(asset?)
- Get balance informationgetPositions(symbol?)
- Get trading positionsgetOrders(symbol?)
- Get open ordersgetTrades(symbol?, options?)
- Get trade history
Events
on(event, handler)
- Add event listeneronce(event, handler)
- Add one-time listeneroff(event, handler?)
- Remove event listenerremoveAllListeners()
- Remove all listeners
Next: React Integration Guide β Building UIs with React
Last updated