Metadata-Version: 2.4
Name: pyxoms
Version: 0.1.3
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Rust
Classifier: Typing :: Typed
License-File: LICENSE-MIT
License-File: LICENSE-APACHE
Summary: Unofficial Rust-powered Python market data client compatible with Primary API / xOMS.
Keywords: primary,xoms,rofex,byma,market-data,websocket,rust
Author: Enzo Drovandi
License-Expression: MIT OR Apache-2.0
Requires-Python: >=3.12
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/enzodrovandi/xoms-rs/blob/main/CHANGELOG.md
Project-URL: Homepage, https://github.com/enzodrovandi/xoms-rs
Project-URL: Issues, https://github.com/enzodrovandi/xoms-rs/issues
Project-URL: Repository, https://github.com/enzodrovandi/xoms-rs

# xoms-rs

An unofficial, high-reliability market data client compatible with Primary API / xOMS endpoints, built with a pure Rust core (`xoms-core`) and ABI3 Python bindings (`pyxoms`).

> **Important — Legal & Non-Affiliation Notice**: `xoms-rs` and `pyxoms` are independent open-source software projects with **no affiliation, endorsement, or sponsorship** from Primary S.A., A3 Mercados (Matba Rofex), or BYMA.
>
> - **Market Data Only (`0.1.x`)**: Order routing is intentionally omitted in the MVP.
> - **Bring Your Own Credentials**: Users are solely responsible for complying with their broker/ALyC terms, exchange market data licensing, and Primary homologation requirements.
> - **Zero Real Market Data**: This repository strictly forbids committing or pasting real exchange quotes, catalogs, tokens, or account numbers.

## Installation

```bash
pip install pyxoms
# or with uv
uv add pyxoms
```

## Key Features

- **Memory-safe Rust core + pure `rustls`**: `#![forbid(unsafe_code)]` in `xoms-core`, HTTPS-only REST (redirects disabled), `wss://`-only WebSockets, and `openssl-sys` banned via `cargo-deny`.
- **GIL-releasing Python ABI3 (`>=3.12`)**: Background Tokio WebSocket actor, single-wheel ABI3 compatibility across Python 3.12–3.14, and frozen Python objects.
- **Financial precision**: Exact `rust_decimal::Decimal` / `decimal.Decimal` for prices, sizes, and volumes (never `f64`), plus UTC timestamps/dates.
- **Market structure correctness**: Preserves separate BYMA settlements (`CI`, `24hs`, `48hs`) in `BymaSettlementQuotes`, supports `BymaOther` suffixes (`72hs`, `T0`, `T1`, `T2`, `CN`, `PL`), models `PESOS` / `DOLAR` / `CABLE` caucion term curves (`1..=365` days), and enforces strict outbound `smd` key ordering (`type` first, `symbol` before `marketId`).
- **Resilient Sans-I/O WebSocket engine**: Zero-`f64` exponential backoff+jitter, 50-minute monotonic `/auth/getToken` TTL refresh, heartbeat/idle checks, stateful field-merging `Conflator`, and anti-batch-poisoning symbol pruning.

## Quick Usage (Python `asyncio`)

```python
import asyncio
from pyxoms import InstrumentCatalog, MarketDataClient, XomsConfig


async def main() -> None:
    # Reads XOMS_ENV (REMARKET | LIVE | LIVE:<BROKER>), XOMS_API_URL, XOMS_WS_URL, XOMS_USER, XOMS_PASSWORD
    cfg = XomsConfig.from_env()
    client = MarketDataClient(cfg)

    # Fetch and cache the catalog losslessly without rebuilding dicts in Python
    catalog = await client.fetch_catalog()
    cached_json = catalog.to_json()
    reloaded = InstrumentCatalog.parse_json(cached_json)
    print(f"Loaded {len(reloaded)} instruments")

    # Conflated WebSocket stream (example synthetic symbols)
    async with client.stream(["MERV - XMEV - SYNA - 24hs", "MERV - XMEV - PESOS - 1D"]) as stream:
        dirty = await stream.wait_dirty(timeout_ms=2_000)
        for quote in dirty:
            bid = quote.best_bid.price if quote.best_bid else None
            print(quote.instrument.symbol, bid)

        byma = stream.byma_settlements("SYNA")
        pesos_curve = stream.caucion_curve("PESOS")
        print(byma.t24h, pesos_curve.shortest())


asyncio.run(main())
```

## Quick Path

Prerequisites: Rust stable (`rustfmt`, `clippy`), `cargo-deny`, and `uv` (Python >= 3.12).

```bash
# 1. Verify the Rust workspace
cargo test --workspace
cargo clippy --workspace --all-targets -- -D warnings
cargo deny check

# 2. Build the local Python extension (with offline testing feature) and run Python checks
uv sync --group dev --no-install-project
uv run --no-sync maturin develop --features testing
uv run --no-sync ruff check . && uv run --no-sync ruff format --check .
uv run --no-sync mypy
uv run --no-sync pytest -q
uv run --no-sync python examples/adapter_pattern.py

# 3. Run offline synthetic benchmarks
cargo bench -p xoms-core --bench market_data_bench -- --warm-up-time 0.2 --measurement-time 0.5
uv run --no-sync python benchmarks/bench_pyxoms.py
uv run --no-sync python benchmarks/compare_pure_python.py

# 4. Mirror CI locally across Rust + Python 3.12 & 3.14 (committed HEAD)
./scripts/ci-local.sh

# 5. Optional manual reMarkets smoke check (outside CI; requires local .env with XOMS_ENV=REMARKET)
cargo test -p xoms-core --test remarkets_smoke -- --ignored --nocapture
uv run python examples/remarkets_smoke.py
```

### Building a Wheel

```bash
uv sync --group dev
uv run maturin build --release --out dist
uv pip install dist/pyxoms-*.whl
```

