copytop 0.1.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 21d91762ed2b5d5a03d46e0e521e024f385de2b6a3674c9b9c94938af94d3d88
4
+ data.tar.gz: ceba560056e50172668957ccf9bc0ea6d2bdf378ab2bbf207fb484ab43e43d1f
5
+ SHA512:
6
+ metadata.gz: ca3e0926564bdc8ae8b69206d9d20552d8a3946a57dddfd2f11649ce587eb86a041dad8f6575a1808af6e8d6e43db3d1290f5866028559343fc34026609151ed
7
+ data.tar.gz: 30272871cf206c2138fe0361d8910f03d5c386b7eb4a701aa6d3fca2475dc444faf221160918cd25eb694e117d4969a59ffdacb6e3aa8ac7e522b7752fa6bf62
data/LICENSE ADDED
@@ -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.
data/README.md ADDED
@@ -0,0 +1,142 @@
1
+ # copytop: Ruby client for copy.top
2
+
3
+ **[copy.top](https://copy.top)** tracks what top traders buy and sell on fomo, pumpfun and Hyperliquid, and lets people copy them. This gem is the official Ruby 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 Ruby.
4
+
5
+ - Read-only: nothing here places an order.
6
+ - No key needed. Standard library only (Net::HTTP), no dependency, Ruby 2.6 or later.
7
+ - All 16 routes of [https://copy.top/v1](https://copy.top/v1/openapi.json), typed errors, retries that honour `Retry-After`.
8
+
9
+ 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)
10
+
11
+ ## Install (coming soon)
12
+
13
+ **Not yet available:** `copytop` is not published on RubyGems yet, so the command below does not work today. It will once the package is out.
14
+
15
+ ```
16
+ gem install copytop
17
+ ```
18
+
19
+ or in a Gemfile: `gem "copytop"` (same: not yet available).
20
+
21
+ ## Examples
22
+
23
+ **1. Coins top traders are buying right now**
24
+
25
+ ```ruby
26
+ require "copytop"
27
+
28
+ ct = Copytop::Client.new
29
+ ct.hot_coins(window: "1h", limit: 5)["coins"].each do |c|
30
+ puts "#{c['symbol']} #{c['topTraders']} top traders, #{c['boughtUsd']} usd bought #{Copytop.coin_url(c['chain'], c['token'])}"
31
+ end
32
+ ```
33
+
34
+ **2. The 7 day leaderboard of pumpfun traders, clean fair play only**
35
+
36
+ ```ruby
37
+ ct.traders(window: "7d", platform: "pumpfun", fair_play: "clean", limit: 10)["traders"].each do |t|
38
+ puts [t["handle"], t["pnl"], t["roi"], t["url"]].join(" ")
39
+ end
40
+ ```
41
+
42
+ **3. Look up a trader or a coin by name, $ticker or address**
43
+
44
+ ```ruby
45
+ found = ct.search("$BONK")
46
+ profile = ct.trader(found["traders"][0]["handle"])
47
+ p profile["trader"]["pnl"], profile["open_positions"].first(3)
48
+ ```
49
+
50
+ **4. An alert bot** (several top traders on one coin, or a big trade)
51
+
52
+ ```ruby
53
+ ct.watch_alerts(kinds: %w[confluence big_trade], min_top_traders: 3) do |event|
54
+ puts "#{event['kind']} #{event['symbol']} #{event['url']}"
55
+ end
56
+ ```
57
+
58
+ `watch_alerts` polls once a minute, passes the cursor of each answer back as `since`, yields the new events oldest first, and keeps going through 429 and 5xx answers (`on_error:` sees them). `break` out of the block to stop; without a block it returns an Enumerator. `on_cursor:` gives you the cursor to save and pass back as `since:` after a restart.
59
+
60
+ **5. Hyperliquid: top perps traders and markets**
61
+
62
+ ```ruby
63
+ whales = ct.hl_traders(window: "30d", sort: "pnl", limit: 5)["traders"]
64
+ stocks = ct.hl_markets(category: "stocks", limit: 10)["markets"]
65
+ btc = ct.hl_market("BTC") # technicals, funding, open interest, what top traders hold
66
+ ```
67
+
68
+ ## Methods
69
+
70
+ Every method returns the decoded JSON answer as a Hash. Keyword arguments are optional; a nil one is left to the server default.
71
+
72
+ | method | route | what it returns |
73
+ |---|---|---|
74
+ | `traders(window:, sort:, chain:, platform:, fair_play:, limit:)` | `GET /traders` | trader leaderboard (fomo and pumpfun), like [copy.top/traders](https://copy.top/traders) |
75
+ | `trader(handle)` | `GET /traders/{handle}` | one trader: pnl 30d, roi, win rate, fair play, positions, latest trades |
76
+ | `search(query)` | `GET /search` | traders and coins by name, @handle, $ticker or address |
77
+ | `hot_coins(window:, max_mcap_usd:, limit:)` | `GET /coins/hot` | coins tracked traders are buying now |
78
+ | `hot_index(window:, chain:, limit:)` | `GET /coins/index` | coins ranked 0 to 100 by attention |
79
+ | `money_flow(side:, window:, limit:)` | `GET /coins/flow` | coins ranked by dollars bought or sold |
80
+ | `dex_paid(limit:)` | `GET /coins/dex-paid` | coins whose team paid for a dexscreener profile in the last 24 h |
81
+ | `coin(chain, address)` | `GET /coins/{chain}/{address}` | one coin: price, market cap, which tracked traders hold or sold it |
82
+ | `trades(since:, side:, min_usd:, limit:)` | `GET /trades` | the live tape of buys and sells, with a cursor |
83
+ | `alerts(since:, min_top_traders:, min_trade_usd:, max_mcap_usd:, kinds:, limit:)` | `GET /alerts` | confluence, big trade and thesis events since a cursor |
84
+ | `watch_alerts(interval:, since:, on_cursor:, on_error:, **filters)` | `GET /alerts` in a loop | yields new events, cursor handled for you |
85
+ | `theses(sort:, hours:, limit:)` | `GET /theses` | theses posted by tracked traders |
86
+ | `hl_traders(window:, sort:, limit:)` | `GET /hyperliquid/traders` | Hyperliquid traders ranked by pnl or roi |
87
+ | `hl_trader(address)` | `GET /hyperliquid/traders/{address}` | one Hyperliquid trader: metrics, positions, fills |
88
+ | `hl_markets(category:, limit:)` | `GET /hyperliquid/markets` | live Hyperliquid markets (crypto, stocks, indices, fx) |
89
+ | `hl_market(coin)` | `GET /hyperliquid/markets/{coin}` | copy.top's read of one Hyperliquid market |
90
+ | `hl_calls(coin)` | `GET /hyperliquid/markets/{coin}/calls` | analyst calls on one Hyperliquid market and their track record |
91
+ | `get(path, params)` | any route | for routes or parameters this gem does not model yet |
92
+
93
+ Page links: `Copytop.trader_url(handle)`, `Copytop.coin_url(chain, address)`, `Copytop.hl_trader_url(address)` and `Copytop.hl_market_url(coin)` give the matching page on copy.top.
94
+
95
+ Chains: `solana`, `base`, `bnb`, `eth`, `robinhood`, `arc`. A handle starting with `pf_` is a pumpfun account; the others are fomo traders.
96
+
97
+ ## Options, limits, API key and errors
98
+
99
+ ```ruby
100
+ ct = Copytop::Client.new(
101
+ api_key: "...", # optional; default: the COPYTOP_API_KEY environment variable
102
+ timeout: 45, # seconds; some routes take up to 30 s on a cold cache
103
+ max_retries: 3,
104
+ backoff: 1.0 # seconds, doubled on each retry
105
+ )
106
+ ```
107
+
108
+ 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. It is sent as `Authorization: Bearer <key>`.
109
+
110
+ Answers 429 and 5xx, and network errors, are retried with exponential backoff, honouring `Retry-After`. Then every error is a `Copytop::Error`:
111
+
112
+ | error | when |
113
+ |---|---|
114
+ | `Copytop::NotFoundError` | 404: no such trader, coin or market |
115
+ | `Copytop::RateLimitError` | 429 after all retries (`e.retry_after` in seconds) |
116
+ | `Copytop::AuthError` | 401 or 403: the API key was refused |
117
+ | `Copytop::BadRequestError` | 400: a parameter was refused |
118
+ | `Copytop::ServerError` | 5xx after all retries |
119
+ | `Copytop::NetworkError` | the API could not be reached |
120
+
121
+ `Copytop::APIError`, the parent of the first five, carries `e.status`, `e.api_message` and `e.url`. `e.temporary?` is true for 429, 5xx and network errors. An empty handle, address or query raises `ArgumentError` before any call.
122
+
123
+ `transport:` takes any object with `call(url, headers, timeout)` returning a `Copytop::Response` (status, headers, body), to plug in another HTTP library or a cache. The default is `Copytop::NetHTTPTransport`.
124
+
125
+ ## Tests
126
+
127
+ ```
128
+ rake test # offline, against a fake transport
129
+ rake live # one call per route on https://copy.top/v1, 4 s apart
130
+ ```
131
+
132
+ ## Also from copy.top
133
+
134
+ - MCP server for AI agents (Claude, ChatGPT, Cursor): `https://copy.top/mcp`, see [https://copy.top/agents](https://copy.top/agents)
135
+ - npm CLI: `npx copytop hot`
136
+ - Web app: [https://copy.top](https://copy.top)
137
+
138
+ ## About
139
+
140
+ 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.
141
+
142
+ Contact: ana@copy.top. License: MIT.
@@ -0,0 +1,418 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+ require "uri"
6
+
7
+ module Copytop
8
+ DEFAULT_BASE_URL = "https://copy.top/v1"
9
+ SITE_URL = "https://copy.top"
10
+
11
+ # Read-only client for the copy.top REST API (https://copy.top/v1).
12
+ #
13
+ # ct = Copytop::Client.new # no key needed
14
+ # ct.traders(window: "7d", platform: "pumpfun", limit: 10)["traders"]
15
+ #
16
+ # Every method returns the decoded JSON answer as a Hash. A nil argument is
17
+ # left to the server default. Answers 429 and 5xx, and network errors, are
18
+ # retried with exponential backoff, honouring Retry-After. Errors raise a
19
+ # Copytop::Error subclass (NotFoundError, RateLimitError, AuthError,
20
+ # BadRequestError, ServerError, NetworkError).
21
+ class Client
22
+ # Seconds. Some routes can take up to 30 seconds when their cache is cold.
23
+ DEFAULT_TIMEOUT = 45
24
+ # Seconds between two polls of watch_alerts. Once a minute is plenty.
25
+ DEFAULT_WATCH_INTERVAL = 60
26
+ MAX_RETRY_AFTER = 120.0
27
+ MAX_BACKOFF = 30.0
28
+
29
+ attr_reader :base_url, :timeout, :max_retries
30
+
31
+ # api_key: optional, from https://copy.top/account#api. Default: the
32
+ # COPYTOP_API_KEY environment variable; "" sends no key.
33
+ # Sent as "Authorization: Bearer <key>".
34
+ # timeout: seconds per HTTP call.
35
+ # max_retries: retries on 429, 5xx and network errors; 0 disables them.
36
+ # backoff: base delay in seconds, doubled on each retry, up to 30 s.
37
+ # transport: any object with call(url, headers, timeout) returning a
38
+ # Copytop::Response; default NetHTTPTransport.
39
+ # sleeper: callable taking seconds; tests replace it.
40
+ def initialize(api_key: nil, base_url: DEFAULT_BASE_URL, timeout: DEFAULT_TIMEOUT, max_retries: 3,
41
+ backoff: 1.0, user_agent: nil, transport: nil, sleeper: nil)
42
+ api_key = ENV["COPYTOP_API_KEY"] if api_key.nil?
43
+ api_key = api_key.to_s.strip
44
+ @api_key = api_key.empty? ? nil : api_key
45
+ base_url = base_url.to_s.strip.sub(%r{/+\z}, "")
46
+ @base_url = base_url.empty? ? DEFAULT_BASE_URL : base_url
47
+ @timeout = timeout
48
+ @max_retries = [max_retries.to_i, 0].max
49
+ @backoff = backoff.to_f
50
+ @user_agent = user_agent || "copytop-ruby/#{VERSION} (+https://copy.top)"
51
+ @transport = transport || NetHTTPTransport.new
52
+ @sleeper = sleeper || ->(seconds) { sleep(seconds) if seconds.positive? }
53
+ end
54
+
55
+ def api_key?
56
+ !@api_key.nil?
57
+ end
58
+
59
+ def inspect
60
+ "#<Copytop::Client base_url=#{@base_url.inspect} api_key=#{api_key? ? 'set' : 'none'}>"
61
+ end
62
+
63
+ # ---------------------------------------------------------------- core
64
+
65
+ # GET any route of the API and return the JSON answer. Use it for routes
66
+ # or parameters this class does not model yet. In params, nil values are
67
+ # dropped, booleans become true/false and arrays are joined with commas.
68
+ def get(path, params = {})
69
+ url = "#{@base_url}/#{path.to_s.sub(%r{\A/+}, '')}"
70
+ query = self.class.encode_query(params || {})
71
+ url = "#{url}?#{query}" unless query.empty?
72
+ headers = { "Accept" => "application/json", "User-Agent" => @user_agent }
73
+ headers["Authorization"] = "Bearer #{@api_key}" if @api_key
74
+
75
+ attempt = 0
76
+ loop do
77
+ begin
78
+ response = @transport.call(url, headers, @timeout)
79
+ rescue NetworkError, *NetHTTPTransport::NETWORK_ERRORS => e
80
+ if attempt < @max_retries
81
+ @sleeper.call(delay(attempt, nil))
82
+ attempt += 1
83
+ next
84
+ end
85
+ raise e if e.is_a?(NetworkError)
86
+
87
+ raise NetworkError.new(url, "#{e.class}: #{e.message}")
88
+ end
89
+
90
+ status = response.status.to_i
91
+ if (status == 429 || status >= 500) && attempt < @max_retries
92
+ @sleeper.call(delay(attempt, response.header("retry-after")))
93
+ attempt += 1
94
+ next
95
+ end
96
+ return self.class.decode_object(response.body.to_s, url, status) if status >= 200 && status < 300
97
+
98
+ raise self.class.api_error(response, url)
99
+ end
100
+ end
101
+
102
+ # Retry-After in seconds (a number of seconds or an HTTP date), capped at
103
+ # two minutes, or nil when absent or unreadable.
104
+ def self.parse_retry_after(value, now = Time.now)
105
+ value = value.to_s.strip
106
+ return nil if value.empty?
107
+
108
+ seconds =
109
+ begin
110
+ Float(value)
111
+ rescue ArgumentError
112
+ begin
113
+ Time.httpdate(value) - now
114
+ rescue ArgumentError
115
+ return nil
116
+ end
117
+ end
118
+ [[seconds.to_f, 0.0].max, MAX_RETRY_AFTER].min
119
+ end
120
+
121
+ # ------------------------------------------------------- fomo, pumpfun
122
+
123
+ # Trader leaderboard (fomo and pumpfun), like https://copy.top/traders.
124
+ # GET /traders.
125
+ #
126
+ # window: 1d, 7d or 30d. sort: total, realized, roi, winrate or copiers.
127
+ # chain: robinhood, solana, base, bnb, eth or arc. platform: fomo or
128
+ # pumpfun. fair_play: clean or clean_or_watch. limit: 1 to 20 (default 10).
129
+ # Returns {"window", "sort", "traders" => [...]}. The leaderboard is a
130
+ # snapshot refreshed periodically; a profile from trader is read live and
131
+ # is the reference.
132
+ def traders(window: nil, sort: nil, chain: nil, platform: nil, fair_play: nil, limit: nil)
133
+ get("traders", "window" => window, "sort" => sort, "chain" => chain, "platform" => platform,
134
+ "fair_play" => fair_play, "limit" => limit)
135
+ end
136
+
137
+ # One trader's profile: pnl over 30 days, roi, win rate, fair play, open
138
+ # positions, latest trades and theses. GET /traders/{handle}.
139
+ #
140
+ # handle as search or another call gave it, with or without "@"; a handle
141
+ # starting with pf_ is a pumpfun account. Raises NotFoundError when there
142
+ # is no such trader.
143
+ def trader(handle)
144
+ get("traders/#{segment('handle', handle.to_s.strip.sub(/\A@+/, ''))}")
145
+ end
146
+
147
+ # Traders and coins by name, @handle, $ticker or address (2 to 80
148
+ # characters). GET /search. Returns {"traders" => [...], "coins" => [...]}.
149
+ def search(query)
150
+ query = query.to_s.strip
151
+ raise ArgumentError, "copytop: empty search query" if query.empty?
152
+
153
+ get("search", "query" => query)
154
+ end
155
+
156
+ # The signal feed: coins tracked traders are buying now. GET /coins/hot.
157
+ # window: 1h or 24h (default 24h). max_mcap_usd: leaves out coins above
158
+ # this market cap. limit: 1 to 15.
159
+ def hot_coins(window: nil, max_mcap_usd: nil, limit: nil)
160
+ get("coins/hot", "window" => window, "max_mcap_usd" => max_mcap_usd, "limit" => limit)
161
+ end
162
+
163
+ # copy.top's hot index: coins ranked 0 to 100 by attention (buyers,
164
+ # callers, activity on X). GET /coins/index. window: 1h, 6h or 24h.
165
+ # chain: optional. limit: 1 to 10.
166
+ def hot_index(window: nil, chain: nil, limit: nil)
167
+ get("coins/index", "window" => window, "chain" => chain, "limit" => limit)
168
+ end
169
+
170
+ # Coins ranked by the dollars tracked traders bought (side buy) or sold
171
+ # (side sell). GET /coins/flow. window: 1h, 6h, 24h or 7d. limit: 1 to 10.
172
+ def money_flow(side: nil, window: nil, limit: nil)
173
+ get("coins/flow", "side" => side, "window" => window, "limit" => limit)
174
+ end
175
+
176
+ # Coins whose team paid for a dexscreener profile in the last 24 hours.
177
+ # GET /coins/dex-paid. limit: 1 to 12.
178
+ def dex_paid(limit: nil)
179
+ get("coins/dex-paid", "limit" => limit)
180
+ end
181
+
182
+ # One coin: price, market cap, moves, liquidity, which tracked traders
183
+ # hold or sold it, and theses. GET /coins/{chain}/{address}.
184
+ # chain: robinhood, solana, base, bnb, eth or arc.
185
+ def coin(chain, address)
186
+ get("coins/#{segment('chain', chain)}/#{segment('address', address)}")
187
+ end
188
+
189
+ # The live tape: the latest buys and sells by tracked traders, newest
190
+ # first. GET /trades. since: an ISO time or the cursor of a previous
191
+ # answer. side: buy or sell. min_usd: leaves out smaller trades. limit: 1
192
+ # to 30. The tape keeps the latest 30 trades: poll at least once a minute
193
+ # to miss none. Returns {"cursor", "trades" => [...]}.
194
+ def trades(since: nil, side: nil, min_usd: nil, limit: nil)
195
+ get("trades", "since" => since, "side" => side, "min_usd" => min_usd, "limit" => limit)
196
+ end
197
+
198
+ # Events since a cursor: confluence (several top traders bought the same
199
+ # coin recently), big_trade (one tracked trader bought or sold a large
200
+ # amount) and thesis (a tracked trader posted a thesis). GET /alerts.
201
+ #
202
+ # since: the cursor of the previous answer (nil: the last 15 minutes).
203
+ # min_top_traders: 1 to 50 (server default 3). min_trade_usd: server
204
+ # default 5000. kinds: an array or a comma separated string of
205
+ # confluence, big_trade, thesis. limit: 1 to 40.
206
+ # Returns {"since", "cursor", "thresholds", "events" => [...]}. Pass the
207
+ # cursor back as since on the next call, or use watch_alerts.
208
+ def alerts(since: nil, min_top_traders: nil, min_trade_usd: nil, max_mcap_usd: nil, kinds: nil, limit: nil)
209
+ get("alerts", "since" => since, "min_top_traders" => min_top_traders, "min_trade_usd" => min_trade_usd,
210
+ "max_mcap_usd" => max_mcap_usd, "kinds" => kinds, "limit" => limit)
211
+ end
212
+
213
+ # Polls alerts every interval seconds, passes the cursor of each answer
214
+ # back as since, and yields every new event, oldest first. Runs until you
215
+ # break out of the block. Without a block, returns an Enumerator.
216
+ #
217
+ # ct.watch_alerts(kinds: %w[confluence big_trade]) do |event|
218
+ # puts "#{event['kind']} #{event['symbol']} #{event['url']}"
219
+ # end
220
+ #
221
+ # Filters are those of alerts. Temporary errors (429, 5xx or network,
222
+ # after the client's own retries) never stop the watch: they go to
223
+ # on_error and the next poll follows. Other errors, like a refused API
224
+ # key, are raised. on_cursor is called with the new cursor after each
225
+ # poll whose events were all handled: save it and pass it back as since
226
+ # to resume after a restart. A coin can alert again when another top
227
+ # trader buys it.
228
+ def watch_alerts(interval: DEFAULT_WATCH_INTERVAL, since: nil, on_cursor: nil, on_error: nil, **filters)
229
+ unless block_given?
230
+ return Enumerator.new do |y|
231
+ watch_alerts(interval: interval, since: since, on_cursor: on_cursor, on_error: on_error, **filters) do |event|
232
+ y << event
233
+ end
234
+ end
235
+ end
236
+
237
+ interval = DEFAULT_WATCH_INTERVAL unless interval.is_a?(Numeric) && interval.positive?
238
+ cursor = since
239
+ loop do
240
+ begin
241
+ answer = alerts(since: cursor, **filters)
242
+ rescue Error => e
243
+ raise unless e.temporary?
244
+
245
+ on_error&.call(e)
246
+ @sleeper.call(interval)
247
+ next
248
+ end
249
+
250
+ events = answer["events"]
251
+ events.reverse_each { |event| yield event } if events.is_a?(Array)
252
+ nxt = answer["cursor"]
253
+ if nxt.is_a?(String) && !nxt.empty?
254
+ cursor = nxt
255
+ on_cursor&.call(nxt)
256
+ end
257
+ @sleeper.call(interval)
258
+ end
259
+ end
260
+
261
+ # Theses (a trader's written reason for holding a coin) posted by tracked
262
+ # traders. GET /theses. sort: new (default) or popular. hours: 1 to 24.
263
+ # limit: 1 to 10.
264
+ def theses(sort: nil, hours: nil, limit: nil)
265
+ get("theses", "sort" => sort, "hours" => hours, "limit" => limit)
266
+ end
267
+
268
+ # --------------------------------------------------------- Hyperliquid
269
+
270
+ # Hyperliquid perps traders tracked by copy.top, ranked by pnl or roi.
271
+ # GET /hyperliquid/traders. window: 24h, 7d, 30d (default) or all. sort:
272
+ # pnl (default) or roi. limit: 1 to 20.
273
+ def hl_traders(window: nil, sort: nil, limit: nil)
274
+ get("hyperliquid/traders", "window" => window, "sort" => sort, "limit" => limit)
275
+ end
276
+
277
+ # One Hyperliquid trader by address (0x and 40 hex characters): metrics,
278
+ # pnl per window, live positions and fills. GET /hyperliquid/traders/{address}.
279
+ def hl_trader(address)
280
+ get("hyperliquid/traders/#{segment('address', address.to_s.downcase)}")
281
+ end
282
+
283
+ # Live Hyperliquid markets (crypto perps and hip-3 markets: stocks,
284
+ # indices, commodities, fx), sorted by 24 hour volume.
285
+ # GET /hyperliquid/markets. category: crypto, stocks, indices... limit: 1 to 50.
286
+ def hl_markets(category: nil, limit: nil)
287
+ get("hyperliquid/markets", "category" => category, "limit" => limit)
288
+ end
289
+
290
+ # copy.top's read of one Hyperliquid market (BTC, ETH, xyz:TSLA...):
291
+ # technicals, funding, open interest, what the top traders hold,
292
+ # liquidations. GET /hyperliquid/markets/{coin}.
293
+ def hl_market(coin)
294
+ get("hyperliquid/markets/#{segment('coin', coin)}")
295
+ end
296
+
297
+ # The X analysts ranked by the track record of their calls on one
298
+ # Hyperliquid market, and their recent calls.
299
+ # GET /hyperliquid/markets/{coin}/calls.
300
+ def hl_calls(coin)
301
+ get("hyperliquid/markets/#{segment('coin', coin)}/calls")
302
+ end
303
+
304
+ # ------------------------------------------------------------- helpers
305
+
306
+ def self.encode_query(params)
307
+ pairs = []
308
+ params.each do |key, value|
309
+ next if value.nil?
310
+
311
+ value =
312
+ case value
313
+ when true, false then value.to_s
314
+ when Array
315
+ parts = value.map { |v| v.to_s.strip }.reject(&:empty?)
316
+ next if parts.empty?
317
+
318
+ parts.join(",")
319
+ when Float then format_float(value)
320
+ else
321
+ v = value.to_s.strip
322
+ next if v.empty?
323
+
324
+ v
325
+ end
326
+ pairs << "#{escape(key.to_s)}=#{escape(value)}"
327
+ end
328
+ pairs.join("&")
329
+ end
330
+
331
+ def self.format_float(value)
332
+ return value.to_i.to_s if value.finite? && value == value.floor && value.abs < 1e15
333
+
334
+ s = format("%.10f", value).sub(/0+\z/, "").sub(/\.\z/, "")
335
+ s.empty? || s == "-0" ? "0" : s
336
+ end
337
+
338
+ # Percent-encodes a query string key or value (space as %20).
339
+ def self.escape(value)
340
+ URI.encode_www_form_component(value.to_s).gsub("+", "%20")
341
+ end
342
+
343
+ # Percent-encodes a path segment, keeping ":" (xyz:TSLA).
344
+ def self.escape_segment(value)
345
+ escape(value).gsub("%3A", ":")
346
+ end
347
+
348
+ def self.decode_object(body, url, status)
349
+ stripped = body.lstrip
350
+ raise Error, "copytop: unexpected answer from #{url} (not a JSON object)" unless stripped.start_with?("{")
351
+
352
+ begin
353
+ JSON.parse(stripped)
354
+ rescue JSON::ParserError => e
355
+ raise Error, "copytop: decoding answer from #{url} (#{status}): #{e.message}"
356
+ end
357
+ end
358
+
359
+ def self.api_error(response, url)
360
+ message = ""
361
+ begin
362
+ data = JSON.parse(response.body.to_s)
363
+ if data.is_a?(Hash) && data.key?("error")
364
+ err = data["error"]
365
+ err = err["message"] if err.is_a?(Hash)
366
+ message = err.to_s.strip unless err.nil? || err.is_a?(Hash) || err.is_a?(Array)
367
+ end
368
+ rescue JSON::ParserError
369
+ message = ""
370
+ end
371
+ message = response.body.to_s.strip[0, 200].to_s.strip if message.empty?
372
+ message = "HTTP #{response.status}" if message.empty?
373
+ APIError.for_status(response.status.to_i, message, url, parse_retry_after(response.header("retry-after")))
374
+ end
375
+
376
+ private
377
+
378
+ # Seconds to wait before retry number attempt + 1.
379
+ def delay(attempt, retry_after)
380
+ parsed = self.class.parse_retry_after(retry_after)
381
+ return parsed unless parsed.nil?
382
+
383
+ d = [@backoff * (2**attempt), MAX_BACKOFF].min
384
+ d += rand * @backoff / 2 if @backoff.positive?
385
+ d
386
+ end
387
+
388
+ def segment(name, value)
389
+ value = value.to_s.strip
390
+ raise ArgumentError, "copytop: empty #{name}" if value.empty?
391
+
392
+ self.class.escape_segment(value)
393
+ end
394
+ end
395
+
396
+ module_function
397
+
398
+ # The copy.top page of a fomo or pumpfun trader, where anyone can copy
399
+ # them: https://copy.top/t/<handle>.
400
+ def trader_url(handle)
401
+ "#{SITE_URL}/t/#{Client.escape_segment(handle.to_s.strip.sub(/\A@+/, ''))}"
402
+ end
403
+
404
+ # The copy.top page of a coin: https://copy.top/token/<chain>/<address>.
405
+ def coin_url(chain, address)
406
+ "#{SITE_URL}/token/#{Client.escape_segment(chain.to_s.strip)}/#{Client.escape_segment(address.to_s.strip)}"
407
+ end
408
+
409
+ # The copy.top page of a Hyperliquid trader: https://copy.top/t/hl/<address>.
410
+ def hl_trader_url(address)
411
+ "#{SITE_URL}/t/hl/#{Client.escape_segment(address.to_s.strip.downcase)}"
412
+ end
413
+
414
+ # The copy.top page of a Hyperliquid market: https://copy.top/token/hyperliquid/<coin>.
415
+ def hl_market_url(coin)
416
+ "#{SITE_URL}/token/hyperliquid/#{Client.escape_segment(coin.to_s.strip)}"
417
+ end
418
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Copytop
4
+ # Base class of every error raised by the client after a call: an error
5
+ # answered by copy.top (APIError and its subclasses) or a network error
6
+ # after all retries (NetworkError).
7
+ class Error < StandardError
8
+ # True when the call may succeed later: 429, 5xx or a network error.
9
+ def temporary?
10
+ false
11
+ end
12
+ end
13
+
14
+ # An error answered by the copy.top API. Subclasses: BadRequestError (400),
15
+ # AuthError (401, 403), NotFoundError (404), RateLimitError (429) and
16
+ # ServerError (5xx).
17
+ class APIError < Error
18
+ # HTTP status, like 404 or 429.
19
+ attr_reader :status
20
+ # The "error" field of the answer, or the start of the body.
21
+ attr_reader :api_message
22
+ # The URL that was called.
23
+ attr_reader :url
24
+ # Seconds from the Retry-After header, or nil.
25
+ attr_reader :retry_after
26
+
27
+ def initialize(status, api_message, url, retry_after = nil)
28
+ @status = status
29
+ @api_message = api_message
30
+ @url = url
31
+ @retry_after = retry_after
32
+ super("copy.top answered #{status}: #{api_message}")
33
+ end
34
+
35
+ def temporary?
36
+ status == 429 || status >= 500
37
+ end
38
+
39
+ # The error class matching an HTTP status.
40
+ def self.for_status(status, api_message, url, retry_after = nil)
41
+ klass =
42
+ if status == 400 then BadRequestError
43
+ elsif status == 401 || status == 403 then AuthError
44
+ elsif status == 404 then NotFoundError
45
+ elsif status == 429 then RateLimitError
46
+ elsif status >= 500 then ServerError
47
+ else APIError
48
+ end
49
+ klass.new(status, api_message, url, retry_after)
50
+ end
51
+ end
52
+
53
+ # 400: a parameter was refused.
54
+ class BadRequestError < APIError; end
55
+
56
+ # 401 or 403: the API key was refused. Create a free one at
57
+ # https://copy.top/account#api, or call without a key.
58
+ class AuthError < APIError; end
59
+
60
+ # 404: no such trader, coin or market on copy.top.
61
+ class NotFoundError < APIError; end
62
+
63
+ # 429: too many calls. Without a key, about 20 calls a minute per IP (about
64
+ # 6 a minute for search, trader and coin). A free key from
65
+ # https://copy.top/account#api raises the limits.
66
+ class RateLimitError < APIError; end
67
+
68
+ # 5xx: copy.top could not answer. Retried automatically before it is raised.
69
+ class ServerError < APIError; end
70
+
71
+ # The API could not be reached (DNS, TLS, timeout, connection reset...).
72
+ class NetworkError < Error
73
+ attr_reader :url
74
+
75
+ def initialize(url, message)
76
+ @url = url
77
+ super("copytop: GET #{url}: #{message}")
78
+ end
79
+
80
+ def temporary?
81
+ true
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module Copytop
8
+ # A raw HTTP answer, as a transport returns it. Header names are lower case.
9
+ Response = Struct.new(:status, :headers, :body) do
10
+ def header(name)
11
+ (headers || {})[name.to_s.downcase]
12
+ end
13
+ end
14
+
15
+ # Default transport, on Net::HTTP from the standard library. Redirects are
16
+ # not followed: the API never redirects, and a redirect to another host
17
+ # would carry the API key.
18
+ #
19
+ # A transport is any object with call(url, headers, timeout) returning a
20
+ # Copytop::Response, and raising Copytop::NetworkError when no HTTP answer
21
+ # was received. Tests pass a fake one.
22
+ class NetHTTPTransport
23
+ NETWORK_ERRORS = [
24
+ SocketError, IOError, SystemCallError, Timeout::Error,
25
+ OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::ProtocolError
26
+ ].freeze
27
+
28
+ def initialize(open_timeout: 10)
29
+ @open_timeout = open_timeout
30
+ end
31
+
32
+ def call(url, headers, timeout)
33
+ uri = URI.parse(url)
34
+ http = Net::HTTP.new(uri.host, uri.port)
35
+ http.use_ssl = uri.scheme == "https"
36
+ http.open_timeout = [@open_timeout, timeout].min
37
+ http.read_timeout = timeout
38
+ http.write_timeout = timeout if http.respond_to?(:write_timeout=)
39
+
40
+ request = Net::HTTP::Get.new(uri.request_uri)
41
+ headers.each { |name, value| request[name] = value }
42
+
43
+ response = http.start { |h| h.request(request) }
44
+ received = {}
45
+ response.each_header { |name, value| received[name.downcase] = value }
46
+ body = response.body.to_s.dup.force_encoding(Encoding::UTF_8)
47
+ Response.new(response.code.to_i, received, body)
48
+ rescue *NETWORK_ERRORS => e
49
+ raise NetworkError.new(url, "#{e.class}: #{e.message}")
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Copytop
4
+ VERSION = "0.1.0"
5
+ end
data/lib/copytop.rb ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Official Ruby client for the copy.top API.
4
+ #
5
+ # copy.top (https://copy.top) tracks what top traders buy and sell on fomo,
6
+ # pumpfun and Hyperliquid, and lets people copy them. This client wraps the
7
+ # public, read-only REST API at https://copy.top/v1. Nothing here places an
8
+ # order. Figures are data, not advice.
9
+ #
10
+ # require "copytop"
11
+ # ct = Copytop::Client.new # no key needed
12
+ # ct.hot_coins(window: "1h", limit: 5)["coins"].each { |c| puts c["symbol"] }
13
+
14
+ require_relative "copytop/version"
15
+ require_relative "copytop/errors"
16
+ require_relative "copytop/transport"
17
+ require_relative "copytop/client"
metadata ADDED
@@ -0,0 +1,60 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: copytop
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - copy.top
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-29 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: 'copy.top (https://copy.top) tracks what top traders buy and sell on
14
+ fomo, pumpfun and Hyperliquid, and lets people copy them. This gem wraps the public,
15
+ read-only REST API: trader leaderboard, trader profiles, coins top traders are buying
16
+ now, money flow, live trades, alerts and Hyperliquid markets. No key needed, standard
17
+ library only (Net::HTTP), typed errors and retries. Nothing here places an order.
18
+ copy.top is independent and not affiliated with fomo, pump.fun or Hyperliquid. Figures
19
+ are data, not advice.'
20
+ email:
21
+ - ana@copy.top
22
+ executables: []
23
+ extensions: []
24
+ extra_rdoc_files: []
25
+ files:
26
+ - LICENSE
27
+ - README.md
28
+ - lib/copytop.rb
29
+ - lib/copytop/client.rb
30
+ - lib/copytop/errors.rb
31
+ - lib/copytop/transport.rb
32
+ - lib/copytop/version.rb
33
+ homepage: https://copy.top
34
+ licenses:
35
+ - MIT
36
+ metadata:
37
+ homepage_uri: https://copy.top
38
+ documentation_uri: https://copy.top/agents
39
+ source_code_uri: https://bitbucket.org/copytop/copytop-ruby
40
+ post_install_message:
41
+ rdoc_options: []
42
+ require_paths:
43
+ - lib
44
+ required_ruby_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '2.6'
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ requirements: []
55
+ rubygems_version: 3.0.3.1
56
+ signing_key:
57
+ specification_version: 4
58
+ summary: 'Official Ruby client for the copy.top API (https://copy.top): what top fomo,
59
+ pumpfun and Hyperliquid traders buy and sell.'
60
+ test_files: []