def __post_init__(self):
self.k = constant(self.y, self.n, self.p)
@property
def probability(self) -> float:
return probability(self.y, self.n, self.p)
@property
def value(self) -> float:
return ((self.max - self.min) * self.probability) + self.min
def bet_yes(self, mana: int) -> Market:
new_n = self.n + mana
new_y = yes(new_n, self.p, self.k)
return Market(self.id, new_y, new_n, self.p, self.min, self.max)
def return_for_yes(self, mana: int) -> Tuple[float, float]:
new_market = self.bet_yes(mana)
return self.y + mana - new_market.y, new_market.probability
def bet_no(self, mana: int) -> Market:
new_y = self.y + mana
new_n = no(new_y, self.p, self.k)
return Market(self.id, new_y, new_n, self.p, self.min, self.max)
def return_for_no(self, mana: int) -> Tuple[float, float]:
new_market = self.bet_no(mana)
return self.n + mana - new_market.n, new_market.probability
# how much mana to spend to get to prob
def mana_for_prob(self, prob: float, max_mana: int = 1000) -> int:
assert 0 < prob < 1
mult = 1
if prob < self.probability:
# buy NO
mult = -1
outcomes = [abs(self.return_for_no(mana)[1] - prob)
for mana in range(0, max_mana + 1)]
else:
# buy YES
outcomes = [abs(self.return_for_yes(mana)[1] - prob)
for mana in range(0, max_mana + 1)]
smallest_index = outcomes.index(min(outcomes))
if smallest_index > max_mana:
return 0
return smallest_index * mult
def market_from_manifold_market(market: dict) -> Market:
p = market["p"]
n = market["pool"]['NO']
y = market["pool"]['YES']
min = market.get("min", 0)
max = market.get("max", 100)
return Market(market['id'], y, n, p, min, max)
Excellent! You've provided the actual implementation details of the prediction market mechanics, specifically using a Constant Function Market Maker (CFMM) model adapted for binary outcome markets (YES/NO). This is similar to how platforms like Manifold Markets operate.
Let's quickly recap the key formulas:
constant(y, n, p) calculates k = y^p * n^(1-p), which is the invariant (conserved quantity) of the market.
probability(y, n, p) gives the current market probability of "YES": p * n / (p*n + (1-p)*y).
yes(n, p, k) and no(y, p, k) are the inverse functions that tell you the new y (YES pool) or n (NO pool) after a trade, given the updated pool size and the conserved k.
With these, your Market class can simulate trades (bet_yes, bet_no), calculate returns, and even find how much "mana" (the platform's currency) is needed to reach a target probability (mana_for_prob).
Now, let's adapt the arbitrage strategy I outlined earlier to work with your specific Market class and the CFMM model.
Goal: Given two markets market_a and market_b with the same resolution criteria but different current probabilities, find the optimal amount of mana to spend in each market to converge their probabilities while maximizing profit.
Here's a step-by-step algorithm, with Python code snippets:
Step 1: Define the Arbitrage Function
We'll create a function find_arbitrage_opportunity(market_a, market_b, max_mana) that:
Takes two Market objects and a max_mana budget.
Returns the optimal mana amounts to spend: (mana_a_no, mana_b_yes, final_profit).
def find_arbitrage_opportunity(market_a: Market, market_b: Market, max_mana: int) -> Tuple[int, int, float]:
"""
Find the optimal mana to spend:
- Buy NO in market_a (if P_A > P_B)
- Buy YES in market_b
Until their probabilities converge or we hit max_mana.
"""
if market_a.probability < market_b.probability:
# Swap markets to ensure market_a has higher P(YES)
market_a, market_b = market_b, market_a
# Step 2: Define the search bounds
low_mana = 0
high_mana = max_mana // 2 # We'll split max_mana between A and B
best_profit = 0.0
best_mana_a_no = 0
best_mana_b_yes = 0
while low_mana <= high_mana:
mid_mana = (low_mana + high_mana) // 2
# Simulate buying NO in A and YES in B
new_market_a = market_a.bet_no(mid_mana)
new_market_b = market_b.bet_yes(mid_mana)
# Check the new probabilities
p_a_yes = new_market_a.probability
p_b_yes = new_market_b.probability
# Calculate the COST (mana spent) and PAYOUT (if probabilities converge)
cost_a = mid_mana
cost_b = mid_mana
total_cost = cost_a + cost_b
# Since we're buying equal "potential payout" shares:
# - If YES resolves: payout = mid_mana (from B)
# - If NO resolves: payout = mid_mana (from A)
potential_payout = mid_mana
profit = potential_payout - total_cost
# Check if this is the best profit so far AND probabilities are close
if profit > best_profit and abs(p_a_yes - p_b_yes) < 0.01: # 1% tolerance
best_profit = profit
best_mana_a_no = mid_mana
best_mana_b_yes = mid_mana
# Bisection search logic:
if p_a_yes < p_b_yes:
# We overshot: probabilities crossed over. Reduce mana.
high_mana = mid_mana - 1
else:
# Probabilities still diverging; try more mana.
low_mana = mid_mana + 1
return best_mana_a_no, best_mana_b_yes, best_profit
Step 2: Fetch Markets and Run the Arbitrage
Now, let's say you fetch two markets from the Manifold API:
python
import requests
def fetch_manifold_markets(market_ids):
markets = []
for market_id in market_ids:
response = requests.get(f"https://manifold.markets/api/v0/market/{market_id}")
market_data = response.json()
market = market_from_manifold_market(market_data)
markets.append(market)
return markets
# Example usage
market_ids = ["market1_id", "market2_id"] # Replace with actual IDs
market_a, market_b = fetch_manifold_markets(market_ids)
print(f"Market A (YES): {market_a.probability:.2%}")
print(f"Market B (YES): {market_b.probability:.2%}")
max_mana_to_risk = 1000 # Your budget
mana_a_no, mana_b_yes, profit = find_arbitrage_opportunity(market_a, market_b, max_mana_to_risk)
if profit > 0:
print(f"ARBITRAGE FOUND!")
print(f" Buy {mana_a_no} mana NO in Market A")
print(f" Buy {mana_b_yes} mana YES in Market B")
print(f" Expected profit: {profit:.2f} mana")
else:
print("No profitable arbitrage opportunity within the given mana budget.")
How It Works:
find_arbitrage_opportunity performs a bisection search over the mana amounts to spend.
For each mid_mana:
It simulates buying mid_mana NO shares in market_a and mid_mana YES shares in market_b.
Checks the new probabilities (p_a_yes, p_b_yes).
Computes the cost (total_cost = mid_mana + mid_mana) and the payout (mid_mana, since we're hedged).
The profit is payout - total_cost.
If the profit is positive and probabilities are close (e.g., within 1%), it updates the best solution.
The bisection logic adjusts low_mana and high_mana based on whether p_a_yes is still > p_b_yes (keep buying) or they've crossed over (too much mana).
Once the search converges, it returns the optimal (mana_a_no, mana_b_yes, profit).
Notes:
Slippage Tolerance: The abs(p_a_yes - p_b_yes) < 0.01 check ensures we don't over-optimize; in practice, tiny differences aren't worth the extra mana.
Execution: In a real trading bot, you'd place these orders near-simultaneously to avoid price movement between trades.
Fees: If Manifold charges fees on bets, factor those into total_cost.
Multiple Markets: You can extend this to scan N markets for the best A/B pair with diverging probabilities.
This implementation leverages your existing Market class and the CFMM math to efficiently find the optimal arbitrage trade sizes that converge probabilities while maximizing your mana profit.