How to trade BTC, ETH, SOL, and XRP markets simultaneously while managing shared capital, portfolio exposure, and execution risk.
Building a market-making bot for a single Polymarket market is one challenge. Running the same strategy across multiple markets introduces an entirely different set of engineering problems.
Imagine your Python bot is already monitoring BTC 5-minute Up/Down markets.
Everything works reasonably well. Your bot receives order book updates, calculates quotes, places orders, and tracks inventory.
Now you want to expand to:
- BTC Up/Down
- ETH Up/Down
- SOL Up/Down
- XRP Up/Down
The obvious solution is to create four independent trading workers.
But there's a problem.
All four workers may be using the same trading capital, and their positions may be exposed to the same market movements.
Without centralized coordination, your bot can overallocate funds, accumulate excessive exposure, or submit orders that violate portfolio-wide risk limits.
In Day 18 of our Polymarket Market Maker Bot series, we'll explore how to build a coordinated multi-market trading architecture using Python.
We'll cover:
- Multi-market trading architecture
- Shared capital allocation
- Reserved capital and available balances
- Independent strategy instances
- Centralized portfolio risk management
- Cross-market correlation
- Portfolio exposure and stress testing
- Dynamic capital allocation
- Asynchronous market execution
- Production readiness and scaling
Let's get started.
1. From a Single-Market Bot to a Multi-Market System
A single-market bot has a relatively straightforward architecture.
Market Data
|
v
Strategy Engine
|
v
Risk Checks
|
v
Order Execution
When you expand to multiple markets, simply duplicating this architecture isn't enough.
Each strategy needs its own market-specific state, but certain resources must be shared across the entire trading system.
A better architecture looks like this:
MULTI-MARKET BOT
|
+-------------+-------------+
| | |
v v v
BTC Bot ETH Bot SOL Bot
| | |
v v v
Strategy Strategy Strategy
| | |
+-------------+-------------+
|
v
CENTRAL RISK MANAGER
|
v
SHARED CAPITAL MANAGER
|
v
ORDER EXECUTION
|
v
PORTFOLIO MONITORING
Each market strategy independently handles:
- Market data
- Order book updates
- Quote calculations
- YES/NO inventory
- Active orders
- Market-specific configuration
Meanwhile, shared services handle:
- Capital allocation
- Portfolio exposure
- Correlation risk
- Trading limits
- Execution coordination
- Monitoring and analytics
This separation allows you to expand without losing control of your overall portfolio.
2. Why Independent Trading Bots Can Fail
Suppose your trading account contains 100 USDC.
You configure four trading bots:
| Market | Capital Budget |
|---|---|
| BTC | $40 |
| ETH | $40 |
| SOL | $40 |
| XRP | $40 |
| Total | $160 |
You only have $100, but your strategies collectively expect to use $160.
This creates a capital allocation problem.
And the situation becomes more complicated when you include open orders.
A strategy might have only $10 in filled positions but another $20 committed to pending buy orders.
Those orders may execute at any moment.
If multiple strategies independently assume that the same funds are available, the trading system can exceed its intended budget.
The solution is simple in principle:
Every market must request capital from one shared capital manager before submitting new orders.
Let's build one.
3. Implementing Centralized Capital Allocation
We'll start with a $100 trading budget.
Our illustrative allocation is:
| Market | Weight | Budget |
|---|---|---|
| BTC | 40% | $40 |
| ETH | 30% | $30 |
| SOL | 20% | $20 |
| XRP | 10% | $10 |
| Total | 100% | $100 |
These values demonstrate the architecture rather than a recommended trading allocation.
Step 1: Define allocation weights
from decimal import Decimal
TOTAL_CAPITAL = Decimal("100")
MARKET_WEIGHTS = {
"BTC": Decimal("0.40"),
"ETH": Decimal("0.30"),
"SOL": Decimal("0.20"),
"XRP": Decimal("0.10"),
}
Using Decimal is preferable to ordinary floating-point arithmetic for financial accounting.
Step 2: Calculate market budgets
def calculate_allocations(total_capital, weights):
if total_capital < 0:
raise ValueError("Capital cannot be negative")
if any(weight < 0 for weight in weights.values()):
raise ValueError("Weights cannot be negative")
total_weight = sum(weights.values())
if total_weight <= 0:
raise ValueError("Total weight must be positive")
return {
market: total_capital * weight / total_weight
for market, weight in weights.items()
}
allocations = calculate_allocations(
TOTAL_CAPITAL,
MARKET_WEIGHTS
)
for market, capital in allocations.items():
print(f"{market}: ${capital:.2f}")
Output:
BTC: $40.00
ETH: $30.00
SOL: $20.00
XRP: $10.00
The advantage of this approach is flexibility.
If your account budget increases or decreases, the allocation function can recalculate the market budgets automatically.
However, allocation alone doesn't prevent overspending.
We also need to track reserved capital.
4. Tracking Available and Reserved Capital
Let's assume BTC has a $40 allocation.
The strategy currently holds:
Allocated capital: $40
Reserved collateral: $15
Available capital: $25
A simplified relationship is:
Available Capital =
Allocated Capital - Reserved Capital
In a real prediction-market system, the accounting must distinguish collateral committed to buy orders from YES/NO tokens reserved for sell orders.
Filled positions, outstanding orders, and account balances must also be reconciled against exchange state.
For now, we'll implement a simplified reservation manager.
from decimal import Decimal
class CapitalManager:
def __init__(self, total_capital):
self.total_capital = Decimal(str(total_capital))
self.allocations = {}
self.reserved = {}
def allocate(self, market, amount):
amount = Decimal(str(amount))
if amount < 0:
raise ValueError("Invalid allocation")
proposed_total = (
sum(self.allocations.values())
- self.allocations.get(market, Decimal("0"))
+ amount
)
if proposed_total > self.total_capital:
raise ValueError("Account budget exceeded")
if amount < self.reserved.get(market, Decimal("0")):
raise ValueError("Below existing reservations")
self.allocations[market] = amount
self.reserved.setdefault(market, Decimal("0"))
def reserve(self, market, amount):
amount = Decimal(str(amount))
if amount < 0:
raise ValueError("Invalid reservation")
if amount > self.available(market):
raise ValueError("Insufficient market capital")
self.reserved[market] += amount
def release(self, market, amount):
amount = Decimal(str(amount))
if amount < 0 or amount > self.reserved[market]:
raise ValueError("Invalid release")
self.reserved[market] -= amount
def available(self, market):
allocated = self.allocations.get(
market, Decimal("0")
)
reserved = self.reserved.get(
market, Decimal("0")
)
return allocated - reserved
Example:
capital = CapitalManager("100")
capital.allocate("BTC", "40")
capital.allocate("ETH", "30")
capital.reserve("BTC", "15")
print(capital.available("BTC"))
Output:
25
This is an educational implementation, not a complete production ledger.
In production, reservations must be atomic across concurrent workers. A shared database transaction or another concurrency-safe reservation mechanism is necessary to prevent two workers from spending the same available balance.
You must also reconcile order fills, cancellations, settlement events, and exchange balances.
5. Creating Independent Market Strategy Instances
Now let's separate the trading state of each market.
Every market needs its own inventory and order tracking.
class MarketStrategy:
def __init__(self, market_id, config):
self.market_id = market_id
self.config = config
self.yes_inventory = Decimal("0")
self.no_inventory = Decimal("0")
self.active_orders = {}
def update_inventory(self, yes, no):
self.yes_inventory = Decimal(str(yes))
self.no_inventory = Decimal(str(no))
def register_order(self, order_id, order):
self.active_orders[order_id] = order
def remove_order(self, order_id):
self.active_orders.pop(order_id, None)
def status(self):
return {
"market": self.market_id,
"yes_inventory": self.yes_inventory,
"no_inventory": self.no_inventory,
"active_orders": len(self.active_orders),
}
We can now create separate instances:
markets = {
symbol: MarketStrategy(symbol, {})
for symbol in ["BTC", "ETH", "SOL", "XRP"]
}
Each strategy can calculate its own quotes using its market's order book and inventory.
For example, the BTC strategy doesn't need to know how the ETH strategy calculates quotes.
But it does need permission from the shared risk system before executing an order.
That brings us to the most important component.
6. Building a Central Portfolio Risk Manager
Imagine your bot currently has the following estimated exposures:
BTC: $30
ETH: $25
SOL: $20
XRP: $15
Total:
Portfolio Exposure = $90
Suppose your portfolio-wide exposure limit is $70.
Even if each individual strategy remains below its own market limit, the combined portfolio already exceeds the intended maximum.
A centralized risk manager must prevent additional exposure from being approved.
Implement a basic risk manager
class PortfolioRiskManager:
def __init__(
self,
max_total_exposure,
max_market_exposure
):
self.max_total_exposure = Decimal(
str(max_total_exposure)
)
self.max_market_exposure = Decimal(
str(max_market_exposure)
)
def approve(
self,
current_total,
market_exposure,
proposed_exposure
):
current_total = Decimal(str(current_total))
market_exposure = Decimal(str(market_exposure))
proposed_exposure = Decimal(str(proposed_exposure))
if proposed_exposure < 0:
return False
if (
current_total + proposed_exposure
> self.max_total_exposure
):
return False
if (
market_exposure + proposed_exposure
> self.max_market_exposure
):
return False
return True
Example:
risk = PortfolioRiskManager(
max_total_exposure="70",
max_market_exposure="30"
)
approved = risk.approve(
current_total="60",
market_exposure="20",
proposed_exposure="15"
)
print(approved)
Output:
False
The trade would increase portfolio exposure from $60 to $75.
Because the limit is $70, the trade is rejected.
This example assumes that the proposed order increases exposure by the specified amount. A real risk engine must distinguish exposure-increasing trades from exposure-reducing trades.
It must also consider existing orders, collateral requirements, and the actual payoff structure of YES/NO positions.
The risk manager should be the final authority before an order reaches the execution layer.
7. Understanding Cross-Market Correlation
Here's another important issue.
BTC, ETH, SOL, and XRP are separate markets, but their underlying asset prices may respond to common market events.
For example, a sudden cryptocurrency market selloff could affect several assets simultaneously.
If your bot holds positions that lose value under the same scenario, the portfolio may suffer multiple losses at once.
This is correlated risk.
What does correlation measure?
Correlation describes the degree of linear relationship between two variables.
Its coefficient ranges from -1 to +1.
| Correlation | Interpretation |
|---|---|
| +1 | Perfect positive linear correlation |
| 0 | No measured linear correlation |
| -1 | Perfect negative linear correlation |
Consider these hypothetical values:
BTC / ETH: 0.85
BTC / SOL: 0.78
BTC / XRP: 0.70
These numbers are examples, not live market measurements.
Calculate correlation with pandas
import pandas as pd
returns = pd.DataFrame({
"BTC": [0.01, -0.02, 0.03, -0.01, 0.02],
"ETH": [0.012, -0.018, 0.025, -0.012, 0.018],
"SOL": [0.015, -0.025, 0.04, -0.015, 0.03],
"XRP": [0.008, -0.01, 0.02, -0.005, 0.01],
})
correlation = returns.corr()
print(correlation.round(2))
This produces a correlation matrix for the sample returns.
For a production system, five observations are nowhere near enough.
You should use a larger historical dataset, align timestamps, handle missing data, and monitor rolling correlations.
There's also an important distinction:
Correlation between cryptocurrency prices is not necessarily the same as correlation between prediction-market token returns or strategy profits.
For Polymarket risk management, you should evaluate the actual YES/NO positions and the outcomes that affect their value.
8. Building a Portfolio Exposure Dashboard
When several strategies run simultaneously, you need a consolidated portfolio view.
A useful monitoring system should track:
- YES inventory
- NO inventory
- Active buy and sell orders
- Reserved collateral
- Market value of positions
- Net directional exposure
- Realized and unrealized P&L
- Portfolio-wide risk limits
Let's build a simple illustrative report.
portfolio = {
"BTC": {
"yes_exposure": 15,
"no_exposure": 5,
"open_order_exposure": 8,
},
"ETH": {
"yes_exposure": 10,
"no_exposure": 8,
"open_order_exposure": 5,
},
"SOL": {
"yes_exposure": 12,
"no_exposure": 4,
"open_order_exposure": 6,
},
"XRP": {
"yes_exposure": 5,
"no_exposure": 3,
"open_order_exposure": 4,
},
}
Calculate a simple gross exposure indicator:
def calculate_gross_exposure(portfolio):
total = 0
for market, positions in portfolio.items():
exposure = sum(positions.values())
print(f"{market}: ${exposure}")
total += exposure
print(f"Total: ${total}")
return total
calculate_gross_exposure(portfolio)
Output:
BTC: $28
ETH: $23
SOL: $22
XRP: $12
Total: $85
This is a simplified accounting indicator, not a complete measure of economic risk.
For example, matched YES and NO positions may have different settlement characteristics than unmatched directional positions.
A production dashboard should display gross commitments, collateral usage, net exposure, and scenario-based risk separately.
9. Portfolio Stress Testing
Correlation analysis helps identify relationships between markets.
But correlation alone cannot tell you how your portfolio will behave during extreme conditions.
That's where stress testing becomes useful.
Suppose we have the following illustrative positions:
| Market | Position Value | Simulated Shock |
|---|---|---|
| BTC | $30 | -15% |
| ETH | $25 | -20% |
| SOL | $20 | -25% |
We can estimate the change in value under this simplified scenario.
positions = {
"BTC": 30,
"ETH": 25,
"SOL": 20,
}
stress_changes = {
"BTC": -0.15,
"ETH": -0.20,
"SOL": -0.25,
}
total_change = 0
for market, value in positions.items():
change = value * stress_changes[market]
total_change += change
print(f"{market}: ${change:.2f}")
print(f"Portfolio Change: ${total_change:.2f}")
Output:
BTC: $-4.50
ETH: $-5.00
SOL: $-5.00
Portfolio Change: $-14.50
This illustrates a general valuation shock.
It does not directly model how Polymarket binary contracts settle.
A proper prediction-market stress engine should evaluate different YES/NO price and resolution scenarios, including trading fees and existing open-order commitments.
The important point is that you must test how the whole portfolio responds to adverse scenarios, not just each strategy individually.
10. Dynamic Capital Allocation
So far, we've assigned fixed capital weights:
BTC: 40%
ETH: 30%
SOL: 20%
XRP: 10%
But market conditions change.
One market may have deeper liquidity, while another may experience higher volatility or worse execution quality.
You may want to adapt capital allocations based on measurable market conditions.
Potential inputs include:
- Liquidity
- Volatility
- Bid-ask spread
- Execution quality
- Inventory concentration
- Available capital
- Adverse selection risk
Here's a basic scoring function:
def market_weight(
liquidity,
execution_quality,
volatility_penalty
):
score = (
liquidity
* execution_quality
* (1 - volatility_penalty)
)
return max(0, score)
Example inputs:
market_scores = {
"BTC": (0.9, 0.9, 0.1),
"ETH": (0.8, 0.8, 0.2),
"SOL": (0.7, 0.6, 0.3),
"XRP": (0.5, 0.7, 0.2),
}
Calculate normalized allocation weights:
raw_weights = {
market: market_weight(*scores)
for market, scores in market_scores.items()
}
total_weight = sum(raw_weights.values())
allocations = {
market: weight / total_weight
for market, weight in raw_weights.items()
}
for market, allocation in allocations.items():
print(f"{market}: {allocation:.2%}")
These scores are hypothetical, and this formula is not a validated trading model.
Before using dynamic allocation in production, you need to establish hard minimum and maximum limits, evaluate historical performance, and prevent excessive rebalancing.
Most importantly, dynamic allocation must never bypass the central risk manager.
11. Running Multiple Market Workers with asyncio
Our architecture is ready for multiple independent strategy instances.
Now we need a way to process them concurrently.
Python's asyncio library is useful for handling multiple market data streams and network operations.
Here's a simple example.
import asyncio
async def monitor_market(market):
while True:
print(f"Monitoring {market}")
await asyncio.sleep(1)
async def main():
markets = [
"BTC",
"ETH",
"SOL",
"XRP",
]
tasks = [
asyncio.create_task(
monitor_market(market)
)
for market in markets
]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Each market runs as an independent asynchronous task.
In a real implementation, the workers would process WebSocket updates, update order books, calculate quotes, and submit proposed orders to shared risk and execution services.
Production considerations
A reliable multi-market bot also needs:
- Automatic WebSocket reconnection
- Bounded event queues
- Backpressure handling
- Per-market exception handling
- Stale-data detection
- API rate-limit coordination
- Order cancellation and reconciliation
- Graceful shutdown
- Persistent strategy state
One failed market worker should not crash the entire trading system.
Likewise, a disconnected or stale market feed should prevent unsafe order submission for the affected market.
12. Putting Everything Together
Let's combine the components into one coordinated architecture.
POLYMARKET
|
v
MARKET DATA LAYER
|
+----------------+----------------+
| | |
v v v
BTC WORKER ETH WORKER SOL WORKER
| | |
v v v
BTC STRATEGY ETH STRATEGY SOL STRATEGY
| | |
+----------------+----------------+
|
v
ORDER PROPOSALS
|
v
CENTRAL RISK MANAGER
|
+---------+---------+
| |
v v
CAPITAL MANAGER PORTFOLIO MANAGER
| |
+---------+---------+
|
v
ORDER EXECUTION
|
v
ORDER STATE MANAGER
|
v
DATABASE / ANALYTICS
The order flow should work like this:
1. Receive market data
Each market worker maintains an up-to-date view of its order book.
2. Calculate a proposed quote
The strategy determines its desired price and size.
3. Check portfolio risk
The central risk manager evaluates market and portfolio limits.
4. Reserve required resources
The capital manager atomically reserves the collateral or inventory needed for the order.
5. Submit the order
The execution layer communicates with the exchange.
6. Reconcile order state
Fills, cancellations, and failures update the shared portfolio state.
7. Update monitoring
The dashboard reflects current inventory, commitments, and risk.
This architecture is more maintainable than duplicating a complete independent trading system for every market.
13. Common Mistakes When Scaling Market-Making Bots
Before expanding your bot, watch out for these mistakes.
Mistake 1: Double-counting available capital
Several strategies assume the same funds are available.
Solution: Use centralized, concurrency-safe reservations.
Mistake 2: Ignoring open orders
Risk calculations include filled positions but overlook pending orders.
Solution: Include open-order commitments in risk checks.
Mistake 3: Treating correlated markets as independent
Several positions lose value under the same broader market event.
Solution: Monitor cross-market exposure and run portfolio stress scenarios.
Mistake 4: Scaling too quickly
Adding ten markets before validating two creates unnecessary complexity.
Solution: Expand gradually and verify reliability at every stage.
Mistake 5: Failing to reconcile after restarts
The bot restarts with incomplete knowledge of outstanding exchange orders.
Solution: Reconcile balances, orders, and positions before resuming trading.
14. A Practical Development Roadmap
If you already have a working single-market Polymarket bot, here's a reasonable sequence for extending it.
| Phase | Implementation |
|---|---|
| 1 | Validate existing single-market strategy |
| 2 | Add centralized capital allocation |
| 3 | Introduce a second market worker |
| 4 | Implement portfolio-wide risk limits |
| 5 | Track combined inventory and open orders |
| 6 | Add correlation and stress testing |
| 7 | Implement asynchronous worker supervision |
| 8 | Build a consolidated monitoring dashboard |
| 9 | Test recovery and state reconciliation |
| 10 | Expand to additional markets gradually |
You don't need to build every component at once.
Start by making two markets operate safely under a shared budget.
Then add complexity only when the system demonstrates that it can handle the existing workload reliably.
Final Thoughts
Building a multi-market Polymarket bot isn't just about running more trading strategies.
It's about designing a system that understands the entire portfolio.
Each market should have its own strategy state, but all markets must share consistent capital accounting, execution coordination, and risk controls.
In this tutorial, we explored how to:
- Allocate capital across multiple markets
- Track available and reserved resources
- Create independent Python strategy instances
- Enforce centralized portfolio risk limits
- Analyze cross-market correlation
- Measure portfolio exposure
- Simulate adverse market scenarios
- Adjust capital allocations dynamically
- Run multiple workers asynchronously
- Design a scalable execution architecture
The central architectural principle is straightforward:
Independent strategies. Shared capital. Centralized risk. Coordinated execution.
That's the foundation for moving from a collection of trading scripts toward a more robust multi-market trading platform.
What's Next? Day 19
In the next tutorial, we'll focus on:
Polymarket Market Maker Bot: Real-Time Monitoring, Alerting, and Trading Operations Dashboard
We'll explore how to build a dashboard that monitors:
- Live market activity
- Active orders and inventory
- Capital utilization
- Portfolio exposure
- Trading performance
- Execution failures
- System health and alerts
The goal is to make your trading infrastructure observable, measurable, and easier to operate.
Project Resources
If you're following this Python Polymarket market-making series, check out the development resources:
GitHub Repository:
Benj4minCup
/
Polymarket-Trading-Bot-python
polymarket Twap Bot polymarket Arbitrage Bot polymarket bot Kalshi bot
Polymarket Trading bot system
An open-source and Strong Strategy collection of Polymarket trading bot and Polymarket arbitrage bot and Polymarket TWAP trading bot in Python for high-performance automated trading on polymarket crypto 5min and 15min markets.
This repository is primarily intended for educational and research purposes. It includes strategy concepts, implementation approaches, and selected performance screenshots to help developers understand how different automated trading strategies can be designed and tested.
The repository does not provide a complete production-ready trading bot source code. Instead, it provides strategy descriptions and research materials that you can use as a foundation for developing your own system.
If you are interested in building a Polymarket Trading Bot, you can follow my tutorials and use the concepts in this repository to develop your own implementation.
For users who prefer a ready-to-deploy solution or require custom strategy development, commercial bot development and customization are also available.
Features
…YouTube Tutorial:
Telegram Community:
https://telegram.me/BenjaminCup
Follow along as we continue building a more complete Python-based Polymarket trading system.
Tags: #python #blockchain #web3 #trading


Top comments (0)