Build a Market-Maker Bot for Chia Offers (Python)

10 min read

digital illustration of a Python code editor screen showing cryptocurrency trading bot code, with Chia Network green logo visible, floating holographic XCH coin symbols, circuit board patterns in background,

Key Takeaways

  • Chia Offers enable trustless peer-to-peer trading without centralized exchanges or custody risks1,2
  • Market-maker bots automate buying and selling to capture spread profits from XCH and CAT trading pairs9
  • Python scripts can interact with Chia’s RPC API to create, post, and manage offers programmatically4,10
  • Setting up a basic market maker requires a synced Chia wallet, Python 3.10+, and understanding of spread configuration6
  • Your bot can post offers to Dexie and other aggregators to maximize fill rates and earn additional DBX rewards7,12

Article Summary: A Chia offers market maker bot automates the creation and management of buy and sell offers on the Chia blockchain using Python. By programmatically placing offers with configured spreads through Chia’s RPC API and posting them to decentralized exchanges like Dexie, miners and traders can provide liquidity while earning profits from the difference between buy and sell prices.1,6

What Is a Chia Offers Market Maker?

A Chia offers market maker is a Python script that automatically creates and manages trading offers on the Chia blockchain.6 Unlike traditional crypto trading bots that connect to centralized exchanges, Chia market makers work with the blockchain’s native Offers system.1

The Offers system is Chia’s built-in peer-to-peer trading mechanism.2 When you create an offer, you propose a trade between assets like XCH, CATs (Chia Asset Tokens), or NFTs. The offer file contains all trade details and can be shared anywhere.5 Anyone who accepts your offer completes the trade atomically—meaning both sides happen together or not at all.2

Market makers place both buy and sell offers for the same trading pair.9 For example, you might offer to buy XCH at $20 and sell XCH at $20.50. The $0.50 difference is your spread. When both offers get accepted, you make a profit equal to the spread minus any transaction fees. To understand the deeper mechanics behind how these trades settle on-chain, see our guide on how Chia Offers and One Market are transforming DeFi transactions.

How Chia Market Making Differs from Traditional Bots

Traditional trading bots connect to centralized exchanges through APIs and must deposit funds into exchange wallets. Chia market makers are different because:

  • You keep full custody of your assets.5 Offers lock coins in your wallet but never transfer them to an exchange.
  • Trading happens on-chain.2 The blockchain itself enforces all trade rules through smart coins powered by Chialisp.
  • No exchange fees. You only pay small network transaction fees instead of trading fees to an exchange.
  • Offers work globally.1 Anyone can accept your offers through any communication channel.

Gene Hoffman, Chia’s President and COO, explained that “In an evolving DeFi ecosystem, Chia is meeting critical security and compliance needs to make peer-to-peer transactions safer and easier.”8

Why Build a Chia Offers Market Maker Bot?

Building your own market-maker bot gives you several advantages over manual trading or using centralized exchanges.

Earn Passive Income from Spreads

Market makers profit from the spread between buy and sell prices.9 Your bot places offers continuously, capturing small profits each time both sides of a trade complete. Over time, these small gains add up, especially in actively traded pairs like XCH-USDC.6

Automate Trading Without Exchange Risk

Centralized exchanges can be hacked, go bankrupt, or freeze withdrawals. With Chia Offers, you never send funds to a third party.5 Your Python bot creates offers that other traders accept directly from your wallet.

Provide Liquidity to the Ecosystem

When you run a market-maker bot, you help other traders buy and sell more easily.12 This makes the whole Chia DeFi ecosystem work better. Dexie also rewards active market makers with DBX tokens for providing liquidity, giving you an extra income stream on top of your spread profits.6

Learn Blockchain Development Skills

Building a market-maker bot teaches you Python programming, blockchain APIs, and DeFi concepts. The smart coin logic underpinning Chia Offers is written in Chialisp — understanding it gives you skills that apply across the entire Chia ecosystem. You can learn more about the language powering it all in our deep dive into Chialisp and next-gen smart contracts.

Quick Decision Guide: Is Market Making Right for You?

