Repository files navigation

EdgeX Python SDK

A Python SDK for interacting with the EdgeX Exchange API. This SDK provides a comprehensive interface to the EdgeX API, allowing you to easily integrate EdgeX functionality into your Python applications.

Branch Status

The main branch contains the current EdgeX V2 SDK. The legacy V1 SDK has moved to the v1 branch and is deprecated. New integrations should use V2.

Features

  • Complete API Coverage: Access all EdgeX API endpoints
  • WebSocket Support: Real-time data streaming
  • Async/Await: Modern Python async interface
  • Type Hints: Comprehensive type annotations for better IDE support
  • Error Handling: Proper error handling and validation
  • Pagination: Support for paginated API endpoints
  • Authentication: Automatic request signing

Installation

From PyPI

pip install edgex-python-sdk

Version Compatibility

edgex-python-sdk on PyPI has two incompatible API generations:

  • <= 0.3.0: contract v1 API SDK
  • >= 2.0.0: contract v2 API SDK

These two generations are not backward compatible. Please choose the package version based on the API generation you are integrating with.

Examples:

# Contract v1 API SDK
pip install "edgex-python-sdk<=0.3.0"# Contract v2 API SDK
pip install "edgex-python-sdk>=2.0.0"

From Source

git clone https://github.com/edgex-Tech/edgex-python-sdk.git
cd edgex-python-sdk
pip install -e .

Using Requirements Files

For production use:

pip install -r requirements.txt

For development (includes testing and linting tools):

pip install -r requirements-dev.txt

Virtual Environment (Recommended)

It's recommended to use a virtual environment:

# Create virtual environment
python3 -m venv venv
# Activate virtual environmentsource venv/bin/activate # On Windows: venv\Scripts\activate# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .

Quick Start

importasyncioimportosfromedgex_sdkimportClient, OrderSideasyncdefmain():
# Create a new clientclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345, # Your account IDtrading_private_key="your-trading-private-key"# Your trading private key
)
# Get server timeserver_time=awaitclient.get_server_time()
print(f"Server Time: {server_time}")
# Get exchange metadatametadata=awaitclient.get_metadata()
print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}")
# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account Assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Account Positions: {positions}")
# Get 24-hour market data for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"BNB2USDT Price: {quote}")
# Create a limit order (uncomment to place real order)# order = await client.create_limit_order(# contract_id="10000004", # BNB2USDT# size="0.01",# price="600.00",# side=OrderSide.BUY# )# print(f"Order created: {order}")# Run the async functionasyncio.run(main())

Architecture

The SDK is organized into modules that correspond to the EdgeX API structure:

edgex_sdk/
├── __init__.py
├── client.py # Main client
├── account/ # Account API
├── funding/ # Funding API
├── internal/ # Internal utilities
├── metadata/ # Metadata API
├── order/ # Order API
├── quote/ # Quote API
├── transfer/ # Transfer API
├── unified_asset/ # Unified asset withdraw / transfer flows
├── cctp/ # Circle CCTP bridge helpers
└── ws/ # WebSocket API

Available APIs

The SDK currently supports the following API modules:

  • Account API: Manage account positions, retrieve position transactions, and handle collateral transactions

    • Get account positions
    • Get position by contract ID
    • Get position transaction history
    • Get collateral transaction details
    • Update leverage settings
  • Unified Asset API: Current market-maker withdrawal flow

    • Build Spot / Perp V2 withdraw attempts with raw token amounts
    • Get fee via getFeeByAssetFlow
    • Sign server-provided EIP-712 payloads
    • Submit flows through submitAssetFlow
  • CCTP Bridge Helpers: Edge Mainnet USDC bridge support

    • Quote Circle CCTP fast-transfer fees
    • Build Edge depositForBurn bridge transactions
    • Fetch Iris V2 attestations
    • Build / submit Ethereum receiveMessage claim transactions
  • Funding API: Manage funding operations and account balance

    • Handle funding transactions
    • Manage funding accounts
    • Get funding transaction history
  • Metadata API: Access exchange system information

    • Get server time
    • Get exchange metadata (trading pairs, contracts, etc.)
  • Order API: Comprehensive order management

    • Create and cancel orders
    • Get active orders
    • Get order fill transactions
    • Calculate maximum order sizes
    • Manage order history
  • Quote API: Access market data and pricing

    • Get multi-contract K-line data
    • Get order book depth
    • Access real-time market quotes
    • Get 24-hour ticker data
  • Transfer API: Handle asset transfers

    • Create transfer out orders
    • Get transfer records (in/out)
    • Check available withdrawal amounts
    • Manage transfer history
  • WebSocket API: Real-time data streaming

    • Market data (tickers, K-lines, order book, trades)
    • Account updates
    • Order updates
    • Position updates

WebSocket Support

The SDK provides a WebSocket manager for handling real-time data:

importasynciofromedgex_sdkimportWebSocketManagerasyncdefmain():
# Create a WebSocket managerws_manager=WebSocketManager(
base_url="wss://edgex-quote-prod-v2.edgex.exchange",
account_id=12345,
api_key="",
api_passphrase="",
api_secret=""
)
# Define message handlersdefticker_handler(message):
print(f"Ticker Update: {message}")
defkline_handler(message):
print(f"K-line Update: {message}")
# Connect to public WebSocket for market dataws_manager.connect_public()
# Subscribe to real-time updates for BNB2USDT (contract ID: 10000004)ws_manager.subscribe_ticker("10000004", ticker_handler)
ws_manager.subscribe_kline("10000004", "1m", kline_handler)
# Connect to private WebSocket for account updatesws_manager.connect_private()
# Wait for updatesawaitasyncio.sleep(30)
# Disconnect all connectionsws_manager.disconnect_all()
asyncio.run(main())

Signing

The v2 SDK uses different keys for different signing flows:

  • trading private key: EIP-712 signing for order placement and setMarginMode
  • wallet private key: unified-asset withdrawal / transfer signing

Unified-asset withdrawals sign the EIP-712 payload returned by getEIP712Data and submit a 0x-prefixed signature. There is no StarkEx signing adapter in the v2 path.

Current Withdrawal Path

fromedgex_sdkimportClient, CreateWithdrawParamsclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345,
api_key="...",
api_passphrase="...",
api_secret="...",
wallet_private_key="...",
)
result=awaitclient.create_withdraw(CreateWithdrawParams(
amount_raw="1000000",
user_address="0xYourWallet",
profile="mainnet-usdc",
))

Use source="perpv2" and the Perp V2 account ID in source_account to reuse the same unified-asset withdrawal path for Perp V2.

Error Handling

The SDK provides proper error handling for API requests:

importasynciofromedgex_sdkimportClient, OrderSideasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
try:
# Create a limit order for BNB2USDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNB2USDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Cancel the orderfromedgex_sdkimportCancelOrderParamscancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")
exceptValueErrorase:
print(f"Failed to create/cancel order: {str(e)}")
exceptExceptionase:
print(f"Unexpected error: {str(e)}")
asyncio.run(main())

Pagination

Many API endpoints support pagination:

importasynciofromedgex_sdkimportClient, GetActiveOrderParamsasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
# Create pagination parametersparams=GetActiveOrderParams(
size="10",
offset_data=""
)
# Get active ordersorders=awaitclient.get_active_orders(params)
print(f"Active orders: {orders}")
# Get next page if availableiforders.get("data", {}).get("hasNext"):
params.offset_data=orders.get("data", {}).get("offsetData")
next_page=awaitclient.get_active_orders(params)
print(f"Next page: {next_page}")
asyncio.run(main())

API Examples

Market Data

Available Enums

KlineType (K-line intervals):

  • KlineType.MINUTE_1, KlineType.MINUTE_5, KlineType.MINUTE_15, KlineType.MINUTE_30
  • KlineType.HOUR_1, KlineType.HOUR_2, KlineType.HOUR_4, KlineType.HOUR_6, KlineType.HOUR_8, KlineType.HOUR_12
  • KlineType.DAY_1, KlineType.WEEK_1, KlineType.MONTH_1

PriceType (price types):

  • PriceType.LAST_PRICE (default) - Latest market price
  • PriceType.INDEX_PRICE - Index price
  • PriceType.ORACLE_PRICE - Oracle price
  • PriceType.ASK1_PRICE - Best ask price
  • PriceType.BID1_PRICE - Best bid price
  • PriceType.OPEN_INTEREST - Open interest
fromedgex_sdkimportClient, GetKLineParams, GetOrderBookDepthParams, KlineType, PriceType# Get 24-hour market quotes for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"Current price: {quote}")
# Get K-line data for BTCUSDT (contract ID: 10000001)kline_params=GetKLineParams(
contract_id="10000001", # BTCUSDTkline_type=KlineType.MINUTE_1,
price_type=PriceType.LAST_PRICE,
size=10
)
# With time filters (optional)# kline_params = GetKLineParams(# contract_id="10000001",# kline_type=KlineType.HOUR_1,# price_type=PriceType.LAST_PRICE,# size=20,# filter_begin_kline_time_inclusive="1640995200000", # Start timestamp# filter_end_kline_time_exclusive="1640998800000" # End timestamp# )klines=awaitclient.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get order book depth for ETHUSDT (contract ID: 10000002)depth_params=GetOrderBookDepthParams(
contract_id="10000002", # ETHUSDTlimit=10
)
depth=awaitclient.quote.get_order_book_depth(depth_params)
print(f"Order book: {depth}")

Account Management

# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Positions: {positions}")
# Get position transactionsfromedgex_sdkimportGetPositionTransactionPageParamstx_params=GetPositionTransactionPageParams(
size="10",
offset_data=""
)
transactions=awaitclient.account.get_position_transaction_page(tx_params)
print(f"Transactions: {transactions}")

Order Management

fromedgex_sdkimportOrderSide, CreateOrderParams, CancelOrderParams# Create a limit order for BNBUSDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNBUSDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Get maximum order size for BNBUSDTmax_size=awaitclient.get_max_order_size("10000004", 600.00)
print(f"Max order size: {max_size}")
# Cancel an ordercancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")

Contract IDs

EdgeX uses numeric contract IDs instead of symbol-based identifiers. Here are some common contract mappings:

Contract IDSymbolTick Size
10000001BTCUSDT0.1
10000002ETHUSDT0.01
10000003SOLUSDT0.01

To get the complete list of available contracts:

metadata=awaitclient.get_metadata()
contracts=metadata.get("data", {}).get("contractList", [])
forcontractincontracts:
print(f"ID: {contract['contractId']} - {contract['contractName']}")

For more detailed examples, please refer to the examples directory.

Testing

The SDK includes comprehensive test coverage with multiple test suites:

Unit Tests

# Run unit tests (no API credentials required)
python -m pytest tests/test_client.py tests/test_eip712_signing.py -v

Public API Tests

# Run public endpoint tests (no authentication required)
python run_public_tests.py

Mock Integration Tests

# Run mock tests (test structure without real API calls)
python run_mock_tests.py

Full Integration Tests

# Run full integration tests (requires real API credentials)
python run_integration_tests.py

All Tests

# Run all available tests
python run_tests.py

For more testing information, see TESTING.md.

Environment Variables

For testing and development, you can set the following environment variables or create a .env file:

# API Configuration
EDGEX_BASE_URL=https://edgex-prod-v2.edgex.exchange
EDGEX_ASSET_BASE_URL=https://spot.edgex.exchange
EDGEX_WS_URL=wss://edgex-quote-prod-v2.edgex.exchange
# Account Credentials
EDGEX_ACCOUNT_ID=12345
EDGEX_TRADING_PRIVATE_KEY=your-trading-private-key

Then load them in your code:

importosfromdotenvimportload_dotenvfromedgex_sdkimportClient# Load environment variables from .env fileload_dotenv()
client=Client(
base_url=os.getenv("EDGEX_BASE_URL"),
asset_base_url=os.getenv("EDGEX_ASSET_BASE_URL"),
account_id=int(os.getenv("EDGEX_ACCOUNT_ID")),
trading_private_key=os.getenv("EDGEX_TRADING_PRIVATE_KEY")
)

Documentation

For detailed API documentation, please refer to the EdgeX API documentation.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin feature/my-new-feature)
  5. Create a new Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

30 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

EdgeX Python SDK

