uni-exec-engine 0.2.0__py3-none-any.whl

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.
Files changed (80) hide show
  1. uni_exec_engine-0.2.0.dist-info/METADATA +576 -0
  2. uni_exec_engine-0.2.0.dist-info/RECORD +80 -0
  3. uni_exec_engine-0.2.0.dist-info/WHEEL +5 -0
  4. uni_exec_engine-0.2.0.dist-info/licenses/LICENSE +21 -0
  5. uni_exec_engine-0.2.0.dist-info/top_level.txt +1 -0
  6. uniswap_autopilot/__init__.py +3 -0
  7. uniswap_autopilot/analytics/__init__.py +0 -0
  8. uniswap_autopilot/analytics/il_calculator.py +525 -0
  9. uniswap_autopilot/analytics/portfolio.py +234 -0
  10. uniswap_autopilot/analytics/position.py +433 -0
  11. uniswap_autopilot/analytics/range_suggest.py +270 -0
  12. uniswap_autopilot/audit.py +194 -0
  13. uniswap_autopilot/common/__init__.py +0 -0
  14. uniswap_autopilot/common/approval_cleanup.py +255 -0
  15. uniswap_autopilot/common/check_balance.py +64 -0
  16. uniswap_autopilot/common/common.py +804 -0
  17. uniswap_autopilot/common/deep_link.py +132 -0
  18. uniswap_autopilot/common/gas.py +141 -0
  19. uniswap_autopilot/data/auto_trade_policy.example.json +29 -0
  20. uniswap_autopilot/data/chains.json +135 -0
  21. uniswap_autopilot/data/common-token-addresses.json +777 -0
  22. uniswap_autopilot/execute/__init__.py +0 -0
  23. uniswap_autopilot/execute/_internal/__init__.py +5 -0
  24. uniswap_autopilot/execute/_internal/constants.py +15 -0
  25. uniswap_autopilot/execute/_internal/preflight.py +150 -0
  26. uniswap_autopilot/execute/_internal/pure_signer.py +182 -0
  27. uniswap_autopilot/execute/_internal/rpc.py +462 -0
  28. uniswap_autopilot/execute/_internal/signer.py +298 -0
  29. uniswap_autopilot/execute/_internal/submit.py +73 -0
  30. uniswap_autopilot/execute/_internal/tx.py +370 -0
  31. uniswap_autopilot/execute/broadcast.py +380 -0
  32. uniswap_autopilot/execute/detect.py +52 -0
  33. uniswap_autopilot/execute/telegram_confirm.py +272 -0
  34. uniswap_autopilot/lp/compare_pools.py +338 -0
  35. uniswap_autopilot/lp/v2/__init__.py +0 -0
  36. uniswap_autopilot/lp/v2/approve.py +100 -0
  37. uniswap_autopilot/lp/v2/build_tx.py +226 -0
  38. uniswap_autopilot/lp/v2/flow.py +204 -0
  39. uniswap_autopilot/lp/v2/pair.py +135 -0
  40. uniswap_autopilot/lp/v2/positions.py +177 -0
  41. uniswap_autopilot/lp/v3/__init__.py +0 -0
  42. uniswap_autopilot/lp/v3/approve.py +109 -0
  43. uniswap_autopilot/lp/v3/auto_rebalance.py +282 -0
  44. uniswap_autopilot/lp/v3/build_tx.py +465 -0
  45. uniswap_autopilot/lp/v3/compound.py +258 -0
  46. uniswap_autopilot/lp/v3/flow.py +358 -0
  47. uniswap_autopilot/lp/v3/pool.py +175 -0
  48. uniswap_autopilot/lp/v3/position.py +112 -0
  49. uniswap_autopilot/lp/v3/tick.py +75 -0
  50. uniswap_autopilot/lp/v4/__init__.py +0 -0
  51. uniswap_autopilot/lp/v4/approve.py +105 -0
  52. uniswap_autopilot/lp/v4/build_tx.py +669 -0
  53. uniswap_autopilot/lp/v4/flow.py +368 -0
  54. uniswap_autopilot/lp/v4/pool.py +174 -0
  55. uniswap_autopilot/lp/v4/position.py +185 -0
  56. uniswap_autopilot/policy.py +371 -0
  57. uniswap_autopilot/price_feed.py +100 -0
  58. uniswap_autopilot/py.typed +0 -0
  59. uniswap_autopilot/search/__init__.py +0 -0
  60. uniswap_autopilot/search/risk.py +200 -0
  61. uniswap_autopilot/search/search.py +580 -0
  62. uniswap_autopilot/state_machine.py +315 -0
  63. uniswap_autopilot/swap/__init__.py +1 -0
  64. uniswap_autopilot/swap/deep_link.py +69 -0
  65. uniswap_autopilot/swap/extensions/__init__.py +2 -0
  66. uniswap_autopilot/swap/extensions/bridge.py +197 -0
  67. uniswap_autopilot/swap/extensions/limit_order.py +272 -0
  68. uniswap_autopilot/swap/extensions/slippage.py +123 -0
  69. uniswap_autopilot/swap/flow.py +693 -0
  70. uniswap_autopilot/swap/flow_core/__init__.py +2 -0
  71. uniswap_autopilot/swap/flow_core/artifacts.py +11 -0
  72. uniswap_autopilot/swap/flow_core/broadcast.py +50 -0
  73. uniswap_autopilot/swap/flow_core/diagnostics.py +216 -0
  74. uniswap_autopilot/swap/flow_core/paper.py +113 -0
  75. uniswap_autopilot/swap/flow_core/policy.py +142 -0
  76. uniswap_autopilot/swap/links/__init__.py +2 -0
  77. uniswap_autopilot/swap/links/deep_link.py +69 -0
  78. uniswap_autopilot/swap/trading_api/permit.py +41 -0
  79. uniswap_autopilot/swap/trading_api/quote.py +282 -0
  80. uniswap_autopilot/swap/trading_api/swap.py +248 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 counterfactual5
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 @@
1
+ uniswap_autopilot
@@ -0,0 +1,3 @@
1
+ """Uniswap Autopilot — Automated swap execution, LP management, and analytics for Uniswap v2/v3/v4."""
2
+
3
+ __version__ = "0.6.0"
File without changes
@@ -0,0 +1,525 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import urllib.error
7
+ import urllib.request
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ from uniswap_autopilot.common.common import dump_json, load_local_env, normalize_chain, resolve_token
13
+ from uniswap_autopilot.analytics.position import (
14
+ analyze_position,
15
+ calculate_position_amounts,
16
+ fetch_token_prices,
17
+ )
18
+ from uniswap_autopilot.lp.v3.tick import nearest_usable_tick, price_to_tick, tick_to_price
19
+ from uniswap_autopilot.analytics.range_suggest import suggest_ranges
20
+
21
+ DEFILLAMA_YIELDS_URL = "https://yields.llama.fi/pools"
22
+
23
+ DEFILLAMA_CHAIN_MAP: dict[str, str] = {
24
+ "avalanche": "avax",
25
+ "world_chain": "worldchain",
26
+ "polygon": "matic",
27
+ }
28
+
29
+ DEFAULT_SCENARIOS = [-50, -30, -20, -10, -5, 5, 10, 20, 30, 50]
30
+
31
+
32
+ def calculate_il(
33
+ price_entry: float,
34
+ price_current: float,
35
+ tick_lower: int,
36
+ tick_upper: int,
37
+ decimals0: int,
38
+ decimals1: int,
39
+ liquidity: int,
40
+ ) -> dict[str, Any]:
41
+ tick_entry = price_to_tick(price_entry, decimals0, decimals1)
42
+ tick_current = price_to_tick(price_current, decimals0, decimals1)
43
+
44
+ amount0_entry, amount1_entry = calculate_position_amounts(
45
+ liquidity, tick_entry, tick_lower, tick_upper, decimals0, decimals1,
46
+ )
47
+ amount0_current, amount1_current = calculate_position_amounts(
48
+ liquidity, tick_current, tick_lower, tick_upper, decimals0, decimals1,
49
+ )
50
+
51
+ hodl_value = amount0_entry * price_current + amount1_entry
52
+ lp_value = amount0_current * price_current + amount1_current
53
+
54
+ if hodl_value > 0:
55
+ il_pct = (lp_value / hodl_value - 1) * 100
56
+ else:
57
+ il_pct = 0.0
58
+
59
+ fee_break_even = abs(il_pct) / (1 + il_pct / 100) if il_pct > -100 else float("inf")
60
+
61
+ in_range = tick_lower < tick_current < tick_upper
62
+
63
+ price_change_pct = ((price_current / price_entry) - 1) * 100 if price_entry != 0 else 0.0
64
+
65
+ return {
66
+ "priceEntry": price_entry,
67
+ "priceCurrent": price_current,
68
+ "priceChangePct": price_change_pct,
69
+ "tickEntry": tick_entry,
70
+ "tickCurrent": tick_current,
71
+ "tickLower": tick_lower,
72
+ "tickUpper": tick_upper,
73
+ "inRange": in_range,
74
+ "amountsAtEntry": {
75
+ "amount0": round(amount0_entry, 8),
76
+ "amount1": round(amount1_entry, 8),
77
+ "valueToken1": round(amount0_entry * price_entry + amount1_entry, 8),
78
+ },
79
+ "amountsAtCurrent": {
80
+ "amount0": round(amount0_current, 8),
81
+ "amount1": round(amount1_current, 8),
82
+ "valueToken1": round(lp_value, 8),
83
+ },
84
+ "hodlValueToken1": round(hodl_value, 8),
85
+ "lpValueToken1": round(lp_value, 8),
86
+ "impermanentLossPct": round(il_pct, 4),
87
+ "feeBreakEvenPct": round(fee_break_even, 4),
88
+ }
89
+
90
+
91
+ def estimate_il_for_position(
92
+ chain_name: str,
93
+ token_id: int,
94
+ price_change_pct: float,
95
+ rpc_url: str | None = None,
96
+ ) -> dict[str, Any]:
97
+ chain = normalize_chain(chain_name)
98
+ pos = analyze_position(chain_name, token_id, rpc_url)
99
+
100
+ addr0 = pos["token0"]["address"]
101
+ addr1 = pos["token1"]["address"]
102
+
103
+ # Resolve decimals from token catalog since analyze_position may not include them
104
+ try:
105
+ tok0 = resolve_token(chain, addr0)
106
+ decimals0 = tok0["decimals"]
107
+ except Exception:
108
+ decimals0 = 18
109
+ try:
110
+ tok1 = resolve_token(chain, addr1)
111
+ decimals1 = tok1["decimals"]
112
+ except Exception:
113
+ decimals1 = 18
114
+
115
+ current_tick = pos["currentTick"]
116
+ current_price = tick_to_price(current_tick, decimals0, decimals1)
117
+ hypothetical_price = current_price * (1 + price_change_pct / 100)
118
+ liquidity = int(pos["liquidity"])
119
+
120
+ il_result = calculate_il(
121
+ price_entry=current_price,
122
+ price_current=hypothetical_price,
123
+ tick_lower=pos["tickLower"],
124
+ tick_upper=pos["tickUpper"],
125
+ decimals0=decimals0,
126
+ decimals1=decimals1,
127
+ liquidity=liquidity,
128
+ )
129
+
130
+ price0, price1 = fetch_token_prices(chain.key, addr0, addr1)
131
+ if price0 is not None and price1 is not None:
132
+ il_result["hodlValueUsd"] = round(il_result["hodlValueToken1"] * price1, 2)
133
+ il_result["lpValueUsd"] = round(il_result["lpValueToken1"] * price1, 2)
134
+ il_result["price0Usd"] = price0
135
+ il_result["price1Usd"] = price1
136
+
137
+ return {
138
+ "action": "il_position",
139
+ "chain": {"key": chain.key, "chainId": chain.chain_id},
140
+ "tokenId": token_id,
141
+ "token0": pos["token0"]["symbol"],
142
+ "token1": pos["token1"]["symbol"],
143
+ "feeTier": pos["feeTier"],
144
+ "currentPrice": current_price,
145
+ "hypotheticalPrice": hypothetical_price,
146
+ "priceChangePct": price_change_pct,
147
+ "currentLiquidity": str(liquidity),
148
+ **il_result,
149
+ }
150
+
151
+
152
+ def compare_il_across_ranges(
153
+ chain_name: str,
154
+ token_a: str,
155
+ token_b: str,
156
+ fee_tier: int,
157
+ price_change_pct: float,
158
+ rpc_url: str | None = None,
159
+ ) -> dict[str, Any]:
160
+ chain = normalize_chain(chain_name)
161
+ tok_a = resolve_token(chain, token_a)
162
+ tok_b = resolve_token(chain, token_b)
163
+
164
+ ranges = suggest_ranges(chain_name, token_a, token_b, fee_tier, rpc_url)
165
+ current_price = float(ranges["currentPrice"])
166
+ hypothetical_price = current_price * (1 + price_change_pct / 100)
167
+ decimals0 = ranges["tokenA"].get("decimals", 18)
168
+ decimals1 = ranges["tokenB"].get("decimals", 18)
169
+
170
+ comparisons = []
171
+ for suggestion in ranges.get("suggestions", []):
172
+ il = calculate_il(
173
+ price_entry=current_price,
174
+ price_current=hypothetical_price,
175
+ tick_lower=suggestion["tickLower"],
176
+ tick_upper=suggestion["tickUpper"],
177
+ decimals0=decimals0,
178
+ decimals1=decimals1,
179
+ liquidity=10**18,
180
+ )
181
+ comparisons.append({
182
+ "profile": suggestion["profile"],
183
+ "rangeWidthPct": suggestion.get("rangeWidthPct"),
184
+ "tickLower": suggestion["tickLower"],
185
+ "tickUpper": suggestion["tickUpper"],
186
+ "impermanentLossPct": il["impermanentLossPct"],
187
+ "inRange": il["inRange"],
188
+ "feeBreakEvenPct": il["feeBreakEvenPct"],
189
+ })
190
+
191
+ return {
192
+ "action": "il_ranges_compare",
193
+ "chain": {"key": chain.key, "chainId": chain.chain_id},
194
+ "tokenA": ranges["tokenA"]["symbol"],
195
+ "tokenB": ranges["tokenB"]["symbol"],
196
+ "feeTier": ranges["feeTier"],
197
+ "currentPrice": current_price,
198
+ "hypotheticalPrice": hypothetical_price,
199
+ "priceChangePct": price_change_pct,
200
+ "comparisons": comparisons,
201
+ }
202
+
203
+
204
+ def _fetch_pool_apy(
205
+ chain_name: str,
206
+ pool_address: str,
207
+ ) -> float | None:
208
+ chain = normalize_chain(chain_name)
209
+ dl_chain = DEFILLAMA_CHAIN_MAP.get(chain.key, chain.key).capitalize()
210
+ try:
211
+ request = urllib.request.Request(DEFILLAMA_YIELDS_URL, headers={"Accept": "application/json"})
212
+ with urllib.request.urlopen(request, timeout=30) as response:
213
+ data = json.loads(response.read().decode("utf-8"))
214
+ except (urllib.error.HTTPError, urllib.error.URLError, OSError, json.JSONDecodeError):
215
+ return None
216
+
217
+ target = pool_address.lower()
218
+ for pool in data.get("data", []):
219
+ if pool.get("project") != "uniswap-v3":
220
+ continue
221
+ if (pool.get("chain") or "").lower() != dl_chain.lower():
222
+ continue
223
+ if (pool.get("pool") or "").lower() == target:
224
+ apy = pool.get("apy")
225
+ return float(apy) if apy is not None else None
226
+ return None
227
+
228
+
229
+ def _get_pool_address_for_pair(
230
+ chain_name: str,
231
+ token_a: str,
232
+ token_b: str,
233
+ fee_tier: int,
234
+ rpc_url: str | None = None,
235
+ ) -> str | None:
236
+ from uniswap_autopilot.lp.v3.pool import query_pool_full_info
237
+ try:
238
+ info = query_pool_full_info(chain_name, token_a, token_b, fee_tier, rpc_url)
239
+ if info.get("exists"):
240
+ return info.get("poolAddress")
241
+ except Exception:
242
+ pass
243
+ return None
244
+
245
+
246
+ def simulate_il(
247
+ chain_name: str,
248
+ token_a: str,
249
+ token_b: str,
250
+ fee_tier: int,
251
+ scenarios: list[float] | None = None,
252
+ rpc_url: str | None = None,
253
+ ) -> dict[str, Any]:
254
+ chain = normalize_chain(chain_name)
255
+ effective_scenarios = scenarios or DEFAULT_SCENARIOS
256
+
257
+ ranges = suggest_ranges(chain_name, token_a, token_b, fee_tier, rpc_url)
258
+ current_price = float(ranges["currentPrice"])
259
+ decimals0 = ranges["tokenA"].get("decimals", 18)
260
+ decimals1 = ranges["tokenB"].get("decimals", 18)
261
+
262
+ pool_addr = _get_pool_address_for_pair(chain_name, token_a, token_b, fee_tier, rpc_url)
263
+ pool_apy = _fetch_pool_apy(chain_name, pool_addr) if pool_addr else None
264
+
265
+ matrix: list[dict[str, Any]] = []
266
+ for pct in effective_scenarios:
267
+ hypothetical_price = current_price * (1 + pct / 100)
268
+ row: dict[str, Any] = {
269
+ "priceChangePct": pct,
270
+ "hypotheticalPrice": round(hypothetical_price, 8),
271
+ "profiles": [],
272
+ }
273
+ for suggestion in ranges.get("suggestions", []):
274
+ il = calculate_il(
275
+ price_entry=current_price,
276
+ price_current=hypothetical_price,
277
+ tick_lower=suggestion["tickLower"],
278
+ tick_upper=suggestion["tickUpper"],
279
+ decimals0=decimals0,
280
+ decimals1=decimals1,
281
+ liquidity=10**18,
282
+ )
283
+ break_even = abs(il["feeBreakEvenPct"])
284
+ apy_covers = pool_apy is not None and pool_apy >= break_even if il["impermanentLossPct"] < 0 else True
285
+ row["profiles"].append({
286
+ "profile": suggestion["profile"],
287
+ "impermanentLossPct": il["impermanentLossPct"],
288
+ "feeBreakEvenPct": il["feeBreakEvenPct"],
289
+ "inRange": il["inRange"],
290
+ "apyCoversIL": apy_covers,
291
+ })
292
+ matrix.append(row)
293
+
294
+ return {
295
+ "action": "il_simulate",
296
+ "chain": {"key": chain.key, "chainId": chain.chain_id},
297
+ "tokenA": ranges["tokenA"]["symbol"],
298
+ "tokenB": ranges["tokenB"]["symbol"],
299
+ "feeTier": ranges["feeTier"],
300
+ "currentPrice": current_price,
301
+ "poolAddress": pool_addr,
302
+ "poolApy": pool_apy,
303
+ "scenarios": effective_scenarios,
304
+ "matrix": matrix,
305
+ }
306
+
307
+
308
+ def simulate_position(
309
+ chain_name: str,
310
+ token_id: int,
311
+ scenarios: list[float] | None = None,
312
+ rpc_url: str | None = None,
313
+ ) -> dict[str, Any]:
314
+ chain = normalize_chain(chain_name)
315
+ effective_scenarios = scenarios or DEFAULT_SCENARIOS
316
+
317
+ pos = analyze_position(chain_name, token_id, rpc_url)
318
+ addr0 = pos["token0"]["address"]
319
+ addr1 = pos["token1"]["address"]
320
+
321
+ try:
322
+ tok0 = resolve_token(chain, addr0)
323
+ decimals0 = tok0["decimals"]
324
+ except Exception:
325
+ decimals0 = 18
326
+ try:
327
+ tok1 = resolve_token(chain, addr1)
328
+ decimals1 = tok1["decimals"]
329
+ except Exception:
330
+ decimals1 = 18
331
+
332
+ current_tick = pos["currentTick"]
333
+ current_price = tick_to_price(current_tick, decimals0, decimals1)
334
+ tick_lower = pos["tickLower"]
335
+ tick_upper = pos["tickUpper"]
336
+ liquidity = int(pos["liquidity"])
337
+
338
+ pool_addr = pos.get("poolAddress")
339
+ pool_apy = _fetch_pool_apy(chain_name, pool_addr) if pool_addr else None
340
+
341
+ price0, price1 = fetch_token_prices(chain.key, addr0, addr1)
342
+
343
+ matrix: list[dict[str, Any]] = []
344
+ for pct in effective_scenarios:
345
+ hypothetical_price = current_price * (1 + pct / 100)
346
+ il = calculate_il(
347
+ price_entry=current_price,
348
+ price_current=hypothetical_price,
349
+ tick_lower=tick_lower,
350
+ tick_upper=tick_upper,
351
+ decimals0=decimals0,
352
+ decimals1=decimals1,
353
+ liquidity=liquidity,
354
+ )
355
+ break_even = abs(il["feeBreakEvenPct"])
356
+ apy_covers = pool_apy is not None and pool_apy >= break_even if il["impermanentLossPct"] < 0 else True
357
+
358
+ lp_usd = il["lpValueToken1"] * (price1 or 0)
359
+ hodl_usd = il["hodlValueToken1"] * (price1 or 0)
360
+
361
+ matrix.append({
362
+ "priceChangePct": pct,
363
+ "hypotheticalPrice": round(hypothetical_price, 8),
364
+ "impermanentLossPct": il["impermanentLossPct"],
365
+ "feeBreakEvenPct": il["feeBreakEvenPct"],
366
+ "inRange": il["inRange"],
367
+ "lpValueUsd": round(lp_usd, 2) if price1 else None,
368
+ "hodlValueUsd": round(hodl_usd, 2) if price1 else None,
369
+ "apyCoversIL": apy_covers,
370
+ })
371
+
372
+ return {
373
+ "action": "il_simulate_position",
374
+ "chain": {"key": chain.key, "chainId": chain.chain_id},
375
+ "tokenId": token_id,
376
+ "token0": pos["token0"]["symbol"],
377
+ "token1": pos["token1"]["symbol"],
378
+ "feeTier": pos["feeTier"],
379
+ "currentPrice": current_price,
380
+ "tickLower": tick_lower,
381
+ "tickUpper": tick_upper,
382
+ "currentLiquidity": str(liquidity),
383
+ "poolAddress": pool_addr,
384
+ "poolApy": pool_apy,
385
+ "scenarios": effective_scenarios,
386
+ "matrix": matrix,
387
+ }
388
+
389
+
390
+ def quick_il(
391
+ price_entry: float,
392
+ price_current: float,
393
+ range_pct: float,
394
+ decimals0: int = 18,
395
+ decimals1: int = 6,
396
+ tick_spacing: int = 60,
397
+ ) -> dict[str, Any]:
398
+ tick_entry = price_to_tick(price_entry, decimals0, decimals1)
399
+ tick_lower = nearest_usable_tick(
400
+ price_to_tick(price_entry * (1 - range_pct / 200), decimals0, decimals1),
401
+ tick_spacing,
402
+ )
403
+ tick_upper = nearest_usable_tick(
404
+ price_to_tick(price_entry * (1 + range_pct / 200), decimals0, decimals1),
405
+ tick_spacing,
406
+ )
407
+
408
+ il = calculate_il(
409
+ price_entry=price_entry,
410
+ price_current=price_current,
411
+ tick_lower=tick_lower,
412
+ tick_upper=tick_upper,
413
+ decimals0=decimals0,
414
+ decimals1=decimals1,
415
+ liquidity=10**18,
416
+ )
417
+ il["rangePct"] = range_pct
418
+ il["tickSpacing"] = tick_spacing
419
+ return {
420
+ "action": "il_quick",
421
+ **il,
422
+ }
423
+
424
+
425
+ def main() -> None:
426
+ parser = argparse.ArgumentParser(description="Uniswap V3 Impermanent Loss Calculator")
427
+ sub = parser.add_subparsers(dest="command")
428
+
429
+ p = sub.add_parser("position", help="Estimate IL for an on-chain position given a hypothetical price change")
430
+ p.add_argument("--chain", required=True)
431
+ p.add_argument("--token-id", type=int, required=True)
432
+ p.add_argument("--price-change", type=float, required=True, help="Hypothetical price change %% (e.g. -20 for -20%%)")
433
+ p.add_argument("--rpc-url")
434
+ p.add_argument("--output")
435
+
436
+ r = sub.add_parser("ranges", help="Compare IL across CONSERVATIVE/MODERATE/AGGRESSIVE ranges")
437
+ r.add_argument("--chain", required=True)
438
+ r.add_argument("--token-a", required=True)
439
+ r.add_argument("--token-b", required=True)
440
+ r.add_argument("--fee-tier", type=int, required=True)
441
+ r.add_argument("--price-change", type=float, required=True, help="Hypothetical price change %%")
442
+ r.add_argument("--rpc-url")
443
+ r.add_argument("--output")
444
+
445
+ q = sub.add_parser("quick", help="Quick IL calculation without on-chain data")
446
+ q.add_argument("--price-entry", type=float, required=True, help="Entry price (token1 per token0)")
447
+ q.add_argument("--price-current", type=float, required=True, help="Current/hypothetical price")
448
+ q.add_argument("--range-pct", type=float, required=True, help="Range width %% (e.g. 20 = +/-10%% each side)")
449
+ q.add_argument("--decimals0", type=int, default=18)
450
+ q.add_argument("--decimals1", type=int, default=6)
451
+ q.add_argument("--tick-spacing", type=int, default=60)
452
+ q.add_argument("--output")
453
+
454
+ sim = sub.add_parser("simulate", help="Multi-scenario IL simulation with fee yield comparison")
455
+ sim.add_argument("--chain", required=True)
456
+ sim.add_argument("--token-a", required=True)
457
+ sim.add_argument("--token-b", required=True)
458
+ sim.add_argument("--fee-tier", type=int, required=True)
459
+ sim.add_argument("--scenarios", help=f"Comma-separated price change %% (default: {','.join(str(s) for s in DEFAULT_SCENARIOS)})")
460
+ sim.add_argument("--rpc-url")
461
+ sim.add_argument("--output")
462
+
463
+ sp = sub.add_parser("simulate-position", help="Multi-scenario IL simulation for an existing position")
464
+ sp.add_argument("--chain", required=True)
465
+ sp.add_argument("--token-id", type=int, required=True)
466
+ sp.add_argument("--scenarios", help=f"Comma-separated price change %% (default: {','.join(str(s) for s in DEFAULT_SCENARIOS)})")
467
+ sp.add_argument("--rpc-url")
468
+ sp.add_argument("--output")
469
+
470
+ args = parser.parse_args()
471
+ load_local_env()
472
+
473
+ if args.command == "position":
474
+ result = estimate_il_for_position(args.chain, args.token_id, args.price_change, args.rpc_url)
475
+ print(f"IL for position #{args.token_id} at {args.price_change:+.1f}% price change: {result['impermanentLossPct']:.4f}%")
476
+ if args.output:
477
+ Path(args.output).write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
478
+ dump_json(result)
479
+ elif args.command == "ranges":
480
+ result = compare_il_across_ranges(args.chain, args.token_a, args.token_b, args.fee_tier, args.price_change, args.rpc_url)
481
+ for c in result["comparisons"]:
482
+ print(f" {c['profile']:13s}: IL={c['impermanentLossPct']:+.4f}% inRange={c['inRange']}")
483
+ if args.output:
484
+ Path(args.output).write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
485
+ dump_json(result)
486
+ elif args.command == "quick":
487
+ result = quick_il(args.price_entry, args.price_current, args.range_pct, args.decimals0, args.decimals1, args.tick_spacing)
488
+ print(f"IL at {result['priceChangePct']:+.1f}% price change, range ±{args.range_pct/2}%: {result['impermanentLossPct']:.4f}%")
489
+ if args.output:
490
+ Path(args.output).write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
491
+ dump_json(result)
492
+ elif args.command == "simulate":
493
+ scenarios = None
494
+ if args.scenarios:
495
+ scenarios = [float(s.strip()) for s in args.scenarios.split(",") if s.strip()]
496
+ result = simulate_il(args.chain, args.token_a, args.token_b, args.fee_tier, scenarios, args.rpc_url)
497
+ apy_str = f"{result['poolApy']:.2f}%" if result["poolApy"] is not None else "N/A"
498
+ print(f"IL Simulation: {result['tokenA']}/{result['tokenB']} fee={result['feeTier']} pool_apy={apy_str}")
499
+ print(f" {'Price%':>8s} {'Profile':13s} {'IL%':>10s} {'BreakEven%':>10s} {'InRng':>5s} {'APY>IL':>6s}")
500
+ for row in result["matrix"]:
501
+ for pr in row["profiles"]:
502
+ print(f" {row['priceChangePct']:>+7.0f}% {pr['profile']:13s} {pr['impermanentLossPct']:>+9.4f}% {pr['feeBreakEvenPct']:>+9.4f}% {str(pr['inRange']):>5s} {str(pr['apyCoversIL']):>6s}")
503
+ if args.output:
504
+ Path(args.output).write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
505
+ dump_json(result)
506
+ elif args.command == "simulate-position":
507
+ scenarios = None
508
+ if args.scenarios:
509
+ scenarios = [float(s.strip()) for s in args.scenarios.split(",") if s.strip()]
510
+ result = simulate_position(args.chain, args.token_id, scenarios, args.rpc_url)
511
+ apy_str = f"{result['poolApy']:.2f}%" if result["poolApy"] is not None else "N/A"
512
+ print(f"IL Simulation: position #{args.token_id} {result['token0']}/{result['token1']} pool_apy={apy_str}")
513
+ print(f" {'Price%':>8s} {'IL%':>10s} {'BreakEven%':>10s} {'InRng':>5s} {'APY>IL':>6s} {'LP USD':>12s}")
514
+ for row in result["matrix"]:
515
+ lp_usd_str = f"${row['lpValueUsd']:.2f}" if row.get("lpValueUsd") is not None else "-"
516
+ print(f" {row['priceChangePct']:>+7.0f}% {row['impermanentLossPct']:>+9.4f}% {row['feeBreakEvenPct']:>+9.4f}% {str(row['inRange']):>5s} {str(row['apyCoversIL']):>6s} {lp_usd_str:>12s}")
517
+ if args.output:
518
+ Path(args.output).write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
519
+ dump_json(result)
520
+ else:
521
+ parser.print_help()
522
+
523
+
524
+ if __name__ == "__main__":
525
+ main()