Your SituationBest ApproachStarting CapitalTime Commitment
New to Chia, learning PythonStart with testnet, small amounts0.1-1 XCH5-10 hours setup
Experienced miner with XCH holdingsDeploy production bot with tight spreads10-50 XCH2-3 hours setup, 1 hour/week monitoring
Active trader wanting automated strategyMulti-pair bot with dynamic pricing20+ XCH + stablecoins10+ hours initial, daily monitoring
DeFi enthusiast exploring opportunitiesExperimental bot on 1-2 pairs5-10 XCH5 hours setup, weekly checks

Understanding How Chia Offers Work

Before building your bot, you need to understand the underlying technology.

The Coin Set Model

Chia uses a different approach than Ethereum or Bitcoin. Instead of account balances, Chia tracks individual coins.5 Each coin has three properties: a parent coin ID, a puzzle hash (like an address), and an amount in mojos (1 XCH = 1 trillion mojos).

When you spend a coin, you provide the puzzle that locks it and a solution. The puzzle and solution together create new coins. Offers use this system to create atomic trades—trades where both sides happen in a single transaction or neither happens at all.2

Offer Files Explained

An offer file is a partially signed spend bundle saved as a text string.5 When you create an offer to trade 1 XCH for 100 USDC, your wallet:

  1. Selects XCH coins totaling at least 1 XCH
  2. Creates a puzzle that will only release the XCH if 100 USDC arrives
  3. Partially signs the transaction
  4. Exports the offer as a string starting with “offer1…”3

Anyone with the offer file can complete it by adding their side of the trade and submitting everything to the blockchain.2 The beauty is that altering the offer file invalidates it.5 Nobody can change the terms after you create the offer.

Settlement Payments and Announcements

Offers use a special puzzle called settlement_payments.5 This puzzle creates announcements that both sides of the trade must match. If your offer requests 100 USDC, the settlement_payments puzzle announces “I need 100 USDC to release 1 XCH.” The taker’s side announces “I’m sending 100 USDC to claim 1 XCH.” Only when both announcements match will the blockchain accept the transaction.

Setting Up Your Development Environment

Let’s build your market-maker bot step by step.

Prerequisites

You’ll need:

  • A synced Chia full node and wallet (light wallets work too)
  • Python 3.10 or newer (Python 3.8 reached end-of-life in October 2024; 3.10+ is recommended for compatibility with current Chia client tooling)
  • Basic understanding of Python programming
  • Some XCH and/or CATs to trade
  • Text editor or IDE (VS Code, PyCharm, etc.)

Installing Required Libraries

Open your terminal and install the necessary Python packages:

pip install requests aiohttp python-dotenv --break-system-packages

The --break-system-packages flag is needed for Python on some Linux systems. Windows and Mac users can usually omit it.

Configuring Your Chia Wallet

Before your bot can create offers, adjust your wallet’s configuration to make coin management easier.6

  1. Open your Chia config file at ~/.chia/mainnet/config/config.yaml
  2. Find the wallet section and locate the reuse_public_key_for_change setting. It is a dictionary keyed by wallet fingerprint. Add your own fingerprint (run chia wallet show to find it) and set it to True:
reuse_public_key_for_change:
  "YOUR_WALLET_FINGERPRINT": True

This setting prevents creating tiny change coins every time you make an offer.6 Without it, your wallet quickly fills with small coins that complicate offer creation. Replace YOUR_WALLET_FINGERPRINT with the numeric fingerprint shown when you run chia wallet show.

Building Your First Simple Market Maker

Here’s a basic Python script that creates a simple market-maker offer for the XCH-USDC trading pair.

Basic Bot Structure

The wallet RPC listens on port 9256 by default and requires mutual TLS authentication using the certificates stored locally in your Chia config directory.10,11 The correct certificate filenames are private_wallet.crt and private_wallet.key — not any other naming convention.4

import requests
import json
import time

# Configuration
WALLET_RPC_PORT = 9256
CERT_PATH = "~/.chia/mainnet/config/ssl/wallet/private_wallet.crt"
KEY_PATH = "~/.chia/mainnet/config/ssl/wallet/private_wallet.key"
XCH_WALLET_ID = 1
USDC_WALLET_ID = 2  # Your USDC CAT wallet ID

