DEV Community

wang vball
wang vball

Posted on

A Stock API Provides Market Data for Apps Within Feed and Usage Limits

A Stock API Provides Market Data for Apps Within Feed and Usage Limits

Summary: A stock API gives an application programmatic access to prices and related financial data, but what can you build with it? Charts, watchlists, research tools, and alerts are common uses; their reliability depends on the feed, timestamps, data definitions, and permitted use. A latest trade, a bid–ask quote, and a daily price bar describe different things, while an open source client library grants no automatic rights to redistribute the underlying data.

What a stock API actually provides

A stock API is an interface through which software requests or receives stock-related data. An application can use it to retrieve recent prices, download historical observations, or subscribe to updates. Some services also expose company fundamentals, corporate actions, or news through separate endpoints.

The interface makes data accessible to code. The feed behind it determines which events are represented, how quickly they arrive, and how much history is available. Two services can both return a price for the same ticker while describing different observations.

An endpoint is a particular operation offered by the service, such as retrieving historical bars. Many APIs deliver a structured response, often JSON, that a program can parse into fields. An SDK is a client library that wraps those operations in convenient functions. Installing an SDK does not change the coverage or permissions of the underlying service.

It also helps to separate market data from trading. Reading a price does not submit an order. A trading application may use a market data API alongside a broker API for account information, order placement, and execution reports. Even when one provider offers both, these are separate capabilities.

Figure 1. A conceptual market data path. Feed coverage and normalization affect what reaches the application; a trade and a quote describe different events.

The data type determines the feature you can build

A trade records a completed transaction. A quote describes a bid and an ask within the coverage of the feed. A price bar summarizes observations over an interval, typically as open, high, low, close, and volume, or OHLCV. These records serve different purposes.

A daily bar is useful for a long-term chart, but it cannot reveal the sequence of price changes inside that day. A last-trade price can support a watchlist, but it is not a promise that a new order will execute at that price. That distinction matters as soon as a display becomes an input to an alert or trading decision.

Application Useful data Important boundary
Watchlist Latest prices and timestamps Show when the observation was recorded and whether it is delayed.
Historical chart OHLCV bars Keep interval, session, and adjustment settings consistent.
Price alert A defined trade or quote stream Handle disconnects and decide which observation triggers the alert.
Portfolio view Prices plus holdings Holdings and cash flows come from a separate source unless explicitly provided.
Research or backtesting Historical observations and reference data Check missing periods, corporate actions, and which securities existed at the time.

For example, TickDB documents a ticker stream with stock symbols, latest prices, and timestamps, including examples for US stocks, Hong Kong stocks, and A-shares. This illustrates the input a watchlist can consume. The application still has to interpret the fields, maintain its own display state, and explain the age of the observation to the reader.

REST and WebSocket describe delivery methods

With a REST-style HTTP API, the client makes a request and receives a response. This fits an on-demand lookup or a historical download. Repeating the request creates polling: the application checks again at an interval it chooses.

A WebSocket connection lets the server send updates over a persistent connection. This can suit a watchlist or alert service that needs frequent changes without repeatedly asking for the same symbols. The client must still manage subscriptions, detect a broken connection, and recover according to the provider's protocol. Reconnecting does not by itself prove that missed events have been recovered.

Neither method establishes the quality of the feed. A WebSocket can carry delayed data, and an HTTP response can contain a recent observation. Similarly, transport latency and market coverage are separate questions. Alpaca's Market Data documentation, for example, distinguishes real-time IEX coverage on its Basic equities plan from broader exchange coverage on another plan. “Real-time” alone does not identify the set of venues represented.

A small example that keeps the timestamp visible

A watchlist should retain the observation time alongside the price. Otherwise, a successful request can make an old observation look current simply because the screen has just refreshed.

The following Python example runs offline using synthetic data and an application-defined schema. It requires only the standard library. It calculates observation age and applies an illustrative 60-second display threshold; it does not measure network latency or decide whether the market should be trading.

from datetime import datetime, timezone
from decimal import Decimal

