综合

Complete Guide to Stock Market Data API Integration: 7 Data Types from Kline to Fundamentals with Tested Python Code

作者: TickDB Research · 发布: 2026/9/15 · 阅读: 7

标签: 官网

When you start building a quant strategy or market data pipeline, the first thing you usually do is pull historical OHLCV data. A few lines of Python, a REST call, daily kline bars flowing into a DataFrame — done. Data layer complete.

Except it isn't. The first time you run a backtest, you notice phantom price gaps on ex-dividend dates — your kline data has no adjustment factors. You try to estimate execution slippage, but you never pulled order book depth, so you hardcode a fixed spread and hope for the best. You want to add a P/E filter to your universe, but you have no fundamentals endpoint wired up, and you're not sure which markets it covers.

Each of those gaps means going back to re-architect the data pipeline — typically 3 to 5 times the effort of the initial build. The root cause is always the same: not knowing, at the start, that market data comes in at least seven distinct types, each served by its own API endpoint with its own field structure and coverage boundaries.

What this guide covers

This guide walks through all 7 types of market data a quant developer's pipeline typically needs, using a single stock — AAPL (Apple Inc., NASDAQ) — and live API calls to show the request parameters, actual JSON responses, and field-by-field explanations for each type.

Here is the full landscape before we dive in:

#Data TypeAPI EndpointKey FieldsTypical Use
1Kline (OHLCV)/v1/market/klineopen, high, low, close, volumeBacktesting, charting, technical analysis
2Real-time Ticker/v1/market/tickerlast_price, volume_24h, high/low, pre/post-marketLive monitoring, signal triggering
3Order Book/v1/market/order-bookbids[], asks[] (price + size)Slippage estimation, liquidity analysis
4Recent Trades/v1/market/recent-tradesprice, quantity, side, trade_sessionExecution analysis, tick-level research
5Capital Flow/v1/market/capital-flowintraday_flow[], distribution by order sizeInstitutional flow tracking
6Market Metrics/v1/market/market-metricsPE_TTM, PB, market_cap, turnover_rateFundamental screening, valuation filters
7Adjustment Factors/v1/market/kline/ex-factorsfactor_a, factor_b, adjust typeAdjusted price calculation for splits/dividends

TickDB provides unified real-time and historical market data for quantitative research, market monitoring, and financial applications. It covers US, Hong Kong, and China A-share markets through a single REST API with consistent authentication and response structures. In this guide, we use its REST API to walk through all 7 data types with AAPL as our test subject.

Every API call below uses the same authentication header:

import requests

BASE_URL = "https://api.tickdb.com"
HEADERS = {"X-API-Key": "your_api_key_here"}

1. Kline (OHLCV Candlestick) Data

What it solves: Kline data is the backbone of any strategy backtest — price history in fixed time intervals. Without it, you have no price series to test against.

Endpoint: GET /v1/market/kline

Request:

params = {
    "symbol": "AAPL.US",
    "interval": "1d",
    "limit": 3
}
resp = requests.get(f"{BASE_URL}/v1/market/kline", headers=HEADERS, params=params)
data = resp.json()

Response (actual API output, retrieved September 15, 2026):

{
  "symbol": "AAPL.US",
  "type": "stock",
  "interval": "1d",
  "klines": [
    {
      "time": 1789012800000,
      "open": "316.67",
      "high": "326.74",
      "low": "316.51",
      "close": "326.57",
      "volume": "70011913",
      "quote_volume": "22610986494"
    },
    {
      "time": 1789099200000,
      "open": "327.45",
      "high": "336.22",
      "low": "326.30",
      "close": "332.27",
      "volume": "50716865",
      "quote_volume": "16888803875"
    },
    {
      "time": 1789358400000,
      "open": "334.79",
      "high": "335.50",
      "low": "331.34",
      "close": "333.08",
      "volume": "39269147",
      "quote_volume": "13101785747"
    }
  ]
}

Key fields:

FieldTypeDescription
timeintUnix timestamp in milliseconds (UTC)
open / high / low / closestringOHLC prices for the interval
volumestringNumber of shares traded
quote_volumestringTotal turnover in quote currency (USD for US stocks)

Supported intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 1d, 1w, 1M — 11 intervals in total. Use GET /v1/market/kline/intervals to retrieve the full list programmatically.

Note: Kline data returns unadjusted (raw) prices by default. If your stock has had splits or dividends, the price series will show gaps at those dates. See Section 7 (Adjustment Factors) for how to handle this.


2. Real-time Ticker Snapshot

What it solves: A ticker snapshot gives you the current state of a symbol in one call — last traded price, today's range, volume, and extended-hours quotes. Use it for live dashboards, alerting, or as a gate check before placing orders.

Endpoint: GET /v1/market/ticker

Request:

params = {"symbols": "AAPL.US"}
resp = requests.get(f"{BASE_URL}/v1/market/ticker", headers=HEADERS, params=params)
data = resp.json()["data"][0]

Response (actual API output, retrieved September 15, 2026):

{
  "symbol": "AAPL.US",
  "name": "Apple Inc.",
  "type": "stock",
  "last_price": "333.08",
  "open": "334.79",
  "prev_close": "332.27",
  "volume_24h": "39269147",
  "quote_volume_24h": "13101785747",
  "high_24h": "335.50",
  "low_24h": "331.34",
  "price_change_24h": "0.81",
  "price_change_percent_24h": "0.24",
  "timestamp": 1789416001000,
  "pre_market_quote": {
    "last_done": "334.34",
    "volume": 593781,
    "high": "335.38",
    "low": "328.77"
  },
  "post_market_quote": {
    "last_done": "332.23",
    "volume": 2532351,
    "high": "333.30",
    "low": "332.08"
  }
}

Key fields:

FieldTypeDescription
last_pricestringMost recent traded price
prev_closestringPrevious session's closing price
volume_24hstringTotal shares traded in the session
quote_volume_24hstringTotal turnover in quote currency
price_change_24hstringAbsolute price change from previous close
price_change_percent_24hstringPercentage change from previous close
pre_market_quoteobjectPre-market session snapshot (US stocks)
post_market_quoteobjectPost-market (after-hours) session snapshot

How ticker differs from kline: Kline gives you historical bars at a fixed interval. Ticker gives you the latest snapshot — one point in time, not a series. If you need to track intraday price movement, use 1-minute kline bars; if you need the current quote for a watchlist or alert, use ticker.


3. Order Book (Market Depth)

What it solves: The order book shows resting bid and ask orders at each price level. Without it, slippage estimation for live trading is guesswork — you're assigning a fixed spread assumption instead of measuring actual available liquidity at each level.

Endpoint: GET /v1/market/order-book

Request:

params = {"symbol": "AAPL.US"}
resp = requests.get(f"{BASE_URL}/v1/market/order-book", headers=HEADERS, params=params)
data = resp.json()["data"]

Response (actual API output, retrieved September 15, 2026 — overnight session):

{
  "symbol": "AAPL.US",
  "type": "stock",
  "timestamp": 1789442431529,
  "bids": [
    ["331.62", "13"]
  ],
  "asks": [
    ["331.65", "7"]
  ]
}

Key fields:

FieldTypeDescription
bidsarrayBuy orders: [price, quantity], best (highest) price first
asksarraySell orders: [price, quantity], best (lowest) price first
timestampintSnapshot timestamp in milliseconds (UTC)

Note: The depth of the order book varies by session and market conditions. The example above was captured during the overnight session, where liquidity is thin and only 1 level is populated on each side. During regular trading hours, you will typically see 5 or more levels. Use the limit parameter to request a specific number of levels.


4. Recent Trades (Trade-by-Trade Data)

What it solves: Recent trades show individual executed transactions — each with a price, quantity, buy/sell direction, and timestamp. This is the data you need for execution analysis, trade-level VWAP calculation, or tick-by-tick research on order flow dynamics.

Endpoint: GET /v1/market/recent-trades

Request:

params = {"symbol": "AAPL.US", "limit": 3}
resp = requests.get(f"{BASE_URL}/v1/market/recent-trades", headers=HEADERS, params=params)
data = resp.json()["data"]

Response (actual API output, retrieved September 15, 2026):

{
  "symbol": "AAPL.US",
  "type": "stock",
  "trades": [
    {
      "id": "1789442410000",
      "price": "331.630",
      "quantity": "1",
      "side": "sell",
      "timestamp": 1789442410000,
      "trade_session": "overnight"
    },
    {
      "id": "1789442410001",
      "price": "331.630",
      "quantity": "8",
      "side": "sell",
      "timestamp": 1789442410000,
      "trade_session": "overnight"
    },
    {
      "id": "1789442430002",
      "price": "331.650",
      "quantity": "8",
      "side": "sell",
      "timestamp": 1789442430000,
      "trade_session": "overnight"
    }
  ]
}

Key fields:

FieldTypeDescription
idstringUnique trade identifier
pricestringExecution price
quantitystringNumber of shares in the trade
sidestringAggressor side: "buy" (buyer lifted the ask) or "sell" (seller hit the bid)
timestampintExecution timestamp in milliseconds (UTC)
trade_sessionstringWhich session the trade occurred in: "normal", "pre_market", "post_market", or "overnight"

Difference from kline data: Kline bars aggregate trades into intervals (1m, 1d, etc.). Recent trades are the raw, unaggregated executions. If you need to analyze how a large order was filled across time, or to build a custom aggregation scheme (e.g., volume bars or dollar bars), you need trade-level data.


5. Capital Flow (Money Flow Analysis)

What it solves: Capital flow data breaks down buying and selling activity by order size — large, medium, and small — and tracks net inflow throughout the trading session. It's used to infer institutional vs. retail participation and to detect divergences between price and flow direction.

Endpoint: GET /v1/market/capital-flow

Request:

params = {"symbol": "AAPL.US"}
resp = requests.get(f"{BASE_URL}/v1/market/capital-flow", headers=HEADERS, params=params)
data = resp.json()["data"]

Response structure (actual API output, retrieved September 15, 2026):

{
  "symbol": "AAPL.US",
  "timestamp": 1789442434,
  "intraday_flow": [
    {"timestamp": 1789392600, "inflow": "152.98"},
    {"timestamp": 1789392660, "inflow": "-34.30"},
    {"timestamp": 1789392720, "inflow": "-691.56"}
  ],
  "distribution": {
    "timestamp": 1789416000,
    "capital_in": {
      "large": "15389.35",
      "medium": "46022.18",
      "small": "77221.09"
    },
    "capital_out": {
      "large": "23335.61",
      "medium": "49599.68",
      "small": "74502.01"
    }
  }
}

(The intraday_flow array contains one entry per minute for the full session; only the first 3 entries are shown above.)

Key fields:

FieldTypeDescription
intraday_flow[].inflowstringCumulative net inflow at that minute (positive = net buying)
distribution.capital_in.largestringTotal buy-side volume from large orders
distribution.capital_in.mediumstringTotal buy-side volume from medium orders
distribution.capital_in.smallstringTotal buy-side volume from small orders
distribution.capital_out.*stringSame breakdown for the sell side

Important: The definition of "large," "medium," and "small" orders — and the methodology for classifying trades into these buckets — varies across data providers. The values shown here reflect TickDB's classification. When comparing capital flow data across sources, verify that the classification methodology matches before drawing conclusions.


6. Market Metrics & Fundamentals

What it solves: Market metrics provide valuation ratios (P/E, P/B), market capitalization, turnover rates, and price performance metrics. You need these for fundamental screening, multi-factor models, and universe filtering — for example, excluding stocks with P/E above a threshold, or ranking by market cap.

There are two levels of fundamental data in the API:

  1. Market Metrics (/v1/market/market-metrics) — valuation ratios, market cap, turnover, price changes. Available for US, Hong Kong, and China A-share stocks.
  2. Fundamentals API (/v1/fundamentals/*) — 25 detailed endpoints covering income statements, balance sheets, cash flows, financial ratios, and more. As of September 15, 2026, these detailed fundamentals cover China A-share stocks on the Shanghai (SH) and Shenzhen (SZ) exchanges — 5,219 individual stocks (SH 2,318 + SZ 2,901). Beijing (BJ) exchange stocks and ETFs are not covered by the fundamentals endpoints.

For this guide, we demonstrate the market metrics endpoint with AAPL.

Endpoint: GET /v1/market/market-metrics

Request:

params = {"symbols": "AAPL.US"}
resp = requests.get(f"{BASE_URL}/v1/market/market-metrics", headers=HEADERS, params=params)
data = resp.json()["data"][0]

Response (actual API output, retrieved September 15, 2026):

{
  "symbol": "AAPL.US",
  "last_done": "333.08",
  "change_val": "0.81",
  "change_rate": "0.0024",
  "volume": "39269147",
  "turnover": "13101785747",
  "ytd_change_rate": "0.2285",
  "turnover_rate": "0.27",
  "total_market_value": "4861029474400",
  "pe_ttm_ratio": "37.7",
  "pb_ratio": "45.21",
  "dividend_ratio_ttm": "0.32",
  "five_day_change_rate": "0.041",
  "ten_day_change_rate": "0.0419",
  "half_year_change_rate": "0.3341"
}

Key fields:

FieldTypeDescription
pe_ttm_ratiostringPrice-to-Earnings ratio (trailing twelve months)
pb_ratiostringPrice-to-Book ratio
total_market_valuestringTotal market capitalization in quote currency
turnover_ratestringDaily turnover rate (volume / float shares)
ytd_change_ratestringYear-to-date price change (decimal; 0.2285 = +22.85%)
dividend_ratio_ttmstringTrailing twelve-month dividend yield
five_day_change_ratestring5-day price change rate
half_year_change_ratestring180-day price change rate

Supplementary: Stock Info. For static reference data — company name, exchange, currency, EPS, BPS, and share count — use GET /v1/market/stock-info:

{
  "symbol": "AAPL.US",
  "name_en": "Apple",
  "exchange": "NASD",
  "currency": "USD",
  "lot_size": 1,
  "total_shares": 14594180000,
  "circulating_shares": 14569121909,
  "eps": "7.67",
  "eps_ttm": "8.83",
  "bps": "7.37",
  "dividend_yield": "1.06"
}

7. Adjustment Factors (Ex-Dividend / Split Adjustments)

What it solves: When a stock pays a dividend or splits, the raw price series shows a discontinuity — a gap that has nothing to do with market movement. If your backtest uses unadjusted prices, every split and every dividend creates a phantom signal. Adjustment factors let you compute adjusted prices that form a continuous series.

Endpoint: GET /v1/market/kline/ex-factors

Request:

params = {
    "symbols": "AAPL.US",
    "adjust": "forward"    # or "backward"
}
resp = requests.get(
    f"{BASE_URL}/v1/market/kline/ex-factors",
    headers=HEADERS, params=params
)

Response structure:

Each record in the response represents one corporate action date and carries two fields:

FieldTypeDescription
factor_afloatMultiplicative adjustment factor
factor_bfloatAdditive adjustment factor
adjuststringAdjustment direction: "forward" or "backward"
timestampintEx-date timestamp

Adjustment formula:

adjusted_price = raw_price × factor_a + factor_b

For China A-share stocks, factor_b is always 0, simplifying the formula to adjusted_price = raw_price × factor_a. For US and Hong Kong stocks, the API supports forward and backward multiplicative adjustments; additive adjustment types are not available for these markets (the API returns HTTP 400 with error code 2001 if requested).

Practical usage: Most backtesting frameworks expect either forward-adjusted or backward-adjusted prices. Forward adjustment scales past prices up to match the current price level; backward adjustment scales the current price down to match the historical series. Choose based on your framework's convention — forward-adjusted is more common for charting, backward-adjusted for backtesting with fixed capital.


Putting It All Together: Data Architecture by Strategy Type

Not every strategy needs all 7 data types. Here's a practical mapping:

Strategy TypeEssential DataOptional but Useful
Trend following (moving averages, breakouts)Kline (daily), Adjustment FactorsTicker (for live signals)
Mean reversion (pairs trading, stat arb)Kline (intraday), Market Metrics (for pair selection)Adjustment Factors
Multi-factor (value, momentum, quality)Market Metrics, Kline (daily), Adjustment FactorsFundamentals API (for A-shares)
Execution / TWAP / VWAPOrder Book, Recent Trades, TickerCapital Flow
Event-driven (earnings, dividends)Adjustment Factors, Kline, Market MetricsCapital Flow, Recent Trades
Sentiment / flow analysisCapital Flow, Ticker, KlineOrder Book

The general rule: start with kline and adjustment factors (every strategy needs a clean price series), add market metrics if you're screening or filtering, and add order book and trades when you move from backtest to live execution.


Market Data Integration Checklist

Before you write the first line of your data pipeline, go through this checklist. For each data type, decide whether your strategy needs it, and note the endpoint and key fields.

#Data TypeMy Strategy Needs It?EndpointKey Fields to ParseStatus
1Kline (OHLCV)☐ Yes / ☐ No/v1/market/klinetime, OHLC, volume☐ Integrated
2Real-time Ticker☐ Yes / ☐ No/v1/market/tickerlast_price, volume_24h, pre/post-market☐ Integrated
3Order Book☐ Yes / ☐ No/v1/market/order-bookbids[], asks[]☐ Integrated
4Recent Trades☐ Yes / ☐ No/v1/market/recent-tradesprice, quantity, side, trade_session☐ Integrated
5Capital Flow☐ Yes / ☐ No/v1/market/capital-flowintraday_flow, distribution☐ Integrated
6Market Metrics☐ Yes / ☐ No/v1/market/market-metricsPE_TTM, PB, market_cap☐ Integrated
7Adjustment Factors☐ Yes / ☐ No/v1/market/kline/ex-factorsfactor_a, factor_b☐ Integrated

Auxiliary endpoints you'll also want to wire up early:

EndpointWhat It Returns
GET /v1/market/trade-daysTrading calendar for a given market
GET /v1/market/trading-sessionsSession schedule (pre-market, regular, post-market, overnight)
GET /v1/market/kline/intervalsSupported kline intervals (currently 11)
GET /v1/market/stock-infoStatic reference data (name, exchange, currency, EPS, BPS)

Conclusion

Market data is not "get kline and you're done." There are at least 7 distinct data types, each solving a different problem in your pipeline — from price history and real-time quotes to order book depth, trade execution records, capital flow analysis, fundamental metrics, and price adjustment factors. Mapping out which ones your strategy actually needs, and understanding their field structures and coverage boundaries, costs an afternoon of reading documentation. Discovering the gaps during a failed backtest or a live trading incident costs weeks.

Every API call in this guide used the same base URL, the same X-API-Key authentication header, and the same JSON response structure. One authentication method, one request pattern, seven data types. That is the practical advantage of a unified market data API — not in any single endpoint, but in the reduced integration complexity across all of them.


All data in this guide was retrieved from TickDB REST API on September 15, 2026. Dynamic values (prices, volumes, market cap, ratios) reflect market conditions at the time of the API call and will differ on subsequent queries. TickDB provides market data for quantitative research, market monitoring, and financial applications across US, Hong Kong, and China A-share markets. For API documentation and access, visit tickdb.com.

通过 TickDB API 获取实时行情数据

一个 API 接入外汇、加密货币、美股、港股、A股、贵金属和全球指数的实时行情。支持 WebSocket 低延迟推送,免费开始使用。

免费领取 API Key查看 API 文档

相关文章