Quick Start Guide
Quick Start Guide: Build Your First MiniApp in 5 Minutes
Get up and running with your first Based.One MiniApp quickly. This guide will walk you through creating a simple trading bot that automatically places buy orders when prices drop below a threshold.
Prerequisites
Node.js 16+ installed
Basic knowledge of JavaScript/TypeScript
Step 1: Create Your Project (30 seconds)
# Create a new directory for your MiniApp
mkdir my-first-miniapp
cd my-first-miniapp
# Initialize a new Node.js project
npm init -y
# Install the MiniApp SDK
npm install @basedone/miniapp-sdk
Step 2: Create Your First MiniApp (2 minutes)
Option A: React MiniApp (Recommended for UI)
Create a React app with interactive trading interface:
# Create React app with TypeScript
npx create-react-app my-first-miniapp --template typescript
cd my-first-miniapp
# Install MiniApp SDK
npm install @basedone/miniapp-sdk
Replace src/App.tsx
:
// src/App.tsx
import React, { useState } from 'react';
import {
SimpleMiniAppProvider,
useSimpleMiniApp,
useSimpleMarketData,
SimpleOrderForm
} from '@basedone/miniapp-sdk/react';
import './App.css';
function TradingBot() {
const { connected, connectionStatus } = useSimpleMiniApp({
appId: 'my-first-react-bot'
});
const { marketData } = useSimpleMarketData(['ETH', 'BTC']);
const [priceThreshold, setPriceThreshold] = useState(2500);
const [autoBuyEnabled, setAutoBuyEnabled] = useState(false);
// Auto-buy logic when price drops below threshold
React.useEffect(() => {
if (!autoBuyEnabled || !marketData.ETH) return;
const ethPrice = marketData.ETH.price;
if (ethPrice < priceThreshold) {
console.log(`🎯 ETH at $${ethPrice} - below threshold $${priceThreshold}!`);
// Auto-buy logic would go here
}
}, [marketData.ETH?.price, priceThreshold, autoBuyEnabled]);
if (!connected) {
return (
<div style={{ padding: '20px', textAlign: 'center' }}>
<h2>🤖 Simple Trading Bot</h2>
<p>Status: {connectionStatus}</p>
<div>Connecting to Based.One terminal...</div>
</div>
);
}
return (
<div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
<h1>🤖 Simple Trading Bot</h1>
{/* Connection Status */}
<div style={{
background: '#e8f5e8',
padding: '10px',
borderRadius: '5px',
marginBottom: '20px'
}}>
✅ Connected to Based.One terminal
</div>
{/* Market Data */}
<div style={{ marginBottom: '30px' }}>
<h2>📊 Market Data</h2>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '15px' }}>
{Object.entries(marketData).map(([symbol, data]) => (
<div key={symbol} style={{
border: '1px solid #ddd',
padding: '15px',
borderRadius: '8px',
background: data.change24h >= 0 ? '#f0f9f0' : '#fff0f0'
}}>
<h3 style={{ margin: '0 0 10px 0' }}>{symbol}</h3>
<div style={{ fontSize: '24px', fontWeight: 'bold' }}>
${data.price.toLocaleString()}
</div>
<div style={{
color: data.change24h >= 0 ? 'green' : 'red',
fontSize: '14px'
}}>
{data.change24h >= 0 ? '+' : ''}{data.change24h.toFixed(2)}% (24h)
</div>
</div>
))}
</div>
</div>
{/* Auto-Buy Settings */}
<div style={{ marginBottom: '30px' }}>
<h2>🎯 Auto-Buy Settings</h2>
<div style={{
border: '1px solid #ddd',
padding: '20px',
borderRadius: '8px',
background: '#f9f9f9'
}}>
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'block', marginBottom: '5px' }}>
ETH Price Threshold: ${priceThreshold}
</label>
<input
type="range"
min="2000"
max="4000"
step="50"
value={priceThreshold}
onChange={(e) => setPriceThreshold(Number(e.target.value))}
style={{ width: '100%' }}
/>
</div>
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<input
type="checkbox"
checked={autoBuyEnabled}
onChange={(e) => setAutoBuyEnabled(e.target.checked)}
/>
Enable Auto-Buy (Buy when ETH drops below threshold)
</label>
</div>
<div style={{
padding: '10px',
background: autoBuyEnabled ? '#fff3cd' : '#f8f9fa',
border: `1px solid ${autoBuyEnabled ? '#ffc107' : '#dee2e6'}`,
borderRadius: '5px',
fontSize: '14px'
}}>
{autoBuyEnabled ?
`⚡ Auto-buy ACTIVE: Will buy 0.01 ETH when price drops below $${priceThreshold}` :
'⏸️ Auto-buy DISABLED: Manual trading only'
}
</div>
</div>
</div>
{/* Manual Trading */}
<div style={{ marginBottom: '30px' }}>
<h2>💰 Manual Trading</h2>
<SimpleOrderForm
symbols={['ETH', 'BTC']}
defaultSymbol="ETH"
style={{
border: '1px solid #ddd',
padding: '20px',
borderRadius: '8px'
}}
/>
</div>
{/* Trading History */}
<div>
<h2>📈 Recent Activity</h2>
<div style={{
border: '1px solid #ddd',
padding: '20px',
borderRadius: '8px',
minHeight: '100px',
background: '#f9f9f9'
}}>
<p style={{ color: '#666' }}>
Recent trades and orders will appear here...
</p>
</div>
</div>
</div>
);
}
function App() {
return (
<SimpleMiniAppProvider appId="my-first-react-bot" autoConnect>
<div className="App">
<TradingBot />
</div>
</SimpleMiniAppProvider>
);
}
export default App;
Step 3: Run Your MiniApp (30 seconds)
For React App
# Start the React development server
npm start
Your browser will open to http://localhost:3000
showing your trading bot interface with:
✅ Real-time ETH and BTC price displays
🎯 Interactive auto-buy threshold slider
💰 Manual trading form with order placement
📊 Market data updates in real-time
Step 4: Customize Your Bot (1 minute)
Now that your bot is running, try customizing it:
// Change the asset and parameters
this.priceThreshold = 40000; // Watch BTC instead
this.buyAmount = 0.001; // Smaller position size
// Subscribe to different markets
await this.miniApp.subscribeToMarketData(['BTC', 'ETH', 'SOL']);
// Add more sophisticated logic
handlePriceUpdate(marketData) {
const { symbol, price, volume24h } = marketData;
// Only trade if there's sufficient volume
if (volume24h > 1000000) {
// Your trading logic here...
}
}
What Just Happened?
Congratulations! You've just built a functional trading bot with:
✅ Real-time market data - Your bot receives live price feeds ✅ Automated trading - Orders are placed automatically based on conditions ✅ Permission management - Users control what your bot can access ✅ Error handling - Robust error handling keeps your bot running ✅ Event-driven architecture - React to market changes in real-time
Next Steps
🎨 Add a User Interface
Want to add controls and displays? Try the React version:
// App.jsx
import React from 'react';
import { SimpleMiniAppProvider, useSimpleMiniApp, SimpleOrderForm } from '@basedone/miniapp-sdk/react';
function TradingBot() {
const { marketData, connected } = useSimpleMiniApp({ appId: 'my-bot-ui' });
if (!connected) return <div>Connecting to terminal...</div>;
return (
<div style={{ padding: '20px' }}>
<h1>My Trading Bot</h1>
<div>
<h3>Current Prices</h3>
{marketData.map(data => (
<div key={data.symbol}>
{data.symbol}: ${data.price}
</div>
))}
</div>
<SimpleOrderForm symbols={['ETH', 'BTC']} />
</div>
);
}
function App() {
return (
<SimpleMiniAppProvider appId="my-bot-ui">
<TradingBot />
</SimpleMiniAppProvider>
);
}
export default App;
📚 Learn More Advanced Features
Architecture Guide - Understand how MiniApps work internally
Simple API Reference - Complete API documentation with examples
React Integration - Build interactive UIs with React
Trading Strategies - Advanced trading bot patterns
🔧 Common Customizations
Add Multiple Assets:
await this.miniApp.subscribeToMarketData(['ETH', 'BTC', 'SOL', 'AVAX']);
Implement Stop Loss:
async placeOrderWithStopLoss(symbol, quantity, stopLossPrice) {
const order = await this.miniApp.quickBuy(symbol, quantity);
// Set stop loss
await this.miniApp.placeOrder({
symbol,
side: 'sell',
type: 'stop_loss',
quantity,
stopPrice: stopLossPrice
});
}
Add Portfolio Tracking:
// Get current positions
const positions = await this.miniApp.getPositions();
const totalValue = positions.reduce((sum, pos) => sum + pos.marketValue, 0);
console.log(`Portfolio value: $${totalValue}`);
Troubleshooting
Connection Issues
// Add connection retry logic
const miniApp = createSimpleMiniApp({
appId: 'my-bot',
autoConnect: true,
reconnectAttempts: 5,
reconnectDelay: 2000
});
Permission Denied
try {
await this.miniApp.requestTradingPermissions();
} catch (error) {
console.log('Trading permissions required. Please approve in the terminal.');
}
Order Failures
this.miniApp.on('orderError', (error) => {
console.error('Order failed:', error.message);
// Implement retry logic or fallback strategy
});
Security Reminders
⚠️ Important Security Notes:
Start with small position sizes while testing
Always implement proper error handling
Test thoroughly before using real funds
Congratulations! 🎉
You've successfully built and deployed your first MiniApp! This simple bot demonstrates the core concepts:
Connecting to the Based.One terminal
Requesting permissions
Subscribing to market data
Placing automated trades
Handling real-time events
Ready to build something more complex? Check out the Complete Tutorial Series or explore Advanced Examples.
Next: Installation & Setup → Learn about development environments and tooling
Last updated