Skip to main content

dcex - DEX & CEX trading library

Important: No default broker tags are set. You may manually specify a broker tag within function arguments if needed.

Forked from krex, a simplified version of the ccxt Python library.

Originally created and maintained by the same contributor, this fork continues active development, building upon the original foundation with enhanced design, unified DEX + CEX support, and fixes for previously unresolved issues.

A high-performance and lightweight Python and Rust library for interacting with cryptocurrency exchanges. dcex offers Python clients backed by a Rust core, plus direct Rust APIs for low-level HTTP, WebSocket, signing, and exchange integrations.

Scope note: dcex focuses on market data, account queries, trading/order APIs, and market/user-data streams. External withdrawal creation endpoints are not currently wrapped, and options support is limited to exchange-specific APIs rather than the unified Product Table Manager.

Python Rust License PyPI Crates.io

Installation

Python:

pip install dcex

or use uv to manage the project:

uv add dcex

Rust:

cargo add dcex

Direct Rust usage is also documented in crates/dcex/README.md.

Quick Start

Python Synchronous Usage

import dcex

client = dcex.binance()

klines = client.get_klines(product_symbol="BTC-USDT-SWAP", interval="1m")
print(klines)

Python Asynchronous Usage

import os
import asyncio
import dcex.async_support as dcex
from dotenv import load_dotenv

load_dotenv()

BINANCE_API_KEY = os.getenv("BINANCE_API_KEY")
BINANCE_API_SECRET = os.getenv("BINANCE_API_SECRET")

async def main():
    client = await dcex.binance(
        api_key=BINANCE_API_KEY,
        api_secret=BINANCE_API_SECRET
    )

    try:
        result = await client.get_income_history()
        print(result)

    finally:
        await client.close()

if __name__ == "__main__":
    asyncio.run(main())

Python WebSocket Usage

import asyncio

from dcex.ws import binance


async def main():
    async with binance.public() as ws:
        await ws.subscribe_agg_trades("BTC-USDT-SPOT")
        print(await ws.recv())


if __name__ == "__main__":
    asyncio.run(main())

Rust Usage

use std::time::Duration;

use dcex::exchanges::binance::BinanceClient;

#[tokio::main]
async fn main() -> dcex::Result<()> {
    let api_key = std::env::var("BINANCE_API_KEY").expect("Set BINANCE_API_KEY");
    let api_secret = std::env::var("BINANCE_API_SECRET").expect("Set BINANCE_API_SECRET");
    let client = BinanceClient::new(Some(api_key), Some(api_secret), Duration::from_secs(10))?;
    let response = client.get_income_history().await?;
    println!("{}", response.data);
    Ok(())
}

Rust HTTP methods that do not require endpoint parameters can be called without passing None or an empty parameter list. Optional query/body parameters are added with builder setters such as .limit(100) or .param("key", value).

Supported Exchanges

Exchange HTTP Sync HTTP Async WS Public WS Private
Binance Yes Yes Yes Yes
Bybit Yes Yes Yes Yes
OKX Yes Yes Yes Yes
Bitget Yes Yes Yes Yes
Kraken Yes Yes Yes Yes
MEXC Yes Yes Yes Yes
BingX Yes Yes Yes Yes
KuCoin Yes Yes Yes Yes
Hyperliquid Yes Yes Yes Yes
Lighter (Mainnet + Robinhood) Yes Yes Yes Yes
Backpack Yes Yes Yes Yes
Aster Yes Yes Yes Yes
Extended Yes Yes Yes Yes

WS private support currently covers authenticated or address-scoped user-data streams. Order placement and cancellation remain on HTTP clients.

Lighter networks

Lighter network selection is explicit per HTTP or WebSocket client. Mainnet and Robinhood use independent credential groups, so both can run concurrently in a single process. There is no global LIGHTER_NETWORK selector and the legacy mainnet-only LIGHTER_* credential fallback is not accepted.

Private Mainnet clients read LIGHTER_MAINNET_ACCOUNT_INDEX, LIGHTER_MAINNET_API_KEY_INDEX, and LIGHTER_MAINNET_API_PRIVATE_KEY. Robinhood clients use the corresponding LIGHTER_ROBINHOOD_* variables. Select the deployment for each client with dcex.lighter.Network; omitting it keeps the Mainnet default.

Key Features

  • Product Table Manager for unifying trading instruments across exchanges
  • HTTP clients with consistent sync and async interfaces where available
  • Native Rust core for exchange HTTP, WebSocket, signing, serialization, and response validation
  • Public and private WebSocket stream clients across the supported exchanges
  • Direct Rust crate (dcex) for applications that do not need the Python layer
  • Opt-in live test suites for public, private, stateful, and generated-report endpoints

