diff --git a/CHANGELOG.md b/CHANGELOG.md index 6657df3..bd40b6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,40 @@ 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.8.0] - 2026-11-01 + +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. CabalSpy ID never holds keys and never +executes; your app executes the instruction with the user's wallet and reports the status back. +Sync and async. + +### Added + +- Copy trading (`/v1/copy-trading/*`) on `CabalSpyID` and `AsyncCabalSpyID`: + `copy_trading_settings` (`external_id` positionally or `csid_id=`; all traders, or one with + `trader=` / `trader_external_id=`), `update_copy_trading_settings` (`enabled`, `mode`, + `amount_usd`, `percent`, `max_usd` (`None` removes the cap), `sides`, `slippage_bps`; only the + settings you pass change), `copy_instructions` / `iter_copy_instructions` (filters + `external_id` / `csid_id`, `status` incl. `expired`; `limit` 1-100), `copy_instruction`, + `report_copy_instruction` (`executed` / `failed` / `skipped`, `tx_signature`, + `executed_amount_usd`, `note`). Values are checked locally like the server does. +- `CopyTradingStream` for `wss://api-id.cabalspy.xyz/v1/copy-trading/stream` via + `client.copy_trading_stream()`: event `copy_trade.instruction` (handlers, or `async for` with + `{"event", "id", "data"}`), heartbeats, reconnects with backoff; `invalid_api_key` is fatal, + `too_many_connections` reconnects. New client option `copy_trading_stream_url`. +- Types: `CopyInstruction`, `CopyAction`, `CopySourceTrade`, `CopyLinks`, `CopyTrader`, + `CopySettings`, `CopyTradingSetting`, `CopyTradingStreamReady`. +- Constants: `COPY_TRADING_WEBHOOK_EVENTS` (`copy_trade.instruction`, also in `WEBHOOK_EVENTS`), + `COPY_MODES`, `COPY_SIDES`, `COPY_INSTRUCTION_STATUSES`, `COPY_REPORT_STATUSES`, + `COPY_INSTRUCTION_TTL_SECONDS`, `COPY_MIN_USD`, `COPY_DEFAULT_SLIPPAGE_BPS`, + `MAX_COPY_TRADING_STREAMS_PER_KEY`, `DEFAULT_COPY_TRADING_STREAM_URL`, `COPY_TRADING_EVENTS`, + `COPY_TRADING_STREAM_EVENTS`; Literal types `CopyMode`, `CopySides`, `CopySide`, + `CopyInstructionStatus`, `CopyReportStatus`. +- Error codes on the existing classes: `copy_managed_elsewhere`, `already_reported`, + `trade_feed_full` (`ConflictError`), `not_in_trade_feed`, `trader_not_found`, `not_found` + (`NotFoundError`), `consent_required`, `trading_private` (`PermissionError`). +- README section "Copy trading" and `examples/copy_trading.py`. + ## [0.7.0] - 2026-10-31 Callouts: your users call tokens, and every call is stamped with the token's price and market @@ -231,6 +265,7 @@ First release. `NotFoundError`, `RateLimitError`, `ServerError`, `APIConnectionError`, `InvalidResponseError`, `OAuthError`, `TokenVerificationError`, `WebhookVerificationError`. +[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 [0.5.2]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.1...v0.5.2 diff --git a/README.md b/README.md index 27c62d3..3ca476b 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 and callouts (on request) | +| `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 | | `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 | @@ -33,7 +33,7 @@ Everything for developers — instance (client_id), client secrets, redirect URI - **Social trading feed** — every trade of your users live, with their X profile and PnL - **Leaderboards** — rank your users by PnL, volume, win rate or trades -- **Copy trading** — follow verified wallets of real, identified traders +- **Copy trading** — follow verified wallets of real, identified traders; every trade of a copied trader arrives as a ready-to-execute instruction sized by the user's settings - **Token theses** — holders-only opinions on a token with the author's real position, as a SocialFi widget or your own UI - **Trader profiles** — X profile, verified wallets, holdings, PnL calendar - **KOL badges** — reviewed badges for influential traders, shown wherever they sign in @@ -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`, `CabalSpyIDAuth`, `verify_webhook`, errors and Data API types | +| `cabalspy_id.api` | `CabalSpyID`, `AsyncCabalSpyID`, `CabalSpyIDStream`, `CalloutsStream`, `CopyTradingStream`, `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`. @@ -233,10 +233,10 @@ except RateLimitError as err: |---|---|---| | `BadRequestError` | 400, 422 | `missing_parameter`, `invalid_parameter`, `instance_required`, `wallet_required`, `invalid_address`, `invalid_return_url`, `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` | +| `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` | -| `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` | +| `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` | | `ServerError` | 5xx | `internal_error`, `service_unavailable` | | `APIConnectionError` | – | network failure, timeout | @@ -406,6 +406,60 @@ comp = csid.create_competition(name="Caller of the week", kind="callouts", chain A full tour is in [`examples/callouts.py`](examples/callouts.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. + +```python +from cabalspy_id import CabalSpyID, ConflictError + +csid = CabalSpyID() + +# Copy @ctkol for user_42: $25 per buy, at most $20, buys and sells, 1.5 % price limit +try: + s = csid.update_copy_trading_settings("user_42", trader="ctkol", enabled=True, mode="fixed_usd", + amount_usd=25, max_usd=20, sides="both", slippage_bps=150) +except ConflictError: # copy_managed_elsewhere: another platform copies this trader for the user + pass + +for s in csid.copy_trading_settings("user_42"): # every trader in the Trade Feed + print(s["trader"]["username"], s["copy"]["enabled"], s["managed_by_other_platform"]) + +for i in csid.iter_copy_instructions("user_42", status="pending"): # newest first + a = i["action"] + sig = execute(i["csid_id"], a) # your swap, before i["expires_at"] + csid.report_copy_instruction(i["id"], status="executed", tx_signature=sig, executed_amount_usd=a["amount_usd"]) +``` + +| Method | Endpoint | +|---|---| +| `copy_trading_settings(external_id \| csid_id=, trader=, trader_external_id=)` | `GET /v1/copy-trading/settings` (a list, or one with a trader) | +| `update_copy_trading_settings(external_id \| csid_id=, trader= \| trader_external_id=, enabled=, mode=, amount_usd=, percent=, max_usd=, sides=, slippage_bps=)` | `POST /v1/copy-trading/settings` | +| `copy_instructions(external_id \| csid_id=, status=, limit=, cursor=)` / `iter_copy_instructions()` | `GET /v1/copy-trading/instructions` | +| `copy_instruction(id)` | `GET /v1/copy-trading/instructions/item` | +| `report_copy_instruction(id, status=, tx_signature=, executed_amount_usd=, note=)` | `POST /v1/copy-trading/instructions/status` | +| `copy_trading_stream()` | `WS /v1/copy-trading/stream` | + +**Settings** (`CopySettings`, per user and trader): `enabled`, `mode` (`fixed_usd`: every buy is `amount_usd`, default 50; `percent`: `percent` % of the trader's buy in USD, default 100, at most 1000), `max_usd` (cap per buy; `max_usd=None` removes it), `sides` (`buys` or `both`, default both), `slippage_bps` (1-5000, default 300). Only the settings you pass change; the trader (handle or csid_id, or `trader_external_id` for one of your platform users) is added to the Trade Feed if needed (HTTP 201). Copying a trader is switched on by **one platform at a time**: only its apps get the instructions, so a user on two platforms is never copied twice (`managed_by_other_platform`, `copy_managed_elsewhere`). + +**An instruction** (`CopyInstruction`): `id`, `status`, `created_at`, `expires_at` (120 seconds later), `csid_id`, `trader`, `action` (`blockchain`, `mint`, `symbol`, `side`; buys: `amount_usd`, `amount_native` in `currency` and `max_price_usd`; sells: `sell_percent` of the copied position and `min_price_usd`; `price_usd`, `slippage_bps`), `source_trade` (the trader's trade), `settings` (as they were), `links`, and once reported `tx_signature`, `executed_amount_usd`, `note`. Buys under $1 are not sent. A sell is only sent after a copied buy of that token that was not reported failed or skipped; a closing sell is `sell_percent` 100. A pending instruction past `expires_at` reads as `expired` (it may still be reported executed). + +**Reporting.** `status` is `executed`, `failed` or `skipped` and final: the same report twice is fine, another one raises `ConflictError` `already_reported`. Reports are not retried after a server or network error. + +**Live stream** (async, needs `cabalspy-id[stream]`), webhook `copy_trade.instruction` (`COPY_TRADING_WEBHOOK_EVENTS`) and REST carry the same instructions; the stream and the webhook add `external_id`: + +```python +async with AsyncCabalSpyID() as csid: + async with csid.copy_trading_stream() as cs: + async for ev in cs: # {"event": "copy_trade.instruction", "id": ..., "data": ...} + i = ev["data"] + await execute_and_report(csid, i) +``` + +Events: `copy_trade.instruction`, plus `ready`, `heartbeat`, `pong`, `open`, `close`, `reconnecting`, `error`. `invalid_api_key` is fatal; `too_many_connections` (at most 5 per key) reconnects with backoff. + +A full tour is in [`examples/copy_trading.py`](examples/copy_trading.py). + ## Token theses A thesis is a short opinion on a token (up to 1000 characters), optionally tagged bull or bear. **Only holders post theses**: one of the author's verified wallets bought the token and still holds it. Every thesis shows the author's real position — what they bought when posting and their live PnL now (or "sold"); authors who keep their trading private show only that they hold. Anyone signed in can reply and react (`like` plus 🔥 🚀 💎 👀 😂 🤝 💀 🐂 🐻). The same theses appear in the widget, through the Data API and on every platform. @@ -554,7 +608,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`). +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`). ```python from cabalspy_id import verify_webhook @@ -577,6 +631,7 @@ CabalSpyID( base_url="https://api-id.cabalspy.xyz/v1", 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", timeout=30.0, max_retries=2, headers={}, diff --git a/cabalspy_id/__init__.py b/cabalspy_id/__init__.py index 5e3d99b..525e060 100644 --- a/cabalspy_id/__init__.py +++ b/cabalspy_id/__init__.py @@ -2,7 +2,7 @@ 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, the live stream, the public thesis API and webhook verification. +competitions, callouts, copy trading, the live stream, the public thesis API and webhook verification. from cabalspy_id import CabalSpyID, CabalSpyIDAuth, verify_webhook @@ -31,10 +31,19 @@ COMPETITION_METRICS, COMPETITION_STATUSES, COMPETITION_WEBHOOK_EVENTS, + COPY_DEFAULT_SLIPPAGE_BPS, + COPY_INSTRUCTION_STATUSES, + COPY_INSTRUCTION_TTL_SECONDS, + COPY_MIN_USD, + COPY_MODES, + COPY_REPORT_STATUSES, + COPY_SIDES, + COPY_TRADING_WEBHOOK_EVENTS, CURRENCY_BY_CHAIN, DATA_SCOPES, DEFAULT_BASE_URL, DEFAULT_CALLOUTS_STREAM_URL, + DEFAULT_COPY_TRADING_STREAM_URL, DEFAULT_ISSUER, DEFAULT_STREAM_URL, DEFAULT_THESES_STREAM_URL, @@ -44,6 +53,7 @@ INBOUND_FORMATS, LEADERBOARD_SORTS, MAX_CALLOUT_STREAMS_PER_KEY, + MAX_COPY_TRADING_STREAMS_PER_KEY, MAX_OPEN_COMPETITIONS, MAX_REQUEST_BODY_BYTES, MAX_THESES_STREAM_TOKENS, @@ -72,6 +82,11 @@ CompetitionKind, CompetitionMetric, CompetitionStatus, + CopyInstructionStatus, + CopyMode, + CopyReportStatus, + CopySide, + CopySides, Currency, DataScope, LeaderboardSort, @@ -150,6 +165,14 @@ CompetitionParticipant, CompetitionStanding, CompetitionStandings, + CopyAction, + CopyInstruction, + CopyLinks, + CopySettings, + CopySourceTrade, + CopyTrader, + CopyTradingSetting, + CopyTradingStreamReady, DiscoveryDocument, HealthResponse, HistoryResponse, @@ -255,6 +278,10 @@ def __getattr__(name: str) -> object: from . import _callouts_stream return getattr(_callouts_stream, name) + if name in ("CopyTradingStream", "COPY_TRADING_STREAM_EVENTS", "COPY_TRADING_EVENTS"): + from . import _copy_trading_stream + + return getattr(_copy_trading_stream, name) raise AttributeError(f"module 'cabalspy_id' has no attribute {name!r}") @@ -266,6 +293,7 @@ def __getattr__(name: str) -> object: "CabalSpyIDStream", "ThesesStream", "CalloutsStream", + "CopyTradingStream", "Envelope", "CabalSpyIDAuth", "AsyncCabalSpyIDAuth", @@ -499,4 +527,30 @@ def __getattr__(name: str) -> object: "CalloutRemovedEvent", "CalloutsStreamReady", "CalloutWebhookData", + # copy trading + "COPY_TRADING_STREAM_EVENTS", + "COPY_TRADING_EVENTS", + "COPY_TRADING_WEBHOOK_EVENTS", + "COPY_MODES", + "COPY_SIDES", + "COPY_INSTRUCTION_STATUSES", + "COPY_REPORT_STATUSES", + "COPY_INSTRUCTION_TTL_SECONDS", + "COPY_MIN_USD", + "COPY_DEFAULT_SLIPPAGE_BPS", + "MAX_COPY_TRADING_STREAMS_PER_KEY", + "DEFAULT_COPY_TRADING_STREAM_URL", + "CopyMode", + "CopySides", + "CopySide", + "CopyInstructionStatus", + "CopyReportStatus", + "CopyTrader", + "CopySettings", + "CopyTradingSetting", + "CopyAction", + "CopySourceTrade", + "CopyLinks", + "CopyInstruction", + "CopyTradingStreamReady", ] diff --git a/cabalspy_id/_client.py b/cabalspy_id/_client.py index 43c927b..237866d 100644 --- a/cabalspy_id/_client.py +++ b/cabalspy_id/_client.py @@ -32,9 +32,14 @@ COMPETITION_KINDS, COMPETITION_METRICS, COMPETITION_STATUSES, + COPY_INSTRUCTION_STATUSES, + COPY_MODES, + COPY_REPORT_STATUSES, + COPY_SIDES, DATA_SCOPES, DEFAULT_BASE_URL, DEFAULT_CALLOUTS_STREAM_URL, + DEFAULT_COPY_TRADING_STREAM_URL, DEFAULT_STREAM_URL, DEFAULT_THESES_STREAM_URL, LEADERBOARD_SORTS, @@ -55,6 +60,10 @@ CompetitionKind, CompetitionMetric, CompetitionStatus, + CopyInstructionStatus, + CopyMode, + CopyReportStatus, + CopySides, DataScope, LeaderboardSort, LeaderboardTrust, @@ -84,6 +93,7 @@ if TYPE_CHECKING: from ._callouts_stream import CalloutsStream + from ._copy_trading_stream import CopyTradingStream from ._stream import CabalSpyIDStream from ._theses_stream import ThesesStream @@ -363,6 +373,71 @@ def _callout_leaderboard_query( } +def _copy_trader(trader: Any, trader_external_id: Any, *, required: bool) -> dict[str, Any]: + """The copied trader: a handle / csid_id (``trader``) or your platform's user id.""" + if trader and trader_external_id: + raise BadRequestError( + "Pass at most one of: trader, trader_external_id.", + code="invalid_parameter", + parameter="trader|trader_external_id", + ) + if required and not (trader or trader_external_id): + raise BadRequestError("Pass one of: trader, trader_external_id.", code="missing_parameter", parameter="trader") + if trader: + return {"trader": trader} + return {"trader_external_id": trader_external_id} if trader_external_id else {} + + +def _number(value: Any, parameter: str, low: float, high: float, *, integer: bool = False) -> None: + """A number above ``low`` and at most ``high`` (whole for ``integer``).""" + if isinstance(value, bool) or not isinstance(value, (int, float)) or not low < value <= high: + kind = "a whole number" if integer else "a number" + raise BadRequestError( + f"{parameter} must be {kind} above {low:g} and at most {high:g}.", + code="invalid_parameter", + parameter=parameter, + ) + if integer and value != int(value): + raise BadRequestError(f"{parameter} must be a whole number.", code="invalid_parameter", parameter=parameter) + + +def _copy_settings_fields(**fields: Any) -> dict[str, Any]: + """Copy settings to change: None = unchanged, except ``max_usd`` (None removes the cap).""" + out = {k: v for k, v in _given(**fields).items() if v is not None or k == "max_usd"} + _one_of(out.get("mode"), COPY_MODES, "mode") + _one_of(out.get("sides"), COPY_SIDES, "sides") + if "enabled" in out and not isinstance(out["enabled"], bool): + raise BadRequestError("enabled must be True or False.", code="invalid_parameter", parameter="enabled") + if "amount_usd" in out: + _number(out["amount_usd"], "amount_usd", 0, 1_000_000) + if "percent" in out: + _number(out["percent"], "percent", 0, 1000) + if out.get("max_usd") is not None: + _number(out["max_usd"], "max_usd", 0, 1_000_000) + if "slippage_bps" in out: + _number(out["slippage_bps"], "slippage_bps", 0, 5000, integer=True) + if not out: + raise BadRequestError( + "Pass at least one of: enabled, mode, amount_usd, percent, max_usd, sides, slippage_bps.", + code="missing_parameter", + parameter="enabled", + ) + return out + + +def _copy_instructions_query(external_id: Any, csid_id: Any, status: Any, limit: Any, cursor: Any) -> dict[str, Any]: + if external_id and csid_id: + raise BadRequestError( + "Pass at most one of: external_id, csid_id.", code="invalid_parameter", parameter="external_id|csid_id" + ) + _one_of(status, COPY_INSTRUCTION_STATUSES, "status") + if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 100): + raise BadRequestError( + "limit must be a whole number from 1 to 100.", code="invalid_parameter", parameter="limit" + ) + return {"external_id": external_id, "csid_id": csid_id, "status": status, "limit": limit, "cursor": cursor} + + 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") @@ -1438,6 +1513,139 @@ def update_callout_settings( raise BadRequestError("Pass at least one setting.", code="missing_parameter", parameter="settings") return self._post("/callouts/settings", changes) + # ── copy trading ───────────────────────────────────────────────────── + # Every trade of a trader a user copies becomes a ready-to-execute instruction for + # that user, sized by their copy settings. CabalSpy ID never holds keys and never + # executes: your app executes the instruction with the user's wallet and reports the + # status back. Needs the user's consent with the scope trade_feed (else + # PermissionError consent_required). Copying a trader is switched on by one platform + # at a time: only its apps get the instructions (webhook copy_trade.instruction, + # copy_trading_stream(), copy_instructions()). + + def copy_trading_settings( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + trader: str | None = None, + trader_external_id: str | None = None, + ) -> Any: + """GET /v1/copy-trading/settings — the copy settings of a user's traders (everyone in + their Trade Feed, copied ones first), or of one ``trader`` (handle or csid_id; + ``trader_external_id`` for one of your platform users). + + Returns a list of :class:`~cabalspy_id.CopyTradingSetting`, or one with a trader. A + trader who is not in the user's Trade Feed raises NotFoundError ``not_in_trade_feed`` + (an unknown one ``trader_not_found``). + """ + who = _who(external_id, csid_id) + return self._get("/copy-trading/settings", {**who, **_copy_trader(trader, trader_external_id, required=False)}) + + def update_copy_trading_settings( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + trader: str | None = None, + trader_external_id: str | None = None, + enabled: bool | None = None, + mode: CopyMode | None = None, + amount_usd: float | None = None, + percent: float | None = None, + max_usd: float | _NotGiven | None = NOT_GIVEN, + sides: CopySides | None = None, + slippage_bps: int | None = None, + ) -> Any: + """POST /v1/copy-trading/settings — changes how a user copies one trader (handle or + csid_id, or ``trader_external_id``); the trader is added to their Trade Feed first if + needed. Only the settings you pass change (None = unchanged; ``max_usd=None`` removes + the cap). + + ``mode``: ``fixed_usd`` (every buy is ``amount_usd``, up to 1,000,000) or ``percent`` + (``percent`` % of the trader's buy, up to 1000); ``max_usd`` caps a buy; ``sides``: + ``buys`` or ``both`` (sells as a share of the copied position); ``slippage_bps`` + 1-5000 (default 300). Buys under $1 are not sent. + + While another platform copies this trader for the user, this raises ConflictError + ``copy_managed_elsewhere``. Returns :class:`~cabalspy_id.CopyTradingSetting` + (HTTP 201 when the trader was added to the Trade Feed). + """ + who = _who(external_id, csid_id) + target = _copy_trader(trader, trader_external_id, required=True) + fields = _copy_settings_fields( + enabled=enabled, + mode=mode, + amount_usd=amount_usd, + percent=percent, + max_usd=max_usd, + sides=sides, + slippage_bps=slippage_bps, + ) + return self._post("/copy-trading/settings", {**who, **target, **fields}) + + def copy_instructions( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + status: CopyInstructionStatus | None = None, + limit: int | None = None, + cursor: str | None = None, + ) -> Any: + """GET /v1/copy-trading/instructions — your instance's copy instructions, newest first + (``limit`` 1-100, default 50); one user's with ``external_id`` / ``csid_id``. + ``status``: pending, executed, failed, skipped or expired (pending past ``expires_at``). + + Returns a list of :class:`~cabalspy_id.CopyInstruction`; see ``iter_copy_instructions``. + """ + return self._get( + "/copy-trading/instructions", _copy_instructions_query(external_id, csid_id, status, limit, cursor) + ) + + def copy_instruction(self, id: str) -> Any: + """GET /v1/copy-trading/instructions/item — one instruction. Returns + :class:`~cabalspy_id.CopyInstruction`.""" + _required(id, "id") + return self._get("/copy-trading/instructions/item", {"id": id}) + + def report_copy_instruction( + self, + id: str, + *, + status: CopyReportStatus, + tx_signature: str | None = None, + executed_amount_usd: float | None = None, + note: str | None = None, + ) -> Any: + """POST /v1/copy-trading/instructions/status — what happened to an instruction: + ``executed`` (with ``tx_signature`` and ``executed_amount_usd``), ``failed`` or + ``skipped`` (``note`` up to 300 characters, e.g. the reason). + + A final status cannot change: the same report twice is fine, another one raises + ConflictError ``already_reported``. A copied buy reported failed or skipped means + the trader's later sells of that token are not sent. Expired instructions may still + be reported executed. Returns :class:`~cabalspy_id.CopyInstruction`. + """ + _required(id, "id") + _required(status, "status") + _one_of(status, COPY_REPORT_STATUSES, "status") + if tx_signature is not None and (not isinstance(tx_signature, str) or not 10 <= len(tx_signature) <= 200): + raise BadRequestError( + "tx_signature must be a transaction signature or hash (10-200 characters).", + code="invalid_parameter", + parameter="tx_signature", + ) + if executed_amount_usd is not None: + _number(executed_amount_usd, "executed_amount_usd", 0, 10_000_000) + body: dict[str, Any] = {"id": id, "status": status} + if tx_signature is not None: + body["tx_signature"] = tx_signature + if executed_amount_usd is not None: + body["executed_amount_usd"] = executed_amount_usd + if note is not None: + body["note"] = note + return self._post("/copy-trading/instructions/status", body) + # ═══════════════════════════════════════════════════════════════════════════ # CLIENTS @@ -1454,6 +1662,7 @@ def __init__( stream_url: str | None = None, theses_stream_url: str | None = None, callouts_stream_url: str | None = None, + copy_trading_stream_url: str | None = None, timeout: float = 30.0, max_retries: int = 2, headers: Mapping[str, str] | None = None, @@ -1467,6 +1676,7 @@ def __init__( self.stream_url = (stream_url or _env("CABALSPY_ID_STREAM_URL") or DEFAULT_STREAM_URL).rstrip("/") 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.timeout = timeout self.max_retries = max_retries self._extra_headers = dict(headers or {}) @@ -1604,6 +1814,17 @@ def callouts_stream(self, *, chain: Chain | None = None, mint: str | None = None self.callouts_stream_url, self._api_key, chain=chain, mint=mint, instance=self.instance, **kwargs ) + def copy_trading_stream(self, **kwargs: Any) -> CopyTradingStream: + """Every new copy instruction of your instance, live (``copy_trade.instruction``). Async only. + + Needs the ``stream`` extra: ``pip install "cabalspy-id[stream]"``. + """ + if not self._api_key: + raise AuthenticationError("The copy trading stream needs an API key.", status=401, code="missing_api_key") + from ._copy_trading_stream import CopyTradingStream + + return CopyTradingStream(self.copy_trading_stream_url, self._api_key, instance=self.instance, **kwargs) + class CabalSpyID(_BaseClient): """Synchronous Data API client. @@ -1882,6 +2103,21 @@ def iter_callout_leaderboard( for page in self.pages("/callouts/leaderboard", query): yield from page.data.get("leaderboard", []) + # ── copy trading ───────────────────────────────────────────────────── + + def iter_copy_instructions( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + status: CopyInstructionStatus | None = None, + limit: int | None = None, + ) -> Iterator[dict[str, Any]]: + """Every copy instruction matching the filters, newest first, following ``next_cursor``.""" + query = _copy_instructions_query(external_id, csid_id, status, limit, None) + for page in self.pages("/copy-trading/instructions", query): + yield from page.data + class AsyncCabalSpyID(_BaseClient): """Asynchronous Data API client. @@ -2157,6 +2393,22 @@ async def iter_callout_leaderboard( for entry in page.data.get("leaderboard", []): yield entry + # ── copy trading ───────────────────────────────────────────────────── + + async def iter_copy_instructions( + self, + external_id: str | None = None, + *, + csid_id: str | None = None, + status: CopyInstructionStatus | None = None, + limit: int | None = None, + ) -> AsyncIterator[dict[str, Any]]: + """Every copy instruction matching the filters, newest first, following ``next_cursor``.""" + query = _copy_instructions_query(external_id, csid_id, status, limit, None) + async for page in self.pages("/copy-trading/instructions", 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 08915b0..edc6680 100644 --- a/cabalspy_id/_constants.py +++ b/cabalspy_id/_constants.py @@ -4,7 +4,7 @@ from typing import Literal -SDK_VERSION = "0.7.0" +SDK_VERSION = "0.8.0" USER_AGENT = f"cabalspy-id-python/{SDK_VERSION}" DEFAULT_BASE_URL = "https://api-id.cabalspy.xyz/v1" @@ -63,6 +63,9 @@ "callout.scored", "callout.final", ) +#: 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 event types. WEBHOOK_EVENTS: tuple[str, ...] = ( "wallet.verified", @@ -77,6 +80,7 @@ *PLATFORM_WEBHOOK_EVENTS, *COMPETITION_WEBHOOK_EVENTS, *CALLOUT_WEBHOOK_EVENTS, + *COPY_TRADING_WEBHOOK_EVENTS, ) #: Reactions: "like" plus a fixed emoji set. @@ -205,3 +209,30 @@ CALLOUT_ACTIVE_MCAP_USD = 10_000 #: Callout stream connections per API key. MAX_CALLOUT_STREAMS_PER_KEY = 5 + +# ── copy trading ───────────────────────────────────────────────────────────── + +DEFAULT_COPY_TRADING_STREAM_URL = "wss://api-id.cabalspy.xyz/v1/copy-trading/stream" +#: fixed_usd: every copied buy is ``amount_usd``; percent: ``percent`` % of the trader's buy (in USD). +CopyMode = Literal["fixed_usd", "percent"] +COPY_MODES: tuple[CopyMode, ...] = ("fixed_usd", "percent") +#: buys: only buys are copied; both: sells too (as "sell X % of the copied position"). +CopySides = Literal["buys", "both"] +COPY_SIDES: tuple[CopySides, ...] = ("buys", "both") +#: An instruction's status. ``expired``: still pending after ``expires_at`` (it may still be +#: reported as executed). +CopyInstructionStatus = Literal["pending", "executed", "failed", "skipped", "expired"] +COPY_INSTRUCTION_STATUSES: tuple[CopyInstructionStatus, ...] = ("pending", "executed", "failed", "skipped", "expired") +#: The statuses your app reports back (final; the same report twice is fine). +CopyReportStatus = Literal["executed", "failed", "skipped"] +COPY_REPORT_STATUSES: tuple[CopyReportStatus, ...] = ("executed", "failed", "skipped") +#: buy or sell. +CopySide = Literal["buy", "sell"] +#: Seconds an instruction is meant to be executed in (``expires_at`` - ``created_at``). +COPY_INSTRUCTION_TTL_SECONDS = 120 +#: Copied buys below this many USD are not sent. +COPY_MIN_USD = 1.0 +#: Default price limit of the instructions in basis points (3 %). +COPY_DEFAULT_SLIPPAGE_BPS = 300 +#: Copy trading stream connections per API key. +MAX_COPY_TRADING_STREAMS_PER_KEY = 5 diff --git a/cabalspy_id/_copy_trading_stream.py b/cabalspy_id/_copy_trading_stream.py new file mode 100644 index 0000000..e196d11 --- /dev/null +++ b/cabalspy_id/_copy_trading_stream.py @@ -0,0 +1,369 @@ +"""Copy trading stream: wss://api-id.cabalspy.xyz/v1/copy-trading/stream. + +Every new copy instruction of your instance, live (``copy_trade.instruction``): +execute it with the user's wallet before ``expires_at``, then report the result +with ``report_copy_instruction``. The same instructions arrive as the webhook +``copy_trade.instruction`` and stay readable through ``copy_instructions()``. + + async with AsyncCabalSpyID() as csid: + cs = csid.copy_trading_stream() + + @cs.on("copy_trade.instruction") + async def _(i): + a = i["action"] + print(i["csid_id"], a["side"], a["amount_usd"] or f"{a['sell_percent']} %", a["symbol"]) + + await cs.connect() # returns on "ready" + await cs.run_forever() + + # or iterate ({"event": ..., "id": ..., "data": ...}): + async with csid.copy_trading_stream() as cs: + async for ev in cs: + ... +""" + +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 copy trading events: copy_trade.instruction (a CopyInstruction plus external_id). +COPY_TRADING_EVENTS = ("copy_trade.instruction",) +#: Events: ready, the copy trading events, heartbeat, pong, open, close, reconnecting, error. +COPY_TRADING_STREAM_EVENTS = ( + "ready", + *COPY_TRADING_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 CopyTradingStream: + """Async client for the copy trading stream. Obtain one via ``client.copy_trading_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 copy trading 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 + self._keepers: list[tuple[str, 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. + + ``copy_trade.instruction`` handlers get the instruction (``data``); its ``id`` is + the instruction id. + """ + if event not in COPY_TRADING_STREAM_EVENTS: + raise ValueError(f"unknown event {event!r}; one of {', '.join(COPY_TRADING_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 copy trading 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"Copy trading 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 COPY_TRADING_EVENTS: + await self._emit(str(event), msg.get("data")) + 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) -> CopyTradingStream: + # Events that arrive between connecting and the first loop are kept for it. + self._backlog = [] + backlog = self._backlog + keepers = [(name, self._keeper(backlog, name)) for name in COPY_TRADING_EVENTS] + for name, fn in keepers: + self.on(name, fn) + self._keepers = keepers + try: + await self.connect() + except BaseException: + self._drop_backlog() + raise + return self + + async def __aexit__(self, *exc: Any) -> None: + await self.close() + + @staticmethod + def _item(name: str, data: Any) -> dict[str, Any]: + return {"event": name, "id": data.get("id") if isinstance(data, dict) else None, "data": data} + + @classmethod + def _keeper(cls, backlog: list[Any], name: str) -> Handler: + return lambda data: backlog.append(cls._item(name, data)) + + def _drop_backlog(self) -> list[Any]: + backlog, self._backlog = self._backlog or [], None + for name, fn in self._keepers: + self.off(name, fn) + self._keepers = [] + return backlog + + async def __aiter__(self) -> AsyncIterator[dict[str, Any]]: + """Iterates over the instructions as ``{"event": ..., "id": ..., "data": ...}``; 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) + + def listener(name: str) -> Handler: + return lambda data: queue.put_nowait(self._item(name, data)) + + listeners = [(name, listener(name)) for name in COPY_TRADING_EVENTS] + + 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) + + for name, fn in listeners: + self.on(name, fn) + 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: + for name, fn in listeners: + self.off(name, fn) + self.off("error", on_error) + self.off("close", on_close) + if owns and not self._closed: + await self.close() diff --git a/cabalspy_id/_errors.py b/cabalspy_id/_errors.py index 7a291b0..0c62c52 100644 --- a/cabalspy_id/_errors.py +++ b/cabalspy_id/_errors.py @@ -98,6 +98,9 @@ class PermissionError_(CabalSpyIDError): Callouts: feature_not_enabled (callouts, and callout competitions, are switched on 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. """ @@ -116,7 +119,8 @@ class PlanUserLimitError(PermissionError_): 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.""" + 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).""" class ConflictError(CabalSpyIDError): @@ -126,7 +130,9 @@ class ConflictError(CabalSpyIDError): wallet_already_verified, already_verified, kol_badge, x_required, kol_not_eligible, volume_check_unavailable. Competitions: competition_limit, competition_closed, competition_full, late_join_closed. Callouts: already_called - (the user called this token less than 24 hours ago). + (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. """ diff --git a/cabalspy_id/_types.py b/cabalspy_id/_types.py index 41e5419..d657b96 100644 --- a/cabalspy_id/_types.py +++ b/cabalspy_id/_types.py @@ -25,6 +25,10 @@ CompetitionKind, CompetitionMetric, CompetitionStatus, + CopyInstructionStatus, + CopyMode, + CopySide, + CopySides, Currency, DataScope, LeaderboardSort, @@ -1442,3 +1446,142 @@ class CalloutWebhookData(TypedDict, total=False): callout: Callout #: callout.milestone only. milestone_x: float + + +# ── copy trading ───────────────────────────────────────────────────────────── + + +class CopyTrader(TypedDict): + """A copied trader as everyone may see them. A platform's own (managed) users have + ``username`` and ``profile_url`` None.""" + + csid_id: str + username: str | None + name: str | None + image_url: str | None + kol: bool + profile_url: str | None + + +class CopySettings(TypedDict): + """How one user copies one trader.""" + + enabled: bool + #: fixed_usd: every buy is ``amount_usd``; percent: ``percent`` % of the trader's buy. + mode: CopyMode + amount_usd: float + #: Percent of the trader's buy in USD (mode percent), above 0 and at most 1000. + percent: float + #: Cap per copied buy in USD; None = no cap. + max_usd: float | None + #: buys, or both (sells are copied as a share of the copied position). + sides: CopySides + #: Price limit sent with every instruction (1-5000, default 300 = 3 %). + slippage_bps: int + updated_at: str | None + + +class CopyTradingSetting(TypedDict): + """GET/POST /v1/copy-trading/settings: one trader in the user's Trade Feed and the copy settings.""" + + trader: CopyTrader + copy: CopySettings + #: True while another platform copies this trader for this user (only that platform + #: gets the instructions; switching it on here raises ``copy_managed_elsewhere``). + managed_by_other_platform: bool + + +class CopyAction(TypedDict): + """What to execute. Buys: ``amount_usd`` (and ``amount_native`` in ``currency``) with + ``max_price_usd`` as the price limit. Sells: ``sell_percent`` of the copied position + with ``min_price_usd`` as the price limit.""" + + blockchain: Chain + mint: str + symbol: str | None + name: str | None + logo: str | None + side: CopySide + #: Buys only. + amount_usd: float | None + #: Buys only, when known: the same amount in the chain's native currency. + amount_native: float | None + currency: Currency | None + #: Sells only: percent of the copied position to sell (100 = everything). + sell_percent: float | None + #: The trader's price. + price_usd: float | None + #: Buys: price_usd * (1 + slippage_bps / 10000). + max_price_usd: float | None + #: Sells: price_usd * (1 - slippage_bps / 10000). + min_price_usd: float | None + slippage_bps: int + + +class CopySourceTrade(TypedDict, total=False): + """The trader's trade that was copied (as in the Trade Feed).""" + + blockchain: Chain + mint: str + symbol: str | None + name: str | None + logo: str | None + side: CopySide + #: new, add, partial, close or sell. + label: str + #: partial sells: percent of the position the trader sold. + sold_percent: float | None + amount_native: float + currency: Currency | None + amount_usd: float | None + token_amount: float | None + price_usd: float | None + pnl_usd: float | None + pnl_percent: float | None + wallet: str + wallet_url: str | None + tx_signature: str + tx_url: str | None + + +class CopyLinks(TypedDict, total=False): + token: str | None + terminal: str | None + profile: str | None + + +class _CopyInstructionOptional(TypedDict, total=False): + #: Webhook and stream only: your platform's user id (white-label), else None. + external_id: str | None + # REST only (the webhook and the stream send the new, pending instruction without them): + #: As reported with the status. + tx_signature: str | None + executed_amount_usd: float | None + note: str | None + updated_at: str + + +class CopyInstruction(_CopyInstructionOptional): + """A ready-to-execute copy instruction: execute ``action`` with the user's wallet, then + report the result with ``report_copy_instruction``. CabalSpy ID never holds keys and + never executes.""" + + id: str + type: Literal["copy_instruction"] + #: pending, executed, failed, skipped; ``expired`` = still pending after ``expires_at``. + status: CopyInstructionStatus + created_at: str + #: ``created_at`` + 120 seconds. + expires_at: str + #: The user to execute it for. + csid_id: str + trader: CopyTrader + action: CopyAction + source_trade: CopySourceTrade + #: The copy settings when the instruction was made. + settings: CopySettings + links: CopyLinks + + +class CopyTradingStreamReady(TypedDict): + events: list[str] diff --git a/cabalspy_id/api.py b/cabalspy_id/api.py index 177aeab..0249991 100644 --- a/cabalspy_id/api.py +++ b/cabalspy_id/api.py @@ -1,7 +1,8 @@ """``cabalspy_id.api`` — the SocialFi API: Data API clients (users, profiles, verified wallets, trading stats, leaderboards, white-label platform users, -trading competitions and callouts), the live trade and callout streams, Login with CabalSpy ID (OpenID -Connect) and webhook verification. +trading competitions, callouts and copy trading), the live trade, callout and +copy trading streams, Login with CabalSpy ID (OpenID Connect) and webhook +verification. from cabalspy_id.api import CabalSpyID, CabalSpyIDAuth, verify_webhook @@ -26,16 +27,26 @@ COMPETITION_METRICS, COMPETITION_STATUSES, COMPETITION_WEBHOOK_EVENTS, + COPY_DEFAULT_SLIPPAGE_BPS, + COPY_INSTRUCTION_STATUSES, + COPY_INSTRUCTION_TTL_SECONDS, + COPY_MIN_USD, + COPY_MODES, + COPY_REPORT_STATUSES, + COPY_SIDES, + COPY_TRADING_WEBHOOK_EVENTS, CURRENCY_BY_CHAIN, DATA_SCOPES, DEFAULT_BASE_URL, DEFAULT_CALLOUTS_STREAM_URL, + DEFAULT_COPY_TRADING_STREAM_URL, DEFAULT_ISSUER, DEFAULT_STREAM_URL, FEATURE_CALLOUTS, INBOUND_FORMATS, LEADERBOARD_SORTS, MAX_CALLOUT_STREAMS_PER_KEY, + MAX_COPY_TRADING_STREAMS_PER_KEY, MAX_OPEN_COMPETITIONS, MAX_REQUEST_BODY_BYTES, PERIODS, @@ -99,6 +110,19 @@ CompetitionStandings, CompetitionStatus, ConflictError, + CopyAction, + CopyInstruction, + CopyInstructionStatus, + CopyLinks, + CopyMode, + CopyReportStatus, + CopySettings, + CopySide, + CopySides, + CopySourceTrade, + CopyTrader, + CopyTradingSetting, + CopyTradingStreamReady, Currency, DataScope, DiscoveryDocument, @@ -417,14 +441,42 @@ "CalloutRemovedEvent", "CalloutsStreamReady", "CalloutWebhookData", + # copy trading + "CopyTradingStream", + "COPY_TRADING_STREAM_EVENTS", + "COPY_TRADING_EVENTS", + "COPY_TRADING_WEBHOOK_EVENTS", + "COPY_MODES", + "COPY_SIDES", + "COPY_INSTRUCTION_STATUSES", + "COPY_REPORT_STATUSES", + "COPY_INSTRUCTION_TTL_SECONDS", + "COPY_MIN_USD", + "COPY_DEFAULT_SLIPPAGE_BPS", + "MAX_COPY_TRADING_STREAMS_PER_KEY", + "DEFAULT_COPY_TRADING_STREAM_URL", + "CopyMode", + "CopySides", + "CopySide", + "CopyInstructionStatus", + "CopyReportStatus", + "CopyTrader", + "CopySettings", + "CopyTradingSetting", + "CopyAction", + "CopySourceTrade", + "CopyLinks", + "CopyInstruction", + "CopyTradingStreamReady", ] _LAZY_CALLOUTS = ("CalloutsStream", "CALLOUTS_STREAM_EVENTS", "CALLOUT_EVENTS") +_LAZY_COPY_TRADING = ("CopyTradingStream", "COPY_TRADING_STREAM_EVENTS", "COPY_TRADING_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): + if name in ("CabalSpyIDStream", "STREAM_EVENTS", *_LAZY_CALLOUTS, *_LAZY_COPY_TRADING): return getattr(_root, name) raise AttributeError(f"module 'cabalspy_id.api' has no attribute {name!r}") diff --git a/examples/copy_trading.py b/examples/copy_trading.py new file mode 100644 index 0000000..a0cd730 --- /dev/null +++ b/examples/copy_trading.py @@ -0,0 +1,110 @@ +"""Copy trading tour: copy a trader for one of your users, execute the instructions, report back. + + pip install "cabalspy-id[stream]" # the stream part only + CABALSPY_API_KEY=... python examples/copy_trading.py + +CabalSpy ID never holds keys and never executes: every trade of a copied trader +becomes an instruction for your app, which executes it with the user's wallet and +reports the result. The user needs to have allowed your app the scope trade_feed. +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, +) + +USER = "user_1" # your platform's user id (external_id) +TRADER = "ctkol" # a CabalSpy ID handle or csid_id + + +def execute(instruction: Any) -> str | None: + """Your swap with the user's wallet. Returns the transaction signature, or None.""" + a = instruction["action"] + if a["side"] == "buy": + print(f" buy ${a['amount_usd']} of {a['symbol']} on {a['blockchain']}, at most ${a['max_price_usd']}") + else: + print(f" sell {a['sell_percent']} % of the copied {a['symbol']}, at least ${a['min_price_usd']}") + return None # placeholder: nothing is executed in this example + + +def report(csid: CabalSpyID, instruction: Any) -> None: + sig = execute(instruction) + if sig: + csid.report_copy_instruction( + instruction["id"], + status="executed", + tx_signature=sig, + executed_amount_usd=instruction["action"]["amount_usd"], + ) + else: + csid.report_copy_instruction(instruction["id"], status="skipped", note="example: not executed") + + +def tour() -> None: + with CabalSpyID() as csid: # reads CABALSPY_ID_API_KEY or CABALSPY_API_KEY + # 1. Copy the trader: $25 per buy, at most $20, buys and sells, 1.5 % price limit + try: + s = csid.update_copy_trading_settings( + USER, + trader=TRADER, + enabled=True, + mode="fixed_usd", + amount_usd=25, + max_usd=20, + sides="both", + slippage_bps=150, + ) + print("copying", s["trader"]["username"], s["copy"]) + except ConflictError as err: # copy_managed_elsewhere: another platform copies this trader + print("managed elsewhere:", err.message) + except PermissionError as err: # consent_required: no trade_feed scope + print("not allowed:", err.code) + return + except NotFoundError as err: # trader_not_found + print("no such trader:", err.code) + return + + # 2. Everyone in the user's Trade Feed and how they are copied + for s in csid.copy_trading_settings(USER): + print(f" {s['trader']['username']}: {s['copy']['enabled']} (elsewhere: {s['managed_by_other_platform']})") + + # 3. Pending instructions, newest first: execute and report each + for i in csid.iter_copy_instructions(USER, status="pending"): + report(csid, i) + + # 4. Percent mode, buys only, no cap + csid.update_copy_trading_settings(USER, trader=TRADER, mode="percent", percent=10, sides="buys", max_usd=None) + + +async def live() -> None: + """New instructions as they happen (the webhook copy_trade.instruction carries the same).""" + async with AsyncCabalSpyID() as csid: + cs = csid.copy_trading_stream() + + @cs.on("copy_trade.instruction") + async def on_instruction(i: Any) -> None: + print("instruction", i["id"], "for", i.get("external_id") or i["csid_id"], i["action"]["side"]) + await csid.report_copy_instruction(i["id"], status="skipped", note="example") + + cs.on("error", lambda err: print("stream error:", err)) + print("ready:", await cs.connect()) + try: + await asyncio.wait_for(cs.run_forever(), timeout=60) + except asyncio.TimeoutError: + pass + finally: + await cs.close() + + +if __name__ == "__main__": + tour() + asyncio.run(live()) diff --git a/pyproject.toml b/pyproject.toml index 7438d0d..9254f05 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cabalspy-id" -version = "0.7.0" +version = "0.8.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_callouts.py b/tests/test_callouts.py index a46c82d..886624c 100644 --- a/tests/test_callouts.py +++ b/tests/test_callouts.py @@ -349,7 +349,6 @@ def test_callout_webhook_events() -> None: def test_exports() -> None: import cabalspy_id - assert cabalspy_id.__version__ == "0.7.0" assert api.CalloutsStream is cabalspy_id.CalloutsStream assert "callout.update" in cabalspy_id.CALLOUT_EVENTS assert "ready" in cabalspy_id.CALLOUTS_STREAM_EVENTS diff --git a/tests/test_copy_trading.py b/tests/test_copy_trading.py new file mode 100644 index 0000000..4e7a21b --- /dev/null +++ b/tests/test_copy_trading.py @@ -0,0 +1,389 @@ +"""Copy trading (settings per user and trader, instructions, status reports), against mocked HTTP.""" + +from __future__ import annotations + +from typing import Any + +import httpx +import pytest + +from cabalspy_id import ( + COPY_INSTRUCTION_STATUSES, + COPY_REPORT_STATUSES, + COPY_TRADING_WEBHOOK_EVENTS, + WEBHOOK_EVENTS, + AsyncCabalSpyID, + BadRequestError, + CabalSpyID, + ConflictError, + NotFoundError, + PermissionError, + RateLimitError, + ServerError, + api, +) + +from .conftest import Recorder, api_error, ok +from .test_platform_users import call, make, query + +KEY = "csid_api_testkey" +MINT = "So11111111111111111111111111111111111111112" +TX = "5" * 88 + +TRADER: dict[str, Any] = { + "csid_id": "t1", + "username": "ctkol", + "name": "Ctkol", + "image_url": None, + "kol": True, + "profile_url": "https://id.cabalspy.xyz/u/ctkol", +} +COPY: dict[str, Any] = { + "enabled": True, + "mode": "fixed_usd", + "amount_usd": 25.0, + "percent": 100.0, + "max_usd": 20.0, + "sides": "both", + "slippage_bps": 300, + "updated_at": "2026-11-01T12:00:00Z", +} +SETTING: dict[str, Any] = {"trader": TRADER, "copy": COPY, "managed_by_other_platform": False} +INSTRUCTION: dict[str, Any] = { + "id": "9f0b1c2d-0000-4000-8000-000000000001", + "type": "copy_instruction", + "status": "pending", + "created_at": "2026-11-01T12:00:00Z", + "expires_at": "2026-11-01T12:02:00Z", + "csid_id": "f1", + "trader": TRADER, + "action": { + "blockchain": "solana", + "mint": MINT, + "symbol": "CPT", + "name": None, + "logo": None, + "side": "buy", + "amount_usd": 20.0, + "amount_native": 0.133333333, + "currency": "SOL", + "sell_percent": None, + "price_usd": 0.15, + "max_price_usd": 0.1545, + "min_price_usd": None, + "slippage_bps": 300, + }, + "source_trade": {"blockchain": "solana", "mint": MINT, "side": "buy", "label": "new", "amount_usd": 150.0}, + "settings": COPY, + "links": {"token": None, "terminal": None, "profile": None}, + "tx_signature": None, + "executed_amount_usd": None, + "note": None, + "updated_at": "2026-11-01T12:00:00Z", +} + + +# ── every endpoint: method, path, query / body ─────────────────────────────── + + +def test_every_copy_trading_endpoint() -> None: + csid, rec = make() + csid.copy_trading_settings("u1") + csid.copy_trading_settings(csid_id="f1", trader="ctkol") + csid.copy_trading_settings("u1", trader_external_id="u2") + csid.update_copy_trading_settings( + "u1", + trader="ctkol", + enabled=True, + mode="fixed_usd", + amount_usd=25, + max_usd=20, + sides="buys", + slippage_bps=150, + ) + csid.update_copy_trading_settings(csid_id="f1", trader_external_id="u2", mode="percent", percent=10, max_usd=None) + csid.update_copy_trading_settings("u1", trader="t1", enabled=False) + csid.copy_instructions() + csid.copy_instructions("u1", status="expired", limit=2, cursor="abc") + csid.copy_instructions(csid_id="f1", status="executed") + csid.copy_instruction("i1") + csid.report_copy_instruction("i1", status="executed", tx_signature=TX, executed_amount_usd=19.8) + csid.report_copy_instruction("i2", status="failed", note="insufficient balance") + csid.report_copy_instruction("i3", status="skipped") + + assert [call(r) for r in rec.requests] == [ + ("GET", "/v1/copy-trading/settings", {"external_id": "u1"}), + ("GET", "/v1/copy-trading/settings", {"csid_id": "f1", "trader": "ctkol"}), + ("GET", "/v1/copy-trading/settings", {"external_id": "u1", "trader_external_id": "u2"}), + ( + "POST", + "/v1/copy-trading/settings", + { + "external_id": "u1", + "trader": "ctkol", + "enabled": True, + "mode": "fixed_usd", + "amount_usd": 25, + "max_usd": 20, + "sides": "buys", + "slippage_bps": 150, + }, + ), + ( + "POST", + "/v1/copy-trading/settings", + {"csid_id": "f1", "trader_external_id": "u2", "mode": "percent", "percent": 10, "max_usd": None}, + ), + ("POST", "/v1/copy-trading/settings", {"external_id": "u1", "trader": "t1", "enabled": False}), + ("GET", "/v1/copy-trading/instructions", {}), + ( + "GET", + "/v1/copy-trading/instructions", + {"external_id": "u1", "status": "expired", "limit": "2", "cursor": "abc"}, + ), + ("GET", "/v1/copy-trading/instructions", {"csid_id": "f1", "status": "executed"}), + ("GET", "/v1/copy-trading/instructions/item", {"id": "i1"}), + ( + "POST", + "/v1/copy-trading/instructions/status", + {"id": "i1", "status": "executed", "tx_signature": TX, "executed_amount_usd": 19.8}, + ), + ( + "POST", + "/v1/copy-trading/instructions/status", + {"id": "i2", "status": "failed", "note": "insufficient balance"}, + ), + ("POST", "/v1/copy-trading/instructions/status", {"id": "i3", "status": "skipped"}), + ] + assert all(r.headers["Authorization"] == f"Bearer {KEY}" for r in rec.requests) + + +def test_returns_settings_and_instruction() -> None: + def handler(r: httpx.Request) -> httpx.Response: + if r.url.path == "/v1/copy-trading/settings": + if r.method == "POST": + return httpx.Response(201, json={"success": True, "data": SETTING}) + return ok(SETTING if query(r).get("trader") else [SETTING]) + if r.url.path == "/v1/copy-trading/instructions": + return ok([INSTRUCTION], pagination={"limit": 50, "next_cursor": None, "has_more": False}) + return ok({**INSTRUCTION, "status": "executed", "tx_signature": TX, "executed_amount_usd": 19.8}) + + csid, _ = make(handler) + s = csid.update_copy_trading_settings("u1", trader="ctkol", enabled=True) + assert s["copy"]["max_usd"] == 20.0 and s["trader"]["username"] == "ctkol" + assert not s["managed_by_other_platform"] + assert csid.copy_trading_settings("u1")[0]["copy"]["enabled"] is True + assert csid.copy_trading_settings("u1", trader="ctkol")["copy"]["slippage_bps"] == 300 + i = csid.copy_instructions("u1")[0] + assert i["type"] == "copy_instruction" and i["action"]["side"] == "buy" and i["action"]["max_price_usd"] == 0.1545 + done = csid.report_copy_instruction(i["id"], status="executed", tx_signature=TX, executed_amount_usd=19.8) + assert done["status"] == "executed" and done["executed_amount_usd"] == 19.8 + + +def test_copy_trading_validation() -> None: + csid, rec = make() + with pytest.raises(BadRequestError): + csid.copy_trading_settings() # no user + with pytest.raises(BadRequestError): + csid.copy_trading_settings("u1", csid_id="f1") # both + with pytest.raises(BadRequestError) as e: + csid.copy_trading_settings("u1", trader="a", trader_external_id="b") + assert e.value.parameter == "trader|trader_external_id" + with pytest.raises(BadRequestError) as e: + csid.update_copy_trading_settings("u1", enabled=True) # no trader + assert e.value.parameter == "trader" + with pytest.raises(BadRequestError) as e: + csid.update_copy_trading_settings("u1", trader="ctkol") # no setting + assert e.value.code == "missing_parameter" + with pytest.raises(BadRequestError) as e: + csid.update_copy_trading_settings("u1", trader="ctkol", mode="all_in") # type: ignore[arg-type] + assert e.value.allowed == ["fixed_usd", "percent"] + with pytest.raises(BadRequestError) as e: + csid.update_copy_trading_settings("u1", trader="ctkol", sides="sells") # type: ignore[arg-type] + assert e.value.allowed == ["buys", "both"] + with pytest.raises(BadRequestError) as e: + csid.update_copy_trading_settings("u1", trader="ctkol", enabled="yes") # type: ignore[arg-type] + assert e.value.parameter == "enabled" + bad: list[tuple[str, Any]] = [ + ("amount_usd", 0), + ("amount_usd", 1_000_001), + ("amount_usd", "abc"), + ("amount_usd", float("inf")), + ("percent", 2000), + ("percent", -1), + ("max_usd", 0), + ("max_usd", True), + ("slippage_bps", 0), + ("slippage_bps", 5001), + ("slippage_bps", 2.5), + ] + for name, value in bad: + with pytest.raises(BadRequestError) as e: + csid.update_copy_trading_settings("u1", trader="ctkol", **{name: value}) + assert e.value.parameter == name, (name, value) + with pytest.raises(BadRequestError): + csid.copy_instructions("u1", csid_id="f1") + with pytest.raises(BadRequestError) as e: + csid.copy_instructions(status="bogus") # type: ignore[arg-type] + assert e.value.allowed == list(COPY_INSTRUCTION_STATUSES) + for bad_limit in (0, 101, True): + with pytest.raises(BadRequestError): + csid.copy_instructions(limit=bad_limit) + with pytest.raises(BadRequestError): + csid.copy_instruction("") + with pytest.raises(BadRequestError): + csid.report_copy_instruction("", status="executed") + with pytest.raises(BadRequestError) as e: + csid.report_copy_instruction("i1", status="done") # type: ignore[arg-type] + assert e.value.allowed == list(COPY_REPORT_STATUSES) + with pytest.raises(BadRequestError) as e: + csid.report_copy_instruction("i1", status="pending") # type: ignore[arg-type] + assert e.value.parameter == "status" + with pytest.raises(BadRequestError) as e: + csid.report_copy_instruction("i1", status="executed", tx_signature="short") + assert e.value.parameter == "tx_signature" + with pytest.raises(BadRequestError) as e: + csid.report_copy_instruction("i1", status="executed", executed_amount_usd=0) + assert e.value.parameter == "executed_amount_usd" + assert rec.requests == [] + + +def test_none_leaves_settings_unchanged() -> None: + csid, rec = make() + csid.update_copy_trading_settings("u1", trader="ctkol", enabled=None, amount_usd=None, sides="both") + assert call(rec.requests[0])[2] == {"external_id": "u1", "trader": "ctkol", "sides": "both"} + + +# ── iterators, async ───────────────────────────────────────────────────────── + + +def test_iter_copy_instructions_follows_cursor() -> None: + def handler(r: httpx.Request) -> httpx.Response: + if query(r).get("cursor") is None: + return ok([{"id": "i1"}, {"id": "i2"}], pagination={"limit": 2, "has_more": True, "next_cursor": "n1"}) + return ok([{"id": "i3"}], pagination={"limit": 2, "has_more": False, "next_cursor": None}) + + csid, rec = make(handler) + assert [i["id"] for i in csid.iter_copy_instructions("u1", status="pending", limit=2)] == ["i1", "i2", "i3"] + assert [query(r) for r in rec.requests] == [ + {"external_id": "u1", "status": "pending", "limit": "2"}, + {"external_id": "u1", "status": "pending", "limit": "2", "cursor": "n1"}, + ] + + +async def test_async_copy_trading() -> None: + def handler(r: httpx.Request) -> httpx.Response: + if r.url.path == "/v1/copy-trading/settings": + return ok(SETTING if r.method == "POST" or query(r).get("trader") else [SETTING]) + if r.url.path == "/v1/copy-trading/instructions": + if query(r).get("cursor"): + return ok([{"id": "i2"}], pagination={"has_more": False, "next_cursor": None}) + return ok([{"id": "i1"}], pagination={"has_more": True, "next_cursor": "n"}) + return ok(INSTRUCTION) + + rec = Recorder(handler) + async with AsyncCabalSpyID(KEY, http_client=rec.async_client(), max_retries=0) as csid: + assert (await csid.copy_trading_settings("u1"))[0]["trader"]["csid_id"] == "t1" + assert (await csid.copy_trading_settings("u1", trader="t1"))["copy"]["mode"] == "fixed_usd" + s = await csid.update_copy_trading_settings("u1", trader="t1", amount_usd=5) + assert s["copy"]["enabled"] + assert (await csid.copy_instructions())[0]["id"] == "i1" + assert [i["id"] async for i in csid.iter_copy_instructions(csid_id="f1")] == ["i1", "i2"] + assert (await csid.copy_instruction("i1"))["status"] == "pending" + assert (await csid.report_copy_instruction("i1", status="skipped"))["id"] == INSTRUCTION["id"] + assert call(rec.requests[2]) == ( + "POST", + "/v1/copy-trading/settings", + {"external_id": "u1", "trader": "t1", "amount_usd": 5}, + ) + + +# ── errors ─────────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("status", "code", "cls"), + [ + (403, "consent_required", PermissionError), + (403, "trading_private", PermissionError), + (404, "trader_not_found", NotFoundError), + (409, "copy_managed_elsewhere", ConflictError), + (409, "trade_feed_full", ConflictError), + ], +) +def test_settings_errors(status: int, code: str, cls: type[Exception]) -> None: + csid, rec = make(lambda r: api_error(status, code)) + with pytest.raises(cls) as e: + csid.update_copy_trading_settings("u1", trader="ctkol", enabled=True) + assert e.value.code == code # type: ignore[attr-defined] + assert e.value.status == status # type: ignore[attr-defined] + assert len(rec.requests) == 1 + + +def test_not_in_trade_feed() -> None: + csid, _ = make(lambda r: api_error(404, "not_in_trade_feed")) + with pytest.raises(NotFoundError) as e: + csid.copy_trading_settings("u1", trader="someone") + assert e.value.code == "not_in_trade_feed" + + +@pytest.mark.parametrize( + ("status", "code", "cls"), + [ + (409, "already_reported", ConflictError), + (404, "not_found", NotFoundError), + (400, "invalid_parameter", BadRequestError), + ], +) +def test_report_errors(status: int, code: str, cls: type[Exception]) -> None: + csid, rec = make(lambda r: api_error(status, code)) + with pytest.raises(cls) as e: + csid.report_copy_instruction("i1", status="failed") + assert e.value.code == code # type: ignore[attr-defined] + assert len(rec.requests) == 1 + + +def test_report_is_not_retried_after_5xx(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("cabalspy_id._client.time.sleep", lambda s: None) + csid, rec = make(lambda r: api_error(503, "service_unavailable"), max_retries=3) + with pytest.raises(ServerError): + csid.report_copy_instruction("i1", status="executed") + assert len(rec.requests) == 1 + # the trade feed's own rate limit on settings is not retried either (only rate_limit_exceeded is) + csid, rec = make(lambda r: api_error(429, "rate_limited", headers={"Retry-After": "0"}), max_retries=2) + with pytest.raises(RateLimitError): + csid.update_copy_trading_settings("u1", trader="ctkol", enabled=True) + assert len(rec.requests) == 1 + + +# ── webhooks, exports, options ─────────────────────────────────────────────── + + +def test_copy_trading_webhook_events() -> None: + assert COPY_TRADING_WEBHOOK_EVENTS == ("copy_trade.instruction",) + assert set(COPY_TRADING_WEBHOOK_EVENTS) <= set(WEBHOOK_EVENTS) + + +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 + for name in ( + "CopyInstruction", + "CopyTradingSetting", + "CopySettings", + "CopyAction", + "CopyTrader", + "COPY_MODES", + "COPY_TRADING_WEBHOOK_EVENTS", + "CopyTradingStream", + ): + assert name in cabalspy_id.__all__ and name in api.__all__ + + +def test_client_option() -> None: + assert CabalSpyID("k", copy_trading_stream_url="ws://x/y/").copy_trading_stream_url == "ws://x/y" + assert CabalSpyID("k").copy_trading_stream_url == "wss://api-id.cabalspy.xyz/v1/copy-trading/stream" diff --git a/tests/test_copy_trading_stream.py b/tests/test_copy_trading_stream.py new file mode 100644 index 0000000..a2dcd74 --- /dev/null +++ b/tests/test_copy_trading_stream.py @@ -0,0 +1,202 @@ +"""CopyTradingStream against a local server that behaves like /v1/copy-trading/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 ( + COPY_TRADING_EVENTS, + AuthenticationError, + CabalSpyID, + PermissionError, + RateLimitError, +) + +INSTRUCTION = { + "id": "i1", + "type": "copy_instruction", + "status": "pending", + "csid_id": "f1", + "external_id": "u1", + "action": {"side": "buy", "amount_usd": 20.0, "symbol": "CPT"}, +} +EVENTS = [ + {"event": "copy_trade.instruction", "id": "i1", "data": INSTRUCTION}, + {"event": "copy_trade.instruction", "id": "i2", "data": {**INSTRUCTION, "id": "i2", "external_id": None}}, +] + + +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 copy trading 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(COPY_TRADING_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/copy-trading/stream" # type: ignore[attr-defined] + yield s + + +def client(s: Server, **kwargs: Any) -> CabalSpyID: + return CabalSpyID("k", copy_trading_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: + cs = client(server, instance="csid_app").copy_trading_stream() + got: list[tuple[str, Any]] = [] + for name in (*COPY_TRADING_EVENTS, "heartbeat", "pong"): + cs.on(name, lambda d, name=name: got.append((name, d))) + ready = await cs.connect() + assert ready == {"events": ["copy_trade.instruction"]} + 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 cs.safe_url.split("api_key=")[1] + await wait_for(lambda: len(got) >= 3) + await cs.ping() + await wait_for(lambda: got[-1][0] == "pong") + await cs.close() + assert [n for n, _ in got] == ["heartbeat", "copy_trade.instruction", "copy_trade.instruction", "pong"] + assert got[1][1]["action"]["amount_usd"] == 20.0 + assert got[1][1]["external_id"] == "u1" + assert got[2][1]["id"] == "i2" + assert got[0][1] == {"ts": 1} + assert json.loads(server.received[0]) == {"op": "ping"} + assert not cs.connected + + +async def test_async_handlers_and_decorator(server: Server) -> None: + cs = client(server).copy_trading_stream() + seen: list[str] = [] + + @cs.on("copy_trade.instruction") + async def on_instruction(i: Any) -> None: + seen.append(i["id"]) + if i["id"] == "i2": + raise ValueError("handler failed") + + errors: list[Any] = [] + cs.on("error", errors.append) + await cs.connect() + await wait_for(lambda: len(seen) == 2 and bool(errors)) + await cs.close() + assert seen == ["i1", "i2"] + assert isinstance(errors[0], ValueError) + with pytest.raises(ValueError): + cs.on("callout.created", print) + + +async def test_iteration(server: Server) -> None: + seen: list[dict[str, Any]] = [] + async with client(server).copy_trading_stream() as cs: + async for ev in cs: + seen.append(ev) + if len(seen) == 2: + break + assert [(e["event"], e["id"]) for e in seen] == [("copy_trade.instruction", "i1"), ("copy_trade.instruction", "i2")] + assert seen[0]["data"]["csid_id"] == "f1" + + +async def test_iteration_without_context_manager(server: Server) -> None: + cs = client(server).copy_trading_stream() + first: dict[str, Any] = {} + async for ev in cs: + first = ev + break + assert first["id"] == "i1" + await cs.close() + + +async def test_invalid_api_key_is_fatal(server: Server) -> None: + server.mode = "deny" + cs = client(server).copy_trading_stream(reconnect_delay=0.01) + with pytest.raises(PermissionError) as e: + await cs.connect() + assert e.value.code == "invalid_api_key" + with pytest.raises(PermissionError): + await asyncio.wait_for(cs.run_forever(), 2) + assert server.connections == 1 + + +async def test_too_many_connections_reconnects(server: Server) -> None: + server.mode = "busy_once" + cs = client(server).copy_trading_stream(reconnect_delay=0.01) + errors: list[Any] = [] + cs.on("error", errors.append) + with pytest.raises(RateLimitError): + await cs.connect() + await wait_for(lambda: cs.connected) + assert cs.connected and server.connections == 2 + assert errors[0].code == "too_many_connections" + await cs.close() + + +async def test_reconnects_after_drop(server: Server) -> None: + server.mode = "drop_once" + cs = client(server).copy_trading_stream(reconnect_delay=0.01) + events: list[str] = [] + cs.on("reconnecting", lambda d: events.append("reconnecting")) + cs.on("ready", lambda d: events.append("ready")) + await cs.connect() + await wait_for(lambda: server.connections == 2 and events.count("ready") == 2) + await cs.close() + assert events == ["ready", "reconnecting", "ready"] + + +async def test_connection_error() -> None: + url = "ws://127.0.0.1:1/v1/copy-trading/stream" + cs = CabalSpyID("k", copy_trading_stream_url=url).copy_trading_stream(reconnect=False) + with pytest.raises(Exception) as e: + await cs.connect() + assert getattr(e.value, "code", None) == "ws_error" + + +def test_local_validation() -> None: + with pytest.raises(AuthenticationError): + CabalSpyID("").copy_trading_stream() + cs = CabalSpyID("k").copy_trading_stream() + assert cs.safe_url == "wss://api-id.cabalspy.xyz/v1/copy-trading/stream?api_key=***"