flashalphahistorical

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 4, 2026 License: MIT Imports: 10 Imported by: 0

README

flashalpha-historical-go

Official Go client for the FlashAlpha Historical API — point-in-time replay of every live analytics endpoint. Ask what GEX, gamma flip, VRP, narrative, max pain, or the full stock summary looked like at any minute back to 2018-04-16, in the same response shape as the live API.

go get github.com/FlashAlpha-lab/flashalpha-historical-go

Go 1.21+. Same X-Api-Key you use for api.flashalpha.com — Alpha plan or higher on every endpoint.

Quickstart

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    fh "github.com/FlashAlpha-lab/flashalpha-historical-go"
)

func main() {
    c := fh.NewClient(os.Getenv("FLASHALPHA_API_KEY"))

    snap, err := c.ExposureSummary(context.Background(), "SPY", "2020-03-16T15:30:00")
    if err != nil { log.Fatal(err) }

    fmt.Printf("regime: %v, gamma_flip: %v\n", snap["regime"], snap["gamma_flip"])
}

Backtesting

ctx := context.Background()
c := fh.NewClient(os.Getenv("FLASHALPHA_API_KEY"))

bt := fh.NewBacktester(c)
bt.Endpoint = fh.EndpointStockSummary
bt.Symbol = "SPY"

start, _ := time.Parse(fh.AtFormatDate, "2024-01-02")
end, _ := time.Parse(fh.AtFormatDate, "2024-03-29")

results, err := bt.Run(ctx, fh.IterDays(start, end), func(at string, snap map[string]interface{}) interface{} {
    vol, _ := snap["volatility"].(map[string]interface{})
    return map[string]interface{}{ "vrp": vol["vrp"] }
})
Minute-level
d, _ := time.Parse(fh.AtFormatDate, "2025-01-15")
steps, _ := fh.Replay(ctx, c, fh.EndpointExposureSummary, "SPY",
    fh.IterMinutes(d, d, 15), nil)
for _, s := range steps {
    fmt.Println(s.At, s.Response["regime"], s.Response["underlying_price"])
}

API surface

Method Endpoint
Tickers(ctx, symbol) /v1/tickers
StockQuote(ctx, t, at) /v1/stockquote/{t}
OptionQuote(ctx, t, at, ...Option) /v1/optionquote/{t}
Surface(ctx, s, at) /v1/surface/{s}
Gex(ctx, s, at, ...Option) /v1/exposure/gex/{s}
Dex(ctx, s, at, ...Option) /v1/exposure/dex/{s}
Vex(ctx, s, at, ...Option) /v1/exposure/vex/{s}
Chex(ctx, s, at, ...Option) /v1/exposure/chex/{s}
ExposureSummary(ctx, s, at) /v1/exposure/summary/{s}
ExposureLevels(ctx, s, at) /v1/exposure/levels/{s}
Narrative(ctx, s, at) /v1/exposure/narrative/{s}
ZeroDte(ctx, s, at, ...Option) /v1/exposure/zero-dte/{s}
MaxPain(ctx, s, at, ...Option) /v1/maxpain/{s}
StockSummary(ctx, s, at) /v1/stock/{s}/summary
Volatility(ctx, s, at) /v1/volatility/{s}
AdvVolatility(ctx, s, at) /v1/adv_volatility/{s}
Vrp(ctx, s, at) /v1/vrp/{s}

Filter helpers: WithExpiration("2024-08-09"), WithMinOI(100), WithExpiry("2024-08-09"), WithStrike(520), WithType("C"), WithStrikeRange(0.05).

Errors (use errors.As)

Type Status
*APIError base — wraps everything
*AuthenticationError 401
*TierRestrictedError 403 — needs Alpha plan
*InvalidAtError 400 invalid_at
*NoDataError 404 no_data
*SymbolNotFoundError 404 symbol_not_found
*NoCoverageError 404 no_coverage
*InsufficientDataError 404 insufficient_data
*RateLimitError 429
*ServerError 5xx

License

MIT

Documentation

Overview

Package flashalphahistorical provides a Go client for the FlashAlpha Historical API.

