Skip to main content

Typed, production-grade Python SDK for the Phemex crypto exchange API

Project description

phemex-py

PyPI version Python License: MIT

Typed, production-grade Python SDK for the Phemex crypto exchange API.

  • Sync and async clients (built on httpx)
  • Fully typed request/response models (built on Pydantic)
  • USD-M perpetual futures: orders, positions, market data, funding rates, and more

Installation

pip install phemex-py

Quick Start

Authentication

You need a Phemex API key and secret. Create one from your Phemex account settings.

Setting them as environment variables is a tried and true method:

PHEMEX_KIND=test
PHEMEX_KEY=
PHEMEX_SECRET=

The kind parameter controls which Phemex environment to connect to:

Kind URL
vip https://vapi.phemex.com
public https://api.phemex.com
test https://testnet-api.phemex.com

Sync Client

from phemex_py import PhemexClient

with PhemexClient(
        kind="public",
        api_key="your-api-key",
        api_secret="your-api-secret",
) as client:
    # Get server time
    server_time = client.server_time()

    # Get product info
    products = client.usdm_rest.product_information()

    # Get ticker
    ticker = client.usdm_rest.ticker(symbol="BTCUSDT")

    # Get open orders
    orders = client.usdm_rest.open_orders(symbol="BTCUSDT")

    # Get account positions
    positions = client.usdm_rest.positions()

Async Client

import asyncio
from phemex_py import AsyncPhemexClient


async def main():
    async with AsyncPhemexClient(
            kind="public",
            api_key="your-api-key",
            api_secret="your-api-secret",
    ) as client:
        ticker = await client.usdm_rest.ticker(symbol="BTCUSDT")
        positions = await client.usdm_rest.positions()


asyncio.run(main())

Testnet

Use kind="test" for paper trading:

client = PhemexClient(
    kind="test",
    api_key="your-testnet-key",
    api_secret="your-testnet-secret",
)

API Coverage

USD-M Perpetual REST API

Category Endpoints
Market Data product_information, order_book, klines, trades, ticker, tickers
Orders place_order, amend_order, cancel_order, bulk_cancel, cancel_all
Positions positions, positions_with_pnl, switch_position_mode, set_leverage, assign_position_balance
Account risk_units
History open_orders, closed_orders, closed_positions, user_trades, order_history, lookup_order, trade_history
Funding funding_fee_history, funding_rates

Philosophy

phemex-py is a thin SDK/wrapper around the Phemex REST API. It handles transport, authentication, serialization, and type safety so you don't have to — but it intentionally stops there. Trading logic, strategy, and risk management belong in your code (your "engine"), not in the SDK.

The guiding principle: if Phemex returns it or requires it, we model it. If it requires judgment or strategy, that's your job.

SDK responsibility (this library)

  • Authentication, request signing, rate limit tracking
  • Typed request/response models with validation
  • Decoding Phemex conventions (e.g. leverage sign → margin mode)
  • Convenience factories that prevent invalid API calls
  • Computed properties that surface implicit data (margin_mode, effective_leverage, signed_size)

Engine responsibility (your code)

  • Position normalization — merging hedged Long/Short into a net position loses information (separate liquidation prices, margins, PnL). Whether and how to merge is strategy-dependent.
  • Order routing — deciding when, what, and how much to trade
  • Risk management — position sizing, max drawdown, kill switches
  • Retry/reconnect logic — how to handle transient failures depends on your latency and correctness requirements
  • State management — tracking fills, reconciling with exchange state

Example: margin mode

The SDK gives you the building blocks:

pos = client.usdm_rest.positions_with_pnl().get("BTCUSDT")
print(pos.margin_mode)  # "Cross" or "Isolated" — SDK decodes this
print(pos.effective_leverage)  # Always positive — SDK normalizes this

# SDK prevents invalid API calls:
req = SetLeverageRequest.with_margin_mode("BTCUSDT", 10, "Isolated")

But deciding which margin mode to use, when to change leverage, or whether to rebalance margin across positions — that's engine logic.

Links

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

phemex_py-0.2.0.tar.gz (160.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

phemex_py-0.2.0-py3-none-any.whl (139.3 kB view details)

Uploaded Python 3

File details

Details for the file phemex_py-0.2.0.tar.gz.

File metadata

  • Download URL: phemex_py-0.2.0.tar.gz
  • Upload date:
  • Size: 160.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.22

File hashes

Hashes for phemex_py-0.2.0.tar.gz
Algorithm Hash digest
SHA256 54fe1fffde411cf6f8dfabc4ff4be0c49889faaa0465bb1808a7528b7481272e
MD5 118c2e62bb5e1c2f0db1390e7c78a965
BLAKE2b-256 eb3bbc16e2f910a42413d0ff04517e0ffd70d51a818219974979f0c3785f374c

See more details on using hashes here.

File details

Details for the file phemex_py-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: phemex_py-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 139.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.22

File hashes

Hashes for phemex_py-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ded4274153b92161f1df5958cf1a988214650929f6ee5a60bc051eb65b637d19
MD5 2db6ac568494c5a79ef36f6690588866
BLAKE2b-256 1285a7f481719384228accbb21cbb7a08fb105f62101e616158e0da060f888b6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page