What is Product Table Manager (PTM)?

PTM is a utility that standardizes and unifies trading instrument metadata across different exchanges, making cross-exchange strategy development easier.

It is a table that contains the following columns:

Column Description
exchange The exchange name
product_symbol The symbol we use to identify the product, it will be the same in different exchanges. For example, BTC-USDT-SWAP is the same product in Binance and Bybit, which named BTCUSDT in Binance and BTC-USDT-SWAP in OKX.
exchange_symbol The symbol that the exchange actually uses
product_type The normalized product type used by dcex, e.g. spot, swap, futures
exchange_type The exchange-specific product type, e.g. spot, linear, inverse, perpetual, delivery
base_currency The base currency, e.g. BTC
quote_currency The quote currency, e.g. USDT
price_precision The price precision, e.g. 0.000001
size_precision The size precision, e.g. 0.000001
min_size The minimum size, e.g. 0.000001
min_notional The minimum notional, e.g. 0.000001
size_per_contract The size per contract. Sometimes 1 contract is not the same as 1 unit in exchanges like OKX.

Options are not currently included in the unified PTM output. Some exchange-specific clients expose option-related parameters or market endpoints, but options are not normalized across exchanges.

How to use Product Table Manager?

In most cases, dcex handles product-symbol mapping internally. If you have a specific use case, you can use ptm to get the information you need.

from dcex.utils.common import Common
from dcex.product_table.manager import ProductTableManager

ptm = ProductTableManager.get_instance(Common.BINANCE)

product_symbol = ptm.get_product_symbol(
    exchange=Common.BINANCE,
    exchange_symbol="BTCUSDT",
    product_type="swap",
)

print(product_symbol)

rows = ptm.rows()
ptm.write_csv("binance_product_table.csv")

Contributing

Contributions are welcome through GitHub issues and pull requests. Run the default test suite before opening a pull request.

Testing

The default test suite is offline and does not require exchange API keys or network access:

uv run pytest

Live, private, stateful, and generated-report tests use the pytest markers configured in pyproject.toml. These tests are opt-in because they can require network access, exchange credentials, or account state.

Lighter live tests can target Mainnet, Robinhood, or both. Stateful Lighter tests create real orders and include post-test cancellation, reduce-only position closing, and a final clean-account assertion. Use only dedicated, initially empty accounts when enabling RUN_LIVE_TRADING_TESTS=1.

Benchmarking

Local CPU-bound benchmarks isolate Lighter signing and hashing hot paths. The recorded sample below compares an older native-Python baseline with current published Rust-backed artifacts and keeps package versions fixed so the comparison is repeatable on the same machine. The benchmark auto-calibrates per-operation inner loops and aggregates multiple process runs to reduce timer, GC, and scheduler noise.

Recorded sample (uv run python scripts/benchmark_core_local.py --iterations 50 --warmup 5 --target-batch-ms 100 --process-runs 3 --python-baseline-version 0.21.2 --pyo3-version 0.26.3 --rust-crate-version 0.4.4, 2026-07-03):

Baseline: PyPI dcex==0.21.2 native Python implementation = 1.00x. Rust-backed Python: PyPI dcex==0.26.3; Rust native: crates.io dcex==0.4.4.

Operation Rust-backed Python Rust native
Cryptographic hash 92.45x 113.10x
Schnorr signature 607.72x 596.91x
Transaction payload signing 491.29x 514.83x
Layer Command Output
Local CPU-bound release artifacts uv run python scripts/benchmark_core_local.py --iterations 50 --warmup 5 --target-batch-ms 100 --process-runs 3 --python-baseline-version 0.21.2 --pyo3-version 0.26.3 --rust-crate-version 0.4.4 Speedup table
Optional local CPU-bound CSV output uv run python scripts/benchmark_core_local.py --csv benchmark_core.csv Ignored local CSV file

The Python benchmark scripts install PyPI packages into temporary target directories with uv pip install --target, then compile the Rust benchmark harness against the requested crates.io package version. They do not mutate the current environment. Use --python-baseline-version, --pyo3-version, and --rust-crate-version when you need to compare against other published artifacts.

Release Publishing

The release workflow detects Conventional Commit changes on main and plans Python and Rust releases independently. A bumped Python release builds wheels and publishes the Python package to PyPI. If no Python version bump is detected, PyPI is not updated.