Point-in-time replay of every live FlashAlpha analytics endpoint. Every analytics method takes a required `at` value (string or time.Time) and returns the same response shape as the live API at that moment in history.

Base URL: https://historical.flashalpha.com

Index

Constants

View Source
const AtFormatDate = "2006-01-02"

AtFormatDate is the canonical date-resolution layout (defaults to 16:00 ET on the API).

View Source
const AtFormatMinute = "2006-01-02T15:04:05"

AtFormatMinute is the canonical minute-resolution layout used by the API.

View Source
const DefaultBaseURL = "https://historical.flashalpha.com"

DefaultBaseURL is the production Historical API base URL.

Variables

This section is empty.

Functions

func EndpointExposureSummary

func EndpointExposureSummary(ctx context.Context, c *Client, symbol, at string) (map[string]interface{}, error)

EndpointExposureSummary calls (*Client).ExposureSummary.

func EndpointStockSummary

func EndpointStockSummary(ctx context.Context, c *Client, symbol, at string) (map[string]interface{}, error)

EndpointStockSummary calls (*Client).StockSummary.

func EndpointVrp

func EndpointVrp(ctx context.Context, c *Client, symbol, at string) (map[string]interface{}, error)

EndpointVrp calls (*Client).Vrp.

func FormatAt

func FormatAt(t time.Time) string

FormatAt formats a time.Time as the ET wall-clock string the API expects. The clock is taken as-is — callers should construct ETs in the ET frame.

func IsTradingDay

func IsTradingDay(t time.Time) bool

IsTradingDay reports whether t falls on a NYSE trading day (weekday and not a known full-close holiday). Time-of-day is ignored.

func IterDays

func IterDays(start, end time.Time) []time.Time

