Internal Trading Bot Development for Crypto Exchanges

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Internal Trading Bot Development for Crypto Exchanges
Medium
~1-2 weeks
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1357
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

Internal Trading Bot Development for Crypto Exchanges

A young crypto exchange without liquidity is a dead exchange. Traders go where spreads are tight and the order book is deep. An internal market-making bot solves this: we design and deploy trading bots with direct access to the matching engine, reducing latency to microseconds and eliminating fees. Unlike public bots for Binance, our internal bot communicates via IPC or gRPC, bypassing HTTP overhead and rate limits. This yields latency under 100 μs versus 1–5 ms for external API.

According to CoinMarketCap, around 70% of volume on top exchanges is provided by market makers.

A recent case: for Exchange X with a daily volume of $50M, we deployed an internal market maker. Result: spread dropped from 0.5% to 0.08%, volume grew 300% in one month. Fee savings exceeded $60,000 per month — 40% more than using an external API.

Our team has over 7 years of experience developing trading bots. We guarantee stable operation and transparent audit for every project.

Why does an exchange need its own trading bot?

We design bots that maintain a spread of 0.05–0.1% for stable pairs and order book depth of up to 50 BTC per level. The bot continuously synchronizes prices with external exchanges (Binance, OKX) via WebSocket, adjusting its own quotes every 100 ms. This is a legitimate practice — most exchanges use internal market makers at launch.

How is a trading bot developed for a crypto exchange?

The process includes several stages: requirements analysis, architecture design, strategy implementation, internal API integration, testing and audit, and deployment. Each stage ends with a documented result. Timeline ranges from 3 to 5 weeks.

Stage Duration Deliverable
Requirements Analysis 2–3 days Strategy specification
Architecture Design 3–5 days High-level design
Strategy Implementation 5–10 days Working prototype
API Integration 3–5 days Connection to matching engine
Testing & Audit 3–5 days Audit report
Deployment 2–3 days Production release

Step-by-step bot configuration

  1. Choose a strategy (market-making, arbitrage, trend).
  2. Configure parameters: spread, number of levels, volume per level.
  3. Connect reference price from an external exchange via WebSocket.
  4. Run in test mode on an internal staging environment.
  5. Monitor metrics: volume, spread, P&L, active orders.

How is a market-making bot structured?

Three key components: quoting strategy, inventory management, and protection against market moves. Let's examine each with code examples.

Quoting strategy

class MarketMakerBot:
    def __init__(self, pair: str, config: MMConfig):
        self.pair = pair
        self.spread_pct = config.spread_pct       # 0.1% = 0.001
        self.order_levels = config.order_levels   # number of levels (5-10)
        self.level_spacing = config.level_spacing # distance between levels
        self.level_size = config.level_size       # volume per level
        self.reference_exchange = config.reference # Binance for price feed
    
    async def update_quotes(self):
        # Get reference price from external exchange
        ref_price = await self.get_reference_price()
        
        # Compute bid/ask
        half_spread = ref_price * self.spread_pct / 2
        best_bid = ref_price - half_spread
        best_ask = ref_price + half_spread
        
        # Generate multiple levels
        new_bids = []
        new_asks = []
        for i in range(self.order_levels):
            bid_price = best_bid * (1 - self.level_spacing * i)
            ask_price = best_ask * (1 + self.level_spacing * i)
            size = self.level_size * (1 + i * 0.5)  # increase size away from mid
            
            new_bids.append({'price': bid_price, 'size': size})
            new_asks.append({'price': ask_price, 'size': size})
        
        await self.refresh_orders(new_bids, new_asks)
    
    async def refresh_orders(self, new_bids, new_asks):
        # Cancel old orders and place new ones atomically
        # Use bulk cancel + bulk place to minimize time without quotes
        await self.exchange.cancel_all_orders(self.pair)
        await asyncio.gather(
            *[self.exchange.place_order(self.pair, 'buy', b['price'], b['size']) 
              for b in new_bids],
            *[self.exchange.place_order(self.pair, 'sell', a['price'], a['size']) 
              for a in new_asks]
        )

Inventory management

During active trading, inventory (ratio of base to quote) drifts. Rebalancing is needed:

