From 8f1694e0dcd40f9f828dd307970c1832215f03c3 Mon Sep 17 00:00:00 2001 From: Kabzelife <141412378+Kabzelife@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:59:29 +0100 Subject: [PATCH] 0.7.0: callouts and callout competitions Callouts are a CabalSpy ID extra, switched on per instance on request. - create_callout, remove_callout, callouts / iter_callouts, callout, callout_stats, callout_leaderboard / iter_callout_leaderboard, callout_settings, update_callout_settings (sync and async) - CalloutsStream for /v1/callouts/stream (client.callouts_stream) - callout competitions: kind, min_callouts, hit_x, chain "all" and the callout metrics on create_competition / update_competition - Callout* TypedDicts, MeResponse.features, CALLOUT_WEBHOOK_EVENTS - new error codes mapped onto the existing classes; callout_cooldown is never retried, 422 raises BadRequestError - README section, examples/callouts.py, CHANGELOG, version 0.7.0 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 58 ++++ README.md | 96 ++++++- cabalspy_id/__init__.py | 94 ++++++- cabalspy_id/_callouts_stream.py | 374 +++++++++++++++++++++++++ cabalspy_id/_client.py | 362 +++++++++++++++++++++++- cabalspy_id/_constants.py | 90 +++++- cabalspy_id/_errors.py | 33 ++- cabalspy_id/_types.py | 246 +++++++++++++++- cabalspy_id/api.py | 95 ++++++- examples/callouts.py | 121 ++++++++ pyproject.toml | 2 +- tests/test_callouts.py | 483 ++++++++++++++++++++++++++++++++ tests/test_callouts_stream.py | 230 +++++++++++++++ 13 files changed, 2246 insertions(+), 38 deletions(-) create mode 100644 cabalspy_id/_callouts_stream.py create mode 100644 examples/callouts.py create mode 100644 tests/test_callouts.py create mode 100644 tests/test_callouts_stream.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 32abf93..6657df3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,63 @@ 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.7.0] - 2026-10-31 + +Callouts: your users call tokens, and every call is stamped with the token's price and market +cap and tracked (every minute for the first 24 hours, then scored on candles; every 5 minutes +after that while the token is active, until 24 hours in a row below a $10k market cap). Callouts +are an extra that CabalSpy switches on per instance on request. Sync and async. + +### Added + +- Callouts (`/v1/callouts*`) on `CabalSpyID` and `AsyncCabalSpyID`: `create_callout` + (`external_id` positionally or `csid_id=`; `chain`, `mint`, `note`), `remove_callout`, + `callouts` / `iter_callouts` (filters `chain`, `mint`, `external_id` / `csid_id`, `since`, + `until`; datetimes are sent as ISO 8601 UTC), `callout`, `callout_stats` (`hit_x`), + `callout_leaderboard` / `iter_callout_leaderboard` (`period`, `chain`, `sort`, `min_callouts`, + `hit_x`), `callout_settings`, `update_callout_settings` (`who`, `require_holding`, + `cooldown_minutes`). +- `CalloutsStream` for `wss://api-id.cabalspy.xyz/v1/callouts/stream` via + `client.callouts_stream(chain=, mint=)`: events `callout.created`, `callout.update`, + `callout.milestone`, `callout.scored`, `callout.final`, `callout.removed` (handlers or + `async for`), heartbeats, reconnects with backoff; `feature_not_enabled` and `invalid_api_key` + are fatal, `too_many_connections` reconnects. New client option `callouts_stream_url`. +- Callout competitions: `create_competition(kind="callouts", ...)` with the metrics + `avg_peak_x`, `best_peak_x`, `sum_peak_x`, `hit_rate`, `callouts`, `min_callouts`, `hit_x` and + `chain="all"`; `update_competition` takes `min_callouts`, `hit_x` and `chain="all"`. The kind + decides which chains, metrics and minimums are accepted locally. +- Types: `Callout` (`at_call`, `now`, `peak`, `score_x`, `tracking` with `below_10k_since`, + `first_day`, ...), `CalloutStats`, `CalloutPeriodStats`, `CalloutLeaderboardEntry`, + `CalloutLeaderboardResponse`, `CalloutSettings`, `CalloutBestCall`, `CalloutUser`, the stream + events `CalloutUpdate`, `CalloutMilestone`, `CalloutRemovedEvent`, `CalloutsStreamReady`, and + `CalloutWebhookData`. `MeResponse.features` (the extras switched on, e.g. `["callouts"]`). + `Competition` has `kind`, `min_callouts` and `hit_x`; `CompetitionStanding` the callout stats + and `best_call`. +- Constants: `CALLOUT_WEBHOOK_EVENTS` (`callout.created`, `callout.milestone`, `callout.scored`, + `callout.final`, also in `WEBHOOK_EVENTS`), `CALLOUT_COMPETITION_METRICS`, `COMPETITION_KINDS`, + `CALLOUT_SORTS`, `CALLOUT_WHO`, `CALLOUT_MAX_NOTE`, `CALLOUT_DEFAULT_HIT_X`, + `CALLOUT_MILESTONES`, `CALLOUT_ACTIVE_MCAP_USD`, `MAX_CALLOUT_STREAMS_PER_KEY`, + `DEFAULT_CALLOUTS_STREAM_URL`, `FEATURE_CALLOUTS`, `CALLOUT_EVENTS`, `CALLOUTS_STREAM_EVENTS`; + Literal types `CompetitionKind`, `CompetitionChain`, `TradingCompetitionMetric`, + `CalloutCompetitionMetric`, `CalloutSort`, `CalloutWho`, `CalloutStatus`, `CalloutPhase`, + `CalloutFirstDayKind`. +- New error codes on the existing classes: `feature_not_enabled`, `kol_only`, `not_a_holder`, + `invalid_account`, `posting_paused`, `consent_required`, `sandbox_user` (`PermissionError`), + `callout_not_found` (`NotFoundError`), `already_called` (`ConflictError`), `callout_cooldown` + (`RateLimitError` with `retry_after`), `no_price` (`BadRequestError`, HTTP 422). +- README section "Callouts (on request)" and `examples/callouts.py`. + +### Changed + +- `callout_cooldown` (429) is never retried automatically, on any route: its `Retry-After` can be + hours. `RateLimitError.retry_after` falls back to the error body's `retry_after` when the header + is missing. +- HTTP 422 responses raise `BadRequestError` (with `status` 422) instead of the base + `CabalSpyIDError`. +- `CompetitionMetric` now covers the trading and the callout metrics; the trading ones alone are + `TradingCompetitionMetric` (`COMPETITION_METRICS` is unchanged). `Competition.min_trades` and + `min_volume_usd` are only present on trading competitions. + ## [0.6.0] - 2026-10-28 White-label: a platform keeps its own login, imports its users (by its own user id, @@ -174,6 +231,7 @@ First release. `NotFoundError`, `RateLimitError`, `ServerError`, `APIConnectionError`, `InvalidResponseError`, `OAuthError`, `TokenVerificationError`, `WebhookVerificationError`. +[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 [0.5.1]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.0...v0.5.1 diff --git a/README.md b/README.md index ad12af8..27c62d3 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 and trading competitions | +| `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) | | `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 | @@ -38,6 +38,7 @@ Everything for developers — instance (client_id), client secrets, redirect URI - **Trader profiles** — X profile, verified wallets, holdings, PnL calendar - **KOL badges** — reviewed badges for influential traders, shown wherever they sign in - **White-label** — keep your own login, import your users and their wallets, run trading competitions +- **Callouts** (on request) — your users call tokens; every call is stamped and tracked, with a score, a callers leaderboard and callout competitions ## Packages @@ -55,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`, `CabalSpyIDAuth`, `verify_webhook`, errors and Data API types | +| `cabalspy_id.api` | `CabalSpyID`, `AsyncCabalSpyID`, `CabalSpyIDStream`, `CalloutsStream`, `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`. @@ -230,13 +231,13 @@ except RateLimitError as err: | Class | Status | Codes | |---|---|---| -| `BadRequestError` | 400 | `missing_parameter`, `invalid_parameter`, `instance_required`, `wallet_required`, `invalid_address`, `invalid_return_url` | +| `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` | +| `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` | | `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` | -| `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` | -| `RateLimitError` | 429 | `rate_limit_exceeded`, `rate_limited`, `too_many_open_verifications` | +| `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` | +| `RateLimitError` | 429 | `rate_limit_exceeded`, `rate_limited`, `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`, …) | @@ -244,7 +245,7 @@ except RateLimitError as err: | `WebhookVerificationError` | – | webhook signature or timestamp invalid | | `PlatformImportError` | – | `bulk_import_platform_users` stopped; carries `result` and `remaining` | -`429`, `5xx` and network errors are retried with exponential backoff (default 2 retries); `Retry-After` wins. Writes (POST) are retried only after the API-wide rate limit (`rate_limit_exceeded`), since they did not run. The rate limit of the last call is in `csid.last_rate_limit` (`X-RateLimit-Limit/Remaining/Reset`). +`429`, `5xx` and network errors are retried with exponential backoff (default 2 retries); `Retry-After` wins. Writes (POST) are retried only after the API-wide rate limit (`rate_limit_exceeded`), since they did not run. `callout_cooldown` is never retried: the wait (`retry_after`) can be hours. The rate limit of the last call is in `csid.last_rate_limit` (`X-RateLimit-Limit/Remaining/Reset`). ## White-label (platform users) @@ -329,6 +330,82 @@ The competition routes page by `offset`; the `iter_*` helpers walk them until `p Webhooks: `platform_user.created`, `platform_user.claimed`, `platform_user.x_connected`, `wallet.added`, `verification.expired`, and per instance `competition.started`, `competition.updated`, `competition.standings`, `competition.ended` (`PLATFORM_WEBHOOK_EVENTS`, `COMPETITION_WEBHOOK_EVENTS`). +## Callouts (on request) + +Callouts are an extra for CabalSpy ID instances: **they are switched on per instance on request** (contact CabalSpy). Until then every callout call raises `PermissionError` with the code `feature_not_enabled`; `csid.me()["features"]` lists `"callouts"` once they are on. + +A user calls a token: its price and market cap are stamped at that moment and tracked. + +- **First 24 hours:** read every minute (current and peak multiple, milestones 2x, 3x, 5x, 10x, ...), then the day is scored on price candles (`first_day`, webhook `callout.scored`). +- **After that:** read every 5 minutes while the token is active, plus each day's candles. Tracking stops after 24 hours in a row below a $10k market cap (`tracking.below_10k_since`, then `callout.final`). + +A callout's score is `score_x`, its peak multiple since the call. On top: stats per user and period, a callers leaderboard, a live stream, webhooks and callout competitions. + +```python +from cabalspy_id import CabalSpyID, ConflictError, RateLimitError + +csid = CabalSpyID() + +try: + c = csid.create_callout("user_42", chain="solana", mint=MINT, note="Undervalued, team ships") + print(c["at_call"]["market_cap_usd"], c["score_x"]) +except ConflictError: # already_called: one call per token and 24 hours + pass +except RateLimitError as err: # callout_cooldown: the instance's cooldown, never retried + print("next callout in", err.retry_after, "seconds") + +for c in csid.iter_callouts(chain="solana", mint=MINT): # chart markers, newest first + print(c["called_at"], c["author"]["name"], c["peak"]["x"], c["tracking"]["phase"]) + +stats = csid.callout_stats("user_42", hit_x=2) # per period: 6h, 1d, 7d, 30d +print(stats["periods"]["7d"]["avg_peak_x"], stats["periods"]["7d"]["hit_rate"]) + +board = csid.callout_leaderboard(period="7d", sort="avg_peak_x", min_callouts=3) +for e in board["leaderboard"]: + print(e["rank"], e["author"]["name"], e["avg_peak_x"], e["best_call"]["symbol"]) + +csid.update_callout_settings(who="all", require_holding=True, cooldown_minutes=360) +``` + +| Method | Endpoint | +|---|---| +| `create_callout(external_id \| csid_id=, chain=, mint=, note=)` | `POST /v1/callouts` | +| `remove_callout(id, reason=)` | `POST /v1/callouts/remove` (moderation) | +| `callouts(chain=, mint=, external_id=, csid_id=, since=, until=, limit=, cursor=)` / `iter_callouts()` | `GET /v1/callouts` | +| `callout(id)` | `GET /v1/callouts/item` | +| `callout_stats(external_id \| csid_id=, hit_x=)` | `GET /v1/callouts/stats` | +| `callout_leaderboard(period=, chain=, sort=, min_callouts=, hit_x=, limit=, cursor=)` / `iter_callout_leaderboard()` | `GET /v1/callouts/leaderboard` | +| `callout_settings()` / `update_callout_settings(who=, require_holding=, cooldown_minutes=)` | `GET` / `POST /v1/callouts/settings` | +| `callouts_stream(chain=, mint=)` | `WS /v1/callouts/stream` | + +**A callout** (`Callout`): `at_call` (price and market cap at the call), `now` and `peak` (price, market cap, multiple `x`, time), `score_x`, `status` (`tracking` or `final`), `tracking` (`active`, `phase` = `first_day` / `extended` / `stopped`, `next_check_at`, `below_10k_since`, `daily_checks`, `stopped_at`, `stop_reason`) and, once the first day is scored, `first_day` (`kind` = `candles` or `live`, `peak_x`, `close_x`, `minutes_to_peak`, `flags`). + +**Stats and leaderboard.** Per period (the callouts made in the last 6h / 1d / 7d / 30d): `callouts`, `avg_peak_x`, `median_peak_x`, `best_peak_x`, `sum_peak_x`, `hits` and `hit_rate` (percent of callouts whose peak reached `hit_x`, default 2), plus `avg_now_x` and `tracking` in the stats. The leaderboard sorts by `avg_peak_x` (default), `best_peak_x`, `sum_peak_x`, `hit_rate`, `callouts` or `median_peak_x`; each entry has `best_call`. + +**Settings.** `who` (`all` or `kol_only`), `require_holding` (only holders may call a token, default on), `cooldown_minutes` (0-10080 between two callouts of one user, default 360). Errors on `create_callout`: `kol_only`, `not_a_holder`, `posting_paused` (`PermissionError`), `already_called` (`ConflictError`), `callout_cooldown` (`RateLimitError` with `retry_after`), `no_price` (`BadRequestError`, 422). + +**Live stream** (async, needs `cabalspy-id[stream]`): + +```python +async with AsyncCabalSpyID() as csid: + async with csid.callouts_stream(chain="solana") as cs: # mint= one token (needs chain) + async for ev in cs: + if ev["event"] == "callout.milestone": + print(ev["data"]["token"]["symbol"], ev["data"]["milestone_x"], "x") +``` + +Events: `callout.created`, `callout.update` (a new price: `price_usd`, `market_cap_usd`, `x`, `peak_x`), `callout.milestone` (the callout plus `milestone_x`), `callout.scored`, `callout.final`, `callout.removed`, plus `ready`, `heartbeat`, `pong`, `open`, `close`, `reconnecting`, `error`. `feature_not_enabled` and `invalid_api_key` are fatal; `too_many_connections` (at most 5 per key) reconnects with backoff. + +**Callout competitions.** `create_competition(kind="callouts", ...)` ranks your users on the callouts they make during the competition: metrics `avg_peak_x`, `best_peak_x`, `sum_peak_x`, `hit_rate`, `callouts`; `min_callouts` to be ranked, `hit_x` the multiple that counts as a hit, and `chain="all"` to count every chain. Standings carry the callout stats and `best_call`. The kind cannot change later; `min_trades` / `min_volume_usd` belong to trading competitions. + +```python +comp = csid.create_competition(name="Caller of the week", kind="callouts", chain="all", + metric="avg_peak_x", duration_hours=168, min_callouts=3, hit_x=2, + enrollment="all_users") +``` + +A full tour is in [`examples/callouts.py`](examples/callouts.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. @@ -477,7 +554,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`). +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`). ```python from cabalspy_id import verify_webhook @@ -499,6 +576,7 @@ CabalSpyID( instance=None, # client_id, when the account has several instances 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", timeout=30.0, max_retries=2, headers={}, diff --git a/cabalspy_id/__init__.py b/cabalspy_id/__init__.py index 8472578..5e3d99b 100644 --- a/cabalspy_id/__init__.py +++ b/cabalspy_id/__init__.py @@ -1,8 +1,8 @@ """CabalSpy ID — the verified social layer for crypto trading. Login with CabalSpy ID (OpenID Connect), the Data API for verified wallets, KOL -badges, trading stats and token theses, white-label platform users and trading -competitions, the live stream, the public thesis API and webhook verification. +badges, trading stats and token theses, white-label platform users, trading +competitions, callouts, the live stream, the public thesis API and webhook verification. from cabalspy_id import CabalSpyID, CabalSpyIDAuth, verify_webhook @@ -16,22 +16,34 @@ from ._client import AsyncCabalSpyID, CabalSpyID, Envelope from ._constants import ( + CALLOUT_ACTIVE_MCAP_USD, + CALLOUT_COMPETITION_METRICS, + CALLOUT_DEFAULT_HIT_X, + CALLOUT_MAX_NOTE, + CALLOUT_MILESTONES, + CALLOUT_SORTS, + CALLOUT_WEBHOOK_EVENTS, + CALLOUT_WHO, CHAINS, CLIENT_ID_HEADER, COMPETITION_ENROLLMENTS, + COMPETITION_KINDS, COMPETITION_METRICS, COMPETITION_STATUSES, COMPETITION_WEBHOOK_EVENTS, CURRENCY_BY_CHAIN, DATA_SCOPES, DEFAULT_BASE_URL, + DEFAULT_CALLOUTS_STREAM_URL, DEFAULT_ISSUER, DEFAULT_STREAM_URL, DEFAULT_THESES_STREAM_URL, DEFAULT_THESIS_URL, DEFAULT_THESIS_WS_URL, + FEATURE_CALLOUTS, INBOUND_FORMATS, LEADERBOARD_SORTS, + MAX_CALLOUT_STREAMS_PER_KEY, MAX_OPEN_COMPETITIONS, MAX_REQUEST_BODY_BYTES, MAX_THESES_STREAM_TOKENS, @@ -48,8 +60,16 @@ THESIS_SCOPES, WALLET_TRUST, WEBHOOK_EVENTS, + CalloutCompetitionMetric, + CalloutFirstDayKind, + CalloutPhase, + CalloutSort, + CalloutStatus, + CalloutWho, Chain, + CompetitionChain, CompetitionEnrollment, + CompetitionKind, CompetitionMetric, CompetitionStatus, Currency, @@ -67,6 +87,7 @@ ThesisScope, ThesisSort, ThesisStance, + TradingCompetitionMetric, VerificationStatus, WalletTrust, ) @@ -102,6 +123,26 @@ ActiveHoldings, ActiveTokens, CabalSpyIDClaims, + Callout, + CalloutBestCall, + CalloutFirstDay, + CalloutLeaderboardEntry, + CalloutLeaderboardResponse, + CalloutMilestone, + CalloutPeriodStats, + CalloutPrice, + CalloutQuote, + CalloutRemoved, + CalloutRemovedEvent, + CalloutSettings, + CalloutsStreamReady, + CalloutStats, + CalloutSummary, + CalloutToken, + CalloutTracking, + CalloutUpdate, + CalloutUser, + CalloutWebhookData, Competition, CompetitionChange, CompetitionDetail, @@ -210,6 +251,10 @@ def __getattr__(name: str) -> object: from . import _theses_stream return getattr(_theses_stream, name) + if name in ("CalloutsStream", "CALLOUTS_STREAM_EVENTS", "CALLOUT_EVENTS"): + from . import _callouts_stream + + return getattr(_callouts_stream, name) raise AttributeError(f"module 'cabalspy_id' has no attribute {name!r}") @@ -220,6 +265,7 @@ def __getattr__(name: str) -> object: "AsyncCabalSpyID", "CabalSpyIDStream", "ThesesStream", + "CalloutsStream", "Envelope", "CabalSpyIDAuth", "AsyncCabalSpyIDAuth", @@ -409,4 +455,48 @@ def __getattr__(name: str) -> object: "CompetitionStanding", "CompetitionStandings", "CompetitionMembership", + # callouts + "CALLOUTS_STREAM_EVENTS", + "CALLOUT_EVENTS", + "CALLOUT_WEBHOOK_EVENTS", + "CALLOUT_COMPETITION_METRICS", + "COMPETITION_KINDS", + "CALLOUT_SORTS", + "CALLOUT_WHO", + "CALLOUT_MAX_NOTE", + "CALLOUT_DEFAULT_HIT_X", + "CALLOUT_MILESTONES", + "CALLOUT_ACTIVE_MCAP_USD", + "MAX_CALLOUT_STREAMS_PER_KEY", + "DEFAULT_CALLOUTS_STREAM_URL", + "FEATURE_CALLOUTS", + "TradingCompetitionMetric", + "CalloutCompetitionMetric", + "CompetitionKind", + "CompetitionChain", + "CalloutSort", + "CalloutWho", + "CalloutStatus", + "CalloutPhase", + "CalloutFirstDayKind", + "Callout", + "CalloutUser", + "CalloutToken", + "CalloutPrice", + "CalloutQuote", + "CalloutTracking", + "CalloutFirstDay", + "CalloutRemoved", + "CalloutSummary", + "CalloutPeriodStats", + "CalloutStats", + "CalloutBestCall", + "CalloutLeaderboardEntry", + "CalloutLeaderboardResponse", + "CalloutSettings", + "CalloutMilestone", + "CalloutUpdate", + "CalloutRemovedEvent", + "CalloutsStreamReady", + "CalloutWebhookData", ] diff --git a/cabalspy_id/_callouts_stream.py b/cabalspy_id/_callouts_stream.py new file mode 100644 index 0000000..109e545 --- /dev/null +++ b/cabalspy_id/_callouts_stream.py @@ -0,0 +1,374 @@ +"""Callouts stream: wss://api-id.cabalspy.xyz/v1/callouts/stream (callouts extra). + +Every callout event of your instance, live: new callouts, price updates, +milestones (2x, 3x, 5x, ...), the first day scored, tracking stopped, removals. +Optional ``chain`` and ``mint`` narrow it to one chain or one token. Callouts are +switched on per instance on request; without them the server refuses the +connection with ``feature_not_enabled``. + + async with AsyncCabalSpyID() as csid: + cs = csid.callouts_stream(chain="solana") + + @cs.on("callout.milestone") + def _(c): + print(c["token"]["symbol"], c["milestone_x"], "x") + + await cs.connect() # returns on "ready" + await cs.run_forever() + + # or iterate ({"event": ..., "data": ...}): + async with csid.callouts_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 ._constants import CHAINS +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 callout events: callout.created (a Callout), callout.update (a price update), +#: callout.milestone (a Callout plus milestone_x), callout.scored (first day scored on +#: candles, a Callout with first_day), callout.final (tracking stopped), callout.removed. +CALLOUT_EVENTS = ( + "callout.created", + "callout.update", + "callout.milestone", + "callout.scored", + "callout.final", + "callout.removed", +) +#: Events: ready, the callout events, heartbeat, pong, open, close, reconnecting, error. +CALLOUTS_STREAM_EVENTS = ("ready", *CALLOUT_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 CalloutsStream: + """Async client for the callouts stream. Obtain one via ``client.callouts_stream()``.""" + + def __init__( + self, + url: str, + api_key: str, + *, + chain: str | None = None, + mint: str | None = None, + 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 callouts stream needs the websockets package: pip install "cabalspy-id[stream]"') + if chain is not None and chain not in CHAINS: + raise BadRequestError( + f"Invalid value for 'chain': {chain!r}", + code="invalid_parameter", + parameter="chain", + allowed=list(CHAINS), + ) + if mint and not chain: + raise BadRequestError("mint needs chain", code="missing_parameter", parameter="chain") + extra = {k: v for k, v in {"chain": chain, "mint": mint, "instance": instance}.items() if v} + self.chain = chain + self.mint = mint + 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.""" + if event not in CALLOUTS_STREAM_EVENTS: + raise ValueError(f"unknown event {event!r}; one of {', '.join(CALLOUTS_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``, ``chain``, ``mint``).""" + 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 callouts 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"Callouts 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 CALLOUT_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, feature_not_enabled, ...): 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) -> CalloutsStream: + # 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 CALLOUT_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 _keeper(backlog: list[Any], name: str) -> Handler: + return lambda data: backlog.append({"event": name, "data": 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 callout events as ``{"event": ..., "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({"event": name, "data": data}) + + listeners = [(name, listener(name)) for name in CALLOUT_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/_client.py b/cabalspy_id/_client.py index d2717a9..43c927b 100644 --- a/cabalspy_id/_client.py +++ b/cabalspy_id/_client.py @@ -17,18 +17,24 @@ import random import time from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mapping, Sequence -from datetime import datetime +from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, Literal, TypeVar import httpx from ._constants import ( + CALLOUT_COMPETITION_METRICS, + CALLOUT_MAX_NOTE, + CALLOUT_SORTS, + CALLOUT_WHO, CHAINS, COMPETITION_ENROLLMENTS, + COMPETITION_KINDS, COMPETITION_METRICS, COMPETITION_STATUSES, DATA_SCOPES, DEFAULT_BASE_URL, + DEFAULT_CALLOUTS_STREAM_URL, DEFAULT_STREAM_URL, DEFAULT_THESES_STREAM_URL, LEADERBOARD_SORTS, @@ -41,8 +47,12 @@ THESIS_SCOPES, USER_AGENT, WALLET_TRUST, + CalloutSort, + CalloutWho, Chain, + CompetitionChain, CompetitionEnrollment, + CompetitionKind, CompetitionMetric, CompetitionStatus, DataScope, @@ -73,6 +83,7 @@ from ._types import PlatformBulkImportResult, PlatformUserInput, PlatformWalletInput if TYPE_CHECKING: + from ._callouts_stream import CalloutsStream from ._stream import CabalSpyIDStream from ._theses_stream import ThesesStream @@ -254,17 +265,104 @@ def _platform_leaderboard_query( return {"blockchain": blockchain, "period": period, "sort": sort, "trust": trust, "limit": limit, "cursor": cursor} -def _competition_fields(**fields: Any) -> dict[str, Any]: +_TRADING_ONLY = ("min_trades", "min_volume_usd") +_CALLOUTS_ONLY = ("min_callouts", "hit_x") + + +def _competition_fields(*, creating: bool, **fields: Any) -> dict[str, Any]: + """Validated competition fields. On create the kind is known (default trading) and + decides the chains, metrics and minimums; on update the server knows the kind.""" out = _given(**fields) - _one_of(out.get("chain"), CHAINS, "chain") - _one_of(out.get("metric"), COMPETITION_METRICS, "metric") + _one_of(out.get("kind"), COMPETITION_KINDS, "kind") + kind = (out.get("kind") or "trading") if creating else None + chains: tuple[str, ...] = (*CHAINS, "all") if kind in ("callouts", None) else CHAINS + if kind == "callouts": + metrics: tuple[str, ...] = CALLOUT_COMPETITION_METRICS + elif kind == "trading": + metrics = COMPETITION_METRICS + else: + metrics = (*COMPETITION_METRICS, *CALLOUT_COMPETITION_METRICS) + _one_of(out.get("chain"), chains, "chain") + _one_of(out.get("metric"), metrics, "metric") _one_of(out.get("wallet_trust"), WALLET_TRUST, "wallet_trust") _one_of(out.get("enrollment"), COMPETITION_ENROLLMENTS, "enrollment") + wrong = _CALLOUTS_ONLY if kind == "trading" else _TRADING_ONLY if kind == "callouts" else () + for name in wrong: + if name in out: + raise BadRequestError( + f"{name} does not apply to {kind} competitions.", code="invalid_parameter", parameter=name + ) + if "hit_x" in out: + _hit_x(out["hit_x"]) if isinstance(out.get("starts_at"), datetime): out["starts_at"] = out["starts_at"].isoformat() return out +def _hit_x(value: Any) -> None: + """hit_x: a number above 1 and at most 1000 (None = the server's default, 2).""" + if value is None: + return + if isinstance(value, bool) or not isinstance(value, (int, float)) or not 1 < value <= 1000: + raise BadRequestError( + "hit_x must be a number above 1 and at most 1000.", code="invalid_parameter", parameter="hit_x" + ) + + +def _time_param(value: str | datetime | None) -> str | None: + """A datetime as ISO 8601 UTC (naive = UTC, like the server); strings pass through.""" + if not isinstance(value, datetime): + return value + aware = value if value.tzinfo else value.replace(tzinfo=timezone.utc) + return aware.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _callouts_query( + chain: Any, mint: Any, external_id: Any, csid_id: Any, since: Any, until: Any, limit: Any, cursor: Any +) -> dict[str, Any]: + _one_of(chain, CHAINS, "chain") + if mint and not chain: + raise BadRequestError("Pass chain together with mint.", code="missing_parameter", parameter="chain") + 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" + ) + return { + "chain": chain, + "mint": mint, + "external_id": external_id, + "csid_id": csid_id, + "since": _time_param(since), + "until": _time_param(until), + "limit": limit, + "cursor": cursor, + } + + +def _callout_leaderboard_query( + period: Any, chain: Any, sort: Any, min_callouts: Any, hit_x: Any, limit: Any, cursor: Any +) -> dict[str, Any]: + _one_of(period, PERIODS, "period") + _one_of(chain, CHAINS, "chain") + _one_of(sort, CALLOUT_SORTS, "sort") + if min_callouts is not None and ( + isinstance(min_callouts, bool) or not isinstance(min_callouts, int) or not 1 <= min_callouts <= 1000 + ): + raise BadRequestError( + "min_callouts must be a whole number from 1 to 1000.", code="invalid_parameter", parameter="min_callouts" + ) + _hit_x(hit_x) + return { + "period": period, + "chain": chain, + "sort": sort, + "min_callouts": min_callouts, + "hit_x": hit_x, + "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") @@ -1026,25 +1124,34 @@ def create_competition( self, *, name: str, - chain: Chain, + chain: CompetitionChain, metric: CompetitionMetric, duration_hours: float, + kind: CompetitionKind | _NotGiven = NOT_GIVEN, starts_at: str | datetime | _NotGiven | None = NOT_GIVEN, min_participants: int | _NotGiven = NOT_GIVEN, max_participants: int | _NotGiven | None = NOT_GIVEN, min_trades: int | _NotGiven = NOT_GIVEN, min_volume_usd: float | _NotGiven = NOT_GIVEN, + min_callouts: int | _NotGiven = NOT_GIVEN, + hit_x: float | _NotGiven = NOT_GIVEN, wallet_trust: WalletTrust | _NotGiven = NOT_GIVEN, enrollment: CompetitionEnrollment | _NotGiven = NOT_GIVEN, late_join: bool | _NotGiven = NOT_GIVEN, prizes: Any = NOT_GIVEN, description: str | _NotGiven | None = NOT_GIVEN, ) -> Any: - """POST /v1/competitions — a trading competition between your platform users. + """POST /v1/competitions — a competition between your platform users. It starts at ``starts_at`` (or at once) once ``min_participants`` joined, then runs ``duration_hours`` (1-8760). ``enrollment="all_users"`` enters every platform user. - Traders below ``min_trades`` / ``min_volume_usd`` are listed but not ranked. + + ``kind="trading"`` (default): ranked on trades; traders below ``min_trades`` / + ``min_volume_usd`` are listed but not ranked. ``kind="callouts"`` (needs the + callouts extra, else ``feature_not_enabled``): ranked on the callouts made during + the competition by ``avg_peak_x``, ``best_peak_x``, ``sum_peak_x``, ``hit_rate`` or + ``callouts``; ``min_callouts`` to be ranked, ``hit_x`` the multiple that counts as + a hit (default 2), ``chain="all"`` counts every chain. The kind cannot change later. Returns :class:`~cabalspy_id.CompetitionDetail`. """ _required(name, "name") @@ -1052,7 +1159,9 @@ def create_competition( _required(metric, "metric") _required(duration_hours, "duration_hours") body = _competition_fields( + creating=True, name=name, + kind=kind, chain=chain, metric=metric, duration_hours=duration_hours, @@ -1061,6 +1170,8 @@ def create_competition( max_participants=max_participants, min_trades=min_trades, min_volume_usd=min_volume_usd, + min_callouts=min_callouts, + hit_x=hit_x, wallet_trust=wallet_trust, enrollment=enrollment, late_join=late_join, @@ -1093,7 +1204,7 @@ def update_competition( *, note: str | None = None, name: str | _NotGiven = NOT_GIVEN, - chain: Chain | _NotGiven = NOT_GIVEN, + chain: CompetitionChain | _NotGiven = NOT_GIVEN, metric: CompetitionMetric | _NotGiven = NOT_GIVEN, duration_hours: float | _NotGiven = NOT_GIVEN, starts_at: str | datetime | _NotGiven | None = NOT_GIVEN, @@ -1101,6 +1212,8 @@ def update_competition( max_participants: int | _NotGiven | None = NOT_GIVEN, min_trades: int | _NotGiven = NOT_GIVEN, min_volume_usd: float | _NotGiven = NOT_GIVEN, + min_callouts: int | _NotGiven = NOT_GIVEN, + hit_x: float | _NotGiven = NOT_GIVEN, wallet_trust: WalletTrust | _NotGiven = NOT_GIVEN, enrollment: CompetitionEnrollment | _NotGiven = NOT_GIVEN, late_join: bool | _NotGiven = NOT_GIVEN, @@ -1112,10 +1225,13 @@ def update_competition( Every change is recorded (``changes``, ``rules_version``) and sent as the webhook ``competition.updated``; ``note`` (max 500 characters) explains it. Pass ``None`` to clear ``starts_at``, ``max_participants``, ``prizes`` or ``description``. + ``min_callouts`` / ``hit_x`` apply to callout competitions, ``min_trades`` / + ``min_volume_usd`` to trading ones; the kind itself cannot change. Returns :class:`~cabalspy_id.CompetitionDetail`. """ _required(id, "id") fields = _competition_fields( + creating=False, name=name, chain=chain, metric=metric, @@ -1125,6 +1241,8 @@ def update_competition( max_participants=max_participants, min_trades=min_trades, min_volume_usd=min_volume_usd, + min_callouts=min_callouts, + hit_x=hit_x, wallet_trust=wallet_trust, enrollment=enrollment, late_join=late_join, @@ -1176,6 +1294,150 @@ def competition_standings(self, id: str, *, limit: int | None = None, offset: in _required(id, "id") return self._get("/competitions/standings", {"id": id, "limit": limit, "offset": offset}) + # ── callouts (an extra, switched on per instance on request) ───────── + # A user calls a token; its price and market cap are stamped and tracked: every + # minute for the first 24 hours (then the day is scored on candles), after that + # every 5 minutes while the token is active. Tracking stops after 24 hours in a + # row below a $10k market cap. Without the extra every call raises + # PermissionError (feature_not_enabled); ``me()["features"]`` shows it. + + def create_callout( + self, + external_id: str | None = None, + *, + chain: Chain, + mint: str, + note: str | None = None, + csid_id: str | None = None, + ) -> Any: + """POST /v1/callouts — one of your users calls a token (``note`` up to 280 characters). + + The instance's settings apply: ``kol_only`` (PermissionError), holders only + (``not_a_holder``), one call per token and 24 hours (ConflictError ``already_called``) + and the cooldown between two callouts (RateLimitError ``callout_cooldown`` with + ``retry_after``; never retried automatically, the wait can be hours). A token without + a market price raises BadRequestError ``no_price`` (422). + Returns :class:`~cabalspy_id.Callout`. + """ + who = _who(external_id, csid_id) + _required(chain, "chain") + _one_of(chain, CHAINS, "chain") + _required(mint, "mint") + if note is not None and len(note) > CALLOUT_MAX_NOTE: + raise BadRequestError( + f"note must be at most {CALLOUT_MAX_NOTE} characters.", code="invalid_parameter", parameter="note" + ) + body: dict[str, Any] = {**who, "chain": chain, "mint": mint} + if note: + body["note"] = note + return self._post("/callouts", body) + + def remove_callout(self, id: str, *, reason: str | None = None) -> Any: + """POST /v1/callouts/remove — takes a callout down (moderation, ``reason`` up to 200 + characters); it leaves every list and statistic. Returns :class:`~cabalspy_id.CalloutRemoved`. + """ + _required(id, "id") + body: dict[str, Any] = {"id": id} + if reason: + body["reason"] = reason + return self._post("/callouts/remove", body) + + def callouts( + self, + *, + chain: Chain | None = None, + mint: str | None = None, + external_id: str | None = None, + csid_id: str | None = None, + since: str | datetime | None = None, + until: str | datetime | None = None, + limit: int | None = None, + cursor: str | None = None, + ) -> Any: + """GET /v1/callouts — your instance's callouts, newest first (``limit`` 1-200, default 50), + e.g. as chart markers. ``mint`` needs ``chain``; ``external_id`` / ``csid_id`` one user's; + ``since`` / ``until`` bound ``called_at`` (datetimes or ISO 8601). + + Returns a list of :class:`~cabalspy_id.Callout`; see ``iter_callouts``. + """ + return self._get("/callouts", _callouts_query(chain, mint, external_id, csid_id, since, until, limit, cursor)) + + def callout(self, id: str) -> Any: + """GET /v1/callouts/item — one callout. Returns :class:`~cabalspy_id.Callout`.""" + _required(id, "id") + return self._get("/callouts/item", {"id": id}) + + def callout_stats( + self, external_id: str | None = None, *, csid_id: str | None = None, hit_x: float | None = None + ) -> Any: + """GET /v1/callouts/stats — one user's callouts per period (6h, 1d, 7d, 30d = callouts + made in that period): count, average / median / best peak multiple, hit rate (percent + reaching ``hit_x``, default 2) and the average multiple now. + + Returns :class:`~cabalspy_id.CalloutStats`. + """ + who = _who(external_id, csid_id) + _hit_x(hit_x) + return self._get("/callouts/stats", {**who, "hit_x": hit_x}) + + def callout_leaderboard( + self, + *, + period: Period | None = None, + chain: Chain | None = None, + sort: CalloutSort | None = None, + min_callouts: int | None = None, + hit_x: float | None = None, + limit: int | None = None, + cursor: str | None = None, + ) -> Any: + """GET /v1/callouts/leaderboard — your callers ranked (default 7d by ``avg_peak_x``; + ``limit`` 1-500, default 100). ``min_callouts`` 1-1000 to be listed. + + Returns :class:`~cabalspy_id.CalloutLeaderboardResponse`; see ``iter_callout_leaderboard``. + """ + return self._get( + "/callouts/leaderboard", + _callout_leaderboard_query(period, chain, sort, min_callouts, hit_x, limit, cursor), + ) + + def callout_settings(self) -> Any: + """GET /v1/callouts/settings. Returns :class:`~cabalspy_id.CalloutSettings`.""" + return self._get("/callouts/settings") + + def update_callout_settings( + self, + *, + who: CalloutWho | None = None, + require_holding: bool | None = None, + cooldown_minutes: int | None = None, + ) -> Any: + """POST /v1/callouts/settings — changes the settings you pass (None = unchanged). + + ``who``: ``all`` or ``kol_only``; ``require_holding``: holders only; + ``cooldown_minutes``: 0-10080 between two callouts of one user. + Returns :class:`~cabalspy_id.CalloutSettings`. + """ + _one_of(who, CALLOUT_WHO, "who") + if cooldown_minutes is not None and ( + isinstance(cooldown_minutes, bool) + or not isinstance(cooldown_minutes, int) + or not 0 <= cooldown_minutes <= 10080 + ): + raise BadRequestError( + "cooldown_minutes must be a whole number from 0 to 10080 (7 days).", + code="invalid_parameter", + parameter="cooldown_minutes", + ) + changes = { + k: v + for k, v in {"who": who, "require_holding": require_holding, "cooldown_minutes": cooldown_minutes}.items() + if v is not None + } + if not changes: + raise BadRequestError("Pass at least one setting.", code="missing_parameter", parameter="settings") + return self._post("/callouts/settings", changes) + # ═══════════════════════════════════════════════════════════════════════════ # CLIENTS @@ -1191,6 +1453,7 @@ def __init__( base_url: str | None = None, stream_url: str | None = None, theses_stream_url: str | None = None, + callouts_stream_url: str | None = None, timeout: float = 30.0, max_retries: int = 2, headers: Mapping[str, str] | None = None, @@ -1203,6 +1466,7 @@ def __init__( self.base_url = (base_url or _env("CABALSPY_ID_BASE_URL") or DEFAULT_BASE_URL).rstrip("/") 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.timeout = timeout self.max_retries = max_retries self._extra_headers = dict(headers or {}) @@ -1326,6 +1590,20 @@ def theses_stream(self, *, scope: ThesisScope | None = None, **kwargs: Any) -> T return ThesesStream(self.theses_stream_url, self._api_key, scope=scope, instance=self.instance, **kwargs) + def callouts_stream(self, *, chain: Chain | None = None, mint: str | None = None, **kwargs: Any) -> CalloutsStream: + """Every callout event of your instance, live (callouts extra). Async only. + + ``chain`` / ``mint`` narrow it to one chain or token (``mint`` needs ``chain``). + Needs the ``stream`` extra: ``pip install "cabalspy-id[stream]"``. + """ + if not self._api_key: + raise AuthenticationError("The callouts stream needs an API key.", status=401, code="missing_api_key") + from ._callouts_stream import CalloutsStream + + return CalloutsStream( + self.callouts_stream_url, self._api_key, chain=chain, mint=mint, instance=self.instance, **kwargs + ) + class CabalSpyID(_BaseClient): """Synchronous Data API client. @@ -1571,6 +1849,39 @@ def iter_competition_standings(self, id: str, *, limit: int | None = None) -> It _required(id, "id") yield from self.offset_items("/competitions/standings", {"id": id, "limit": limit}, key="standings") + # ── callouts ───────────────────────────────────────────────────────── + + def iter_callouts( + self, + *, + chain: Chain | None = None, + mint: str | None = None, + external_id: str | None = None, + csid_id: str | None = None, + since: str | datetime | None = None, + until: str | datetime | None = None, + limit: int | None = None, + ) -> Iterator[dict[str, Any]]: + """Every callout matching the filters, newest first, following ``next_cursor``.""" + query = _callouts_query(chain, mint, external_id, csid_id, since, until, limit, None) + for page in self.pages("/callouts", query): + yield from page.data + + def iter_callout_leaderboard( + self, + *, + period: Period | None = None, + chain: Chain | None = None, + sort: CalloutSort | None = None, + min_callouts: int | None = None, + hit_x: float | None = None, + limit: int | None = None, + ) -> Iterator[dict[str, Any]]: + """Every entry of the callers leaderboard, following ``next_cursor``.""" + query = _callout_leaderboard_query(period, chain, sort, min_callouts, hit_x, limit, None) + for page in self.pages("/callouts/leaderboard", query): + yield from page.data.get("leaderboard", []) + class AsyncCabalSpyID(_BaseClient): """Asynchronous Data API client. @@ -1811,6 +2122,41 @@ async def iter_competition_standings(self, id: str, *, limit: int | None = None) async for item in self.offset_items("/competitions/standings", {"id": id, "limit": limit}, key="standings"): yield item + # ── callouts ───────────────────────────────────────────────────────── + + async def iter_callouts( + self, + *, + chain: Chain | None = None, + mint: str | None = None, + external_id: str | None = None, + csid_id: str | None = None, + since: str | datetime | None = None, + until: str | datetime | None = None, + limit: int | None = None, + ) -> AsyncIterator[dict[str, Any]]: + """Every callout matching the filters, newest first, following ``next_cursor``.""" + query = _callouts_query(chain, mint, external_id, csid_id, since, until, limit, None) + async for page in self.pages("/callouts", query): + for item in page.data: + yield item + + async def iter_callout_leaderboard( + self, + *, + period: Period | None = None, + chain: Chain | None = None, + sort: CalloutSort | None = None, + min_callouts: int | None = None, + hit_x: float | None = None, + limit: int | None = None, + ) -> AsyncIterator[dict[str, Any]]: + """Every entry of the callers leaderboard, following ``next_cursor``.""" + query = _callout_leaderboard_query(period, chain, sort, min_callouts, hit_x, limit, None) + async for page in self.pages("/callouts/leaderboard", query): + for entry in page.data.get("leaderboard", []): + yield entry + 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 af38275..08915b0 100644 --- a/cabalspy_id/_constants.py +++ b/cabalspy_id/_constants.py @@ -4,7 +4,7 @@ from typing import Literal -SDK_VERSION = "0.6.0" +SDK_VERSION = "0.7.0" USER_AGENT = f"cabalspy-id-python/{SDK_VERSION}" DEFAULT_BASE_URL = "https://api-id.cabalspy.xyz/v1" @@ -55,6 +55,14 @@ "competition.standings", "competition.ended", ) +#: Webhook events about callouts (an extra, switched on per instance). Sent per instance; +#: ``data.callout`` is the callout, ``callout.milestone`` adds ``data.milestone_x``. +CALLOUT_WEBHOOK_EVENTS: tuple[str, ...] = ( + "callout.created", + "callout.milestone", + "callout.scored", + "callout.final", +) #: Webhook event types. WEBHOOK_EVENTS: tuple[str, ...] = ( "wallet.verified", @@ -68,6 +76,7 @@ "webhook.test", *PLATFORM_WEBHOOK_EVENTS, *COMPETITION_WEBHOOK_EVENTS, + *CALLOUT_WEBHOOK_EVENTS, ) #: Reactions: "like" plus a fixed emoji set. @@ -111,8 +120,47 @@ # ── trading competitions ───────────────────────────────────────────────────── -CompetitionMetric = Literal["pnl_usd", "pnl", "volume_usd", "volume", "trades", "win_rate"] -COMPETITION_METRICS: tuple[CompetitionMetric, ...] = ("pnl_usd", "pnl", "volume_usd", "volume", "trades", "win_rate") +#: Metrics of a trading competition (kind = trading). +TradingCompetitionMetric = Literal["pnl_usd", "pnl", "volume_usd", "volume", "trades", "win_rate"] +#: Metrics of a callout competition (kind = callouts): the callouts made during it, each +#: scored by its peak multiple. +CalloutCompetitionMetric = Literal["avg_peak_x", "best_peak_x", "sum_peak_x", "hit_rate", "callouts"] +#: Any competition metric: the trading ones, or the callout ones for kind = callouts. +CompetitionMetric = Literal[ + "pnl_usd", + "pnl", + "volume_usd", + "volume", + "trades", + "win_rate", + "avg_peak_x", + "best_peak_x", + "sum_peak_x", + "hit_rate", + "callouts", +] +#: Metrics of trading competitions. +COMPETITION_METRICS: tuple[TradingCompetitionMetric, ...] = ( + "pnl_usd", + "pnl", + "volume_usd", + "volume", + "trades", + "win_rate", +) +#: Metrics of callout competitions (kind = callouts). +CALLOUT_COMPETITION_METRICS: tuple[CalloutCompetitionMetric, ...] = ( + "avg_peak_x", + "best_peak_x", + "sum_peak_x", + "hit_rate", + "callouts", +) +#: trading: ranked on trades (default); callouts: ranked on callouts (needs the callouts extra). +CompetitionKind = Literal["trading", "callouts"] +COMPETITION_KINDS: tuple[CompetitionKind, ...] = ("trading", "callouts") +#: A competition's chain; "all" (every chain) only for callout competitions. +CompetitionChain = Literal["solana", "bnb", "base", "eth", "rh", "all"] #: waiting: the start time passed, but fewer than min_participants joined. CompetitionStatus = Literal["scheduled", "waiting", "running", "ended", "cancelled"] COMPETITION_STATUSES: tuple[CompetitionStatus, ...] = ("scheduled", "waiting", "running", "ended", "cancelled") @@ -121,3 +169,39 @@ COMPETITION_ENROLLMENTS: tuple[CompetitionEnrollment, ...] = ("opt_in", "all_users") #: Scheduled + running competitions at a time per developer account. MAX_OPEN_COMPETITIONS = 5 + +# ── callouts (an extra, switched on per instance on request) ───────────────── + +#: The ``features`` entry in ``me()`` when callouts are switched on for the instance. +FEATURE_CALLOUTS = "callouts" +DEFAULT_CALLOUTS_STREAM_URL = "wss://api-id.cabalspy.xyz/v1/callouts/stream" +#: Leaderboard sorts of the callers leaderboard. +CalloutSort = Literal["avg_peak_x", "best_peak_x", "sum_peak_x", "hit_rate", "callouts", "median_peak_x"] +CALLOUT_SORTS: tuple[CalloutSort, ...] = ( + "avg_peak_x", + "best_peak_x", + "sum_peak_x", + "hit_rate", + "callouts", + "median_peak_x", +) +#: Who may make callouts: every user, or only users with the KOL badge. +CalloutWho = Literal["all", "kol_only"] +CALLOUT_WHO: tuple[CalloutWho, ...] = ("all", "kol_only") +#: tracking: still tracked; final: tracking stopped (removed callouts are never returned). +CalloutStatus = Literal["tracking", "final"] +#: first_day: read every minute; extended: every 5 minutes while active; stopped. +CalloutPhase = Literal["first_day", "extended", "stopped"] +#: candles: the first day was scored on price candles; live: no candles, the live numbers stand. +CalloutFirstDayKind = Literal["candles", "live"] +#: Maximum note length in characters (at most one link). +CALLOUT_MAX_NOTE = 280 +#: Default ``hit_x``: a callout is a hit once its peak multiple reaches it. +CALLOUT_DEFAULT_HIT_X = 2.0 +#: Multiples announced once each as ``callout.milestone``. +CALLOUT_MILESTONES: tuple[int, ...] = (2, 3, 5, 10, 20, 50, 100) +#: After the first day, a token below this market cap (USD) for 24 hours in a row is +#: inactive and tracking stops. +CALLOUT_ACTIVE_MCAP_USD = 10_000 +#: Callout stream connections per API key. +MAX_CALLOUT_STREAMS_PER_KEY = 5 diff --git a/cabalspy_id/_errors.py b/cabalspy_id/_errors.py index e180086..7a291b0 100644 --- a/cabalspy_id/_errors.py +++ b/cabalspy_id/_errors.py @@ -80,7 +80,11 @@ 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. + + 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. + """ class AuthenticationError(CabalSpyIDError): @@ -89,7 +93,12 @@ class AuthenticationError(CabalSpyIDError): class PermissionError_(CabalSpyIDError): """403 — invalid_api_key, product_not_enabled, no_instance, scope_not_allowed; - public thesis API: origin_not_allowed; platform users: claim_disabled.""" + public thesis API: origin_not_allowed; platform users: claim_disabled. + + 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. + """ class PlanUserLimitError(PermissionError_): @@ -107,7 +116,7 @@ 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.""" + competitions: competition_not_found; callouts: callout_not_found.""" class ConflictError(CabalSpyIDError): @@ -116,14 +125,17 @@ class ConflictError(CabalSpyIDError): Platform users: account_claimed, last_wallet, too_many_wallets, 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. + competition_closed, competition_full, late_join_closed. Callouts: already_called + (the user called this token less than 24 hours ago). """ class RateLimitError(CabalSpyIDError): """429 — rate_limit_exceeded; public thesis API: rate_limited (Retry-After 60); platform users: rate_limited (new users or inbound events per minute), - too_many_open_verifications.""" + 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.""" def __init__(self, message: str, *, retry_after: float | None = None, **kwargs: Any) -> None: super().__init__(message, **kwargs) @@ -199,8 +211,11 @@ def error_from_status( "body": body, } message = b.get("message") or fallback + body_wait = b.get("retry_after") + if retry_after is None and isinstance(body_wait, (int, float)) and not isinstance(body_wait, bool): + retry_after = float(body_wait) - if status == 400: + if status in (400, 422): return BadRequestError(message, **kwargs) if status == 401: return AuthenticationError(message, **kwargs) @@ -219,6 +234,12 @@ def error_from_status( return CabalSpyIDError(message, **kwargs) +#: 429 codes that are not worth an automatic retry (the wait can be hours). +NOT_RETRYABLE_CODES = frozenset({"callout_cooldown"}) + + def is_retryable(exc: BaseException) -> bool: """True for failures where retrying with backoff is worthwhile.""" + if isinstance(exc, CabalSpyIDError) and exc.code in NOT_RETRYABLE_CODES: + return False return isinstance(exc, (RateLimitError, ServerError, APIConnectionError)) diff --git a/cabalspy_id/_types.py b/cabalspy_id/_types.py index 2b23468..41e5419 100644 --- a/cabalspy_id/_types.py +++ b/cabalspy_id/_types.py @@ -14,8 +14,15 @@ from typing import Any, Literal, TypedDict from ._constants import ( + CalloutFirstDayKind, + CalloutPhase, + CalloutSort, + CalloutStatus, + CalloutWho, Chain, + CompetitionChain, CompetitionEnrollment, + CompetitionKind, CompetitionMetric, CompetitionStatus, Currency, @@ -70,6 +77,8 @@ class MeResponse(TypedDict): #: Whether scope="global" is available (Enterprise). global_scope: bool users_with_data: int + #: Extras switched on for the instance by CabalSpy, e.g. ``["callouts"]``. + features: list[str] # ── users ──────────────────────────────────────────────────────────────────── @@ -1123,13 +1132,28 @@ class CompetitionChange(TypedDict): note: str | None -class Competition(TypedDict): - """A competition as listed (GET /v1/competitions).""" +class _CompetitionKindFields(TypedDict, total=False): + #: Trading competitions only. + min_trades: int + min_volume_usd: float + #: Callout competitions only: callouts needed to be ranked, and the multiple that counts as a hit. + min_callouts: int + hit_x: float + + +class Competition(_CompetitionKindFields): + """A competition as listed (GET /v1/competitions). + + Trading competitions carry ``min_trades`` and ``min_volume_usd``; callout + competitions (``kind`` = callouts) ``min_callouts`` and ``hit_x``. + """ id: str name: str description: str | None - chain: Chain + kind: CompetitionKind + #: "all" (every chain) only for callout competitions. + chain: CompetitionChain chain_name: str metric: CompetitionMetric wallet_trust: WalletTrust @@ -1143,8 +1167,6 @@ class Competition(TypedDict): min_participants: int max_participants: int | None participants: int - min_trades: int - min_volume_usd: float late_join: bool prizes: Any rules_version: int @@ -1166,8 +1188,22 @@ class CompetitionParticipant(TypedDict): joined_at: str | None +class CalloutBestCall(TypedDict): + """A caller's best callout (highest peak multiple).""" + + id: str + chain: Chain + mint: str + symbol: str | None + peak_x: float | None + + class CompetitionStanding(TypedDict, total=False): - """One trader. Unranked traders (below the minimums) have ``rank`` None.""" + """One trader. Unranked traders (below the minimums) have ``rank`` None. + + Trading competitions carry the trading stats (pnl ... wallets); callout + competitions the callout stats (callouts ... best_call). + """ rank: int | None ranked: bool @@ -1187,6 +1223,16 @@ class CompetitionStanding(TypedDict, total=False): win_rate: float tokens: int wallets: int + # callout competitions + callouts: int + avg_peak_x: float | None + median_peak_x: float | None + best_peak_x: float | None + sum_peak_x: float + hits: int + #: Percent (0-100) of the callouts that reached ``hit_x``. + hit_rate: float + best_call: CalloutBestCall | None class CompetitionStandings(TypedDict): @@ -1208,3 +1254,191 @@ class CompetitionMembership(TypedDict, total=False): already: bool #: leave: whether the user was a participant. left: bool + + +# ── callouts (an extra, switched on per instance on request) ───────────────── + + +class CalloutUser(TypedDict, total=False): + """The caller. A user without a profile row only has ``csid_id``.""" + + csid_id: str + #: Your platform's user id (white-label), else None. + external_id: str | None + name: str | None + username: str | None + avatar_url: str | None + kol: bool + + +class CalloutToken(TypedDict): + name: str | None + symbol: str | None + logo: str | None + + +class CalloutPrice(TypedDict): + price_usd: float | None + market_cap_usd: float | None + + +class CalloutQuote(CalloutPrice): + #: Multiple against the entry price (price / entry). + x: float | None + at: str | None + + +class CalloutTracking(TypedDict): + active: bool + phase: CalloutPhase + next_check_at: str | None + #: After the first day: since when the market cap is below $10k (tracking stops after + #: 24 h in a row below it). None while at or above it, and once tracking stopped. + below_10k_since: str | None + #: Daily candle checks done after the first day. + daily_checks: int + stopped_at: str | None + #: inactive (24 h below a $10k market cap) or no_price. + stop_reason: str | None + + +class CalloutFirstDay(TypedDict): + """The first 24 hours, scored on candles once they are over.""" + + kind: CalloutFirstDayKind + entry_price_usd: float | None + #: candles only (None for kind = live). + peak_x: float | None + close_x: float | None + minutes_to_peak: int | None + #: e.g. STALE_ENTRY, NO_TRADES_AFTER, NO_TRADES_LAST_6H, EXTREME_MULTIPLE, CANDLES_UNAVAILABLE. + flags: list[str] + + +class _CalloutOptional(TypedDict, total=False): + #: Present once the first day is scored (``callout.scored``). + first_day: CalloutFirstDay + + +class Callout(_CalloutOptional): + """A callout: a user called a token; price and market cap are stamped and tracked.""" + + id: str + chain: Chain + mint: str + token: CalloutToken + author: CalloutUser + note: str | None + called_at: str + #: The end of the first day (called_at + 24 h). + window_ends_at: str + status: CalloutStatus + #: Price and market cap at the call. + at_call: CalloutPrice + now: CalloutQuote + peak: CalloutQuote + #: The score: the peak multiple since the call. + score_x: float | None + #: Market data provider of the numbers. + source: str | None + tracking: CalloutTracking + + +class CalloutRemoved(TypedDict): + id: str + removed: bool + + +class CalloutSummary(TypedDict): + """Peak multiples of a set of callouts.""" + + callouts: int + avg_peak_x: float | None + median_peak_x: float | None + best_peak_x: float | None + sum_peak_x: float + #: Callouts whose peak multiple reached ``hit_x``. + hits: int + #: Percent (0-100) of the callouts that reached ``hit_x``. + hit_rate: float + + +class CalloutPeriodStats(CalloutSummary): + """One period: the callouts made in the last 6h / 1d / 7d / 30d.""" + + #: Average multiple right now. + avg_now_x: float | None + #: Callouts of the period that are still tracked. + tracking: int + + +class CalloutStats(TypedDict): + user: CalloutUser | None + hit_x: float + #: Keys 6h, 1d, 7d, 30d. + periods: dict[str, CalloutPeriodStats] + callouts_all_time: int + + +class CalloutLeaderboardEntry(CalloutSummary): + rank: int + csid_id: str + author: CalloutUser | None + best_call: CalloutBestCall + + +class CalloutLeaderboardResponse(TypedDict): + period: Period + chain: Chain | None + sort: CalloutSort + hit_x: float + leaderboard: list[CalloutLeaderboardEntry] + + +class CalloutSettings(TypedDict): + #: all, or kol_only (only users with the KOL badge). + who: CalloutWho + #: Only holders of the token may call it. + require_holding: bool + #: Minutes between two callouts of one user (0-10080). + cooldown_minutes: int + + +class CalloutMilestone(Callout): + """Stream event ``callout.milestone``: the callout plus the multiple reached.""" + + milestone_x: float + + +class CalloutUpdate(TypedDict): + """Stream event ``callout.update``: a new price of a tracked callout.""" + + id: str + chain: Chain + mint: str + price_usd: float + market_cap_usd: float | None + x: float | None + peak_x: float + + +class CalloutRemovedEvent(TypedDict): + """Stream event ``callout.removed``: the platform took a callout down.""" + + id: str + chain: Chain + mint: str + + +class CalloutsStreamReady(TypedDict): + events: list[str] + chain: Chain | None + mint: str | None + + +class CalloutWebhookData(TypedDict, total=False): + """``data`` of the webhooks callout.created / .milestone / .scored / .final.""" + + callout: Callout + #: callout.milestone only. + milestone_x: float diff --git a/cabalspy_id/api.py b/cabalspy_id/api.py index 2dfc5b1..177aeab 100644 --- a/cabalspy_id/api.py +++ b/cabalspy_id/api.py @@ -1,6 +1,6 @@ """``cabalspy_id.api`` — the SocialFi API: Data API clients (users, profiles, -verified wallets, trading stats, leaderboards, white-label platform users and -trading competitions), the live trade stream, Login with CabalSpy ID (OpenID +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. from cabalspy_id.api import CabalSpyID, CabalSpyIDAuth, verify_webhook @@ -12,18 +12,30 @@ import cabalspy_id as _root from cabalspy_id import ( + CALLOUT_ACTIVE_MCAP_USD, + CALLOUT_COMPETITION_METRICS, + CALLOUT_DEFAULT_HIT_X, + CALLOUT_MAX_NOTE, + CALLOUT_MILESTONES, + CALLOUT_SORTS, + CALLOUT_WEBHOOK_EVENTS, + CALLOUT_WHO, CHAINS, COMPETITION_ENROLLMENTS, + COMPETITION_KINDS, COMPETITION_METRICS, COMPETITION_STATUSES, COMPETITION_WEBHOOK_EVENTS, CURRENCY_BY_CHAIN, DATA_SCOPES, DEFAULT_BASE_URL, + DEFAULT_CALLOUTS_STREAM_URL, DEFAULT_ISSUER, DEFAULT_STREAM_URL, + FEATURE_CALLOUTS, INBOUND_FORMATS, LEADERBOARD_SORTS, + MAX_CALLOUT_STREAMS_PER_KEY, MAX_OPEN_COMPETITIONS, MAX_REQUEST_BODY_BYTES, PERIODS, @@ -47,11 +59,39 @@ CabalSpyIDAuth, CabalSpyIDClaims, CabalSpyIDError, + Callout, + CalloutBestCall, + CalloutCompetitionMetric, + CalloutFirstDay, + CalloutFirstDayKind, + CalloutLeaderboardEntry, + CalloutLeaderboardResponse, + CalloutMilestone, + CalloutPeriodStats, + CalloutPhase, + CalloutPrice, + CalloutQuote, + CalloutRemoved, + CalloutRemovedEvent, + CalloutSettings, + CalloutSort, + CalloutsStreamReady, + CalloutStats, + CalloutStatus, + CalloutSummary, + CalloutToken, + CalloutTracking, + CalloutUpdate, + CalloutUser, + CalloutWebhookData, + CalloutWho, Chain, Competition, + CompetitionChain, CompetitionChange, CompetitionDetail, CompetitionEnrollment, + CompetitionKind, CompetitionMembership, CompetitionMetric, CompetitionParticipant, @@ -147,6 +187,7 @@ Trade, TradeOwner, TraderProfile, + TradingCompetitionMetric, VerificationStatus, VerifiedWallet, WalletAdded, @@ -331,11 +372,59 @@ "CompetitionStanding", "CompetitionStandings", "CompetitionMembership", + # callouts + "CalloutsStream", + "CALLOUTS_STREAM_EVENTS", + "CALLOUT_EVENTS", + "CALLOUT_WEBHOOK_EVENTS", + "CALLOUT_COMPETITION_METRICS", + "COMPETITION_KINDS", + "CALLOUT_SORTS", + "CALLOUT_WHO", + "CALLOUT_MAX_NOTE", + "CALLOUT_DEFAULT_HIT_X", + "CALLOUT_MILESTONES", + "CALLOUT_ACTIVE_MCAP_USD", + "MAX_CALLOUT_STREAMS_PER_KEY", + "DEFAULT_CALLOUTS_STREAM_URL", + "FEATURE_CALLOUTS", + "TradingCompetitionMetric", + "CalloutCompetitionMetric", + "CompetitionKind", + "CompetitionChain", + "CalloutSort", + "CalloutWho", + "CalloutStatus", + "CalloutPhase", + "CalloutFirstDayKind", + "Callout", + "CalloutUser", + "CalloutToken", + "CalloutPrice", + "CalloutQuote", + "CalloutTracking", + "CalloutFirstDay", + "CalloutRemoved", + "CalloutSummary", + "CalloutPeriodStats", + "CalloutStats", + "CalloutBestCall", + "CalloutLeaderboardEntry", + "CalloutLeaderboardResponse", + "CalloutSettings", + "CalloutMilestone", + "CalloutUpdate", + "CalloutRemovedEvent", + "CalloutsStreamReady", + "CalloutWebhookData", ] +_LAZY_CALLOUTS = ("CalloutsStream", "CALLOUTS_STREAM_EVENTS", "CALLOUT_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"): + if name in ("CabalSpyIDStream", "STREAM_EVENTS", *_LAZY_CALLOUTS): return getattr(_root, name) raise AttributeError(f"module 'cabalspy_id.api' has no attribute {name!r}") diff --git a/examples/callouts.py b/examples/callouts.py new file mode 100644 index 0000000..3ec6c54 --- /dev/null +++ b/examples/callouts.py @@ -0,0 +1,121 @@ +"""Callouts tour: your users call tokens, every call is stamped and tracked. + + pip install "cabalspy-id[stream]" # the stream part only + CABALSPY_API_KEY=... python examples/callouts.py + +Callouts are an extra that CabalSpy switches on per instance on request; without +it every call raises PermissionError (feature_not_enabled). The user and the token +below are placeholders: replace them with one of your platform users and a token +they hold. +""" + +from __future__ import annotations + +import asyncio +from typing import Any + +from cabalspy_id import ( + FEATURE_CALLOUTS, + AsyncCabalSpyID, + CabalSpyID, + Chain, + ConflictError, + PermissionError, + RateLimitError, +) + +USER = "user_1" # your platform's user id (external_id) +CHAIN: Chain = "solana" +MINT = "So11111111111111111111111111111111111111112" + + +def tour() -> None: + with CabalSpyID() as csid: # reads CABALSPY_ID_API_KEY or CABALSPY_API_KEY + if FEATURE_CALLOUTS not in csid.me()["features"]: + print("Callouts are not switched on for this instance yet: ask CabalSpy to enable them.") + return + + # Rules of the instance: who may call, holders only, cooldown between two callouts + settings = csid.update_callout_settings(who="all", require_holding=True, cooldown_minutes=360) + print("settings:", settings) + + # 1. A user calls a token: price and market cap are stamped now and tracked from here + try: + c = csid.create_callout(USER, chain=CHAIN, mint=MINT, note="Strong chart, team ships") + print(f"called {c['token']['symbol']} at ${c['at_call']['market_cap_usd']:,.0f} market cap") + except ConflictError as err: # already_called: one call per token and 24 hours + print("already called:", err.message) + except RateLimitError as err: # callout_cooldown: never retried by the SDK + print(f"cooldown: next callout in {err.retry_after or 0:.0f} s") + except PermissionError as err: # not_a_holder, kol_only, posting_paused, ... + print("not allowed:", err.code) + + # 2. Callouts on the token, e.g. as chart markers (newest first) + for c in csid.iter_callouts(chain=CHAIN, mint=MINT): + t = c["tracking"] + print( + f" {c['called_at']} {c['author'].get('name')} now {c['now']['x']}x peak {c['score_x']}x ({t['phase']})" + ) + if t["below_10k_since"]: + print(" below a $10k market cap since", t["below_10k_since"]) + if "first_day" in c: + print(" first day:", c["first_day"]["kind"], c["first_day"]["peak_x"]) + + # 3. One user's numbers per period (6h, 1d, 7d, 30d) + stats = csid.callout_stats(USER, hit_x=2) + for period, s in stats["periods"].items(): + print(f" {period}: {s['callouts']} callouts, avg peak {s['avg_peak_x']}x, hit rate {s['hit_rate']}%") + + # 4. The callers leaderboard + board = csid.callout_leaderboard(period="7d", sort="avg_peak_x", min_callouts=1) + for e in board["leaderboard"][:10]: + name = (e["author"] or {}).get("name") or e["csid_id"] + print(f" #{e['rank']} {name}: avg {e['avg_peak_x']}x, best {e['best_call']['symbol']} {e['best_peak_x']}x") + + # 5. A callout competition between your users (counts every chain) + comp = csid.create_competition( + name="Caller of the week", + kind="callouts", + chain="all", + metric="avg_peak_x", + duration_hours=168, + min_callouts=3, + hit_x=2, + enrollment="all_users", + ) + print("competition:", comp["id"], comp["status"]) + + +async def live() -> None: + """Every callout event of the instance for 60 seconds.""" + async with AsyncCabalSpyID() as csid: + cs = csid.callouts_stream(chain=CHAIN) + + @cs.on("callout.created") + def on_created(c: dict[str, Any]) -> None: + print("new callout:", c["token"]["symbol"], "by", c["author"].get("name")) + + @cs.on("callout.milestone") + def on_milestone(c: dict[str, Any]) -> None: + print(f"{c['token']['symbol']} hit {c['milestone_x']}x") + + @cs.on("callout.final") + def on_final(c: dict[str, Any]) -> None: + print("tracking stopped:", c["id"], c["tracking"]["stop_reason"], "score", c["score_x"]) + + @cs.on("error") + def on_error(e: Exception) -> None: + print("error:", e) + + 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 b744e93..7438d0d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cabalspy-id" -version = "0.6.0" +version = "0.7.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 new file mode 100644 index 0000000..a46c82d --- /dev/null +++ b/tests/test_callouts.py @@ -0,0 +1,483 @@ +"""Callouts (an extra per instance) and callout competitions, against mocked HTTP.""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +from typing import Any + +import httpx +import pytest + +from cabalspy_id import ( + CALLOUT_COMPETITION_METRICS, + CALLOUT_SORTS, + CALLOUT_WEBHOOK_EVENTS, + COMPETITION_METRICS, + WEBHOOK_EVENTS, + AsyncCabalSpyID, + BadRequestError, + CabalSpyID, + ConflictError, + NotFoundError, + PermissionError, + RateLimitError, + ServerError, + api, +) +from cabalspy_id._errors import is_retryable + +from .conftest import Recorder, api_error, ok +from .test_platform_users import call, make, query + +KEY = "csid_api_testkey" +SOL = "So11111111111111111111111111111111111111112" + +CALLOUT: dict[str, Any] = { + "id": "c1", + "chain": "solana", + "mint": SOL, + "token": {"name": "Wrapped SOL", "symbol": "SOL", "logo": None}, + "author": { + "csid_id": "a1", + "external_id": "u1", + "name": "Alice", + "username": None, + "avatar_url": None, + "kol": False, + }, + "note": "gm", + "called_at": "2026-10-31T12:00:00Z", + "window_ends_at": "2026-11-01T12:00:00Z", + "status": "tracking", + "at_call": {"price_usd": 1.0, "market_cap_usd": 50000.0}, + "now": {"price_usd": 2.0, "market_cap_usd": 100000.0, "x": 2.0, "at": "2026-10-31T13:00:00Z"}, + "peak": {"price_usd": 3.0, "market_cap_usd": 150000.0, "x": 3.0, "at": "2026-10-31T12:30:00Z"}, + "score_x": 3.0, + "source": "birdeye", + "tracking": { + "active": True, + "phase": "first_day", + "next_check_at": None, + "below_10k_since": None, + "daily_checks": 0, + "stopped_at": None, + "stop_reason": None, + }, +} + + +# ── every endpoint: method, path, query / body ─────────────────────────────── + + +def test_every_callout_endpoint() -> None: + csid, rec = make() + csid.create_callout("u1", chain="solana", mint=SOL, note="gm") + csid.create_callout(csid_id="4b7c", chain="base", mint="0xabc") + csid.remove_callout("c1", reason="spam") + csid.remove_callout("c2") + csid.callouts( + chain="solana", + mint=SOL, + external_id="u1", + since=datetime(2026, 10, 30, 18, tzinfo=timezone.utc), + until="2026-10-31T00:00:00Z", + limit=20, + cursor="abc", + ) + csid.callouts() + csid.callouts(csid_id="4b7c", since=datetime(2026, 10, 30, 20, 0, tzinfo=timezone(timedelta(hours=2)))) + csid.callout("c1") + csid.callout_stats("u1", hit_x=3) + csid.callout_stats(csid_id="4b7c") + csid.callout_leaderboard(period="30d", chain="bnb", sort="hit_rate", min_callouts=3, hit_x=5, limit=10, cursor="x") + csid.callout_leaderboard() + csid.callout_settings() + csid.update_callout_settings(who="kol_only", require_holding=False, cooldown_minutes=0) + csid.update_callout_settings(cooldown_minutes=60) + + assert [call(r) for r in rec.requests] == [ + ("POST", "/v1/callouts", {"external_id": "u1", "chain": "solana", "mint": SOL, "note": "gm"}), + ("POST", "/v1/callouts", {"csid_id": "4b7c", "chain": "base", "mint": "0xabc"}), + ("POST", "/v1/callouts/remove", {"id": "c1", "reason": "spam"}), + ("POST", "/v1/callouts/remove", {"id": "c2"}), + ( + "GET", + "/v1/callouts", + { + "chain": "solana", + "mint": SOL, + "external_id": "u1", + "since": "2026-10-30T18:00:00Z", + "until": "2026-10-31T00:00:00Z", + "limit": "20", + "cursor": "abc", + }, + ), + ("GET", "/v1/callouts", {}), + ("GET", "/v1/callouts", {"csid_id": "4b7c", "since": "2026-10-30T18:00:00Z"}), + ("GET", "/v1/callouts/item", {"id": "c1"}), + ("GET", "/v1/callouts/stats", {"external_id": "u1", "hit_x": "3"}), + ("GET", "/v1/callouts/stats", {"csid_id": "4b7c"}), + ( + "GET", + "/v1/callouts/leaderboard", + { + "period": "30d", + "chain": "bnb", + "sort": "hit_rate", + "min_callouts": "3", + "hit_x": "5", + "limit": "10", + "cursor": "x", + }, + ), + ("GET", "/v1/callouts/leaderboard", {}), + ("GET", "/v1/callouts/settings", {}), + ("POST", "/v1/callouts/settings", {"who": "kol_only", "require_holding": False, "cooldown_minutes": 0}), + ("POST", "/v1/callouts/settings", {"cooldown_minutes": 60}), + ] + assert all(r.headers["Authorization"] == f"Bearer {KEY}" for r in rec.requests) + + +def test_naive_datetime_is_utc() -> None: + csid, rec = make(lambda r: ok([])) + csid.callouts(since=datetime(2026, 10, 30, 18, 0, 0, 123000)) + assert query(rec.requests[0]) == {"since": "2026-10-30T18:00:00.123000Z"} + + +def test_returns_the_callout() -> None: + csid, _ = make(lambda r: httpx.Response(201, json={"success": True, "data": CALLOUT})) + c = csid.create_callout("u1", chain="solana", mint=SOL) + assert c["score_x"] == 3.0 + assert c["tracking"]["below_10k_since"] is None + assert c["at_call"]["market_cap_usd"] == 50000.0 + + +def test_callout_validation() -> None: + csid, rec = make() + with pytest.raises(BadRequestError): + csid.create_callout(chain="solana", mint=SOL) # no user + with pytest.raises(BadRequestError): + csid.create_callout("u1", csid_id="a", chain="solana", mint=SOL) # both + with pytest.raises(BadRequestError) as e: + csid.create_callout("u1", chain="tron", mint=SOL) # type: ignore[arg-type] + assert e.value.parameter == "chain" + with pytest.raises(BadRequestError) as e: + csid.create_callout("u1", chain="solana", mint="") + assert e.value.parameter == "mint" + with pytest.raises(BadRequestError) as e: + csid.create_callout("u1", chain="solana", mint=SOL, note="x" * 281) + assert e.value.parameter == "note" + with pytest.raises(BadRequestError): + csid.remove_callout("") + with pytest.raises(BadRequestError) as e: + csid.callouts(mint=SOL) + assert e.value.parameter == "chain" + with pytest.raises(BadRequestError): + csid.callouts(external_id="u1", csid_id="a") + with pytest.raises(BadRequestError): + csid.callouts(chain="sol") # type: ignore[arg-type] + with pytest.raises(BadRequestError): + csid.callout("") + with pytest.raises(BadRequestError): + csid.callout_stats() + for bad in (1, 0.5, 1001, True, "2"): + with pytest.raises(BadRequestError) as e: + csid.callout_stats("u1", hit_x=bad) # type: ignore[arg-type] + assert e.value.parameter == "hit_x" + with pytest.raises(BadRequestError) as e: + csid.callout_leaderboard(period="1y") # type: ignore[arg-type] + assert e.value.parameter == "period" + with pytest.raises(BadRequestError) as e: + csid.callout_leaderboard(sort="pnl") # type: ignore[arg-type] + assert e.value.allowed == list(CALLOUT_SORTS) + for bad_min in (0, 1001, 2.5): + with pytest.raises(BadRequestError): + csid.callout_leaderboard(min_callouts=bad_min) # type: ignore[arg-type] + with pytest.raises(BadRequestError): + csid.update_callout_settings() + with pytest.raises(BadRequestError) as e: + csid.update_callout_settings(who="everyone") # type: ignore[arg-type] + assert e.value.allowed == ["all", "kol_only"] + for bad_cd in (-1, 10081, True): + with pytest.raises(BadRequestError): + csid.update_callout_settings(cooldown_minutes=bad_cd) + assert rec.requests == [] + + +# ── iterators ──────────────────────────────────────────────────────────────── + + +def test_iter_callouts_follows_cursor() -> None: + def handler(r: httpx.Request) -> httpx.Response: + cur = query(r).get("cursor") + if cur is None: + return ok([{"id": "c1"}, {"id": "c2"}], pagination={"limit": 2, "has_more": True, "next_cursor": "n1"}) + return ok([{"id": "c3"}], pagination={"limit": 2, "has_more": False, "next_cursor": None}) + + csid, rec = make(handler) + since = datetime(2026, 10, 1, tzinfo=timezone.utc) + assert [c["id"] for c in csid.iter_callouts(chain="solana", limit=2, since=since)] == ["c1", "c2", "c3"] + assert [query(r) for r in rec.requests] == [ + {"chain": "solana", "since": "2026-10-01T00:00:00Z", "limit": "2"}, + {"chain": "solana", "since": "2026-10-01T00:00:00Z", "limit": "2", "cursor": "n1"}, + ] + + +def test_iter_callout_leaderboard_follows_cursor() -> None: + def handler(r: httpx.Request) -> httpx.Response: + start = 2 if query(r).get("cursor") else 0 + rows = [{"rank": i + 1, "csid_id": f"a{i}"} for i in range(start, min(start + 2, 3))] + nxt = "o2" if start == 0 else None + return ok( + {"period": "7d", "chain": None, "sort": "avg_peak_x", "hit_x": 2.0, "leaderboard": rows}, + pagination={"limit": 2, "total": 3, "has_more": nxt is not None, "next_cursor": nxt}, + ) + + csid, rec = make(handler) + ranks = [e["rank"] for e in csid.iter_callout_leaderboard(sort="avg_peak_x", min_callouts=2, limit=2)] + assert ranks == [1, 2, 3] + assert query(rec.requests[1]) == {"sort": "avg_peak_x", "min_callouts": "2", "limit": "2", "cursor": "o2"} + + +async def test_async_callouts() -> None: + def handler(r: httpx.Request) -> httpx.Response: + if r.url.path == "/v1/callouts" and r.method == "GET": + if query(r).get("cursor"): + return ok([{"id": "c2"}], pagination={"has_more": False, "next_cursor": None}) + return ok([{"id": "c1"}], pagination={"has_more": True, "next_cursor": "n"}) + if r.url.path == "/v1/callouts/leaderboard": + return ok({"leaderboard": [{"rank": 1}]}, pagination={"has_more": False, "next_cursor": None}) + if r.url.path == "/v1/callouts/stats": + return ok({"user": None, "hit_x": 2.0, "periods": {}, "callouts_all_time": 0}) + if r.url.path == "/v1/callouts/settings": + return ok({"who": "all", "require_holding": True, "cooldown_minutes": 360}) + return httpx.Response(201, json={"success": True, "data": CALLOUT}) + + rec = Recorder(handler) + async with AsyncCabalSpyID(KEY, http_client=rec.async_client(), max_retries=0) as csid: + assert (await csid.create_callout("u1", chain="solana", mint=SOL))["id"] == "c1" + assert (await csid.callout("c1"))["id"] == "c1" + assert (await csid.remove_callout("c1"))["id"] == "c1" + assert (await csid.callout_stats("u1"))["callouts_all_time"] == 0 + assert (await csid.callout_settings())["cooldown_minutes"] == 360 + assert (await csid.update_callout_settings(require_holding=True))["who"] == "all" + assert [c["id"] async for c in csid.iter_callouts()] == ["c1", "c2"] + assert [e["rank"] async for e in csid.iter_callout_leaderboard(period="1d")] == [1] + assert (await csid.callouts(chain="eth"))[0]["id"] == "c1" + assert (await csid.callout_leaderboard())["leaderboard"][0]["rank"] == 1 + assert call(rec.requests[0]) == ("POST", "/v1/callouts", {"external_id": "u1", "chain": "solana", "mint": SOL}) + + +# ── errors ─────────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("status", "code", "cls"), + [ + (403, "feature_not_enabled", PermissionError), + (403, "kol_only", PermissionError), + (403, "not_a_holder", PermissionError), + (403, "invalid_account", PermissionError), + (403, "posting_paused", PermissionError), + (403, "consent_required", PermissionError), + (404, "callout_not_found", NotFoundError), + (409, "already_called", ConflictError), + (422, "no_price", BadRequestError), + (503, "service_unavailable", ServerError), + ], +) +def test_callout_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.create_callout("u1", chain="solana", mint=SOL) + assert e.value.code == code # type: ignore[attr-defined] + assert e.value.status == status # type: ignore[attr-defined] + assert len(rec.requests) == 1 # writes are not retried after a 5xx + + +def test_callout_cooldown_is_not_retried(monkeypatch: pytest.MonkeyPatch) -> None: + sleeps: list[float] = [] + monkeypatch.setattr("cabalspy_id._client.time.sleep", sleeps.append) + csid, rec = make( + lambda r: api_error(429, "callout_cooldown", headers={"Retry-After": "7200"}, retry_after=7200), + max_retries=3, + ) + with pytest.raises(RateLimitError) as e: + csid.create_callout("u1", chain="solana", mint=SOL) + assert e.value.code == "callout_cooldown" + assert e.value.retry_after == 7200 + assert len(rec.requests) == 1 + assert sleeps == [] + assert not is_retryable(e.value) + + +def test_retry_after_from_the_body_when_no_header() -> None: + csid, _ = make(lambda r: api_error(429, "callout_cooldown", retry_after=90)) + with pytest.raises(RateLimitError) as e: + csid.create_callout("u1", chain="solana", mint=SOL) + assert e.value.retry_after == 90.0 + + +def test_callout_cooldown_on_get_is_not_retried(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("cabalspy_id._client.time.sleep", lambda s: None) + csid, rec = make(lambda r: api_error(429, "callout_cooldown", headers={"Retry-After": "60"}), max_retries=3) + with pytest.raises(RateLimitError): + csid.get_raw("/callouts") + assert len(rec.requests) == 1 + # the API's own rate limit still is + csid, rec = make(lambda r: api_error(429, "rate_limit_exceeded", headers={"Retry-After": "0"}), max_retries=2) + with pytest.raises(RateLimitError): + csid.callouts() + assert len(rec.requests) == 3 + + +# ── /v1/me features, webhooks, exports ─────────────────────────────────────── + + +def test_me_features() -> None: + csid, _ = make(lambda r: ok({"instance": "app.example.com", "features": ["callouts"]})) + me = csid.me() + assert "callouts" in me["features"] + + +def test_callout_webhook_events() -> None: + assert CALLOUT_WEBHOOK_EVENTS == ("callout.created", "callout.milestone", "callout.scored", "callout.final") + assert set(CALLOUT_WEBHOOK_EVENTS) <= set(WEBHOOK_EVENTS) + + +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 + for name in ("Callout", "CalloutStats", "CalloutLeaderboardEntry", "CalloutSettings", "CALLOUT_SORTS"): + assert name in cabalspy_id.__all__ and name in api.__all__ + + +# ── callout competitions ───────────────────────────────────────────────────── + + +def test_callout_competition_create_and_update() -> None: + csid, rec = make() + csid.create_competition( + name="Best caller", + kind="callouts", + chain="all", + metric="avg_peak_x", + duration_hours=168, + min_callouts=3, + hit_x=5, + enrollment="all_users", + ) + csid.create_competition(name="Solana calls", kind="callouts", chain="solana", metric="hit_rate", duration_hours=24) + csid.create_competition(name="Trading", kind="trading", chain="base", metric="pnl_usd", duration_hours=24) + csid.update_competition("c1", min_callouts=5, hit_x=3.5, chain="all", metric="best_peak_x", note="tighter") + csid.update_competition("c2", metric="pnl") + assert [call(r) for r in rec.requests] == [ + ( + "POST", + "/v1/competitions", + { + "name": "Best caller", + "kind": "callouts", + "chain": "all", + "metric": "avg_peak_x", + "duration_hours": 168, + "min_callouts": 3, + "hit_x": 5, + "enrollment": "all_users", + }, + ), + ( + "POST", + "/v1/competitions", + {"name": "Solana calls", "kind": "callouts", "chain": "solana", "metric": "hit_rate", "duration_hours": 24}, + ), + ( + "POST", + "/v1/competitions", + {"name": "Trading", "kind": "trading", "chain": "base", "metric": "pnl_usd", "duration_hours": 24}, + ), + ( + "POST", + "/v1/competitions/update", + {"id": "c1", "chain": "all", "metric": "best_peak_x", "min_callouts": 5, "hit_x": 3.5, "note": "tighter"}, + ), + ("POST", "/v1/competitions/update", {"id": "c2", "metric": "pnl"}), + ] + + +def test_callout_competition_validation() -> None: + csid, rec = make() + # trading (the default kind): no chain "all", no callout metrics or minimums + with pytest.raises(BadRequestError) as e: + csid.create_competition(name="x", chain="all", metric="pnl", duration_hours=1) + assert e.value.parameter == "chain" + with pytest.raises(BadRequestError) as e: + csid.create_competition(name="x", chain="solana", metric="avg_peak_x", duration_hours=1) + assert e.value.allowed == list(COMPETITION_METRICS) + with pytest.raises(BadRequestError) as e: + csid.create_competition(name="x", chain="solana", metric="pnl", duration_hours=1, min_callouts=2) + assert e.value.parameter == "min_callouts" + # callouts: no trading metrics or minimums + with pytest.raises(BadRequestError) as e: + csid.create_competition(name="x", kind="callouts", chain="all", metric="pnl", duration_hours=1) + assert e.value.allowed == list(CALLOUT_COMPETITION_METRICS) + with pytest.raises(BadRequestError) as e: + csid.create_competition( + name="x", kind="callouts", chain="all", metric="callouts", duration_hours=1, min_trades=1 + ) + assert e.value.parameter == "min_trades" + with pytest.raises(BadRequestError) as e: + csid.create_competition(name="x", kind="callouts", chain="all", metric="callouts", duration_hours=1, hit_x=1) + assert e.value.parameter == "hit_x" + with pytest.raises(BadRequestError) as e: + csid.create_competition(name="x", kind="league", chain="all", metric="callouts", duration_hours=1) # type: ignore[arg-type] + assert e.value.parameter == "kind" + # update: the kind is the server's; only the value ranges are checked here + with pytest.raises(BadRequestError): + csid.update_competition("c1", hit_x=2000) + with pytest.raises(BadRequestError): + csid.update_competition("c1", metric="best") # type: ignore[arg-type] + with pytest.raises(BadRequestError): + csid.update_competition("c1", chain="tron") # type: ignore[arg-type] + assert rec.requests == [] + + +def test_callout_competition_feature_not_enabled() -> None: + csid, _ = make(lambda r: api_error(403, "feature_not_enabled")) + with pytest.raises(PermissionError) as e: + csid.create_competition(name="x", kind="callouts", chain="all", metric="callouts", duration_hours=1) + assert e.value.code == "feature_not_enabled" + + +def test_callout_standings_iterate() -> None: + row = { + "rank": 1, + "ranked": True, + "csid_id": "a1", + "score": 4.5, + "callouts": 3, + "avg_peak_x": 4.5, + "best_call": {"id": "c1", "chain": "solana", "mint": SOL, "symbol": "SOL", "peak_x": 9.0}, + } + csid, _ = make(lambda r: ok({"standings": [row]}, pagination={"limit": 100, "total": 1})) + rows = list(csid.iter_competition_standings("comp")) + assert rows[0]["best_call"]["peak_x"] == 9.0 + + +async def test_async_callout_competition() -> None: + rec = Recorder(lambda r: ok({"id": "comp", "kind": "callouts"})) + async with AsyncCabalSpyID(KEY, http_client=rec.async_client(), max_retries=0) as csid: + comp = await csid.create_competition( + name="n", kind="callouts", chain="all", metric="sum_peak_x", duration_hours=2 + ) + assert comp["kind"] == "callouts" + assert call(rec.requests[0])[2]["kind"] == "callouts" + + +def test_client_option() -> None: + assert CabalSpyID("k", callouts_stream_url="ws://x/y/").callouts_stream_url == "ws://x/y" diff --git a/tests/test_callouts_stream.py b/tests/test_callouts_stream.py new file mode 100644 index 0000000..7a92dc2 --- /dev/null +++ b/tests/test_callouts_stream.py @@ -0,0 +1,230 @@ +"""CalloutsStream against a local server that behaves like /v1/callouts/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 ( + CALLOUT_EVENTS, + AuthenticationError, + BadRequestError, + CabalSpyID, + PermissionError, + RateLimitError, +) + +MINT = "So11111111111111111111111111111111111111112" +EVENTS = [ + {"event": "callout.created", "data": {"id": "c1", "chain": "solana", "mint": MINT, "score_x": 1.0}}, + { + "event": "callout.update", + "data": { + "id": "c1", + "chain": "solana", + "mint": MINT, + "price_usd": 2.0, + "market_cap_usd": None, + "x": 2.0, + "peak_x": 2.0, + }, + }, + {"event": "callout.milestone", "data": {"id": "c1", "chain": "solana", "mint": MINT, "milestone_x": 2}}, + {"event": "callout.scored", "data": {"id": "c1", "first_day": {"kind": "candles", "peak_x": 2.5}}}, + {"event": "callout.final", "data": {"id": "c1", "tracking": {"active": False, "stop_reason": "inactive"}}}, + {"event": "callout.removed", "data": {"id": "c1", "chain": "solana", "mint": MINT}}, +] + + +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": ("feature_not_enabled", "Callouts are not enabled for this instance."), + "busy": ("too_many_connections", "At most 5 callout 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 + q = {k: v[0] for k, v in parse_qs(urlsplit(ws.request.path).query).items()} + await ws.send( + json.dumps( + { + "event": "ready", + "data": {"events": list(CALLOUT_EVENTS), "chain": q.get("chain"), "mint": q.get("mint")}, + } + ) + ) + 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/callouts/stream" # type: ignore[attr-defined] + yield s + + +def client(s: Server, **kwargs: Any) -> CabalSpyID: + return CabalSpyID("k", callouts_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").callouts_stream(chain="solana", mint=MINT) + got: list[tuple[str, Any]] = [] + for name in (*CALLOUT_EVENTS, "heartbeat", "pong"): + cs.on(name, lambda d, name=name: got.append((name, d))) + ready = await cs.connect() + assert ready == {"events": list(CALLOUT_EVENTS), "chain": "solana", "mint": MINT} + q = {k: v[0] for k, v in parse_qs(urlsplit(server.paths[0]).query).items()} + assert q == {"api_key": "k", "chain": "solana", "mint": MINT, "instance": "csid_app"} + assert "k" not in cs.safe_url.split("api_key=")[1] + await wait_for(lambda: len(got) >= 7) + await cs.ping() + await wait_for(lambda: got[-1][0] == "pong") + await cs.close() + assert [n for n, _ in got] == ["heartbeat", *CALLOUT_EVENTS, "pong"] + data = dict(got[1:7]) + assert data["callout.created"]["score_x"] == 1.0 + assert data["callout.update"]["price_usd"] == 2.0 + assert data["callout.milestone"]["milestone_x"] == 2 + assert data["callout.scored"]["first_day"]["kind"] == "candles" + assert data["callout.final"]["tracking"]["stop_reason"] == "inactive" + assert data["callout.removed"] == {"id": "c1", "chain": "solana", "mint": MINT} + 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).callouts_stream() + seen: list[str] = [] + + @cs.on("callout.created") + async def on_created(c: Any) -> None: + seen.append(c["id"]) + + def boom(_c: Any) -> None: + raise ValueError("handler failed") + + errors: list[Any] = [] + cs.on("callout.removed", boom) + cs.on("error", errors.append) + await cs.connect() + await wait_for(lambda: bool(seen) and bool(errors)) + cs.off("callout.removed", boom) + await cs.close() + assert seen == ["c1"] + assert isinstance(errors[0], ValueError) + with pytest.raises(ValueError): + cs.on("callout.deleted", print) + + +async def test_iteration(server: Server) -> None: + seen: list[str] = [] + async with client(server).callouts_stream() as cs: + async for ev in cs: + seen.append(ev["event"]) + if len(seen) == len(CALLOUT_EVENTS): + break + assert seen == list(CALLOUT_EVENTS) + + +async def test_iteration_without_context_manager(server: Server) -> None: + cs = client(server).callouts_stream() + first: dict[str, Any] = {} + async for ev in cs: + first = ev + break + assert first["event"] == "callout.created" + await cs.close() + + +async def test_feature_not_enabled_is_fatal(server: Server) -> None: + server.mode = "deny" + cs = client(server).callouts_stream(reconnect_delay=0.01) + with pytest.raises(PermissionError) as e: + await cs.connect() + assert e.value.code == "feature_not_enabled" + 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).callouts_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).callouts_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: + cs = CabalSpyID("k", callouts_stream_url="ws://127.0.0.1:1/v1/callouts/stream").callouts_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(BadRequestError) as e: + CabalSpyID("k").callouts_stream(chain="tron") # type: ignore[arg-type] + assert e.value.parameter == "chain" + with pytest.raises(BadRequestError) as e: + CabalSpyID("k").callouts_stream(mint=MINT) + assert e.value.parameter == "chain" + with pytest.raises(AuthenticationError): + CabalSpyID("").callouts_stream() + cs = CabalSpyID("k").callouts_stream() + assert cs.safe_url == "wss://api-id.cabalspy.xyz/v1/callouts/stream?api_key=***"