A Python SDK for interacting with the EdgeX Exchange API. This SDK provides a comprehensive interface to the EdgeX API, allowing you to easily integrate EdgeX functionality into your Python applications.

Branch Status

The main branch contains the current EdgeX V2 SDK. The legacy V1 SDK has moved to the v1 branch and is deprecated. New integrations should use V2.

Features

  • Complete API Coverage: Access all EdgeX API endpoints
  • WebSocket Support: Real-time data streaming
  • Async/Await: Modern Python async interface
  • Type Hints: Comprehensive type annotations for better IDE support
  • Error Handling: Proper error handling and validation
  • Pagination: Support for paginated API endpoints
  • Authentication: Automatic request signing

Installation

From PyPI

pip install edgex-python-sdk

Version Compatibility

edgex-python-sdk on PyPI has two incompatible API generations:

  • <= 0.3.0: contract v1 API SDK
  • >= 2.0.0: contract v2 API SDK

These two generations are not backward compatible. Please choose the package version based on the API generation you are integrating with.

Examples:

# Contract v1 API SDK
pip install "edgex-python-sdk<=0.3.0"# Contract v2 API SDK
pip install "edgex-python-sdk>=2.0.0"

From Source

git clone https://github.com/edgex-Tech/edgex-python-sdk.git
cd edgex-python-sdk
pip install -e .

Using Requirements Files

For production use:

pip install -r requirements.txt

For development (includes testing and linting tools):

pip install -r requirements-dev.txt

Virtual Environment (Recommended)

It's recommended to use a virtual environment:

# Create virtual environment
python3 -m venv venv
# Activate virtual environmentsource venv/bin/activate # On Windows: venv\Scripts\activate# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .

Quick Start

importasyncioimportosfromedgex_sdkimportClient, OrderSideasyncdefmain():
# Create a new clientclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345, # Your account IDtrading_private_key="your-trading-private-key"# Your trading private key
)
# Get server timeserver_time=awaitclient.get_server_time()
print(f"Server Time: {server_time}")
# Get exchange metadatametadata=awaitclient.get_metadata()
print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}")
# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account Assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Account Positions: {positions}")
# Get 24-hour market data for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"BNB2USDT Price: {quote}")
# Create a limit order (uncomment to place real order)# order = await client.create_limit_order(# contract_id="10000004", # BNB2USDT# size="0.01",# price="600.00",# side=OrderSide.BUY# )# print(f"Order created: {order}")# Run the async functionasyncio.run(main())

Architecture

The SDK is organized into modules that correspond to the EdgeX API structure:

edgex_sdk/
├── __init__.py
├── client.py # Main client
├── account/ # Account API
├── funding/ # Funding API
├── internal/ # Internal utilities
├── metadata/ # Metadata API
├── order/ # Order API
├── quote/ # Quote API
├── transfer/ # Transfer API
├── unified_asset/ # Unified asset withdraw / transfer flows
├── cctp/ # Circle CCTP bridge helpers
└── ws/ # WebSocket API

Available APIs

The SDK currently supports the following API modules:

  • Account API: Manage account positions, retrieve position transactions, and handle collateral transactions

    • Get account positions
    • Get position by contract ID
    • Get position transaction history
    • Get collateral transaction details
    • Update leverage settings
  • Unified Asset API: Current market-maker withdrawal flow

    • Build Spot / Perp V2 withdraw attempts with raw token amounts
    • Get fee via getFeeByAssetFlow
    • Sign server-provided EIP-712 payloads
    • Submit flows through submitAssetFlow
  • CCTP Bridge Helpers: Edge Mainnet USDC bridge support

    • Quote Circle CCTP fast-transfer fees
    • Build Edge depositForBurn bridge transactions
    • Fetch Iris V2 attestations
    • Build / submit Ethereum receiveMessage claim transactions
  • Funding API: Manage funding operations and account balance

    • Handle funding transactions
    • Manage funding accounts
    • Get funding transaction history
  • Metadata API: Access exchange system information

    • Get server time
    • Get exchange metadata (trading pairs, contracts, etc.)
  • Order API: Comprehensive order management

    • Create and cancel orders
    • Get active orders
    • Get order fill transactions
    • Calculate maximum order sizes
    • Manage order history
  • Quote API: Access market data and pricing

    • Get multi-contract K-line data
    • Get order book depth
    • Access real-time market quotes
    • Get 24-hour ticker data
  • Transfer API: Handle asset transfers

    • Create transfer out orders
    • Get transfer records (in/out)
    • Check available withdrawal amounts
    • Manage transfer history
  • WebSocket API: Real-time data streaming

    • Market data (tickers, K-lines, order book, trades)
    • Account updates
    • Order updates
    • Position updates

WebSocket Support

The SDK provides a WebSocket manager for handling real-time data:

importasynciofromedgex_sdkimportWebSocketManagerasyncdefmain():
# Create a WebSocket managerws_manager=WebSocketManager(
base_url="wss://edgex-quote-prod-v2.edgex.exchange",
account_id=12345,
api_key="",
api_passphrase="",
api_secret=""
)
# Define message handlersdefticker_handler(message):
print(f"Ticker Update: {message}")
defkline_handler(message):
print(f"K-line Update: {message}")
# Connect to public WebSocket for market dataws_manager.connect_public()
# Subscribe to real-time updates for BNB2USDT (contract ID: 10000004)ws_manager.subscribe_ticker("10000004", ticker_handler)
ws_manager.subscribe_kline("10000004", "1m", kline_handler)
# Connect to private WebSocket for account updatesws_manager.connect_private()
# Wait for updatesawaitasyncio.sleep(30)
# Disconnect all connectionsws_manager.disconnect_all()
asyncio.run(main())

Signing

The v2 SDK uses different keys for different signing flows:

  • trading private key: EIP-712 signing for order placement and setMarginMode
  • wallet private key: unified-asset withdrawal / transfer signing

Unified-asset withdrawals sign the EIP-712 payload returned by getEIP712Data and submit a 0x-prefixed signature. There is no StarkEx signing adapter in the v2 path.

Current Withdrawal Path

fromedgex_sdkimportClient, CreateWithdrawParamsclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345,
api_key="...",
api_passphrase="...",
api_secret="...",
wallet_private_key="...",
)
result=awaitclient.create_withdraw(CreateWithdrawParams(
amount_raw="1000000",
user_address="0xYourWallet",
profile="mainnet-usdc",
))

Use source="perpv2" and the Perp V2 account ID in source_account to reuse the same unified-asset withdrawal path for Perp V2.

Error Handling

The SDK provides proper error handling for API requests:

importasynciofromedgex_sdkimportClient, OrderSideasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
try:
# Create a limit order for BNB2USDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNB2USDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Cancel the orderfromedgex_sdkimportCancelOrderParamscancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")
exceptValueErrorase:
print(f"Failed to create/cancel order: {str(e)}")
exceptExceptionase:
print(f"Unexpected error: {str(e)}")
asyncio.run(main())

Pagination

Many API endpoints support pagination:

importasynciofromedgex_sdkimportClient, GetActiveOrderParamsasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
# Create pagination parametersparams=GetActiveOrderParams(
size="10",
offset_data=""
)
# Get active ordersorders=awaitclient.get_active_orders(params)
print(f"Active orders: {orders}")
# Get next page if availableiforders.get("data", {}).get("hasNext"):
params.offset_data=orders.get("data", {}).get("offsetData")
next_page=awaitclient.get_active_orders(params)
print(f"Next page: {next_page}")
asyncio.run(main())

API Examples

Market Data

Available Enums

KlineType (K-line intervals):

  • KlineType.MINUTE_1, KlineType.MINUTE_5, KlineType.MINUTE_15, KlineType.MINUTE_30
  • KlineType.HOUR_1, KlineType.HOUR_2, KlineType.HOUR_4, KlineType.HOUR_6, KlineType.HOUR_8, KlineType.HOUR_12
  • KlineType.DAY_1, KlineType.WEEK_1, KlineType.MONTH_1

PriceType (price types):

  • PriceType.LAST_PRICE (default) - Latest market price
  • PriceType.INDEX_PRICE - Index price
  • PriceType.ORACLE_PRICE - Oracle price
  • PriceType.ASK1_PRICE - Best ask price
  • PriceType.BID1_PRICE - Best bid price
  • PriceType.OPEN_INTEREST - Open interest
fromedgex_sdkimportClient, GetKLineParams, GetOrderBookDepthParams, KlineType, PriceType# Get 24-hour market quotes for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"Current price: {quote}")
# Get K-line data for BTCUSDT (contract ID: 10000001)kline_params=GetKLineParams(
contract_id="10000001", # BTCUSDTkline_type=KlineType.MINUTE_1,
price_type=PriceType.LAST_PRICE,
size=10
)
# With time filters (optional)# kline_params = GetKLineParams(# contract_id="10000001",# kline_type=KlineType.HOUR_1,# price_type=PriceType.LAST_PRICE,# size=20,# filter_begin_kline_time_inclusive="1640995200000", # Start timestamp# filter_end_kline_time_exclusive="1640998800000" # End timestamp# )klines=awaitclient.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get order book depth for ETHUSDT (contract ID: 10000002)depth_params=GetOrderBookDepthParams(
contract_id="10000002", # ETHUSDTlimit=10
)
depth=awaitclient.quote.get_order_book_depth(depth_params)
print(f"Order book: {depth}")

Account Management

# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Positions: {positions}")
# Get position transactionsfromedgex_sdkimportGetPositionTransactionPageParamstx_params=GetPositionTransactionPageParams(
size="10",
offset_data=""
)
transactions=awaitclient.account.get_position_transaction_page(tx_params)
print(f"Transactions: {transactions}")

Order Management

fromedgex_sdkimportOrderSide, CreateOrderParams, CancelOrderParams# Create a limit order for BNBUSDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNBUSDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Get maximum order size for BNBUSDTmax_size=awaitclient.get_max_order_size("10000004", 600.00)
print(f"Max order size: {max_size}")
# Cancel an ordercancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")

Contract IDs

EdgeX uses numeric contract IDs instead of symbol-based identifiers. Here are some common contract mappings:

Contract IDSymbolTick Size
10000001BTCUSDT0.1
10000002ETHUSDT0.01
10000003SOLUSDT0.01

To get the complete list of available contracts:

metadata=awaitclient.get_metadata()
contracts=metadata.get("data", {}).get("contractList", [])
forcontractincontracts:
print(f"ID: {contract['contractId']} - {contract['contractName']}")

For more detailed examples, please refer to the examples directory.

Testing

The SDK includes comprehensive test coverage with multiple test suites:

Unit Tests

# Run unit tests (no API credentials required)
python -m pytest tests/test_client.py tests/test_eip712_signing.py -v

Public API Tests

# Run public endpoint tests (no authentication required)
python run_public_tests.py

Mock Integration Tests

# Run mock tests (test structure without real API calls)
python run_mock_tests.py

Full Integration Tests

# Run full integration tests (requires real API credentials)
python run_integration_tests.py

All Tests

# Run all available tests
python run_tests.py

For more testing information, see TESTING.md.

Environment Variables

For testing and development, you can set the following environment variables or create a .env file:

# API Configuration
EDGEX_BASE_URL=https://edgex-prod-v2.edgex.exchange
EDGEX_ASSET_BASE_URL=https://spot.edgex.exchange
EDGEX_WS_URL=wss://edgex-quote-prod-v2.edgex.exchange
# Account Credentials
EDGEX_ACCOUNT_ID=12345
EDGEX_TRADING_PRIVATE_KEY=your-trading-private-key

Then load them in your code:

importosfromdotenvimportload_dotenvfromedgex_sdkimportClient# Load environment variables from .env fileload_dotenv()
client=Client(
base_url=os.getenv("EDGEX_BASE_URL"),
asset_base_url=os.getenv("EDGEX_ASSET_BASE_URL"),
account_id=int(os.getenv("EDGEX_ACCOUNT_ID")),
trading_private_key=os.getenv("EDGEX_TRADING_PRIVATE_KEY")
)

Documentation

For detailed API documentation, please refer to the EdgeX API documentation.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin feature/my-new-feature)
  5. Create a new Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

30 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

EdgeX Python SDK

A Python SDK for interacting with the EdgeX Exchange API. This SDK provides a comprehensive interface to the EdgeX API, allowing you to easily integrate EdgeX functionality into your Python applications.

