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.3.1.tar.gz (167.4 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.3.1-py3-none-any.whl (142.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for phemex_py-0.3.1.tar.gz
Algorithm Hash digest
SHA256 d7b71bd406ebe56867fd160efeb7e0254ebd081e2dcc80020d79ed12bb3b2186
MD5 49f08e10a9e57ba76d1915992630f530
BLAKE2b-256 904a2559b194a5a799cab5f94b4e6dfc9da858350c5329fcdcf0d05b523858cc

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for phemex_py-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5f6d489cf60868914233815cf532784aa023c5a47db721f1a7a1e255056fa71c
MD5 ef0712575fd5a8247604bdb39d53e77c
BLAKE2b-256 5feac2f984cb524cf2156c4e707787d21d5ebbe06dd7f5ed4eef60616436e2b5

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