Skip to main content

First MEV Integration

Get your trading bot or MEV application connected to Axol in under 5 minutes. This guide covers the essential endpoints for MEV extraction, liquidation monitoring, and trading automation.

Prerequisites

  • An Axol API key (Get one free)
  • Python 3.8+ or Node.js 16+
  • Basic understanding of MEV concepts

Quick Setup

1. Install Dependencies

Python:

pip install requests websockets aiohttp

TypeScript:

npm install axios ws

2. Configure Your Client

Python:

import os
import requests

API_KEY = os.getenv('AXOL_API_KEY')
BASE_URL = 'https://api.axol.io/api/v1'

headers = {'X-API-Key': API_KEY}

# Test connection
response = requests.get(f'{BASE_URL}/health', headers=headers)
print(f"API Status: {response.json()}")

TypeScript:

const API_KEY = process.env.AXOL_API_KEY;
const BASE_URL = 'https://api.axol.io/api/v1';

const headers = { 'X-API-Key': API_KEY };

// Test connection
const response = await fetch(`${BASE_URL}/health`, { headers });
console.log('API Status:', await response.json());

Essential MEV Endpoints

Gas Oracle (Low Latency)

Get real-time gas prices with multi-provider failover:

Python:

# Unauthenticated endpoint - no API key required
response = requests.get(f'{BASE_URL}/oracle/gas/ethereum')
gas = response.json()

print(f"Slow: {gas['slow']['max_fee_gwei']} gwei")
print(f"Standard: {gas['standard']['max_fee_gwei']} gwei")
print(f"Fast: {gas['fast']['max_fee_gwei']} gwei")
print(f"Instant: {gas['instant']['max_fee_gwei']} gwei")
print(f"Base Fee: {gas['base_fee_gwei']} gwei")
print(f"Network Congestion: {gas['congestion_level']}")

TypeScript:

const gasResponse = await fetch(`${BASE_URL}/oracle/gas/ethereum`);
const gas = await gasResponse.json();

console.log(`Slow: ${gas.slow.max_fee_gwei} gwei`);
console.log(`Fast: ${gas.fast.max_fee_gwei} gwei`);
console.log(`Instant: ${gas.instant.max_fee_gwei} gwei`);
console.log(`Congestion: ${gas.congestion_level}`);

LRT Exchange Rates

Get liquid restaking token rates for arbitrage opportunities:

response = requests.get(f'{BASE_URL}/oracle/lrt-rates')
rates = response.json()

for token, data in rates['rates'].items():
print(f"{token}: {data['rate']} ETH (source: {data['source']})")

Supported tokens: weETH, stETH, wstETH, rETH, cbETH, ezETH, rsETH


Real-Time Mempool Streaming

Monitor pending transactions for MEV opportunities:

Python (asyncio):

import asyncio
import websockets
import json

async def monitor_mempool():
uri = f"wss://api.axol.io/api/v1/mempool/ethereum/stream"

async with websockets.connect(uri, extra_headers={'X-API-Key': API_KEY}) as ws:
# Subscribe with filters
await ws.send(json.dumps({
'action': 'subscribe',
'filter': {
'tx_types': ['swap', 'liquidation'],
'min_value_eth': 1.0,
'dex_protocols': ['uniswap_v3', 'uniswap_v2']
}
}))

async for message in ws:
tx = json.loads(message)
if tx['type'] == 'pending_tx':
print(f"Pending: {tx['hash'][:16]}... | Type: {tx['tx_type']}")
print(f" Value: {tx['value_eth']} ETH | Gas: {tx['gas_price_gwei']} gwei")

if tx.get('mev_opportunity'):
print(f" MEV: {tx['mev_opportunity']['type']} - {tx['mev_opportunity']['estimated_profit_eth']} ETH")

asyncio.run(monitor_mempool())

TypeScript:

import WebSocket from 'ws';

const ws = new WebSocket('wss://api.axol.io/api/v1/mempool/ethereum/stream', {
headers: { 'X-API-Key': API_KEY }
});

ws.on('open', () => {
ws.send(JSON.stringify({
action: 'subscribe',
filter: {
tx_types: ['swap', 'liquidation'],
min_value_eth: 1.0
}
}));
});