Branch Status

The main branch contains the current EdgeX V2 SDK. The legacy V1 SDK has moved to the v1 branch and is deprecated. New integrations should use V2.

Features

  • Complete API Coverage: Access all EdgeX API endpoints
  • WebSocket Support: Real-time data streaming
  • Async/Await: Modern Python async interface
  • Type Hints: Comprehensive type annotations for better IDE support
  • Error Handling: Proper error handling and validation
  • Pagination: Support for paginated API endpoints
  • Authentication: Automatic request signing

Installation

From PyPI

pip install edgex-python-sdk

Version Compatibility

edgex-python-sdk on PyPI has two incompatible API generations:

  • <= 0.3.0: contract v1 API SDK
  • >= 2.0.0: contract v2 API SDK

These two generations are not backward compatible. Please choose the package version based on the API generation you are integrating with.

Examples:

# Contract v1 API SDK
pip install "edgex-python-sdk<=0.3.0"# Contract v2 API SDK
pip install "edgex-python-sdk>=2.0.0"

From Source

git clone https://github.com/edgex-Tech/edgex-python-sdk.git
cd edgex-python-sdk
pip install -e .

Using Requirements Files

For production use:

pip install -r requirements.txt

For development (includes testing and linting tools):

pip install -r requirements-dev.txt

Virtual Environment (Recommended)

It's recommended to use a virtual environment:

# Create virtual environment
python3 -m venv venv
# Activate virtual environmentsource venv/bin/activate # On Windows: venv\Scripts\activate# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .

Quick Start

importasyncioimportosfromedgex_sdkimportClient, OrderSideasyncdefmain():
# Create a new clientclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345, # Your account IDtrading_private_key="your-trading-private-key"# Your trading private key
)
# Get server timeserver_time=awaitclient.get_server_time()
print(f"Server Time: {server_time}")
# Get exchange metadatametadata=awaitclient.get_metadata()
print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}")
# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account Assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Account Positions: {positions}")
# Get 24-hour market data for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"BNB2USDT Price: {quote}")
# Create a limit order (uncomment to place real order)# order = await client.create_limit_order(# contract_id="10000004", # BNB2USDT# size="0.01",# price="600.00",# side=OrderSide.BUY# )# print(f"Order created: {order}")# Run the async functionasyncio.run(main())

Architecture

The SDK is organized into modules that correspond to the EdgeX API structure:

edgex_sdk/
├── __init__.py
├── client.py # Main client
├── account/ # Account API
├── funding/ # Funding API
├── internal/ # Internal utilities
├── metadata/ # Metadata API
├── order/ # Order API
├── quote/ # Quote API
├── transfer/ # Transfer API
├── unified_asset/ # Unified asset withdraw / transfer flows
├── cctp/ # Circle CCTP bridge helpers
└── ws/ # WebSocket API

Available APIs

The SDK currently supports the following API modules:

  • Account API: Manage account positions, retrieve position transactions, and handle collateral transactions

    • Get account positions
    • Get position by contract ID
    • Get position transaction history
    • Get collateral transaction details
    • Update leverage settings
  • Unified Asset API: Current market-maker withdrawal flow

    • Build Spot / Perp V2 withdraw attempts with raw token amounts
    • Get fee via getFeeByAssetFlow
    • Sign server-provided EIP-712 payloads
    • Submit flows through submitAssetFlow
  • CCTP Bridge Helpers: Edge Mainnet USDC bridge support

    • Quote Circle CCTP fast-transfer fees
    • Build Edge depositForBurn bridge transactions
    • Fetch Iris V2 attestations
    • Build / submit Ethereum receiveMessage claim transactions
  • Funding API: Manage funding operations and account balance

    • Handle funding transactions
    • Manage funding accounts
    • Get funding transaction history
  • Metadata API: Access exchange system information

    • Get server time
    • Get exchange metadata (trading pairs, contracts, etc.)
  • Order API: Comprehensive order management

    • Create and cancel orders
    • Get active orders
    • Get order fill transactions
    • Calculate maximum order sizes
    • Manage order history
  • Quote API: Access market data and pricing

    • Get multi-contract K-line data
    • Get order book depth
    • Access real-time market quotes
    • Get 24-hour ticker data
  • Transfer API: Handle asset transfers

    • Create transfer out orders
    • Get transfer records (in/out)
    • Check available withdrawal amounts
    • Manage transfer history
  • WebSocket API: Real-time data streaming

    • Market data (tickers, K-lines, order book, trades)
    • Account updates
    • Order updates
    • Position updates

WebSocket Support

The SDK provides a WebSocket manager for handling real-time data:

importasynciofromedgex_sdkimportWebSocketManagerasyncdefmain():
# Create a WebSocket managerws_manager=WebSocketManager(
base_url="wss://edgex-quote-prod-v2.edgex.exchange",
account_id=12345,
api_key="",
api_passphrase="",
api_secret=""
)
# Define message handlersdefticker_handler(message):
print(f"Ticker Update: {message}")
defkline_handler(message):
print(f"K-line Update: {message}")
# Connect to public WebSocket for market dataws_manager.connect_public()
# Subscribe to real-time updates for BNB2USDT (contract ID: 10000004)ws_manager.subscribe_ticker("10000004", ticker_handler)
ws_manager.subscribe_kline("10000004", "1m", kline_handler)
# Connect to private WebSocket for account updatesws_manager.connect_private()
# Wait for updatesawaitasyncio.sleep(30)
# Disconnect all connectionsws_manager.disconnect_all()
asyncio.run(main())

Signing

The v2 SDK uses different keys for different signing flows:

  • trading private key: EIP-712 signing for order placement and setMarginMode
  • wallet private key: unified-asset withdrawal / transfer signing

Unified-asset withdrawals sign the EIP-712 payload returned by getEIP712Data and submit a 0x-prefixed signature. There is no StarkEx signing adapter in the v2 path.

Current Withdrawal Path

fromedgex_sdkimportClient, CreateWithdrawParamsclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345,
api_key="...",
api_passphrase="...",
api_secret="...",
wallet_private_key="...",
)
result=awaitclient.create_withdraw(CreateWithdrawParams(
amount_raw="1000000",
user_address="0xYourWallet",
profile="mainnet-usdc",
))

Use source="perpv2" and the Perp V2 account ID in source_account to reuse the same unified-asset withdrawal path for Perp V2.

Error Handling

The SDK provides proper error handling for API requests:

importasynciofromedgex_sdkimportClient, OrderSideasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
try:
# Create a limit order for BNB2USDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNB2USDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Cancel the orderfromedgex_sdkimportCancelOrderParamscancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")
exceptValueErrorase:
print(f"Failed to create/cancel order: {str(e)}")
exceptExceptionase:
print(f"Unexpected error: {str(e)}")
asyncio.run(main())

Pagination

Many API endpoints support pagination:

importasynciofromedgex_sdkimportClient, GetActiveOrderParamsasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
# Create pagination parametersparams=GetActiveOrderParams(
size="10",
offset_data=""
)
# Get active ordersorders=awaitclient.get_active_orders(params)
print(f"Active orders: {orders}")
# Get next page if availableiforders.get("data", {}).get("hasNext"):
params.offset_data=orders.get("data", {}).get("offsetData")
next_page=awaitclient.get_active_orders(params)
print(f"Next page: {next_page}")
asyncio.run(main())

API Examples

Market Data

Available Enums

KlineType (K-line intervals):

  • KlineType.MINUTE_1, KlineType.MINUTE_5, KlineType.MINUTE_15, KlineType.MINUTE_30
  • KlineType.HOUR_1, KlineType.HOUR_2, KlineType.HOUR_4, KlineType.HOUR_6, KlineType.HOUR_8, KlineType.HOUR_12
  • KlineType.DAY_1, KlineType.WEEK_1, KlineType.MONTH_1

PriceType (price types):

  • PriceType.LAST_PRICE (default) - Latest market price
  • PriceType.INDEX_PRICE - Index price
  • PriceType.ORACLE_PRICE - Oracle price
  • PriceType.ASK1_PRICE - Best ask price
  • PriceType.BID1_PRICE - Best bid price
  • PriceType.OPEN_INTEREST - Open interest
fromedgex_sdkimportClient, GetKLineParams, GetOrderBookDepthParams, KlineType, PriceType# Get 24-hour market quotes for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"Current price: {quote}")
# Get K-line data for BTCUSDT (contract ID: 10000001)kline_params=GetKLineParams(
contract_id="10000001", # BTCUSDTkline_type=KlineType.MINUTE_1,
price_type=PriceType.LAST_PRICE,
size=10
)
# With time filters (optional)# kline_params = GetKLineParams(# contract_id="10000001",# kline_type=KlineType.HOUR_1,# price_type=PriceType.LAST_PRICE,# size=20,# filter_begin_kline_time_inclusive="1640995200000", # Start timestamp# filter_end_kline_time_exclusive="1640998800000" # End timestamp# )klines=awaitclient.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get order book depth for ETHUSDT (contract ID: 10000002)depth_params=GetOrderBookDepthParams(
contract_id="10000002", # ETHUSDTlimit=10
)
depth=awaitclient.quote.get_order_book_depth(depth_params)
print(f"Order book: {depth}")

Account Management

# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Positions: {positions}")
# Get position transactionsfromedgex_sdkimportGetPositionTransactionPageParamstx_params=GetPositionTransactionPageParams(
size="10",
offset_data=""
)
transactions=awaitclient.account.get_position_transaction_page(tx_params)
print(f"Transactions: {transactions}")

Order Management

fromedgex_sdkimportOrderSide, CreateOrderParams, CancelOrderParams# Create a limit order for BNBUSDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNBUSDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Get maximum order size for BNBUSDTmax_size=awaitclient.get_max_order_size("10000004", 600.00)
print(f"Max order size: {max_size}")
# Cancel an ordercancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")

Contract IDs

EdgeX uses numeric contract IDs instead of symbol-based identifiers. Here are some common contract mappings:

Contract IDSymbolTick Size
10000001BTCUSDT0.1
10000002ETHUSDT0.01
10000003SOLUSDT0.01

To get the complete list of available contracts:

metadata=awaitclient.get_metadata()
contracts=metadata.get("data", {}).get("contractList", [])
forcontractincontracts:
print(f"ID: {contract['contractId']} - {contract['contractName']}")

For more detailed examples, please refer to the examples directory.

Testing

The SDK includes comprehensive test coverage with multiple test suites:

Unit Tests

# Run unit tests (no API credentials required)
python -m pytest tests/test_client.py tests/test_eip712_signing.py -v

Public API Tests

# Run public endpoint tests (no authentication required)
python run_public_tests.py

Mock Integration Tests

# Run mock tests (test structure without real API calls)
python run_mock_tests.py

Full Integration Tests

# Run full integration tests (requires real API credentials)
python run_integration_tests.py

All Tests

# Run all available tests
python run_tests.py

For more testing information, see TESTING.md.

Environment Variables

For testing and development, you can set the following environment variables or create a .env file:

# API Configuration
EDGEX_BASE_URL=https://edgex-prod-v2.edgex.exchange
EDGEX_ASSET_BASE_URL=https://spot.edgex.exchange
EDGEX_WS_URL=wss://edgex-quote-prod-v2.edgex.exchange
# Account Credentials
EDGEX_ACCOUNT_ID=12345
EDGEX_TRADING_PRIVATE_KEY=your-trading-private-key

Then load them in your code:

importosfromdotenvimportload_dotenvfromedgex_sdkimportClient# Load environment variables from .env fileload_dotenv()
client=Client(
base_url=os.getenv("EDGEX_BASE_URL"),
asset_base_url=os.getenv("EDGEX_ASSET_BASE_URL"),
account_id=int(os.getenv("EDGEX_ACCOUNT_ID")),
trading_private_key=os.getenv("EDGEX_TRADING_PRIVATE_KEY")
)

Documentation

For detailed API documentation, please refer to the EdgeX API documentation.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin feature/my-new-feature)
  5. Create a new Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

30 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

EdgeX Python SDK

A Python SDK for interacting with the EdgeX Exchange API. This SDK provides a comprehensive interface to the EdgeX API, allowing you to easily integrate EdgeX functionality into your Python applications.

Branch Status

The main branch contains the current EdgeX V2 SDK. The legacy V1 SDK has moved to the v1 branch and is deprecated. New integrations should use V2.

