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
A code editor (VS Code recommended)
Step 1: Create Your Project (30 seconds)
# 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-sdkStep 2: Add MiniApp Logic (2 minutes)
Replace src/App.tsx:
// src/App.tsx
import React, { useState } from 'react';
import {
BasedMiniAppProvider,
useMiniApp,
useMarketData
} from '@basedone/miniapp-sdk/react';
import './App.css';
function TradingBot() {
const { connected, connecting } = useMiniApp();
const marketData = useMarketData(['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>🤖 Trading Bot</h2>
<p>Status: {connecting ? 'Connecting...' : 'Disconnected'}</p>
<div>Connecting to Based.One terminal...</div>
</div>
);
}
return (
<div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
<h1>🤖 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>
{/* Order form component would go here */}
<div style={{
border: '1px solid #ddd',
padding: '20px',
borderRadius: '8px'
}}>
<p>Order placement UI here</p>
</div>
</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 (
<BasedMiniAppProvider config={{ appId: 'my-first-react-bot', autoConnect: true }}>
<div className="App">
<TradingBot />
</div>
</BasedMiniAppProvider>
);
}
export default App;Step 3: Run Your MiniApp (30 seconds)
# Start the React development server
npm startYour 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. Load miniapp on our testkit
Visit https://testnet.based.one
Click bug icon on lower right hand corner
Enter appId (12-letter alphanumeric) and url: http://localhost:3000
Load app

You should see console output like this:
🤖 Starting Trade Bot...
✅ Connected to Based.One terminal
✅ Trading permissions granted
✅ Subscribed to ETH market data
🚀 Bot is now running! Watching for ETH price drops...
📊 ETH Price: $2487.50
🎯 Price trigger activated! ETH at $2487.50, buying 0.01 ETH...
📈 Buy order placed successfully!
📝 New threshold set to: $2462.63Step 5: 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.sdk.subscribeToMarkets(['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 { BasedMiniAppProvider, useMiniApp } from '@basedone/miniapp-sdk/react';
function TradingBot() {
const { marketData, connected } = useMiniApp();
if (!connected) return <div>Connecting to terminal...</div>;
return (
<div style={{ padding: '20px' }}>
<h1>My Trading Bot</h1>
<div>
<h3>Current Prices</h3>
{Object.entries(marketData).map(([symbol, data]) => (
<div key={symbol}>
{symbol}: ${data.price}
</div>
))}
</div>
{/* Order form component would go here */}
</div>
);
}
function App() {
return (
<BasedMiniAppProvider config={{ appId: 'my-bot-ui' }}>
<TradingBot />
</BasedMiniAppProvider>
);
}
export default App;🔧 Common Customizations
Add Multiple Assets:
await this.sdk.subscribeToMarkets(['ETH', 'BTC', 'SOL', 'AVAX']);Implement Stop Loss:
async placeOrderWithStopLoss(symbol, size, stopLossPrice) {
const order = await this.sdk.placeOrder({
symbol,
side: 'buy',
orderType: 'market',
size
});
// Set stop loss
await this.sdk.placeOrder({
symbol,
side: 'sell',
orderType: 'market',
size,
tpsl: {
slLossPercent: 5,
}
});
}Add Portfolio Tracking:
// Get current positions
const positions = await this.sdk.getPositions();
const totalValue = positions.reduce((sum, pos) => sum + pos.marketValue, 0);
console.log(`Portfolio value: $${totalValue}`);Troubleshooting
Connection Issues
// Add connection retry logic
const sdk = new MiniAppSDK({
appId: 'my-bot',
autoConnect: true
});
// Manual retry logic if needed
let retries = 5;
while (retries > 0) {
try {
await sdk.connect();
break;
} catch (error) {
retries--;
await new Promise(r => setTimeout(r, 2000));
}
}Permission Denied
try {
await this.sdk.requestPermissions(['place_orders', 'read_market_data']);
} catch (error) {
console.log('Trading permissions required. Please approve in the terminal.');
}Order Failures
this.sdk.on('error', (error) => {
console.error('Order failed:', error.message);
// Implement retry logic or fallback strategy
});Security Reminders
⚠️ Important Security Notes:
Never share your private keys or API credentials
Start with small position sizes while testing
Always implement proper error handling
Test thoroughly before using real funds
Monitor your bots regularly
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