# Get current XCH price from CoinGecko
def get_xch_price():
    response = requests.get("//api.coingecko.com/api/v3/simple/price?ids=chia&vs_currencies=usd")
    return response.json()['chia']['usd']

# Create an offer via RPC
def create_offer(wallet_id_offered, amount_offered, wallet_id_requested, amount_requested, fee=0):
    url = f"//localhost:{WALLET_RPC_PORT}/create_offer_for_ids"
    
    offer_dict = {
        str(wallet_id_offered): -int(amount_offered),  # Negative for offering
        str(wallet_id_requested): int(amount_requested)  # Positive for requesting
    }
    
    payload = {
        "offer": offer_dict,
        "fee": fee,
        "validate_only": False
    }
    
    response = requests.post(
        url,
        json=payload,
        cert=(CERT_PATH, KEY_PATH),
        verify=False
    )
    
    return response.json()

Adding Spread Configuration

The key to market making is setting the right spread.9 Here’s how to add buy and sell order creation. Note that all CAT amounts are expressed in mojos, where 1 CAT token = 1,000 mojos — this is the fixed standard for every CAT on the Chia network, including stablecoins like USDC.46

# Market maker configuration
SPREAD_PERCENT = 2.0  # 2% spread
OFFER_AMOUNT_XCH = 0.5  # Trade 0.5 XCH per offer

def create_market_maker_offers():
    # Get current price
    current_price = get_xch_price()
    
    # Calculate buy and sell prices with spread
    buy_price = current_price * (1 - SPREAD_PERCENT / 200)  # Below market
    sell_price = current_price * (1 + SPREAD_PERCENT / 200)  # Above market
    
    # Convert XCH to mojos (1 XCH = 1,000,000,000,000 mojos)
    xch_mojos = int(OFFER_AMOUNT_XCH * 1_000_000_000_000)
    
    # Convert USDC to mojos (1 CAT token = 1,000 mojos — standard for all Chia CATs)
    usdc_to_receive = int(sell_price * OFFER_AMOUNT_XCH * 1000)
    sell_offer = create_offer(XCH_WALLET_ID, xch_mojos, USDC_WALLET_ID, usdc_to_receive)
    
    # Create buy offer (buy XCH with USDC)
    usdc_to_spend = int(buy_price * OFFER_AMOUNT_XCH * 1000)
    buy_offer = create_offer(USDC_WALLET_ID, usdc_to_spend, XCH_WALLET_ID, xch_mojos)
    
    return sell_offer, buy_offer

This code fetches the current XCH price, calculates buy and sell prices with a 2% spread, then creates both offers.4

Posting Offers to Dexie

Creating offers locally isn’t enough—traders need to discover them.12 Dexie is the main offer aggregator where Chia users find and accept trades.7

Using the Dexie API

Dexie provides a public API for posting offers.7 The example below uses the v1 endpoint — always check the Dexie developer documentation for the current API version before deploying, as endpoints are subject to change.

import requests

def post_offer_to_dexie(offer_string):
    """Post an offer to Dexie.space"""
    url = "//api.dexie.space/v1/offers"
    
    payload = {
        "offer": offer_string
    }
    
    try:
        response = requests.post(url, json=payload)
        if response.status_code == 200:
            result = response.json()
            return result.get('id')
        else:
            print(f"Error posting to Dexie: {response.text}")
            return None
    except Exception as e:
        print(f"Exception posting to Dexie: {e}")
        return None

Automating the Full Workflow

Now combine offer creation and posting into an automated loop:6

import time

