Documentation
¶
Index ¶
- Constants
- Variables
- func SetDefaultCaptchaSolver(s CaptchaSolver)
- type APIError
- type ActivityKind
- type ActivityPeriod
- type ActivityRecord
- type ActivityStream
- type ActivityType
- type Address
- type Alpha
- type Auxiliary
- type BannedError
- type BrowserProfile
- type CaptchaSolver
- type Check
- type Classification
- type Client
- func (c *Client) Activities(ctx context.Context, kind ActivityKind) (*ActivityStream, error)
- func (c *Client) AlphaCheckBody(ctx context.Context, id string) (bool, []string, error)
- func (c *Client) AlphaPnL(ctx context.Context, id string) (*PnLSeries, error)
- func (c *Client) BaseURL() *url.URL
- func (c *Client) CheckAlpha(ctx context.Context, id string) (*IsBlock, error)
- func (c *Client) ClearCredentials()
- func (c *Client) Competitions(ctx context.Context) (*Page[Competition], error)
- func (c *Client) CompletePersona(ctx context.Context, inquiry, email, password string) (*Session, error)
- func (c *Client) CookieJarPath() string
- func (c *Client) Cooldown() time.Duration
- func (c *Client) CreateSimulation(ctx context.Context, req SimulationRequest) (string, error)
- func (c *Client) DataFields(ctx context.Context, q DataFieldsQuery) (*DataFieldsPage, error)
- func (c *Client) DataFieldsAll(ctx context.Context, q DataFieldsQuery) (<-chan DataField, <-chan error)
- func (c *Client) FetchCaptchaChallenge(ctx context.Context) ([]byte, error)
- func (c *Client) ForgotPassword(ctx context.Context, email, recaptcha string) error
- func (c *Client) GetAlpha(ctx context.Context, id string) (*Alpha, error)
- func (c *Client) GetSimulation(ctx context.Context, id string) (*Simulation, error)
- func (c *Client) IsBanned() bool
- func (c *Client) ListAlphas(ctx context.Context, opts ListAlphasOptions) (*Page[Alpha], error)
- func (c *Client) ListAlphasAll(ctx context.Context, opts ListAlphasOptions) (<-chan Alpha, <-chan error)
- func (c *Client) Logger() *slog.Logger
- func (c *Client) Login(ctx context.Context, email, password string) (*Session, error)
- func (c *Client) Logout(ctx context.Context) error
- func (c *Client) Operators(ctx context.Context) ([]Operator, error)
- func (c *Client) Probe(ctx context.Context) (*SessionInfo, error)
- func (c *Client) Profile() BrowserProfile
- func (c *Client) Register(ctx context.Context, in RegisterInput) (*User, error)
- func (c *Client) ResetPassword(ctx context.Context, jwt, newPassword string) error
- func (c *Client) ReverifyEmail(ctx context.Context, email, recaptcha string) error
- func (c *Client) Self(ctx context.Context) (*User, error)
- func (c *Client) SetCredentials(email, password string)
- func (c *Client) SubmitAlpha(ctx context.Context, id string) (*Verdict, error)
- func (c *Client) VerifyEmail(ctx context.Context, jwt string) error
- func (c *Client) WaitForSimulation(ctx context.Context, id string) (*Simulation, error)
- type Competition
- type CookieEntry
- type CookieSnapshot
- type DRFError
- type DailyBudget
- type DataField
- type DataFieldsPage
- type DataFieldsQuery
- type Education
- type IsBlock
- type Leaderboard
- type ListAlphasOptions
- type NamedRef
- type NotVerifiedError
- type Observer
- type Operator
- type Options
- type Page
- type PersonaInquiryError
- type PnLPoint
- type PnLSeries
- type RateLimitError
- type RecordSchema
- type RecordSetBlock
- type RegisterInput
- type RetryKind
- type SchemaProperty
- type Session
- type SessionInfo
- type SimSettings
- type Simulation
- type SimulationRequest
- type Token
- type User
- type UserRef
- type Verdict
Constants ¶
const DefaultProfile = ProfileChrome131
DefaultProfile is the production-recommended starting point. We keep this at chrome131 (mapped to Chrome_131_PSK internally) for parity with the production bridge — migrating an account from TS to Go preserves its fingerprint identity.
Variables ¶
var ( // ErrNotAuthenticated means the client has no usable session and no // credentials cached for auto-relogin. ErrNotAuthenticated = errors.New("brainapi: not authenticated") // ErrDailyBudgetExhausted means the in-process daily budget gate refused // the call. The counter resets at the next 3am-ET BRAIN day boundary. ErrDailyBudgetExhausted = errors.New("brainapi: daily budget exhausted") // ErrCooldown means a recent rate-limit or "concurrent simulation" response // put this Client into a temporary cooldown; the call was refused locally // without hitting the network. ErrCooldown = errors.New("brainapi: client in cooldown") // ErrLongPollExceeded means a long-poll (submit / simulation / pnl / // check-alpha) didn't reach a terminal state within MaxLongPolls. ErrLongPollExceeded = errors.New("brainapi: long-poll cap exceeded") )
Sentinel errors. Callers can use errors.Is to match.
var AgreeAll = []string{
"user-agreement",
"terms-conditions",
"privacy-policy",
"account-details",
"challenge",
}
AgreeAll is the canonical auxiliary.agree list that BRAIN's registration flow expects. Mirrors the AGREE_ALL constant in the TS registrar.
var ErrInvalidArgument = errors.New("brainapi: invalid argument")
ErrInvalidArgument is returned when the SDK rejects a caller-supplied value before dispatching the request (e.g. an empty alpha id).
Functions ¶
func SetDefaultCaptchaSolver ¶
func SetDefaultCaptchaSolver(s CaptchaSolver)
SetDefaultCaptchaSolver registers the captcha solver used by NewClient when Options.CaptchaSolver is nil. The altcha package calls this from its init(). Concurrent-safe.
Types ¶
type APIError ¶
APIError is the catch-all wrapper for any unexpected non-2xx response.
func AsAPIError ¶
AsAPIError unwraps to *APIError if err carries one.
type ActivityKind ¶
type ActivityKind string
ActivityKind is the path-segment for GET /users/self/activities/{kind}.
const ( ActivityBasePayment ActivityKind = "base-payment" ActivityOtherPayment ActivityKind = "other-payment" ActivitySimulations ActivityKind = "simulations" ActivitySubmissions ActivityKind = "submissions" )
type ActivityPeriod ¶
type ActivityPeriod struct {
Start string `json:"start"`
End string `json:"end"`
Value json.Number `json:"value"`
}
ActivityPeriod is one of the named summary windows.
type ActivityRecord ¶
type ActivityRecord map[string]json.RawMessage
ActivityRecord is a generic decoded row from ActivityStream.Records.records, keyed by RecordSchema.Properties[*].Name. Values are kept as json.RawMessage because the column types are heterogeneous (date/amount/integer/text).
func DecodeActivities ¶
func DecodeActivities(s *ActivityStream) ([]ActivityRecord, error)
DecodeActivities converts the tuple-array RecordSetBlock.Records into ActivityRecord dicts using the columnar schema. Returns an empty slice if either the schema or the records are absent.
type ActivityStream ¶
type ActivityStream struct {
Type ActivityType `json:"type"`
Currency string `json:"currency,omitempty"`
Yesterday *ActivityPeriod `json:"yesterday,omitempty"`
Current *ActivityPeriod `json:"current,omitempty"`
Previous *ActivityPeriod `json:"previous,omitempty"`
YTD *ActivityPeriod `json:"ytd,omitempty"`
Total *ActivityPeriod `json:"total,omitempty"`
Records *RecordSetBlock `json:"records,omitempty"`
}
ActivityStream is the body of GET /users/self/activities/{kind}.
type ActivityType ¶
type ActivityType string
ActivityType discriminates the two envelope shapes BRAIN returns for /activities/*: "DAILY" includes the yesterday/current/previous/ytd buckets; "LIST" only has total.
const ( ActivityTypeDaily ActivityType = "DAILY" ActivityTypeList ActivityType = "LIST" )
type Address ¶
type Address struct {
Country string `json:"country"`
State string `json:"state,omitempty"`
City string `json:"city,omitempty"`
Street string `json:"street,omitempty"`
Zip string `json:"zip,omitempty"`
}
Address is a sub-object of RegisterInput.
type Alpha ¶
type Alpha struct {
ID string `json:"id"`
Type string `json:"type"`
Author string `json:"author,omitempty"`
Settings json.RawMessage `json:"settings,omitempty"`
Regular json.RawMessage `json:"regular,omitempty"`
DateCreated string `json:"dateCreated,omitempty"`
DateSubmitted *string `json:"dateSubmitted,omitempty"`
DateModified string `json:"dateModified,omitempty"`
Name *string `json:"name,omitempty"`
Favorite bool `json:"favorite,omitempty"`
Hidden bool `json:"hidden,omitempty"`
Color json.RawMessage `json:"color,omitempty"`
Category json.RawMessage `json:"category,omitempty"`
Tags []string `json:"tags,omitempty"`
Classifications []Classification `json:"classifications,omitempty"`
Grade string `json:"grade,omitempty"`
Stage string `json:"stage,omitempty"`
Status string `json:"status,omitempty"`
Is *IsBlock `json:"is,omitempty"`
Os json.RawMessage `json:"os,omitempty"`
Train json.RawMessage `json:"train,omitempty"`
Test json.RawMessage `json:"test,omitempty"`
Prod json.RawMessage `json:"prod,omitempty"`
Competitions json.RawMessage `json:"competitions,omitempty"`
Themes json.RawMessage `json:"themes,omitempty"`
Pyramids json.RawMessage `json:"pyramids,omitempty"`
PyramidThemes json.RawMessage `json:"pyramidThemes,omitempty"`
Team json.RawMessage `json:"team,omitempty"`
Origin json.RawMessage `json:"origin,omitempty"`
}
Alpha mirrors the body of GET /alphas/{id} and the items in GET /users/self/alphas results[].
type Auxiliary ¶
type Auxiliary struct {
Agree []string `json:"agree"`
Password string `json:"password"`
Confirmation string `json:"confirmation"`
Captcha string `json:"captcha,omitempty"`
}
Auxiliary is the sub-object of RegisterInput. Captcha is auto-populated by the SDK after a successful CaptchaSolver round.
type BannedError ¶
BannedError means the client (typically a secondary account) hit the configured consecutive-403 threshold and is now considered banned.
func (*BannedError) Error ¶
func (e *BannedError) Error() string
type BrowserProfile ¶
type BrowserProfile string
BrowserProfile identifies the TLS/JA3 + HTTP/2 fingerprint to impersonate. The string names are stable across SDK versions even when the underlying tls-client constants are renamed — ParseProfile maps user input here.
const ( ProfileChrome131 BrowserProfile = "chrome131" // production-parity with the production bridge ProfileChrome133 BrowserProfile = "chrome133" // tls-client's current default ProfileChrome144 BrowserProfile = "chrome144" ProfileChrome146 BrowserProfile = "chrome146" ProfileSafari16 BrowserProfile = "safari16" ProfileSafariIOS BrowserProfile = "safari-ios" // alias for Safari_IOS_18_0 ProfileFirefox132 BrowserProfile = "firefox132" ProfileFirefox147 BrowserProfile = "firefox147" )
func ParseProfile ¶
func ParseProfile(s string) BrowserProfile
ParseProfile resolves a user-facing string ("chrome131" / "safari-ios" / "auto:user@x.com") into a BrowserProfile. Unknown strings fall back to DefaultProfile.
func ProfileForEmail ¶
func ProfileForEmail(email string) BrowserProfile
ProfileForEmail picks a profile deterministically from an email address by taking the low 64 bits of md5(email) modulo len(subProfiles). MD5 is used here purely as a uniform hash — it is NOT load-bearing for security.
type CaptchaSolver ¶
type CaptchaSolver interface {
Solve(ctx context.Context, fetch func(context.Context) ([]byte, error)) (string, error)
}
CaptchaSolver fetches a /captcha challenge and returns the base64-encoded solution payload to drop into auxiliary.captcha on POST /users.
The fetch callback is supplied by the SDK and bound to the active Client's transport — implementations don't import brainapi, which keeps the captcha sub-package free of import cycles. The standard implementation lives in pkg/captcha/altcha (CaptchaAdapter); callers can plug their own for tests or non-Altcha future captcha mechanisms.
type Check ¶
type Check struct {
Name string `json:"name"`
Result string `json:"result"` // PASS | FAIL | PENDING | ERROR
Limit *float64 `json:"limit,omitempty"`
Value *float64 `json:"value,omitempty"`
Competitions json.RawMessage `json:"competitions,omitempty"`
}
Check is one item of IsBlock.Checks.
type Classification ¶
Classification is one entry of Alpha.Classifications.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the BRAIN HTTP client. All endpoint methods route through it. Goroutine-safe; one Client per (account, proxy) pair is the intended usage pattern.
func NewClient ¶
NewClient constructs a Client from Options. Returns an error only if the underlying tls-client could not be initialized (e.g. an invalid proxy URL).
func (*Client) Activities ¶
func (c *Client) Activities(ctx context.Context, kind ActivityKind) (*ActivityStream, error)
Activities calls GET /users/self/activities/{kind}. The two envelope shapes (DAILY and LIST) are handled by ActivityStream's tagged decoder.
func (*Client) AlphaCheckBody ¶
AlphaCheckBody is a convenience that calls CheckAlpha and converts the resulting checks into a verdict-like {pass: bool, fails: []string} pair. Useful for CLI output.
func (*Client) AlphaPnL ¶
AlphaPnL calls GET /alphas/{id}/recordsets/pnl and long-polls until the PnL series is populated. Returns nil + ErrLongPollExceeded if the cache stays cold past MaxLongPolls.
func (*Client) CheckAlpha ¶
CheckAlpha calls GET /alphas/{id}/check and long-polls until a terminal (non-empty) body is returned, or MaxLongPolls is exceeded.
/check covers the deterministic pre-submit gates (LOW_SHARPE, LOW_FITNESS, turnover bounds, concentrated weight, sub-universe sharpe, matches-comp). It does NOT compute SELF_CORRELATION — that verdict only comes from SubmitAlpha.
func (*Client) ClearCredentials ¶
func (c *Client) ClearCredentials()
ClearCredentials wipes the cached email/password, undoing SetCredentials. After this call 401 responses propagate ErrNotAuthenticated instead of triggering a transparent re-login. Logout invokes this automatically; callers in long-lived services should invoke it when the credentials are no longer needed (e.g. after switching accounts). Safe to call concurrently with other Client methods.
func (*Client) Competitions ¶
Competitions calls GET /users/self/competitions and returns the (paginated) list of competitions the user has signed up for, with leaderboard info.
func (*Client) CompletePersona ¶
func (c *Client) CompletePersona(ctx context.Context, inquiry, email, password string) (*Session, error)
CompletePersona drives the persona-inquiry flow. Operationally dead-code in current BRAIN production (no secondary account login has triggered the inquiry envelope since rotation), but kept as a safety net per spec.
The function POSTs the inquiry id to /authentication/persona and then re-issues POST /authentication to finalize the session.
func (*Client) CookieJarPath ¶
CookieJarPath returns the on-disk path for persisted cookies (or "").
func (*Client) Cooldown ¶
Cooldown returns how long the Client is locked out by a server-side "concurrent" / "previous to finish" 429 hint. Zero if not cooling down.
func (*Client) CreateSimulation ¶
CreateSimulation calls POST /simulations and returns the new simulation id (extracted from the Location header). The body shape mirrors what BRAIN's platform UI sends — see SimulationRequest.
Budget: consumes one /sim slot if DailyBudget.Sims is set. Concurrency: bounded by MaxConcurrentSims.
func (*Client) DataFields ¶
func (c *Client) DataFields(ctx context.Context, q DataFieldsQuery) (*DataFieldsPage, error)
DataFields calls GET /data-fields with the four REQUIRED query params (instrumentType, region, universe, delay) and optional pagination. The response envelope is {count, results} — no next/previous URLs.
func (*Client) DataFieldsAll ¶
func (c *Client) DataFieldsAll(ctx context.Context, q DataFieldsQuery) (<-chan DataField, <-chan error)
DataFieldsAll iterates every data-field for the (region, universe, delay) tier by following BRAIN's count-vs-results pagination. Implementation walks the offset cursor since /data-fields has no next/previous links.
func (*Client) FetchCaptchaChallenge ¶
FetchCaptchaChallenge calls GET /captcha and returns the raw challenge body. Used by the altcha solver implementation. Exposed so callers can compose their own captcha flow if they need to.
func (*Client) ForgotPassword ¶
ForgotPassword calls POST /user/password/forgot to initiate the reset flow. recaptcha is the legacy v2 token; same caveat as ReverifyEmail.
func (*Client) GetAlpha ¶
GetAlpha calls GET /alphas/{id}. Single round-trip, returns the full alpha record. Note: is.selfCorrelation is only populated when status==ACTIVE; for UNSUBMITTED alphas the verdict comes from SubmitAlpha's long-poll, not from this endpoint.
func (*Client) GetSimulation ¶
GetSimulation calls GET /simulations/{id} and returns the current status. One-shot call; for a wait-to-completion loop use WaitForSimulation.
func (*Client) IsBanned ¶
IsBanned returns true after the consecutive-403 ban threshold has fired. Re-creating the Client clears the flag; this is intentional — the caller decides when to recover.
func (*Client) ListAlphas ¶
ListAlphas returns the first page of GET /users/self/alphas with the supplied options. Use ListAlphasAll for an iterator over all pages.
func (*Client) ListAlphasAll ¶
func (c *Client) ListAlphasAll(ctx context.Context, opts ListAlphasOptions) (<-chan Alpha, <-chan error)
ListAlphasAll yields every alpha matching opts by following Django REST pagination. Callers must drain the returned channel; cancellation is honored via ctx.
func (*Client) Logger ¶
Logger returns the Client's slog target. Useful for endpoint methods that want to log under the same handler.
func (*Client) Login ¶
Login performs POST /authentication with HTTP Basic auth. On success the session cookie lands in the configured cookie jar (and is persisted to disk if CookieJarPath is set). The email/password are cached on the Client so subsequent 401 retries can re-login transparently.
Three possible terminal outcomes:
- normal login: returns a Session with User+Token+Permissions
- persona inquiry: returns *PersonaInquiryError carrying the Inquiry id
- bad credentials: returns *APIError with status 401
func (*Client) Logout ¶
Logout calls DELETE /authentication. On success it also wipes the local session state: the persisted cookie jar file (if any), the in-memory jar cookies for the configured baseURL, and the cached email/password. The Client is safe to reuse for a fresh Login afterwards.
If DELETE fails (network error, 5xx, etc.) local state is left untouched so the caller can retry without losing a still-valid server-side session.
func (*Client) Operators ¶
Operators calls GET /operators. The response is a bare JSON array, not the Django REST pagination envelope.
func (*Client) Probe ¶
func (c *Client) Probe(ctx context.Context) (*SessionInfo, error)
Probe calls GET /authentication. Returns the live session info. Treats a 401 or an empty 200 body (observed in production after Logout destroys the server-side session but cached cookies look syntactically valid) as ErrNotAuthenticated — both mean "no usable session".
func (*Client) Profile ¶
func (c *Client) Profile() BrowserProfile
Profile returns the configured browser fingerprint name.
func (*Client) Register ¶
Register calls POST /users to create a new secondary account. The caller supplies profile data; the SDK fetches a fresh Altcha PoW captcha challenge via the configured CaptchaSolver and injects the encoded solution into auxiliary.captcha.
On 201 the body is opaque (TBD upstream); we return the parsed body if non-empty, else nil.
func (*Client) ResetPassword ¶
ResetPassword calls POST /user/password/reset with the JWT from the reset email link plus the desired new password.
func (*Client) ReverifyEmail ¶
ReverifyEmail calls POST /user/email/reverify in the anonymous (no-session) mode used by the production revival path.
Critical: the endpoint behaves differently when called with an active session cookie — see account-registration.md. Use a fresh Client (no prior Login) to stay in anonymous mode.
recaptcha is the legacy reCAPTCHA v2 token; this endpoint hasn't migrated to Altcha yet. Pass an empty string if BRAIN has dropped the field by now (we'll find out the first time the live call returns 400 with {recaptcha: ["required"]}).
func (*Client) SetCredentials ¶
SetCredentials updates the email/password cache used for auto-relogin. Safe to call concurrently with other methods.
func (*Client) SubmitAlpha ¶
SubmitAlpha calls POST /alphas/{id}/submit then long-polls GET until a terminal verdict is observed. This is the ONLY source of truth for SELF_CORRELATION outcomes; GET /alphas/{id} alone is insufficient.
Verdict.Status is one of: "verified" | "corr_rejected" | "submit_failed" | "pending_corr" (latter means long-poll cap exceeded).
Budget: each call consumes one /submit slot if DailyBudget.Submits is set.
func (*Client) VerifyEmail ¶
VerifyEmail calls POST /user/email/verify with the JWT extracted from the verification-mail link. The JWT is the entire payload — body is empty, auth lives in the Authorization: Bearer header.
func (*Client) WaitForSimulation ¶
WaitForSimulation polls GET /simulations/{id} until the response carries terminal status (COMPLETE / FAIL / ERROR) or MaxLongPolls is exceeded. FAIL and ERROR are NOT wrapped as Go errors — the caller is expected to inspect Simulation.Status. We only surface transport / context errors.
type Competition ¶
type Competition struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Scoring string `json:"scoring"`
Status string `json:"status"`
SignUpDate *string `json:"signUpDate"`
StartDate *string `json:"startDate"`
EndDate *string `json:"endDate"`
SignUpStartDate *string `json:"signUpStartDate"`
SignUpEndDate *string `json:"signUpEndDate"`
Leaderboard *Leaderboard `json:"leaderboard"`
Countries json.RawMessage `json:"countries"`
ExcludedCountries json.RawMessage `json:"excludedCountries"`
Universities json.RawMessage `json:"universities"`
Team json.RawMessage `json:"team"`
TeamBased bool `json:"teamBased"`
PrizeBoard bool `json:"prizeBoard"`
UniversityBoard bool `json:"universityBoard"`
Submissions bool `json:"submissions"`
Progress json.RawMessage `json:"progress"`
FAQ string `json:"faq"`
}
Competition is one item of GET /users/self/competitions results[].
type CookieEntry ¶
type CookieEntry struct {
Name string `json:"name"`
Value string `json:"value"`
Path string `json:"path,omitempty"`
Domain string `json:"domain,omitempty"`
Expires time.Time `json:"expires,omitempty"`
Secure bool `json:"secure,omitempty"`
HTTP bool `json:"httpOnly,omitempty"`
}
CookieEntry is one persisted cookie.
type CookieSnapshot ¶
type CookieSnapshot struct {
URL string `json:"url"`
Cookies []CookieEntry `json:"cookies"`
Saved time.Time `json:"saved"`
}
CookieSnapshot is used by the file-backed jar to persist cookies to disk.
type DRFError ¶
DRFError carries the Django REST framework field-validation envelope:
{"<field>": ["<msg>", ...], ...}
Locale-aware — strings come back in whatever language the BRAIN edge chose (often zh-CN). Match on field names, never on message strings.
func AsDRFError ¶
AsDRFError unwraps to *DRFError if err carries one.
type DailyBudget ¶
DailyBudget is the in-process daily quota gate. Counters reset at the next BRAIN day boundary (3 AM ET). Set Sims or Submits to 0 to disable the gate for that operation type.
type DataField ¶
type DataField struct {
ID string `json:"id"`
Region string `json:"region"`
Universe string `json:"universe"`
Delay int `json:"delay"`
Type string `json:"type"`
Category NamedRef `json:"category"`
Dataset NamedRef `json:"dataset"`
Subcategory NamedRef `json:"subcategory"`
Description string `json:"description"`
Coverage float64 `json:"coverage"`
DateCoverage float64 `json:"dateCoverage"`
AlphaCount int `json:"alphaCount"`
UserCount int `json:"userCount"`
Themes []NamedRef `json:"themes"`
}
DataField is one item from GET /data-fields results[].
type DataFieldsPage ¶
DataFieldsPage is the (no-next, no-previous) flavor used by /data-fields.
type DataFieldsQuery ¶
type DataFieldsQuery struct {
InstrumentType string // "EQUITY"
Region string // "USA"
Universe string // "TOP3000"
Delay int // 0 or 1
Limit int
Offset int
}
DataFieldsQuery configures GET /data-fields. All four core fields are REQUIRED — BRAIN returns 400 if any is missing.
type Education ¶
type Education struct {
University string `json:"university"`
Major string `json:"major"`
Degree string `json:"degree"`
GradYear int `json:"gradYear"`
}
Education is a sub-object of RegisterInput.
type IsBlock ¶
type IsBlock struct {
PnL json.Number `json:"pnl,omitempty"`
BookSize json.Number `json:"bookSize,omitempty"`
LongCount int `json:"longCount,omitempty"`
ShortCount int `json:"shortCount,omitempty"`
Turnover float64 `json:"turnover,omitempty"`
Returns float64 `json:"returns,omitempty"`
Drawdown float64 `json:"drawdown,omitempty"`
Margin float64 `json:"margin,omitempty"`
Sharpe float64 `json:"sharpe,omitempty"`
Fitness float64 `json:"fitness,omitempty"`
StartDate string `json:"startDate,omitempty"`
SelfCorrelation *float64 `json:"selfCorrelation,omitempty"` // ACTIVE alphas only
ProdCorrelation *float64 `json:"prodCorrelation,omitempty"` // ACTIVE alphas only
Checks []Check `json:"checks,omitempty"`
}
IsBlock is the IS-stage metrics block on an Alpha.
type Leaderboard ¶
type Leaderboard struct {
Alphas int `json:"alphas"`
Country string `json:"country"`
Level string `json:"level"`
Rank int `json:"rank"`
Score json.Number `json:"score"`
University json.RawMessage `json:"university"`
User string `json:"user"`
}
Leaderboard is the user's standing inside a Competition.
Score is intentionally json.Number — the BRAIN edge returns it as an int for active users with non-zero standings (e.g. 45565) but as a float "0.0" for secondary accounts with no competition activity. Captured live 2026-05-18.
type ListAlphasOptions ¶
type ListAlphasOptions struct {
Status string // "ACTIVE" | "UNSUBMITTED" | "DECOMMISSIONED" | ""
Limit int // default 100 per BRAIN
Offset int
Order string // "-dateCreated" etc.
}
ListAlphasOptions configures GET /users/self/alphas.
type NotVerifiedError ¶
type NotVerifiedError struct {
Email string
}
NotVerifiedError is returned when login or a probe shows the account is not yet email-verified. BRAIN exposes this as 403 with body containing "NOT_VERIFIED".
func (*NotVerifiedError) Error ¶
func (e *NotVerifiedError) Error() string
type Observer ¶
type Observer interface {
// ObserveRequest is called exactly once per finished HTTP round-trip,
// AFTER status classification but BEFORE any retry sleep. status==0
// means the call failed at the transport layer (no HTTP response).
ObserveRequest(method, path string, status int, dur time.Duration, err error)
// ObserveRetry is called when the do() loop decides to retry. attempt
// is 0-indexed (the number of retries already attempted).
ObserveRetry(method, path string, status, attempt int, kind RetryKind, sleep time.Duration)
// ObserveLongPoll is called once per long-poll iteration on /submit,
// /simulations, /check, /recordsets/pnl.
ObserveLongPoll(method, path string, iter int, sleep time.Duration)
}
Observer is the pluggable instrumentation hook. Implementations can wire the SDK to Prometheus, OpenTelemetry, or any structured logging system.
All methods MUST be non-blocking (or block only briefly) and goroutine-safe. The SDK calls them synchronously on the request hot path.
Pass an implementation via Options.Observer. The default is a no-op.
type Operator ¶
type Operator struct {
Name string `json:"name"`
Category string `json:"category"`
Scope []string `json:"scope"`
Definition string `json:"definition"`
Description string `json:"description,omitempty"`
Documentation string `json:"documentation,omitempty"`
Level string `json:"level,omitempty"`
}
Operator is one item from GET /operators (bare array).
type Options ¶
type Options struct {
// BaseURL overrides "https://api.worldquantbrain.com".
BaseURL string
// Profile selects the TLS/JA3 fingerprint. Default: ProfileChrome131.
Profile BrowserProfile
// Proxy is an optional HTTP/HTTPS/SOCKS5 proxy URL. Default: direct.
Proxy string
// CookieJarPath, when non-empty, persists cookies to disk after every
// successful request, and reloads them at NewClient time.
CookieJarPath string
// Timeout per HTTP call. Default: 15s.
Timeout time.Duration
// MaxRetries is the number of retry attempts (in addition to the
// initial call) for non-long-poll error classes. Default: 3.
MaxRetries int
// MaxLongPolls bounds /alphas/{id}/submit, /simulations/{id},
// /alphas/{id}/check, /alphas/{id}/recordsets/pnl loops. Default: 60.
MaxLongPolls int
// MaxConcurrentSims is the semaphore size for in-flight POST /simulations.
// Default: 2 for main, 1 for sub — callers must set explicitly based on
// account tier.
MaxConcurrentSims int
// BanThreshold is the consecutive-403 streak that flips a secondary account
// to BannedError. 0 disables ban detection. Default: 3.
BanThreshold int
// DailyBudget enforces in-process quota gates per BRAIN challenge-day.
DailyBudget DailyBudget
// Logger is the slog target. Default: slog.Default().
Logger *slog.Logger
// Observer is the instrumentation hook. Default: no-op. Wire to
// Prometheus / OTel by implementing the Observer interface.
Observer Observer
// CaptchaSolver is used by Register. Default: pkg/captcha/altcha solver
// (wired by SetDefaultAltchaSolver in init).
CaptchaSolver CaptchaSolver
// Email / Password are cached for auto-relogin on 401. Setting these
// makes the Client capable of recovering from session expiry without
// caller intervention.
Email string
Password string
}
Options configures a Client. Zero-value Options yields a usable client against BRAIN production with default Chrome 131 fingerprint and no proxy or persistent cookies.
type Page ¶
type Page[T any] struct { Count int `json:"count"` Next *string `json:"next"` Previous *string `json:"previous"` Results []T `json:"results"` }
Page is a typed wrapper for the Django REST envelope used by /users/self/alphas and /users/self/competitions.
type PersonaInquiryError ¶
type PersonaInquiryError struct {
Inquiry string
}
PersonaInquiryError is returned when POST /authentication produces the 2FA-like persona envelope. Callers who want to drive the persona challenge must capture Inquiry and call the (currently un-exercised) persona path. In steady-state production this branch is dead — kept as a safety net.
func (*PersonaInquiryError) Error ¶
func (e *PersonaInquiryError) Error() string
type PnLPoint ¶
PnLPoint is one [date, value] tuple from PnLSeries.Records.
func (PnLPoint) MarshalJSON ¶
MarshalJSON re-encodes a PnLPoint as the [date, value] tuple BRAIN emits.
func (*PnLPoint) UnmarshalJSON ¶
UnmarshalJSON decodes the heterogeneous-typed [string, number] tuple.
type PnLSeries ¶
type PnLSeries struct {
Schema *RecordSchema `json:"schema"`
Records []PnLPoint `json:"records"`
}
PnLSeries is the body of GET /alphas/{id}/recordsets/pnl.
type RateLimitError ¶
type RateLimitError struct {
Status int
RetryAfter time.Duration
Cooldown bool // true when the server hinted "concurrent" / "previous to finish"
URL string
Body []byte
}
RateLimitError is returned when a 429 (or 503 outside a long-poll context) trips the retry policy and the caller must back off.
func AsRateLimitError ¶
func AsRateLimitError(err error) (*RateLimitError, bool)
AsRateLimitError unwraps to *RateLimitError if err carries one.
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
type RecordSchema ¶
type RecordSchema struct {
Name string `json:"name,omitempty"`
Title string `json:"title,omitempty"`
Properties []SchemaProperty `json:"properties,omitempty"`
}
RecordSchema describes the columnar shape of RecordSetBlock.Records.
type RecordSetBlock ¶
type RecordSetBlock struct {
Schema *RecordSchema `json:"schema,omitempty"`
Records []json.RawMessage `json:"records,omitempty"`
}
RecordSetBlock is the {schema, records} envelope used by /recordsets/pnl, /activities/* and selfCorrelated. records is an array of heterogeneous-typed tuples — keep raw for typed access via Schema.Properties[*].Name.
type RegisterInput ¶
type RegisterInput struct {
Email string `json:"email"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
FullName string `json:"fullName"`
Gender string `json:"gender"`
Telephone string `json:"telephone,omitempty"`
Address Address `json:"address"`
Education Education `json:"education"`
Employment json.RawMessage `json:"employment,omitempty"`
Auxiliary Auxiliary `json:"auxiliary"`
}
RegisterInput is the high-level POST /users payload. The SDK fills in Auxiliary.Captcha automatically via the configured CaptchaSolver.
type SchemaProperty ¶
type SchemaProperty struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Type string `json:"type"`
}
SchemaProperty is one column descriptor.
type Session ¶
type Session struct {
User *UserRef `json:"user,omitempty"`
Token *Token `json:"token,omitempty"`
Permissions []string `json:"permissions,omitempty"`
Inquiry string `json:"inquiry,omitempty"`
}
Session is the body returned by POST /authentication on success. Two shapes can land at 201:
- normal login -> User + Token + Permissions populated
- persona required -> Inquiry populated, others zero
type SessionInfo ¶
type SessionInfo struct {
User UserRef `json:"user"`
Token Token `json:"token"`
Permissions []string `json:"permissions"`
}
SessionInfo is the body of GET /authentication.
type SimSettings ¶
type SimSettings struct {
InstrumentType string `json:"instrumentType"`
Region string `json:"region"`
Universe string `json:"universe"`
Delay int `json:"delay"`
Decay int `json:"decay"`
Neutralization string `json:"neutralization"`
Truncation float64 `json:"truncation"`
Pasteurization string `json:"pasteurization"`
UnitHandling string `json:"unitHandling"`
NanHandling string `json:"nanHandling"`
Language string `json:"language"`
Visualization bool `json:"visualization"`
}
SimSettings captures the simulate-time knobs. Fields match BRAIN's exact names (camelCase) so a SimulationRequest round-trips byte-for-byte through the SDK.
type Simulation ¶
type Simulation struct {
ID string `json:"id,omitempty"`
Type string `json:"type,omitempty"`
Settings json.RawMessage `json:"settings,omitempty"`
Regular json.RawMessage `json:"regular,omitempty"`
Status string `json:"status,omitempty"` // COMPLETE | FAIL | ERROR | "" (still running)
Alpha string `json:"alpha,omitempty"` // populated on COMPLETE
Message string `json:"message,omitempty"` // populated on FAIL/ERROR
Progress *float64 `json:"progress,omitempty"` // [0..1] while running
}
Simulation is the body of GET /simulations/{id}.
type SimulationRequest ¶
type SimulationRequest struct {
Type string `json:"type"` // "REGULAR" | "SUPER" | "COMBO"
Regular string `json:"regular,omitempty"`
Super string `json:"super,omitempty"`
Settings SimSettings `json:"settings"`
Combo json.RawMessage `json:"combo,omitempty"`
}
SimulationRequest is the POST /simulations body.
type Token ¶
type Token struct {
Expiry float64 `json:"expiry"`
}
Token holds session-token TTL info. Expiry is "seconds remaining" — not an absolute timestamp — per BRAIN's GET /authentication response shape.
type User ¶
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Telephone *string `json:"telephone"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
FullName string `json:"fullName"`
Gender string `json:"gender"`
DateCreated string `json:"dateCreated"`
DateVerified string `json:"dateVerified"`
DateApproved string `json:"dateApproved"`
Verified bool `json:"verified"`
Approved bool `json:"approved"`
Address json.RawMessage `json:"address"`
Education json.RawMessage `json:"education"`
Employment json.RawMessage `json:"employment"`
Recruitment json.RawMessage `json:"recruitment"`
Resume json.RawMessage `json:"resume"`
Image json.RawMessage `json:"image"`
Settings json.RawMessage `json:"settings"`
Onboarding json.RawMessage `json:"onboarding"`
GeniusLevel json.RawMessage `json:"geniusLevel"`
}
User is the body of GET /users/self. Twenty-one top-level keys observed 2026-05-06; we keep the common ones strongly typed and fall back to Extra (json.RawMessage) for forward-compat with new fields BRAIN may add.
type UserRef ¶
type UserRef struct {
ID string `json:"id"`
}
UserRef is the minimal user identifier embedded in session bodies.
type Verdict ¶
type Verdict struct {
Status string `json:"status"`
Reason string `json:"reason,omitempty"`
Body *Alpha `json:"body,omitempty"`
Checks []Check `json:"checks,omitempty"`
HTTP int `json:"http,omitempty"`
}
Verdict is the parsed terminal outcome of POST + GET long-poll on /alphas/{id}/submit. Status is one of:
verified — alpha was activated corr_rejected — SELF_CORRELATION FAIL submit_failed — any other non-CORR FAIL pending_corr — long-poll cap exceeded, verdict still computing