hyperliquid-position-csv 1.0.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HoldWins (https://holdwins.com)
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,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: hyperliquid-position-csv
3
+ Version: 1.0.0
4
+ Summary: Zero-dependency exact Decimal reconstructor for Hyperliquid userFills perpetual position cycles (VWAP entry/exit, peak size, PnL, fees) with RFC-4180 CSV export.
5
+ Keywords: hyperliquid,whale-tracker,perpetual-futures,csv-export,position-cycles,vwap,crypto
6
+ Author: HoldWins
7
+ Author-email: HoldWins <ops@holdwins.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Financial and Insurance Industry
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Office/Business :: Financial :: Investment
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.9
18
+ Project-URL: Homepage, https://holdwins.com/en/hyperliquid-tracker/
19
+ Project-URL: Live Whale Radar (EN), https://holdwins.com/en/hyperliquid-tracker/
20
+ Project-URL: Hyperliquid 巨鲸雷达 (中文), https://holdwins.com/hyperliquid-tracker/
21
+ Project-URL: Trade History Guide, https://holdwins.com/guides/hyperliquid-wallet-trade-history/
22
+ Project-URL: Documentation, https://dalangdalang934.github.io/hyperliquid-position-csv/
23
+ Project-URL: Repository, https://github.com/dalangdalang934/hyperliquid-position-csv
24
+ Description-Content-Type: text/markdown
25
+
26
+ # hyperliquid-position-csv
27
+
28
+ Zero-dependency **Python (`decimal.Decimal`)** & **JavaScript (ESM)** library + CLI to reconstruct **flat-to-flat perpetual position cycles** (`0 → position → 0`) from Hyperliquid's public `userFills` endpoint and export clean RFC-4180 CSV summaries.
29
+
30
+ - **Live Web Tracker (English)**: [Hyperliquid Whale Position & Trade History Tracker](https://holdwins.com/en/hyperliquid-tracker/)
31
+ - **在线巨鲸持仓与交易历史追踪器(中文)**: [Hyperliquid 钱包追踪器](https://holdwins.com/hyperliquid-tracker/)
32
+ - **Methodology & CSV Guide**: [Hyperliquid Wallet Trade History & Position Cycles](https://holdwins.com/en/guides/hyperliquid-wallet-trade-history/)
33
+
34
+ ---
35
+
36
+ ## Python Installation & Quick Start
37
+
38
+ ```bash
39
+ pip install hyperliquid-position-csv
40
+ hl-position-csv --address 0x... > positions.csv
41
+ ```
42
+
43
+ ```python
44
+ from hyperliquid_position_csv import group_position_cycles, cycles_to_csv
45
+
46
+ cycles = group_position_cycles(raw_fills)
47
+ print(cycles_to_csv(cycles))
48
+ ```
49
+
50
+ ---
51
+
52
+ ## Why Reconstruct Position Cycles?
53
+
54
+ Hyperliquid's public `POST https://api.hyperliquid.xyz/info` (`{"type": "userFills", "user": "0x..."}`) returns up to 2,000 individual order execution fragments. A single position entered across 15 partial maker fills and closed across 12 taker fills appears as 27 separate rows, and a single flip order crossing zero splits across two logical trades.
55
+
56
+ `hyperliquid-position-csv` groups raw fills per market (preserving both native perpetuals like `BTC` and HIP-3 namespaced builder markets like `xyz:NVDA`) into clean **position cycles**:
57
+
58
+ - **Exact `BigInt` 18-decimal fixed-point math** — no IEEE-754 floating-point precision drift on sizes, fees, or realized PnL.
59
+ - **Honest window boundaries** — if a wallet's 2,000-fill history starts mid-position (`startPosition != 0`), `complete` is marked `false` rather than fabricating an entry price.
60
+ - **Single-fill reversals handled** — orders that cross through `0` close the prior cycle cleanly and open a new opposite-side cycle.
61
+
62
+ ---
63
+
64
+ ## Usage
65
+
66
+ ### 1. CLI (Export any `0x` wallet directly to CSV)
67
+
68
+ ```bash
69
+ # Fetch live public fills for a Hyperliquid wallet and write CSV
70
+ node ./bin/cli.mjs 0x0000000000000000000000000000000000000000 --out positions.csv
71
+
72
+ # Or reconstruct offline from a saved userFills JSON array
73
+ node ./bin/cli.mjs --input ./sample-fills.json --out positions.csv
74
+ ```
75
+
76
+ ### 2. ESM Library
77
+
78
+ ```js
79
+ import { fetchHyperliquidUserFills, groupPositionCycles, cyclesToCsv } from './src/index.mjs';
80
+
81
+ const fills = await fetchHyperliquidUserFills('0x...');
82
+ const cycles = groupPositionCycles(fills);
83
+ console.log(cyclesToCsv(cycles));
84
+ ```
85
+
86
+ ---
87
+
88
+ ## Output CSV Columns
89
+
90
+ | Column | Description |
91
+ | --- | --- |
92
+ | `coin` | Perpetual symbol (e.g. `BTC`, `ETH`, or HIP-3 `namespace:SYMBOL`) |
93
+ | `side` | `long` or `short` |
94
+ | `status` | `closed` (returned to `0`) or `open` |
95
+ | `opened_at` / `closed_at` | ISO-8601 timestamps (blank if outside the 2,000-fill window) |
96
+ | `opened_size` / `closed_size` | Total base quantity opened and closed within the cycle |
97
+ | `avg_entry_px` / `avg_exit_px` | Volume-weighted average entry and exit prices |
98
+ | `realized_pnl` | Sum of `closedPnl` across all executions in the cycle |
99
+ | `fees` / `fee_token` | Total execution fees and fee currency |
100
+ | `fills_count` | Number of partial fills aggregated into this cycle |
101
+ | `complete` | `true` only when both flat entry (`0 → pos`) and flat exit (`pos → 0`) are inside the loaded history |
102
+
103
+ ---
104
+
105
+ ## Related Open Analytics & Documentation by HoldWins
106
+
107
+ - [Hyperliquid Whale Radar (Live Leaderboard,Candlesticks B/S Markers & CSV Export)](https://holdwins.com/en/hyperliquid-tracker/) · [中文巨鲸雷达](https://holdwins.com/hyperliquid-tracker/)
108
+ - [How to Track Hyperliquid Whale Positions](https://holdwins.com/en/guides/hyperliquid-whale-positions/) · [巨鲸持仓查询指南](https://holdwins.com/guides/hyperliquid-whale-positions/)
109
+ - [Hyperliquid Liquidation Price & Mark Distance](https://holdwins.com/en/guides/hyperliquid-liquidation-price/) · [清算价与清算距离](https://holdwins.com/guides/hyperliquid-liquidation-price/)
110
+ - [HIP-3 Tokenized Stock Perps vs bStocks](https://holdwins.com/en/guides/rwa-tokenized-stocks-contracts/) · [美股代币与链上永续合约区别](https://holdwins.com/guides/rwa-tokenized-stocks-contracts/)
111
+ - [Perpetual Futures Open Interest & Funding Monitor](https://holdwins.com/en/market-intel/) · [合约异动监测](https://holdwins.com/market-intel/)
112
+
113
+ ## License
114
+
115
+ MIT © [HoldWins](https://holdwins.com)
@@ -0,0 +1,90 @@
1
+ # hyperliquid-position-csv
2
+
3
+ Zero-dependency **Python (`decimal.Decimal`)** & **JavaScript (ESM)** library + CLI to reconstruct **flat-to-flat perpetual position cycles** (`0 → position → 0`) from Hyperliquid's public `userFills` endpoint and export clean RFC-4180 CSV summaries.
4
+
5
+ - **Live Web Tracker (English)**: [Hyperliquid Whale Position & Trade History Tracker](https://holdwins.com/en/hyperliquid-tracker/)
6
+ - **在线巨鲸持仓与交易历史追踪器(中文)**: [Hyperliquid 钱包追踪器](https://holdwins.com/hyperliquid-tracker/)
7
+ - **Methodology & CSV Guide**: [Hyperliquid Wallet Trade History & Position Cycles](https://holdwins.com/en/guides/hyperliquid-wallet-trade-history/)
8
+
9
+ ---
10
+
11
+ ## Python Installation & Quick Start
12
+
13
+ ```bash
14
+ pip install hyperliquid-position-csv
15
+ hl-position-csv --address 0x... > positions.csv
16
+ ```
17
+
18
+ ```python
19
+ from hyperliquid_position_csv import group_position_cycles, cycles_to_csv
20
+
21
+ cycles = group_position_cycles(raw_fills)
22
+ print(cycles_to_csv(cycles))
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Why Reconstruct Position Cycles?
28
+
29
+ Hyperliquid's public `POST https://api.hyperliquid.xyz/info` (`{"type": "userFills", "user": "0x..."}`) returns up to 2,000 individual order execution fragments. A single position entered across 15 partial maker fills and closed across 12 taker fills appears as 27 separate rows, and a single flip order crossing zero splits across two logical trades.
30
+
31
+ `hyperliquid-position-csv` groups raw fills per market (preserving both native perpetuals like `BTC` and HIP-3 namespaced builder markets like `xyz:NVDA`) into clean **position cycles**:
32
+
33
+ - **Exact `BigInt` 18-decimal fixed-point math** — no IEEE-754 floating-point precision drift on sizes, fees, or realized PnL.
34
+ - **Honest window boundaries** — if a wallet's 2,000-fill history starts mid-position (`startPosition != 0`), `complete` is marked `false` rather than fabricating an entry price.
35
+ - **Single-fill reversals handled** — orders that cross through `0` close the prior cycle cleanly and open a new opposite-side cycle.
36
+
37
+ ---
38
+
39
+ ## Usage
40
+
41
+ ### 1. CLI (Export any `0x` wallet directly to CSV)
42
+
43
+ ```bash
44
+ # Fetch live public fills for a Hyperliquid wallet and write CSV
45
+ node ./bin/cli.mjs 0x0000000000000000000000000000000000000000 --out positions.csv
46
+
47
+ # Or reconstruct offline from a saved userFills JSON array
48
+ node ./bin/cli.mjs --input ./sample-fills.json --out positions.csv
49
+ ```
50
+
51
+ ### 2. ESM Library
52
+
53
+ ```js
54
+ import { fetchHyperliquidUserFills, groupPositionCycles, cyclesToCsv } from './src/index.mjs';
55
+
56
+ const fills = await fetchHyperliquidUserFills('0x...');
57
+ const cycles = groupPositionCycles(fills);
58
+ console.log(cyclesToCsv(cycles));
59
+ ```
60
+
61
+ ---
62
+
63
+ ## Output CSV Columns
64
+
65
+ | Column | Description |
66
+ | --- | --- |
67
+ | `coin` | Perpetual symbol (e.g. `BTC`, `ETH`, or HIP-3 `namespace:SYMBOL`) |
68
+ | `side` | `long` or `short` |
69
+ | `status` | `closed` (returned to `0`) or `open` |
70
+ | `opened_at` / `closed_at` | ISO-8601 timestamps (blank if outside the 2,000-fill window) |
71
+ | `opened_size` / `closed_size` | Total base quantity opened and closed within the cycle |
72
+ | `avg_entry_px` / `avg_exit_px` | Volume-weighted average entry and exit prices |
73
+ | `realized_pnl` | Sum of `closedPnl` across all executions in the cycle |
74
+ | `fees` / `fee_token` | Total execution fees and fee currency |
75
+ | `fills_count` | Number of partial fills aggregated into this cycle |
76
+ | `complete` | `true` only when both flat entry (`0 → pos`) and flat exit (`pos → 0`) are inside the loaded history |
77
+
78
+ ---
79
+
80
+ ## Related Open Analytics & Documentation by HoldWins
81
+
82
+ - [Hyperliquid Whale Radar (Live Leaderboard,Candlesticks B/S Markers & CSV Export)](https://holdwins.com/en/hyperliquid-tracker/) · [中文巨鲸雷达](https://holdwins.com/hyperliquid-tracker/)
83
+ - [How to Track Hyperliquid Whale Positions](https://holdwins.com/en/guides/hyperliquid-whale-positions/) · [巨鲸持仓查询指南](https://holdwins.com/guides/hyperliquid-whale-positions/)
84
+ - [Hyperliquid Liquidation Price & Mark Distance](https://holdwins.com/en/guides/hyperliquid-liquidation-price/) · [清算价与清算距离](https://holdwins.com/guides/hyperliquid-liquidation-price/)
85
+ - [HIP-3 Tokenized Stock Perps vs bStocks](https://holdwins.com/en/guides/rwa-tokenized-stocks-contracts/) · [美股代币与链上永续合约区别](https://holdwins.com/guides/rwa-tokenized-stocks-contracts/)
86
+ - [Perpetual Futures Open Interest & Funding Monitor](https://holdwins.com/en/market-intel/) · [合约异动监测](https://holdwins.com/market-intel/)
87
+
88
+ ## License
89
+
90
+ MIT © [HoldWins](https://holdwins.com)
@@ -0,0 +1,44 @@
1
+ [project]
2
+ name = "hyperliquid-position-csv"
3
+ version = "1.0.0"
4
+ description = "Zero-dependency exact Decimal reconstructor for Hyperliquid userFills perpetual position cycles (VWAP entry/exit, peak size, PnL, fees) with RFC-4180 CSV export."
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [
10
+ { name = "HoldWins", email = "ops@holdwins.com" }
11
+ ]
12
+ keywords = [
13
+ "hyperliquid",
14
+ "whale-tracker",
15
+ "perpetual-futures",
16
+ "csv-export",
17
+ "position-cycles",
18
+ "vwap",
19
+ "crypto"
20
+ ]
21
+ classifiers = [
22
+ "Development Status :: 5 - Production/Stable",
23
+ "Intended Audience :: Developers",
24
+ "Intended Audience :: Financial and Insurance Industry",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3 :: Only",
27
+ "Topic :: Office/Business :: Financial :: Investment",
28
+ "Typing :: Typed"
29
+ ]
30
+
31
+ [project.scripts]
32
+ hl-position-csv = "hyperliquid_position_csv.cli:main"
33
+
34
+ [project.urls]
35
+ Homepage = "https://holdwins.com/en/hyperliquid-tracker/"
36
+ "Live Whale Radar (EN)" = "https://holdwins.com/en/hyperliquid-tracker/"
37
+ "Hyperliquid 巨鲸雷达 (中文)" = "https://holdwins.com/hyperliquid-tracker/"
38
+ "Trade History Guide" = "https://holdwins.com/guides/hyperliquid-wallet-trade-history/"
39
+ Documentation = "https://dalangdalang934.github.io/hyperliquid-position-csv/"
40
+ Repository = "https://github.com/dalangdalang934/hyperliquid-position-csv"
41
+
42
+ [build-system]
43
+ requires = ["uv_build>=0.9.0,<0.12.0"]
44
+ build-backend = "uv_build"
@@ -0,0 +1,232 @@
1
+ """Reconstruct flat-to-flat perpetual position cycles from Hyperliquid userFills."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timezone
9
+ from decimal import Decimal, getcontext
10
+ from typing import Any, Iterable, Sequence
11
+
12
+ getcontext().prec = 36
13
+
14
+
15
+ def _dec(val: Any) -> Decimal:
16
+ return val if isinstance(val, Decimal) else Decimal(str(val or "0"))
17
+
18
+
19
+ def _fmt_dec(val: Decimal) -> str:
20
+ s = format(val.normalize(), "f")
21
+ if "." in s:
22
+ s = s.rstrip("0").rstrip(".")
23
+ return "0" if s in ("", "-0") else s
24
+
25
+
26
+ def is_perp_fill(fill: dict[str, Any]) -> bool:
27
+ coin = str(fill.get("coin") or "")
28
+ return bool(coin) and not coin.startswith("@") and "/" not in coin
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class PositionCycle:
33
+ coin: str
34
+ direction: str
35
+ status: str
36
+ opened_at_ms: int
37
+ closed_at_ms: int | None
38
+ fill_count: int
39
+ peak_size: str
40
+ avg_entry_price: str
41
+ avg_exit_price: str
42
+ realized_pnl: str
43
+ total_fees: str
44
+ net_pnl: str
45
+ fee_token: str
46
+
47
+ def to_dict(self) -> dict[str, Any]:
48
+ return {
49
+ "coin": self.coin,
50
+ "direction": self.direction,
51
+ "status": self.status,
52
+ "openedAt": datetime.fromtimestamp(self.opened_at_ms / 1000, tz=timezone.utc).isoformat(),
53
+ "closedAt": datetime.fromtimestamp(self.closed_at_ms / 1000, tz=timezone.utc).isoformat()
54
+ if self.closed_at_ms is not None
55
+ else "",
56
+ "fillCount": self.fill_count,
57
+ "peakSize": self.peak_size,
58
+ "avgEntryPrice": self.avg_entry_price,
59
+ "avgExitPrice": self.avg_exit_price,
60
+ "realizedPnl": self.realized_pnl,
61
+ "totalFees": self.total_fees,
62
+ "netPnl": self.net_pnl,
63
+ "feeToken": self.fee_token,
64
+ }
65
+
66
+
67
+ def group_position_cycles(raw_fills: Iterable[dict[str, Any]]) -> list[PositionCycle]:
68
+ by_coin: dict[str, list[dict[str, Any]]] = {}
69
+ for f in raw_fills:
70
+ if not is_perp_fill(f):
71
+ continue
72
+ side_str = "buy" if f.get("side") in ("B", "buy") else "sell"
73
+ sz = _dec(f.get("sz") if f.get("sz") is not None else f.get("size", "0"))
74
+ px = _dec(f.get("px") if f.get("px") is not None else f.get("price", "0"))
75
+ if sz <= 0:
76
+ continue
77
+ before = _dec(f["startPosition"]) if f.get("startPosition") is not None else Decimal("0")
78
+ delta = sz if side_str == "buy" else -sz
79
+ after = before + delta
80
+ by_coin.setdefault(str(f["coin"]), []).append(
81
+ {
82
+ "coin": str(f["coin"]),
83
+ "time": int(f.get("time") or 0),
84
+ "tid": int(f.get("tid") or f.get("id") or 0),
85
+ "side": side_str,
86
+ "sz": sz,
87
+ "px": px,
88
+ "before": before,
89
+ "after": after,
90
+ "pnl": _dec(f.get("closedPnl", "0")),
91
+ "fee": _dec(f.get("fee", "0")),
92
+ "fee_token": str(f.get("feeToken") or "USDC"),
93
+ }
94
+ )
95
+
96
+ cycles: list[PositionCycle] = []
97
+ for coin, events in by_coin.items():
98
+ events.sort(key=lambda e: (e["time"], e["tid"]))
99
+ cur: dict[str, Any] | None = None
100
+
101
+ def flush(status: str, close_time: int | None) -> None:
102
+ nonlocal cur
103
+ if not cur:
104
+ return
105
+ entry_vwap = _fmt_dec(cur["entry_notional"] / cur["entry_sz"]) if cur["entry_sz"] > 0 else ""
106
+ exit_vwap = _fmt_dec(cur["exit_notional"] / cur["exit_sz"]) if cur["exit_sz"] > 0 else ""
107
+ cycles.append(
108
+ PositionCycle(
109
+ coin=coin,
110
+ direction="long" if cur["sign"] > 0 else "short",
111
+ status=status,
112
+ opened_at_ms=cur["open_time"],
113
+ closed_at_ms=close_time if status == "closed" else None,
114
+ fill_count=cur["fills"],
115
+ peak_size=_fmt_dec(cur["peak"]),
116
+ avg_entry_price=entry_vwap,
117
+ avg_exit_price=exit_vwap,
118
+ realized_pnl=_fmt_dec(cur["pnl"]),
119
+ total_fees=_fmt_dec(cur["fees"]),
120
+ net_pnl=_fmt_dec(cur["pnl"] - cur["fees"]),
121
+ fee_token=cur["fee_token"],
122
+ )
123
+ )
124
+ cur = None
125
+
126
+ for ev in events:
127
+ b, a, sz, px = ev["before"], ev["after"], ev["sz"], ev["px"]
128
+ b_sign = 1 if b > 0 else (-1 if b < 0 else 0)
129
+ a_sign = 1 if a > 0 else (-1 if a < 0 else 0)
130
+
131
+ if b_sign != 0 and a_sign != 0 and b_sign != a_sign:
132
+ close_sz = abs(b)
133
+ open_sz = abs(a)
134
+ ratio = close_sz / sz
135
+ if cur is None:
136
+ cur = {
137
+ "sign": b_sign,
138
+ "open_time": ev["time"],
139
+ "fills": 0,
140
+ "peak": close_sz,
141
+ "entry_notional": Decimal("0"),
142
+ "entry_sz": Decimal("0"),
143
+ "exit_notional": Decimal("0"),
144
+ "exit_sz": Decimal("0"),
145
+ "pnl": Decimal("0"),
146
+ "fees": Decimal("0"),
147
+ "fee_token": ev["fee_token"],
148
+ }
149
+ cur["fills"] += 1
150
+ cur["exit_notional"] += close_sz * px
151
+ cur["exit_sz"] += close_sz
152
+ cur["pnl"] += ev["pnl"]
153
+ cur["fees"] += ev["fee"] * ratio
154
+ flush("closed", ev["time"])
155
+
156
+ cur = {
157
+ "sign": a_sign,
158
+ "open_time": ev["time"],
159
+ "fills": 1,
160
+ "peak": open_sz,
161
+ "entry_notional": open_sz * px,
162
+ "entry_sz": open_sz,
163
+ "exit_notional": Decimal("0"),
164
+ "exit_sz": Decimal("0"),
165
+ "pnl": Decimal("0"),
166
+ "fees": ev["fee"] * (Decimal("1") - ratio),
167
+ "fee_token": ev["fee_token"],
168
+ }
169
+ continue
170
+
171
+ active_sign = a_sign if b_sign == 0 else b_sign
172
+ if active_sign == 0:
173
+ continue
174
+ if cur is None:
175
+ cur = {
176
+ "sign": active_sign,
177
+ "open_time": ev["time"],
178
+ "fills": 0,
179
+ "peak": abs(b),
180
+ "entry_notional": Decimal("0"),
181
+ "entry_sz": Decimal("0"),
182
+ "exit_notional": Decimal("0"),
183
+ "exit_sz": Decimal("0"),
184
+ "pnl": Decimal("0"),
185
+ "fees": Decimal("0"),
186
+ "fee_token": ev["fee_token"],
187
+ }
188
+ cur["fills"] += 1
189
+ cur["peak"] = max(cur["peak"], abs(a))
190
+ if abs(a) > abs(b):
191
+ cur["entry_notional"] += sz * px
192
+ cur["entry_sz"] += sz
193
+ else:
194
+ cur["exit_notional"] += sz * px
195
+ cur["exit_sz"] += sz
196
+ cur["pnl"] += ev["pnl"]
197
+ cur["fees"] += ev["fee"]
198
+ if a == 0:
199
+ flush("closed", ev["time"])
200
+
201
+ if cur is not None:
202
+ flush("open", None)
203
+
204
+ cycles.sort(key=lambda c: c.opened_at_ms, reverse=True)
205
+ return cycles
206
+
207
+
208
+ def cycles_to_csv(cycles: Sequence[PositionCycle]) -> str:
209
+ cols = [
210
+ "coin",
211
+ "direction",
212
+ "status",
213
+ "openedAt",
214
+ "closedAt",
215
+ "fillCount",
216
+ "peakSize",
217
+ "avgEntryPrice",
218
+ "avgExitPrice",
219
+ "realizedPnl",
220
+ "totalFees",
221
+ "netPnl",
222
+ "feeToken",
223
+ ]
224
+ buf = io.StringIO()
225
+ writer = csv.DictWriter(buf, fieldnames=cols, lineterminator="\n")
226
+ writer.writeheader()
227
+ for c in cycles:
228
+ writer.writerow(c.to_dict())
229
+ return buf.getvalue()
230
+
231
+
232
+ __all__ = ["PositionCycle", "cycles_to_csv", "group_position_cycles", "is_perp_fill"]
@@ -0,0 +1,42 @@
1
+ """CLI for hyperliquid-position-csv."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ import urllib.request
9
+
10
+ from . import cycles_to_csv, group_position_cycles
11
+
12
+
13
+ def main() -> int:
14
+ parser = argparse.ArgumentParser(
15
+ prog="hl-position-csv",
16
+ description="Reconstruct Hyperliquid perpetual position cycles from a 0x address or JSON file and output CSV.",
17
+ )
18
+ parser.add_argument("--address", help="Hyperliquid 0x wallet address to query from api.hyperliquid.xyz")
19
+ parser.add_argument("--input", help="Local JSON file containing userFills array")
20
+ args = parser.parse_args()
21
+
22
+ if args.input:
23
+ with open(args.input, encoding="utf-8") as f:
24
+ fills = json.load(f)
25
+ elif args.address:
26
+ req = urllib.request.Request(
27
+ "https://api.hyperliquid.xyz/info",
28
+ data=json.dumps({"type": "userFills", "user": args.address}).encode("utf-8"),
29
+ headers={"Content-Type": "application/json"},
30
+ )
31
+ with urllib.request.urlopen(req, timeout=20) as resp:
32
+ fills = json.load(resp)
33
+ else:
34
+ parser.error("Provide either --address 0x... or --input fills.json")
35
+ return 2
36
+
37
+ sys.stdout.write(cycles_to_csv(group_position_cycles(fills)))
38
+ return 0
39
+
40
+
41
+ if __name__ == "__main__":
42
+ raise SystemExit(main())