Skip to content

Commit 08996b5

Browse files
authored
feat: market maker example script (#10)
1 parent 5fbcee0 commit 08996b5

File tree

4 files changed

+947
-766
lines changed

4 files changed

+947
-766
lines changed

.claude/skills/market-maker/SKILL.md

Lines changed: 60 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ TURBINE_API_PRIVATE_KEY={api_private_key}
138138
Present the user with these trading algorithm options for prediction markets:
139139

140140
**Option 1: Price Action Trader (Recommended)**
141+
- Reference: `examples/price_action_bot.py`
141142
- Uses real-time BTC price from Pyth Network (same oracle Turbine uses)
142143
- Compares current price to the market's strike price
143144
- If BTC is above strike price → buy YES (bet it stays above)
@@ -146,65 +147,83 @@ Present the user with these trading algorithm options for prediction markets:
146147
- Best for: Beginners, following price momentum
147148
- Risk: Medium - follows current price action
148149

149-
**Option 2: Simple Spread Market Maker**
150-
- Places bid and ask orders around the mid-price with a fixed spread
151-
- Best for: Learning the basics, stable markets
152-
- Risk: Medium - can accumulate inventory in trending markets
150+
**Option 2: Probability-Based Market Maker**
151+
- Reference: `examples/market_maker.py`
152+
- Dynamic pricing from Pyth BTC price vs strike with time decay
153+
- Multi-level bid/ask ladders on both YES and NO outcomes
154+
- Geometric size distribution concentrates liquidity at best prices
155+
- Spread tightens toward expiration (min 0.5%)
156+
- Best for: Providing liquidity, earning spread
157+
- Risk: Medium - manages both sides of the book
153158

154159
**Option 3: Inventory-Aware Market Maker**
160+
- Reference: `examples/market_maker.py` (modify pricing to skew based on position)
155161
- Adjusts quotes based on current position to reduce inventory risk
156162
- Skews prices to encourage trades that reduce position
157163
- Best for: Balanced exposure, risk management
158164
- Risk: Lower - actively manages inventory
159165

160166
**Option 4: Momentum-Following Trader**
167+
- Reference: `examples/price_action_bot.py` (modify signal logic)
161168
- Detects price direction from recent trades
162169
- Buys when momentum is up, sells when momentum is down
163170
- Best for: Trending markets, breakouts
164171
- Risk: Higher - can be wrong on reversals
165172

166173
**Option 5: Mean Reversion Trader**
174+
- Reference: `examples/price_action_bot.py` (modify signal logic)
167175
- Fades large moves expecting price to revert
168176
- Buys after dips, sells after spikes
169177
- Best for: Range-bound markets, overreactions
170178
- Risk: Higher - can fight strong trends
171179

172180
**Option 6: Probability-Weighted Trader**
181+
- Reference: `examples/price_action_bot.py` (modify signal logic)
173182
- Uses distance from 50% as a signal
174183
- Bets on extremes reverting toward uncertainty
175184
- Best for: Markets with overconfident pricing
176185
- Risk: Medium - based on market efficiency assumptions
177186

178-
## Reference Implementation
187+
## Reference Implementations
179188

180-
A complete, production-ready implementation exists for the **Price Action Trader**:
189+
There are two production-ready reference implementations. Choose based on the algorithm type:
181190

182-
**`examples/price_action_bot.py`**
183-
- Signs a single gasless max USDC permit per settlement contract on first trade
184-
- All subsequent orders use the existing allowance (no per-order permit overhead)
185-
- Order sizing in USDC terms with position tracking
191+
### For Trading Bots (Options 1, 4, 5, 6): **`examples/price_action_bot.py`**
192+
- Directional trading: buys one side based on a signal
193+
- Position tracking and order verification
194+
- Pending order TX tracking to prevent double-ordering
195+
- Market expiration flag to stop trading 60s before expiry
196+
- Unclaimed winnings discovery from previous sessions
197+
198+
### For Market Maker Bots (Options 2, 3): **`examples/market_maker.py`**
199+
- Two-sided quoting on both YES and NO outcomes
200+
- Multi-level geometric order distribution
201+
- Dynamic probability pricing from Pyth BTC price
202+
- Allocation-based budgeting (total USDC split across 4 sides x N levels)
203+
- Cancel-then-place order refresh to avoid self-trade issues
204+
- Timeout-based WS loop that doesn't block on quiet markets
186205

187206
When generating a bot:
188-
1. **Read `examples/price_action_bot.py`** as the primary reference
189-
2. Copy the structure exactly, customizing only configuration parameters as needed
207+
1. **Read the appropriate reference file** based on the chosen algorithm type
208+
2. Copy the structure exactly, customizing only the strategy logic
190209
3. **DO NOT** use the simplified code snippets in this skill - they are incomplete
191210

192-
For **other algorithm options**, use the same bot structure but replace the algorithm-specific methods:
211+
For **trading bots**, replace these methods from `price_action_bot.py`:
193212
- `calculate_signal()` - Replace with the chosen algorithm's signal logic
194213
- `execute_signal()` - Adapt order placement to match the algorithm
195214
- `price_action_loop()` - Rename and adapt the main loop for the algorithm
196215

197-
The reference implementations include critical patterns that **MUST** be preserved in all bots:
198-
- Position syncing from API (`sync_position()`, `verify_position()`)
199-
- Pending order TX tracking (`pending_order_txs` set)
200-
- Trade verification (check failed_trades, pending_trades, recent trades)
201-
- Market transition detection with `market_expiring` flag
202-
- Unclaimed winnings discovery from previous sessions
203-
- Rate-limited claiming (15s delay between claims)
204-
- Async HTTP client for non-blocking external API calls
216+
For **market maker bots**, replace these methods from `market_maker.py`:
217+
- `calculate_target_prices_with_time()` - Replace with the chosen pricing model
218+
- `place_multi_level_quotes()` - Adapt quoting logic for the algorithm
219+
220+
Critical patterns that **MUST** be preserved in all bots:
205221
- Gasless max permit approval when entering new markets (`ensure_settlement_approved()`)
206222
- USDC-based order sizing (`calculate_shares_from_usdc()`)
207-
- Position tracking in USDC terms (`position_usdc` dict)
223+
- Async HTTP client for non-blocking external API calls
224+
- Market transition handling and automatic winnings claiming
225+
- Order cancellation using API query with `side` parameter (not local tracking alone)
226+
- Rate-limited claiming (15s delay between claims)
208227

209228
## Step 5: Generate the Bot Code
210229

@@ -590,27 +609,7 @@ When generating bots, use these implementations:
590609

591610
**⚠️ IMPORTANT: Use the reference implementation at `examples/price_action_bot.py`**
592611

593-
Read that file for the complete, production-ready implementation. The simplified snippet below is **incomplete** and missing critical patterns.
594-
595-
**Key methods in the reference implementation:**
596-
597-
- `get_current_btc_price()` - Fetches BTC price from Pyth Network (async, non-blocking)
598-
- `calculate_signal()` - Returns (action, confidence) based on price vs strike
599-
- `execute_signal()` - Places orders with proper verification flow
600-
- `price_action_loop()` - Main trading loop
601-
- `sync_position()` / `verify_position()` - Position management
602-
- `cleanup_pending_orders()` - Handles settling orders
603-
- `discover_unclaimed_markets()` - Finds winnings from previous sessions
604-
605-
**The reference implementation handles (that the snippet below does NOT):**
606-
607-
- Async HTTP client for non-blocking price fetches
608-
- Position verification after every order attempt
609-
- Pending order tracking to prevent double-ordering
610-
- Failed trade detection immediately after submission
611-
- Market expiration flag to stop trading 60s before expiry
612-
- Processed trade ID tracking to avoid double-counting fills
613-
- Rate-limited claiming with 15s delays
612+
Read that file for the complete, production-ready implementation. The simplified snippets in this skill are **incomplete** and missing critical patterns.
614613

615614
**Algorithm summary:**
616615

@@ -620,35 +619,28 @@ Read that file for the complete, production-ready implementation. The simplified
620619
- If BTC < strike by threshold → buy NO
621620
- Confidence scales with distance from strike (capped at 90%)
622621

623-
### Simple Spread Market Maker
624-
```python
625-
SPREAD_BPS = 200 # 2% total spread (1% each side)
626-
627-
def calculate_quotes(self, mid_price):
628-
"""Calculate bid/ask around mid price."""
629-
half_spread = (mid_price * SPREAD_BPS) // 20000
630-
bid = max(1, mid_price - half_spread)
631-
ask = min(999999, mid_price + half_spread)
632-
return bid, ask
633-
```
622+
### Probability-Based Market Maker
634623

635-
### Inventory-Aware Market Maker
636-
```python
637-
SPREAD_BPS = 200
638-
SKEW_FACTOR = 50 # BPS skew per share of inventory
624+
**⚠️ IMPORTANT: Use the reference implementation at `examples/market_maker.py`**
639625

640-
def calculate_quotes(self, mid_price):
641-
"""Skew quotes based on inventory."""
642-
half_spread = (mid_price * SPREAD_BPS) // 20000
626+
Read that file for the complete, production-ready implementation.
643627

644-
# Skew to reduce inventory
645-
inventory_shares = self.current_position / 1_000_000
646-
skew = int(inventory_shares * SKEW_FACTOR)
628+
**Algorithm summary:**
647629

648-
bid = max(1, mid_price - half_spread - skew)
649-
ask = min(999999, mid_price + half_spread - skew)
650-
return bid, ask
651-
```
630+
- Fetches BTC price from Pyth Network, compares to strike price
631+
- YES target = 0.50 + (price_deviation% * sensitivity), with time decay
632+
- Quotes multi-level bid/ask ladders on both YES and NO outcomes
633+
- Geometric distribution (lambda=1.5) concentrates liquidity at best prices
634+
- Spread tightens toward expiration (min 0.5%)
635+
- Requotes only when target shifts >2% (rebalance threshold)
636+
- Cancel-then-place refresh avoids self-trade issues
637+
- Timeout-based WS recv loop prevents blocking on quiet markets
638+
639+
### Inventory-Aware Market Maker
640+
641+
**⚠️ IMPORTANT: Use `examples/market_maker.py` as the base, then modify pricing to skew based on position.**
642+
643+
Add position tracking and skew the target probability based on inventory to encourage trades that reduce exposure.
652644

653645
### Momentum Following
654646
```python

0 commit comments

Comments
 (0)