Agent SDK
The @monohub/agent-sdk is a TypeScript library for building automated trading agents that interact with MonoHub's on-chain contracts and Trading API. It provides a high-level MonoHubAgent class, a strategy framework with built-in templates, and REST + WebSocket clients for market data and order execution.
Installation
npm install @monohub/agent-sdk
The SDK is ESM-only and requires Node.js 18+. It depends on viem (for chain interaction) and ws (for WebSocket).
Quick Start
import { MonoHubAgent, createMomentumStrategy } from "@monohub/agent-sdk";
const agent = new MonoHubAgent({
apiUrl: "https://api.monohub.xyz",
apiKey: process.env.MONOHUB_API_KEY,
chainId: 262146, // Sprintnet
dryRun: true, // Simulate trades without executing
logLevel: "info",
strategies: [
createMomentumStrategy({
rsiThreshold: 70,
priceChangeThreshold: 0.05,
maxPositionSize: 0.1,
}),
],
});
// Event handlers
agent.on("started", () => console.log("Agent started"));
agent.on("trade", (data) => console.log("Trade:", data));
agent.on("dry-run", (data) => console.log("[DRY RUN]:", data));
agent.on("error", (err) => console.error("Error:", err));
// Start and watch markets
await agent.start();
const markets = await agent.getMarkets();
const topMarkets = markets
.sort((a, b) => parseFloat(b.volume24h) - parseFloat(a.volume24h))
.slice(0, 3);
for (const market of topMarkets) {
await agent.watchMarket(market.pair);
}
// Graceful shutdown
process.on("SIGINT", async () => {
await agent.stop();
process.exit(0);
});
Core Concepts
MonoHubAgent
The MonoHubAgent class is the main entry point. It orchestrates API clients, WebSocket connections, strategy evaluation, and trade execution. It extends EventEmitter and emits the following events:
| Event | Payload | Description |
|---|---|---|
started | -- | Agent has connected and is running |
stopped | -- | Agent has shut down |
trade | { pair, strategy, decision, order } | A trade was executed |
dry-run | { pair, strategy, decision } | A trade would have been executed (dry run mode) |
error | { type, error } | An error occurred |
log | { level, message, data, timestamp } | Log output from the agent |
AgentConfig
interface AgentConfig {
apiUrl: string; // MonoHub Trading API base URL
apiKey?: string; // API key for authentication
chainId?: ChainId; // Target chain (default: 262146 Sprintnet)
rpcUrl?: string; // Custom RPC URL (optional)
privateKey?: `0x${string}`; // Wallet private key for on-chain execution
strategies?: Strategy[]; // Initial strategies to register
autoTrade?: boolean; // Auto-evaluate strategies on ticker updates
dryRun?: boolean; // Simulate trades without executing (default: false)
logLevel?: "debug" | "info" | "warn" | "error"; // Default: "info"
}
Agent Methods
| Method | Description |
|---|---|
start() | Connect WebSocket, start strategy loops |
stop() | Disconnect and clean up |
registerStrategy(strategy) | Add a strategy at runtime |
unregisterStrategy(name) | Remove a strategy by name |
watchMarket(pair) | Fetch market data and subscribe to real-time updates |
unwatchMarket(pair) | Stop watching a market |
evaluateStrategies(pair) | Manually trigger strategy evaluation for a pair |
getState() | Returns current AgentState (running, strategies, trade count, PnL) |
getApi() | Returns the underlying ApiClient instance |
getWs() | Returns the underlying WsClient instance |
getMarkets() | Fetch all available markets |
getRisk(tokenAddress) | Fetch risk score for a token |
placeOrder(pair, side, amount) | Place a trade directly |
Strategy Framework
Strategies are objects that implement the Strategy interface. The agent calls evaluate() on each strategy whenever a watched market receives a ticker update (when autoTrade is enabled), or when evaluateStrategies() is called manually.
A trade is only executed when the strategy returns an action of buy or sell with a confidence score of 0.7 or higher.
Strategy Interface
interface Strategy {
name: string;
description?: string;
// Risk management
maxPositionSize: number; // Max % of portfolio per trade (0-1)
maxPortfolioRisk: number; // Max total portfolio at risk (0-1)
stopLoss?: number; // Stop loss percentage (0-1)
takeProfit?: number; // Take profit percentage (0-1)
minRiskScore?: number; // Minimum token risk score (0-100)
// Core method
evaluate(context: StrategyContext): Promise<StrategyDecision>;
// Lifecycle hooks
onStart?(): Promise<void>;
onStop?(): Promise<void>;
onTrade?(trade: Trade): Promise<void>;
onError?(error: Error): Promise<void>;
}
StrategyContext
Each call to evaluate() receives a context object with current market data:
interface StrategyContext {
market: Market; // Current market data (price, volume, etc.)
recentTrades: Trade[]; // Last 20 trades
portfolio: {
balance: string;
valueUsd: string;
};
indicators: StrategyIndicators; // Calculated technical indicators
risk?: RiskScore; // Token risk score (if available)
}
interface StrategyIndicators {
rsi?: number; // Relative Strength Index (14-period)
sma?: number; // Simple Moving Average (20-period)
ema?: number; // Exponential Moving Average (20-period)
volume24h?: number; // 24h volume
priceChange24h?: number;
volatility?: number;
}
StrategyDecision
interface StrategyDecision {
action: "buy" | "sell" | "hold";
amount?: string; // Trade amount (optional)
confidence: number; // 0-1, trades execute at >= 0.7
reason: string; // Human-readable explanation
}
Built-in Strategy Templates
The SDK ships with four configurable strategy templates.
Momentum Strategy
Buys tokens with strong upward momentum. Sells when RSI indicates overbought conditions.
import { createMomentumStrategy } from "@monohub/agent-sdk";
const strategy = createMomentumStrategy({
rsiThreshold: 70, // Sell above this RSI (default: 70)
priceChangeThreshold: 0.05, // Buy above 5% 24h change (default: 0.05)
maxPositionSize: 0.1, // Max 10% of portfolio per trade
});
DCA (Dollar Cost Averaging) Strategy
Buys a fixed amount at regular intervals regardless of price.
import { createDcaStrategy } from "@monohub/agent-sdk";
const strategy = createDcaStrategy({
buyAmountUsd: 100, // Buy $100 worth each interval
intervalMinutes: 60, // Every 60 minutes
maxPositionSize: 0.2, // Max 20% of portfolio
});
Grid Trading Strategy
Places buy and sell orders at regular price intervals around the current price.
import { createGridStrategy } from "@monohub/agent-sdk";
const strategy = createGridStrategy({
gridLevels: 5, // 5 levels above and below current price
gridSpacing: 0.02, // 2% spacing between levels
amountPerLevel: 100, // $100 per level
});
Mean Reversion Strategy
Buys dips and sells rallies based on deviation from the moving average.
import { createMeanReversionStrategy } from "@monohub/agent-sdk";
const strategy = createMeanReversionStrategy({
deviationThreshold: 0.1, // Trade at 10% deviation from mean
lookbackPeriod: 24, // Calculate mean over 24 candles
maxPositionSize: 0.15,
});
API Client
The ApiClient class provides typed access to all Trading API endpoints. It can be used standalone or accessed via agent.getApi().
import { ApiClient } from "@monohub/agent-sdk";
const api = new ApiClient({
baseUrl: "https://api.monohub.xyz",
apiKey: "your-api-key",
chainId: 262146,
});
// Market data
const markets = await api.getMarkets();
const market = await api.getMarket("0xPairAddress");
const trades = await api.getTrades("0xPairAddress", 50);
const candles = await api.getCandles("0xPairAddress", "1h", 100);
const orderbook = await api.getOrderbook("0xPairAddress");
// Account (requires auth)
const account = await api.getAccount();
const balances = await api.getBalances(["0xToken1", "0xToken2"]);
const history = await api.getTradeHistory(50);
// Trading (requires auth with trade permission)
const quote = await api.getQuote("0xPairAddress", "buy", "1000000000000000000");
const order = await api.placeOrder("0xPairAddress", "buy", "1000000000000000000");
const orders = await api.getOrders();
await api.cancelOrder("ord_123");
// Risk analysis
const risk = await api.getRisk("0xTokenAddress");
WebSocket Client
The WsClient class provides real-time streaming. It extends EventEmitter, supports automatic reconnection, and re-subscribes to channels after reconnecting.
import { WsClient } from "@monohub/agent-sdk";
const ws = new WsClient({
baseUrl: "https://api.monohub.xyz",
apiKey: "your-api-key",
reconnect: true, // Auto-reconnect (default: true)
reconnectInterval: 5000, // 5 seconds between retries
});
await ws.connect();
// Subscribe to channels
ws.subscribeTrades("0xPairAddress");
ws.subscribeTicker("0xPairAddress");
ws.subscribeOrderbook("0xPairAddress");
ws.subscribeCandles("0xPairAddress", "1h");
// User channels (requires auth)
ws.subscribeOrders();
ws.subscribeFills();
// Listen for data
ws.on("trades", (msg) => console.log("Trade update:", msg));
ws.on("ticker", (msg) => console.log("Ticker:", msg));
ws.on("connected", () => console.log("Connected"));
ws.on("disconnected", () => console.log("Disconnected"));
// Heartbeat
ws.ping();
// Cleanup
ws.disconnect();
Contract Interaction
The SDK exports ABI constants and contract addresses for Monolythium protocol contracts. These are used internally and can also be used for direct on-chain interaction with viem.
import { addresses, AgentRegistryAbi, AgentLaunchpadAbi, AgentArenaAbi } from "@monohub/agent-sdk";
// Contract addresses per chain
console.log(addresses.sprintnet.agentRegistry);
console.log(addresses.sprintnet.agentLaunchpad);
console.log(addresses.sprintnet.agentArena);
Chain Configuration
The SDK includes viem chain definitions for supported networks:
import { sprintnet, avalancheFuji, lineaSepolia, CHAINS } from "@monohub/agent-sdk";
// Use with viem
import { createPublicClient, http } from "viem";
const client = createPublicClient({
chain: sprintnet,
transport: http(),
});
| Chain ID | Name | Native Token |
|---|---|---|
| 262146 | Sprintnet | LYTH |
| 43113 | Avalanche Fuji | AVAX |
| 59141 | Linea Sepolia | ETH |
TypeScript Types
All types are exported from the package root:
import type {
// Config
ChainId,
SdkConfig,
AgentConfig,
AgentState,
// API types
ApiClientOptions,
AuthResponse,
Market,
Trade,
Candle,
OrderQuote,
Order,
AccountBalance,
RiskScore,
// WebSocket types
WsClientOptions,
WsMessage,
Channel,
UserChannel,
TradeData,
TickerData,
// Strategy types
Strategy,
StrategyConfig,
StrategyContext,
StrategyDecision,
StrategyIndicators,
StrategyTemplate,
} from "@monohub/agent-sdk";
Best Practices
-
Always start with
dryRun: true. Verify your strategy logic with dry-run mode before enabling real trades. Dry-run events are emitted asdry-runon the agent. -
Use API keys for bots. Create a dedicated API key with only the permissions your agent needs (
readfor monitoring,read+tradefor trading). This limits exposure if the key is compromised. -
Set risk management parameters. Every strategy template accepts
maxPositionSize,stopLoss,takeProfit, andminRiskScore. Configure these to limit downside risk. -
Check token risk scores. The
getRisk()method returns a score (0-100) and grade (A-F). Strategies can filter onminRiskScoreto avoid low-quality tokens. -
Handle errors and shutdowns gracefully. Register
onErrorhooks on strategies and listen for theerrorevent on the agent. Useprocess.on('SIGINT')to callagent.stop()for clean shutdown. -
Monitor logs. Set
logLevel: "debug"during development to see strategy decisions, trade execution details, and WebSocket activity. -
Respect rate limits. The free tier allows 60 requests per minute. If running multiple agents, use API keys and consider upgrading to Basic (300/min) or Pro (1,200/min).