Features

  • Complete API Coverage: Access all EdgeX API endpoints
  • WebSocket Support: Real-time data streaming
  • Async/Await: Modern Python async interface
  • Type Hints: Comprehensive type annotations for better IDE support
  • Error Handling: Proper error handling and validation
  • Pagination: Support for paginated API endpoints
  • Authentication: Automatic request signing

Installation

From PyPI

pip install edgex-python-sdk

Version Compatibility

edgex-python-sdk on PyPI has two incompatible API generations:

  • <= 0.3.0: contract v1 API SDK
  • >= 2.0.0: contract v2 API SDK

These two generations are not backward compatible. Please choose the package version based on the API generation you are integrating with.

Examples:

# Contract v1 API SDK
pip install "edgex-python-sdk<=0.3.0"# Contract v2 API SDK
pip install "edgex-python-sdk>=2.0.0"

From Source

git clone https://github.com/edgex-Tech/edgex-python-sdk.git
cd edgex-python-sdk
pip install -e .

Using Requirements Files

For production use:

pip install -r requirements.txt

For development (includes testing and linting tools):

pip install -r requirements-dev.txt

Virtual Environment (Recommended)

It's recommended to use a virtual environment:

# Create virtual environment
python3 -m venv venv
# Activate virtual environmentsource venv/bin/activate # On Windows: venv\Scripts\activate# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .

Quick Start

importasyncioimportosfromedgex_sdkimportClient, OrderSideasyncdefmain():
# Create a new clientclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345, # Your account IDtrading_private_key="your-trading-private-key"# Your trading private key
)
# Get server timeserver_time=awaitclient.get_server_time()
print(f"Server Time: {server_time}")
# Get exchange metadatametadata=awaitclient.get_metadata()
print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}")
# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account Assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Account Positions: {positions}")
# Get 24-hour market data for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"BNB2USDT Price: {quote}")
# Create a limit order (uncomment to place real order)# order = await client.create_limit_order(# contract_id="10000004", # BNB2USDT# size="0.01",# price="600.00",# side=OrderSide.BUY# )# print(f"Order created: {order}")# Run the async functionasyncio.run(main())

Architecture

The SDK is organized into modules that correspond to the EdgeX API structure:

edgex_sdk/
├── __init__.py
├── client.py # Main client
├── account/ # Account API
├── funding/ # Funding API
├── internal/ # Internal utilities
├── metadata/ # Metadata API
├── order/ # Order API
├── quote/ # Quote API
├── transfer/ # Transfer API
├── unified_asset/ # Unified asset withdraw / transfer flows
├── cctp/ # Circle CCTP bridge helpers
└── ws/ # WebSocket API

Available APIs

The SDK currently supports the following API modules:

  • Account API: Manage account positions, retrieve position transactions, and handle collateral transactions

    • Get account positions
    • Get position by contract ID
    • Get position transaction history
    • Get collateral transaction details
    • Update leverage settings
  • Unified Asset API: Current market-maker withdrawal flow

    • Build Spot / Perp V2 withdraw attempts with raw token amounts
    • Get fee via getFeeByAssetFlow
    • Sign server-provided EIP-712 payloads
    • Submit flows through submitAssetFlow
  • CCTP Bridge Helpers: Edge Mainnet USDC bridge support

    • Quote Circle CCTP fast-transfer fees
    • Build Edge depositForBurn bridge transactions
    • Fetch Iris V2 attestations
    • Build / submit Ethereum receiveMessage claim transactions
  • Funding API: Manage funding operations and account balance

    • Handle funding transactions
    • Manage funding accounts
    • Get funding transaction history
  • Metadata API: Access exchange system information

    • Get server time
    • Get exchange metadata (trading pairs, contracts, etc.)
  • Order API: Comprehensive order management

    • Create and cancel orders
    • Get active orders
    • Get order fill transactions
    • Calculate maximum order sizes
    • Manage order history
  • Quote API: Access market data and pricing

    • Get multi-contract K-line data
    • Get order book depth
    • Access real-time market quotes
    • Get 24-hour ticker data
  • Transfer API: Handle asset transfers

    • Create transfer out orders
    • Get transfer records (in/out)
    • Check available withdrawal amounts
    • Manage transfer history
  • WebSocket API: Real-time data streaming

    • Market data (tickers, K-lines, order book, trades)
    • Account updates
    • Order updates
    • Position updates

WebSocket Support

The SDK provides a WebSocket manager for handling real-time data:

importasynciofromedgex_sdkimportWebSocketManagerasyncdefmain():
# Create a WebSocket managerws_manager=WebSocketManager(
base_url="wss://edgex-quote-prod-v2.edgex.exchange",
account_id=12345,
api_key="",
api_passphrase="",
api_secret=""
)
# Define message handlersdefticker_handler(message):
print(f"Ticker Update: {message}")
defkline_handler(message):
print(f"K-line Update: {message}")
# Connect to public WebSocket for market dataws_manager.connect_public()
# Subscribe to real-time updates for BNB2USDT (contract ID: 10000004)ws_manager.subscribe_ticker("10000004", ticker_handler)
ws_manager.subscribe_kline("10000004", "1m", kline_handler)
# Connect to private WebSocket for account updatesws_manager.connect_private()
# Wait for updatesawaitasyncio.sleep(30)
# Disconnect all connectionsws_manager.disconnect_all()
asyncio.run(main())

Signing

The v2 SDK uses different keys for different signing flows:

  • trading private key: EIP-712 signing for order placement and setMarginMode
  • wallet private key: unified-asset withdrawal / transfer signing

Unified-asset withdrawals sign the EIP-712 payload returned by getEIP712Data and submit a 0x-prefixed signature. There is no StarkEx signing adapter in the v2 path.

Current Withdrawal Path

fromedgex_sdkimportClient, CreateWithdrawParamsclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345,
api_key="...",
api_passphrase="...",
api_secret="...",
wallet_private_key="...",
)
result=awaitclient.create_withdraw(CreateWithdrawParams(
amount_raw="1000000",
user_address="0xYourWallet",
profile="mainnet-usdc",
))

Use source="perpv2" and the Perp V2 account ID in source_account to reuse the same unified-asset withdrawal path for Perp V2.

Error Handling

The SDK provides proper error handling for API requests:

importasynciofromedgex_sdkimportClient, OrderSideasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
try:
# Create a limit order for BNB2USDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNB2USDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Cancel the orderfromedgex_sdkimportCancelOrderParamscancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")
exceptValueErrorase:
print(f"Failed to create/cancel order: {str(e)}")
exceptExceptionase:
print(f"Unexpected error: {str(e)}")
asyncio.run(main())

Pagination

Many API endpoints support pagination:

importasynciofromedgex_sdkimportClient, GetActiveOrderParamsasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
# Create pagination parametersparams=GetActiveOrderParams(
size="10",
offset_data=""
)
# Get active ordersorders=awaitclient.get_active_orders(params)
print(f"Active orders: {orders}")
# Get next page if availableiforders.get("data", {}).get("hasNext"):
params.offset_data=orders.get("data", {}).get("offsetData")
next_page=awaitclient.get_active_orders(params)
print(f"Next page: {next_page}")
asyncio.run(main())

API Examples

Market Data

Available Enums

KlineType (K-line intervals):

  • KlineType.MINUTE_1, KlineType.MINUTE_5, KlineType.MINUTE_15, KlineType.MINUTE_30
  • KlineType.HOUR_1, KlineType.HOUR_2, KlineType.HOUR_4, KlineType.HOUR_6, KlineType.HOUR_8, KlineType.HOUR_12
  • KlineType.DAY_1, KlineType.WEEK_1, KlineType.MONTH_1

PriceType (price types):

  • PriceType.LAST_PRICE (default) - Latest market price
  • PriceType.INDEX_PRICE - Index price
  • PriceType.ORACLE_PRICE - Oracle price
  • PriceType.ASK1_PRICE - Best ask price
  • PriceType.BID1_PRICE - Best bid price
  • PriceType.OPEN_INTEREST - Open interest
fromedgex_sdkimportClient, GetKLineParams, GetOrderBookDepthParams, KlineType, PriceType# Get 24-hour market quotes for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"Current price: {quote}")
# Get K-line data for BTCUSDT (contract ID: 10000001)kline_params=GetKLineParams(
contract_id="10000001", # BTCUSDTkline_type=KlineType.MINUTE_1,
price_type=PriceType.LAST_PRICE,
size=10
)
# With time filters (optional)# kline_params = GetKLineParams(# contract_id="10000001",# kline_type=KlineType.HOUR_1,# price_type=PriceType.LAST_PRICE,# size=20,# filter_begin_kline_time_inclusive="1640995200000", # Start timestamp# filter_end_kline_time_exclusive="1640998800000" # End timestamp# )klines=awaitclient.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get order book depth for ETHUSDT (contract ID: 10000002)depth_params=GetOrderBookDepthParams(
contract_id="10000002", # ETHUSDTlimit=10
)
depth=awaitclient.quote.get_order_book_depth(depth_params)
print(f"Order book: {depth}")

Account Management

# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Positions: {positions}")
# Get position transactionsfromedgex_sdkimportGetPositionTransactionPageParamstx_params=GetPositionTransactionPageParams(
size="10",
offset_data=""
)
transactions=awaitclient.account.get_position_transaction_page(tx_params)
print(f"Transactions: {transactions}")

Order Management

fromedgex_sdkimportOrderSide, CreateOrderParams, CancelOrderParams# Create a limit order for BNBUSDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNBUSDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Get maximum order size for BNBUSDTmax_size=awaitclient.get_max_order_size("10000004", 600.00)
print(f"Max order size: {max_size}")
# Cancel an ordercancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")

Contract IDs

EdgeX uses numeric contract IDs instead of symbol-based identifiers. Here are some common contract mappings:

Contract IDSymbolTick Size
10000001BTCUSDT0.1
10000002ETHUSDT0.01
10000003SOLUSDT0.01

To get the complete list of available contracts:

metadata=awaitclient.get_metadata()
contracts=metadata.get("data", {}).get("contractList", [])
forcontractincontracts:
print(f"ID: {contract['contractId']} - {contract['contractName']}")

For more detailed examples, please refer to the examples directory.

Testing

The SDK includes comprehensive test coverage with multiple test suites:

Unit Tests

# Run unit tests (no API credentials required)
python -m pytest tests/test_client.py tests/test_eip712_signing.py -v

Public API Tests

# Run public endpoint tests (no authentication required)
python run_public_tests.py

Mock Integration Tests

# Run mock tests (test structure without real API calls)
python run_mock_tests.py

Full Integration Tests

# Run full integration tests (requires real API credentials)
python run_integration_tests.py

All Tests

# Run all available tests
python run_tests.py

For more testing information, see TESTING.md.

Environment Variables

For testing and development, you can set the following environment variables or create a .env file:

# API Configuration
EDGEX_BASE_URL=https://edgex-prod-v2.edgex.exchange
EDGEX_ASSET_BASE_URL=https://spot.edgex.exchange
EDGEX_WS_URL=wss://edgex-quote-prod-v2.edgex.exchange
# Account Credentials
EDGEX_ACCOUNT_ID=12345
EDGEX_TRADING_PRIVATE_KEY=your-trading-private-key

Then load them in your code:

importosfromdotenvimportload_dotenvfromedgex_sdkimportClient# Load environment variables from .env fileload_dotenv()
client=Client(
base_url=os.getenv("EDGEX_BASE_URL"),
asset_base_url=os.getenv("EDGEX_ASSET_BASE_URL"),
account_id=int(os.getenv("EDGEX_ACCOUNT_ID")),
trading_private_key=os.getenv("EDGEX_TRADING_PRIVATE_KEY")
)

Documentation

For detailed API documentation, please refer to the EdgeX API documentation.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin feature/my-new-feature)
  5. Create a new Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

30 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

EdgeX Python SDK

A Python SDK for interacting with the EdgeX Exchange API. This SDK provides a comprehensive interface to the EdgeX API, allowing you to easily integrate EdgeX functionality into your Python applications.

Branch Status

The main branch contains the current EdgeX V2 SDK. The legacy V1 SDK has moved to the v1 branch and is deprecated. New integrations should use V2.

