Day 20 of the Polymarket Trading Bot Development Series
A trading bot can have an excellent strategy and still lose money because of poor execution.
Imagine your Polymarket bot is monitoring four markets simultaneously:
- BTC needs a new bid and ask.
- ETH has a partially filled order.
- SOL has an outdated quote that needs cancellation.
- XRP has stale market data.
- Your account has limited available capital.
Each strategy knows what it wants to do. But what happens when all four strategies attempt to communicate with the exchange at the same time?
Without a centralized execution system, you can run into duplicate orders, conflicting cancellations, excessive API requests, and unexpected portfolio exposure.
This is why production trading systems need more than trading algorithms.
They need an execution engine.
In this tutorial, we'll design a Python-based execution controller for a multi-market Polymarket market maker bot.
We'll cover order routing, risk validation, partial fills, cancellation races, priority queues, API rate limiting, and exchange reconciliation.
This article is part of an educational series. The Python examples illustrate internal execution architecture rather than a complete, production-ready Polymarket integration.
1. Why Order Execution Deserves Its Own Architecture
A simple trading bot often follows this pattern:
Market Data | v Trading Strategy | v Exchange API The strategy receives market data, calculates an order, and sends it directly to the exchange.
This architecture can work for an experimental bot.
But once you operate across several markets, it becomes increasingly difficult to coordinate execution.
For example, consider a BTC market:
Best Bid: $0.48 Best Ask: $0.52 Desired Buy: $0.49 Desired Sell: $0.53 The strategy determines the desired quotes.
However, it shouldn't be responsible for every detail of how those quotes become actual orders.
Before placing an order, the system needs to answer several questions:
- Is the market still active?
- Is the order price valid?
- Is there enough available capital?
- Does an equivalent order already exist?
- Is an old order still being canceled?
- Has the market data become stale?
- Is the API currently rate-limited?
These questions belong to the execution layer.
A more reliable architecture separates strategy decisions from exchange operations.
BTC Strategy ──┐ ETH Strategy ──┤ SOL Strategy ──┼──> Execution Controller XRP Strategy ──┘ | v Risk Manager | v Order Manager | v Exchange Adapter | v Polymarket The core principle is straightforward:
The strategy decides what it wants to trade. The execution engine decides how to execute that decision safely.
2. Represent Trading Decisions as Order Intents
Instead of sending orders directly to Polymarket, each strategy should generate an internal order intent.
An order intent describes the action the strategy wants to perform.
It is not yet an exchange order.
Let's define a Python model.
from dataclasses import dataclass from decimal import Decimal from typing import Literal @dataclass class OrderIntent: market: str token_id: str side: Literal["BUY", "SELL"] price: Decimal quantity: Decimal strategy_id: str Now create an example intent.
intent = OrderIntent( market="BTC", token_id="example-token-id", side="BUY", price=Decimal("0.49"), quantity=Decimal("100"), strategy_id="btc-market-maker", ) print(intent) This tells the execution controller that the BTC strategy wants to purchase 100 shares at $0.49.
But the controller hasn't approved anything yet.
It can:
- Approve the request.
- Reject it.
- Delay execution.
- Reduce the order quantity.
- Replace an existing order instead.
Using Decimal is important because trading systems should avoid unnecessary floating-point precision errors.
For example:
from decimal import Decimal price = Decimal("0.49") quantity = Decimal("100") notional = price * quantity print(notional) # 49.00 This makes financial calculations more predictable.
However, you must still validate the actual market's price precision, tick size, quantity requirements, and supported order parameters.
3. Validate Every Order Before Submission
A strategy generating an order intent doesn't mean the order is safe to execute.
Every order should pass validation.
At a minimum, the execution controller should check market status, data freshness, price and quantity validity, available capital, and portfolio risk.
Here's a basic validator.
from decimal import Decimal def validate_order(intent, market_state): if intent.price <= Decimal("0"): return False, "Invalid price" if intent.quantity <= Decimal("0"): return False, "Invalid quantity" if not market_state["active"]: return False, "Market is inactive" if not market_state["data_fresh"]: return False, "Market data is stale" if not market_state["trading_enabled"]: return False, "Trading is disabled" return True, "Order passed validation" Example:
market_state = { "active": True, "data_fresh": True, "trading_enabled": True, } approved, reason = validate_order( intent, market_state, ) print(approved, reason) Output:
True Order passed validation This example handles only basic validation.
A production validator must also check the actual outcome token, market price boundaries, tick sizes, quantity precision, balances, open-order exposure, and inventory limits.
For instance, suppose your bot has $200 available.
Three strategies independently request:
BTC: $100 ETH: $100 SOL: $100 Each strategy might believe its request is affordable.
But the combined requests require $300.
A centralized risk manager must account for capital already committed to outstanding orders before approving new exposure.
Otherwise, independent strategies can oversubscribe the same available balance.
4. Design an Order Lifecycle Manager
Submitting an order is only the beginning.
After submission, the order may be accepted, rejected, partially filled, completely filled, or canceled.
A simplified order lifecycle looks like this:
CREATED | v SUBMITTED | +--------> REJECTED | v ACCEPTED | v ACTIVE | +--------> FILLED | v PARTIALLY_FILLED | +--------> FILLED | +--------> CANCELED Real execution systems must also handle uncertain states.
For example, a network timeout might prevent your bot from knowing whether an order was accepted.
Let's create an internal order model.
from dataclasses import dataclass from decimal import Decimal @dataclass class ManagedOrder: order_id: str market: str side: str price: Decimal quantity: Decimal filled_quantity: Decimal = Decimal("0") status: str = "CREATED" @property def remaining_quantity(self): return max( Decimal("0"), self.quantity - self.filled_quantity, ) Suppose an order requests 100 shares but only 40 have been filled.
order = ManagedOrder( order_id="order-001", market="BTC", side="BUY", price=Decimal("0.49"), quantity=Decimal("100"), filled_quantity=Decimal("40"), status="PARTIALLY_FILLED", ) print(order.remaining_quantity) Output:
60 The order has 60 shares remaining.
That remaining quantity matters when calculating inventory, replacing quotes, or canceling outstanding orders.
Why persistent state matters
An in-memory Python object isn't sufficient for a production execution system.
If the process restarts, the bot must still be able to reconstruct the state of outstanding orders.
A more reliable approach is to persist order events and reconcile them against the exchange.
You should also deduplicate fill notifications.
If the same fill event is delivered twice, the bot must not count it twice.
Otherwise, inventory and P&L calculations can become incorrect.
5. Handle Order Cancellation and Replacement Safely
Market makers constantly adjust their quotes as market conditions change.
Suppose your bot currently has this active order:
BUY 100 shares @ $0.48 The strategy recalculates the desired price:
BUY 100 shares @ $0.49 It seems simple: cancel the old order and submit a new one.
But there's a dangerous race condition.
Consider the following timeline:
10:00:00 Old order is active 10:00:01 Bot requests cancellation 10:00:02 New quote is calculated 10:00:03 Old order receives a fill 10:00:04 Cancellation is confirmed If the bot submits the replacement before accounting for the old order's fill, it may purchase more shares than intended.
A safer replacement workflow is:
Request Cancellation | v Wait for Result | v Reconcile Order State | v Calculate Remaining Exposure | v Validate Replacement | v Submit New Order The important distinction is between requesting cancellation and confirming cancellation.
They are not the same event.
Your execution controller must handle fills that occur while cancellation is pending.
It should also avoid assuming that cancel-and-replace is atomic unless the exchange explicitly supports that behavior.
6. Prioritize Execution Tasks Across Markets
When multiple markets require attention simultaneously, not every request should have equal priority.
Consider this example:
| Market | Event | Priority |
|---|---|---|
| BTC | Risk limit approaching | Critical |
| ETH | Cancel outdated order | High |
| SOL | Normal quote update | Medium |
| XRP | Minor price adjustment | Low |
A risk-reducing action should generally be processed before a routine quote adjustment.
Let's define priorities.
PRIORITY = { "CRITICAL": 1, "HIGH": 2, "MEDIUM": 3, "LOW": 4, } Then create a sorting function.
def sort_execution_tasks(tasks): return sorted( tasks, key=lambda task: PRIORITY[ task["priority"] ], ) Example:
tasks = [ {"market": "SOL", "priority": "MEDIUM"}, {"market": "BTC", "priority": "CRITICAL"}, {"market": "XRP", "priority": "LOW"}, {"market": "ETH", "priority": "HIGH"}, ] sorted_tasks = sort_execution_tasks(tasks) for task in sorted_tasks: print( task["market"], task["priority"], ) Output:
BTC CRITICAL ETH HIGH SOL MEDIUM XRP LOW This is a simple scheduling model.
A real scheduler also needs to account for pending actions, execution deadlines, queue capacity, and worker failures.
Priority alone doesn't guarantee safety.
For example, a high-priority cancellation still needs confirmation and reconciliation.
7. Avoid Excessive Quote Updates
Market-making strategies can calculate new quotes very frequently.
Imagine a strategy updating its desired bid every 100 milliseconds.
$0.480 $0.481 $0.480 $0.482 $0.481 If every tiny movement triggers a cancellation and replacement, the bot may generate unnecessary exchange traffic.
This creates several problems:
- More API requests.
- Higher risk of rate-limit errors.
- More complicated order tracking.
- Unnecessary loss of queue position.
- Greater operational overhead.
One solution is to introduce a quote refresh threshold.
from decimal import Decimal def should_refresh_quote( current_price, desired_price, threshold, ): difference = abs( desired_price - current_price ) return difference >= threshold Example:
current_price = Decimal("0.480") desired_price = Decimal("0.481") threshold = Decimal("0.005") refresh = should_refresh_quote( current_price, desired_price, threshold, ) print(refresh) Output:
False The difference is smaller than the configured threshold, so the bot keeps its existing quote.
This reduces unnecessary updates.
However, the threshold shouldn't be arbitrary.
It should reflect market tick size, volatility, execution costs, inventory exposure, and the value of retaining queue position.
A threshold that is too large can leave quotes stale.
A threshold that is too small can cause excessive replacement activity.
8. Introduce API Rate-Limit Control
A multi-market bot communicates with the exchange for many different operations.
These include:
- Submitting orders.
- Canceling orders.
- Checking order status.
- Retrieving balances.
- Reconciling fills.
- Refreshing market information.
If every strategy sends requests independently, the combined request volume can exceed exchange limits.
A centralized rate limiter helps coordinate this traffic.
One common approach is the token-bucket algorithm.
Implementing a token bucket in Python
import asyncio import time class TokenBucket: def __init__(self, capacity, refill_rate): self.capacity = capacity self.tokens = capacity self.refill_rate = refill_rate self.updated_at = time.monotonic() self.lock = asyncio.Lock() async def acquire(self): while True: async with self.lock: now = time.monotonic() elapsed = ( now - self.updated_at ) self.tokens = min( self.capacity, self.tokens + elapsed * self.refill_rate, ) self.updated_at = now if self.tokens >= 1: self.tokens -= 1 return await asyncio.sleep(0.05) Create a bucket:
bucket = TokenBucket( capacity=5, refill_rate=2, ) Before sending an API request:
async def send_request(): await bucket.acquire() print("Request permitted") This example allows an initial burst of up to five requests and replenishes tokens at two per second.
These numbers are illustrative, not Polymarket's documented rate limits.
A production implementation must use the exchange's current limits, including any endpoint-specific restrictions.
It must also coordinate workers and respond correctly to rate-limit errors.
9. Prevent Duplicate Orders After API Timeouts
One of the most dangerous execution problems occurs when the exchange's response is uncertain.
Imagine this sequence:
- The bot submits a buy order.
- The request times out.
- The bot assumes the order failed.
- The bot submits the same order again.
- Both requests are accepted.
Now the bot has twice the intended exposure.
The problem is that a timeout doesn't prove the exchange rejected the original request.
The bot needs a reconciliation process.
Create Internal Order ID | v Record Submission Attempt | v Send Exchange Request | v Response? / \ / \ v v Confirmed Timeout | | v v Update State UNKNOWN | v Reconcile Exchange | +-----+-----+ | | v v Found Not Found | | v v Update State Verify Before Retry The safest principle is:
Never automatically retry an uncertain order submission without first checking what happened.
Where the exchange supports client-generated identifiers or idempotency mechanisms, use them according to its documentation.
Otherwise, reconcile the actual exchange state before deciding whether a new submission is safe.
This is especially important when operating across several markets with shared capital.
10. Build a Central Asynchronous Execution Queue
Now we can combine order prioritization with asynchronous execution.
Instead of letting each strategy communicate directly with Polymarket, strategies submit tasks to a shared queue.
Python's asyncio.PriorityQueue is a useful starting point.
import asyncio import itertools async def execution_worker(queue): while True: priority, sequence, task = await queue.get() try: print( "Processing:", task["market"], task["action"], ) # Replace with real execution logic. finally: queue.task_done() async def main(): queue = asyncio.PriorityQueue( maxsize=1000 ) sequence = itertools.count() tasks = [ ( 1, { "market": "BTC", "action": "CANCEL_UNSAFE_ORDER", }, ), ( 3, { "market": "SOL", "action": "UPDATE_QUOTE", }, ), ( 2, { "market": "ETH", "action": "CHECK_ORDER_STATE", }, ), ] for priority, task in tasks: await queue.put(( priority, next(sequence), task, )) worker = asyncio.create_task( execution_worker(queue) ) await queue.join() worker.cancel() try: await worker except asyncio.CancelledError: pass asyncio.run(main()) Expected output:
Processing: BTC CANCEL_UNSAFE_ORDER Processing: ETH CHECK_ORDER_STATE Processing: SOL UPDATE_QUOTE The queue processes lower numeric priority values first.
We also use a sequence number to break ties between tasks with the same priority.
Without this, Python may attempt to compare dictionaries when two queued tasks have equal priorities.
This example uses a single worker and a bounded queue.
Production systems need additional controls for worker failures, persistent tasks, retries, and graceful shutdown.
They should also ensure that urgent risk-reducing actions aren't blocked indefinitely by large numbers of ordinary quote updates.
11. Keep Exchange-Specific Logic Behind an Adapter
Your strategy shouldn't need to understand the details of the exchange API.
Instead, define an internal execution interface.
Python's Protocol provides a convenient way to describe this contract.
from typing import Protocol class ExecutionClient(Protocol): async def submit_order(self, intent): ... async def cancel_order(self, order_id): ... async def get_order(self, order_id): ... async def get_open_orders(self): ... Your strategy can depend on this interface rather than directly importing exchange-specific code.
The architecture becomes:
Trading Strategy | v Execution Interface | v Polymarket Adapter | v Exchange API This design has several advantages.
You can replace the exchange adapter, introduce a simulated execution environment, or test strategy logic without submitting real orders.
It also makes API upgrades easier because exchange-specific changes remain isolated.
The interface methods above are illustrative internal methods, not verified Polymarket SDK method names.
Before implementing the adapter, consult the current official Polymarket documentation for supported order submission, cancellation, and status operations.
12. Monitor Execution Quality
A successful API response doesn't necessarily mean your execution system is performing well.
You need execution-specific metrics.
| Metric | Purpose |
|---|---|
| Submission latency | Measure order submission speed |
| Cancellation latency | Measure cancellation response time |
| Fill rate | Track how frequently orders execute |
| Partial-fill rate | Measure incomplete executions |
| Rejection rate | Detect invalid or rejected requests |
| Unknown order count | Identify unresolved submission states |
| Duplicate event count | Detect repeated event processing |
| API request rate | Monitor exchange traffic |
| Quote replacement rate | Measure order update frequency |
These metrics help identify operational problems.
For example, a high quote replacement rate may indicate that your strategy reacts too aggressively to small price movements.
A growing unknown-order count may indicate connectivity or reconciliation problems.
A high fill rate isn't automatically a positive result, either.
It can mean your quotes are being executed against by better-informed participants.
Execution quality should therefore be evaluated alongside P&L, inventory exposure, and adverse-selection metrics.
13. Putting Everything Together
We now have the main components of a centralized execution system.
A practical architecture looks like this:
Market Strategies | v Order Intents | v Execution Controller | +----------+----------+ | | v v Risk Manager Priority Scheduler | | +----------+----------+ | v Execution Queue | v Order Manager | v Rate Limiter | v Exchange Adapter | v Polymarket | v Order Reconciliation | v Database and Logs Each component has a clear responsibility.
Market strategies generate desired trading actions.
The execution controller coordinates those actions.
The risk manager checks whether they are permitted.
The priority scheduler decides which tasks should run first.
The order manager tracks each order throughout its lifecycle.
The rate limiter controls exchange API traffic.
The exchange adapter translates internal operations into actual exchange requests.
The reconciliation system verifies exchange state and keeps local records consistent.
This separation makes the trading system easier to test, maintain, and scale.
14. Production Testing Checklist
Before connecting the execution controller to live trading, test its behavior under normal and abnormal conditions.
Order lifecycle
- [ ] New order submission
- [ ] Full order fill
- [ ] Partial order fill
- [ ] Multiple partial fills
- [ ] Cancellation success and failure
- [ ] Cancellation delays
- [ ] Order replacement
- [ ] Duplicate fill events
- [ ] Unknown submission results
Execution control
- [ ] Priority queue ordering
- [ ] Rate-limit handling
- [ ] Queue capacity limits
- [ ] Worker failure recovery
- [ ] Graceful shutdown
- [ ] Per-market order tracking
Risk management
- [ ] Available capital validation
- [ ] Inventory limit enforcement
- [ ] Outstanding order exposure
- [ ] Stale market data rejection
- [ ] Risk-reducing task prioritization
- [ ] Unsafe retry prevention
Monitoring
- [ ] Submission latency
- [ ] Cancellation latency
- [ ] Order rejection rate
- [ ] Partial-fill tracking
- [ ] Unknown-order alerts
- [ ] Persistent execution logs
- [ ] Exchange reconciliation
Testing these scenarios in simulation or paper-trading mode helps identify dangerous assumptions before real capital is involved.
Conclusion
Building a market-making strategy is only one part of developing a reliable trading bot.
As soon as your system manages multiple markets, you need a centralized execution layer capable of coordinating orders, validating risk, tracking partial fills, handling cancellations, and recovering from uncertain API responses.
In this tutorial, we explored how to build that architecture using Python.
We introduced order intents, state management, priority scheduling, quote refresh thresholds, asynchronous queues, rate limiting, and exchange reconciliation.
The most important takeaway is simple:
A strategy decides what should happen. A reliable execution system ensures that the decision becomes a controlled, verifiable exchange operation.
That separation is what helps transform a basic trading script into a more maintainable multi-market trading platform.
What's Next? Day 21
Polymarket Market Maker Bot: Complete System Integration, End-to-End Testing, and Production Deployment
In Day 21, we'll connect the components developed throughout this series into a complete application.
We'll explore how market data, strategy calculation, risk management, capital allocation, execution, monitoring, analytics, and recovery work together.
Project Resources
If you're building your own Polymarket trading bot, you can explore the project ...