The Rust crate has an independent version in crates/dcex/Cargo.toml and is published from rust-v* tags. For example, rust-vX.Y.Z publishes crate version X.Y.Z to crates.io and creates a separate GitHub Release. The crates/dcex-python package is an internal PyO3 build crate and is not published to crates.io; the Python package version is managed only in pyproject.toml.

License

This project is licensed under the MIT License.

Support

Disclaimer

Cryptocurrency trading involves significant risk. This library is provided as-is without any warranty. Users are responsible for their own trading decisions and risk management.

Release files for dcex 0.32.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dcex 0.32.0
File Size Uploaded
dcex-0.32.0.tar.gz 553.4 kB Details

Built distributions (wheels)

Table of built distributions (wheels) for dcex 0.32.0
File Interpreter ABI Platform
dcex-0.32.0-cp312-cp312-win_amd64.whl CPython 3.12 CPython 3.12 Windows x86-64 Details
dcex-0.32.0-cp312-cp312-manylinux_2_34_x86_64.whl CPython 3.12 CPython 3.12 Linux glibc 2.34+ x86-64 Details
dcex-0.32.0-cp312-cp312-macosx_11_0_arm64.whl CPython 3.12 CPython 3.12 macOS 11.0+ ARM64 Details

Total release size: 31.4 MB

Release files / dcex-0.32.0.tar.gz

Download URL dcex-0.32.0.tar.gz
Size 553.4 kB
Tags Source
SHA-256 checksum
How to use checksums
5cf6b61d26f28f348c4cae92b3ed56f9195ef35d8ea462b3b11a911680e76d22
BLAKE2b-256 checksum
How to use checksums
b4d6c1d0aa3f3a4aa04521a625ae7e3dfe46e9743400892902a809bdaee431ff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.13 {"installer":{"name":"uv","version":"0.12.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / dcex-0.32.0-cp312-cp312-win_amd64.whl

Download URL dcex-0.32.0-cp312-cp312-win_amd64.whl
Size 10.9 MB
Tags CPython 3.12 Windows x86-64
SHA-256 checksum
How to use checksums
aacd71a356af9f7b60ddf6b9b1b82b37bcf43bef1dd9799c59d1c5d766d9ffc9
BLAKE2b-256 checksum
How to use checksums
c2f6be0d72e12e70ecabdf2286700280c3f33803141f5b8e93e6c42b09dd3291
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.13 {"installer":{"name":"uv","version":"0.12.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / dcex-0.32.0-cp312-cp312-manylinux_2_34_x86_64.whl

Download URL dcex-0.32.0-cp312-cp312-manylinux_2_34_x86_64.whl
Size 10.4 MB
Tags CPython 3.12 Linux glibc 2.34+ x86-64
SHA-256 checksum
How to use checksums
1c3d7ab23046128341c32766e8b2cc4b75dce348c7fa5d5c77dea20cd9d2f46a
BLAKE2b-256 checksum
How to use checksums
73ac205152edf7cd5726d4157ea66b4cd9e26d4a47f0ac11a36aaa2d10c93860
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.13 {"installer":{"name":"uv","version":"0.12.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / dcex-0.32.0-cp312-cp312-macosx_11_0_arm64.whl

Download URL dcex-0.32.0-cp312-cp312-macosx_11_0_arm64.whl
Size 9.6 MB
Tags CPython 3.12 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
9509d9bca3af6c84907398b374957d436808d167705bf65dd19b14398d0f8eb6
BLAKE2b-256 checksum
How to use checksums
0ee64b0679cfa3cdb438644375ea3663f7dc1a6a7f7d55ec130065d239525e33
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.13 {"installer":{"name":"uv","version":"0.12.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release history Release notifications | RSS feed

0.33.0

4 release files

This release

0.32.0 This release

4 release files

0.31.0

4 release files

0.30.0

4 release files

0.29.1

4 release files

0.29.0

4 release files

0.28.5

4 release files

0.28.4

4 release files

0.28.3

4 release files

0.28.2

4 release files

0.28.1

4 release files

0.28.0

4 release files

0.27.0

4 release files

0.26.2

4 release files

0.26.1

4 release files

0.26.0

4 release files

0.25.0

4 release files

0.24.2

4 release files

0.24.1

4 release files

0.24.0

4 release files

0.23.0

4 release files

0.22.0

4 release files

0.21.2

2 release files

0.21.1

2 release files

0.21.0

2 release files

0.20.3

2 release files

0.20.2

2 release files

0.20.1

2 release files

0.20.0

2 release files

0.10.0

2 release files

0.9.3

2 release files

0.9.2

2 release files

0.9.1

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.0

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.4

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page