Features

  • Complete API Coverage: Access all EdgeX API endpoints
  • WebSocket Support: Real-time data streaming
  • Async/Await: Modern Python async interface
  • Type Hints: Comprehensive type annotations for better IDE support
  • Error Handling: Proper error handling and validation
  • Pagination: Support for paginated API endpoints
  • Authentication: Automatic request signing

Installation

From PyPI

pip install edgex-python-sdk

Version Compatibility

edgex-python-sdk on PyPI has two incompatible API generations:

  • <= 0.3.0: contract v1 API SDK
  • >= 2.0.0: contract v2 API SDK

These two generations are not backward compatible. Please choose the package version based on the API generation you are integrating with.

Examples:

# Contract v1 API SDK
pip install "edgex-python-sdk<=0.3.0"# Contract v2 API SDK
pip install "edgex-python-sdk>=2.0.0"

From Source

git clone https://github.com/edgex-Tech/edgex-python-sdk.git
cd edgex-python-sdk
pip install -e .

Using Requirements Files

For production use:

pip install -r requirements.txt

For development (includes testing and linting tools):

pip install -r requirements-dev.txt

Virtual Environment (Recommended)

It's recommended to use a virtual environment:

# Create virtual environment
python3 -m venv venv
# Activate virtual environmentsource venv/bin/activate # On Windows: venv\Scripts\activate# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .

Quick Start

importasyncioimportosfromedgex_sdkimportClient, OrderSideasyncdefmain():
# Create a new clientclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345, # Your account IDtrading_private_key="your-trading-private-key"# Your trading private key
)
# Get server timeserver_time=awaitclient.get_server_time()
print(f"Server Time: {server_time}")
# Get exchange metadatametadata=awaitclient.get_metadata()
print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}")
# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account Assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Account Positions: {positions}")
# Get 24-hour market data for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"BNB2USDT Price: {quote}")
# Create a limit order (uncomment to place real order)# order = await client.create_limit_order(# contract_id="10000004", # BNB2USDT# size="0.01",# price="600.00",# side=OrderSide.BUY# )# print(f"Order created: {order}")# Run the async functionasyncio.run(main())

Architecture

The SDK is organized into modules that correspond to the EdgeX API structure:

edgex_sdk/
├── __init__.py
├── client.py # Main client
├── account/ # Account API
├── funding/ # Funding API
├── internal/ # Internal utilities
├── metadata/ # Metadata API
├── order/ # Order API
├── quote/ # Quote API
├── transfer/ # Transfer API
├── unified_asset/ # Unified asset withdraw / transfer flows
├── cctp/ # Circle CCTP bridge helpers
└── ws/ # WebSocket API

Available APIs

The SDK currently supports the following API modules:

  • Account API: Manage account positions, retrieve position transactions, and handle collateral transactions

    • Get account positions
    • Get position by contract ID
    • Get position transaction history
    • Get collateral transaction details
    • Update leverage settings
  • Unified Asset API: Current market-maker withdrawal flow

    • Build Spot / Perp V2 withdraw attempts with raw token amounts
    • Get fee via getFeeByAssetFlow
    • Sign server-provided EIP-712 payloads
    • Submit flows through submitAssetFlow
  • CCTP Bridge Helpers: Edge Mainnet USDC bridge support

    • Quote Circle CCTP fast-transfer fees
    • Build Edge depositForBurn bridge transactions
    • Fetch Iris V2 attestations
    • Build / submit Ethereum receiveMessage claim transactions
  • Funding API: Manage funding operations and account balance

    • Handle funding transactions
    • Manage funding accounts
    • Get funding transaction history
  • Metadata API: Access exchange system information

    • Get server time
    • Get exchange metadata (trading pairs, contracts, etc.)
  • Order API: Comprehensive order management

    • Create and cancel orders
    • Get active orders
    • Get order fill transactions
    • Calculate maximum order sizes
    • Manage order history
  • Quote API: Access market data and pricing

    • Get multi-contract K-line data
    • Get order book depth
    • Access real-time market quotes
    • Get 24-hour ticker data
  • Transfer API: Handle asset transfers

    • Create transfer out orders
    • Get transfer records (in/out)
    • Check available withdrawal amounts
    • Manage transfer history
  • WebSocket API: Real-time data streaming

    • Market data (tickers, K-lines, order book, trades)
    • Account updates
    • Order updates
    • Position updates

WebSocket Support

The SDK provides a WebSocket manager for handling real-time data:

importasynciofromedgex_sdkimportWebSocketManagerasyncdefmain():
# Create a WebSocket managerws_manager=WebSocketManager(
base_url="wss://edgex-quote-prod-v2.edgex.exchange",
account_id=12345,
api_key="",
api_passphrase="",
api_secret=""
)
# Define message handlersdefticker_handler(message):
print(f"Ticker Update: {message}")
defkline_handler(message):
print(f"K-line Update: {message}")
# Connect to public WebSocket for market dataws_manager.connect_public()
# Subscribe to real-time updates for BNB2USDT (contract ID: 10000004)ws_manager.subscribe_ticker("10000004", ticker_handler)
ws_manager.subscribe_kline("10000004", "1m", kline_handler)
# Connect to private WebSocket for account updatesws_manager.connect_private()
# Wait for updatesawaitasyncio.sleep(30)
# Disconnect all connectionsws_manager.disconnect_all()
asyncio.run(main())

Signing

The v2 SDK uses different keys for different signing flows:

  • trading private key: EIP-712 signing for order placement and setMarginMode
  • wallet private key: unified-asset withdrawal / transfer signing

Unified-asset withdrawals sign the EIP-712 payload returned by getEIP712Data and submit a 0x-prefixed signature. There is no StarkEx signing adapter in the v2 path.

Current Withdrawal Path

fromedgex_sdkimportClient, CreateWithdrawParamsclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345,
api_key="...",
api_passphrase="...",
api_secret="...",
wallet_private_key="...",
)
result=awaitclient.create_withdraw(CreateWithdrawParams(
amount_raw="1000000",
user_address="0xYourWallet",
profile="mainnet-usdc",
))

Use source="perpv2" and the Perp V2 account ID in source_account to reuse the same unified-asset withdrawal path for Perp V2.

Error Handling

The SDK provides proper error handling for API requests:

importasynciofromedgex_sdkimportClient, OrderSideasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
try:
# Create a limit order for BNB2USDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNB2USDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Cancel the orderfromedgex_sdkimportCancelOrderParamscancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")
exceptValueErrorase:
print(f"Failed to create/cancel order: {str(e)}")
exceptExceptionase:
print(f"Unexpected error: {str(e)}")
asyncio.run(main())

Pagination

Many API endpoints support pagination:

importasynciofromedgex_sdkimportClient, GetActiveOrderParamsasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
# Create pagination parametersparams=GetActiveOrderParams(
size="10",
offset_data=""
)
# Get active ordersorders=awaitclient.get_active_orders(params)
print(f"Active orders: {orders}")
# Get next page if availableiforders.get("data", {}).get("hasNext"):
params.offset_data=orders.get("data", {}).get("offsetData")
next_page=awaitclient.get_active_orders(params)
print(f"Next page: {next_page}")
asyncio.run(main())

API Examples

Market Data

Available Enums

KlineType (K-line intervals):

  • KlineType.MINUTE_1, KlineType.MINUTE_5, KlineType.MINUTE_15, KlineType.MINUTE_30
  • KlineType.HOUR_1, KlineType.HOUR_2, KlineType.HOUR_4, KlineType.HOUR_6, KlineType.HOUR_8, KlineType.HOUR_12
  • KlineType.DAY_1, KlineType.WEEK_1, KlineType.MONTH_1

PriceType (price types):

  • PriceType.LAST_PRICE (default) - Latest market price
  • PriceType.INDEX_PRICE - Index price
  • PriceType.ORACLE_PRICE - Oracle price
  • PriceType.ASK1_PRICE - Best ask price
  • PriceType.BID1_PRICE - Best bid price
  • PriceType.OPEN_INTEREST - Open interest
fromedgex_sdkimportClient, GetKLineParams, GetOrderBookDepthParams, KlineType, PriceType# Get 24-hour market quotes for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"Current price: {quote}")
# Get K-line data for BTCUSDT (contract ID: 10000001)kline_params=GetKLineParams(
contract_id="10000001", # BTCUSDTkline_type=KlineType.MINUTE_1,
price_type=PriceType.LAST_PRICE,
size=10
)
# With time filters (optional)# kline_params = GetKLineParams(# contract_id="10000001",# kline_type=KlineType.HOUR_1,# price_type=PriceType.LAST_PRICE,# size=20,# filter_begin_kline_time_inclusive="1640995200000", # Start timestamp# filter_end_kline_time_exclusive="1640998800000" # End timestamp# )klines=awaitclient.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get order book depth for ETHUSDT (contract ID: 10000002)depth_params=GetOrderBookDepthParams(
contract_id="10000002", # ETHUSDTlimit=10
)
depth=awaitclient.quote.get_order_book_depth(depth_params)
print(f"Order book: {depth}")

Account Management

# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Positions: {positions}")
# Get position transactionsfromedgex_sdkimportGetPositionTransactionPageParamstx_params=GetPositionTransactionPageParams(
size="10",
offset_data=""
)
transactions=awaitclient.account.get_position_transaction_page(tx_params)
print(f"Transactions: {transactions}")

Order Management

fromedgex_sdkimportOrderSide, CreateOrderParams, CancelOrderParams# Create a limit order for BNBUSDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNBUSDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Get maximum order size for BNBUSDTmax_size=awaitclient.get_max_order_size("10000004", 600.00)
print(f"Max order size: {max_size}")
# Cancel an ordercancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")

Contract IDs

EdgeX uses numeric contract IDs instead of symbol-based identifiers. Here are some common contract mappings:

Contract IDSymbolTick Size
10000001BTCUSDT0.1
10000002ETHUSDT0.01
10000003SOLUSDT0.01

To get the complete list of available contracts:

metadata=awaitclient.get_metadata()
contracts=metadata.get("data", {}).get("contractList", [])
forcontractincontracts:
print(f"ID: {contract['contractId']} - {contract['contractName']}")

For more detailed examples, please refer to the examples directory.

Testing

The SDK includes comprehensive test coverage with multiple test suites:

Unit Tests

# Run unit tests (no API credentials required)
python -m pytest tests/test_client.py tests/test_eip712_signing.py -v

Public API Tests

# Run public endpoint tests (no authentication required)
python run_public_tests.py

Mock Integration Tests

# Run mock tests (test structure without real API calls)
python run_mock_tests.py

Full Integration Tests

# Run full integration tests (requires real API credentials)
python run_integration_tests.py

All Tests

# Run all available tests
python run_tests.py

For more testing information, see TESTING.md.

Environment Variables

For testing and development, you can set the following environment variables or create a .env file:

# API Configuration
EDGEX_BASE_URL=https://edgex-prod-v2.edgex.exchange
EDGEX_ASSET_BASE_URL=https://spot.edgex.exchange
EDGEX_WS_URL=wss://edgex-quote-prod-v2.edgex.exchange
# Account Credentials
EDGEX_ACCOUNT_ID=12345
EDGEX_TRADING_PRIVATE_KEY=your-trading-private-key

Then load them in your code:

importosfromdotenvimportload_dotenvfromedgex_sdkimportClient# Load environment variables from .env fileload_dotenv()
client=Client(
base_url=os.getenv("EDGEX_BASE_URL"),
asset_base_url=os.getenv("EDGEX_ASSET_BASE_URL"),
account_id=int(os.getenv("EDGEX_ACCOUNT_ID")),
trading_private_key=os.getenv("EDGEX_TRADING_PRIVATE_KEY")
)

Documentation

For detailed API documentation, please refer to the EdgeX API documentation.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin feature/my-new-feature)
  5. Create a new Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

30 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

EdgeX Python SDK

A Python SDK for interacting with the EdgeX Exchange API. This SDK provides a comprehensive interface to the EdgeX API, allowing you to easily integrate EdgeX functionality into your Python applications.

Branch Status

The main branch contains the current EdgeX V2 SDK. The legacy V1 SDK has moved to the v1 branch and is deprecated. New integrations should use V2.

