惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
博客园_首页
J
Java Code Geeks
Jina AI
Jina AI
B
Blog RSS Feed
量子位
有赞技术团队
有赞技术团队
M
MIT News - Artificial intelligence
L
LangChain Blog
Microsoft Security Blog
Microsoft Security Blog
小众软件
小众软件
博客园 - 聂微东
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 三生石上(FineUI控件)
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog
I
InfoQ
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
Y
Y Combinator Blog
Vercel News
Vercel News
雷峰网
雷峰网

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Match Orders in 100 Lines of Ruby
Stefan Buhrmester · 2026-06-27 · via DEV Community
Cover image for How to Match Orders in 100 Lines of Ruby

Stefan Buhrmester

Order matching has dropped in Shitcoin Swap in ~100 lines of Ruby.

Most crypto exchanges reach for an existing matching engine or a Uniswap-style AMM. We wrote our own — not because we're smarter, but because the problem is simpler than people think, and understanding every line of your matching logic pays off if things go sideways at 3 AM.

The data model

Two tables, one idea:

  • Account — holds a balance of one asset. Each user gets one account per asset.
  • Order — says "I want to sell X of asset A to buy Y of asset B." Tracks how much is funded, how much remains, and whether it's filled.
Account(id, user_id, asset_id, balance)

Order(id, account_id, sell_asset_id, buy_asset_id,
      sell_amount, buy_amount, funded_amount,
      remaining_sell_amount, price, completed, cancelled_at)

Orders are pre-funded at creation time — the funded_amount is automatically set to the minimum of your sell_amount and your account's available balance (which subtracts funds already locked in other active orders):

def available_balance
  balance - orders.active.sum(:funded_amount)
end

def fund!
  self.funded_amount = [account.available_balance, sell_amount].min
  save!
end

You can place an order for any amount you want. But if your account can't cover it, funded_amount gets capped at what's available — and an order with no funding won't match anything. It'll just sit there until you deposit. No rejection, no error, just waiting.

The matching algorithm

When an order is created, it funds itself, then searches for a counterparty.

Step 1 — find matching orders:

def matching
  result = Order.active.where(
    sell_asset_id: buy_asset_id,
    buy_asset_id: sell_asset_id
  )

  if price
    result = result.where("price IS NULL OR price >= ?", 1.0 / price)
  end

  result
end

Two orders match when their asset pairs are flipped. If the order has a limit price, we filter out counterparties whose price would give us less than we asked for — a single WHERE clause that handles the unit conversion implicitly.

Step 2 — agree on a price and execute:

def match!(other)
  return if completed? || remaining_sell_amount <= 0 || funded_amount <= 0

  # Negotiate price
  if other.price
    price = [self.price, 1.0.to_r / other.price].compact.min
  elsif self.price
    price = self.price
  else
    return  # both market orders — can't determine fair rate
  end

  amount_affordable = funded_amount.to_r / price
  amount = [amount_affordable, other.funded_amount.to_r].min.to_r
  return unless amount > 0

  # Execute
  self.remaining_sell_amount -= price * amount
  self.funded_amount -= price * amount
  other.remaining_sell_amount -= amount
  other.funded_amount -= amount

  self.completed = true if remaining_sell_amount <= 0
  other.completed = true if other.remaining_sell_amount <= 0

  [other, self].each(&:save!)
end

Price discovery has three cases:

This order Other order Result
Limit Limit Trade at $\min(P_{\text{this}}, 1/P_{\text{other}})$ — satisfies both
Limit Market Trade at this order's price
Market Market Skip — no fair rate determinable

The trade amount is the minimum of what we can afford and what the counterparty has. Both sides debit proportionally. Either side hits zero remaining → marked complete. Partial fills happen naturally.

Two details worth mentioning

Rational numbers. You'll see to_r everywhere. Floating-point is fine for 50000 / 1 but not for 1 / 3 repeated across dozens of conversions. Ruby's Rational gives us exact arithmetic during matching; we cast to decimal only for database storage.

Pessimistic locking. Two concurrent matches on the same order would double-spend the funded amount. process! locks both rows with SELECT ... FOR UPDATE:

def process!
  self.lock!
  matching.lock.each do |other|
    match!(other)
    break if completed?
  end
end

The database serializes access. With SQLite that means one writer at a time — fine for now. PostgreSQL would give row-level granularity when needed.

What's still missing

  • Account settlement: We debit order state but haven't hooked up balance transfers yet (that's the TODO in match!).

The takeaway

An order matching engine doesn't need to be complex. Find counterparty, negotiate price, debit both sides — it fits in ~100 lines. The hard parts aren't algorithmic; they're concurrency, numeric precision, and making sure the accounting never drifts by a single satoshi.


Shitcoin Swap is a work in progress. Follow along or contribute at github.com/shitcoinsociety.