def run_market_maker():
    while True:
        try:
            # Create offers
            sell_offer, buy_offer = create_market_maker_offers()
            
            # Extract offer strings
            sell_offer_str = sell_offer.get('offer')
            buy_offer_str = buy_offer.get('offer')
            
            # Post to Dexie
            if sell_offer_str:
                sell_id = post_offer_to_dexie(sell_offer_str)
                print(f"Posted sell offer: {sell_id}")
            
            if buy_offer_str:
                buy_id = post_offer_to_dexie(buy_offer_str)
                print(f"Posted buy offer: {buy_id}")
            
            # Wait before creating new offers (avoid spamming)
            time.sleep(3600)  # Wait 1 hour
            
        except Exception as e:
            print(f"Error in market maker loop: {e}")
            time.sleep(60)  # Wait 1 minute on error

if __name__ == "__main__":
    run_market_maker()

Advanced Market-Making Features

Once your basic bot runs, you can add sophisticated features.

Dynamic Spread Adjustment

Instead of a fixed spread, adjust based on market volatility:9

def calculate_dynamic_spread(price_history):
    """Calculate spread based on recent price volatility"""
    if len(price_history) < 10:
        return 2.0  # Default 2%
    
    # Calculate standard deviation of recent prices
    import statistics
    volatility = statistics.stdev(price_history[-20:])
    
    # Higher volatility = wider spread
    base_spread = 1.0
    volatility_multiplier = volatility / statistics.mean(price_history[-20:])
    
    return base_spread + (volatility_multiplier * 100)

Managing Multiple Trading Pairs

Expand your bot to trade multiple pairs like XCH-USDC, XCH-DBX, and XCH-wETH:6

TRADING_PAIRS = [
    {
        'name': 'XCH-USDC',
        'base_wallet': 1,
        'quote_wallet': 2,
        'spread': 2.0,
        'amount': 0.5
    },
    {
        'name': 'XCH-DBX',
        'base_wallet': 1,
        'quote_wallet': 3,
        'spread': 3.0,
        'amount': 1.0
    }
]

def run_multi_pair_market_maker():
    for pair in TRADING_PAIRS:
        create_offers_for_pair(pair)

Offer Expiration Management

Set expiration times to prevent stale offers using the max_time parameter:3,4

import datetime

def create_offer_with_expiry(wallet_id_offered, amount_offered, 
                            wallet_id_requested, amount_requested, 
                            expiry_hours=24):
    """Create offer that expires after specified hours"""
    expiry_timestamp = int((datetime.datetime.now() + 
                           datetime.timedelta(hours=expiry_hours)).timestamp())
    
    payload = {
        "offer": {
            str(wallet_id_offered): -amount_offered,
            str(wallet_id_requested): amount_requested
        },
        "max_time": expiry_timestamp,
        "validate_only": False
    }
    
    # Make RPC call as before...

Comparison: Chia Market Making vs AMM Pools

FeatureChia Offers Market MakingAMM Liquidity Pools
CustodyFull self-custody, funds never leave your wallet5Deposit funds into smart contract pool
Price SettingYou set exact buy/sell prices9Algorithmic pricing based on pool ratio
Impermanent LossNo impermanent loss risk12Subject to impermanent loss
FlexibilityCancel/update offers anytime2Must withdraw from pool to change strategy
Technical SkillRequires coding/scripting knowledge6Simple deposit interface
FeesOnly network transaction fees2Trading fees shared with all LPs

Risk Management and Best Practices

Running a market-maker bot involves risks. Here’s how to manage them.

Start Small and Scale Gradually

Begin with small amounts on testnet or with 0.1-1 XCH on mainnet. Once your bot runs reliably for a week without errors, gradually increase your trading amounts.

Monitor Your Bot Regularly

Check your bot at least daily. Look for:

  • Errors in logs
  • Offers getting stuck
  • Unusual price movements
  • Wallet balance changes

Set Stop-Loss Limits

Configure maximum loss thresholds:

MAX_DAILY_LOSS_XCH = 2.0  # Stop bot if loses more than 2 XCH per day

def check_stop_loss(starting_balance, current_balance):
    loss = starting_balance - current_balance
    if loss > MAX_DAILY_LOSS_XCH:
        print("Stop-loss triggered!")
        return True
    return False

Keep Detailed Records

Save all offer IDs, trades, and profits to a database or CSV file.6 This helps you analyze performance and report taxes accurately.

Conclusion