ws.on('message', (data) => {
const tx = JSON.parse(data.toString());
if (tx.type === 'pending_tx') {
console.log(`Pending: ${tx.hash.slice(0, 16)}... | Type: ${tx.tx_type}`);
console.log(` Value: ${tx.value_eth} ETH | Gas: ${tx.gas_price_gwei} gwei`);
}
});

DeFi Liquidation Monitoring

Find liquidation opportunities across lending protocols:

Python:

# Get liquidatable positions
response = requests.get(
f'{BASE_URL}/defi/ethereum/liquidations/opportunities',
headers=headers,
params={
'min_profit_usd': 50,
'protocol': 'aave_v3'
}
)
opportunities = response.json()

for opp in opportunities['opportunities']:
print(f"Position: {opp['borrower'][:16]}...")
print(f" Protocol: {opp['protocol']}")
print(f" Health Factor: {opp['health_factor']}")
print(f" Debt: ${opp['debt_usd']:,.2f}")
print(f" Collateral: ${opp['collateral_usd']:,.2f}")
print(f" Est. Profit: ${opp['estimated_profit_usd']:,.2f}")
print()

Stream Liquidation Opportunities

async def stream_liquidations():
uri = f"wss://api.axol.io/api/v1/defi/ethereum/liquidations/stream"

async with websockets.connect(uri, extra_headers={'X-API-Key': API_KEY}) as ws:
await ws.send(json.dumps({
'action': 'subscribe',
'filter': {
'min_profit_usd': 100,
'protocols': ['aave_v3', 'compound_v3']
}
}))

async for message in ws:
opp = json.loads(message)
print(f"New opportunity: ${opp['estimated_profit_usd']:.2f} profit")
print(f" Borrower: {opp['borrower']}")
print(f" Health: {opp['health_factor']}")

asyncio.run(stream_liquidations())

Direct Node Access (Gateway)

For latency-critical operations, use the Gateway for direct node access:

# Check gateway status
response = requests.get(f'{BASE_URL}/gateway/status', headers=headers)
status = response.json()

print("Available endpoints:")
for chain, endpoints in status['endpoints'].items():
print(f" {chain}:")
print(f" RPC: {endpoints['rpc']['url']}")
print(f" WS: {endpoints['ws']['url']}")

Gateway provides:

  • Sub-100ms latency to nodes
  • Direct WebSocket connections
  • Beacon API access for blob data
  • Bypasses rate limiting for premium tiers

Complete Trading Bot Skeleton

Here's a minimal trading bot structure:

Python:

import asyncio
import aiohttp
import websockets
import json
from dataclasses import dataclass

@dataclass
class Config:
api_key: str
base_url: str = 'https://api.axol.io/api/v1'
min_profit_eth: float = 0.01

class TradingBot:
def __init__(self, config: Config):
self.config = config
self.headers = {'X-API-Key': config.api_key}

async def get_gas_price(self, chain: str = 'ethereum') -> dict:
async with aiohttp.ClientSession() as session:
async with session.get(
f'{self.config.base_url}/oracle/gas/{chain}'
) as resp:
return await resp.json()

async def monitor_opportunities(self):
uri = f"wss://api.axol.io/api/v1/mempool/ethereum/stream"

async with websockets.connect(uri, extra_headers=self.headers) as ws:
await ws.send(json.dumps({
'action': 'subscribe',
'filter': {'tx_types': ['swap']}
}))

async for message in ws:
tx = json.loads(message)
await self.evaluate_opportunity(tx)

async def evaluate_opportunity(self, tx: dict):
# Your MEV logic here
if tx.get('mev_opportunity'):
profit = tx['mev_opportunity'].get('estimated_profit_eth', 0)
if profit >= self.config.min_profit_eth:
print(f"Opportunity found: {profit} ETH profit")
# Execute your strategy

async def run(self):
print("Starting trading bot...")
await self.monitor_opportunities()

# Run the bot
config = Config(api_key=os.getenv('AXOL_API_KEY'))
bot = TradingBot(config)
asyncio.run(bot.run())

Next Steps

Now that you have the basics:

  1. Deep dive into MEV features:

  2. Build production systems:

  3. Understand the platform:


Support

Questions about MEV integration?