Features

  • Complete API Coverage: Access all EdgeX API endpoints
  • WebSocket Support: Real-time data streaming
  • Async/Await: Modern Python async interface
  • Type Hints: Comprehensive type annotations for better IDE support
  • Error Handling: Proper error handling and validation
  • Pagination: Support for paginated API endpoints
  • Authentication: Automatic request signing

Installation

From PyPI

pip install edgex-python-sdk

Version Compatibility

edgex-python-sdk on PyPI has two incompatible API generations:

  • <= 0.3.0: contract v1 API SDK
  • >= 2.0.0: contract v2 API SDK

These two generations are not backward compatible. Please choose the package version based on the API generation you are integrating with.

Examples:

# Contract v1 API SDK
pip install "edgex-python-sdk<=0.3.0"# Contract v2 API SDK
pip install "edgex-python-sdk>=2.0.0"

From Source

git clone https://github.com/edgex-Tech/edgex-python-sdk.git
cd edgex-python-sdk
pip install -e .

Using Requirements Files

For production use:

pip install -r requirements.txt

For development (includes testing and linting tools):

pip install -r requirements-dev.txt

Virtual Environment (Recommended)

It's recommended to use a virtual environment:

# Create virtual environment
python3 -m venv venv
# Activate virtual environmentsource venv/bin/activate # On Windows: venv\Scripts\activate# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .

Quick Start

importasyncioimportosfromedgex_sdkimportClient, OrderSideasyncdefmain():
# Create a new clientclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345, # Your account IDtrading_private_key="your-trading-private-key"# Your trading private key
)
# Get server timeserver_time=awaitclient.get_server_time()
print(f"Server Time: {server_time}")
# Get exchange metadatametadata=awaitclient.get_metadata()
print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}")
# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account Assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Account Positions: {positions}")
# Get 24-hour market data for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"BNB2USDT Price: {quote}")
# Create a limit order (uncomment to place real order)# order = await client.create_limit_order(# contract_id="10000004", # BNB2USDT# size="0.01",# price="600.00",# side=OrderSide.BUY# )# print(f"Order created: {order}")# Run the async functionasyncio.run(main())

Architecture

The SDK is organized into modules that correspond to the EdgeX API structure:

edgex_sdk/
├── __init__.py
├── client.py # Main client
├── account/ # Account API
├── funding/ # Funding API
├── internal/ # Internal utilities
├── metadata/ # Metadata API
├── order/ # Order API
├── quote/ # Quote API
├── transfer/ # Transfer API
├── unified_asset/ # Unified asset withdraw / transfer flows
├── cctp/ # Circle CCTP bridge helpers
└── ws/ # WebSocket API

Available APIs

The SDK currently supports the following API modules:

  • Account API: Manage account positions, retrieve position transactions, and handle collateral transactions

    • Get account positions
    • Get position by contract ID
    • Get position transaction history
    • Get collateral transaction details
    • Update leverage settings
  • Unified Asset API: Current market-maker withdrawal flow

    • Build Spot / Perp V2 withdraw attempts with raw token amounts
    • Get fee via getFeeByAssetFlow
    • Sign server-provided EIP-712 payloads
    • Submit flows through submitAssetFlow
  • CCTP Bridge Helpers: Edge Mainnet USDC bridge support

    • Quote Circle CCTP fast-transfer fees
    • Build Edge depositForBurn bridge transactions
    • Fetch Iris V2 attestations
    • Build / submit Ethereum receiveMessage claim transactions
  • Funding API: Manage funding operations and account balance

    • Handle funding transactions
    • Manage funding accounts
    • Get funding transaction history
  • Metadata API: Access exchange system information

    • Get server time
    • Get exchange metadata (trading pairs, contracts, etc.)
  • Order API: Comprehensive order management

    • Create and cancel orders
    • Get active orders
    • Get order fill transactions
    • Calculate maximum order sizes
    • Manage order history
  • Quote API: Access market data and pricing

    • Get multi-contract K-line data
    • Get order book depth
    • Access real-time market quotes
    • Get 24-hour ticker data
  • Transfer API: Handle asset transfers

    • Create transfer out orders
    • Get transfer records (in/out)
    • Check available withdrawal amounts
    • Manage transfer history
  • WebSocket API: Real-time data streaming

    • Market data (tickers, K-lines, order book, trades)
    • Account updates
    • Order updates
    • Position updates

WebSocket Support

The SDK provides a WebSocket manager for handling real-time data:

importasynciofromedgex_sdkimportWebSocketManagerasyncdefmain():
# Create a WebSocket managerws_manager=WebSocketManager(
base_url="wss://edgex-quote-prod-v2.edgex.exchange",
account_id=12345,
api_key="",
api_passphrase="",
api_secret=""
)
# Define message handlersdefticker_handler(message):
print(f"Ticker Update: {message}")
defkline_handler(message):
print(f"K-line Update: {message}")
# Connect to public WebSocket for market dataws_manager.connect_public()
# Subscribe to real-time updates for BNB2USDT (contract ID: 10000004)ws_manager.subscribe_ticker("10000004", ticker_handler)
ws_manager.subscribe_kline("10000004", "1m", kline_handler)
# Connect to private WebSocket for account updatesws_manager.connect_private()
# Wait for updatesawaitasyncio.sleep(30)
# Disconnect all connectionsws_manager.disconnect_all()
asyncio.run(main())

Signing

The v2 SDK uses different keys for different signing flows:

  • trading private key: EIP-712 signing for order placement and setMarginMode
  • wallet private key: unified-asset withdrawal / transfer signing

Unified-asset withdrawals sign the EIP-712 payload returned by getEIP712Data and submit a 0x-prefixed signature. There is no StarkEx signing adapter in the v2 path.

Current Withdrawal Path

fromedgex_sdkimportClient, CreateWithdrawParamsclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345,
api_key="...",
api_passphrase="...",
api_secret="...",
wallet_private_key="...",
)
result=awaitclient.create_withdraw(CreateWithdrawParams(
amount_raw="1000000",
user_address="0xYourWallet",
profile="mainnet-usdc",
))

Use source="perpv2" and the Perp V2 account ID in source_account to reuse the same unified-asset withdrawal path for Perp V2.

Error Handling

The SDK provides proper error handling for API requests:

importasynciofromedgex_sdkimportClient, OrderSideasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
try:
# Create a limit order for BNB2USDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNB2USDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Cancel the orderfromedgex_sdkimportCancelOrderParamscancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")
exceptValueErrorase:
print(f"Failed to create/cancel order: {str(e)}")
exceptExceptionase:
print(f"Unexpected error: {str(e)}")
asyncio.run(main())

Pagination

Many API endpoints support pagination:

importasynciofromedgex_sdkimportClient, GetActiveOrderParamsasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
# Create pagination parametersparams=GetActiveOrderParams(
size="10",
offset_data=""
)
# Get active ordersorders=awaitclient.get_active_orders(params)
print(f"Active orders: {orders}")
# Get next page if availableiforders.get("data", {}).get("hasNext"):
params.offset_data=orders.get("data", {}).get("offsetData")
next_page=awaitclient.get_active_orders(params)
print(f"Next page: {next_page}")
asyncio.run(main())

API Examples

Market Data

Available Enums

KlineType (K-line intervals):

  • KlineType.MINUTE_1, KlineType.MINUTE_5, KlineType.MINUTE_15, KlineType.MINUTE_30
  • KlineType.HOUR_1, KlineType.HOUR_2, KlineType.HOUR_4, KlineType.HOUR_6, KlineType.HOUR_8, KlineType.HOUR_12
  • KlineType.DAY_1, KlineType.WEEK_1, KlineType.MONTH_1

PriceType (price types):

  • PriceType.LAST_PRICE (default) - Latest market price
  • PriceType.INDEX_PRICE - Index price
  • PriceType.ORACLE_PRICE - Oracle price
  • PriceType.ASK1_PRICE - Best ask price
  • PriceType.BID1_PRICE - Best bid price
  • PriceType.OPEN_INTEREST - Open interest
fromedgex_sdkimportClient, GetKLineParams, GetOrderBookDepthParams, KlineType, PriceType# Get 24-hour market quotes for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"Current price: {quote}")
# Get K-line data for BTCUSDT (contract ID: 10000001)kline_params=GetKLineParams(
contract_id="10000001", # BTCUSDTkline_type=KlineType.MINUTE_1,
price_type=PriceType.LAST_PRICE,
size=10
)
# With time filters (optional)# kline_params = GetKLineParams(# contract_id="10000001",# kline_type=KlineType.HOUR_1,# price_type=PriceType.LAST_PRICE,# size=20,# filter_begin_kline_time_inclusive="1640995200000", # Start timestamp# filter_end_kline_time_exclusive="1640998800000" # End timestamp# )klines=awaitclient.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get order book depth for ETHUSDT (contract ID: 10000002)depth_params=GetOrderBookDepthParams(
contract_id="10000002", # ETHUSDTlimit=10
)
depth=awaitclient.quote.get_order_book_depth(depth_params)
print(f"Order book: {depth}")

Account Management

# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Positions: {positions}")
# Get position transactionsfromedgex_sdkimportGetPositionTransactionPageParamstx_params=GetPositionTransactionPageParams(
size="10",
offset_data=""
)
transactions=awaitclient.account.get_position_transaction_page(tx_params)
print(f"Transactions: {transactions}")

Order Management

fromedgex_sdkimportOrderSide, CreateOrderParams, CancelOrderParams# Create a limit order for BNBUSDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNBUSDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Get maximum order size for BNBUSDTmax_size=awaitclient.get_max_order_size("10000004", 600.00)
print(f"Max order size: {max_size}")
# Cancel an ordercancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")

Contract IDs

EdgeX uses numeric contract IDs instead of symbol-based identifiers. Here are some common contract mappings:

Contract IDSymbolTick Size
10000001BTCUSDT0.1
10000002ETHUSDT0.01
10000003SOLUSDT0.01

To get the complete list of available contracts:

metadata=awaitclient.get_metadata()
contracts=metadata.get("data", {}).get("contractList", [])
forcontractincontracts:
print(f"ID: {contract['contractId']} - {contract['contractName']}")

For more detailed examples, please refer to the examples directory.

Testing

The SDK includes comprehensive test coverage with multiple test suites:

Unit Tests

# Run unit tests (no API credentials required)
python -m pytest tests/test_client.py tests/test_eip712_signing.py -v

Public API Tests

# Run public endpoint tests (no authentication required)
python run_public_tests.py

Mock Integration Tests

# Run mock tests (test structure without real API calls)
python run_mock_tests.py

Full Integration Tests

# Run full integration tests (requires real API credentials)
python run_integration_tests.py

All Tests

# Run all available tests
python run_tests.py

For more testing information, see TESTING.md.

Environment Variables

For testing and development, you can set the following environment variables or create a .env file:

# API Configuration
EDGEX_BASE_URL=https://edgex-prod-v2.edgex.exchange
EDGEX_ASSET_BASE_URL=https://spot.edgex.exchange
EDGEX_WS_URL=wss://edgex-quote-prod-v2.edgex.exchange
# Account Credentials
EDGEX_ACCOUNT_ID=12345
EDGEX_TRADING_PRIVATE_KEY=your-trading-private-key

Then load them in your code:

importosfromdotenvimportload_dotenvfromedgex_sdkimportClient# Load environment variables from .env fileload_dotenv()
client=Client(
base_url=os.getenv("EDGEX_BASE_URL"),
asset_base_url=os.getenv("EDGEX_ASSET_BASE_URL"),
account_id=int(os.getenv("EDGEX_ACCOUNT_ID")),
trading_private_key=os.getenv("EDGEX_TRADING_PRIVATE_KEY")
)

Documentation

For detailed API documentation, please refer to the EdgeX API documentation.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin feature/my-new-feature)
  5. Create a new Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

30 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

EdgeX Python SDK

A Python SDK for interacting with the EdgeX Exchange API. This SDK provides a comprehensive interface to the EdgeX API, allowing you to easily integrate EdgeX functionality into your Python applications.

Branch Status

The main branch contains the current EdgeX V2 SDK. The legacy V1 SDK has moved to the v1 branch and is deprecated. New integrations should use V2.

Features

  • Complete API Coverage: Access all EdgeX API endpoints
  • WebSocket Support: Real-time data streaming
  • Async/Await: Modern Python async interface
  • Type Hints: Comprehensive type annotations for better IDE support
  • Error Handling: Proper error handling and validation
  • Pagination: Support for paginated API endpoints
  • Authentication: Automatic request signing

