Metadata-Version: 2.4
Name: langchain-aperiodic
Version: 0.1.0
Summary: An integration package connecting Aperiodic and LangChain: point-in-time market data for perpetual futures on Binance, OKX and Hyperliquid
License-Expression: MIT
License-File: LICENSE
Keywords: langchain,langgraph,agents,tools,aperiodic,market-data,perpetual-futures,funding-rate,open-interest,order-flow,market-microstructure,binance,okx,hyperliquid
Author: Aperiodic
Author-email: info@aperiodic.io
Requires-Python: >=3.11,<4.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Dist: aperiodic[pandas] (>=4.5.0,<5.0.0)
Requires-Dist: httpx (>=0.25.0)
Requires-Dist: langchain-core (>=1.0.0,<2.0.0)
Requires-Dist: pandas (>=2.0.0)
Requires-Dist: pydantic (>=2.7.4,<3.0.0)
Project-URL: Changelog, https://github.com/aperiodic-io/langchain-aperiodic/releases
Project-URL: Documentation, https://github.com/aperiodic-io/langchain-aperiodic#readme
Project-URL: Homepage, https://aperiodic.io
Project-URL: Issues, https://github.com/aperiodic-io/langchain-aperiodic/issues
Project-URL: Repository, https://github.com/aperiodic-io/langchain-aperiodic
Description-Content-Type: text/markdown

# langchain-aperiodic

[![PyPI](https://img.shields.io/pypi/v/langchain-aperiodic)](https://pypi.org/project/langchain-aperiodic/)
[![CI](https://github.com/aperiodic-io/langchain-aperiodic/actions/workflows/ci.yml/badge.svg)](https://github.com/aperiodic-io/langchain-aperiodic/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/aperiodic-io/langchain-aperiodic/blob/main/LICENSE)

LangChain tools for [Aperiodic](https://aperiodic.io), point-in-time market data for
perpetual futures on Binance, OKX and Hyperliquid.

Aperiodic covers crypto perpetuals and perpetuals on tokenized stocks (TSLA, NVDA,
AAPL and others), indices (the S&P 500 through Hyperliquid HIP-3 markets) and
commodities (gold, oil), delisted contracts included. Its datasets are OHLCV bars,
funding rate, open interest and other derivatives data, and order flow and liquidity
(L1/L2 order book) metrics. This package wraps the
[`aperiodic`](https://pypi.org/project/aperiodic/) Python SDK.

## Installation

```bash
pip install -U langchain-aperiodic
```

Requires Python 3.11 or later (as do `aperiodic` and `langchain-core` 1.x).

## Authentication

Make an API key at [aperiodic.io/home/api](https://aperiodic.io/home/api) and set it:

```bash
export APERIODIC_API_KEY="your-api-key"
```

or pass `api_key="..."` to a tool or the toolkit. A key saved on the machine by
`aperiodic.login()` is also picked up. A free account key covers a fixed sample of
markets and dates; see [aperiodic.io/pricing](https://aperiodic.io/pricing).

Without a key the tools use Aperiodic's public preview, which serves only a small
fixed sample (listed at [aperiodic.io/catalog#preview](https://aperiodic.io/catalog#preview));
other requests come back as an error message the model can read.

## Tools

| Tool name | Class | Wraps | What it returns |
| --- | --- | --- | --- |
| `aperiodic_symbol_search` | `AperiodicSymbolSearch` | `aperiodic.get_symbols` | The symbol ids of an asset's perpetuals on each venue, with the first and last day of data |
| `aperiodic_ohlcv` | `AperiodicOHLCV` | `aperiodic.get_ohlcv` | OHLCV bars: the range as one bar (open, high, low, close, change, volume) and the latest bars |
| `aperiodic_derivatives` | `AperiodicDerivatives` | `aperiodic.get_derivative_metrics` | `funding`, `open_interest`, `basis` or `derivative_price` (last, mark and index prices) |
| `aperiodic_metrics` | `AperiodicMetrics` | `aperiodic.get_metrics` | Order flow, trade size, impact, slippage, VWAP/TWAP, range, returns, ticks, runs, and L1/L2 order book price, imbalance and liquidity |

`AperiodicToolkit().get_tools()` returns all four.

Symbols are [Atlas](https://github.com/aperiodic-io/atlas) ids:
`perpetual-BTC-USDT:USDT` on `binance-futures` and `okx-perps`,
`perpetual-BTC-USDC:USDC` on `hyperliquid-perps`, and `perpetual-XYZ:TSLA-USDC:USDC`
for a Hyperliquid HIP-3 market (the part before the colon names the market's dex).
The tool descriptions tell the model this, and to call `aperiodic_symbol_search` when
it is unsure.

The data tools take `exchange`, `symbol`, `start_date` and `end_date` (UTC days,
inclusive), `interval` (`1m` to `1d`, default `1h`; `15s` and `30s` are not on every
plan), `timestamp` (`exchange` for venue times, `true` for when the data reached
Aperiodic) and `last_n` (rows to include, at most 50). `aperiodic_derivatives` and
`aperiodic_metrics` also take `metric` and an optional list of `columns`.

## Quickstart: an agent

```python
from langchain.agents import create_agent

from langchain_aperiodic import AperiodicToolkit

tools = AperiodicToolkit().get_tools()

# Any chat model that supports tool calling, as "provider:model"
# (pip install "langchain[anthropic]", "langchain[openai]", ...).
agent = create_agent(model="anthropic:claude-sonnet-4-6", tools=tools)

result = agent.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "Which venues list a TSLA perpetual, and how did the "
                "Hyperliquid one trade in October 2026?",
            }
        ]
    }
)
print(result["messages"][-1].content)
```

## Without an API key

The public preview includes the Binance BTC-USDT perpetual at 5-minute bars for
May 2025, so this runs with no key:

```python
from langchain_aperiodic import AperiodicOHLCV, AperiodicSymbolSearch

ohlcv = AperiodicOHLCV()
print(
    ohlcv.invoke(
        {
            "exchange": "binance-futures",
            "symbol": "perpetual-BTC-USDT:USDT",
            "interval": "5m",
            "start_date": "2025-05-01",
            "end_date": "2025-05-31",
            "last_n": 2,
        }
    )
)

# Symbol search works without a key too: it reads the public coverage listing.
print(AperiodicSymbolSearch().invoke({"query": "NVDA"}))
```

The OHLCV call returns (formatted here; the tool returns compact JSON):

```json
{
  "exchange": "binance-futures",
  "symbol": "perpetual-BTC-USDT:USDT",
  "dataset": "ohlcv",
  "interval": "5m",
  "timestamp": "exchange",
  "start_date": "2025-05-01",
  "end_date": "2025-05-31",
  "access": "public preview (no API key)",
  "rows": 8928,
  "first_time": "2025-05-01 00:00",
  "last_time": "2025-05-31 23:55",
  "time_zone": "UTC, start of each interval",
  "period": {
    "open": 94125.2,
    "high": 111959.5,
    "low": 93327.0,
    "close": 104544.7,
    "change_pct": 11.06983,
    "volume": 5650406.0,
    "volume_notional": 587505900000.0
  },
  "last_rows": {
    "columns": ["time", "open", "high", "low", "close", "volume", "volume_notional"],
    "rows": [
      ["2025-05-31 23:50", 104612.1, 104615.0, 104558.4, 104558.5, 85.636, 8956574.0],
      ["2025-05-31 23:55", 104558.4, 104562.8, 104536.3, 104544.7, 74.448, 7783346.0]
    ]
  },
  "rows_note": "Showing the last 2 of 8928 rows."
}
```

## Output size

Each tool answers with a compact JSON summary sized for a model's context, never the
whole series: the request, the row count, the first and last interval, per-column
first/last/min/max/mean (for OHLCV, the range as one bar) and the last `last_n` rows
(default 10, at most 50). Metric datasets have up to 36 columns; without `columns`
the first 8 are summarized and the result lists the rest. Requests over `max_bars`
intervals (default 250,000, about six months of 1-minute bars) are refused before
anything is downloaded.

## The full DataFrame

To keep the model's view small but work with every row in your code, construct a
tool with `response_format="content_and_artifact"`. Invoked with a tool call (as an
agent does), it returns a `ToolMessage` whose `content` is the summary and whose
`artifact` is the full pandas DataFrame:

```python
from langchain_aperiodic import AperiodicMetrics

tool = AperiodicMetrics(response_format="content_and_artifact")
message = tool.invoke(
    {
        "name": tool.name,
        "id": "1",
        "type": "tool_call",
        "args": {
            "metric": "l1_liquidity",
            "exchange": "binance-futures",
            "symbol": "perpetual-BTC-USDT:USDT",
            "interval": "5m",
            "start_date": "2025-05-01",
            "end_date": "2025-05-31",
        },
    }
)
frame = message.artifact  # pandas DataFrame, 8928 rows
```

Or call the SDK directly:

```python
from datetime import date

import aperiodic

frame = aperiodic.get_metrics(
    metric="l1_liquidity",
    exchange="binance-futures",
    symbol="perpetual-BTC-USDT:USDT",
    interval="5m",
    timestamp="exchange",
    start_date=date(2025, 5, 1),
    end_date=date(2025, 5, 31),
    output="pandas",
    preview=True,  # drop this when APERIODIC_API_KEY is set
)
```

## Configuration

| Argument | On | Default | Meaning |
| --- | --- | --- | --- |
| `api_key` | toolkit, every tool | `APERIODIC_API_KEY` | The API key, kept as a `SecretStr` and never logged |
| `preview` | toolkit, every tool | `None` | `None`: use a key when one is found, else the public preview. `True`: always the preview. `False`: require a key |
| `max_bars` | toolkit, data tools | `250_000` | Largest request, in intervals, a data tool accepts |
| `cache_seconds` | `AperiodicSymbolSearch` | `3600` | How long symbol lists are reused |
| `handle_tool_error` | every tool | `True` | API refusals (bad symbol, plan or preview limits, rate limits) are returned as the tool's output, so the agent can correct its call. `False` raises `ToolException` |
| `response_format` | data tools | `"content"` | `"content_and_artifact"` adds the full DataFrame as `ToolMessage.artifact` |

Invalid arguments (an unknown exchange, `end_date` before `start_date`) are also
returned as text rather than raised.

## Other ways to use Aperiodic from an agent

Aperiodic runs a remote MCP server at `https://aperiodic.io/mcp`, which LangChain
agents can use through
[`langchain-mcp-adapters`](https://github.com/langchain-ai/langchain-mcp-adapters).

## Development

```bash
uv sync                    # dev dependencies: test, lint and typing groups
make test                  # unit tests, network disabled
make integration_tests     # live API, public preview; no key needed
make lint                  # ruff, ruff format --diff, mypy
```

Integration tests marked `requires_key` also run when `APERIODIC_API_KEY` is set.
Skip all network tests with `uv run pytest -m "not integration"`.

## License

MIT. See [LICENSE](https://github.com/aperiodic-io/langchain-aperiodic/blob/main/LICENSE).