def format_observation(row, now, max_age_seconds=60):
    observed = datetime.fromisoformat(
        row["observed_at"].replace("Z", "+00:00")
    )
    if observed.utcoffset() is None or now.utcoffset() is None:
        raise ValueError("Timezone-aware timestamps required")
    price = Decimal(str(row["last_price"]))
    if not price.is_finite() or price <= 0:
        raise ValueError("Expected a finite positive stock price")
    age = (now - observed).total_seconds()
    if age < 0:
        state = "check clock or timestamp semantics"
    elif age > max_age_seconds:
        state = "older than display threshold"
    else:
        state = "within display threshold"
    return f"{row['symbol']} {price} | age={age:.0f}s | {state}"

# Synthetic observation and clock; not a live API response.
sample = {
    "symbol": "EXAMPLE.US",
    "last_price": "100.25",
    "observed_at": "2026-10-28T14:30:00Z",
}
now = datetime(2026, 10, 28, 14, 31, 15, tzinfo=timezone.utc)
print(format_observation(sample, now))
Enter fullscreen mode Exit fullscreen mode

The output is EXAMPLE.US 100.25 | age=75s | older than display threshold. The displayed number is still available, but the application no longer presents its recency ambiguously.

For a real integration, map the provider's fields into this small internal schema only after checking their meanings. TickDB's ticker documentation specifies Unix milliseconds for its timestamp field and describes latest prices as strings. Converting milliseconds as if they were seconds would invalidate the age calculation. Its documentation also notes that a 24h field suffix does not imply a rolling 24-hour window in every market; stock statistics usually refer to a trading day or session.

The threshold remains an application policy. An old last trade can be normal after a session ends or when an instrument has not traded recently. Use a market calendar and the feed's timestamp definition before turning an age label into a service-health warning. This example also leaves ingestion validation, symbol mapping, persistence, and recovery to the surrounding application.

Is there an open source stock API available

Yes, open source software exists for accessing stock data. The useful distinction is whether you mean an open source client, a server you can host, or a dataset with permissions that fit your project.

For example, yfinance is an open source Python library for accessing Yahoo Finance data. Its repository states that it is not affiliated with Yahoo, describes its research and educational purpose, and directs users to Yahoo's terms for rights to downloaded data. The repository also notes that the Yahoo Finance API is intended for personal use. The software license and the terms governing the data are separate.

Hosting your own API around downloaded data gives you control over your application interface. It does not create new data rights, improve the original feed's coverage, or guarantee that its upstream service will remain available. A free hosted API is a different option again: it may offer access subject to quotas and conditions without publishing its server implementation.

Figure 2. Open source software, access to a data service, and permission to use the data are separate considerations.

Limitations that matter after the first successful request

Coverage and freshness need separate checks. Confirm which markets, venues, instruments, and sessions the feed represents. A response labeled “latest” may contain the most recent available observation rather than an observation from the present moment. Extended-hours support also needs an explicit check; a regular-session chart should not silently mix in a different session.

Historical data has definitions and revisions. A split changes the relationship between share count and price. Dividend adjustments serve another purpose. Alpaca's historical bars reference exposes separate adjustment options, which illustrates why a chart should record its settings instead of relying on an unnoticed default. For a backtest, also check delisted instruments and information availability dates; today's list of surviving companies is not automatically an appropriate historical universe.

Capacity depends on the workload. Suppose a dashboard polls 120 symbols individually every 10 seconds. That is 720 requests per minute before retries. If an endpoint supports all 120 symbols in one batch, the same schedule requires six requests per minute, although the provider may meter symbols or data volume separately. Streaming reduces repeated polling but introduces connection and subscription limits of its own.

Access and public use are different requirements. An API key proves that a service accepts a credential for a request. It does not, on its own, establish permission for public display, redistribution, or every commercial use. Check the relevant data agreement for the intended application before building a public product around a personal-use prototype.

Start with a feature narrow enough to verify: one chart, a small watchlist, or one alert rule. Record its required data type, acceptable observation age, session coverage, and intended use. Then check both a normal response and an empty, delayed, or interrupted one. A stock API is useful when those conditions match the application—not merely when a request returns a price.

Sources consulted on November 1, 2026: Bavest, Stock API – What You Need to Know; Databento, Stock Market API and schema documentation; Alpaca, About Market Data API and Historical Bars; TickDB Docs, Real-Time Quotes; yfinance repository README. Examples and diagrams are explanatory, not live market measurements.

Top comments (0)