def calculate_inventory_skew(self, base_balance: float, quote_balance: float, 
                               mid_price: float) -> float:
    """
    Returns skew (-1.0 to +1.0)
    -1.0: all balance in base (bought too much) -> lower bid, raise ask
    +1.0: all balance in quote (sold too much) -> raise bid, lower ask
    """
    base_value = base_balance * mid_price
    total_value = base_value + quote_balance
    
    if total_value == 0:
        return 0.0
    
    ideal_pct = 0.5  # target balance 50/50
    current_pct = base_value / total_value
    return (ideal_pct - current_pct) * 2  # normalize to [-1, 1]

def apply_inventory_skew(self, mid_price: float, skew: float) -> tuple:
    """Shift quotes to reduce imbalance"""
    skew_adjustment = mid_price * self.skew_factor * skew
    adjusted_mid = mid_price + skew_adjustment
    
    bid = adjusted_mid * (1 - self.spread_pct / 2)
    ask = adjusted_mid * (1 + self.spread_pct / 2)
    return bid, ask

Protection against market moves

Sharp market moves with open positions pose a risk of loss. Protection:

async def check_price_deviation(self):
    """Stop quoting if market moves too fast"""
    current_ref = await self.get_reference_price()
    price_change = abs(current_ref - self.last_ref_price) / self.last_ref_price
    
    if price_change > self.max_price_change:  # e.g., 0.5%
        await self.cancel_all_orders()
        await asyncio.sleep(self.pause_duration)  # pause N seconds
        self.last_ref_price = current_ref

A sandwich attack occurs when an attacker places orders before and after your transaction to profit from price movement. Protection: use a private mempool (e.g., Flashbots Protect) and implement a maximum price impact check in the contract itself. For CEX bots this is less relevant, but for DEX integration it's mandatory.

How to implement internal exchange access?

The key advantage of an internal bot is that it can work through the exchange's internal API, bypassing HTTP overhead, rate limits, and fees. Instead of HTTP, we use IPC or gRPC, reducing latency from 1–5 ms to 100 μs. Below is a Go example:

// Direct matching engine call without HTTP
type InternalBotConnector struct {
    matchingEngine *MatchingEngine
    balanceManager *BalanceManager
}

func (c *InternalBotConnector) PlaceOrder(order Order) ([]Trade, error) {
    // Direct call, no network
    return c.matchingEngine.AddOrder(order)
}

func (c *InternalBotConnector) GetOrderBook(pair string) OrderBook {
    return c.matchingEngine.GetSnapshot(pair)
}

An internal bot is 50x faster than an external API in terms of latency. This is critical for high-frequency strategies where every millisecond matters.

How to monitor bot performance?

Real-time P&L monitoring is mandatory. We implement metrics for volume, spread captured, and effective spread in basis points.

class BotMetrics:
    def __init__(self):
        self.filled_volume = defaultdict(float)
        self.pnl = defaultdict(float)
        self.spread_captured = defaultdict(float)
    
    def on_fill(self, trade: Trade):
        pair = trade.pair
        self.filled_volume[pair] += trade.quantity
        
        # P&L calculation: each fill with positive spread = income
        if trade.is_maker:
            # Maker fill: we earned the spread
            spread_earned = abs(trade.price - self.mid_price[pair]) * trade.quantity
            self.spread_captured[pair] += spread_earned
    
    def get_stats(self) -> dict:
        return {pair: {
            'volume_24h': self.filled_volume[pair],
            'spread_captured': self.spread_captured[pair],
            'effective_spread_bps': self.spread_captured[pair] / self.filled_volume[pair] * 10000
                if self.filled_volume[pair] > 0 else 0
        } for pair in self.filled_volume}

A Grafana dashboard displays key metrics: trading volume, spread, P&L, active order count. Alerts are sent to Telegram/Slack when metrics deviate from normal.

What's included in the development?

  • Architecture design (high-level + detailed specification)
  • Implementation of quoting and risk management strategies
  • Integration with the exchange's internal API (REST, WebSocket, gRPC)
  • Development of monitoring dashboard (Grafana + Prometheus)
  • Load testing and security audit
  • Documentation and team training

Additional options

  • Integration with Chainlink oracle for price feed
  • Support for multiple pairs and strategies
  • Backup and disaster recovery

Case study: how we increased exchange liquidity 4x

Client: a young exchange with $5M daily turnover. Spread was 0.5%, order book depth only 10 BTC at best price. We developed an internal market maker using the quoting algorithm described above. Results after one month:

  • Spread narrowed to 0.08%.
  • Order book depth increased to 200 BTC across five levels.
  • Turnover grew to $25M per day (400% increase).
  • Fee savings if using an external API would have been $3,000 per day, but with internal access fees are zero.

