-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmarket_maker_bot.py
More file actions
671 lines (587 loc) · 21.7 KB
/
market_maker_bot.py
File metadata and controls
671 lines (587 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
"""
Reference market maker example.
WARNING:
- This script is for educational/reference purposes only.
- Do NOT run on mainnet with real funds unless you fully understand and audit it.
- Automated trading can lose money due to market volatility, latency, and config mistakes.
"""
from __future__ import annotations
import argparse
import asyncio
import math
import os
from dataclasses import dataclass
from decimal import ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_EVEN, Decimal
from enum import StrEnum
from aptos_sdk.account import Account
from aptos_sdk.ed25519 import PrivateKey
from decibel import (
NAMED_CONFIGS,
BaseSDKOptions,
DecibelWriteDex,
GasPriceManager,
PlaceOrderSuccess,
TimeInForce,
)
from decibel.read import DecibelReadDex, PerpMarket
@dataclass(frozen=True)
class MMSettings:
market_name: str = "BTC/USD"
spread: float = 0.001
order_size: float = 0.001
max_inventory: float = 0.005
skew_per_unit: float = 0.0001
max_margin_usage: float = 0.5
refresh_interval_s: float = 20.0
cooldown_s: float = 1.5
cancel_resync_s: float = 8.0
max_cycles: int = 0
dry_run: bool = False
class QuoteStatus(StrEnum):
OK = "ok"
PAUSE_NO_PRICE = "pause_no_price"
PAUSE_INVENTORY_LIMIT = "pause_inventory_limit"
PAUSE_SIZE_INVALID = "pause_size_invalid"
@dataclass(frozen=True)
class QuoteDecision:
status: QuoteStatus
bid: Decimal | None = None
ask: Decimal | None = None
size: Decimal | None = None
def _env_bool(name: str, default: bool = False) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "y", "on"}
def _normalize_market_name(name: str) -> str:
return name.strip().replace("-", "/").upper()
def _resolve_market(markets: list[PerpMarket], requested_name: str) -> PerpMarket | None:
requested = _normalize_market_name(requested_name)
for market in markets:
if _normalize_market_name(market.market_name) == requested:
return market
return None
def _to_decimal(value: float | int | str | Decimal) -> Decimal:
if isinstance(value, Decimal):
return value
return Decimal(str(value))
def _decimal_scale(decimals: int) -> Decimal:
return Decimal(10) ** decimals
def _round_to_tick_size_decimal(
price: Decimal, tick_size: int, px_decimals: int, round_up: bool
) -> Decimal:
if price == 0:
return Decimal(0)
scale = _decimal_scale(px_decimals)
denormalized = price * scale
ticks = denormalized / Decimal(tick_size)
rounding = ROUND_CEILING if round_up else ROUND_FLOOR
rounded_ticks = ticks.to_integral_value(rounding=rounding)
rounded_units = rounded_ticks * Decimal(tick_size)
return rounded_units / scale
def _round_to_valid_order_size_decimal(
order_size: Decimal,
lot_size: int,
sz_decimals: int,
min_size: int,
) -> Decimal:
if order_size == 0:
return Decimal(0)
scale = _decimal_scale(sz_decimals)
normalized_min_size = Decimal(min_size) / scale
if order_size < normalized_min_size:
return normalized_min_size
denormalized = order_size * scale
lots = (denormalized / Decimal(lot_size)).to_integral_value(rounding=ROUND_HALF_EVEN)
rounded_units = lots * Decimal(lot_size)
return rounded_units / scale
def _decimal_to_chain_units(amount: Decimal, decimals: int) -> int:
scale = _decimal_scale(decimals)
return int((amount * scale).to_integral_value(rounding=ROUND_HALF_EVEN))
def _compute_quotes(
*,
mid: float,
inventory: float,
market: PerpMarket,
settings: MMSettings,
) -> QuoteDecision:
tick_size = int(market.tick_size)
lot_size = int(market.lot_size)
min_size = int(market.min_size)
if mid <= 0:
return QuoteDecision(status=QuoteStatus.PAUSE_NO_PRICE)
if not math.isfinite(settings.spread) or settings.spread <= 0:
raise ValueError("spread must be a finite value > 0; adjust --spread")
if not math.isfinite(settings.max_inventory) or settings.max_inventory <= 0:
raise ValueError("max_inventory must be a finite value > 0; adjust --max-inventory")
if not math.isfinite(settings.max_margin_usage) or settings.max_margin_usage <= 0:
raise ValueError("max_margin_usage must be a finite value > 0; adjust --max-margin-usage")
mid_d = _to_decimal(mid)
inventory_d = _to_decimal(inventory)
spread_d = _to_decimal(settings.spread)
max_inventory_d = _to_decimal(settings.max_inventory)
tick_human = Decimal(tick_size) / _decimal_scale(market.px_decimals)
min_spread = tick_human / mid_d
if spread_d < min_spread:
raise ValueError(
f"spread {settings.spread} is tighter than one tick ({min_spread:.8f}); "
"increase --spread",
)
if abs(inventory_d) >= max_inventory_d:
return QuoteDecision(status=QuoteStatus.PAUSE_INVENTORY_LIMIT)
if not math.isfinite(settings.order_size) or settings.order_size <= 0:
return QuoteDecision(status=QuoteStatus.PAUSE_SIZE_INVALID)
valid_size = _round_to_valid_order_size_decimal(
_to_decimal(settings.order_size),
lot_size=lot_size,
sz_decimals=market.sz_decimals,
min_size=min_size,
)
if valid_size <= 0:
return QuoteDecision(status=QuoteStatus.PAUSE_SIZE_INVALID)
half_spread = spread_d / Decimal(2)
skew = inventory_d * _to_decimal(settings.skew_per_unit)
raw_bid = mid_d * (Decimal(1) - half_spread - skew)
raw_ask = mid_d * (Decimal(1) + half_spread - skew)
if (not raw_bid.is_finite()) or (not raw_ask.is_finite()) or raw_bid <= 0 or raw_ask <= 0:
raise ValueError(
"computed quote prices are non-positive/invalid; adjust --skew-per-unit "
"or --max-inventory",
)
bid = _round_to_tick_size_decimal(
raw_bid,
tick_size=tick_size,
px_decimals=market.px_decimals,
round_up=False,
)
ask = _round_to_tick_size_decimal(
raw_ask,
tick_size=tick_size,
px_decimals=market.px_decimals,
round_up=True,
)
if ask <= bid:
ask = _round_to_tick_size_decimal(
bid + tick_human,
tick_size=tick_size,
px_decimals=market.px_decimals,
round_up=True,
)
if (not bid.is_finite()) or (not ask.is_finite()) or bid <= 0 or ask <= 0:
raise ValueError(
"rounded quote prices are non-positive/invalid; adjust --skew-per-unit "
"or --max-inventory",
)
return QuoteDecision(
status=QuoteStatus.OK,
bid=bid,
ask=ask,
size=valid_size,
)
async def _sync_state(
read: DecibelReadDex,
market: PerpMarket,
subaccount_addr: str,
) -> tuple[float | None, float, float, list[str]]:
overview_task = read.account_overview.get_by_addr(sub_addr=subaccount_addr)
positions_task = read.user_positions.get_by_addr(sub_addr=subaccount_addr, limit=100)
orders_task = read.user_open_orders.get_by_addr(sub_addr=subaccount_addr, limit=200)
prices_task = read.market_prices.get_by_name(market.market_name)
overview, positions, open_orders, prices = await asyncio.gather(
overview_task,
positions_task,
orders_task,
prices_task,
)
inventory = 0.0
for pos in positions:
if pos.market == market.market_addr:
inventory = pos.size
break
market_order_ids = [
order.order_id for order in open_orders.items if order.market == market.market_addr
]
mid: float | None = None
for price in prices:
if price.market == market.market_addr:
mid = price.mid_px
break
if mid is None:
try:
depth = await read.market_depth.get_by_name(market.market_name, limit=1)
if depth.bids and depth.asks:
mid = (depth.bids[0].price + depth.asks[0].price) / 2.0
except Exception as exc:
print(f" warning: failed depth fallback for {market.market_name}: {exc}")
return mid, inventory, overview.cross_margin_ratio, market_order_ids
async def _cancel_market_orders(
write: DecibelWriteDex | None,
market_name: str,
order_ids: list[str],
subaccount_addr: str,
dry_run: bool,
) -> tuple[int, int]:
cancelled = 0
failed = 0
for order_id in order_ids:
if dry_run:
print(f" [dry-run] would cancel {order_id}")
cancelled += 1
continue
if write is None:
raise RuntimeError("write client is required when not in dry-run mode")
try:
await write.cancel_order(
order_id=order_id,
market_name=market_name,
subaccount_addr=subaccount_addr,
)
cancelled += 1
except Exception as exc:
print(f" cancel failed ({order_id}): {exc}")
failed += 1
return cancelled, failed
async def _place_quote(
write: DecibelWriteDex | None,
*,
market: PerpMarket,
subaccount_addr: str,
is_buy: bool,
price: Decimal,
size: Decimal,
dry_run: bool,
) -> None:
side = "bid" if is_buy else "ask"
if dry_run:
print(f" [dry-run] would place {side}: {price} x {size}")
return
if write is None:
raise RuntimeError("write client is required in live mode")
result = await write.place_order(
market_name=market.market_name,
price=_decimal_to_chain_units(price, market.px_decimals),
size=_decimal_to_chain_units(size, market.sz_decimals),
is_buy=is_buy,
time_in_force=TimeInForce.PostOnly,
is_reduce_only=False,
subaccount_addr=subaccount_addr,
)
if isinstance(result, PlaceOrderSuccess):
print(f" {side} placed: {price} x {size} (tx={result.transaction_hash[:16]}...)")
else:
print(f" {side} failed: {result.error}")
async def _run_cycle(
cycle: int,
*,
read: DecibelReadDex,
write: DecibelWriteDex | None,
market: PerpMarket,
subaccount_addr: str,
settings: MMSettings,
) -> None:
mid, inventory, margin_usage, open_order_ids = await _sync_state(read, market, subaccount_addr)
print(
f"\n[cycle {cycle}] mid={mid if mid is not None else 'N/A'} "
f"inventory={inventory:+.6f} "
f"margin={margin_usage * 100:.2f}% open_orders={len(open_order_ids)}"
)
if margin_usage > settings.max_margin_usage:
print(
f" paused: margin {margin_usage * 100:.2f}% > {settings.max_margin_usage * 100:.2f}%"
)
if (settings.dry_run or write is not None) and open_order_ids:
await _cancel_market_orders(
write,
market_name=market.market_name,
order_ids=open_order_ids,
subaccount_addr=subaccount_addr,
dry_run=settings.dry_run,
)
return
if mid is None:
print(" paused: no mid price available")
if (settings.dry_run or write is not None) and open_order_ids:
await _cancel_market_orders(
write,
market_name=market.market_name,
order_ids=open_order_ids,
subaccount_addr=subaccount_addr,
dry_run=settings.dry_run,
)
return
decision = _compute_quotes(
mid=mid,
inventory=inventory,
market=market,
settings=settings,
)
if decision.status is QuoteStatus.PAUSE_INVENTORY_LIMIT:
print(
f" paused: inventory {inventory:+.6f} at/above max {settings.max_inventory}; "
"canceling resting orders only"
)
if (settings.dry_run or write is not None) and open_order_ids:
await _cancel_market_orders(
write,
market_name=market.market_name,
order_ids=open_order_ids,
subaccount_addr=subaccount_addr,
dry_run=settings.dry_run,
)
return
if decision.status is QuoteStatus.PAUSE_SIZE_INVALID:
raise ValueError(
"invalid order size: must be finite and > 0, and must not round to 0 after "
"market lot/min-size constraints; adjust --order-size or market lot/min size"
)
if decision.status is QuoteStatus.PAUSE_NO_PRICE:
print(" paused: invalid mid price")
if (settings.dry_run or write is not None) and open_order_ids:
await _cancel_market_orders(
write,
market_name=market.market_name,
order_ids=open_order_ids,
subaccount_addr=subaccount_addr,
dry_run=settings.dry_run,
)
return
if decision.bid is None or decision.ask is None or decision.size is None:
raise RuntimeError(f"unexpected quote decision: {decision.status}")
bid, ask, size = decision.bid, decision.ask, decision.size
print(f" quotes: bid={bid} ask={ask} size={size}")
failed = 0
if (settings.dry_run or write is not None) and open_order_ids:
cancelled, failed = await _cancel_market_orders(
write,
market_name=market.market_name,
order_ids=open_order_ids,
subaccount_addr=subaccount_addr,
dry_run=settings.dry_run,
)
print(f" cancelled={cancelled} failed={failed}")
if failed > 0:
await asyncio.sleep(settings.cancel_resync_s)
still_open = await read.user_open_orders.get_by_addr(sub_addr=subaccount_addr, limit=200)
market_still_open = [o for o in still_open.items if o.market == market.market_addr]
if market_still_open:
print(f" still {len(market_still_open)} open orders, skip this cycle")
return
await _place_quote(
write,
market=market,
subaccount_addr=subaccount_addr,
is_buy=True,
price=bid,
size=size,
dry_run=settings.dry_run,
)
await asyncio.sleep(settings.cooldown_s)
await _place_quote(
write,
market=market,
subaccount_addr=subaccount_addr,
is_buy=False,
price=ask,
size=size,
dry_run=settings.dry_run,
)
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Single-file Decibel market maker bot: each cycle cancels existing market "
"orders and places a POST_ONLY bid/ask around mid price with inventory skew. "
"Reference only; avoid mainnet live trading unless fully audited."
),
)
def _env_default_numeric(name: str, default: float | int, caster: type[float] | type[int]):
raw = os.getenv(name)
if raw is None:
return default
try:
return caster(raw)
except ValueError:
parser.error(f"invalid value for {name}: {raw!r} (expected {caster.__name__})")
parser.add_argument(
"--network",
default=os.getenv("NETWORK", "testnet"),
choices=tuple(NAMED_CONFIGS),
help="Network profile key from decibel.NAMED_CONFIGS",
)
parser.add_argument(
"--market",
default=os.getenv("MARKET_NAME", "BTC/USD"),
help="Market symbol, e.g. BTC/USD",
)
parser.add_argument(
"--spread",
type=float,
default=_env_default_numeric("MM_SPREAD", 0.001, float),
)
parser.add_argument(
"--order-size",
type=float,
default=_env_default_numeric("MM_ORDER_SIZE", 0.001, float),
)
parser.add_argument(
"--max-inventory",
type=float,
default=_env_default_numeric("MM_MAX_INVENTORY", 0.005, float),
)
parser.add_argument(
"--skew-per-unit",
type=float,
default=_env_default_numeric("MM_SKEW_PER_UNIT", 0.0001, float),
)
parser.add_argument(
"--max-margin-usage",
type=float,
default=_env_default_numeric("MM_MAX_MARGIN", 0.5, float),
help="Pause quoting when cross_margin_ratio exceeds this value",
)
parser.add_argument(
"--refresh-interval",
type=float,
default=_env_default_numeric("MM_REFRESH_S", 20.0, float),
help="Seconds between cycles",
)
parser.add_argument(
"--cooldown",
type=float,
default=_env_default_numeric("MM_COOLDOWN_S", 1.5, float),
help="Seconds between placing bid and ask",
)
parser.add_argument(
"--cancel-resync",
type=float,
default=_env_default_numeric("MM_CANCEL_RESYNC_S", 8.0, float),
help="Sleep before re-checking open orders after cancel failures",
)
parser.add_argument(
"--max-cycles",
type=int,
default=_env_default_numeric("MAX_CYCLES", 0, int),
help="Stop after N cycles (0 = run forever)",
)
parser.add_argument(
"--dry-run",
action=argparse.BooleanOptionalAction,
default=_env_bool("DRY_RUN", False),
help="Simulate cancels/orders without sending transactions",
)
return parser.parse_args()
def _validate_settings(settings: MMSettings) -> None:
errors: list[str] = []
finite_positive_fields = (
("spread", settings.spread, "--spread"),
("order_size", settings.order_size, "--order-size"),
("max_inventory", settings.max_inventory, "--max-inventory"),
("skew_per_unit", settings.skew_per_unit, "--skew-per-unit"),
("max_margin_usage", settings.max_margin_usage, "--max-margin-usage"),
("refresh_interval_s", settings.refresh_interval_s, "--refresh-interval"),
("cooldown_s", settings.cooldown_s, "--cooldown"),
("cancel_resync_s", settings.cancel_resync_s, "--cancel-resync"),
)
for field_name, value, flag in finite_positive_fields:
if not math.isfinite(value) or value <= 0:
errors.append(f"{field_name} must be a finite value > 0; adjust {flag}")
if settings.max_cycles < 0:
errors.append("max_cycles must be >= 0; adjust --max-cycles")
if errors:
raise ValueError("; ".join(errors))
async def main() -> int:
args = _parse_args()
subaccount_addr = os.getenv("SUBACCOUNT_ADDRESS", "").strip()
node_api_key = os.getenv("APTOS_NODE_API_KEY", "").strip() or None
private_key_hex = os.getenv("PRIVATE_KEY", "").strip()
if not subaccount_addr:
print("Error: SUBACCOUNT_ADDRESS is required")
return 1
dry_run = args.dry_run
if not private_key_hex:
print("PRIVATE_KEY missing, forcing dry-run mode")
dry_run = True
settings = MMSettings(
market_name=args.market,
spread=args.spread,
order_size=args.order_size,
max_inventory=args.max_inventory,
skew_per_unit=args.skew_per_unit,
max_margin_usage=args.max_margin_usage,
refresh_interval_s=args.refresh_interval,
cooldown_s=args.cooldown,
cancel_resync_s=args.cancel_resync,
max_cycles=args.max_cycles,
dry_run=dry_run,
)
_validate_settings(settings)
config = NAMED_CONFIGS[args.network]
read = DecibelReadDex(config, api_key=node_api_key)
gas: GasPriceManager | None = None
write: DecibelWriteDex | None = None
try:
markets = await read.markets.get_all()
market = _resolve_market(markets, settings.market_name)
if market is None:
preview = ", ".join(m.market_name for m in markets[:8])
print(f"Market '{settings.market_name}' not found. Sample: {preview}")
return 1
print(f"Starting MM bot on {market.market_name} ({args.network})")
print(
f" spread={settings.spread} order_size={settings.order_size} "
f"max_inventory={settings.max_inventory} skew_per_unit={settings.skew_per_unit}"
)
print(
f" max_margin_usage={settings.max_margin_usage} "
f"refresh={settings.refresh_interval_s}s "
f"cooldown={settings.cooldown_s}s dry_run={settings.dry_run}"
)
# Safety reminder for anyone running this example as-is.
if args.network == "mainnet":
print(
" WARNING: This example is reference-only and may lose funds. "
"Do not run live on mainnet without full strategy/risk validation."
)
if not settings.dry_run:
# Live-mode sends real transactions. Use with caution.
private_key = PrivateKey.from_hex(private_key_hex)
account = Account.load_key(private_key.hex())
gas = GasPriceManager(config)
await gas.initialize()
write = DecibelWriteDex(
config,
account,
opts=BaseSDKOptions(
node_api_key=node_api_key,
gas_price_manager=gas,
skip_simulate=False,
no_fee_payer=True,
time_delta_ms=0,
),
)
cycle = 1
while True:
try:
await _run_cycle(
cycle,
read=read,
write=write,
market=market,
subaccount_addr=subaccount_addr,
settings=settings,
)
except ValueError as exc:
print(f"fatal config error: {exc}")
return 2
except Exception as exc:
print(f" [cycle {cycle} error] {exc}")
if settings.max_cycles > 0 and cycle >= settings.max_cycles:
break
cycle += 1
await asyncio.sleep(settings.refresh_interval_s)
finally:
await read.ws.close()
if gas is not None:
await gas.destroy()
return 0
if __name__ == "__main__":
raise SystemExit(asyncio.run(main()))