Installation

From PyPI

pip install edgex-python-sdk

Version Compatibility

edgex-python-sdk on PyPI has two incompatible API generations:

  • <= 0.3.0: contract v1 API SDK
  • >= 2.0.0: contract v2 API SDK

These two generations are not backward compatible. Please choose the package version based on the API generation you are integrating with.

Examples:

# Contract v1 API SDK
pip install "edgex-python-sdk<=0.3.0"# Contract v2 API SDK
pip install "edgex-python-sdk>=2.0.0"

From Source

git clone https://github.com/edgex-Tech/edgex-python-sdk.git
cd edgex-python-sdk
pip install -e .

Using Requirements Files

For production use:

pip install -r requirements.txt

For development (includes testing and linting tools):

pip install -r requirements-dev.txt

Virtual Environment (Recommended)

It's recommended to use a virtual environment:

# Create virtual environment
python3 -m venv venv
# Activate virtual environmentsource venv/bin/activate # On Windows: venv\Scripts\activate# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .

Quick Start

importasyncioimportosfromedgex_sdkimportClient, OrderSideasyncdefmain():
# Create a new clientclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345, # Your account IDtrading_private_key="your-trading-private-key"# Your trading private key
)
# Get server timeserver_time=awaitclient.get_server_time()
print(f"Server Time: {server_time}")
# Get exchange metadatametadata=awaitclient.get_metadata()
print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}")
# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account Assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Account Positions: {positions}")
# Get 24-hour market data for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"BNB2USDT Price: {quote}")
# Create a limit order (uncomment to place real order)# order = await client.create_limit_order(# contract_id="10000004", # BNB2USDT# size="0.01",# price="600.00",# side=OrderSide.BUY# )# print(f"Order created: {order}")# Run the async functionasyncio.run(main())

Architecture

The SDK is organized into modules that correspond to the EdgeX API structure:

edgex_sdk/
├── __init__.py
├── client.py # Main client
├── account/ # Account API
├── funding/ # Funding API
├── internal/ # Internal utilities
├── metadata/ # Metadata API
├── order/ # Order API
├── quote/ # Quote API
├── transfer/ # Transfer API
├── unified_asset/ # Unified asset withdraw / transfer flows
├── cctp/ # Circle CCTP bridge helpers
└── ws/ # WebSocket API

Available APIs

The SDK currently supports the following API modules:

  • Account API: Manage account positions, retrieve position transactions, and handle collateral transactions

    • Get account positions
    • Get position by contract ID
    • Get position transaction history
    • Get collateral transaction details
    • Update leverage settings
  • Unified Asset API: Current market-maker withdrawal flow

    • Build Spot / Perp V2 withdraw attempts with raw token amounts
    • Get fee via getFeeByAssetFlow
    • Sign server-provided EIP-712 payloads
    • Submit flows through submitAssetFlow
  • CCTP Bridge Helpers: Edge Mainnet USDC bridge support

    • Quote Circle CCTP fast-transfer fees
    • Build Edge depositForBurn bridge transactions
    • Fetch Iris V2 attestations
    • Build / submit Ethereum receiveMessage claim transactions
  • Funding API: Manage funding operations and account balance

    • Handle funding transactions
    • Manage funding accounts
    • Get funding transaction history
  • Metadata API: Access exchange system information

    • Get server time
    • Get exchange metadata (trading pairs, contracts, etc.)
  • Order API: Comprehensive order management

    • Create and cancel orders
    • Get active orders
    • Get order fill transactions
    • Calculate maximum order sizes
    • Manage order history
  • Quote API: Access market data and pricing

    • Get multi-contract K-line data
    • Get order book depth
    • Access real-time market quotes
    • Get 24-hour ticker data
  • Transfer API: Handle asset transfers

    • Create transfer out orders
    • Get transfer records (in/out)
    • Check available withdrawal amounts
    • Manage transfer history
  • WebSocket API: Real-time data streaming

    • Market data (tickers, K-lines, order book, trades)
    • Account updates
    • Order updates
    • Position updates

WebSocket Support

The SDK provides a WebSocket manager for handling real-time data:

importasynciofromedgex_sdkimportWebSocketManagerasyncdefmain():
# Create a WebSocket managerws_manager=WebSocketManager(
base_url="wss://edgex-quote-prod-v2.edgex.exchange",
account_id=12345,
api_key="",
api_passphrase="",
api_secret=""
)
# Define message handlersdefticker_handler(message):
print(f"Ticker Update: {message}")
defkline_handler(message):
print(f"K-line Update: {message}")
# Connect to public WebSocket for market dataws_manager.connect_public()
# Subscribe to real-time updates for BNB2USDT (contract ID: 10000004)ws_manager.subscribe_ticker("10000004", ticker_handler)
ws_manager.subscribe_kline("10000004", "1m", kline_handler)
# Connect to private WebSocket for account updatesws_manager.connect_private()
# Wait for updatesawaitasyncio.sleep(30)
# Disconnect all connectionsws_manager.disconnect_all()
asyncio.run(main())

Signing

The v2 SDK uses different keys for different signing flows:

  • trading private key: EIP-712 signing for order placement and setMarginMode
  • wallet private key: unified-asset withdrawal / transfer signing

Unified-asset withdrawals sign the EIP-712 payload returned by getEIP712Data and submit a 0x-prefixed signature. There is no StarkEx signing adapter in the v2 path.

Current Withdrawal Path

fromedgex_sdkimportClient, CreateWithdrawParamsclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345,
api_key="...",
api_passphrase="...",
api_secret="...",
wallet_private_key="...",
)
result=awaitclient.create_withdraw(CreateWithdrawParams(
amount_raw="1000000",
user_address="0xYourWallet",
profile="mainnet-usdc",
))

Use source="perpv2" and the Perp V2 account ID in source_account to reuse the same unified-asset withdrawal path for Perp V2.

Error Handling

The SDK provides proper error handling for API requests:

importasynciofromedgex_sdkimportClient, OrderSideasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
try:
# Create a limit order for BNB2USDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNB2USDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Cancel the orderfromedgex_sdkimportCancelOrderParamscancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")
exceptValueErrorase:
print(f"Failed to create/cancel order: {str(e)}")
exceptExceptionase:
print(f"Unexpected error: {str(e)}")
asyncio.run(main())

Pagination

Many API endpoints support pagination:

importasynciofromedgex_sdkimportClient, GetActiveOrderParamsasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
# Create pagination parametersparams=GetActiveOrderParams(
size="10",
offset_data=""
)
# Get active ordersorders=awaitclient.get_active_orders(params)
print(f"Active orders: {orders}")
# Get next page if availableiforders.get("data", {}).get("hasNext"):
params.offset_data=orders.get("data", {}).get("offsetData")
next_page=awaitclient.get_active_orders(params)
print(f"Next page: {next_page}")
asyncio.run(main())

API Examples

Market Data

Available Enums

KlineType (K-line intervals):

  • KlineType.MINUTE_1, KlineType.MINUTE_5, KlineType.MINUTE_15, KlineType.MINUTE_30
  • KlineType.HOUR_1, KlineType.HOUR_2, KlineType.HOUR_4, KlineType.HOUR_6, KlineType.HOUR_8, KlineType.HOUR_12
  • KlineType.DAY_1, KlineType.WEEK_1, KlineType.MONTH_1

PriceType (price types):

  • PriceType.LAST_PRICE (default) - Latest market price
  • PriceType.INDEX_PRICE - Index price
  • PriceType.ORACLE_PRICE - Oracle price
  • PriceType.ASK1_PRICE - Best ask price
  • PriceType.BID1_PRICE - Best bid price
  • PriceType.OPEN_INTEREST - Open interest
fromedgex_sdkimportClient, GetKLineParams, GetOrderBookDepthParams, KlineType, PriceType# Get 24-hour market quotes for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"Current price: {quote}")
# Get K-line data for BTCUSDT (contract ID: 10000001)kline_params=GetKLineParams(
contract_id="10000001", # BTCUSDTkline_type=KlineType.MINUTE_1,
price_type=PriceType.LAST_PRICE,
size=10
)
# With time filters (optional)# kline_params = GetKLineParams(# contract_id="10000001",# kline_type=KlineType.HOUR_1,# price_type=PriceType.LAST_PRICE,# size=20,# filter_begin_kline_time_inclusive="1640995200000", # Start timestamp# filter_end_kline_time_exclusive="1640998800000" # End timestamp# )klines=awaitclient.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get order book depth for ETHUSDT (contract ID: 10000002)depth_params=GetOrderBookDepthParams(
contract_id="10000002", # ETHUSDTlimit=10
)
depth=awaitclient.quote.get_order_book_depth(depth_params)
print(f"Order book: {depth}")

Account Management

# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Positions: {positions}")
# Get position transactionsfromedgex_sdkimportGetPositionTransactionPageParamstx_params=GetPositionTransactionPageParams(
size="10",
offset_data=""
)
transactions=awaitclient.account.get_position_transaction_page(tx_params)
print(f"Transactions: {transactions}")

Order Management

fromedgex_sdkimportOrderSide, CreateOrderParams, CancelOrderParams# Create a limit order for BNBUSDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNBUSDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Get maximum order size for BNBUSDTmax_size=awaitclient.get_max_order_size("10000004", 600.00)
print(f"Max order size: {max_size}")
# Cancel an ordercancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")

Contract IDs

EdgeX uses numeric contract IDs instead of symbol-based identifiers. Here are some common contract mappings:

Contract IDSymbolTick Size
10000001BTCUSDT0.1
10000002ETHUSDT0.01
10000003SOLUSDT0.01

To get the complete list of available contracts:

metadata=awaitclient.get_metadata()
contracts=metadata.get("data", {}).get("contractList", [])
forcontractincontracts:
print(f"ID: {contract['contractId']} - {contract['contractName']}")

For more detailed examples, please refer to the examples directory.

Testing

The SDK includes comprehensive test coverage with multiple test suites:

Unit Tests

# Run unit tests (no API credentials required)
python -m pytest tests/test_client.py tests/test_eip712_signing.py -v

Public API Tests

# Run public endpoint tests (no authentication required)
python run_public_tests.py

Mock Integration Tests

# Run mock tests (test structure without real API calls)
python run_mock_tests.py

Full Integration Tests

# Run full integration tests (requires real API credentials)
python run_integration_tests.py

All Tests

# Run all available tests
python run_tests.py

For more testing information, see TESTING.md.

Environment Variables

For testing and development, you can set the following environment variables or create a .env file:

# API Configuration
EDGEX_BASE_URL=https://edgex-prod-v2.edgex.exchange
EDGEX_ASSET_BASE_URL=https://spot.edgex.exchange
EDGEX_WS_URL=wss://edgex-quote-prod-v2.edgex.exchange
# Account Credentials
EDGEX_ACCOUNT_ID=12345
EDGEX_TRADING_PRIVATE_KEY=your-trading-private-key

Then load them in your code:

importosfromdotenvimportload_dotenvfromedgex_sdkimportClient# Load environment variables from .env fileload_dotenv()
client=Client(
base_url=os.getenv("EDGEX_BASE_URL"),
asset_base_url=os.getenv("EDGEX_ASSET_BASE_URL"),
account_id=int(os.getenv("EDGEX_ACCOUNT_ID")),
trading_private_key=os.getenv("EDGEX_TRADING_PRIVATE_KEY")
)

Documentation

For detailed API documentation, please refer to the EdgeX API documentation.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin feature/my-new-feature)
  5. Create a new Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

30 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

EdgeX Python SDK

A Python SDK for interacting with the EdgeX Exchange API. This SDK provides a comprehensive interface to the EdgeX API, allowing you to easily integrate EdgeX functionality into your Python applications.

Branch Status

The main branch contains the current EdgeX V2 SDK. The legacy V1 SDK has moved to the v1 branch and is deprecated. New integrations should use V2.

Features

  • Complete API Coverage: Access all EdgeX API endpoints
  • WebSocket Support: Real-time data streaming
  • Async/Await: Modern Python async interface
  • Type Hints: Comprehensive type annotations for better IDE support
  • Error Handling: Proper error handling and validation
  • Pagination: Support for paginated API endpoints
  • Authentication: Automatic request signing

Installation

From PyPI

pip install edgex-python-sdk