## Synthetic Benchmark Snapshot

Measured offline via `uv run python benchmarks/compare_pure_python.py` on Linux x86_64 (CPython 3.14, `--release` ABI3 wheel) against an equivalent pure-Python baseline (`stdlib json` + `Decimal`):

| Workload (100% synthetic) | Pure Python (`json` + `Decimal`) | `pyxoms` (Rust ABI3) | Improvement |
|---|---:|---:|---:|
| Catalog parse (1,600 instruments ×10) | `7.20 ms` median | **`2.72 ms`** median | **`2.6x` faster** |
| Batch parse + conflate (20k msgs) | `114,991 msg/s` | **`489,031 msg/s`** | **`4.3x` throughput** |
| Async burst & event-loop jitter (10k frames) | `112,874 msg/s` (`p99` `196.3 µs`) | **`372,305 msg/s`** (`p99` `2.1 µs`) | **`3.3x` (`max_stall` `0.21 ms` → `0.04 ms`)** |
| Python heap peak (`tracemalloc`, 10k frames) | `79.0 KiB` | **`24.7 KiB`** | **`3.2x` smaller** |

## Architecture

| Component | Role | Stack |
|---|---|---|
| `crates/xoms-core` | Pure Rust domain types, config guards, protocol codecs, and transport traits | Rust (`rustls`, `#![forbid(unsafe_code)]`) |
| `crates/pyxoms` | Thin PyO3 ABI3 (`>=3.12`) FFI layer releasing the GIL | Rust (`pyo3`) + `maturin` |
| `python/pyxoms` | Typed Python package with PEP 561 `.pyi` stubs | Python >= 3.12 |

See [ADR 0001](https://github.com/enzodrovandi/xoms-rs/blob/main/docs/adr/0001-mvp-scope-and-stack.md) for the rationale behind the workspace split, TLS backend, and financial precision choices.

### Environment Profiles & Stream Scope

- **Fail-closed `Environment` profiles**: `XomsConfig` / `XOMS_ENV` accepts only `"REMARKET"`, `"LIVE"`, or `"LIVE:<BROKER>"` (e.g. `"LIVE:ECO"`). Unprefixed broker names (such as `"ECO"`) are rejected so mistyped configs never route silently to live endpoints.
- **Conflated stream (`0.1.x`)**: `Conflator` and `MarketDataStream` conflate deltas per instrument in Rust outside the Python GIL for low jitter and heap pressure; lossless tick-by-tick streaming (`MarketDataMessage`) is planned for `v0.2.0`.

## Roadmap

- **Stage 0 (Done)**: OSS governance, dual license, `cargo-deny`, CI parity (`scripts/ci-local.sh`), workspace skeleton, and AI integration layer.
- **Stage 1 (Done)**: Domain & protocol (`config` environment guards, `SecretString`, `Clock`, `BymaSettlementQuotes`, strict `smd` field ordering, dual `Md` parser with `rust_decimal` and `jiff::Timestamp`, and `status: ERROR` missing-product parser).
- **Stage 2 (Done)**: Async REST client (`auth` `/auth/getToken` with 50m monotonic TTL, `ReqwestTransport` over `rustls`, `InstrumentCatalog`, and `RestClient` with 401 refresh and bounded retries).
- **Stage 3 (Done)**: Sans-I/O WebSocket engine (`WsEngine` / `WsClient`), `WsTransport` + `TungsteniteTransport` (`rustls`) / `FakeWsTransport`, zero-`f64` backoff+jitter, `caucion` term-curve domain, stateful field-merging `Conflator`, and anti-batch-poisoning isolation.
- **Stage 4 & `v0.1.3` (Current)**: Full `pyxoms` ABI3 async/conflated Python API (`MarketDataClient`, background-Tokio `MarketDataStream`, frozen `Decimal`/`UTC` domain objects, lazy cancel-safe `asyncio` bridge), `criterion`/Python benchmarks, `CABLE` cauciones, `BymaOther` suffixes, configurable `WsConfig.subscription_entries`, lossless `InstrumentCatalog.to_json()`, single-pass conflation, cancel-safe `WsClient`, structured Python error attributes, and production ABI3 PyPI packaging.
- **`v0.2.0` (Planned)**: Optional lossless tick-by-tick stream mode (`MarketDataMessage` delivery alongside conflated snapshots).

## AI-Friendly Integration

If you are using an AI coding agent to integrate `xoms-rs` or `pyxoms` into another repository:

- Read [llms.txt](https://github.com/enzodrovandi/xoms-rs/blob/main/llms.txt) for a concise machine-oriented contract of public APIs and invariants.
- Copy [skills/xoms-integration/SKILL.md](https://github.com/enzodrovandi/xoms-rs/blob/main/skills/xoms-integration/SKILL.md) into your host repo's `.agents/skills/` directory.
- Follow [examples/adapter_pattern.py](https://github.com/enzodrovandi/xoms-rs/blob/main/examples/adapter_pattern.py) to wrap `pyxoms` behind your own port/protocol.
- For contributors working inside this repo, read [AGENTS.md](https://github.com/enzodrovandi/xoms-rs/blob/main/AGENTS.md) and [CONTRIBUTING.md](https://github.com/enzodrovandi/xoms-rs/blob/main/CONTRIBUTING.md).

## License

Dual-licensed under **MIT OR Apache-2.0** ([LICENSE-MIT](https://github.com/enzodrovandi/xoms-rs/blob/main/LICENSE-MIT), [LICENSE-APACHE](https://github.com/enzodrovandi/xoms-rs/blob/main/LICENSE-APACHE)).

*Documentación en español disponible en [README.es.md](https://github.com/enzodrovandi/xoms-rs/blob/main/README.es.md).*