Comparison: internal bot vs external API

Metric Internal Bot External API
Latency < 100 μs 1–5 ms
Fees zero maker/taker
Rate limits none yes
Order book access full limited
Security isolated environment depends on provider

Development of a trading bot with market-making strategy for internal use: 3–5 weeks. Includes quoting strategy, inventory management, monitoring dashboard, and integration with the exchange's internal API.

Get a consultation: discuss your requirements, we'll propose an architecture and estimate the economic impact. Order the development of a trading bot for your exchange.

Why exchange development requires deep domain expertise

We develop exchanges — not 'chart sites,' but matching engines that process thousands of orders per second without delay, route liquidity between pools, and guarantee that no user gains access to others' funds. Teams that start with the UI and postpone the engine 'for later' end up rewriting everything in six months in 90% of cases.

Order Book vs AMM: where most projects break

Centralized exchanges (CEX) are built around an order book + matching engine. Decentralized exchanges (DEX) either also use an order book (dYdX on StarkEx, Serum/OpenBook on Solana) or an AMM with concentrated liquidity (Uniswap v3/v4, Curve, Balancer). A classic mistake when developing a CEX is implementing the matching engine on top of a relational database with transactions for each match. PostgreSQL handles ~500 RPS without special effort, but at peak loads of 5,000–10,000 orders per second, it turns into a deadlock nightmare. The correct architecture: in-memory order book (Redis Sorted Sets or custom C++/Rust structure), asynchronous writing of matches to PostgreSQL via a queue (Kafka/RabbitMQ), and a separate settlement service that finally updates balances.

For DEX, the most painful problem is sandwich attacks and MEV. A pool with a plain xy=k AMM without slippage protection becomes a target for MEV bots within hours of launch. Uniswap v2 lost hundreds of millions of dollars in user liquidity. Solutions: integration with Flashbots Protect, a commit-reveal scheme for orders, or switching to TWAMM (Time-Weighted AMM) for large trades.

Concentrated liquidity and impermanent loss

Uniswap v3 introduced concentrated liquidity – LPs choose a price range in which to provide liquidity. Capital efficiency increased 4,000x compared to v2 for stable pairs. But implementing this mechanism correctly is non-trivial. The Uniswap v3 liquidity contract uses tick-based accounting: the price space is divided into discrete ticks (tick = log₁.0001(price)), each tick stores accumulated fee growth and liquidity delta. When creating a position, the lower and upper ticks are computed, and the contract recalculates all active positions at each swap. Storage layout is critical here – incorrect variable packing in slots easily adds 40–60% to swap gas cost.

We implemented a Uniswap v3 fork for a client on Polygon with a custom fee tier system. The initial version consumed 180k gas for a swap across 2 ticks. After slot packing of variables in Tick.Info and inlining several internal calls, it dropped to 112k gas. This reduced gas costs by 38% and saved the client substantial costs on fees monthly. The techniques applied are described in the Uniswap v3 Whitepaper and confirmed by our audit experience.

How a matching engine delivers performance

A production-ready matching engine is built according to the following scheme:

  • Order ingestion layer – WebSocket gateway (Go or Rust), accepts orders, validates signature, checks balance via Redis, queues them. Latency at this level must be <1ms.
  • Matching core – single-threaded event loop (eliminates race conditions without mutexes). In memory, we hold two Sorted Sets for each trading instrument: bids and asks. FIFO matching for limit orders, immediate-or-cancel for market orders. Throughput with a proper Rust implementation – 500k–1M matches per second on a single core.
  • Settlement service – reads matches from Kafka, atomically updates balances in PostgreSQL (UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1). Optimistic locking via row versioning.
  • Withdrawal pipeline – separate service with cold/hot wallet architecture. The hot wallet holds 5–10% of total deposits, the rest is cold storage with multi-sig (Gnosis Safe or custom HSM). Automatic withdrawals only from hot wallet, large amounts require manual authorization.
Component Technology Latency / Throughput
Order gateway Go + WebSocket <1ms p99
Matching engine Rust (in-memory) 500k+ orders/sec
Balance store Redis (write-through) <0.5ms
Settlement DB PostgreSQL 14+ ~50k TPS with partitioning
Event streaming Apache Kafka 1M+ events/sec
Blockchain node Geth / Solana validator depends on chain

How our exchange development process ensures reliability

Smart contracts and gas optimization

For EVM-based DEX (Ethereum, Arbitrum, Optimism, Polygon), the entire critical path lives in Solidity. Main contracts: Pool, Factory, Router, PositionManager (for v3-like), and Quoter for off-chain calculations. Typical mistakes we see in audits:

Reentrancy via callback. Uniswap v3 uses flash swap with a callback (uniswapV3SwapCallback). If your router lacks a nonReentrant guard and you don't check msg.sender == pool, the contract gets drained via a nested call. This is not hypothetical – several v3 forks lost funds this way.

Oracle manipulation in AMM. If your contract uses the spot price from the pool for collateral calculation, it is front-runnable. Correct: TWAP over 30+ minutes (Uniswap v3 OracleLib) or an external oracle (Chainlink).

Unbounded loops in liquidity range. If a swap crosses many ticks in a row (price impact 80%+), gas may exceed the block limit. Need MAX_TICKS_CROSSED with partial fill and returning the remainder.

For Solana DEX (Anchor framework, Rust), the architecture is fundamentally different: account-based model, Program Derived Addresses (PDA) instead of storage, Cross-Program Invocations instead of internal calls. Solana's throughput (~3,000–4,000 TPS vs 15–30 on Ethereum mainnet) allows building on-chain order books – exactly what Phoenix DEX does.

Liquidity bootstrapping and aggregator integration

Launching a pool is not enough – you need to ensure liquidity at launch. Practical mechanisms:

  • Liquidity Bootstrapping Pool (LBP) – initial price is high, asset weights dynamically shift, creating selling pressure and even token distribution. Implemented in Balancer v2.
  • Initial Liquidity Offering via Uniswap v3 – adding liquidity in a narrow range around the initial price, then gradually expanding as volume grows. Requires active liquidity management or integration with Arrakis/Gamma.
  • Integration with 1inch, Paraswap, Li.Fi – aggregators bring traffic but require standard compliance: the pool must have correct getAmountsOut, support ERC-20 approval/permit, and not have custom transfer hooks that break the aggregator's routing.

Development process and deliverables

Analytics and design begin with choosing the architectural model: CEX with custodial storage, non-custodial DEX, or hybrid (off-chain order book + on-chain settlement, like dYdX v3). This decision determines everything – regulatory load, tech stack, team.

Development proceeds in layers: first smart contracts with full Foundry coverage (fuzzing, invariant testing), then backend services, then integration layer, and finally frontend. Testing includes fork testing on mainnet via Foundry – we reproduce real liquidity conditions, not synthetic ones.

Audit is mandatory before mainnet deployment. For DEX contracts, minimally one firm with manual review (Trail of Bits, Spearbit, Code4rena contest). For CEX custody, audit of key storage processes. We guarantee all contracts undergo formal verification and fuzzing testing (Echidna, Foundry invariant).

Estimated timelines

Exchange type Timeframe
DEX (AMM, xy=k) 3 to 5 months
DEX with concentrated liquidity (v3-like) 6 to 10 months
CEX (matching engine + custody + trading UI) 8 to 14 months
Integration with existing protocol 4 to 8 weeks

Cost is calculated individually after a technical briefing: chain selection, throughput requirements, custodial model. Our certified engineers with 10+ years of experience will help you choose the optimal architecture and avoid common pitfalls. Contact our team for a detailed proposal.

Pitfalls to avoid at launch

  • Forgetting the price oracle in AMM. Spot price can be manipulated with a flash loan in one transaction. If your lending protocol uses the spot price from its own pool, that's a bug.
  • Hot wallet without limits. A CEX without daily limits on automatic withdrawals is an invitation for attackers. Compromising one key should lose at most 10% of total funds.
  • Absence of circuit breaker. A 40% price drop in 5 minutes should halt automatic liquidations or withdrawals until manual review. Without this, a cascading liquidation spiral destroys all TVL.
  • Incorrect decimal handling. USDC uses 6 decimals, WBTC – 8, most tokens – 18. Mixing without normalization leads to either precision loss or overflow. Solidity has no float; we work with fixed-point using FullMath (mulDiv with overflow protection).

Want to avoid these problems? Get a consultation — we will select the architecture for your project and provide exact timelines. Order exchange development with quality guarantee and ongoing support.