IterDays returns one time.Time per trading day in [start, end] inclusive, stamped at 16:00 (the API's session close). Both bounds are interpreted as dates — time-of-day on the inputs is ignored.

func IterMinutes

func IterMinutes(start, end time.Time, stepMinutes int) []time.Time

IterMinutes returns ET wall-clock minute timestamps inside RTH for every trading day in [start, end]. Default cadence is 1 minute (390 stamps/day). Pass stepMinutes to coarsen the cadence.

func ReplayChan

func ReplayChan(
	ctx context.Context,
	client *Client,
	endpoint AtEndpoint,
	symbol string,
	timestamps []time.Time,
	opts *ReplayOptions,
) (<-chan ReplayStep, <-chan error)

ReplayChan is a channel-yielding variant of Replay — useful for very long loops where you want to start consuming snapshots before the run finishes. The returned channel is closed when the run completes; any error is sent on errCh exactly once before close.

func SortByAt

func SortByAt(steps []BacktestStep)

SortByAt sorts a slice of BacktestStep by At (lexicographic = chronological for ISO timestamps).

Types

type APIError

type APIError struct {
	StatusCode int
	Code       string // upstream "error" field, e.g. "no_data", "invalid_at"
	Message    string
	Response   map[string]interface{}
}

APIError is the base error type returned by the FlashAlpha Historical client. It carries the HTTP status code, a human-readable message, the upstream error code (e.g. "no_data", "invalid_at"), and the raw response body (if any) parsed as a map.

func (*APIError) Error

func (e *APIError) Error() string

type AtEndpoint

type AtEndpoint func(ctx context.Context, c *Client, symbol, at string) (map[string]interface{}, error)

AtEndpoint is the function signature for any client method that takes a symbol + ET wall-clock `at` string. Used by Replay and Backtester.

type AuthenticationError

type AuthenticationError struct{ *APIError }

AuthenticationError — HTTP 401.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

type BacktestStep

type BacktestStep struct {
	At       string
	Snapshot map[string]interface{}
	Output   interface{}
}

BacktestStep is one snapshot + the strategy output for that step.

type Backtester

type Backtester struct {
	Client      *Client
	Endpoint    AtEndpoint
	Symbol      string
	SkipMissing bool
}

Backtester is a minimal orchestrator — pulls a snapshot per step, feeds it to the strategy, collects the output. No fill simulation, no portfolio accounting.

func NewBacktester

func NewBacktester(client *Client) *Backtester

NewBacktester creates a Backtester with sensible defaults (StockSummary, SPY).

func (*Backtester) Run

func (b *Backtester) Run(ctx context.Context, timestamps []time.Time, strategy Strategy) ([]BacktestStep, error)

Run walks the timestamps, calling the endpoint and the strategy for each.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a thread-safe HTTP client for the FlashAlpha Historical API.

func NewClient

func NewClient(apiKey string) *Client

NewClient creates a Client using the default base URL.

func NewClientWithURL

func NewClientWithURL(apiKey, baseURL string) *Client

NewClientWithURL creates a Client with a custom base URL.

func (*Client) AdvVolatility

func (c *Client) AdvVolatility(ctx context.Context, symbol, at string) (map[string]interface{}, error)

AdvVolatility returns SVI parameters, variance surface, and arbitrage flags.

func (*Client) Chex

func (c *Client) Chex(ctx context.Context, symbol, at string, opts ...Option) (map[string]interface{}, error)

Chex returns charm exposure by strike.

func (*Client) Dex

func (c *Client) Dex(ctx context.Context, symbol, at string, opts ...Option) (map[string]interface{}, error)

Dex returns delta exposure by strike.

func (*Client) ExposureLevels

func (c *Client) ExposureLevels(ctx context.Context, symbol, at string) (map[string]interface{}, error)

ExposureLevels returns key technical levels (gamma flip, walls, magnet).

func (*Client) ExposureSummary

func (c *Client) ExposureSummary(ctx context.Context, symbol, at string) (map[string]interface{}, error)

ExposureSummary returns the full composite dashboard.

func (*Client) Gex

func (c *Client) Gex(ctx context.Context, symbol, at string, opts ...Option) (map[string]interface{}, error)

Gex returns gamma exposure by strike. Use WithExpiration / WithMinOI for filters.

func (*Client) MaxPain

func (c *Client) MaxPain(ctx context.Context, symbol, at string, opts ...Option) (map[string]interface{}, error)

MaxPain returns strike-by-strike pain curve, OI breakdown, and dealer alignment.

func (*Client) Narrative

func (c *Client) Narrative(ctx context.Context, symbol, at string) (map[string]interface{}, error)

Narrative returns verbal analysis + prior-day GEX comparison + VIX context.

func (*Client) OptionQuote

func (c *Client) OptionQuote(ctx context.Context, ticker, at string, opts ...Option) (map[string]interface{}, error)

OptionQuote returns option quote(s) + greeks + OI at the requested minute. Pass WithExpiry / WithStrike / WithType for filters; with all three the response is a single object instead of an array.

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(h *http.Client)

SetHTTPClient swaps in a custom *http.Client (timeout, transport, etc.).

func (*Client) StockQuote

func (c *Client) StockQuote(ctx context.Context, ticker, at string) (map[string]interface{}, error)

StockQuote returns stock bid/ask/mid/last at the requested minute.

func (*Client) StockSummary

func (c *Client) StockSummary(ctx context.Context, symbol, at string) (map[string]interface{}, error)

StockSummary returns the full composite snapshot.

func (*Client) Surface

func (c *Client) Surface(ctx context.Context, symbol, at string) (map[string]interface{}, error)

Surface returns the 50×50 IV surface grid. May raise InsufficientDataError for sparse historical days.

func (*Client) Tickers

func (c *Client) Tickers(ctx context.Context, symbol string) (map[string]interface{}, error)

Tickers lists every symbol with historical coverage. Pass a non-empty symbol to get a single coverage object (returns NoCoverageError if missing).

func (*Client) Vex

func (c *Client) Vex(ctx context.Context, symbol, at string, opts ...Option) (map[string]interface{}, error)

Vex returns vanna exposure by strike.

func (*Client) Volatility

func (c *Client) Volatility(ctx context.Context, symbol, at string) (map[string]interface{}, error)

Volatility returns the realized vol ladder + IV-RV spreads + skew + term.

func (*Client) Vrp

func (c *Client) Vrp(ctx context.Context, symbol, at string) (map[string]interface{}, error)

Vrp returns the variance-risk-premium dashboard with date-bounded percentiles.

func (*Client) ZeroDte

func (c *Client) ZeroDte(ctx context.Context, symbol, at string, opts ...Option) (map[string]interface{}, error)

ZeroDte returns 0DTE-specific analytics.

type InsufficientDataError

type InsufficientDataError struct{ *APIError }

InsufficientDataError — HTTP 404 with error="insufficient_data". The surface grid can't be built (too few OTM+liquid contracts).

func (*InsufficientDataError) Error

func (e *InsufficientDataError) Error() string

type InvalidAtError

type InvalidAtError struct{ *APIError }

InvalidAtError — HTTP 400 with error="invalid_at". The `at` parameter is missing or has an invalid format.

func (*InvalidAtError) Error

func (e *InvalidAtError) Error() string

type NoCoverageError

type NoCoverageError struct{ *APIError }

NoCoverageError — HTTP 404 with error="no_coverage". The symbol is not in the historical dataset.

func (*NoCoverageError) Error

func (e *NoCoverageError) Error() string

type NoDataError

type NoDataError struct{ *APIError }

NoDataError — HTTP 404 with error="no_data". The (symbol, at) tuple has no data — outside the coverage window or inside a known gap.

func (*NoDataError) Error

func (e *NoDataError) Error() string

type Option

type Option func(url.Values)

Option configures a method call (filters like `expiration`, `min_oi`, etc.).

func WithExpiration

func WithExpiration(s string) Option

WithExpiration adds an `expiration=YYYY-MM-DD` filter.

func WithExpiry

func WithExpiry(s string) Option

WithExpiry adds an `expiry=YYYY-MM-DD` filter (option_quote).

func WithMinOI

func WithMinOI(n int) Option

WithMinOI adds a `min_oi=N` filter.

func WithStrike

func WithStrike(x float64) Option

WithStrike adds a `strike=X` filter (option_quote).

func WithStrikeRange

func WithStrikeRange(x float64) Option

WithStrikeRange adds a `strike_range=X` filter (zero-DTE).

func WithType

func WithType(t string) Option

WithType adds a `type=C|Call|P|Put` filter (option_quote).

type RateLimitError

type RateLimitError struct {
	*APIError
	RetryAfter int
}

RateLimitError — HTTP 429. Daily quota is shared with the live API.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type ReplayOptions

type ReplayOptions struct {
	// SkipMissing, when true (default), silently skips 404-class data gaps
	// (no_data, symbol_not_found, insufficient_data). Other errors abort.
	SkipMissing bool
	// OnError is invoked when SkipMissing swallows an error. Optional.
	OnError func(at time.Time, err error)
}

ReplayOptions configures a Replay call.

type ReplayStep

type ReplayStep struct {
	At       string
	Response map[string]interface{}
}

ReplayStep is one yielded step of a replay run.

func Replay

func Replay(
	ctx context.Context,
	client *Client,
	endpoint AtEndpoint,
	symbol string,
	timestamps []time.Time,
	opts *ReplayOptions,
) ([]ReplayStep, error)

Replay walks an endpoint over a sequence of timestamps, returning one step per successful call. By default skips data-gap days silently. The slice is returned in encounter order; for streaming use ReplayChan.

type ServerError

type ServerError struct{ *APIError }

ServerError — HTTP 5xx.

func (*ServerError) Error

func (e *ServerError) Error() string

type Strategy

type Strategy func(at string, snap map[string]interface{}) interface{}

Strategy is the user-supplied callback for each backtest step.

type SymbolNotFoundError

type SymbolNotFoundError struct{ *APIError }

SymbolNotFoundError — HTTP 404 with error="symbol_not_found". The symbol has no historical data at the requested `at`.

func (*SymbolNotFoundError) Error

func (e *SymbolNotFoundError) Error() string

type TierRestrictedError

type TierRestrictedError struct {
	*APIError
	CurrentPlan  string
	RequiredPlan string
}

TierRestrictedError — HTTP 403. Every Historical endpoint requires Alpha+.

func (*TierRestrictedError) Error

func (e *TierRestrictedError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL