copytop 0.1.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.
- copytop/__init__.py +36 -0
- copytop/__main__.py +3 -0
- copytop/cli.py +343 -0
- copytop/client.py +420 -0
- copytop/py.typed +0 -0
- copytop-0.1.0.dist-info/METADATA +152 -0
- copytop-0.1.0.dist-info/RECORD +10 -0
- copytop-0.1.0.dist-info/WHEEL +4 -0
- copytop-0.1.0.dist-info/entry_points.txt +2 -0
- copytop-0.1.0.dist-info/licenses/LICENSE +21 -0
copytop/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""copytop: Python client for the copy.top API.
|
|
2
|
+
|
|
3
|
+
copy.top (https://copy.top) tracks what top traders buy and sell on fomo, pumpfun
|
|
4
|
+
and Hyperliquid, and lets people copy them. This package reads the public REST API
|
|
5
|
+
at https://copy.top/v1. Read-only: nothing here places an order.
|
|
6
|
+
Figures are data, not advice.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__version__ = "0.1.0"
|
|
10
|
+
|
|
11
|
+
from .client import ( # noqa: E402
|
|
12
|
+
AuthError,
|
|
13
|
+
Client,
|
|
14
|
+
CopyTopError,
|
|
15
|
+
NotFoundError,
|
|
16
|
+
RateLimitError,
|
|
17
|
+
RedirectRefusedError,
|
|
18
|
+
coin_url,
|
|
19
|
+
hl_market_url,
|
|
20
|
+
hl_trader_url,
|
|
21
|
+
trader_url,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"Client",
|
|
26
|
+
"CopyTopError",
|
|
27
|
+
"NotFoundError",
|
|
28
|
+
"RateLimitError",
|
|
29
|
+
"AuthError",
|
|
30
|
+
"RedirectRefusedError",
|
|
31
|
+
"trader_url",
|
|
32
|
+
"coin_url",
|
|
33
|
+
"hl_trader_url",
|
|
34
|
+
"hl_market_url",
|
|
35
|
+
"__version__",
|
|
36
|
+
]
|
copytop/__main__.py
ADDED
copytop/cli.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
"""copytop command line: copy.top in your terminal.
|
|
2
|
+
|
|
3
|
+
copytop hot
|
|
4
|
+
copytop traders --window 7d --platform pumpfun
|
|
5
|
+
copytop trader <handle>
|
|
6
|
+
copytop hl-markets --category stocks
|
|
7
|
+
|
|
8
|
+
Add --json to any command for raw JSON. Read-only: nothing here places an order.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
from .client import Client, CopyTopError, coin_url, hl_market_url, hl_trader_url, trader_url
|
|
21
|
+
|
|
22
|
+
FOOTER = "copy.top | https://copy.top | figures are data, not advice"
|
|
23
|
+
|
|
24
|
+
# Terminal control characters (ESC, CSI, BEL, backspace, CR...). An API string holding them
|
|
25
|
+
# could move the cursor, rewrite lines or change the window title of the terminal. Tab and
|
|
26
|
+
# newline are kept. Every output of the CLI, errors included, goes through _clean().
|
|
27
|
+
_CONTROL = re.compile("[\x00-\x08\x0b-\x1f\x7f\x9b]")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _clean(text: Any) -> str:
|
|
31
|
+
return _CONTROL.sub("", str(text))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _out(text: Any, file: Any = None) -> None:
|
|
35
|
+
print(_clean(text), file=file or sys.stdout, flush=True)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _money(v: Any) -> str:
|
|
39
|
+
if v is None:
|
|
40
|
+
return "-"
|
|
41
|
+
try:
|
|
42
|
+
x = float(v)
|
|
43
|
+
except (TypeError, ValueError):
|
|
44
|
+
return str(v)
|
|
45
|
+
sign = "-" if x < 0 else ""
|
|
46
|
+
x = abs(x)
|
|
47
|
+
for unit, div in (("B", 1e9), ("M", 1e6), ("k", 1e3)):
|
|
48
|
+
if x >= div:
|
|
49
|
+
return "%s$%.1f%s" % (sign, x / div, unit)
|
|
50
|
+
return "%s$%.0f" % (sign, x)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _pct(v: Any, ratio: bool = False) -> str:
|
|
54
|
+
if v is None:
|
|
55
|
+
return "-"
|
|
56
|
+
try:
|
|
57
|
+
x = float(v) * (100 if ratio else 1)
|
|
58
|
+
except (TypeError, ValueError):
|
|
59
|
+
return str(v)
|
|
60
|
+
return "%+.1f%%" % x
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _table(rows: List[List[str]], header: List[str]) -> str:
|
|
64
|
+
widths = [len(h) for h in header]
|
|
65
|
+
for r in rows:
|
|
66
|
+
for i, c in enumerate(r):
|
|
67
|
+
widths[i] = max(widths[i], len(c))
|
|
68
|
+
fmt = " ".join("{:<%d}" % w for w in widths)
|
|
69
|
+
out = [fmt.format(*header), fmt.format(*["-" * w for w in widths])]
|
|
70
|
+
out += [fmt.format(*r) for r in rows]
|
|
71
|
+
return "\n".join(out)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
Render = Callable[[Dict[str, Any]], str]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _r_traders(d: Dict[str, Any]) -> str:
|
|
78
|
+
rows = [[str(i + 1), t.get("handle", ""), (t.get("name") or "")[:18], ",".join(t.get("platforms") or []),
|
|
79
|
+
_money(t.get("pnl")), _pct(t.get("roi"), True), _pct(t.get("winRate"), True).lstrip("+"),
|
|
80
|
+
t.get("fairPlay") or "-", trader_url(t.get("handle", ""))]
|
|
81
|
+
for i, t in enumerate(d.get("traders") or [])]
|
|
82
|
+
return _table(rows, ["#", "handle", "name", "platform", "pnl", "roi", "win", "fair play", "page"])
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _r_hot(d: Dict[str, Any]) -> str:
|
|
86
|
+
rows = [[c.get("symbol") or "", c.get("chain") or "", _money(c.get("mcap")), str(c.get("traders", "-")),
|
|
87
|
+
str(c.get("topTraders", "-")), str(c.get("topStillIn", "-")), _money(c.get("boughtUsd")),
|
|
88
|
+
coin_url(c.get("chain", ""), c.get("token", ""))]
|
|
89
|
+
for c in d.get("coins") or []]
|
|
90
|
+
return _table(rows, ["coin", "chain", "mcap", "traders", "top", "still in", "bought", "page"])
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _r_index(d: Dict[str, Any]) -> str:
|
|
94
|
+
rows = [[str(c.get("score", "-")), c.get("symbol") or "", c.get("chain") or "", c.get("tier") or "",
|
|
95
|
+
_money(c.get("mcap")), _pct(c.get("change24h")), coin_url(c.get("chain", ""), c.get("token", ""))]
|
|
96
|
+
for c in d.get("coins") or []]
|
|
97
|
+
return _table(rows, ["score", "coin", "chain", "tier", "mcap", "24h", "page"])
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _r_flow(d: Dict[str, Any]) -> str:
|
|
101
|
+
rows = [[c.get("symbol") or "", c.get("chain") or "", _money(c.get("usd")), str(c.get("traders", "-")),
|
|
102
|
+
coin_url(c.get("chain", ""), c.get("token", ""))] for c in d.get("coins") or []]
|
|
103
|
+
return _table(rows, ["coin", "chain", "usd", "traders", "page"])
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _r_dexpaid(d: Dict[str, Any]) -> str:
|
|
107
|
+
rows = [[c.get("symbol") or "", c.get("chain") or "", _money(c.get("mcap")), _money(c.get("volume24h")),
|
|
108
|
+
_pct(c.get("change24h")), (c.get("paidAt") or "")[:16], coin_url(c.get("chain", ""), c.get("token", ""))]
|
|
109
|
+
for c in d.get("coins") or []]
|
|
110
|
+
return _table(rows, ["coin", "chain", "mcap", "vol 24h", "24h", "paid at", "page"])
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _r_trades(d: Dict[str, Any]) -> str:
|
|
114
|
+
rows = [[(t.get("at") or "")[11:19], t.get("handle") or "", t.get("side") or "", t.get("symbol") or "",
|
|
115
|
+
t.get("chain") or "", _money(t.get("usd"))] for t in d.get("trades") or []]
|
|
116
|
+
return _table(rows, ["time", "trader", "side", "coin", "chain", "usd"])
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _r_alerts(d: Dict[str, Any]) -> str:
|
|
120
|
+
rows = [[(e.get("at") or "")[11:19], e.get("kind") or "", e.get("symbol") or "", e.get("chain") or "",
|
|
121
|
+
str(e.get("topTraders") or e.get("handle") or ""), (e.get("url") or "").split("?")[0]]
|
|
122
|
+
for e in d.get("events") or []]
|
|
123
|
+
return _table(rows, ["time", "kind", "coin", "chain", "top / trader", "page"])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _r_theses(d: Dict[str, Any]) -> str:
|
|
127
|
+
rows = [[t.get("handle") or "", t.get("symbol") or "", (t.get("text") or "").replace("\n", " ")[:60],
|
|
128
|
+
coin_url(t.get("chain", ""), t.get("token", ""))] for t in d.get("theses") or []]
|
|
129
|
+
return _table(rows, ["trader", "coin", "thesis", "page"])
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _r_search(d: Dict[str, Any]) -> str:
|
|
133
|
+
out = []
|
|
134
|
+
for t in d.get("traders") or []:
|
|
135
|
+
out.append("trader %-20s %-20s %s" % (t.get("handle", ""), (t.get("name") or "")[:20], trader_url(t.get("handle", ""))))
|
|
136
|
+
for c in d.get("coins") or []:
|
|
137
|
+
out.append("coin %-20s %-20s %s" % (c.get("symbol", ""), c.get("chain", ""),
|
|
138
|
+
coin_url(c.get("chain", ""), c.get("token") or c.get("address", ""))))
|
|
139
|
+
return "\n".join(out) or "nothing found"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _r_trader(d: Dict[str, Any]) -> str:
|
|
143
|
+
t = d.get("trader") or {}
|
|
144
|
+
lines = [
|
|
145
|
+
"%s (%s) %s" % (t.get("handle", ""), t.get("name") or "-", trader_url(t.get("handle", ""))),
|
|
146
|
+
"pnl 30d %s realized %s unrealized %s roi %s win rate %s fair play %s" % (
|
|
147
|
+
_money(t.get("pnl")), _money(t.get("realized")), _money(t.get("unrealized")),
|
|
148
|
+
_pct(t.get("roi"), True), _pct(t.get("winRate"), True).lstrip("+"), t.get("fairPlay") or "-"),
|
|
149
|
+
"followers %s copiers %s platforms %s" % (t.get("followers", "-"), t.get("copiers", "-"),
|
|
150
|
+
",".join(t.get("platforms") or [])),
|
|
151
|
+
]
|
|
152
|
+
pos = d.get("open_positions") or []
|
|
153
|
+
if pos:
|
|
154
|
+
lines += ["", "open positions:", _table([[p.get("symbol") or "", p.get("chain") or "", _money(p.get("valueUsd")),
|
|
155
|
+
_money(p.get("pnlUsd"))] for p in pos], ["coin", "chain", "value", "pnl"])]
|
|
156
|
+
return "\n".join(lines)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _r_coin(d: Dict[str, Any]) -> str:
|
|
160
|
+
t = d.get("token") or {}
|
|
161
|
+
leaders = d.get("leaders") or {}
|
|
162
|
+
lines = ["%s (%s) price %s mcap %s 1h %s 24h %s liquidity %s" % (
|
|
163
|
+
t.get("symbol", ""), t.get("name") or "-", t.get("price", "-"), _money(t.get("mcap")),
|
|
164
|
+
_pct(t.get("change1h")), _pct(t.get("change24h")), _money(t.get("liquidityUsd"))),
|
|
165
|
+
"tracked traders holding %s, sold out %s" % (leaders.get("holdingNow", "-"), leaders.get("soldOut", "-"))]
|
|
166
|
+
rows = [[r.get("handle") or "", "yes" if r.get("holding") else "no", _money(r.get("bagUsd")),
|
|
167
|
+
_money(r.get("pnlOnCoinUsd")), "top" if r.get("top") else ""] for r in leaders.get("rows") or []]
|
|
168
|
+
if rows:
|
|
169
|
+
lines += ["", _table(rows, ["trader", "holding", "bag", "pnl on coin", ""])]
|
|
170
|
+
return "\n".join(lines)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _r_hl_traders(d: Dict[str, Any]) -> str:
|
|
174
|
+
rows = [[str(i + 1), (t.get("address") or "")[:10] + "...", _money(t.get("accountValue")), _money(t.get("pnl")),
|
|
175
|
+
_pct(t.get("roi"), True), _pct(t.get("winRate"), True).lstrip("+"), t.get("style") or "-",
|
|
176
|
+
hl_trader_url(t.get("address", ""))] for i, t in enumerate(d.get("traders") or [])]
|
|
177
|
+
return _table(rows, ["#", "address", "account", "pnl", "roi", "win", "style", "page"])
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _r_hl_markets(d: Dict[str, Any]) -> str:
|
|
181
|
+
rows = [[m.get("coin") or "", m.get("category") or "", str(m.get("markPx", "-")), _pct(m.get("change24h"), True),
|
|
182
|
+
_money(m.get("dayNtlVlm")), _money(m.get("openInterestUsd")), hl_market_url(m.get("coin", ""))]
|
|
183
|
+
for m in d.get("markets") or []]
|
|
184
|
+
return _table(rows, ["market", "category", "mark", "24h", "volume 24h", "open interest", "page"])
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _r_hl_calls(d: Dict[str, Any]) -> str:
|
|
188
|
+
rows = [[(c.get("handle") or ""), c.get("dir") or "", str(c.get("entry") or c.get("px") or "-"),
|
|
189
|
+
str(c.get("target") or "-"), c.get("status") or "", (c.get("url") or "")] for c in d.get("calls") or []]
|
|
190
|
+
return _table(rows, ["analyst", "dir", "entry", "target", "status", "post"])
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _r_json_summary(d: Dict[str, Any]) -> str:
|
|
194
|
+
return json.dumps(d, indent=2, ensure_ascii=False)[:4000]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
198
|
+
p = argparse.ArgumentParser(
|
|
199
|
+
prog="copytop",
|
|
200
|
+
description="copy.top in your terminal: what top fomo, pumpfun and Hyperliquid traders are buying. "
|
|
201
|
+
"Read-only, nothing here places an order. https://copy.top",
|
|
202
|
+
epilog="figures are data, not advice. docs: https://copy.top/agents",
|
|
203
|
+
)
|
|
204
|
+
p.add_argument("--version", action="version", version="copytop %s" % __version__)
|
|
205
|
+
p.add_argument("--key", help="API key from https://copy.top/account#api (or set COPYTOP_API_KEY)")
|
|
206
|
+
sub = p.add_subparsers(dest="cmd", metavar="command")
|
|
207
|
+
|
|
208
|
+
def add(name: str, help_: str, aliases: Sequence[str] = ()) -> argparse.ArgumentParser:
|
|
209
|
+
sp = sub.add_parser(name, help=help_, aliases=list(aliases))
|
|
210
|
+
sp.add_argument("--json", action="store_true", help="print raw JSON")
|
|
211
|
+
return sp
|
|
212
|
+
|
|
213
|
+
s = add("hot", "coins tracked traders are buying now")
|
|
214
|
+
s.add_argument("--window", choices=["1h", "24h"], default="24h")
|
|
215
|
+
s.add_argument("--max-mcap", type=float)
|
|
216
|
+
s.add_argument("--limit", type=int)
|
|
217
|
+
s = add("traders", "trader leaderboard (fomo and pumpfun)", aliases=["leaderboard"])
|
|
218
|
+
s.add_argument("--window", choices=["1d", "7d", "30d"], default="30d")
|
|
219
|
+
s.add_argument("--sort", choices=["total", "realized", "roi", "winrate", "copiers"], default="total")
|
|
220
|
+
s.add_argument("--platform", choices=["fomo", "pumpfun"])
|
|
221
|
+
s.add_argument("--chain")
|
|
222
|
+
s.add_argument("--clean", action="store_true", help="only traders with a clean fair play verdict")
|
|
223
|
+
s.add_argument("--limit", type=int)
|
|
224
|
+
s = add("trader", "one trader's profile")
|
|
225
|
+
s.add_argument("handle")
|
|
226
|
+
s = add("search", "find traders and coins")
|
|
227
|
+
s.add_argument("query")
|
|
228
|
+
s = add("coin", "one coin")
|
|
229
|
+
s.add_argument("chain")
|
|
230
|
+
s.add_argument("address")
|
|
231
|
+
s = add("flow", "coins ranked by dollars bought or sold")
|
|
232
|
+
s.add_argument("--side", choices=["buy", "sell"], default="buy")
|
|
233
|
+
s.add_argument("--window", choices=["1h", "6h", "24h", "7d"], default="24h")
|
|
234
|
+
s.add_argument("--limit", type=int)
|
|
235
|
+
s = add("index", "hot index: coins ranked 0 to 100 by attention")
|
|
236
|
+
s.add_argument("--window", choices=["1h", "6h", "24h"])
|
|
237
|
+
s.add_argument("--chain")
|
|
238
|
+
s.add_argument("--limit", type=int)
|
|
239
|
+
s = add("dexpaid", "coins whose team paid for a dexscreener profile")
|
|
240
|
+
s.add_argument("--limit", type=int)
|
|
241
|
+
s = add("trades", "the live tape")
|
|
242
|
+
s.add_argument("--side", choices=["buy", "sell"])
|
|
243
|
+
s.add_argument("--min-usd", type=float)
|
|
244
|
+
s.add_argument("--limit", type=int)
|
|
245
|
+
s = add("alerts", "confluence, big trades and theses since a cursor")
|
|
246
|
+
s.add_argument("--since")
|
|
247
|
+
s.add_argument("--kinds", help="comma separated: confluence,big_trade,thesis")
|
|
248
|
+
s.add_argument("--min-top-traders", type=int)
|
|
249
|
+
s.add_argument("--min-trade-usd", type=float)
|
|
250
|
+
s.add_argument("--max-mcap", type=float)
|
|
251
|
+
s.add_argument("--watch", action="store_true", help="keep polling once a minute and print new events")
|
|
252
|
+
s = add("theses", "theses posted by tracked traders")
|
|
253
|
+
s.add_argument("--sort", choices=["new", "popular"], default="new")
|
|
254
|
+
s.add_argument("--hours", type=int)
|
|
255
|
+
s.add_argument("--limit", type=int)
|
|
256
|
+
s = add("hl-traders", "Hyperliquid traders ranked by pnl or roi")
|
|
257
|
+
s.add_argument("--window", choices=["24h", "7d", "30d", "all"], default="30d")
|
|
258
|
+
s.add_argument("--sort", choices=["pnl", "roi"], default="pnl")
|
|
259
|
+
s.add_argument("--limit", type=int)
|
|
260
|
+
s = add("hl-trader", "one Hyperliquid trader")
|
|
261
|
+
s.add_argument("address")
|
|
262
|
+
s = add("hl-markets", "live Hyperliquid markets")
|
|
263
|
+
s.add_argument("--category")
|
|
264
|
+
s.add_argument("--limit", type=int)
|
|
265
|
+
s = add("hl-market", "copy.top's read of one Hyperliquid market")
|
|
266
|
+
s.add_argument("coin")
|
|
267
|
+
s = add("hl-calls", "analyst calls on one Hyperliquid market")
|
|
268
|
+
s.add_argument("coin")
|
|
269
|
+
return p
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def run(args: argparse.Namespace, client: Client) -> Tuple[Dict[str, Any], Render]:
|
|
273
|
+
c = args.cmd
|
|
274
|
+
if c == "hot":
|
|
275
|
+
return client.hot_coins(window=args.window, max_mcap_usd=args.max_mcap, limit=args.limit), _r_hot
|
|
276
|
+
if c in ("traders", "leaderboard"):
|
|
277
|
+
return client.traders(window=args.window, sort=args.sort, platform=args.platform, chain=args.chain,
|
|
278
|
+
fair_play="clean" if args.clean else None, limit=args.limit), _r_traders
|
|
279
|
+
if c == "trader":
|
|
280
|
+
return client.trader(args.handle), _r_trader
|
|
281
|
+
if c == "search":
|
|
282
|
+
return client.search(args.query), _r_search
|
|
283
|
+
if c == "coin":
|
|
284
|
+
return client.coin(args.chain, args.address), _r_coin
|
|
285
|
+
if c == "flow":
|
|
286
|
+
return client.money_flow(side=args.side, window=args.window, limit=args.limit), _r_flow
|
|
287
|
+
if c == "index":
|
|
288
|
+
return client.hot_index(window=args.window, chain=args.chain, limit=args.limit), _r_index
|
|
289
|
+
if c == "dexpaid":
|
|
290
|
+
return client.dex_paid(limit=args.limit), _r_dexpaid
|
|
291
|
+
if c == "trades":
|
|
292
|
+
return client.trades(side=args.side, min_usd=args.min_usd, limit=args.limit), _r_trades
|
|
293
|
+
if c == "alerts":
|
|
294
|
+
return client.alerts(since=args.since, kinds=args.kinds, min_top_traders=args.min_top_traders,
|
|
295
|
+
min_trade_usd=args.min_trade_usd, max_mcap_usd=args.max_mcap), _r_alerts
|
|
296
|
+
if c == "theses":
|
|
297
|
+
return client.theses(sort=args.sort, hours=args.hours, limit=args.limit), _r_theses
|
|
298
|
+
if c == "hl-traders":
|
|
299
|
+
return client.hl_traders(window=args.window, sort=args.sort, limit=args.limit), _r_hl_traders
|
|
300
|
+
if c == "hl-trader":
|
|
301
|
+
return client.hl_trader(args.address), _r_json_summary
|
|
302
|
+
if c == "hl-markets":
|
|
303
|
+
return client.hl_markets(category=args.category, limit=args.limit), _r_hl_markets
|
|
304
|
+
if c == "hl-market":
|
|
305
|
+
return client.hl_market(args.coin), _r_json_summary
|
|
306
|
+
if c == "hl-calls":
|
|
307
|
+
return client.hl_calls(args.coin), _r_hl_calls
|
|
308
|
+
raise SystemExit("unknown command %r" % c)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def main(argv: Optional[Sequence[str]] = None, client: Optional[Client] = None) -> int:
|
|
312
|
+
parser = build_parser()
|
|
313
|
+
args = parser.parse_args(argv)
|
|
314
|
+
if not args.cmd:
|
|
315
|
+
parser.print_help()
|
|
316
|
+
return 0
|
|
317
|
+
client = client or Client(api_key=args.key)
|
|
318
|
+
try:
|
|
319
|
+
if args.cmd == "alerts" and args.watch:
|
|
320
|
+
filters = dict(kinds=args.kinds, min_top_traders=args.min_top_traders,
|
|
321
|
+
min_trade_usd=args.min_trade_usd, max_mcap_usd=args.max_mcap)
|
|
322
|
+
for event in client.watch_alerts(since=args.since, **filters):
|
|
323
|
+
if args.json:
|
|
324
|
+
_out(json.dumps(event, ensure_ascii=False))
|
|
325
|
+
else:
|
|
326
|
+
_out(_r_alerts({"events": [event]}).splitlines()[-1])
|
|
327
|
+
return 0
|
|
328
|
+
data, render = run(args, client)
|
|
329
|
+
except KeyboardInterrupt:
|
|
330
|
+
return 130
|
|
331
|
+
except CopyTopError as e:
|
|
332
|
+
_out(e, file=sys.stderr)
|
|
333
|
+
return 1
|
|
334
|
+
if args.json:
|
|
335
|
+
_out(json.dumps(data, indent=2, ensure_ascii=False))
|
|
336
|
+
else:
|
|
337
|
+
_out(render(data))
|
|
338
|
+
_out("\n" + FOOTER)
|
|
339
|
+
return 0
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
if __name__ == "__main__": # pragma: no cover
|
|
343
|
+
raise SystemExit(main())
|
copytop/client.py
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
"""copy.top REST API client.
|
|
2
|
+
|
|
3
|
+
copy.top (https://copy.top) tracks what top traders buy and sell on fomo, pumpfun
|
|
4
|
+
and Hyperliquid, and lets people copy them. This client wraps the public, read-only
|
|
5
|
+
REST API at https://copy.top/v1. Nothing here places an order.
|
|
6
|
+
|
|
7
|
+
Figures are data, not advice.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import random
|
|
15
|
+
import time
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.parse
|
|
18
|
+
import urllib.request
|
|
19
|
+
from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Tuple, Union
|
|
20
|
+
|
|
21
|
+
from . import __version__
|
|
22
|
+
|
|
23
|
+
JSON = Dict[str, Any]
|
|
24
|
+
|
|
25
|
+
DEFAULT_BASE_URL = "https://copy.top/v1"
|
|
26
|
+
SITE_URL = "https://copy.top"
|
|
27
|
+
USER_AGENT = "copytop-python/%s (+https://copy.top)" % __version__
|
|
28
|
+
|
|
29
|
+
# A transport takes (url, headers, timeout) and returns (status, headers, body bytes).
|
|
30
|
+
# The default one uses urllib from the standard library. Tests pass a fake one.
|
|
31
|
+
Transport = Callable[[str, Mapping[str, str], float], Tuple[int, Mapping[str, str], bytes]]
|
|
32
|
+
|
|
33
|
+
RETRY_STATUSES = frozenset({429, 500, 502, 503, 504, 520, 521, 522, 524})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CopyTopError(Exception):
|
|
37
|
+
"""An error answered by the copy.top API (or a network error after all retries)."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, message: str, status: Optional[int] = None, url: Optional[str] = None):
|
|
40
|
+
super().__init__(message)
|
|
41
|
+
self.message = message
|
|
42
|
+
self.status = status
|
|
43
|
+
self.url = url
|
|
44
|
+
|
|
45
|
+
def __str__(self) -> str:
|
|
46
|
+
if self.status:
|
|
47
|
+
return "copy.top answered %s: %s" % (self.status, self.message)
|
|
48
|
+
return self.message
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class NotFoundError(CopyTopError):
|
|
52
|
+
"""404: no such trader, coin or market on copy.top."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class RateLimitError(CopyTopError):
|
|
56
|
+
"""429: too many calls. Without a key, about 20 calls a minute per IP
|
|
57
|
+
(about 6 a minute for search, trader and coin). A free key from
|
|
58
|
+
https://copy.top/account#api raises the limits."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class AuthError(CopyTopError):
|
|
62
|
+
"""401: the API key was refused."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class RedirectRefusedError(CopyTopError):
|
|
66
|
+
"""A redirect was refused: https to http would send the request (and the key) in clear text."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _origin(url: str) -> Tuple[str, str, Optional[int]]:
|
|
70
|
+
parts = urllib.parse.urlsplit(url)
|
|
71
|
+
scheme = parts.scheme.lower()
|
|
72
|
+
port = parts.port or {"https": 443, "http": 80}.get(scheme)
|
|
73
|
+
return scheme, (parts.hostname or "").lower(), port
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
77
|
+
"""urllib's redirect handler copies every header, Authorization included, to the new
|
|
78
|
+
location, whatever its host or scheme. This one refuses https -> http and drops the
|
|
79
|
+
Authorization header as soon as the scheme, host or port changes (for example
|
|
80
|
+
www.copy.top -> copy.top), so the key only ever goes to the origin it was given for."""
|
|
81
|
+
|
|
82
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[override]
|
|
83
|
+
newurl = urllib.parse.urljoin(req.full_url, newurl)
|
|
84
|
+
old, new = _origin(req.full_url), _origin(newurl)
|
|
85
|
+
if old[0] == "https" and new[0] != "https":
|
|
86
|
+
if fp is not None:
|
|
87
|
+
fp.close()
|
|
88
|
+
raise RedirectRefusedError("refused redirect from https to %s: %s" % (new[0] or "?", newurl), code, req.full_url)
|
|
89
|
+
new_req = super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
90
|
+
if new_req is not None and new != old:
|
|
91
|
+
for store in (new_req.headers, new_req.unredirected_hdrs):
|
|
92
|
+
for name in [k for k in store if k.lower() == "authorization"]:
|
|
93
|
+
del store[name]
|
|
94
|
+
return new_req
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_OPENER = urllib.request.build_opener(_SafeRedirectHandler)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _urllib_transport(url: str, headers: Mapping[str, str], timeout: float) -> Tuple[int, Mapping[str, str], bytes]:
|
|
101
|
+
req = urllib.request.Request(url, headers=dict(headers), method="GET")
|
|
102
|
+
try:
|
|
103
|
+
with _OPENER.open(req, timeout=timeout) as resp:
|
|
104
|
+
return resp.status, dict(resp.headers.items()), resp.read()
|
|
105
|
+
except urllib.error.HTTPError as e:
|
|
106
|
+
body = e.read() if hasattr(e, "read") else b""
|
|
107
|
+
return e.code, dict(e.headers.items()) if e.headers else {}, body
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def trader_url(handle: str) -> str:
|
|
111
|
+
"""The copy.top page of a fomo or pumpfun trader: https://copy.top/t/<handle>."""
|
|
112
|
+
return "%s/t/%s" % (SITE_URL, urllib.parse.quote(handle.lstrip("@"), safe=""))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def coin_url(chain: str, address: str) -> str:
|
|
116
|
+
"""The copy.top page of a coin: https://copy.top/token/<chain>/<address>."""
|
|
117
|
+
return "%s/token/%s/%s" % (SITE_URL, urllib.parse.quote(chain, safe=""), urllib.parse.quote(address, safe=""))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def hl_trader_url(address: str) -> str:
|
|
121
|
+
"""The copy.top page of a Hyperliquid trader: https://copy.top/t/hl/<address>."""
|
|
122
|
+
return "%s/t/hl/%s" % (SITE_URL, urllib.parse.quote(address.lower(), safe=""))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def hl_market_url(coin: str) -> str:
|
|
126
|
+
"""The copy.top page of a Hyperliquid market: https://copy.top/token/hyperliquid/<coin>."""
|
|
127
|
+
return "%s/token/hyperliquid/%s" % (SITE_URL, urllib.parse.quote(coin, safe=":"))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class Client:
|
|
131
|
+
"""Read-only client for the copy.top REST API (https://copy.top/v1).
|
|
132
|
+
|
|
133
|
+
>>> from copytop import Client
|
|
134
|
+
>>> ct = Client() # no key needed
|
|
135
|
+
>>> ct.hot_coins(window="1h", limit=5)["coins"][0]["symbol"]
|
|
136
|
+
|
|
137
|
+
Every method returns the decoded JSON answer as a dict. Errors raise
|
|
138
|
+
CopyTopError (NotFoundError, RateLimitError, AuthError). Calls answered
|
|
139
|
+
429 or 5xx are retried with backoff, honouring Retry-After.
|
|
140
|
+
|
|
141
|
+
api_key: optional, from https://copy.top/account#api. Defaults to the
|
|
142
|
+
COPYTOP_API_KEY environment variable. Sent as "Authorization: Bearer <key>".
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
def __init__(
|
|
146
|
+
self,
|
|
147
|
+
api_key: Optional[str] = None,
|
|
148
|
+
*,
|
|
149
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
150
|
+
timeout: float = 30.0,
|
|
151
|
+
max_retries: int = 3,
|
|
152
|
+
backoff: float = 2.0,
|
|
153
|
+
user_agent: Optional[str] = None,
|
|
154
|
+
transport: Optional[Transport] = None,
|
|
155
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
156
|
+
) -> None:
|
|
157
|
+
if api_key is None:
|
|
158
|
+
api_key = os.environ.get("COPYTOP_API_KEY") or None
|
|
159
|
+
self.api_key = api_key
|
|
160
|
+
self.base_url = base_url.rstrip("/")
|
|
161
|
+
self.timeout = timeout
|
|
162
|
+
self.max_retries = max(0, int(max_retries))
|
|
163
|
+
self.backoff = backoff
|
|
164
|
+
self.user_agent = user_agent or USER_AGENT
|
|
165
|
+
self._transport = transport or _urllib_transport
|
|
166
|
+
self._sleep = sleep
|
|
167
|
+
|
|
168
|
+
def __repr__(self) -> str:
|
|
169
|
+
return "Client(base_url=%r, api_key=%s)" % (self.base_url, "set" if self.api_key else "none")
|
|
170
|
+
|
|
171
|
+
# ------------------------------------------------------------------ core
|
|
172
|
+
|
|
173
|
+
def get(self, path: str, params: Optional[Mapping[str, Any]] = None) -> JSON:
|
|
174
|
+
"""GET any route of https://copy.top/v1 and return the JSON answer.
|
|
175
|
+
|
|
176
|
+
None values are dropped, booleans become true/false, lists are joined with commas.
|
|
177
|
+
"""
|
|
178
|
+
url = self.base_url + "/" + path.lstrip("/")
|
|
179
|
+
query = _encode_params(params or {})
|
|
180
|
+
if query:
|
|
181
|
+
url += "?" + query
|
|
182
|
+
headers = {"Accept": "application/json", "User-Agent": self.user_agent}
|
|
183
|
+
if self.api_key:
|
|
184
|
+
headers["Authorization"] = "Bearer " + self.api_key
|
|
185
|
+
|
|
186
|
+
attempt = 0
|
|
187
|
+
while True:
|
|
188
|
+
try:
|
|
189
|
+
status, resp_headers, body = self._transport(url, headers, self.timeout)
|
|
190
|
+
except (urllib.error.URLError, OSError, TimeoutError) as e:
|
|
191
|
+
if attempt < self.max_retries:
|
|
192
|
+
self._sleep(self._delay(attempt, None))
|
|
193
|
+
attempt += 1
|
|
194
|
+
continue
|
|
195
|
+
raise CopyTopError("network error: %s" % e, None, url) from e
|
|
196
|
+
|
|
197
|
+
if status in RETRY_STATUSES and attempt < self.max_retries:
|
|
198
|
+
self._sleep(self._delay(attempt, _header(resp_headers, "retry-after")))
|
|
199
|
+
attempt += 1
|
|
200
|
+
continue
|
|
201
|
+
|
|
202
|
+
data = _decode(body)
|
|
203
|
+
if 200 <= status < 300:
|
|
204
|
+
if not isinstance(data, dict):
|
|
205
|
+
raise CopyTopError("unexpected answer (not a JSON object)", status, url)
|
|
206
|
+
return data
|
|
207
|
+
|
|
208
|
+
message = data.get("error") if isinstance(data, dict) else None
|
|
209
|
+
if not message:
|
|
210
|
+
message = (body[:200].decode("utf-8", "replace").strip() or "http error") if body else "http error"
|
|
211
|
+
cls = {404: NotFoundError, 429: RateLimitError, 401: AuthError, 403: AuthError}.get(status, CopyTopError)
|
|
212
|
+
raise cls(str(message), status, url)
|
|
213
|
+
|
|
214
|
+
def _delay(self, attempt: int, retry_after: Optional[str]) -> float:
|
|
215
|
+
if retry_after:
|
|
216
|
+
try:
|
|
217
|
+
return min(max(float(retry_after), 0.0), 120.0)
|
|
218
|
+
except ValueError:
|
|
219
|
+
pass
|
|
220
|
+
return self.backoff * (2 ** attempt) + random.uniform(0, 0.5)
|
|
221
|
+
|
|
222
|
+
# --------------------------------------------------------- fomo, pumpfun
|
|
223
|
+
|
|
224
|
+
def traders(
|
|
225
|
+
self,
|
|
226
|
+
*,
|
|
227
|
+
window: str = "30d",
|
|
228
|
+
sort: str = "total",
|
|
229
|
+
chain: Optional[str] = None,
|
|
230
|
+
platform: Optional[str] = None,
|
|
231
|
+
fair_play: Optional[str] = None,
|
|
232
|
+
limit: Optional[int] = None,
|
|
233
|
+
) -> JSON:
|
|
234
|
+
"""Trader leaderboard (fomo and pumpfun), like https://copy.top/traders.
|
|
235
|
+
|
|
236
|
+
window: 1d, 7d or 30d. sort: total, realized, roi, winrate or copiers.
|
|
237
|
+
chain: robinhood, solana, base, bnb, eth or arc. platform: fomo or pumpfun.
|
|
238
|
+
fair_play: clean or clean_or_watch. limit: 1 to 20 (default 10).
|
|
239
|
+
Returns {"window", "sort", "traders": [...]}.
|
|
240
|
+
"""
|
|
241
|
+
return self.get("traders", {"window": window, "sort": sort, "chain": chain, "platform": platform,
|
|
242
|
+
"fair_play": fair_play, "limit": limit})
|
|
243
|
+
|
|
244
|
+
def trader(self, handle: str) -> JSON:
|
|
245
|
+
"""One trader's profile: pnl 30d, roi, win rate, fair play, open positions, latest trades.
|
|
246
|
+
|
|
247
|
+
handle as search or another call gave it (a handle starting with pf_ is a pumpfun account).
|
|
248
|
+
Returns {"as_of", "trader", "open_positions", "latest_trades", ...}.
|
|
249
|
+
"""
|
|
250
|
+
return self.get("traders/" + _seg(handle.lstrip("@")))
|
|
251
|
+
|
|
252
|
+
def search(self, query: str) -> JSON:
|
|
253
|
+
"""Find traders and coins by name, @handle, $ticker or address (2 to 80 characters).
|
|
254
|
+
|
|
255
|
+
Returns {"traders": [...], "coins": [...]}.
|
|
256
|
+
"""
|
|
257
|
+
return self.get("search", {"query": query})
|
|
258
|
+
|
|
259
|
+
def hot_coins(self, *, window: str = "24h", max_mcap_usd: Optional[float] = None,
|
|
260
|
+
limit: Optional[int] = None) -> JSON:
|
|
261
|
+
"""The signal feed: coins tracked traders are buying now.
|
|
262
|
+
|
|
263
|
+
window: 1h or 24h. max_mcap_usd: optional ceiling. limit: 1 to 15.
|
|
264
|
+
Returns {"window", "at", "coins": [...]}.
|
|
265
|
+
"""
|
|
266
|
+
return self.get("coins/hot", {"window": window, "max_mcap_usd": max_mcap_usd, "limit": limit})
|
|
267
|
+
|
|
268
|
+
def hot_index(self, *, window: Optional[str] = None, chain: Optional[str] = None,
|
|
269
|
+
limit: Optional[int] = None) -> JSON:
|
|
270
|
+
"""copy.top's hot index: coins ranked 0 to 100 by attention (buyers, callers, x activity).
|
|
271
|
+
|
|
272
|
+
window: 1h, 6h or 24h. chain: optional. limit: 1 to 10.
|
|
273
|
+
Returns {"window", "total", "at", "coins": [...]}.
|
|
274
|
+
"""
|
|
275
|
+
return self.get("coins/index", {"window": window, "chain": chain, "limit": limit})
|
|
276
|
+
|
|
277
|
+
def money_flow(self, *, side: str = "buy", window: str = "24h", limit: Optional[int] = None) -> JSON:
|
|
278
|
+
"""Coins ranked by dollars tracked traders bought (side buy) or sold (side sell).
|
|
279
|
+
|
|
280
|
+
window: 1h, 6h, 24h or 7d. limit: 1 to 10.
|
|
281
|
+
Returns {"side", "window", "at", "coins": [...]}.
|
|
282
|
+
"""
|
|
283
|
+
return self.get("coins/flow", {"side": side, "window": window, "limit": limit})
|
|
284
|
+
|
|
285
|
+
def dex_paid(self, *, limit: Optional[int] = None) -> JSON:
|
|
286
|
+
"""Coins whose team paid for a dexscreener profile in the last 24 h. limit: 1 to 12."""
|
|
287
|
+
return self.get("coins/dex-paid", {"limit": limit})
|
|
288
|
+
|
|
289
|
+
def coin(self, chain: str, address: str) -> JSON:
|
|
290
|
+
"""One coin: price, market cap, moves, liquidity, which tracked traders hold or sold it, theses.
|
|
291
|
+
|
|
292
|
+
chain: robinhood, solana, base, bnb, eth or arc. address: the token address.
|
|
293
|
+
Returns {"token", "leaders", "theses", ...}.
|
|
294
|
+
"""
|
|
295
|
+
return self.get("coins/%s/%s" % (_seg(chain), _seg(address)))
|
|
296
|
+
|
|
297
|
+
def trades(self, *, since: Optional[str] = None, side: Optional[str] = None,
|
|
298
|
+
min_usd: Optional[float] = None, limit: Optional[int] = None) -> JSON:
|
|
299
|
+
"""The live tape: latest buys and sells by tracked traders, newest first.
|
|
300
|
+
|
|
301
|
+
since: ISO time or the cursor of a previous call. side: buy or sell. limit: 1 to 30.
|
|
302
|
+
The tape keeps the latest 30 trades: poll at least once a minute to miss none.
|
|
303
|
+
Returns {"cursor", "trades": [...]}.
|
|
304
|
+
"""
|
|
305
|
+
return self.get("trades", {"since": since, "side": side, "min_usd": min_usd, "limit": limit})
|
|
306
|
+
|
|
307
|
+
def alerts(
|
|
308
|
+
self,
|
|
309
|
+
*,
|
|
310
|
+
since: Optional[str] = None,
|
|
311
|
+
min_top_traders: Optional[int] = None,
|
|
312
|
+
min_trade_usd: Optional[float] = None,
|
|
313
|
+
max_mcap_usd: Optional[float] = None,
|
|
314
|
+
kinds: Union[None, str, Iterable[str]] = None,
|
|
315
|
+
limit: Optional[int] = None,
|
|
316
|
+
) -> JSON:
|
|
317
|
+
"""Events since a cursor: confluence (several top traders on one coin), big_trade, thesis.
|
|
318
|
+
|
|
319
|
+
Pass the "cursor" of the previous answer back as since. Without since: the last 15 minutes.
|
|
320
|
+
min_top_traders: 1 to 50 (default 3). min_trade_usd: default 5000.
|
|
321
|
+
kinds: list or comma separated string of confluence, big_trade, thesis. limit: 1 to 40.
|
|
322
|
+
Returns {"since", "cursor", "thresholds", "events": [...]}.
|
|
323
|
+
"""
|
|
324
|
+
return self.get("alerts", {"since": since, "min_top_traders": min_top_traders,
|
|
325
|
+
"min_trade_usd": min_trade_usd, "max_mcap_usd": max_mcap_usd,
|
|
326
|
+
"kinds": kinds, "limit": limit})
|
|
327
|
+
|
|
328
|
+
def watch_alerts(self, *, interval: float = 60.0, since: Optional[str] = None,
|
|
329
|
+
**filters: Any) -> Iterator[JSON]:
|
|
330
|
+
"""Yield new alert events forever, polling alerts() every `interval` seconds
|
|
331
|
+
and passing the cursor back as since. Once a minute is plenty.
|
|
332
|
+
|
|
333
|
+
>>> for event in Client().watch_alerts(kinds=["confluence"]):
|
|
334
|
+
... print(event["symbol"], event["url"])
|
|
335
|
+
"""
|
|
336
|
+
cursor = since
|
|
337
|
+
while True:
|
|
338
|
+
answer = self.alerts(since=cursor, **filters)
|
|
339
|
+
for event in answer.get("events") or []:
|
|
340
|
+
yield event
|
|
341
|
+
cursor = answer.get("cursor") or cursor
|
|
342
|
+
self._sleep(interval)
|
|
343
|
+
|
|
344
|
+
def theses(self, *, sort: str = "new", hours: Optional[int] = None, limit: Optional[int] = None) -> JSON:
|
|
345
|
+
"""Theses (a trader's written reason for holding a coin) posted by tracked traders.
|
|
346
|
+
|
|
347
|
+
sort: new or popular. hours: 1 to 24. limit: 1 to 10.
|
|
348
|
+
Returns {"theses": [...]}.
|
|
349
|
+
"""
|
|
350
|
+
return self.get("theses", {"sort": sort, "hours": hours, "limit": limit})
|
|
351
|
+
|
|
352
|
+
# ------------------------------------------------------------ Hyperliquid
|
|
353
|
+
|
|
354
|
+
def hl_traders(self, *, window: str = "30d", sort: str = "pnl", limit: Optional[int] = None) -> JSON:
|
|
355
|
+
"""Hyperliquid perps traders tracked by copy.top, ranked by pnl or roi.
|
|
356
|
+
|
|
357
|
+
window: 24h, 7d, 30d or all. sort: pnl or roi. limit: 1 to 20.
|
|
358
|
+
Returns {"window", "sort", "total", "updatedAt", "traders": [...]}.
|
|
359
|
+
"""
|
|
360
|
+
return self.get("hyperliquid/traders", {"window": window, "sort": sort, "limit": limit})
|
|
361
|
+
|
|
362
|
+
def hl_trader(self, address: str) -> JSON:
|
|
363
|
+
"""One Hyperliquid trader by address (0x + 40 hex): metrics, pnl per window, positions, fills."""
|
|
364
|
+
return self.get("hyperliquid/traders/" + _seg(address))
|
|
365
|
+
|
|
366
|
+
def hl_markets(self, *, category: Optional[str] = None, limit: Optional[int] = None) -> JSON:
|
|
367
|
+
"""Live Hyperliquid markets (crypto perps and hip-3: stocks, indices, commodities, fx),
|
|
368
|
+
sorted by 24h volume. category: e.g. crypto, stocks, indices. limit: 1 to 50.
|
|
369
|
+
Returns {"total", "categories", "markets": [...]}.
|
|
370
|
+
"""
|
|
371
|
+
return self.get("hyperliquid/markets", {"category": category, "limit": limit})
|
|
372
|
+
|
|
373
|
+
def hl_market(self, coin: str) -> JSON:
|
|
374
|
+
"""copy.top's read of one Hyperliquid market (BTC, ETH, SOL...): technicals, funding,
|
|
375
|
+
open interest, what the top 300 traders hold, liquidations."""
|
|
376
|
+
return self.get("hyperliquid/markets/" + _seg(coin))
|
|
377
|
+
|
|
378
|
+
def hl_calls(self, coin: str) -> JSON:
|
|
379
|
+
"""X analysts ranked by the track record of their calls on one Hyperliquid market, and their recent calls."""
|
|
380
|
+
return self.get("hyperliquid/markets/%s/calls" % _seg(coin))
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
# ---------------------------------------------------------------- helpers
|
|
384
|
+
|
|
385
|
+
def _seg(value: str) -> str:
|
|
386
|
+
value = str(value).strip()
|
|
387
|
+
if not value:
|
|
388
|
+
raise ValueError("empty path parameter")
|
|
389
|
+
return urllib.parse.quote(value, safe=":")
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _encode_params(params: Mapping[str, Any]) -> str:
|
|
393
|
+
pairs: List[Tuple[str, str]] = []
|
|
394
|
+
for key, value in params.items():
|
|
395
|
+
if value is None:
|
|
396
|
+
continue
|
|
397
|
+
if isinstance(value, bool):
|
|
398
|
+
value = "true" if value else "false"
|
|
399
|
+
elif isinstance(value, (list, tuple, set, frozenset)):
|
|
400
|
+
value = ",".join(str(v) for v in value)
|
|
401
|
+
elif isinstance(value, float) and value.is_integer():
|
|
402
|
+
value = int(value)
|
|
403
|
+
pairs.append((key, str(value)))
|
|
404
|
+
return urllib.parse.urlencode(pairs)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _header(headers: Mapping[str, str], name: str) -> Optional[str]:
|
|
408
|
+
for k, v in (headers or {}).items():
|
|
409
|
+
if k.lower() == name:
|
|
410
|
+
return v
|
|
411
|
+
return None
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _decode(body: bytes) -> Any:
|
|
415
|
+
if not body:
|
|
416
|
+
return None
|
|
417
|
+
try:
|
|
418
|
+
return json.loads(body.decode("utf-8"))
|
|
419
|
+
except (ValueError, UnicodeDecodeError):
|
|
420
|
+
return None
|
copytop/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: copytop
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for copy.top (https://copy.top): what top fomo, pumpfun and Hyperliquid traders buy and sell. Read-only, no key needed.
|
|
5
|
+
Project-URL: Homepage, https://copy.top
|
|
6
|
+
Project-URL: Documentation, https://copy.top/agents
|
|
7
|
+
Project-URL: API, https://copy.top/v1/openapi.json
|
|
8
|
+
Project-URL: MCP server, https://copy.top/mcp
|
|
9
|
+
Project-URL: Developers, https://copy.top/developers
|
|
10
|
+
Author-email: "copy.top" <ana@copy.top>
|
|
11
|
+
Maintainer-email: "copy.top" <ana@copy.top>
|
|
12
|
+
License-Expression: MIT
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Keywords: api client,copy trading,copy.top,copytop,crypto,fomo,hyperliquid,leaderboard,mcp,memecoins,pump.fun,pumpfun,smart money,solana,top traders,trading signals,whale tracker
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
27
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
28
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
29
|
+
Classifier: Typing :: Typed
|
|
30
|
+
Requires-Python: >=3.9
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# copytop: Python client for copy.top
|
|
34
|
+
|
|
35
|
+
**[copy.top](https://copy.top)** tracks what top traders buy and sell on fomo, pumpfun and Hyperliquid, and lets people copy them. This package is the official Python client for the copy.top API: the trader leaderboard, a trader's profile, the coins top traders are buying now, money flow, live trades, alerts and Hyperliquid markets, in a few lines of Python.
|
|
36
|
+
|
|
37
|
+
- Read-only: nothing here places an order.
|
|
38
|
+
- No key needed. Pure Python, no dependency, Python 3.9 or later.
|
|
39
|
+
- Every call returns the JSON answer of [https://copy.top/v1](https://copy.top/v1/openapi.json) as a dict.
|
|
40
|
+
|
|
41
|
+
Site: [https://copy.top](https://copy.top) | Docs for developers and AI agents: [https://copy.top/agents](https://copy.top/agents) | OpenAPI: [https://copy.top/v1/openapi.json](https://copy.top/v1/openapi.json)
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
pip install copytop
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Examples
|
|
50
|
+
|
|
51
|
+
**1. Coins top traders are buying right now**
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from copytop import Client, coin_url
|
|
55
|
+
|
|
56
|
+
ct = Client()
|
|
57
|
+
for c in ct.hot_coins(window="1h", limit=5)["coins"]:
|
|
58
|
+
print(c["symbol"], c["topTraders"], "top traders,", c["boughtUsd"], "usd bought", coin_url(c["chain"], c["token"]))
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
**2. The 7 day leaderboard of pumpfun traders, clean fair play only**
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
for t in ct.traders(window="7d", platform="pumpfun", fair_play="clean", limit=10)["traders"]:
|
|
65
|
+
print(t["handle"], t["pnl"], t["roi"], t["url"])
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**3. Look up a trader or a coin by name, $ticker or address**
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
found = ct.search("$BONK")
|
|
72
|
+
profile = ct.trader(found["traders"][0]["handle"])
|
|
73
|
+
print(profile["trader"]["pnl"], profile["open_positions"][:3])
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
**4. An alert bot in five lines** (several top traders on one coin, or a big trade)
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
for event in ct.watch_alerts(kinds=["confluence", "big_trade"], min_top_traders=3, interval=60):
|
|
80
|
+
print(event["kind"], event.get("symbol"), event["url"])
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**5. Hyperliquid: top perps traders and markets**
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
whales = ct.hl_traders(window="30d", sort="pnl", limit=5)["traders"]
|
|
87
|
+
stocks = ct.hl_markets(category="stocks", limit=10)["markets"]
|
|
88
|
+
btc = ct.hl_market("BTC") # technicals, funding, open interest, what top traders hold
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Command line
|
|
92
|
+
|
|
93
|
+
The package installs a `copytop` command (also `python -m copytop`):
|
|
94
|
+
|
|
95
|
+
```
|
|
96
|
+
copytop hot --window 1h
|
|
97
|
+
copytop traders --window 7d --platform pumpfun --clean
|
|
98
|
+
copytop trader <handle>
|
|
99
|
+
copytop coin solana <address>
|
|
100
|
+
copytop alerts --watch --kinds confluence
|
|
101
|
+
copytop hl-markets --category stocks
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Add `--json` to any command for raw JSON.
|
|
105
|
+
|
|
106
|
+
## Methods
|
|
107
|
+
|
|
108
|
+
| method | route | what it returns |
|
|
109
|
+
|---|---|---|
|
|
110
|
+
| `traders(window, sort, chain, platform, fair_play, limit)` | `GET /traders` | trader leaderboard (fomo and pumpfun), like [copy.top/traders](https://copy.top/traders) |
|
|
111
|
+
| `trader(handle)` | `GET /traders/{handle}` | one trader: pnl 30d, roi, win rate, fair play, positions, latest trades |
|
|
112
|
+
| `search(query)` | `GET /search` | traders and coins by name, @handle, $ticker or address |
|
|
113
|
+
| `hot_coins(window, max_mcap_usd, limit)` | `GET /coins/hot` | coins tracked traders are buying now |
|
|
114
|
+
| `hot_index(window, chain, limit)` | `GET /coins/index` | coins ranked 0 to 100 by attention |
|
|
115
|
+
| `money_flow(side, window, limit)` | `GET /coins/flow` | coins ranked by dollars bought or sold |
|
|
116
|
+
| `dex_paid(limit)` | `GET /coins/dex-paid` | coins whose team paid for a dexscreener profile in the last 24 h |
|
|
117
|
+
| `coin(chain, address)` | `GET /coins/{chain}/{address}` | one coin: price, market cap, which tracked traders hold or sold it |
|
|
118
|
+
| `trades(since, side, min_usd, limit)` | `GET /trades` | the live tape of buys and sells, with a cursor |
|
|
119
|
+
| `alerts(since, min_top_traders, min_trade_usd, max_mcap_usd, kinds, limit)` | `GET /alerts` | confluence, big trade and thesis events since a cursor |
|
|
120
|
+
| `watch_alerts(interval, **filters)` | `GET /alerts` in a loop | a generator of new events, cursor handled for you |
|
|
121
|
+
| `theses(sort, hours, limit)` | `GET /theses` | theses posted by tracked traders |
|
|
122
|
+
| `hl_traders(window, sort, limit)` | `GET /hyperliquid/traders` | Hyperliquid traders ranked by pnl or roi |
|
|
123
|
+
| `hl_trader(address)` | `GET /hyperliquid/traders/{address}` | one Hyperliquid trader: metrics, positions, fills |
|
|
124
|
+
| `hl_markets(category, limit)` | `GET /hyperliquid/markets` | live Hyperliquid markets (crypto, stocks, indices, fx) |
|
|
125
|
+
| `hl_market(coin)` | `GET /hyperliquid/markets/{coin}` | copy.top's read of one Hyperliquid market |
|
|
126
|
+
| `hl_calls(coin)` | `GET /hyperliquid/markets/{coin}/calls` | analyst calls on one Hyperliquid market and their track record |
|
|
127
|
+
|
|
128
|
+
Page links: `trader_url(handle)`, `coin_url(chain, address)`, `hl_trader_url(address)` and `hl_market_url(coin)` give the matching page on copy.top.
|
|
129
|
+
|
|
130
|
+
Chains: `solana`, `base`, `bnb`, `eth`, `robinhood`, `arc`. A handle starting with `pf_` is a pumpfun account; the others are fomo traders.
|
|
131
|
+
|
|
132
|
+
## Limits, API key and errors
|
|
133
|
+
|
|
134
|
+
The API is open without a key, at about 20 calls a minute per IP (about 6 a minute for search, trader and coin). A free key from [https://copy.top/account#api](https://copy.top/account#api) raises the limits:
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
ct = Client(api_key="...") # or set COPYTOP_API_KEY
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Answers 429 and 5xx are retried with backoff (`max_retries=3`, honours `Retry-After`). Errors raise `copytop.CopyTopError`, with `NotFoundError` (404), `RateLimitError` (429) and `AuthError` (401) as subclasses.
|
|
141
|
+
|
|
142
|
+
## Also from copy.top
|
|
143
|
+
|
|
144
|
+
- MCP server for AI agents (Claude, ChatGPT, Cursor): `https://copy.top/mcp`, see [https://copy.top/agents](https://copy.top/agents)
|
|
145
|
+
- npm CLI: `npx copytop hot`
|
|
146
|
+
- Web app: [https://copy.top](https://copy.top)
|
|
147
|
+
|
|
148
|
+
## About
|
|
149
|
+
|
|
150
|
+
copy.top is independent and is not affiliated with fomo, pump.fun or Hyperliquid. Figures are data, not advice. Trading crypto is risky and past performance does not predict results.
|
|
151
|
+
|
|
152
|
+
Contact: ana@copy.top. License: MIT.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
copytop/__init__.py,sha256=bWT309MVTavB7_73xTIXJ1gaf9uvb2xfp6001VKcdQ0,785
|
|
2
|
+
copytop/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
|
|
3
|
+
copytop/cli.py,sha256=bctis975849ctc9-xuOcs5gEAGD1kP-AOCQypbp46jg,15986
|
|
4
|
+
copytop/client.py,sha256=lU27S61_cQMZOl74YeHagCywZzWoLLCoX7csjlckWeE,17894
|
|
5
|
+
copytop/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
copytop-0.1.0.dist-info/METADATA,sha256=dMz_3_XRcxxSodrYw_caZvCjYsUHwDWfUtMgzrOwD5k,7417
|
|
7
|
+
copytop-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
copytop-0.1.0.dist-info/entry_points.txt,sha256=D6KHzjy_Vh47dtIXK73Jrrvsom2ksh_AruGyjKMXI80,45
|
|
9
|
+
copytop-0.1.0.dist-info/licenses/LICENSE,sha256=Ic55t9XBAR7-ztZBb-IqLj4nm-Y4Gxd4Rj-epLT2cBY,1065
|
|
10
|
+
copytop-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 copy.top
|
|
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.
|