Building a Chia offers market maker bot with Python gives you powerful tools to participate in decentralized finance while maintaining full control of your assets.1,5 Start with a simple single-pair bot, test thoroughly on testnet, then gradually expand to multiple pairs and advanced features. The key to success is careful monitoring, proper risk management, and continuous learning from your bot’s performance.

By running a market-maker bot, you not only earn profits from spreads but also contribute valuable liquidity to the Chia ecosystem.12 As you gain experience, you’ll develop skills that transfer to other blockchain development projects and deepen your understanding of DeFi mechanics.

Chia Offers Market Maker FAQs

What Is a Chia Offers Market Maker Bot?

A Chia offers market maker bot is a Python program that automates creating buy and sell offers on the Chia blockchain.6 The bot places offers at different prices to capture the spread between buying and selling, earning profits when both sides of trades complete while you maintain full custody of your assets.5

How Does a Chia Offers Market Maker Make Money?

Market makers earn money from the spread between buy and sell prices.9 If your bot offers to buy XCH at $20 and sell XCH at $20.50, you profit $0.50 on each complete round trip trade. Dexie also rewards market makers with DBX tokens for providing liquidity, creating an additional income stream on top of spread earnings.6

Do I Need Programming Experience to Build a Chia Offers Market Maker?

Basic Python knowledge is recommended but not strictly required. If you can follow tutorials and understand concepts like variables, loops, and functions, you can build a simple market-maker bot.6 Many example scripts are available on GitHub that you can adapt to your needs.

What Are the Risks of Running a Market Maker Bot?

Main risks include software bugs causing incorrect offers, price volatility leading to unfavorable trades, and opportunity cost if markets move strongly in one direction. However, unlike AMM pools, you face no impermanent loss because you set exact prices.12 Proper testing, monitoring, and risk limits minimize these dangers.

Can I Run a Chia Market Maker Bot on a Light Wallet?

Yes, you can run a market-maker bot with a light wallet as long as the wallet has RPC access enabled.10,11 Light wallets sync faster and use less disk space than full nodes while still allowing offer creation through the RPC API. However, a full node provides better reliability for production bots.

Chia Offers Market Maker Citations

1. Chia Network. “Chia Offers: Unlocking Global Peer-to-Peer Markets.” https://www.chia.net/2024/02/16/chia-offers-unlocking-global-peer-to-peer-markets/

2. Chia Documentation. “Offers | Chia Documentation.” https://docs.chia.net/academy-offers/

3. Chia Documentation. “Offers – CLI | Chia Documentation.” https://docs.chia.net/guides/offers-cli-tutorial/

4. Chia Documentation. “Offer RPC | Chia Documentation.” https://docs.chia.net/offer-rpc/

5. Chialisp.com. “Offers | Chialisp.” https://chialisp.com/offers/

6. AbandonedLand. “MarketMaker: Chia Market Maker GitHub Repository (PowerShell-based reference implementation).” https://github.com/AbandonedLand/MarketMaker

7. Dexie Space. “Splash: A Decentralized Network for Sharing Offers.” https://github.com/dexie-space/splash

8. Business Wire. “Chia Launches the First Native Peer-to-Peer Exchange Capabilities and DEXs.” https://www.businesswire.com/news/home/20220112005414/en/Chia-Launches-the-First-Native-Peer-to-Peer-Exchange-Capabilities-and-DEXs

9. Wundertrading. “How Market Maker Bots Can Benefit Your Trading Strategy.” https://wundertrading.com/journal/en/learn/article/how-market-maker-bots-can-benefit-your-trading-strategy

10. Chia Documentation. “Wallet RPC | Chia Documentation.” https://docs.chia.net/wallet-rpc/

11. Chia Documentation. “RPC Overview | Chia Documentation.” https://docs.chia.net/rpc/

12. Dexie Notes. “Decentralized Liquidity with Chia Offers.” https://notes.dexie.space/p/decentralized-liquidity-with-chia

46. Chia Documentation. “CAT Creation Tutorial — CAT token to mojo ratio.” https://docs.chia.net/guides/cat-creation-tutorial/