From 7bdf4bbffc12490885fabf548456890a13761981 Mon Sep 17 00:00:00 2001 From: Kabzelife <141412378+Kabzelife@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:51:46 +0100 Subject: [PATCH] 0.9.0: Trade Feed - Feed, traders (list, add, remove), notifications, by csid_id or external_id - Trade Feed WebSocket stream, typed trade_feed.trade / trade_feed.thesis webhooks - README, example, tests Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 38 +++ README.md | 70 +++++- cabalspy_id/__init__.py | 63 ++++- cabalspy_id/_client.py | 244 ++++++++++++++++++ cabalspy_id/_constants.py | 28 ++- cabalspy_id/_errors.py | 16 +- cabalspy_id/_trade_feed_stream.py | 364 +++++++++++++++++++++++++++ cabalspy_id/_types.py | 171 ++++++++++++- cabalspy_id/api.py | 63 ++++- examples/trade_feed.py | 100 ++++++++ pyproject.toml | 2 +- tests/test_copy_trading.py | 1 - tests/test_trade_feed.py | 403 ++++++++++++++++++++++++++++++ tests/test_trade_feed_stream.py | 218 ++++++++++++++++ 14 files changed, 1763 insertions(+), 18 deletions(-) create mode 100644 cabalspy_id/_trade_feed_stream.py create mode 100644 examples/trade_feed.py create mode 100644 tests/test_trade_feed.py create mode 100644 tests/test_trade_feed_stream.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bd40b6a..040b422 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,43 @@ All notable changes to this package are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/). +## [0.9.0] - 2026-11-01 + +Trade Feed: read and manage your users' Trade Feeds from your backend (the traders they follow, +every trade and thesis of those traders, alert filters and notifications), and get every new +trade and thesis for them live, with the users to tell. Sync and async. + +### Added + +- Trade Feed (`/v1/trade-feed/*`) on `CabalSpyID` and `AsyncCabalSpyID`, every method in the name + of one user (`external_id` positionally or `csid_id=`): `trade_feed` / `iter_trade_feed` + (`filter` all / buys / sells / theses, `limit` 1-100), `trade_feed_traders` / + `iter_trade_feed_traders` (`limit` 1-300; pagination `total` and `max`), + `add_trade_feed_trader` (`trader=` / `trader_external_id=`, `notify_buys`, `notify_sells`, + `notify_theses`, `min_sol`, `min_bnb`, `min_eth` (0-1,000,000), `muted`; `created` tells 201 + from 200), `remove_trade_feed_trader`, `trade_feed_notifications` / + `iter_trade_feed_notifications` (`limit` 1-100). Values are checked locally like the server does. +- `TradeFeedStream` for `wss://api-id.cabalspy.xyz/v1/trade-feed/stream` via + `client.trade_feed_stream()`: events `trade_feed.trade` and `trade_feed.thesis` (handlers get + the item plus `recipients` and `recipients_external`; `async for` yields `{"event", "id", "data"}` + with the event id), heartbeats, reconnects with backoff; `invalid_api_key` is fatal, + `too_many_connections` reconnects. New client option `trade_feed_stream_url`. +- Types: `TradeFeedItem` (`TradeFeedTradeItem` | `TradeFeedThesisItem`), `TradeFeedTrade`, + `TradeFeedThesis`, `TradeFeedTrader`, `TradeFeedSettings` (with the existing `CopySettings` as + `copy`), `TradeFeedMinNative`, `TradeFeedTraderResult`, `TradeFeedRemoveResult`, + `TradeFeedNotification`, `TradeFeedEvent` (`TradeFeedTradeEvent` | `TradeFeedThesisEvent`, the + webhook and stream `data`), `TradeFeedStreamReady`. +- Constants: `TRADE_FEED_WEBHOOK_EVENTS` (`trade_feed.trade`, `trade_feed.thesis`, also in + `WEBHOOK_EVENTS`), `TRADE_FEED_FILTERS`, `TRADE_LABELS`, `MAX_TRADE_FEED_TRADERS` (300), + `TRADE_FEED_CHANGES_PER_HOUR` (120), `TRADE_FEED_MAX_MIN_NATIVE`, + `MAX_TRADE_FEED_STREAMS_PER_KEY`, `DEFAULT_TRADE_FEED_STREAM_URL`, `TRADE_FEED_EVENTS`, + `TRADE_FEED_STREAM_EVENTS`; Literal types `TradeFeedFilter`, `TradeFeedItemType`, `TradeLabel`. +- Error codes on the existing classes: `cannot_add_self` (`BadRequestError`), `trade_feed_full` + (`ConflictError`), `trader_not_found`, `platform_user_not_found` (`NotFoundError`), + `consent_required`, `trading_private` (`PermissionError`), `plan_user_limit` + (`PlanUserLimitError`), `rate_limited` (`RateLimitError`, not retried). +- README section "Trade Feed" and `examples/trade_feed.py`. + ## [0.8.0] - 2026-11-01 Copy trading: every trade of a trader one of your users copies becomes a ready-to-execute @@ -265,6 +302,7 @@ First release. `NotFoundError`, `RateLimitError`, `ServerError`, `APIConnectionError`, `InvalidResponseError`, `OAuthError`, `TokenVerificationError`, `WebhookVerificationError`. +[0.9.0]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.8.0...v0.9.0 [0.8.0]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.7.0...v0.8.0 [0.7.0]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.6.0...v0.7.0 [0.6.0]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.2...v0.6.0 diff --git a/README.md b/README.md index 3ca476b..8408e37 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ pip install "cabalspy-id[stream]" | | | |---|---| | `CabalSpyIDAuth` / `AsyncCabalSpyIDAuth` | OpenID Connect for your server: PKCE, code exchange, refresh, revoke, userinfo, ID token verification (ES256 / JWKS) | -| `CabalSpyID` / `AsyncCabalSpyID` | Data API client for `https://api-id.cabalspy.xyz/v1`, typed responses, pagination, live trade stream, white-label platform users, trading competitions, callouts (on request) and copy trading | +| `CabalSpyID` / `AsyncCabalSpyID` | Data API client for `https://api-id.cabalspy.xyz/v1`, typed responses, pagination, live trade stream, white-label platform users, trading competitions, callouts (on request), the Trade Feed and copy trading | | `ThesisClient` / `AsyncThesisClient` | public token thesis API with your public `client_id` and a user's access token, plus `live()` updates | | `verify_webhook` | Standard Webhooks signature verification | @@ -56,7 +56,7 @@ One codebase, one version line. The focused packages re-export parts of `cabalsp | Import | Contents | |---|---| | `cabalspy_id` | everything | -| `cabalspy_id.api` | `CabalSpyID`, `AsyncCabalSpyID`, `CabalSpyIDStream`, `CalloutsStream`, `CopyTradingStream`, `CabalSpyIDAuth`, `verify_webhook`, errors and Data API types | +| `cabalspy_id.api` | `CabalSpyID`, `AsyncCabalSpyID`, `CabalSpyIDStream`, `CalloutsStream`, `CopyTradingStream`, `TradeFeedStream`, `CabalSpyIDAuth`, `verify_webhook`, errors and Data API types | | `cabalspy_id.thesis` | `CabalSpyID` (thesis methods), `ThesisClient`, `AsyncThesisClient`, `ThesisLive`, `ThesesStream`, thesis types | The objects are the same as in `cabalspy_id`. @@ -231,13 +231,13 @@ except RateLimitError as err: | Class | Status | Codes | |---|---|---| -| `BadRequestError` | 400, 422 | `missing_parameter`, `invalid_parameter`, `instance_required`, `wallet_required`, `invalid_address`, `invalid_return_url`, `no_price` (422) | +| `BadRequestError` | 400, 422 | `missing_parameter`, `invalid_parameter`, `instance_required`, `wallet_required`, `invalid_address`, `invalid_return_url`, `cannot_add_self`, `no_price` (422) | | `AuthenticationError` | 401 | `missing_api_key` | | `PermissionError` | 403 | `invalid_api_key`, `product_not_enabled`, `no_instance`, `scope_not_allowed`, `claim_disabled`, `feature_not_enabled`, `kol_only`, `not_a_holder`, `invalid_account`, `posting_paused`, `consent_required`, `sandbox_user`, `trading_private` | | `PlanUserLimitError` | 403 | `plan_user_limit` | | `NotFoundError` | 404 | `profile_not_found`, `wallet_not_found`, `instance_not_found`, `platform_user_not_found`, `verification_not_found`, `competition_not_found`, `callout_not_found`, `trader_not_found`, `not_in_trade_feed`, `not_found` | | `ConflictError` | 409 | `account_claimed`, `last_wallet`, `too_many_wallets`, `wallet_already_verified`, `kol_badge`, `x_required`, `kol_not_eligible`, `competition_limit`, `competition_closed`, `competition_full`, `late_join_closed`, `already_called`, `copy_managed_elsewhere`, `already_reported`, `trade_feed_full` | -| `RateLimitError` | 429 | `rate_limit_exceeded`, `rate_limited`, `too_many_open_verifications`, `callout_cooldown` | +| `RateLimitError` | 429 | `rate_limit_exceeded`, `rate_limited` (also the Trade Feed's 120 changes per hour; not retried), `too_many_open_verifications`, `callout_cooldown` | | `ServerError` | 5xx | `internal_error`, `service_unavailable` | | `APIConnectionError` | – | network failure, timeout | | `OAuthError` | 4xx | OAuth errors from the login endpoints (`invalid_grant`, `invalid_client`, …) | @@ -406,6 +406,65 @@ comp = csid.create_competition(name="Caller of the week", kind="callouts", chain A full tour is in [`examples/callouts.py`](examples/callouts.py). +## Trade Feed + +A user's **Trade Feed** is the traders they follow: every trade and thesis of those traders, alerts filtered per trader, and the [copy settings](#copy-trading). Read and manage it from your backend in the user's name: a person who signed in to your app with the scope `trade_feed` (else `PermissionError` `consent_required`), or one of your platform users, within your plan's user limit. Every method takes the user as `external_id` (positional, your own user id) or `csid_id=`; a trader is a handle (with or without @) or a csid_id, or `trader_external_id=` for one of your platform users. + +```python +from cabalspy_id import CabalSpyID, ConflictError, PermissionError + +csid = CabalSpyID() + +# Add @MazeCCC to user_42's Trade Feed: alerts for buys from 0.5 SOL, no sells +try: + r = csid.add_trade_feed_trader("user_42", trader="@MazeCCC", min_sol=0.5, notify_sells=False) + print(r["created"], r["settings"]["min_native"]) # True on HTTP 201, False when already there +except PermissionError as err: # consent_required, trading_private + print(err.code) +except ConflictError: # trade_feed_full: 300 traders + pass + +for item in csid.iter_trade_feed("user_42", filter="buys"): # newest first + t = item["trade"] + print(item["trader"]["username"], t["side"], t["symbol"], t["amount_usd"], t["label"]) + +for entry in csid.iter_trade_feed_traders("user_42"): + print(entry["trader"]["username"], entry["settings"]["muted"], entry["settings"]["copy"]["enabled"]) + +csid.remove_trade_feed_trader("user_42", trader="MazeCCC") # also ends copying +``` + +| Method | Endpoint | +|---|---| +| `trade_feed(external_id \| csid_id=, filter=, limit=, cursor=)` / `iter_trade_feed()` | `GET /v1/trade-feed` | +| `trade_feed_traders(external_id \| csid_id=, limit=, cursor=)` / `iter_trade_feed_traders()` | `GET /v1/trade-feed/traders` | +| `add_trade_feed_trader(external_id \| csid_id=, trader= \| trader_external_id=, notify_buys=, notify_sells=, notify_theses=, min_sol=, min_bnb=, min_eth=, muted=)` | `POST /v1/trade-feed/traders` | +| `remove_trade_feed_trader(external_id \| csid_id=, trader= \| trader_external_id=)` | `POST /v1/trade-feed/traders/delete` | +| `trade_feed_notifications(external_id \| csid_id=, limit=, cursor=)` / `iter_trade_feed_notifications()` | `GET /v1/trade-feed/notifications` | +| `trade_feed_stream()` | `WS /v1/trade-feed/stream` | + +**The feed** (`TradeFeedItem`, newest first; `filter` `all`, `buys`, `sells` or `theses`; `limit` 1-100, default 30): trade items (`type` `trade`: `trader`, `trade` with `side`, `label` (`new`, `add`, `partial`, `close`, `sell`), `sold_percent`, `amount_native` in `currency`, `amount_usd`, `price_usd`, `pnl_usd` / `pnl_percent` for sells with a known entry, `wallet`, `tx_signature` and explorer links) and thesis items (`type` `thesis`, `id` `h` + the thesis id). An item's `id` is the same in the feed, the webhook, the stream and the notifications. Traders who keep their trading private are left out. + +**Traders** (`TradeFeedTrader`, most recently added first; `limit` 1-300, default 100; the envelope's pagination has `total` and `max`): `trader`, `trading_public`, `added_at`, `in_trade_feeds` and `settings` (`notify_buys`, `notify_sells`, `notify_theses`, `min_native` `{"SOL", "BNB", "ETH"}`, `muted`, and `copy`, the `CopySettings`). `add_trade_feed_trader` uses the user's default alert settings unless you pass others; for a trader already there it updates what you pass (None = unchanged). `min_*` are 0 to 1,000,000 (0 = every trade). + +**Notifications** (`TradeFeedNotification`, `limit` 1-100, default 50): every alert that passed the user's filters, with `id`, `event` (`trade_feed.trade` / `trade_feed.thesis`), a ready-made `text`, `created_at` and the item as `data`. Useful as an inbox when you do not use webhooks. + +**Errors.** `BadRequestError` `cannot_add_self`; `PermissionError` `consent_required`, `trading_private`; `PlanUserLimitError` `plan_user_limit` (an `anon_` id); `NotFoundError` `trader_not_found`, `platform_user_not_found`; `ConflictError` `trade_feed_full` (300 traders); `RateLimitError` `rate_limited` (more than 120 changes of a user's Trade Feed in an hour; not retried). + +**Live stream** (async, needs `cabalspy-id[stream]`) and webhooks `trade_feed.trade` / `trade_feed.thesis` (`TRADE_FEED_WEBHOOK_EVENTS`) carry every new trade and thesis that concerns your users, once per event (not per user): `data` is the item plus `recipients` (csid_ids of your users whose filters let it through) and `recipients_external` (your own ids of those who are platform users). + +```python +async with AsyncCabalSpyID() as csid: + async with csid.trade_feed_stream() as tf: + async for ev in tf: # {"event": "trade_feed.trade", "id": ..., "data": ...} + for user in ev["data"]["recipients_external"]: + await notify(user, ev["data"]) +``` + +Events: `trade_feed.trade`, `trade_feed.thesis`, plus `ready`, `heartbeat`, `pong`, `open`, `close`, `reconnecting`, `error`. `invalid_api_key` is fatal; `too_many_connections` (at most 5 per key) reconnects with backoff. Events made while disconnected are not replayed: read the notifications or the feed to catch up. + +A full tour is in [`examples/trade_feed.py`](examples/trade_feed.py). + ## Copy trading Every trade of a trader one of your users copies becomes a **ready-to-execute instruction** for that user, sized by their copy settings for that trader. CabalSpy ID never holds keys and never executes: your app executes the instruction with the user's wallet and reports what happened. It needs the user's consent with the scope `trade_feed` (else `PermissionError` `consent_required`); a copied trader is in the user's Trade Feed. @@ -608,7 +667,7 @@ The server sends a heartbeat every 30 seconds. The client reconnects with expone ## Webhooks -Deliveries follow the [Standard Webhooks](https://www.standardwebhooks.com) spec (`webhook-id`, `webhook-timestamp`, `webhook-signature`, secret `whsec_...`) and are retried for about 2 days. Events: `wallet.verified`, `wallet.removed`, `profile.updated`, `kol.granted`, `consent.revoked`, `thesis.created`, `thesis.reply`, `thesis.reaction` — only for users within the plan's limit. White-label adds `platform_user.created`, `platform_user.claimed`, `platform_user.x_connected`, `wallet.added`, `verification.expired` and the instance-level `competition.started`, `competition.updated`, `competition.standings`, `competition.ended` (these carry `competition_id` instead of `sub`). Callouts add `callout.created`, `callout.milestone`, `callout.scored`, `callout.final` (`data.callout`; `CALLOUT_WEBHOOK_EVENTS`). Copy trading adds `copy_trade.instruction` (one per user and copied trade; `data` is the instruction plus `external_id`; `COPY_TRADING_WEBHOOK_EVENTS`). +Deliveries follow the [Standard Webhooks](https://www.standardwebhooks.com) spec (`webhook-id`, `webhook-timestamp`, `webhook-signature`, secret `whsec_...`) and are retried for about 2 days. Events: `wallet.verified`, `wallet.removed`, `profile.updated`, `kol.granted`, `consent.revoked`, `thesis.created`, `thesis.reply`, `thesis.reaction` — only for users within the plan's limit. White-label adds `platform_user.created`, `platform_user.claimed`, `platform_user.x_connected`, `wallet.added`, `verification.expired` and the instance-level `competition.started`, `competition.updated`, `competition.standings`, `competition.ended` (these carry `competition_id` instead of `sub`). Callouts add `callout.created`, `callout.milestone`, `callout.scored`, `callout.final` (`data.callout`; `CALLOUT_WEBHOOK_EVENTS`). Copy trading adds `copy_trade.instruction` (one per user and copied trade; `data` is the instruction plus `external_id`; `COPY_TRADING_WEBHOOK_EVENTS`). The Trade Feed adds `trade_feed.trade` and `trade_feed.thesis` (one per trade or thesis, not per user; `data` is the feed item plus `recipients` and `recipients_external`; `TradeFeedTradeEvent` / `TradeFeedThesisEvent`; `TRADE_FEED_WEBHOOK_EVENTS`). ```python from cabalspy_id import verify_webhook @@ -632,6 +691,7 @@ CabalSpyID( stream_url="wss://api-id.cabalspy.xyz/v1/stream", callouts_stream_url="wss://api-id.cabalspy.xyz/v1/callouts/stream", copy_trading_stream_url="wss://api-id.cabalspy.xyz/v1/copy-trading/stream", + trade_feed_stream_url="wss://api-id.cabalspy.xyz/v1/trade-feed/stream", timeout=30.0, max_retries=2, headers={}, diff --git a/cabalspy_id/__init__.py b/cabalspy_id/__init__.py index 525e060..f18ca99 100644 --- a/cabalspy_id/__init__.py +++ b/cabalspy_id/__init__.py @@ -2,7 +2,8 @@ Login with CabalSpy ID (OpenID Connect), the Data API for verified wallets, KOL badges, trading stats and token theses, white-label platform users, trading -competitions, callouts, copy trading, the live stream, the public thesis API and webhook verification. +competitions, callouts, copy trading, the Trade Feed, the live stream, the public thesis API and +webhook verification. from cabalspy_id import CabalSpyID, CabalSpyIDAuth, verify_webhook @@ -49,6 +50,7 @@ DEFAULT_THESES_STREAM_URL, DEFAULT_THESIS_URL, DEFAULT_THESIS_WS_URL, + DEFAULT_TRADE_FEED_STREAM_URL, FEATURE_CALLOUTS, INBOUND_FORMATS, LEADERBOARD_SORTS, @@ -57,6 +59,8 @@ MAX_OPEN_COMPETITIONS, MAX_REQUEST_BODY_BYTES, MAX_THESES_STREAM_TOKENS, + MAX_TRADE_FEED_STREAMS_PER_KEY, + MAX_TRADE_FEED_TRADERS, PERIODS, PLATFORM_IMPORT_MAX, PLATFORM_MAX_WALLETS_PER_REQUEST, @@ -68,6 +72,11 @@ THESIS_MAX_BODY, THESIS_REPORT_REASONS, THESIS_SCOPES, + TRADE_FEED_CHANGES_PER_HOUR, + TRADE_FEED_FILTERS, + TRADE_FEED_MAX_MIN_NATIVE, + TRADE_FEED_WEBHOOK_EVENTS, + TRADE_LABELS, WALLET_TRUST, WEBHOOK_EVENTS, CalloutCompetitionMetric, @@ -102,6 +111,9 @@ ThesisScope, ThesisSort, ThesisStance, + TradeFeedFilter, + TradeFeedItemType, + TradeLabel, TradingCompetitionMetric, VerificationStatus, WalletTrust, @@ -246,6 +258,21 @@ TrackerResponse, TrackerTrade, Trade, + TradeFeedEvent, + TradeFeedItem, + TradeFeedMinNative, + TradeFeedNotification, + TradeFeedRemoveResult, + TradeFeedSettings, + TradeFeedStreamReady, + TradeFeedThesis, + TradeFeedThesisEvent, + TradeFeedThesisItem, + TradeFeedTrade, + TradeFeedTradeEvent, + TradeFeedTradeItem, + TradeFeedTrader, + TradeFeedTraderResult, TradeOwner, TraderProfile, VerifiedWallet, @@ -282,6 +309,10 @@ def __getattr__(name: str) -> object: from . import _copy_trading_stream return getattr(_copy_trading_stream, name) + if name in ("TradeFeedStream", "TRADE_FEED_STREAM_EVENTS", "TRADE_FEED_EVENTS"): + from . import _trade_feed_stream + + return getattr(_trade_feed_stream, name) raise AttributeError(f"module 'cabalspy_id' has no attribute {name!r}") @@ -294,6 +325,7 @@ def __getattr__(name: str) -> object: "ThesesStream", "CalloutsStream", "CopyTradingStream", + "TradeFeedStream", "Envelope", "CabalSpyIDAuth", "AsyncCabalSpyIDAuth", @@ -553,4 +585,33 @@ def __getattr__(name: str) -> object: "CopyLinks", "CopyInstruction", "CopyTradingStreamReady", + # trade feed + "TRADE_FEED_STREAM_EVENTS", + "TRADE_FEED_EVENTS", + "TRADE_FEED_WEBHOOK_EVENTS", + "TRADE_FEED_FILTERS", + "TRADE_LABELS", + "MAX_TRADE_FEED_TRADERS", + "TRADE_FEED_CHANGES_PER_HOUR", + "TRADE_FEED_MAX_MIN_NATIVE", + "MAX_TRADE_FEED_STREAMS_PER_KEY", + "DEFAULT_TRADE_FEED_STREAM_URL", + "TradeFeedFilter", + "TradeFeedItemType", + "TradeLabel", + "TradeFeedTrade", + "TradeFeedThesis", + "TradeFeedTradeItem", + "TradeFeedThesisItem", + "TradeFeedItem", + "TradeFeedMinNative", + "TradeFeedSettings", + "TradeFeedTrader", + "TradeFeedTraderResult", + "TradeFeedRemoveResult", + "TradeFeedNotification", + "TradeFeedTradeEvent", + "TradeFeedThesisEvent", + "TradeFeedEvent", + "TradeFeedStreamReady", ] diff --git a/cabalspy_id/_client.py b/cabalspy_id/_client.py index 237866d..a1702a6 100644 --- a/cabalspy_id/_client.py +++ b/cabalspy_id/_client.py @@ -42,7 +42,9 @@ DEFAULT_COPY_TRADING_STREAM_URL, DEFAULT_STREAM_URL, DEFAULT_THESES_STREAM_URL, + DEFAULT_TRADE_FEED_STREAM_URL, LEADERBOARD_SORTS, + MAX_TRADE_FEED_TRADERS, PERIODS, PLATFORM_IMPORT_MAX, PLATFORM_MAX_WALLETS_PER_REQUEST, @@ -50,6 +52,8 @@ THESIS_EMOJIS, THESIS_REPORT_REASONS, THESIS_SCOPES, + TRADE_FEED_FILTERS, + TRADE_FEED_MAX_MIN_NATIVE, USER_AGENT, WALLET_TRUST, CalloutSort, @@ -75,6 +79,7 @@ ThesisScope, ThesisSort, ThesisStance, + TradeFeedFilter, WalletTrust, ) from ._errors import ( @@ -96,6 +101,7 @@ from ._copy_trading_stream import CopyTradingStream from ._stream import CabalSpyIDStream from ._theses_stream import ThesesStream + from ._trade_feed_stream import TradeFeedStream _T = TypeVar("_T") @@ -438,6 +444,41 @@ def _copy_instructions_query(external_id: Any, csid_id: Any, status: Any, limit: return {"external_id": external_id, "csid_id": csid_id, "status": status, "limit": limit, "cursor": cursor} +def _limit(limit: Any, high: int) -> None: + if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= high): + raise BadRequestError( + f"limit must be a whole number from 1 to {high}.", code="invalid_parameter", parameter="limit" + ) + + +def _trade_feed_query( + external_id: Any, csid_id: Any, limit: Any, cursor: Any, *, max_limit: int = 100, **extra: Any +) -> dict[str, Any]: + """A Trade Feed read: exactly one user, ``limit`` 1-``max_limit``.""" + who = _who(external_id, csid_id) + _limit(limit, max_limit) + return {**who, **extra, "limit": limit, "cursor": cursor} + + +def _trade_feed_settings(**fields: Any) -> dict[str, Any]: + """Alert settings for one trader; None = not sent (unchanged, or the user's defaults).""" + out = {k: v for k, v in fields.items() if v is not None} + for k in ("notify_buys", "notify_sells", "notify_theses", "muted"): + if k in out and not isinstance(out[k], bool): + raise BadRequestError(f"{k} must be True or False.", code="invalid_parameter", parameter=k) + for k in ("min_sol", "min_bnb", "min_eth"): + v = out.get(k) + if k in out and ( + isinstance(v, bool) or not isinstance(v, (int, float)) or not 0 <= v <= TRADE_FEED_MAX_MIN_NATIVE + ): + raise BadRequestError( + f"{k} must be a number from 0 to {TRADE_FEED_MAX_MIN_NATIVE:,} (0 = every trade).", + code="invalid_parameter", + parameter=k, + ) + return out + + def _import_items(users: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]: if isinstance(users, (str, Mapping)): raise BadRequestError("users must be a list of users.", code="invalid_parameter", parameter="users") @@ -1646,6 +1687,129 @@ def report_copy_instruction( body["note"] = note return self._post("/copy-trading/instructions/status", body) + # ── trade feed ─────────────────────────────────────────────────────── + # A user's Trade Feed: the traders they follow, every trade and thesis of them, + # alerts and the copy settings. Everything acts in the name of one user (positional + # ``external_id`` for a platform user, or ``csid_id=``) who signed in to your app with + # the scope trade_feed (else PermissionError consent_required) and is within your + # plan's user limit (an ``anon_`` id raises PlanUserLimitError plan_user_limit). An + # unknown external_id raises NotFoundError platform_user_not_found. + + def trade_feed( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + filter: TradeFeedFilter | None = None, + limit: int | None = None, + cursor: str | None = None, + ) -> Any: + """GET /v1/trade-feed — the user's Trade Feed, newest first: every trade and thesis + of the traders in it (traders who keep their trading private are left out). + + ``filter``: all (default), buys, sells or theses; ``limit`` 1-100 (default 30). + Returns a list of :data:`~cabalspy_id.TradeFeedItem` (``type`` trade or thesis); + see ``iter_trade_feed``. + """ + _one_of(filter, TRADE_FEED_FILTERS, "filter") + return self._get("/trade-feed", _trade_feed_query(external_id, csid_id, limit, cursor, filter=filter)) + + def trade_feed_traders( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + limit: int | None = None, + cursor: str | None = None, + ) -> Any: + """GET /v1/trade-feed/traders — the traders in the user's Trade Feed, most recently + added first, with the user's alert and copy settings for each (``limit`` 1-300, + default 100). The envelope's pagination (``get_raw``) has ``total`` and ``max`` (300). + + Returns a list of :class:`~cabalspy_id.TradeFeedTrader`; see ``iter_trade_feed_traders``. + """ + return self._get( + "/trade-feed/traders", + _trade_feed_query(external_id, csid_id, limit, cursor, max_limit=MAX_TRADE_FEED_TRADERS), + ) + + def add_trade_feed_trader( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + trader: str | None = None, + trader_external_id: str | None = None, + notify_buys: bool | None = None, + notify_sells: bool | None = None, + notify_theses: bool | None = None, + min_sol: float | None = None, + min_bnb: float | None = None, + min_eth: float | None = None, + muted: bool | None = None, + ) -> Any: + """POST /v1/trade-feed/traders — adds a trader (handle with or without @, or csid_id; + ``trader_external_id`` for one of your platform users) to the user's Trade Feed, with + the user's default alert settings unless you pass others. When the trader is already + there, the settings you pass are updated (None = unchanged). + + ``min_sol`` / ``min_bnb`` / ``min_eth``: minimum trade size for alerts, 0-1,000,000 + (0 = every trade); ``muted``: no alerts for this trader. + + Returns :class:`~cabalspy_id.TradeFeedTraderResult` (``created`` True and HTTP 201 + when the trader was added). Raises BadRequestError ``cannot_add_self``, + PermissionError ``trading_private``, NotFoundError ``trader_not_found``, + ConflictError ``trade_feed_full`` (300 traders) and RateLimitError ``rate_limited`` + (more than 120 changes in an hour; not retried). + """ + who = _who(external_id, csid_id) + target = _copy_trader(trader, trader_external_id, required=True) + settings = _trade_feed_settings( + notify_buys=notify_buys, + notify_sells=notify_sells, + notify_theses=notify_theses, + min_sol=min_sol, + min_bnb=min_bnb, + min_eth=min_eth, + muted=muted, + ) + return self._post("/trade-feed/traders", {**who, **target, **settings}) + + def remove_trade_feed_trader( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + trader: str | None = None, + trader_external_id: str | None = None, + ) -> Any: + """POST /v1/trade-feed/traders/delete — removes a trader from the user's Trade Feed; + this also ends copying of that trader. + + Returns :class:`~cabalspy_id.TradeFeedRemoveResult` (``removed`` False when the + trader was not in the Trade Feed). + """ + who = _who(external_id, csid_id) + target = _copy_trader(trader, trader_external_id, required=True) + return self._post("/trade-feed/traders/delete", {**who, **target}) + + def trade_feed_notifications( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + limit: int | None = None, + cursor: str | None = None, + ) -> Any: + """GET /v1/trade-feed/notifications — the user's recent Trade Feed alerts, newest + first: every trade and thesis that passed the user's filters for that trader + (``limit`` 1-100, default 50). For an alert inbox without webhooks. + + Returns a list of :class:`~cabalspy_id.TradeFeedNotification`; see + ``iter_trade_feed_notifications``. + """ + return self._get("/trade-feed/notifications", _trade_feed_query(external_id, csid_id, limit, cursor)) + # ═══════════════════════════════════════════════════════════════════════════ # CLIENTS @@ -1663,6 +1827,7 @@ def __init__( theses_stream_url: str | None = None, callouts_stream_url: str | None = None, copy_trading_stream_url: str | None = None, + trade_feed_stream_url: str | None = None, timeout: float = 30.0, max_retries: int = 2, headers: Mapping[str, str] | None = None, @@ -1677,6 +1842,7 @@ def __init__( self.theses_stream_url = (theses_stream_url or DEFAULT_THESES_STREAM_URL).rstrip("/") self.callouts_stream_url = (callouts_stream_url or DEFAULT_CALLOUTS_STREAM_URL).rstrip("/") self.copy_trading_stream_url = (copy_trading_stream_url or DEFAULT_COPY_TRADING_STREAM_URL).rstrip("/") + self.trade_feed_stream_url = (trade_feed_stream_url or DEFAULT_TRADE_FEED_STREAM_URL).rstrip("/") self.timeout = timeout self.max_retries = max_retries self._extra_headers = dict(headers or {}) @@ -1825,6 +1991,19 @@ def copy_trading_stream(self, **kwargs: Any) -> CopyTradingStream: return CopyTradingStream(self.copy_trading_stream_url, self._api_key, instance=self.instance, **kwargs) + def trade_feed_stream(self, **kwargs: Any) -> TradeFeedStream: + """Every new trade and thesis that concerns your users, live (``trade_feed.trade``, + ``trade_feed.thesis``; ``data`` adds ``recipients`` and ``recipients_external``). + Async only. + + Needs the ``stream`` extra: ``pip install "cabalspy-id[stream]"``. + """ + if not self._api_key: + raise AuthenticationError("The Trade Feed stream needs an API key.", status=401, code="missing_api_key") + from ._trade_feed_stream import TradeFeedStream + + return TradeFeedStream(self.trade_feed_stream_url, self._api_key, instance=self.instance, **kwargs) + class CabalSpyID(_BaseClient): """Synchronous Data API client. @@ -2118,6 +2297,36 @@ def iter_copy_instructions( for page in self.pages("/copy-trading/instructions", query): yield from page.data + # ── trade feed ─────────────────────────────────────────────────────── + + def iter_trade_feed( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + filter: TradeFeedFilter | None = None, + limit: int | None = None, + ) -> Iterator[dict[str, Any]]: + """Every item of the user's Trade Feed, newest first, following ``next_cursor``.""" + _one_of(filter, TRADE_FEED_FILTERS, "filter") + for page in self.pages("/trade-feed", _trade_feed_query(external_id, csid_id, limit, None, filter=filter)): + yield from page.data + + def iter_trade_feed_traders( + self, external_id: str | None = None, *, csid_id: str | None = None, limit: int | None = None + ) -> Iterator[dict[str, Any]]: + """Every trader in the user's Trade Feed, most recently added first, following ``next_cursor``.""" + query = _trade_feed_query(external_id, csid_id, limit, None, max_limit=MAX_TRADE_FEED_TRADERS) + for page in self.pages("/trade-feed/traders", query): + yield from page.data + + def iter_trade_feed_notifications( + self, external_id: str | None = None, *, csid_id: str | None = None, limit: int | None = None + ) -> Iterator[dict[str, Any]]: + """Every Trade Feed alert of the user, newest first, following ``next_cursor``.""" + for page in self.pages("/trade-feed/notifications", _trade_feed_query(external_id, csid_id, limit, None)): + yield from page.data + class AsyncCabalSpyID(_BaseClient): """Asynchronous Data API client. @@ -2409,6 +2618,41 @@ async def iter_copy_instructions( for item in page.data: yield item + # ── trade feed ─────────────────────────────────────────────────────── + + async def iter_trade_feed( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + filter: TradeFeedFilter | None = None, + limit: int | None = None, + ) -> AsyncIterator[dict[str, Any]]: + """Every item of the user's Trade Feed, newest first, following ``next_cursor``.""" + _one_of(filter, TRADE_FEED_FILTERS, "filter") + query = _trade_feed_query(external_id, csid_id, limit, None, filter=filter) + async for page in self.pages("/trade-feed", query): + for item in page.data: + yield item + + async def iter_trade_feed_traders( + self, external_id: str | None = None, *, csid_id: str | None = None, limit: int | None = None + ) -> AsyncIterator[dict[str, Any]]: + """Every trader in the user's Trade Feed, most recently added first, following ``next_cursor``.""" + query = _trade_feed_query(external_id, csid_id, limit, None, max_limit=MAX_TRADE_FEED_TRADERS) + async for page in self.pages("/trade-feed/traders", query): + for item in page.data: + yield item + + async def iter_trade_feed_notifications( + self, external_id: str | None = None, *, csid_id: str | None = None, limit: int | None = None + ) -> AsyncIterator[dict[str, Any]]: + """Every Trade Feed alert of the user, newest first, following ``next_cursor``.""" + query = _trade_feed_query(external_id, csid_id, limit, None) + async for page in self.pages("/trade-feed/notifications", query): + for item in page.data: + yield item + def _users_query(params: Mapping[str, Any]) -> dict[str, Any]: allowed = {"limit", "kol", "cursor", "scope"} diff --git a/cabalspy_id/_constants.py b/cabalspy_id/_constants.py index edc6680..288ade2 100644 --- a/cabalspy_id/_constants.py +++ b/cabalspy_id/_constants.py @@ -4,7 +4,7 @@ from typing import Literal -SDK_VERSION = "0.8.0" +SDK_VERSION = "0.9.0" USER_AGENT = f"cabalspy-id-python/{SDK_VERSION}" DEFAULT_BASE_URL = "https://api-id.cabalspy.xyz/v1" @@ -66,6 +66,10 @@ #: Webhook events about copy trading: one ``copy_trade.instruction`` per user and copied #: trade; ``data`` is the instruction plus ``external_id`` (white-label, else None). COPY_TRADING_WEBHOOK_EVENTS: tuple[str, ...] = ("copy_trade.instruction",) +#: Webhook events about the Trade Feed: one per trade or thesis of a trader in your users' +#: Trade Feeds (not one per user); ``data`` is the feed item plus ``recipients`` (csid_ids) +#: and ``recipients_external`` (your external_ids). +TRADE_FEED_WEBHOOK_EVENTS: tuple[str, ...] = ("trade_feed.trade", "trade_feed.thesis") #: Webhook event types. WEBHOOK_EVENTS: tuple[str, ...] = ( "wallet.verified", @@ -81,6 +85,7 @@ *COMPETITION_WEBHOOK_EVENTS, *CALLOUT_WEBHOOK_EVENTS, *COPY_TRADING_WEBHOOK_EVENTS, + *TRADE_FEED_WEBHOOK_EVENTS, ) #: Reactions: "like" plus a fixed emoji set. @@ -236,3 +241,24 @@ COPY_DEFAULT_SLIPPAGE_BPS = 300 #: Copy trading stream connections per API key. MAX_COPY_TRADING_STREAMS_PER_KEY = 5 + +# ── trade feed ─────────────────────────────────────────────────────────────── + +DEFAULT_TRADE_FEED_STREAM_URL = "wss://api-id.cabalspy.xyz/v1/trade-feed/stream" +#: all: trades and theses; buys / sells: only those trades; theses: only theses. +TradeFeedFilter = Literal["all", "buys", "sells", "theses"] +TRADE_FEED_FILTERS: tuple[TradeFeedFilter, ...] = ("all", "buys", "sells", "theses") +#: A feed item's type. +TradeFeedItemType = Literal["trade", "thesis"] +#: What a trade did to the trader's position: new (first buy), add (bought more), partial +#: (sold part, see ``sold_percent``), close (sold everything), sell (a sell without a known buy). +TradeLabel = Literal["new", "add", "partial", "close", "sell"] +TRADE_LABELS: tuple[TradeLabel, ...] = ("new", "add", "partial", "close", "sell") +#: Traders per Trade Feed. +MAX_TRADE_FEED_TRADERS = 300 +#: Changes (adding traders) per user and hour; more raise RateLimitError ``rate_limited``. +TRADE_FEED_CHANGES_PER_HOUR = 120 +#: Upper bound of ``min_sol`` / ``min_bnb`` / ``min_eth`` (0 = every trade). +TRADE_FEED_MAX_MIN_NATIVE = 1_000_000 +#: Trade Feed stream connections per API key. +MAX_TRADE_FEED_STREAMS_PER_KEY = 5 diff --git a/cabalspy_id/_errors.py b/cabalspy_id/_errors.py index 0c62c52..b51ef4d 100644 --- a/cabalspy_id/_errors.py +++ b/cabalspy_id/_errors.py @@ -80,7 +80,8 @@ def __str__(self) -> str: class BadRequestError(CabalSpyIDError): """400 — missing_parameter, invalid_parameter, instance_required; platform users: - wallet_required, invalid_address, invalid_return_url, invalid_body. + wallet_required, invalid_address, invalid_return_url, invalid_body; Trade Feed: + cannot_add_self (the user tried to add themselves). Also 422 — callouts: no_price (the token has no market price yet, so a callout could not be tracked). ``status`` keeps the real HTTP status. @@ -99,8 +100,9 @@ class PermissionError_(CabalSpyIDError): per instance on request), invalid_account, kol_only, not_a_holder, posting_paused, consent_required, sandbox_user. - Copy trading: consent_required (the user has not allowed your app the scope - trade_feed), trading_private. + Copy trading and Trade Feed: consent_required (the user has not allowed your app + the scope trade_feed, or is beyond the plan's user limit), trading_private (the + trader keeps their trading private). """ @@ -120,7 +122,9 @@ class NotFoundError(CabalSpyIDError): """404 — profile_not_found, wallet_not_found, instance_not_found; platform users: platform_user_not_found, verification_not_found, invalid_inbound_url; competitions: competition_not_found; callouts: callout_not_found; copy trading: - trader_not_found, not_in_trade_feed, not_found (no such instruction for your instance).""" + trader_not_found, not_in_trade_feed, not_found (no such instruction for your instance); + Trade Feed: trader_not_found, platform_user_not_found (unknown external_id or + trader_external_id).""" class ConflictError(CabalSpyIDError): @@ -133,6 +137,7 @@ class ConflictError(CabalSpyIDError): (the user called this token less than 24 hours ago). Copy trading: copy_managed_elsewhere (another platform copies this trader for the user), already_reported (the instruction already has another final status), trade_feed_full. + Trade Feed: trade_feed_full (the Trade Feed has the maximum of 300 traders). """ @@ -141,7 +146,8 @@ class RateLimitError(CabalSpyIDError): platform users: rate_limited (new users or inbound events per minute), too_many_open_verifications; callouts: callout_cooldown (the instance's cooldown between two callouts of a user; ``retry_after`` can be hours, so it is never - retried automatically); streams: too_many_connections.""" + retried automatically); Trade Feed: rate_limited (more than 120 changes of a + user's Trade Feed in an hour; not retried); streams: too_many_connections.""" def __init__(self, message: str, *, retry_after: float | None = None, **kwargs: Any) -> None: super().__init__(message, **kwargs) diff --git a/cabalspy_id/_trade_feed_stream.py b/cabalspy_id/_trade_feed_stream.py new file mode 100644 index 0000000..cf6e027 --- /dev/null +++ b/cabalspy_id/_trade_feed_stream.py @@ -0,0 +1,364 @@ +"""Trade Feed stream: wss://api-id.cabalspy.xyz/v1/trade-feed/stream. + +Every new trade and thesis that concerns your users, live (``trade_feed.trade``, +``trade_feed.thesis``). ``data`` is the feed item plus ``recipients`` (the csid_ids of +your users to tell: the trader is in their Trade Feed and their filters let the +event through) and ``recipients_external`` (your own user ids of those who are +platform users). The same events arrive as webhooks; events made while you were +disconnected are not replayed (read ``trade_feed_notifications()`` to catch up). + + async with AsyncCabalSpyID() as csid: + tf = csid.trade_feed_stream() + + @tf.on("trade_feed.trade") + async def _(item): + t = item["trade"] + for user in item["recipients_external"]: + notify(user, f"{item['trader']['username']} {t['side']} {t['symbol']}") + + await tf.connect() # returns on "ready" + await tf.run_forever() + + # or iterate ({"event": ..., "id": ..., "data": ...}): + async with csid.trade_feed_stream() as tf: + async for ev in tf: + ... +""" + +from __future__ import annotations + +import asyncio +import contextlib +import inspect +import json +import random +from collections.abc import AsyncIterator, Callable +from typing import Any, TypeVar, overload +from urllib.parse import urlencode + +from ._errors import APIConnectionError, BadRequestError, CabalSpyIDError, PermissionError_, RateLimitError + +try: + import websockets +except ImportError: # pragma: no cover + websockets = None # type: ignore[assignment] + +Handler = Callable[[Any], Any] +H = TypeVar("H", bound=Callable[[Any], Any]) + +#: The Trade Feed events: trade_feed.trade and trade_feed.thesis (the feed item plus +#: recipients and recipients_external). +TRADE_FEED_EVENTS = ("trade_feed.trade", "trade_feed.thesis") +#: Events: ready, the Trade Feed events, heartbeat, pong, open, close, reconnecting, error. +TRADE_FEED_STREAM_EVENTS = ( + "ready", + *TRADE_FEED_EVENTS, + "heartbeat", + "pong", + "open", + "close", + "reconnecting", + "error", +) + + +def _refused(code: str, message: str) -> CabalSpyIDError: + if code == "invalid_parameter": + return BadRequestError(message, code=code, status=400) + if code == "too_many_connections": + return RateLimitError(message, code=code, status=429) + return PermissionError_(message, code=code, status=403) + + +class TradeFeedStream: + """Async client for the Trade Feed stream. Obtain one via ``client.trade_feed_stream()``.""" + + def __init__( + self, + url: str, + api_key: str, + *, + instance: str | None = None, + reconnect: bool = True, + reconnect_delay: float = 1.0, + max_reconnect_delay: float = 30.0, + heartbeat_timeout: float | None = 75.0, + open_timeout: float = 20.0, + ) -> None: + if websockets is None: # pragma: no cover + raise ImportError('The Trade Feed stream needs the websockets package: pip install "cabalspy-id[stream]"') + extra = {"instance": instance} if instance else {} + self._url = f"{url}?{urlencode({'api_key': api_key, **extra})}" + #: The URL with the key masked, safe to log. + self.safe_url = f"{url}?{urlencode({'api_key': '***', **extra}, safe='*')}" + self.reconnect = reconnect + self.reconnect_delay = reconnect_delay + self.max_reconnect_delay = max_reconnect_delay + self.heartbeat_timeout = heartbeat_timeout + self.open_timeout = open_timeout + + self._ws: Any = None + self._ready = False + self._handlers: dict[str, list[Handler]] = {} + self._attempt = 0 + self._closed = False + self._fatal: CabalSpyIDError | None = None + self._reader: asyncio.Task[None] | None = None + self._ready_future: asyncio.Future[dict[str, Any]] | None = None + self._done = asyncio.Event() + self._backlog: list[Any] | None = None + # Internal listeners for whole events ({"event", "id", "data"}): the backlog and iterators. + self._listeners: list[Handler] = [] + + # ── handlers ───────────────────────────────────────────────────────── + + @overload + def on(self, event: str) -> Callable[[H], H]: ... + + @overload + def on(self, event: str, handler: H) -> H: ... + + def on(self, event: str, handler: Handler | None = None) -> Any: + """Registers a handler (sync or async). Usable directly or as a decorator. + + ``trade_feed.trade`` / ``trade_feed.thesis`` handlers get the event's ``data``: the + feed item (its ``id`` is the trade's or thesis' id) plus ``recipients`` and + ``recipients_external``. + """ + if event not in TRADE_FEED_STREAM_EVENTS: + raise ValueError(f"unknown event {event!r}; one of {', '.join(TRADE_FEED_STREAM_EVENTS)}") + + def register(fn: Handler) -> Handler: + self._handlers.setdefault(event, []).append(fn) + return fn + + return register if handler is None else register(handler) + + def off(self, event: str, handler: Handler) -> None: + if handler in self._handlers.get(event, []): + self._handlers[event].remove(handler) + + async def _emit(self, event: str, payload: Any) -> None: + for handler in list(self._handlers.get(event, [])): + try: + result = handler(payload) + if inspect.isawaitable(result): + await result + except Exception as exc: + if event != "error": + await self._emit("error", exc) + + # ── connection ─────────────────────────────────────────────────────── + + @property + def connected(self) -> bool: + return self._ws is not None and self._ready + + async def connect(self) -> dict[str, Any]: + """Opens the socket. Returns the ``ready`` data (``events``).""" + self._closed = False + self._fatal = None + self._ready = False + self._done.clear() + self._ready_future = asyncio.get_running_loop().create_future() + try: + ws = await websockets.connect(self._url, open_timeout=self.open_timeout) + except Exception as exc: + raise APIConnectionError(f"Could not connect to {self.safe_url}: {exc}", code="ws_error") from exc + self._ws = ws + await self._emit("open", None) + self._reader = asyncio.create_task(self._read(ws, self._ready_future)) + return await self._ready_future + + async def _read(self, ws: Any, ready: asyncio.Future[dict[str, Any]]) -> None: + info: dict[str, Any] = {} + try: + while True: + try: + if self.heartbeat_timeout: + raw = await asyncio.wait_for(ws.recv(), timeout=self.heartbeat_timeout) + else: + raw = await ws.recv() + except asyncio.TimeoutError: + await self._emit( + "error", + APIConnectionError( + "No heartbeat from the Trade Feed stream; reconnecting", code="heartbeat_timeout" + ), + ) + with contextlib.suppress(Exception): + await ws.close(code=4000, reason="heartbeat timeout") + break + try: + msg = json.loads(raw) + except (ValueError, TypeError): + continue + if isinstance(msg, dict): + await self._dispatch(msg, ready) + except websockets.ConnectionClosed as exc: + rcvd = getattr(exc, "rcvd", None) + info = {"code": getattr(rcvd, "code", None), "reason": getattr(rcvd, "reason", "")} + except asyncio.CancelledError: + raise + except Exception as exc: + await self._emit("error", exc) + finally: + if self._ws is ws: + self._ws = None + self._ready = False + await self._emit("close", info) + if not ready.done(): + ready.set_exception( + self._fatal + or APIConnectionError( + f"Trade Feed stream closed before it was ready (code {info.get('code')})", code="ws_closed_early" + ) + ) + if not self._closed and not self._fatal and self.reconnect: + await self._reconnect() + else: + self._done.set() + + async def _dispatch(self, msg: dict[str, Any], ready: asyncio.Future[dict[str, Any]]) -> None: + event = msg.get("event") + if event == "ready": + self._ready = True + self._attempt = 0 + data = msg.get("data") or {} + await self._emit("ready", data) + if not ready.done(): + ready.set_result(data) + elif event in TRADE_FEED_EVENTS: + data = msg.get("data") + await self._emit(str(event), data) + item = {"event": str(event), "id": msg.get("id"), "data": data} + for listener in list(self._listeners): + listener(item) + elif event == "heartbeat": + await self._emit("heartbeat", {"ts": msg.get("ts")}) + elif event == "pong": + await self._emit("pong", {}) + elif event == "error": + err = msg.get("error") or {} + code, message = str(err.get("code") or "stream_error"), str(err.get("message") or "Stream error") + exc = _refused(code, message) + if not self._ready: + # Refused before ready (invalid_api_key, ...): the server closes the socket. + # Only too_many_connections is worth reconnecting for. + if code != "too_many_connections": + self._fatal = exc + if not ready.done(): + ready.set_exception(exc) + await self._emit("error", exc) + + async def _reconnect(self) -> None: + while not self._closed: + delay = min(self.reconnect_delay * (2**self._attempt), self.max_reconnect_delay) + random.random() * 0.25 + self._attempt += 1 + await self._emit("reconnecting", {"attempt": self._attempt, "delay": delay}) + await asyncio.sleep(delay) + if self._closed: + break + try: + await self.connect() + return + except CabalSpyIDError as exc: + await self._emit("error", exc) + if self._fatal: + break + if self._ws is not None or (self._reader and not self._reader.done()): + return + self._done.set() + + async def ping(self) -> None: + """Sends a ping (answered with ``pong``).""" + if self._ws is not None: + await self._ws.send(json.dumps({"op": "ping"})) + + async def run_forever(self) -> None: + """Blocks until :meth:`close` is called or a fatal error stops the stream (raised).""" + await self._done.wait() + if self._fatal: + raise self._fatal + + async def close(self) -> None: + """Closes the socket and stops reconnecting.""" + self._closed = True + ws, self._ws = self._ws, None + self._ready = False + if ws is not None: + with contextlib.suppress(Exception): + await ws.close() + task = self._reader + if task and not task.done() and task is not asyncio.current_task(): + try: + await asyncio.wait_for(asyncio.shield(task), timeout=2) + except (asyncio.TimeoutError, Exception): + task.cancel() + self._done.set() + + async def __aenter__(self) -> TradeFeedStream: + # Events that arrive between connecting and the first loop are kept for it. + self._backlog = [] + self._listeners.append(self._backlog.append) + try: + await self.connect() + except BaseException: + self._drop_backlog() + raise + return self + + async def __aexit__(self, *exc: Any) -> None: + await self.close() + + def _drop_backlog(self) -> list[Any]: + backlog, self._backlog = self._backlog, None + if backlog is None: + return [] + with contextlib.suppress(ValueError): + self._listeners.remove(backlog.append) + return backlog + + async def __aiter__(self) -> AsyncIterator[dict[str, Any]]: + """Iterates over the events as ``{"event": ..., "id": ..., "data": ...}`` (``id`` is the + event id); connects if needed. + + Ends when :meth:`close` is called, or raises the fatal error. ``break`` + does not close the socket by itself: use ``async with`` or call :meth:`close`. + """ + queue: asyncio.Queue[Any] = asyncio.Queue() + stop = object() + for item in self._drop_backlog(): + queue.put_nowait(item) + + listener: Handler = queue.put_nowait + + def on_error(_exc: Any) -> None: + if self._fatal: + queue.put_nowait(stop) + + def on_close(_info: Any) -> None: + if self._closed or not self.reconnect: + queue.put_nowait(stop) + + self._listeners.append(listener) + self.on("error", on_error) + self.on("close", on_close) + owns = self._ws is None + try: + if owns: + await self.connect() + while True: + item = await queue.get() + if item is stop: + if self._fatal: + raise self._fatal + return + yield item + finally: + with contextlib.suppress(ValueError): + self._listeners.remove(listener) + self.off("error", on_error) + self.off("close", on_close) + if owns and not self._closed: + await self.close() diff --git a/cabalspy_id/_types.py b/cabalspy_id/_types.py index d657b96..96e27a7 100644 --- a/cabalspy_id/_types.py +++ b/cabalspy_id/_types.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Any, Literal, TypedDict +from typing import Any, Literal, TypeAlias, TypedDict from ._constants import ( CalloutFirstDayKind, @@ -36,6 +36,8 @@ PlatformImportStatus, PlatformWalletStatus, Scope, + ThesisStance, + TradeLabel, VerificationStatus, WalletTrust, ) @@ -1585,3 +1587,170 @@ class CopyInstruction(_CopyInstructionOptional): class CopyTradingStreamReady(TypedDict): events: list[str] + + +# ── trade feed ─────────────────────────────────────────────────────────────── + + +class TradeFeedTrade(TypedDict): + """A trade in the Trade Feed (``item["trade"]``).""" + + blockchain: Chain + mint: str + symbol: str | None + name: str | None + logo: str | None + side: CopySide + #: new, add, partial, close or sell. + label: TradeLabel + #: partial: the share of the position sold, 0-100; else None. + sold_percent: float | None + #: Trade size in the chain's native coin (``currency``). + amount_native: float + currency: Currency | None + amount_usd: float | None + token_amount: float | None + price_usd: float | None + #: Sells with a known entry: realized PnL of this sell against the average entry. + pnl_usd: float | None + pnl_percent: float | None + wallet: str + wallet_url: str | None + tx_signature: str + tx_url: str | None + + +class TradeFeedThesis(TypedDict): + """A thesis in the Trade Feed (``item["thesis"]``).""" + + id: str + blockchain: Chain + mint: str + symbol: str | None + name: str | None + logo: str | None + stance: ThesisStance | None + body: str + likes: int + replies: int + url: str + + +class _TradeFeedItemOptional(TypedDict, total=False): + #: GET /v1/trade-feed only: the item's position in the feed. + cursor: str + + +class TradeFeedTradeItem(_TradeFeedItemOptional): + """A trade item: the same ``id`` everywhere (feed, webhook, stream, notifications).""" + + id: str + type: Literal["trade"] + timestamp: str + trader: CopyTrader + trade: TradeFeedTrade + #: token (the CabalSpy Terminal on Solana and BNB Chain, else the token's theses), + #: terminal (None outside Solana and BNB Chain), profile. + links: CopyLinks + + +class TradeFeedThesisItem(_TradeFeedItemOptional): + """A thesis item; ``id`` is ``"h"`` followed by the thesis id.""" + + id: str + type: Literal["thesis"] + timestamp: str + trader: CopyTrader + thesis: TradeFeedThesis + links: CopyLinks + + +#: GET /v1/trade-feed: a trade or a thesis (check ``item["type"]``). +TradeFeedItem: TypeAlias = TradeFeedTradeItem | TradeFeedThesisItem + + +class TradeFeedMinNative(TypedDict): + """Minimum trade size for alerts per native coin (0 = every trade).""" + + SOL: float + BNB: float + ETH: float + + +class TradeFeedSettings(TypedDict): + """A user's alert settings for one trader, plus the copy settings.""" + + notify_buys: bool + notify_sells: bool + notify_theses: bool + min_native: TradeFeedMinNative + #: No alerts for this trader. + muted: bool + #: How the user copies this trader (see copy trading). + copy: CopySettings + + +class TradeFeedTrader(TypedDict): + """GET /v1/trade-feed/traders: one trader in the user's Trade Feed.""" + + trader: CopyTrader + #: False while the trader keeps their trading private: they stay in the list, but + #: nothing of them shows in the feed. + trading_public: bool + added_at: str + #: In how many Trade Feeds the trader is. + in_trade_feeds: int + settings: TradeFeedSettings + + +class TradeFeedTraderResult(TypedDict): + """POST /v1/trade-feed/traders (HTTP 201 when added, 200 when already there).""" + + in_trade_feed: Literal[True] + #: True when the trader was added, False when they were already in the Trade Feed. + created: bool + trader: CopyTrader + settings: TradeFeedSettings + + +class TradeFeedRemoveResult(TypedDict): + """POST /v1/trade-feed/traders/delete.""" + + in_trade_feed: Literal[False] + #: False when the trader was not in the Trade Feed. + removed: bool + + +class TradeFeedNotification(TypedDict): + """GET /v1/trade-feed/notifications: an alert that passed the user's filters.""" + + id: int + #: trade_feed.trade or trade_feed.thesis. + event: str + #: A ready-made line in plain text. + text: str | None + created_at: str + data: TradeFeedItem + + +class _TradeFeedRecipients(TypedDict): + #: csid_ids of your users to tell (trader in their Trade Feed, filters passed). + recipients: list[str] + #: Your own user ids (external_id) of the recipients who are platform users. + recipients_external: list[str] + + +class TradeFeedTradeEvent(TradeFeedTradeItem, _TradeFeedRecipients): + """``data`` of the webhook and stream event ``trade_feed.trade``.""" + + +class TradeFeedThesisEvent(TradeFeedThesisItem, _TradeFeedRecipients): + """``data`` of the webhook and stream event ``trade_feed.thesis``.""" + + +#: ``data`` of a Trade Feed webhook or stream event. +TradeFeedEvent: TypeAlias = TradeFeedTradeEvent | TradeFeedThesisEvent + + +class TradeFeedStreamReady(TypedDict): + events: list[str] diff --git a/cabalspy_id/api.py b/cabalspy_id/api.py index 0249991..f7b6c4b 100644 --- a/cabalspy_id/api.py +++ b/cabalspy_id/api.py @@ -1,7 +1,7 @@ """``cabalspy_id.api`` — the SocialFi API: Data API clients (users, profiles, verified wallets, trading stats, leaderboards, white-label platform users, -trading competitions, callouts and copy trading), the live trade, callout and -copy trading streams, Login with CabalSpy ID (OpenID Connect) and webhook +trading competitions, callouts, copy trading and the Trade Feed), the live trade, +callout, copy trading and Trade Feed streams, Login with CabalSpy ID (OpenID Connect) and webhook verification. from cabalspy_id.api import CabalSpyID, CabalSpyIDAuth, verify_webhook @@ -42,6 +42,7 @@ DEFAULT_COPY_TRADING_STREAM_URL, DEFAULT_ISSUER, DEFAULT_STREAM_URL, + DEFAULT_TRADE_FEED_STREAM_URL, FEATURE_CALLOUTS, INBOUND_FORMATS, LEADERBOARD_SORTS, @@ -49,6 +50,8 @@ MAX_COPY_TRADING_STREAMS_PER_KEY, MAX_OPEN_COMPETITIONS, MAX_REQUEST_BODY_BYTES, + MAX_TRADE_FEED_STREAMS_PER_KEY, + MAX_TRADE_FEED_TRADERS, PERIODS, PLATFORM_IMPORT_MAX, PLATFORM_MAX_WALLETS_PER_REQUEST, @@ -56,6 +59,11 @@ SCOPES, SDK_VERSION, STREAM_TOPICS, + TRADE_FEED_CHANGES_PER_HOUR, + TRADE_FEED_FILTERS, + TRADE_FEED_MAX_MIN_NATIVE, + TRADE_FEED_WEBHOOK_EVENTS, + TRADE_LABELS, WALLET_TRUST, WEBHOOK_EVENTS, ActiveHoldings, @@ -209,6 +217,24 @@ TrackerResponse, TrackerTrade, Trade, + TradeFeedEvent, + TradeFeedFilter, + TradeFeedItem, + TradeFeedItemType, + TradeFeedMinNative, + TradeFeedNotification, + TradeFeedRemoveResult, + TradeFeedSettings, + TradeFeedStreamReady, + TradeFeedThesis, + TradeFeedThesisEvent, + TradeFeedThesisItem, + TradeFeedTrade, + TradeFeedTradeEvent, + TradeFeedTradeItem, + TradeFeedTrader, + TradeFeedTraderResult, + TradeLabel, TradeOwner, TraderProfile, TradingCompetitionMetric, @@ -468,15 +494,46 @@ "CopyLinks", "CopyInstruction", "CopyTradingStreamReady", + # trade feed + "TradeFeedStream", + "TRADE_FEED_STREAM_EVENTS", + "TRADE_FEED_EVENTS", + "TRADE_FEED_WEBHOOK_EVENTS", + "TRADE_FEED_FILTERS", + "TRADE_LABELS", + "MAX_TRADE_FEED_TRADERS", + "TRADE_FEED_CHANGES_PER_HOUR", + "TRADE_FEED_MAX_MIN_NATIVE", + "MAX_TRADE_FEED_STREAMS_PER_KEY", + "DEFAULT_TRADE_FEED_STREAM_URL", + "TradeFeedFilter", + "TradeFeedItemType", + "TradeLabel", + "TradeFeedTrade", + "TradeFeedThesis", + "TradeFeedTradeItem", + "TradeFeedThesisItem", + "TradeFeedItem", + "TradeFeedMinNative", + "TradeFeedSettings", + "TradeFeedTrader", + "TradeFeedTraderResult", + "TradeFeedRemoveResult", + "TradeFeedNotification", + "TradeFeedTradeEvent", + "TradeFeedThesisEvent", + "TradeFeedEvent", + "TradeFeedStreamReady", ] _LAZY_CALLOUTS = ("CalloutsStream", "CALLOUTS_STREAM_EVENTS", "CALLOUT_EVENTS") _LAZY_COPY_TRADING = ("CopyTradingStream", "COPY_TRADING_STREAM_EVENTS", "COPY_TRADING_EVENTS") +_LAZY_TRADE_FEED = ("TradeFeedStream", "TRADE_FEED_STREAM_EVENTS", "TRADE_FEED_EVENTS") def __getattr__(name: str) -> Any: # The stream needs the optional websockets dependency: loaded lazily, like the root package. - if name in ("CabalSpyIDStream", "STREAM_EVENTS", *_LAZY_CALLOUTS, *_LAZY_COPY_TRADING): + if name in ("CabalSpyIDStream", "STREAM_EVENTS", *_LAZY_CALLOUTS, *_LAZY_COPY_TRADING, *_LAZY_TRADE_FEED): return getattr(_root, name) raise AttributeError(f"module 'cabalspy_id.api' has no attribute {name!r}") diff --git a/examples/trade_feed.py b/examples/trade_feed.py new file mode 100644 index 0000000..dc4e93f --- /dev/null +++ b/examples/trade_feed.py @@ -0,0 +1,100 @@ +"""Trade Feed tour: manage one user's Trade Feed, read it, and get new trades live. + + pip install "cabalspy-id[stream]" # the stream part only + CABALSPY_API_KEY=... python examples/trade_feed.py + +Every call acts in the name of one of your users: someone who signed in to your app with +the scope trade_feed, or one of your platform users. The user and the trader below are +placeholders. +""" + +from __future__ import annotations + +import asyncio +from typing import Any + +from cabalspy_id import ( + AsyncCabalSpyID, + CabalSpyID, + ConflictError, + NotFoundError, + PermissionError, + RateLimitError, +) + +USER = "user_1" # your platform's user id (external_id) +TRADER = "MazeCCC" # a CabalSpy ID handle or csid_id + + +def line(item: Any) -> str: + who = item["trader"]["username"] or item["trader"]["name"] + if item["type"] == "thesis": + th = item["thesis"] + return f"{who} posted a {th['stance'] or 'neutral'} thesis on {th['symbol']}: {th['body'][:60]}" + t = item["trade"] + size = f"${t['amount_usd']:.0f}" if t["amount_usd"] else f"{t['amount_native']} {t['currency']}" + return f"{who} {'bought' if t['side'] == 'buy' else 'sold'} {t['symbol']} for {size} ({t['label']})" + + +def tour() -> None: + with CabalSpyID() as csid: # reads CABALSPY_ID_API_KEY or CABALSPY_API_KEY + # 1. Add the trader: alerts for buys from 0.5 SOL, no sells + try: + r = csid.add_trade_feed_trader(USER, trader=TRADER, min_sol=0.5, notify_sells=False) + print("added" if r["created"] else "already there:", r["trader"]["username"], r["settings"]) + except PermissionError as err: # consent_required (no trade_feed scope), trading_private + print("not allowed:", err.code) + return + except NotFoundError as err: # trader_not_found, platform_user_not_found + print("not found:", err.code) + return + except ConflictError as err: # trade_feed_full: 300 traders + print("full:", err.message) + except RateLimitError as err: # rate_limited: more than 120 changes in an hour + print("slow down:", err.message) + + # 2. Everyone in the Trade Feed, with alert and copy settings + page = csid.get_raw("/trade-feed/traders", {"external_id": USER}) + print(f"{(page.pagination or {}).get('total')} of {(page.pagination or {}).get('max')} traders") + for entry in csid.iter_trade_feed_traders(USER): + s, name = entry["settings"], entry["trader"]["username"] + print(f" {name}: muted={s['muted']} min={s['min_native']} copy={s['copy']['enabled']}") + + # 3. The feed, newest first (first 20 items) + for n, item in enumerate(csid.iter_trade_feed(USER), 1): + print(" ", line(item)) + if n == 20: + break + + # 4. Alerts that passed the user's filters + for alert in csid.trade_feed_notifications(USER, limit=5): + print(" alert:", alert["created_at"], alert["text"]) + + # 5. Mute the trader (updates the settings, the trader stays), then remove them + csid.add_trade_feed_trader(USER, trader=TRADER, muted=True) + print("removed:", csid.remove_trade_feed_trader(USER, trader=TRADER)["removed"]) + + +async def live() -> None: + """New trades and theses as they happen (the webhooks trade_feed.trade / .thesis carry the same).""" + async with AsyncCabalSpyID() as csid: + tf = csid.trade_feed_stream() + + @tf.on("trade_feed.trade") + @tf.on("trade_feed.thesis") + def on_item(item: Any) -> None: + print(line(item), "-> tell", item["recipients_external"] or item["recipients"]) + + tf.on("error", lambda err: print("stream error:", err)) + print("ready:", await tf.connect()) + try: + await asyncio.wait_for(tf.run_forever(), timeout=60) + except asyncio.TimeoutError: + pass + finally: + await tf.close() + + +if __name__ == "__main__": + tour() + asyncio.run(live()) diff --git a/pyproject.toml b/pyproject.toml index 9254f05..ee88410 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cabalspy-id" -version = "0.8.0" +version = "0.9.0" description = "SocialFi API & SDK for CabalSpy ID — add a social layer to any app: login with X + verified wallets, live trades and PnL of your users, token theses, leaderboards and copy trading on Solana, BNB Chain, Base, Ethereum and Robinhood Chain." readme = "README.md" license = "MIT" diff --git a/tests/test_copy_trading.py b/tests/test_copy_trading.py index 4e7a21b..0641a63 100644 --- a/tests/test_copy_trading.py +++ b/tests/test_copy_trading.py @@ -367,7 +367,6 @@ def test_copy_trading_webhook_events() -> None: def test_exports() -> None: import cabalspy_id - assert cabalspy_id.__version__ == "0.8.0" assert api.CopyTradingStream is cabalspy_id.CopyTradingStream assert cabalspy_id.COPY_TRADING_EVENTS == ("copy_trade.instruction",) assert "ready" in cabalspy_id.COPY_TRADING_STREAM_EVENTS diff --git a/tests/test_trade_feed.py b/tests/test_trade_feed.py new file mode 100644 index 0000000..f6c44c1 --- /dev/null +++ b/tests/test_trade_feed.py @@ -0,0 +1,403 @@ +"""Trade Feed (feed, traders, notifications), against mocked HTTP.""" + +from __future__ import annotations + +from typing import Any + +import httpx +import pytest + +from cabalspy_id import ( + TRADE_FEED_FILTERS, + TRADE_FEED_WEBHOOK_EVENTS, + WEBHOOK_EVENTS, + AsyncCabalSpyID, + BadRequestError, + CabalSpyID, + ConflictError, + NotFoundError, + PermissionError, + PlanUserLimitError, + RateLimitError, + ServerError, + TradeFeedItem, + api, +) + +from .conftest import Recorder, api_error, ok +from .test_platform_users import call, make, query + +KEY = "csid_api_testkey" +MINT = "3Pkrq4MmLvDXyn1fa3sz5MekKRkZkc1iLDcz5AzWpump" + +TRADER: dict[str, Any] = { + "csid_id": "t1", + "username": "MazeCCC", + "name": "Maze", + "image_url": None, + "kol": True, + "profile_url": "https://id.cabalspy.xyz/u/MazeCCC", +} +LINKS: dict[str, Any] = {"token": "https://app.cabalspy.xyz/token/x", "terminal": None, "profile": None} +TRADE_ITEM: dict[str, Any] = { + "id": "t3b1f0c9e8d7a6b5c4d3e2f1a0b9c8d7e", + "type": "trade", + "timestamp": "2026-11-01T18:40:05Z", + "trader": TRADER, + "trade": { + "blockchain": "solana", + "mint": MINT, + "symbol": "CPT", + "name": "Copycat", + "logo": None, + "side": "sell", + "label": "partial", + "sold_percent": 50.0, + "amount_native": 1.5, + "currency": "SOL", + "amount_usd": 225.0, + "token_amount": 500.0, + "price_usd": 0.45, + "pnl_usd": 150.0, + "pnl_percent": 200.0, + "wallet": "W1", + "wallet_url": None, + "tx_signature": "2Bq7", + "tx_url": None, + }, + "links": LINKS, + "cursor": "c1", +} +THESIS_ITEM: dict[str, Any] = { + "id": "h8a1d2c3b", + "type": "thesis", + "timestamp": "2026-11-01T18:21:44Z", + "trader": TRADER, + "thesis": { + "id": "8a1d2c3b", + "blockchain": "solana", + "mint": MINT, + "symbol": "CPT", + "name": "Copycat", + "logo": None, + "stance": "bull", + "body": "Dev still holding.", + "likes": 12, + "replies": 3, + "url": "https://id.cabalspy.xyz/try/thesis?chain=solana&mint=x", + }, + "links": LINKS, + "cursor": "c2", +} +SETTINGS: dict[str, Any] = { + "notify_buys": True, + "notify_sells": True, + "notify_theses": True, + "min_native": {"SOL": 0.5, "BNB": 0.0, "ETH": 0.0}, + "muted": False, + "copy": { + "enabled": False, + "mode": "fixed_usd", + "amount_usd": 50.0, + "percent": 100.0, + "max_usd": None, + "sides": "both", + "slippage_bps": 300, + "updated_at": None, + }, +} +ENTRY: dict[str, Any] = { + "trader": TRADER, + "trading_public": True, + "added_at": "2026-10-20T09:12:00+00:00", + "in_trade_feeds": 128, + "settings": SETTINGS, +} +NOTIFICATION: dict[str, Any] = { + "id": 48213, + "event": "trade_feed.trade", + "text": "Trade Feed: @MazeCCC sold $CPT", + "created_at": "2026-11-01T18:40:06Z", + "data": TRADE_ITEM, +} + + +# ── every endpoint: method, path, query / body ─────────────────────────────── + + +def test_every_trade_feed_endpoint() -> None: + csid, rec = make() + csid.trade_feed("u1") + csid.trade_feed(csid_id="f1", filter="theses", limit=5, cursor="abc") + csid.trade_feed_traders("u1") + csid.trade_feed_traders(csid_id="f1", limit=300, cursor="MTAw") + csid.add_trade_feed_trader("u1", trader="@MazeCCC", min_sol=0.5) + csid.add_trade_feed_trader( + csid_id="f1", + trader_external_id="u2", + notify_buys=True, + notify_sells=False, + notify_theses=True, + min_sol=0, + min_bnb=1, + min_eth=0.25, + muted=False, + ) + csid.add_trade_feed_trader("u1", trader="t1") + csid.remove_trade_feed_trader("u1", trader="MazeCCC") + csid.remove_trade_feed_trader(csid_id="f1", trader_external_id="u2") + csid.trade_feed_notifications("u1") + csid.trade_feed_notifications(csid_id="f1", limit=20, cursor="n1") + + assert [call(r) for r in rec.requests] == [ + ("GET", "/v1/trade-feed", {"external_id": "u1"}), + ("GET", "/v1/trade-feed", {"csid_id": "f1", "filter": "theses", "limit": "5", "cursor": "abc"}), + ("GET", "/v1/trade-feed/traders", {"external_id": "u1"}), + ("GET", "/v1/trade-feed/traders", {"csid_id": "f1", "limit": "300", "cursor": "MTAw"}), + ("POST", "/v1/trade-feed/traders", {"external_id": "u1", "trader": "@MazeCCC", "min_sol": 0.5}), + ( + "POST", + "/v1/trade-feed/traders", + { + "csid_id": "f1", + "trader_external_id": "u2", + "notify_buys": True, + "notify_sells": False, + "notify_theses": True, + "min_sol": 0, + "min_bnb": 1, + "min_eth": 0.25, + "muted": False, + }, + ), + ("POST", "/v1/trade-feed/traders", {"external_id": "u1", "trader": "t1"}), + ("POST", "/v1/trade-feed/traders/delete", {"external_id": "u1", "trader": "MazeCCC"}), + ("POST", "/v1/trade-feed/traders/delete", {"csid_id": "f1", "trader_external_id": "u2"}), + ("GET", "/v1/trade-feed/notifications", {"external_id": "u1"}), + ("GET", "/v1/trade-feed/notifications", {"csid_id": "f1", "limit": "20", "cursor": "n1"}), + ] + assert all(r.headers["Authorization"] == f"Bearer {KEY}" for r in rec.requests) + + +def test_returns_items_traders_and_results() -> None: + def handler(r: httpx.Request) -> httpx.Response: + path = r.url.path + if path == "/v1/trade-feed": + return ok([TRADE_ITEM, THESIS_ITEM], pagination={"limit": 30, "next_cursor": None, "has_more": False}) + if path == "/v1/trade-feed/traders" and r.method == "GET": + pagination = {"limit": 100, "total": 1, "max": 300, "next_cursor": None, "has_more": False} + return ok([ENTRY], pagination=pagination) + if path == "/v1/trade-feed/traders": + data = {"in_trade_feed": True, "created": True, "trader": TRADER, "settings": SETTINGS} + return httpx.Response(201, json={"success": True, "data": data}) + if path == "/v1/trade-feed/traders/delete": + return ok({"in_trade_feed": False, "removed": True}) + return ok([NOTIFICATION], pagination={"limit": 50, "next_cursor": None, "has_more": False}) + + csid, _ = make(handler) + items: list[TradeFeedItem] = csid.trade_feed("u1") + trade, thesis = items + assert trade["type"] == "trade" and trade["trade"]["label"] == "partial" and trade["trade"]["sold_percent"] == 50 + assert thesis["type"] == "thesis" and thesis["thesis"]["stance"] == "bull" + entry = csid.trade_feed_traders("u1")[0] + assert entry["settings"]["min_native"]["SOL"] == 0.5 and entry["settings"]["copy"]["enabled"] is False + assert entry["in_trade_feeds"] == 128 and entry["trading_public"] + page = csid.get_raw("/trade-feed/traders", {"external_id": "u1"}) + assert page.pagination == {"limit": 100, "total": 1, "max": 300, "next_cursor": None, "has_more": False} + added = csid.add_trade_feed_trader("u1", trader="MazeCCC") + assert added["created"] and added["in_trade_feed"] and added["trader"]["username"] == "MazeCCC" + assert csid.remove_trade_feed_trader("u1", trader="MazeCCC") == {"in_trade_feed": False, "removed": True} + n = csid.trade_feed_notifications("u1")[0] + assert n["id"] == 48213 and n["event"] == "trade_feed.trade" and n["data"]["id"] == TRADE_ITEM["id"] + + +def test_trade_feed_validation() -> None: + csid, rec = make() + with pytest.raises(BadRequestError) as e: + csid.trade_feed() # no user + assert e.value.parameter == "external_id|csid_id" + with pytest.raises(BadRequestError): + csid.trade_feed("u1", csid_id="f1") # both + with pytest.raises(BadRequestError) as e: + csid.trade_feed("u1", filter="mints") # type: ignore[arg-type] + assert e.value.allowed == list(TRADE_FEED_FILTERS) + for bad_limit in (0, 101, True, 2.5): + with pytest.raises(BadRequestError) as e: + csid.trade_feed("u1", limit=bad_limit) # type: ignore[arg-type] + assert e.value.parameter == "limit" + with pytest.raises(BadRequestError): + csid.trade_feed_notifications("u1", limit=101) + with pytest.raises(BadRequestError): + csid.trade_feed_traders("u1", limit=301) + with pytest.raises(BadRequestError): + csid.trade_feed_traders() + with pytest.raises(BadRequestError) as e: + csid.add_trade_feed_trader("u1") # no trader + assert e.value.parameter == "trader" + with pytest.raises(BadRequestError) as e: + csid.add_trade_feed_trader("u1", trader="a", trader_external_id="b") + assert e.value.parameter == "trader|trader_external_id" + with pytest.raises(BadRequestError): + csid.add_trade_feed_trader(trader="a") # no user + bad: list[tuple[str, Any]] = [ + ("notify_buys", "yes"), + ("notify_sells", 1), + ("notify_theses", "false"), + ("muted", 0), + ("min_sol", -1), + ("min_bnb", 1_000_001), + ("min_eth", "0.5"), + ("min_sol", True), + ("min_sol", float("nan")), + ] + for name, value in bad: + with pytest.raises(BadRequestError) as e: + csid.add_trade_feed_trader("u1", trader="t1", **{name: value}) + assert e.value.parameter == name, (name, value) + with pytest.raises(BadRequestError) as e: + csid.remove_trade_feed_trader("u1") + assert e.value.parameter == "trader" + with pytest.raises(BadRequestError): + csid.remove_trade_feed_trader(trader="t1") + with pytest.raises(BadRequestError): + list(csid.iter_trade_feed("u1", filter="nope")) # type: ignore[arg-type] + assert rec.requests == [] + + +def test_none_settings_are_not_sent() -> None: + csid, rec = make() + csid.add_trade_feed_trader("u1", trader="t1", notify_buys=None, min_sol=None, muted=True) + assert call(rec.requests[0])[2] == {"external_id": "u1", "trader": "t1", "muted": True} + + +# ── iterators, async ───────────────────────────────────────────────────────── + + +def test_iterators_follow_cursor() -> None: + def handler(r: httpx.Request) -> httpx.Response: + if query(r).get("cursor") is None: + return ok([{"id": "a"}, {"id": "b"}], pagination={"limit": 2, "has_more": True, "next_cursor": "n1"}) + return ok([{"id": "c"}], pagination={"limit": 2, "has_more": False, "next_cursor": None}) + + csid, rec = make(handler) + assert [i["id"] for i in csid.iter_trade_feed("u1", filter="buys", limit=2)] == ["a", "b", "c"] + assert [i["id"] for i in csid.iter_trade_feed_traders(csid_id="f1", limit=2)] == ["a", "b", "c"] + assert [i["id"] for i in csid.iter_trade_feed_notifications("u1")] == ["a", "b", "c"] + assert [call(r) for r in rec.requests] == [ + ("GET", "/v1/trade-feed", {"external_id": "u1", "filter": "buys", "limit": "2"}), + ("GET", "/v1/trade-feed", {"external_id": "u1", "filter": "buys", "limit": "2", "cursor": "n1"}), + ("GET", "/v1/trade-feed/traders", {"csid_id": "f1", "limit": "2"}), + ("GET", "/v1/trade-feed/traders", {"csid_id": "f1", "limit": "2", "cursor": "n1"}), + ("GET", "/v1/trade-feed/notifications", {"external_id": "u1"}), + ("GET", "/v1/trade-feed/notifications", {"external_id": "u1", "cursor": "n1"}), + ] + + +async def test_async_trade_feed() -> None: + def handler(r: httpx.Request) -> httpx.Response: + path = r.url.path + if r.method == "POST" and path == "/v1/trade-feed/traders": + return ok({"in_trade_feed": True, "created": False, "trader": TRADER, "settings": SETTINGS}) + if path == "/v1/trade-feed/traders/delete": + return ok({"in_trade_feed": False, "removed": False}) + if query(r).get("cursor"): + return ok([{"id": "b"}], pagination={"has_more": False, "next_cursor": None}) + return ok([{"id": "a"}], pagination={"has_more": True, "next_cursor": "n"}) + + rec = Recorder(handler) + async with AsyncCabalSpyID(KEY, http_client=rec.async_client(), max_retries=0) as csid: + assert (await csid.trade_feed("u1"))[0]["id"] == "a" + assert [i["id"] async for i in csid.iter_trade_feed(csid_id="f1", filter="sells")] == ["a", "b"] + assert [i["id"] async for i in csid.iter_trade_feed_traders("u1")] == ["a", "b"] + assert [i["id"] async for i in csid.iter_trade_feed_notifications("u1", limit=1)] == ["a", "b"] + assert (await csid.trade_feed_traders("u1"))[0]["id"] == "a" + assert (await csid.trade_feed_notifications("u1"))[0]["id"] == "a" + added = await csid.add_trade_feed_trader("u1", trader="t1", notify_theses=False) + assert added["created"] is False + assert (await csid.remove_trade_feed_trader("u1", trader="t1"))["removed"] is False + assert call(rec.requests[-2]) == ( + "POST", + "/v1/trade-feed/traders", + {"external_id": "u1", "trader": "t1", "notify_theses": False}, + ) + + +# ── errors ─────────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("status", "code", "cls"), + [ + (400, "cannot_add_self", BadRequestError), + (403, "consent_required", PermissionError), + (403, "trading_private", PermissionError), + (403, "plan_user_limit", PlanUserLimitError), + (404, "trader_not_found", NotFoundError), + (404, "platform_user_not_found", NotFoundError), + (409, "trade_feed_full", ConflictError), + (429, "rate_limited", RateLimitError), + (503, "service_unavailable", ServerError), + ], +) +def test_add_errors_are_not_retried(status: int, code: str, cls: type[Exception]) -> None: + csid, rec = make(lambda r: api_error(status, code, headers={"Retry-After": "0"}), max_retries=2) + with pytest.raises(cls) as e: + csid.add_trade_feed_trader("u1", trader="MazeCCC") + assert e.value.code == code # type: ignore[attr-defined] + assert e.value.status == status # type: ignore[attr-defined] + assert len(rec.requests) == 1 + + +@pytest.mark.parametrize( + ("status", "code", "cls"), + [ + (403, "consent_required", PermissionError), + (403, "plan_user_limit", PlanUserLimitError), + (404, "platform_user_not_found", NotFoundError), + (400, "invalid_parameter", BadRequestError), + ], +) +def test_read_errors(status: int, code: str, cls: type[Exception]) -> None: + csid, _ = make(lambda r: api_error(status, code)) + with pytest.raises(cls) as e: + csid.trade_feed("u1") + assert e.value.code == code # type: ignore[attr-defined] + + +# ── webhooks, exports, options ─────────────────────────────────────────────── + + +def test_trade_feed_webhook_events() -> None: + assert TRADE_FEED_WEBHOOK_EVENTS == ("trade_feed.trade", "trade_feed.thesis") + assert set(TRADE_FEED_WEBHOOK_EVENTS) <= set(WEBHOOK_EVENTS) + + +def test_exports() -> None: + import cabalspy_id + + assert cabalspy_id.__version__ == "0.9.0" + assert api.TradeFeedStream is cabalspy_id.TradeFeedStream + assert cabalspy_id.TRADE_FEED_EVENTS == ("trade_feed.trade", "trade_feed.thesis") + assert "ready" in cabalspy_id.TRADE_FEED_STREAM_EVENTS + for name in ( + "TradeFeedStream", + "TradeFeedItem", + "TradeFeedTradeItem", + "TradeFeedThesisItem", + "TradeFeedTrader", + "TradeFeedTraderResult", + "TradeFeedRemoveResult", + "TradeFeedNotification", + "TradeFeedSettings", + "TradeFeedEvent", + "TRADE_FEED_FILTERS", + "TRADE_FEED_WEBHOOK_EVENTS", + "MAX_TRADE_FEED_TRADERS", + ): + assert name in cabalspy_id.__all__ and name in api.__all__, name + assert hasattr(api, name), name + + +def test_client_option() -> None: + assert CabalSpyID("k", trade_feed_stream_url="ws://x/y/").trade_feed_stream_url == "ws://x/y" + assert CabalSpyID("k").trade_feed_stream_url == "wss://api-id.cabalspy.xyz/v1/trade-feed/stream" diff --git a/tests/test_trade_feed_stream.py b/tests/test_trade_feed_stream.py new file mode 100644 index 0000000..d142bd7 --- /dev/null +++ b/tests/test_trade_feed_stream.py @@ -0,0 +1,218 @@ +"""TradeFeedStream against a local server that behaves like /v1/trade-feed/stream.""" + +from __future__ import annotations + +import asyncio +import json +from typing import Any +from urllib.parse import parse_qs, urlsplit + +import pytest +from websockets.asyncio.server import serve + +from cabalspy_id import ( + TRADE_FEED_EVENTS, + AuthenticationError, + CabalSpyID, + PermissionError, + RateLimitError, +) + +TRADER = {"csid_id": "t1", "username": "MazeCCC", "name": "Maze", "image_url": None, "kol": True, "profile_url": None} +TRADE = { + "id": "tk1", + "type": "trade", + "timestamp": "2026-11-01T18:40:05Z", + "trader": TRADER, + "trade": {"side": "buy", "label": "new", "symbol": "CPT", "amount_native": 1.5, "currency": "SOL"}, + "links": {"token": None, "terminal": None, "profile": None}, + "recipients": ["f1", "f2"], + "recipients_external": ["u1"], +} +THESIS = { + "id": "h9", + "type": "thesis", + "timestamp": "2026-11-01T18:41:00Z", + "trader": TRADER, + "thesis": {"id": "9", "stance": "bear", "body": "Top is in."}, + "links": {"token": None, "terminal": None, "profile": None}, + "recipients": ["f1"], + "recipients_external": [], +} +EVENTS = [ + {"event": "trade_feed.trade", "id": "ev1", "data": TRADE}, + {"event": "trade_feed.thesis", "id": "ev2", "data": THESIS}, +] + + +class Server: + def __init__(self) -> None: + self.paths: list[str] = [] + self.received: list[str] = [] + self.mode = "ok" + self.connections = 0 + + async def handler(self, ws: Any) -> None: + self.connections += 1 + self.paths.append(ws.request.path) + deny = { + "deny": ("invalid_api_key", "API key is invalid or does not exist"), + "busy": ("too_many_connections", "At most 5 Trade Feed stream connections per API key."), + }.get(self.mode) + if deny or (self.mode == "busy_once" and self.connections == 1): + code, message = deny or ("too_many_connections", "busy") + await ws.send(json.dumps({"event": "error", "error": {"code": code, "message": message}})) + await ws.close(code=4403) + return + await ws.send(json.dumps({"event": "ready", "data": {"events": list(TRADE_FEED_EVENTS)}})) + await ws.send(json.dumps({"event": "heartbeat", "ts": 1})) + await ws.send("not json") + await ws.send(json.dumps({"event": "something.new", "data": {}})) + for ev in EVENTS: + await ws.send(json.dumps(ev)) + if self.mode == "drop_once" and self.connections == 1: + await asyncio.sleep(0.05) + await ws.close(code=1011) + return + async for raw in ws: + self.received.append(raw) + if json.loads(raw).get("op") == "ping": + await ws.send(json.dumps({"event": "pong"})) + + +@pytest.fixture +async def server(): + s = Server() + async with serve(s.handler, "127.0.0.1", 0) as srv: + s.url = f"ws://127.0.0.1:{srv.sockets[0].getsockname()[1]}/v1/trade-feed/stream" # type: ignore[attr-defined] + yield s + + +def client(s: Server, **kwargs: Any) -> CabalSpyID: + return CabalSpyID("k", trade_feed_stream_url=s.url, **kwargs) # type: ignore[attr-defined] + + +async def wait_for(cond: Any, timeout: float = 2.0) -> None: + for _ in range(int(timeout / 0.02)): + if cond(): + return + await asyncio.sleep(0.02) + + +async def test_events_are_parsed(server: Server) -> None: + tf = client(server, instance="csid_app").trade_feed_stream() + got: list[tuple[str, Any]] = [] + for name in (*TRADE_FEED_EVENTS, "heartbeat", "pong"): + tf.on(name, lambda d, name=name: got.append((name, d))) + ready = await tf.connect() + assert ready == {"events": ["trade_feed.trade", "trade_feed.thesis"]} + q = {k: v[0] for k, v in parse_qs(urlsplit(server.paths[0]).query).items()} + assert q == {"api_key": "k", "instance": "csid_app"} + assert "k" not in tf.safe_url.split("api_key=")[1] + await wait_for(lambda: len(got) >= 3) + await tf.ping() + await wait_for(lambda: got[-1][0] == "pong") + await tf.close() + assert [n for n, _ in got] == ["heartbeat", "trade_feed.trade", "trade_feed.thesis", "pong"] + assert got[1][1]["trade"]["side"] == "buy" + assert got[1][1]["recipients"] == ["f1", "f2"] and got[1][1]["recipients_external"] == ["u1"] + assert got[2][1]["thesis"]["stance"] == "bear" + assert got[0][1] == {"ts": 1} + assert json.loads(server.received[0]) == {"op": "ping"} + assert not tf.connected + + +async def test_async_handlers_and_decorator(server: Server) -> None: + tf = client(server).trade_feed_stream() + seen: list[str] = [] + + @tf.on("trade_feed.trade") + async def on_trade(item: Any) -> None: + seen.append(item["id"]) + raise ValueError("handler failed") + + @tf.on("trade_feed.thesis") + def on_thesis(item: Any) -> None: + seen.append(item["id"]) + + errors: list[Any] = [] + tf.on("error", errors.append) + await tf.connect() + await wait_for(lambda: len(seen) == 2 and bool(errors)) + await tf.close() + assert seen == ["tk1", "h9"] + assert isinstance(errors[0], ValueError) + with pytest.raises(ValueError): + tf.on("copy_trade.instruction", print) + + +async def test_iteration_yields_event_ids(server: Server) -> None: + seen: list[dict[str, Any]] = [] + async with client(server).trade_feed_stream() as tf: + async for ev in tf: + seen.append(ev) + if len(seen) == 2: + break + assert [(e["event"], e["id"]) for e in seen] == [("trade_feed.trade", "ev1"), ("trade_feed.thesis", "ev2")] + assert seen[0]["data"]["id"] == "tk1" and seen[0]["data"]["recipients_external"] == ["u1"] + + +async def test_iteration_without_context_manager(server: Server) -> None: + tf = client(server).trade_feed_stream() + first: dict[str, Any] = {} + async for ev in tf: + first = ev + break + assert first["id"] == "ev1" + await tf.close() + + +async def test_invalid_api_key_is_fatal(server: Server) -> None: + server.mode = "deny" + tf = client(server).trade_feed_stream(reconnect_delay=0.01) + with pytest.raises(PermissionError) as e: + await tf.connect() + assert e.value.code == "invalid_api_key" + with pytest.raises(PermissionError): + await asyncio.wait_for(tf.run_forever(), 2) + assert server.connections == 1 + + +async def test_too_many_connections_reconnects(server: Server) -> None: + server.mode = "busy_once" + tf = client(server).trade_feed_stream(reconnect_delay=0.01) + errors: list[Any] = [] + tf.on("error", errors.append) + with pytest.raises(RateLimitError): + await tf.connect() + await wait_for(lambda: tf.connected) + assert tf.connected and server.connections == 2 + assert errors[0].code == "too_many_connections" + await tf.close() + + +async def test_reconnects_after_drop(server: Server) -> None: + server.mode = "drop_once" + tf = client(server).trade_feed_stream(reconnect_delay=0.01) + events: list[str] = [] + tf.on("reconnecting", lambda d: events.append("reconnecting")) + tf.on("ready", lambda d: events.append("ready")) + await tf.connect() + await wait_for(lambda: server.connections == 2 and events.count("ready") == 2) + await tf.close() + assert events == ["ready", "reconnecting", "ready"] + + +async def test_connection_error() -> None: + url = "ws://127.0.0.1:1/v1/trade-feed/stream" + tf = CabalSpyID("k", trade_feed_stream_url=url).trade_feed_stream(reconnect=False) + with pytest.raises(Exception) as e: + await tf.connect() + assert getattr(e.value, "code", None) == "ws_error" + + +def test_local_validation() -> None: + with pytest.raises(AuthenticationError): + CabalSpyID("").trade_feed_stream() + tf = CabalSpyID("k").trade_feed_stream() + assert tf.safe_url == "wss://api-id.cabalspy.xyz/v1/trade-feed/stream?api_key=***"