Version Compatibility

edgex-python-sdk on PyPI has two incompatible API generations:

  • <= 0.3.0: contract v1 API SDK
  • >= 2.0.0: contract v2 API SDK

These two generations are not backward compatible. Please choose the package version based on the API generation you are integrating with.

Examples:

# Contract v1 API SDK
pip install "edgex-python-sdk<=0.3.0"# Contract v2 API SDK
pip install "edgex-python-sdk>=2.0.0"

From Source

git clone https://github.com/edgex-Tech/edgex-python-sdk.git
cd edgex-python-sdk
pip install -e .

Using Requirements Files

For production use:

pip install -r requirements.txt

For development (includes testing and linting tools):

pip install -r requirements-dev.txt

Virtual Environment (Recommended)

It's recommended to use a virtual environment:

# Create virtual environment
python3 -m venv venv
# Activate virtual environmentsource venv/bin/activate # On Windows: venv\Scripts\activate# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .

Quick Start

importasyncioimportosfromedgex_sdkimportClient, OrderSideasyncdefmain():
# Create a new clientclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345, # Your account IDtrading_private_key="your-trading-private-key"# Your trading private key
)
# Get server timeserver_time=awaitclient.get_server_time()
print(f"Server Time: {server_time}")
# Get exchange metadatametadata=awaitclient.get_metadata()
print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}")
# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account Assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Account Positions: {positions}")
# Get 24-hour market data for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"BNB2USDT Price: {quote}")
# Create a limit order (uncomment to place real order)# order = await client.create_limit_order(# contract_id="10000004", # BNB2USDT# size="0.01",# price="600.00",# side=OrderSide.BUY# )# print(f"Order created: {order}")# Run the async functionasyncio.run(main())

Architecture

The SDK is organized into modules that correspond to the EdgeX API structure:

edgex_sdk/
├── __init__.py
├── client.py # Main client
├── account/ # Account API
├── funding/ # Funding API
├── internal/ # Internal utilities
├── metadata/ # Metadata API
├── order/ # Order API
├── quote/ # Quote API
├── transfer/ # Transfer API
├── unified_asset/ # Unified asset withdraw / transfer flows
├── cctp/ # Circle CCTP bridge helpers
└── ws/ # WebSocket API

Available APIs

The SDK currently supports the following API modules:

  • Account API: Manage account positions, retrieve position transactions, and handle collateral transactions

    • Get account positions
    • Get position by contract ID
    • Get position transaction history
    • Get collateral transaction details
    • Update leverage settings
  • Unified Asset API: Current market-maker withdrawal flow

    • Build Spot / Perp V2 withdraw attempts with raw token amounts
    • Get fee via getFeeByAssetFlow
    • Sign server-provided EIP-712 payloads
    • Submit flows through submitAssetFlow
  • CCTP Bridge Helpers: Edge Mainnet USDC bridge support

    • Quote Circle CCTP fast-transfer fees
    • Build Edge depositForBurn bridge transactions
    • Fetch Iris V2 attestations
    • Build / submit Ethereum receiveMessage claim transactions
  • Funding API: Manage funding operations and account balance

    • Handle funding transactions
    • Manage funding accounts
    • Get funding transaction history
  • Metadata API: Access exchange system information

    • Get server time
    • Get exchange metadata (trading pairs, contracts, etc.)
  • Order API: Comprehensive order management

    • Create and cancel orders
    • Get active orders
    • Get order fill transactions
    • Calculate maximum order sizes
    • Manage order history
  • Quote API: Access market data and pricing

    • Get multi-contract K-line data
    • Get order book depth
    • Access real-time market quotes
    • Get 24-hour ticker data
  • Transfer API: Handle asset transfers

    • Create transfer out orders
    • Get transfer records (in/out)
    • Check available withdrawal amounts
    • Manage transfer history
  • WebSocket API: Real-time data streaming

    • Market data (tickers, K-lines, order book, trades)
    • Account updates
    • Order updates
    • Position updates

WebSocket Support

The SDK provides a WebSocket manager for handling real-time data:

importasynciofromedgex_sdkimportWebSocketManagerasyncdefmain():
# Create a WebSocket managerws_manager=WebSocketManager(
base_url="wss://edgex-quote-prod-v2.edgex.exchange",
account_id=12345,
api_key="",
api_passphrase="",
api_secret=""
)
# Define message handlersdefticker_handler(message):
print(f"Ticker Update: {message}")
defkline_handler(message):
print(f"K-line Update: {message}")
# Connect to public WebSocket for market dataws_manager.connect_public()
# Subscribe to real-time updates for BNB2USDT (contract ID: 10000004)ws_manager.subscribe_ticker("10000004", ticker_handler)
ws_manager.subscribe_kline("10000004", "1m", kline_handler)
# Connect to private WebSocket for account updatesws_manager.connect_private()
# Wait for updatesawaitasyncio.sleep(30)
# Disconnect all connectionsws_manager.disconnect_all()
asyncio.run(main())

Signing

The v2 SDK uses different keys for different signing flows:

  • trading private key: EIP-712 signing for order placement and setMarginMode
  • wallet private key: unified-asset withdrawal / transfer signing

Unified-asset withdrawals sign the EIP-712 payload returned by getEIP712Data and submit a 0x-prefixed signature. There is no StarkEx signing adapter in the v2 path.

Current Withdrawal Path

fromedgex_sdkimportClient, CreateWithdrawParamsclient=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
asset_base_url="https://spot.edgex.exchange",
account_id=12345,
api_key="...",
api_passphrase="...",
api_secret="...",
wallet_private_key="...",
)
result=awaitclient.create_withdraw(CreateWithdrawParams(
amount_raw="1000000",
user_address="0xYourWallet",
profile="mainnet-usdc",
))

Use source="perpv2" and the Perp V2 account ID in source_account to reuse the same unified-asset withdrawal path for Perp V2.

Error Handling

The SDK provides proper error handling for API requests:

importasynciofromedgex_sdkimportClient, OrderSideasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
try:
# Create a limit order for BNB2USDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNB2USDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Cancel the orderfromedgex_sdkimportCancelOrderParamscancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")
exceptValueErrorase:
print(f"Failed to create/cancel order: {str(e)}")
exceptExceptionase:
print(f"Unexpected error: {str(e)}")
asyncio.run(main())

Pagination

Many API endpoints support pagination:

importasynciofromedgex_sdkimportClient, GetActiveOrderParamsasyncdefmain():
client=Client(
base_url="https://edgex-prod-v2.edgex.exchange",
account_id=12345,
trading_private_key="your-trading-private-key"
)
# Create pagination parametersparams=GetActiveOrderParams(
size="10",
offset_data=""
)
# Get active ordersorders=awaitclient.get_active_orders(params)
print(f"Active orders: {orders}")
# Get next page if availableiforders.get("data", {}).get("hasNext"):
params.offset_data=orders.get("data", {}).get("offsetData")
next_page=awaitclient.get_active_orders(params)
print(f"Next page: {next_page}")
asyncio.run(main())

API Examples

Market Data

Available Enums

KlineType (K-line intervals):

  • KlineType.MINUTE_1, KlineType.MINUTE_5, KlineType.MINUTE_15, KlineType.MINUTE_30
  • KlineType.HOUR_1, KlineType.HOUR_2, KlineType.HOUR_4, KlineType.HOUR_6, KlineType.HOUR_8, KlineType.HOUR_12
  • KlineType.DAY_1, KlineType.WEEK_1, KlineType.MONTH_1

PriceType (price types):

  • PriceType.LAST_PRICE (default) - Latest market price
  • PriceType.INDEX_PRICE - Index price
  • PriceType.ORACLE_PRICE - Oracle price
  • PriceType.ASK1_PRICE - Best ask price
  • PriceType.BID1_PRICE - Best bid price
  • PriceType.OPEN_INTEREST - Open interest
fromedgex_sdkimportClient, GetKLineParams, GetOrderBookDepthParams, KlineType, PriceType# Get 24-hour market quotes for BNB2USDT (contract ID: 10000004)quote=awaitclient.get_24_hour_quote("10000004")
print(f"Current price: {quote}")
# Get K-line data for BTCUSDT (contract ID: 10000001)kline_params=GetKLineParams(
contract_id="10000001", # BTCUSDTkline_type=KlineType.MINUTE_1,
price_type=PriceType.LAST_PRICE,
size=10
)
# With time filters (optional)# kline_params = GetKLineParams(# contract_id="10000001",# kline_type=KlineType.HOUR_1,# price_type=PriceType.LAST_PRICE,# size=20,# filter_begin_kline_time_inclusive="1640995200000", # Start timestamp# filter_end_kline_time_exclusive="1640998800000" # End timestamp# )klines=awaitclient.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get order book depth for ETHUSDT (contract ID: 10000002)depth_params=GetOrderBookDepthParams(
contract_id="10000002", # ETHUSDTlimit=10
)
depth=awaitclient.quote.get_order_book_depth(depth_params)
print(f"Order book: {depth}")

Account Management

# Get account assetsassets=awaitclient.get_account_asset()
print(f"Account assets: {assets}")
# Get account positionspositions=awaitclient.get_account_positions()
print(f"Positions: {positions}")
# Get position transactionsfromedgex_sdkimportGetPositionTransactionPageParamstx_params=GetPositionTransactionPageParams(
size="10",
offset_data=""
)
transactions=awaitclient.account.get_position_transaction_page(tx_params)
print(f"Transactions: {transactions}")

Order Management

fromedgex_sdkimportOrderSide, CreateOrderParams, CancelOrderParams# Create a limit order for BNBUSDTorder=awaitclient.create_limit_order(
contract_id="10000004", # BNBUSDTsize="0.01",
price="600.00",
side=OrderSide.BUY
)
print(f"Order created: {order}")
# Get maximum order size for BNBUSDTmax_size=awaitclient.get_max_order_size("10000004", 600.00)
print(f"Max order size: {max_size}")
# Cancel an ordercancel_params=CancelOrderParams(
order_id=order.get("data", {}).get("orderId")
)
cancel_result=awaitclient.cancel_order(cancel_params)
print(f"Order cancelled: {cancel_result}")

Contract IDs

EdgeX uses numeric contract IDs instead of symbol-based identifiers. Here are some common contract mappings:

Contract IDSymbolTick Size
10000001BTCUSDT0.1
10000002ETHUSDT0.01
10000003SOLUSDT0.01

To get the complete list of available contracts:

metadata=awaitclient.get_metadata()
contracts=metadata.get("data", {}).get("contractList", [])
forcontractincontracts:
print(f"ID: {contract['contractId']} - {contract['contractName']}")

For more detailed examples, please refer to the examples directory.

Testing

The SDK includes comprehensive test coverage with multiple test suites:

Unit Tests

# Run unit tests (no API credentials required)
python -m pytest tests/test_client.py tests/test_eip712_signing.py -v

Public API Tests

# Run public endpoint tests (no authentication required)
python run_public_tests.py

Mock Integration Tests

# Run mock tests (test structure without real API calls)
python run_mock_tests.py

Full Integration Tests

# Run full integration tests (requires real API credentials)
python run_integration_tests.py

All Tests

# Run all available tests
python run_tests.py

For more testing information, see TESTING.md.

Environment Variables

For testing and development, you can set the following environment variables or create a .env file:

# API Configuration
EDGEX_BASE_URL=https://edgex-prod-v2.edgex.exchange
EDGEX_ASSET_BASE_URL=https://spot.edgex.exchange
EDGEX_WS_URL=wss://edgex-quote-prod-v2.edgex.exchange
# Account Credentials
EDGEX_ACCOUNT_ID=12345
EDGEX_TRADING_PRIVATE_KEY=your-trading-private-key

Then load them in your code:

importosfromdotenvimportload_dotenvfromedgex_sdkimportClient# Load environment variables from .env fileload_dotenv()
client=Client(
base_url=os.getenv("EDGEX_BASE_URL"),
asset_base_url=os.getenv("EDGEX_ASSET_BASE_URL"),
account_id=int(os.getenv("EDGEX_ACCOUNT_ID")),
trading_private_key=os.getenv("EDGEX_TRADING_PRIVATE_KEY")
)

Documentation

For detailed API documentation, please refer to the EdgeX API documentation.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin feature/my-new-feature)
  5. Create a new Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

30 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages