Workflows & Recipes

Build a crypto trading bot with live data

Written by Rishabh Narang, CEO, Hive IntelligenceLast updated

This guide shows how to wire an AI-driven crypto trading bot to live market data, DEX liquidity, perpetual funding rates, and token-security signals through one MCP endpoint. You'll build a reusable pre-trade check function, run a worked example on a live pool, and produce an execution plan your own controlled trading system can review before placing orders.


Why trading bots need more than a price feed

A naive bot asks "what is the price?" and acts on it. A production trading workflow answers four questions before any order is considered:

  1. Is the market priced correctly? Spot price and short-term OHLC from CoinGecko or a DEX aggregator.
  2. Is there enough liquidity to enter and exit? Pool depth and price impact from Codex or DeFiLlama.
  3. Is this leg financially expensive to hold? Funding rates and basis across exchanges via CCXT.
  4. Does the token trigger risk flags? Honeypot flags, owner privileges, and tax walls from GoPlus.

Four questions, four providers, four auth schemes, four rate limiters. Without a unified data layer, teams often leave out one or two checks because the integration cost is high. Hive consolidates those four signals behind one MCP endpoint and one API key.


Architecture overview

text
             ┌────────────────────────┐
             │    Your trading bot    │
             │  (Python / Node / Go)  │
             └───────────┬────────────┘
                         │  one MCP / REST call per signal
                         ▼
             ┌────────────────────────┐
             │ Hive Intelligence MCP  │
             │   mcp.hiveintelligence │
             └─┬──────┬──────┬─────┬──┘
               │      │      │     │
        CoinGecko  Codex  CCXT   GoPlus  (+ 5 more providers)

The bot speaks one protocol (MCP or REST). Hive routes each tool call to the correct provider, applies a single credit, and returns provider data with consistent Hive execution metadata. No upstream keys to rotate, no per-provider retry logic.


Prerequisites

  • A Hive API key from /dashboard/keys. Your plan controls monthly credits and rate limits; check Pricing and Rate Limits before running high-frequency polling, multi-pair scans, or production traffic.
  • Node.js 20+ or Python 3.11+ depending on which example you follow.
  • Familiarity with async/await.

Step 1: Configure your client

Use the REST execute endpoint for production code, or install the TypeScript adapter with npm install hive-mcp-client:

bash
export HIVE_API_KEY=hive_live_...
javascript
const HIVE_BASE_URL = 'https://mcp.hiveintelligence.xyz'

async function callHive(tool, args) {
  const response = await fetch(`${HIVE_BASE_URL}/api/v1/execute`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.HIVE_API_KEY}`,
    },
    body: JSON.stringify({ tool, args }),
  })

  if (!response.ok) {
    throw new Error(`Hive ${tool} failed: ${response.status} ${await response.text()}`)
  }

  return response.json()
}

Every example below maps one-to-one to a POST /api/v1/execute call. If your runtime already speaks MCP, use the root /mcp endpoint and invoke_api_endpoint instead.


Step 2: Build the pre-trade check

The pre-trade check answers all four questions in parallel. Failing any one of them blocks handoff to the trading system.

javascript
export async function preTradeCheck({ tokenAddress, poolAddress, symbol }) {
  const [security, pool, price, funding] = await Promise.all([
    callHive('get_token_security', {
      chainId: '1',
      contract_addresses: tokenAddress,
    }),
    callHive('get_pool_info', {
      poolAddress,
      networkId: 1,
    }),
    callHive('get_price', {
      ids: symbol,
      vs_currencies: 'usd',
    }),
    callHive('get_funding_rate', {
      exchange: 'binance',
      symbol: `${symbol.toUpperCase()}/USDT:USDT`,
    }),
  ])

  const secRecord = security?.result?.[tokenAddress.toLowerCase()] ?? {}
  const isHoneypot = secRecord.is_honeypot === '1'
  const ownerCanMint = secRecord.owner_change_balance === '1'
  const buyTax = Number(secRecord.buy_tax ?? 0)
  const sellTax = Number(secRecord.sell_tax ?? 0)
  const liquidity = Number(pool?.liquidity ?? 0)
  const spot = Number(price?.[symbol]?.usd ?? 0)
  const fundingAnnualized = Number(funding?.fundingRate ?? 0) * 3 * 365 * 100

  const reasons = []
  if (isHoneypot) reasons.push('honeypot flagged')
  if (ownerCanMint) reasons.push('owner can mint')
  if (buyTax > 5 || sellTax > 5) reasons.push(`tax wall (${buyTax}%/${sellTax}%)`)
  if (liquidity < 100_000) reasons.push(`thin liquidity ($${liquidity})`)
  if (Math.abs(fundingAnnualized) > 50) reasons.push(`extreme funding (${fundingAnnualized.toFixed(1)}% APR)`)

  return {
    safe: reasons.length === 0,
    reasons,
    liquidity,
    spot,
    fundingAnnualized,
  }
}

Four tool calls run in parallel via Promise.all. Total latency is bounded by the slowest provider response, so production bots should log fetched_at, duration_ms, and provider status before acting on an opportunity.

Expected shape of the result:

json
{
  "safe": false,
  "reasons": ["thin liquidity ($42000)"],
  "liquidity": 42000,
  "spot": 0.00001342,
  "fundingAnnualized": 12.4
}

Your bot reads safe. If false, log reasons and skip the signal. If true, build a bounded execution plan from liquidity, spot, and your own account policy.


Step 3: Hand off a bounded execution plan

javascript
export async function handleSignal(signal) {
  const check = await preTradeCheck(signal)
  if (!check.safe) {
    logger.warn({ signal, reasons: check.reasons }, 'pre-trade check failed')
    return { approvedForExecution: false, reasons: check.reasons }
  }

  // Size: never take more than 1% of pool liquidity
  const maxNotionalUsd = check.liquidity * 0.01
  const notionalUsd = Math.min(signal.targetNotionalUsd, maxNotionalUsd)
  const qty = notionalUsd / check.spot

  // Funding-rate-aware perp sizing
  const leverage = check.fundingAnnualized > 20 ? 1 : signal.baseLeverage

  const executionPlan = {
    symbol: signal.symbol,
    side: signal.side,
    qty,
    leverage,
    maxNotionalUsd,
    source: 'hive-pre-trade-check',
  }

  return { approvedForExecution: true, executionPlan, check }
}

The handoff does three things with Hive data:

  • Liquidity-aware sizing limits the planned position against current pool depth.
  • Funding-rate-aware leverage reduces leverage when the cost of carry turns hostile.
  • Security gating filters out honeypots and high-tax tokens before the plan reaches your order executor.

Hive does not sign transactions, place exchange orders, custody assets, or decide whether capital should be deployed. Keep order placement in your own execution layer with explicit user, policy, or risk-system approval.


Step 4: Add monitoring

While a position is open, poll for two conditions every N seconds and emit risk events to your own execution or alerting system:

  • Liquidity crash. get_pool_info returns a new liquidity value. If it drops by >40% from entry, exit.
  • Funding flip. get_funding_rate turns from positive to negative or vice versa. Adjust the hedge.
javascript
setInterval(async () => {
  const [pool, funding] = await Promise.all([
    callHive('get_pool_info', { poolAddress, networkId: 1 }),
    callHive('get_funding_rate', { exchange: 'binance', symbol: 'ETH/USDT:USDT' }),
  ])
  if (Number(pool.liquidity) < entryLiquidity * 0.6) {
    await emitRiskEvent({ type: 'liquidity_crash', pool, severity: 'high' })
  }
  if (Math.sign(Number(funding.fundingRate)) !== Math.sign(lastFundingSign)) {
    await emitRiskEvent({ type: 'funding_flip', funding, severity: 'medium' })
  }
}, 30_000)

Credit usage depends on polling frequency and how many signals each loop checks. Log X-Quota-Remaining, cache repeated reads where safe, and review Rate Limits before running continuous monitors.


Tools used end-to-end

ToolProviderPurpose
get_priceCoinGeckoSpot reference price
get_coin_ohlc_rangeCoinGeckoCustom-range OHLC for lookback
get_pool_infoCodexDEX pool depth, volume, price impact
get_trending_poolsCoinGeckoPools with rising volume
get_token_securityGoPlusHoneypot, tax, ownership risk
get_funding_rateCCXTPerpetual funding across exchanges
get_token_top_holdersMoralisHolder concentration

All seven tools are available through the root /mcp endpoint. For a narrower agent, the category endpoints /hive_market_data/mcp, /hive_onchain_dex/mcp, and /hive_security_risk/mcp cover the same seven between them.


What to tune next

  • Caching. Hive deduplicates upstream calls, but keeping a 30-second local cache of get_price for frequently-polled pairs saves credits without degrading signal.
  • Backtesting. Run get_coin_ohlc_range over a historical window to backtest the sizing and funding-adjusted leverage rules before deploying capital.
  • Alerts. Wire get_token_security into a cron task that checks every token in your allowlist daily. Tokens can go malicious through owner proxy upgrades even after they were safe at entry.