hypercall-rfq-example 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hypercall_rfq_example-0.1.0/.github/workflows/ci.yml +20 -0
- hypercall_rfq_example-0.1.0/.github/workflows/publish.yml +37 -0
- hypercall_rfq_example-0.1.0/.gitignore +5 -0
- hypercall_rfq_example-0.1.0/LICENSE +21 -0
- hypercall_rfq_example-0.1.0/PKG-INFO +68 -0
- hypercall_rfq_example-0.1.0/README.md +45 -0
- hypercall_rfq_example-0.1.0/maker.py +313 -0
- hypercall_rfq_example-0.1.0/pyproject.toml +35 -0
- hypercall_rfq_example-0.1.0/src/hypercall_rfq_example/__init__.py +5 -0
- hypercall_rfq_example-0.1.0/src/hypercall_rfq_example/client.py +569 -0
- hypercall_rfq_example-0.1.0/src/hypercall_rfq_example/signing.py +325 -0
- hypercall_rfq_example-0.1.0/tests/golden/rfq_v2_signing_vectors.json +365 -0
- hypercall_rfq_example-0.1.0/tests/test_client.py +346 -0
- hypercall_rfq_example-0.1.0/tests/test_example.py +176 -0
- hypercall_rfq_example-0.1.0/tests/test_signing_parity.py +76 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
on:
|
|
3
|
+
push:
|
|
4
|
+
branches: [main]
|
|
5
|
+
pull_request:
|
|
6
|
+
permissions:
|
|
7
|
+
contents: read
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python: ["3.11", "3.12", "3.13"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python }}
|
|
19
|
+
- run: pip install -e '.[test]'
|
|
20
|
+
- run: pytest -q
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
on:
|
|
3
|
+
push:
|
|
4
|
+
tags: ["v*"]
|
|
5
|
+
jobs:
|
|
6
|
+
build:
|
|
7
|
+
runs-on: ubuntu-latest
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
steps:
|
|
11
|
+
- uses: actions/checkout@v4
|
|
12
|
+
- uses: actions/setup-python@v5
|
|
13
|
+
with:
|
|
14
|
+
python-version: "3.12"
|
|
15
|
+
- run: pip install -e '.[test]' build
|
|
16
|
+
- run: pytest -q
|
|
17
|
+
- name: Tag matches pyproject version
|
|
18
|
+
run: |
|
|
19
|
+
v=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
|
|
20
|
+
test "v$v" = "$GITHUB_REF_NAME"
|
|
21
|
+
- run: python -m build
|
|
22
|
+
- uses: actions/upload-artifact@v4
|
|
23
|
+
with:
|
|
24
|
+
name: dist
|
|
25
|
+
path: dist/
|
|
26
|
+
publish:
|
|
27
|
+
needs: build
|
|
28
|
+
runs-on: ubuntu-latest
|
|
29
|
+
environment: pypi
|
|
30
|
+
permissions:
|
|
31
|
+
id-token: write
|
|
32
|
+
steps:
|
|
33
|
+
- uses: actions/download-artifact@v4
|
|
34
|
+
with:
|
|
35
|
+
name: dist
|
|
36
|
+
path: dist/
|
|
37
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hypercall
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: hypercall-rfq-example
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Demo helpers for the Hypercall RFQ v2 maker tutorial: EIP-712 signing, read grants, quoting, executions.
|
|
5
|
+
Project-URL: Homepage, https://github.com/hypercall-public/hypercall-rfq-example
|
|
6
|
+
Project-URL: Tutorial, https://blog.hypercall.xyz/build-an-rfq-v2-maker/
|
|
7
|
+
Project-URL: Documentation, https://docs.hypercall.xyz/docs/trading/over-api/rfq-v2
|
|
8
|
+
Author: Hypercall
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: eip712,hypercall,hyperliquid,market-making,options,rfq
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Requires-Dist: eth-account>=0.13
|
|
17
|
+
Requires-Dist: httpx>=0.27
|
|
18
|
+
Requires-Dist: websockets>=13
|
|
19
|
+
Provides-Extra: test
|
|
20
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
|
|
21
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# hypercall-rfq-example
|
|
25
|
+
|
|
26
|
+
Demo helpers and the demo maker (`maker.py`) for the Hypercall tutorial
|
|
27
|
+
[Build an RFQ V2 Maker](https://blog.hypercall.xyz/build-an-rfq-v2-maker/). They cover
|
|
28
|
+
read grants, the `rfq_v2` stream with change-feed replay, signed firm quotes,
|
|
29
|
+
declines, withdrawals, the cancel-schedule heartbeat, the executions stream,
|
|
30
|
+
the provider read, and perp hedge orders through Hypercall.
|
|
31
|
+
|
|
32
|
+
This is teaching code, kept short enough to read in one sitting. It is not a
|
|
33
|
+
supported SDK. For production integrations use the Rust client
|
|
34
|
+
(`hypercall-client`) or sign the documented EIP-712 messages yourself.
|
|
35
|
+
|
|
36
|
+
Needs Python 3.11 or newer (the maker uses `asyncio.TaskGroup`).
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install hypercall-rfq-example
|
|
40
|
+
curl -O https://raw.githubusercontent.com/hypercall-public/hypercall-rfq-example/main/maker.py
|
|
41
|
+
export HC_ACCOUNT=0xYourAccount HC_SIGNER_KEY=0xApiWalletKey
|
|
42
|
+
python maker.py --dry-run
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`--dry-run` prices and logs RFQs without posting quotes, declines, withdrawals
|
|
46
|
+
or hedges. Without it the maker posts firm, executable quotes.
|
|
47
|
+
|
|
48
|
+
On SIGINT or SIGTERM the maker withdraws every open quote and clears its
|
|
49
|
+
cancel schedule before it exits. A `kill -9` skips that; the 30-second
|
|
50
|
+
dead-man switch then withdraws the quotes instead.
|
|
51
|
+
|
|
52
|
+
The perp hedge only works for a portfolio margin Account contract with an
|
|
53
|
+
on-chain API wallet as the signer. See step 7 of the tutorial for the full
|
|
54
|
+
list; with a plain wallet as `HC_ACCOUNT`, hedge orders fail with
|
|
55
|
+
`400 unknown_account`.
|
|
56
|
+
|
|
57
|
+
## Tests
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install -e '.[test]' && pytest
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`tests/test_signing_parity.py` signs golden vectors generated by the Rust
|
|
64
|
+
signer and must match them byte for byte.
|
|
65
|
+
|
|
66
|
+
## License
|
|
67
|
+
|
|
68
|
+
MIT
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# hypercall-rfq-example
|
|
2
|
+
|
|
3
|
+
Demo helpers and the demo maker (`maker.py`) for the Hypercall tutorial
|
|
4
|
+
[Build an RFQ V2 Maker](https://blog.hypercall.xyz/build-an-rfq-v2-maker/). They cover
|
|
5
|
+
read grants, the `rfq_v2` stream with change-feed replay, signed firm quotes,
|
|
6
|
+
declines, withdrawals, the cancel-schedule heartbeat, the executions stream,
|
|
7
|
+
the provider read, and perp hedge orders through Hypercall.
|
|
8
|
+
|
|
9
|
+
This is teaching code, kept short enough to read in one sitting. It is not a
|
|
10
|
+
supported SDK. For production integrations use the Rust client
|
|
11
|
+
(`hypercall-client`) or sign the documented EIP-712 messages yourself.
|
|
12
|
+
|
|
13
|
+
Needs Python 3.11 or newer (the maker uses `asyncio.TaskGroup`).
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install hypercall-rfq-example
|
|
17
|
+
curl -O https://raw.githubusercontent.com/hypercall-public/hypercall-rfq-example/main/maker.py
|
|
18
|
+
export HC_ACCOUNT=0xYourAccount HC_SIGNER_KEY=0xApiWalletKey
|
|
19
|
+
python maker.py --dry-run
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`--dry-run` prices and logs RFQs without posting quotes, declines, withdrawals
|
|
23
|
+
or hedges. Without it the maker posts firm, executable quotes.
|
|
24
|
+
|
|
25
|
+
On SIGINT or SIGTERM the maker withdraws every open quote and clears its
|
|
26
|
+
cancel schedule before it exits. A `kill -9` skips that; the 30-second
|
|
27
|
+
dead-man switch then withdraws the quotes instead.
|
|
28
|
+
|
|
29
|
+
The perp hedge only works for a portfolio margin Account contract with an
|
|
30
|
+
on-chain API wallet as the signer. See step 7 of the tutorial for the full
|
|
31
|
+
list; with a plain wallet as `HC_ACCOUNT`, hedge orders fail with
|
|
32
|
+
`400 unknown_account`.
|
|
33
|
+
|
|
34
|
+
## Tests
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install -e '.[test]' && pytest
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`tests/test_signing_parity.py` signs golden vectors generated by the Rust
|
|
41
|
+
signer and must match them byte for byte.
|
|
42
|
+
|
|
43
|
+
## License
|
|
44
|
+
|
|
45
|
+
MIT
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Demo RFQ v2 market maker from the "Build an RFQ v2 maker" tutorial.
|
|
2
|
+
|
|
3
|
+
DEMO ONLY. This is not a risk system. It shows the shape of an RFQ V2 maker
|
|
4
|
+
on Hypercall, end to end:
|
|
5
|
+
|
|
6
|
+
stream RFQs (full view) -> price off Deribit's mark +/- a spread
|
|
7
|
+
-> post a signed firm quote -> read executions by cursor
|
|
8
|
+
-> hedge each execution's net delta with a Hyperliquid perp
|
|
9
|
+
-> renew a cancel schedule (dead-man switch) -> withdraw everything on exit
|
|
10
|
+
|
|
11
|
+
Its only limits are a cap on open quotes and on contracts per leg. It does
|
|
12
|
+
not track worst-case exposure across open quotes, reconcile positions after
|
|
13
|
+
a restart, or handle ambiguous quote outcomes. Bring your own limits before
|
|
14
|
+
quoting real size: quotes are firm, and once posted a taker can fill them.
|
|
15
|
+
|
|
16
|
+
pip install hypercall-rfq-example # or, from this folder: pip install .
|
|
17
|
+
export HC_ACCOUNT=0xYourAccount HC_SIGNER_KEY=0xApiWalletKey
|
|
18
|
+
python maker.py --dry-run # price and log, post nothing
|
|
19
|
+
python maker.py --host http://localhost:3000 --chain-id 998
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
import asyncio
|
|
26
|
+
import logging
|
|
27
|
+
import os
|
|
28
|
+
import signal
|
|
29
|
+
import time
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
from datetime import datetime
|
|
32
|
+
|
|
33
|
+
import httpx
|
|
34
|
+
|
|
35
|
+
from hypercall_rfq_example import Execution, Hypercall, HypercallError, Rfq
|
|
36
|
+
|
|
37
|
+
DERIBIT = "https://www.deribit.com/api/v2"
|
|
38
|
+
# Smaller residual deltas wait for the next fill. Hyperliquid refuses orders
|
|
39
|
+
# under about $10 of notional, so keep each minimum above $10 at the current price.
|
|
40
|
+
MIN_HEDGE = {"BTC": 0.001, "ETH": 0.01}
|
|
41
|
+
log = logging.getLogger("maker")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# ---- pricing (step 3) --------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def underlying(symbol: str) -> str:
|
|
48
|
+
return symbol.split("-")[0]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def to_deribit(symbol: str) -> str:
|
|
52
|
+
"""BTC-20261226-100000-C -> BTC-26DEC26-100000-C (Deribit drops the leading zero of the day)."""
|
|
53
|
+
coin, expiry, strike, kind = symbol.split("-")
|
|
54
|
+
day = datetime.strptime(expiry, "%Y%m%d")
|
|
55
|
+
return f"{coin}-{day.day}{day.strftime('%b%y').upper()}-{strike}-{kind}"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class Mark:
|
|
60
|
+
usd: float # mark price per contract, in USD
|
|
61
|
+
delta: float # per contract, from the long side
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Pricer:
|
|
65
|
+
def __init__(self, spread: float):
|
|
66
|
+
self.spread = spread
|
|
67
|
+
self.http = httpx.AsyncClient(base_url=DERIBIT, timeout=5)
|
|
68
|
+
|
|
69
|
+
async def mark(self, symbol: str) -> Mark:
|
|
70
|
+
r = await self.http.get("/public/ticker", params={"instrument_name": to_deribit(symbol)})
|
|
71
|
+
r.raise_for_status()
|
|
72
|
+
t = r.json()["result"]
|
|
73
|
+
# Deribit quotes options in the coin; convert to USD per contract.
|
|
74
|
+
return Mark(t["mark_price"] * t["underlying_price"], t["greeks"]["delta"])
|
|
75
|
+
|
|
76
|
+
async def price_leg(self, leg) -> float:
|
|
77
|
+
"""Deribit mark, plus the spread when the taker buys, minus when it sells."""
|
|
78
|
+
mark = (await self.mark(leg.instrument)).usd
|
|
79
|
+
return mark * (1 + self.spread) if leg.taker_side == "buy" else mark * (1 - self.spread)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# ---- the one guard (step 6) ------------------------------------------------------
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Limits:
|
|
86
|
+
"""A cap on open quotes and on contracts per leg. Not a risk system."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, max_open_quotes: int, max_contracts: float):
|
|
89
|
+
self.max_open_quotes = max_open_quotes
|
|
90
|
+
self.max_contracts = max_contracts
|
|
91
|
+
self.open: dict[str, float] = {} # quote id -> expires_at_ms
|
|
92
|
+
|
|
93
|
+
def allows(self, rfq: Rfq, units: int) -> bool:
|
|
94
|
+
now = time.time() * 1000
|
|
95
|
+
self.open = {q: exp for q, exp in self.open.items() if exp > now}
|
|
96
|
+
packages = units / 1_000_000
|
|
97
|
+
biggest_leg = max(float(leg.contracts_per_package) * packages for leg in rfq.legs)
|
|
98
|
+
return len(self.open) < self.max_open_quotes and biggest_leg <= self.max_contracts
|
|
99
|
+
|
|
100
|
+
def track(self, quote_id: str, expires_at_ms: float) -> None:
|
|
101
|
+
self.open[quote_id] = expires_at_ms
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# ---- the bot -------------------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Maker:
|
|
108
|
+
def __init__(self, hc: Hypercall, pricer: Pricer, limits: Limits, dry_run: bool, quote_ttl_s: float):
|
|
109
|
+
self.hc, self.pricer, self.limits = hc, pricer, limits
|
|
110
|
+
self.dry_run, self.quote_ttl_s = dry_run, quote_ttl_s
|
|
111
|
+
self.answered: set[str] = set()
|
|
112
|
+
self.unhedged: dict[str, float] = {} # options delta per coin not yet hedged
|
|
113
|
+
self.stats = {"rfqs": 0, "quoted": 0, "declined": 0, "executions": 0, "hedges": 0}
|
|
114
|
+
|
|
115
|
+
async def on_rfq(self, rfq: Rfq) -> None:
|
|
116
|
+
"""Step 4: quote or decline each new RFQ once."""
|
|
117
|
+
# Our own quote produces another change for this RFQ, so answer each
|
|
118
|
+
# RFQ once, before the first await.
|
|
119
|
+
if rfq.status != "open" or rfq.id in self.answered or rfq.maker_generation is None:
|
|
120
|
+
return
|
|
121
|
+
self.answered.add(rfq.id)
|
|
122
|
+
if rfq.quote_deadline_ms <= await self.hc.now_ms():
|
|
123
|
+
return
|
|
124
|
+
self.stats["rfqs"] += 1
|
|
125
|
+
legs = [(l.instrument, l.taker_side, str(l.contracts_per_package)) for l in rfq.legs]
|
|
126
|
+
units = rfq.target if rfq.fill_policy["mode"] == "full_size_once" else rfq.remaining_target
|
|
127
|
+
if not self.limits.allows(rfq, units):
|
|
128
|
+
log.info("rfq %s %s: over the open-quote or size limit, declining", rfq.id, legs)
|
|
129
|
+
return await self.decline(rfq)
|
|
130
|
+
try:
|
|
131
|
+
prices = [await self.pricer.price_leg(l) for l in rfq.legs]
|
|
132
|
+
except (httpx.HTTPError, KeyError, ValueError) as error:
|
|
133
|
+
log.info("rfq %s %s: no Deribit price (%s), declining", rfq.id, legs, error)
|
|
134
|
+
return await self.decline(rfq)
|
|
135
|
+
if any(p <= 0 for p in prices):
|
|
136
|
+
log.info("rfq %s %s: zero mark, declining", rfq.id, legs)
|
|
137
|
+
return await self.decline(rfq)
|
|
138
|
+
log.info("rfq %s %s: pricing %s", rfq.id, legs, [round(p, 6) for p in prices])
|
|
139
|
+
if self.dry_run:
|
|
140
|
+
return
|
|
141
|
+
try:
|
|
142
|
+
quote = await self.hc.rfq_v2.quote(rfq, prices=prices, capacity=units, expires_in_s=self.quote_ttl_s)
|
|
143
|
+
except (HypercallError, httpx.HTTPError, ValueError) as error:
|
|
144
|
+
log.warning("rfq %s: quote not posted: %s", rfq.id, error)
|
|
145
|
+
return
|
|
146
|
+
self.limits.track(quote.id, quote.expires_at_ms)
|
|
147
|
+
self.stats["quoted"] += 1
|
|
148
|
+
log.info("quote %s on rfq %s: executable=%s capacity=%s", quote.id, rfq.id, quote.executable, quote.capacity)
|
|
149
|
+
|
|
150
|
+
async def handle(self, rfq: Rfq) -> None:
|
|
151
|
+
await self.on_rfq(rfq)
|
|
152
|
+
self.hc.rfq_v2.ack(rfq) # not reached if handling raised or was cancelled
|
|
153
|
+
|
|
154
|
+
async def decline(self, rfq: Rfq) -> None:
|
|
155
|
+
self.stats["declined"] += 1
|
|
156
|
+
if not self.dry_run:
|
|
157
|
+
try:
|
|
158
|
+
await self.hc.rfq_v2.decline(rfq)
|
|
159
|
+
except (HypercallError, httpx.HTTPError) as error:
|
|
160
|
+
log.warning("rfq %s: decline refused: %s", rfq.id, error)
|
|
161
|
+
|
|
162
|
+
async def run_executions(self, cursor_file: str) -> None:
|
|
163
|
+
"""Step 5: every execution, once, in order: log it, then hedge it.
|
|
164
|
+
|
|
165
|
+
The cursor file resumes after the last execution handled, on a
|
|
166
|
+
restart and on every retry below, so no execution is hedged twice. A failed read or handler
|
|
167
|
+
is logged and retried with backoff instead of raised: inside the
|
|
168
|
+
TaskGroup an unhandled error would also stop RFQ intake and the
|
|
169
|
+
heartbeat.
|
|
170
|
+
"""
|
|
171
|
+
backoff = 1.0
|
|
172
|
+
while True:
|
|
173
|
+
try:
|
|
174
|
+
async for ex in self.hc.rfq_v2.executions(cursor_file=cursor_file):
|
|
175
|
+
await self.on_execution(ex)
|
|
176
|
+
backoff = 1.0
|
|
177
|
+
except asyncio.CancelledError:
|
|
178
|
+
raise
|
|
179
|
+
except Exception as error: # noqa: BLE001 - the feed must outlive any one failure
|
|
180
|
+
log.warning("executions feed failed, retrying in %.0fs: %s", backoff, error)
|
|
181
|
+
await asyncio.sleep(backoff)
|
|
182
|
+
backoff = min(backoff * 2, 60.0)
|
|
183
|
+
|
|
184
|
+
async def on_execution(self, ex: Execution) -> None:
|
|
185
|
+
if ex.role != "maker":
|
|
186
|
+
return
|
|
187
|
+
delta: dict[str, float] = {}
|
|
188
|
+
for leg in ex.legs:
|
|
189
|
+
mark = await self.pricer.mark(leg.instrument)
|
|
190
|
+
sign = 1 if leg.side == "buy" else -1
|
|
191
|
+
coin = underlying(leg.instrument)
|
|
192
|
+
delta[coin] = delta.get(coin, 0.0) + sign * float(leg.contracts) * mark.delta
|
|
193
|
+
self.stats["executions"] += 1
|
|
194
|
+
log.info(
|
|
195
|
+
"execution %s rfq %s quote %s units %s legs %s delta %s",
|
|
196
|
+
ex.execution_id, ex.rfq_id, ex.quote_id, ex.package_units,
|
|
197
|
+
[(l.instrument, l.side, str(l.contracts), str(l.price_usd)) for l in ex.legs], delta,
|
|
198
|
+
)
|
|
199
|
+
for coin, d in delta.items():
|
|
200
|
+
self.unhedged[coin] = self.unhedged.get(coin, 0.0) + d
|
|
201
|
+
# The execution is booked once its delta is in `unhedged`. A hedge
|
|
202
|
+
# failure must not escape: the executions loop would retry this
|
|
203
|
+
# execution and add its delta a second time. The delta stays unhedged
|
|
204
|
+
# and the next execution retries the order.
|
|
205
|
+
try:
|
|
206
|
+
await self.hedge()
|
|
207
|
+
except Exception as error: # noqa: BLE001 - never re-book an execution
|
|
208
|
+
log.warning("hedge after execution %s failed, will retry after the next fill: %s", ex.execution_id, error)
|
|
209
|
+
|
|
210
|
+
async def hedge(self) -> None:
|
|
211
|
+
"""Step 7: sell (or buy) the Hyperliquid perp against the unhedged options delta.
|
|
212
|
+
|
|
213
|
+
Deltas too small to trade carry over to the next execution. A failed
|
|
214
|
+
order keeps its delta unhedged so the next execution retries it.
|
|
215
|
+
"""
|
|
216
|
+
for coin, delta in list(self.unhedged.items()):
|
|
217
|
+
if abs(delta) < MIN_HEDGE.get(coin, 0.01):
|
|
218
|
+
continue
|
|
219
|
+
log.info("hedge %s: %s %.6f perp", coin, "sell" if delta > 0 else "buy", abs(delta))
|
|
220
|
+
if self.dry_run:
|
|
221
|
+
self.unhedged[coin] = 0.0
|
|
222
|
+
continue
|
|
223
|
+
try:
|
|
224
|
+
result = await self.hc.perps.order(coin=coin, is_buy=delta < 0, size=abs(delta), type="ioc", slippage_bps=20)
|
|
225
|
+
except (HypercallError, httpx.HTTPError, KeyError, ValueError) as error:
|
|
226
|
+
log.warning("hedge %s failed, will retry after the next fill: %s", coin, error)
|
|
227
|
+
continue
|
|
228
|
+
self.unhedged[coin] = 0.0
|
|
229
|
+
self.stats["hedges"] += 1
|
|
230
|
+
log.info("hedge %s submitted: %s", coin, result)
|
|
231
|
+
|
|
232
|
+
async def heartbeat(self) -> None:
|
|
233
|
+
"""Step 6: a 30-second dead-man switch, renewed every 10 seconds."""
|
|
234
|
+
while True:
|
|
235
|
+
if not self.dry_run:
|
|
236
|
+
try:
|
|
237
|
+
await self.hc.rfq_v2.cancel_after(seconds=30)
|
|
238
|
+
except (HypercallError, httpx.HTTPError) as error:
|
|
239
|
+
log.warning("heartbeat renewal failed: %s", error)
|
|
240
|
+
await asyncio.sleep(10)
|
|
241
|
+
|
|
242
|
+
async def report(self) -> None:
|
|
243
|
+
while True:
|
|
244
|
+
await asyncio.sleep(30)
|
|
245
|
+
log.info("stats %s open_quotes=%d unhedged=%s", self.stats, len(self.limits.open), self.unhedged)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def stop_on_signals() -> None:
|
|
249
|
+
"""Cancel the main task on SIGINT or SIGTERM, so its `finally` still withdraws.
|
|
250
|
+
|
|
251
|
+
Without this, SIGTERM (what `kill`, systemd, Docker and Kubernetes send)
|
|
252
|
+
ends the process at once and every open quote stays live.
|
|
253
|
+
"""
|
|
254
|
+
task = asyncio.current_task()
|
|
255
|
+
loop = asyncio.get_running_loop()
|
|
256
|
+
|
|
257
|
+
stopping = False
|
|
258
|
+
|
|
259
|
+
def stop(sig: signal.Signals) -> None:
|
|
260
|
+
nonlocal stopping
|
|
261
|
+
if stopping:
|
|
262
|
+
return # a second signal must not cut the withdrawal short
|
|
263
|
+
stopping = True
|
|
264
|
+
log.info("%s: withdrawing quotes and stopping", sig.name)
|
|
265
|
+
task.cancel()
|
|
266
|
+
|
|
267
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
268
|
+
loop.add_signal_handler(sig, stop, sig) # Unix only
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
async def main(args) -> None:
|
|
272
|
+
stop_on_signals()
|
|
273
|
+
hc = Hypercall(host=args.host, account=os.environ["HC_ACCOUNT"], signer_key=os.environ["HC_SIGNER_KEY"], chain_id=args.chain_id)
|
|
274
|
+
if args.hyperliquid_info:
|
|
275
|
+
hc.perps.info_url = args.hyperliquid_info # e.g. a localnet HyperCore node
|
|
276
|
+
try:
|
|
277
|
+
log.info("provider: %s", await hc.rfq_v2.provider())
|
|
278
|
+
except HypercallError as error:
|
|
279
|
+
log.info("provider read unavailable: %s", error)
|
|
280
|
+
maker = Maker(hc, Pricer(args.spread), Limits(args.max_open_quotes, args.max_contracts), args.dry_run, args.quote_ttl)
|
|
281
|
+
try:
|
|
282
|
+
async with asyncio.TaskGroup() as tg:
|
|
283
|
+
tg.create_task(maker.heartbeat())
|
|
284
|
+
tg.create_task(maker.run_executions(args.exec_cursor))
|
|
285
|
+
tg.create_task(maker.report())
|
|
286
|
+
# One task per RFQ. The cursor advances only once a task is done,
|
|
287
|
+
# so a restart replays any RFQ still being priced or posted.
|
|
288
|
+
async for rfq in hc.rfq_v2.stream(cursor_file=args.rfq_cursor, manual_ack=True):
|
|
289
|
+
tg.create_task(maker.handle(rfq))
|
|
290
|
+
finally:
|
|
291
|
+
if not args.dry_run:
|
|
292
|
+
# Never leave quotes behind.
|
|
293
|
+
await hc.rfq_v2.withdraw_all()
|
|
294
|
+
await hc.rfq_v2.cancel_after(None)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
if __name__ == "__main__":
|
|
298
|
+
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
299
|
+
p.add_argument("--host", default=os.environ.get("HC_HOST", "https://api.hypercall.xyz"))
|
|
300
|
+
p.add_argument("--chain-id", type=int, default=int(os.environ.get("HC_CHAIN_ID", "999")))
|
|
301
|
+
p.add_argument("--hyperliquid-info", default=os.environ.get("HC_HYPERLIQUID_INFO"), help="Hyperliquid /info URL for perp meta and mids")
|
|
302
|
+
p.add_argument("--dry-run", action="store_true", help="price and log RFQs without posting anything")
|
|
303
|
+
p.add_argument("--spread", type=float, default=0.02)
|
|
304
|
+
p.add_argument("--quote-ttl", type=float, default=20.0, help="seconds each quote stays executable")
|
|
305
|
+
p.add_argument("--max-open-quotes", type=int, default=20, help="open quotes at once")
|
|
306
|
+
p.add_argument("--max-contracts", type=float, default=5.0, help="contracts per leg in one quote")
|
|
307
|
+
p.add_argument("--rfq-cursor", default="rfq.cursor")
|
|
308
|
+
p.add_argument("--exec-cursor", default="exec.cursor")
|
|
309
|
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
310
|
+
try:
|
|
311
|
+
asyncio.run(main(p.parse_args()))
|
|
312
|
+
except (KeyboardInterrupt, asyncio.CancelledError):
|
|
313
|
+
pass
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "hypercall-rfq-example"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Demo helpers for the Hypercall RFQ v2 maker tutorial: EIP-712 signing, read grants, quoting, executions."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = { text = "MIT" }
|
|
8
|
+
authors = [{ name = "Hypercall" }]
|
|
9
|
+
keywords = ["hypercall", "rfq", "options", "market-making", "hyperliquid", "eip712"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"License :: OSI Approved :: MIT License",
|
|
13
|
+
"Development Status :: 3 - Alpha",
|
|
14
|
+
]
|
|
15
|
+
dependencies = ["eth-account>=0.13", "httpx>=0.27", "websockets>=13"]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Homepage = "https://github.com/hypercall-public/hypercall-rfq-example"
|
|
19
|
+
Tutorial = "https://blog.hypercall.xyz/build-an-rfq-v2-maker/"
|
|
20
|
+
Documentation = "https://docs.hypercall.xyz/docs/trading/over-api/rfq-v2"
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
test = ["pytest>=8", "pytest-asyncio>=0.24"]
|
|
24
|
+
|
|
25
|
+
[build-system]
|
|
26
|
+
requires = ["hatchling"]
|
|
27
|
+
build-backend = "hatchling.build"
|
|
28
|
+
|
|
29
|
+
[tool.hatch.build.targets.wheel]
|
|
30
|
+
packages = ["src/hypercall_rfq_example"]
|
|
31
|
+
|
|
32
|
+
[tool.pytest.ini_options]
|
|
33
|
+
asyncio_mode = "auto"
|
|
34
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
35
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""Demo helpers for the Hypercall "Build an RFQ v2 maker" tutorial."""
|
|
2
|
+
|
|
3
|
+
from .client import Execution, Hypercall, HypercallError, Leg, Quote, Rfq, exact_prices, to_micros
|
|
4
|
+
|
|
5
|
+
__all__ = ["Execution", "Hypercall", "HypercallError", "Leg", "Quote", "Rfq", "exact_prices", "to_micros"]
|