OpenTradingCore Python SDK¶
Quick Start¶
Install the Python SDK and optional realtime support:
python3 -m pip install "https://api.opentradingcore.com/sdk/opentradingcore-0.1.9-py3-none-any.whl"
python3 -m pip install "websocket-client>=1.7,<2"
Create a Trader API key in the trading terminal. Store the secret securely.
from opentradingcore import OpenTradingCoreClient
api = OpenTradingCoreClient.public(
base_url="https://trade.opentradingcore.com", location="YOUR_TENANT")
print(api.products())
print(api.snapshot("BTCUSDT"))
print(api.ticker_24h("BTCUSDT"))
# Use the same OpenTradingCoreClient class for signed operations:
api = OpenTradingCoreClient.from_api_key(
base_url="https://trade.opentradingcore.com",
api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET",
location="YOUR_TENANT")
api.login()
print(api.balances())
print(api.funds_history())
Live market subscriptions¶
api.connect_stream(channel="market")
try:
api.subscribe_ticker("BTCUSDT")
api.subscribe_order_book("BTCUSDT")
api.subscribe_recent_trades("BTCUSDT")
api.subscribe_candles("BTCUSDT", interval="5m")
for event in api.events(channel="market"):
print(event)
finally:
api.close_stream(channel="market")
Authenticated account subscriptions¶
# api.login() is required before private subscriptions.
api.connect_stream(channel="private")
try:
api.subscribe_balances()
api.subscribe_positions()
api.subscribe_order_status("BTCUSDT")
api.subscribe_executions("BTCUSDT")
for event in api.events(channel="private"):
print(event)
finally:
api.close_stream(channel="private")
Availability: Real market notifications and scoped private order/fill/balance/position notifications have been observed. Sustained availability, reconnect and replay consistency are not yet certified. Subscription success by itself is not proof that any event arrived.
Market Data¶
OpenTradingCoreClient.products()¶
Method details
List enabled products for the tenant without API keys.
api.products()
OpenTradingCoreClient.snapshot(symbol)¶
Method details
Current order-book image, latest quote and recent trades for one product. A snapshot is not a subscription.
api.snapshot("BTCUSDT")
OpenTradingCoreClient.ticker_24h(symbol)¶
Method details
Market-header metrics for one tenant/product: latest and reference prices, price change %, mark/index, 24h high/low, funding rate and UTC countdown, Premium, base volume and USDT turnover. Source uses the current 1D aggregation, not a guaranteed sliding 24-hour period. Missing fields return None.
api.ticker_24h("BTCUSDT")
| Return field | Meaning |
|---|---|
last_price |
Latest execution price |
price_change_percent |
Change versus reference price (%) |
mark_price |
Mark price |
index_price |
Index price |
high_price_24h |
MD 1D high shown in the terminal |
low_price_24h |
MD 1D low shown in the terminal |
funding_rate_percent |
Funding rate in percent |
funding_countdown_utc |
Countdown to next UTC eight-hour boundary |
premium_percent |
(mark minus index) / index (%) |
volume_24h |
MD 1D base-asset volume |
turnover_24h_usdt |
MD 1D turnover, displayed as USDT |
Unavailable prices and volume are returned as None, not fabricated zeros. The current 1D source is not a verified rolling 24-hour window.
OpenTradingCoreClient.kline(symbol, interval="5m", limit=200)¶
Method details
Read historical candle bars. Signed Trader/Broker login required.
api.kline("BTCUSDT", interval="5m", limit=200)
Trading & History¶
OpenTradingCoreClient.place_limit_order(symbol, side, quantity, price)¶
Method details
Submit a limit order. Recover uncertain results by querying order history; do not blindly retry.
api.place_limit_order("BTCUSDT", "Buy", "0.001", "90000")
OpenTradingCoreClient.cancel_order(symbol, order_id)¶
Method details
Cancel an existing order by its immutable order ID.
api.cancel_order("BTCUSDT", "ORDER_ID")
OpenTradingCoreClient.open_orders(symbol)¶
Method details
Read currently open orders for the signed user.
api.open_orders("BTCUSDT")
OpenTradingCoreClient.order_history(page=0, page_size=20, symbol=None)¶
Method details
Page through historical order states for the signed user.
api.order_history(page=0, page_size=20, symbol="BTCUSDT")
OpenTradingCoreClient.execution_history(page=0, page_size=20, symbol=None)¶
Method details
Page through fills and historical executions for the signed user.
api.execution_history(page=0, page_size=20, symbol="BTCUSDT")
Balance, Positions & Funds¶
OpenTradingCoreClient.balances()¶
Method details
Read the signed Trader account balances. Applies to Trade-mode products.
api.balances()
OpenTradingCoreClient.positions(symbol)¶
Method details
Read signed Trader positions. Order-only products have no TradeSvr positions.
api.positions("BTC003USDT")
OpenTradingCoreClient.funds_history(page=0, page_size=50)¶
Method details
Read tenant-scoped Trader funds ledger postings; authenticated identity is enforced.
api.funds_history(page=0, page_size=50)
Realtime Subscriptions¶
OpenTradingCoreClient.connect_stream(channel="market")¶
Method details
Connect one of the market/public or private/authenticated realtime channels.
api.connect_stream(channel="market")
OpenTradingCoreClient.subscribe_ticker(symbol)¶
Method details
Subscribe to live market-header updates for one tenant/product. These are existing MD 1D-derived ticker fields; obtain ticker_24h(symbol) first for the initial snapshot.
api.subscribe_ticker("BTCUSDT")
OpenTradingCoreClient.subscribe_order_book(symbol)¶
Method details
Subscribe to an initial depth image and incremental updates. On a gap, obtain a fresh image.
api.subscribe_order_book("BTCUSDT")
OpenTradingCoreClient.subscribe_recent_trades(symbol)¶
Method details
Subscribe to recent public trade events for one product.
api.subscribe_recent_trades("BTCUSDT")
OpenTradingCoreClient.subscribe_candles(symbol, interval="5m")¶
Method details
Subscribe to candle updates for a product and interval.
api.subscribe_candles("BTCUSDT", interval="5m")
OpenTradingCoreClient.events(channel="market")¶
Method details
Iterate received market notifications after connecting and subscribing. Transport drop requires reconnect and resnapshot.
for event in api.events(channel="market"):
print(event)
OpenTradingCoreClient.subscribe_balances()¶
Method details
Subscribe to private Trader balance changes. Requires ACCOUNT_READ. Continuous delivery is pending live acceptance.
api.subscribe_balances()
OpenTradingCoreClient.subscribe_positions()¶
Method details
Subscribe to private Trader position changes. Requires ACCOUNT_READ.
api.subscribe_positions()
OpenTradingCoreClient.subscribe_order_status(symbol)¶
Method details
Subscribe to private order status transitions. Requires ORDER_READ.
api.subscribe_order_status("BTCUSDT")
OpenTradingCoreClient.subscribe_executions(symbol)¶
Method details
Subscribe to private fills and executions. Requires ORDER_READ.
api.subscribe_executions("BTCUSDT")
OpenTradingCoreClient.close_stream(channel="market")¶
Method details
Always close the chosen realtime channel in a finally block.
api.close_stream(channel="market")
Periodic Refresh¶
OpenTradingCoreClient.watch_ticker_24h(symbol, interval_seconds=15)¶
Method details
Periodically refresh market-header metrics for one product. This is polling, not a push stream.
for ticker in api.watch_ticker_24h("BTCUSDT"):
print(ticker)
OpenTradingCoreClient.watch_funds_history(interval_seconds=15)¶
Method details
Periodically refresh the signed Trader funds ledger. This is polling, not a push stream.
for funds in api.watch_funds_history():
print(funds)
Broker / Custom Pricing¶
OpenTradingCoreClient.publish_price(data_source_id=..., index_price=..., mark_price=...)¶
Method details
Publish custom prices for the tenant-owned active data source. Source ID and traded symbol are independent.
api.publish_price(data_source_id="MY_BTC", index_price="90000", mark_price="90001", ttl_ms=60000)
OpenTradingCoreClient.place_customer_limit_order(customer_id, symbol, side, quantity, price)¶
Method details
Place a delegated limit order within an authorized customer and tenant scope.
api.place_customer_limit_order("CUSTOMER_ID", "BTCUSDT", "Buy", "0.001", "90000")
Data freshness and safety¶
24h market-header metrics are scoped to one tenant and one instrument and reflect the current MD 1D aggregate, not necessarily a strict sliding 24h window. Market-header and funds history refresh use periodic read-only queries, not advertised push subscriptions. For Order-only products, balances and Trade positions are not maintained. Never automatically replay an ambiguous order or funding operation.
Rate limits¶
Limits apply to one authenticated API session, shared by its Python SDK business calls. The rate limiter uses a token bucket with the following currently configured values:
| API key session | Limit profile | Refill rate | Bucket capacity (burst) |
|---|---|---|---|
| Trader | TRADER_STANDARD |
100 requests/second | 30 requests |
| Broker | TRADER_STANDARD |
100 requests/second | 30 requests |
| Tenant service | TENANT_STANDARD |
20 requests/second | 10 requests |
Every rate-limited business call currently costs one token. There are no distinct per-method weights or dedicated Broker buckets. These are configured limits, not guaranteed throughput. Public market subscriptions and periodic refresh have different usage patterns; avoid fast polling when a stream is available.
The SDK raises OpenTradingCoreError with code=10003 when a session exceeds its bucket (RATE_LIMIT_EXCEEDED). Slow down and apply bounded exponential backoff with jitter to read-only calls. Do not blindly retry order placement, cancellation, customer funding or other writes following a timeout or unknown result. First reconcile using the corresponding query method and the original order/client ID. A profile configuration problem is code=10005.
Error codes¶
The Python SDK raises ValueError for locally rejected arguments and OpenTradingCoreError for unsuccessful remote requests. The latter includes a stable numeric code=... where available; backend diagnostic text is intentionally hidden. A successful call returns the requested data. The commonly relevant public codes are:
| Code | Name | Meaning / handling |
|---|---|---|
1, 1004 |
INVALID_REQUEST |
Invalid input; correct the arguments |
1005, 10004 |
ACCESS_DENIED |
Operation not permitted for this session |
1006 |
CHECK_FAILED |
Request validation failed; verify the operation preconditions |
1007 |
TIMEOUT |
Result uncertain; reconcile before any write retry |
1050 |
CONNECTION_LIMIT_EXCEEDED |
Reduce concurrent connections |
5000 |
TRADE_BALANCE_NOT_ENOUGH |
Insufficient trading balance |
5001 |
TRADE_ACCOUNTBALANCE_NOTEXIST |
Trading balance record unavailable |
5002 |
TRADE_POSITION_NOT_ENOUGH |
Insufficient position for the operation |
5003 |
MARK_PRICE_NOT_FOUND |
No currently valid mark price (including source expiry) |
5004 |
SYMBOL_NOT_FOUND |
Product not available to this tenant / not yet visible to Order |
7000 |
API_NOT_EXIST |
Key unknown or not yet propagated |
7001 |
API_REQ_HAS_EXPIRE |
Signed login request expired |
7002 |
API_SIGN_ERROR |
Signature verification failed |
7003 |
API_IP_NOT_ALLOWED |
Source IP fails API key policy |
7004 |
API_KEY_POLICY_NOT_READY |
Gateway has not received the key policy yet |
8000 |
ORDER_NOT_FOUND |
Requested order does not exist in permitted scope |
9000 |
INTERNAL_ERROR |
Unexpected service failure; avoid replaying writes |
9001 |
USER_NOT_FOUND |
User not found |
9002 |
USER_SESSION_NOTEXIST |
Session missing or expired; authenticate again |
9004 |
PARAMETER_ERROR |
Invalid required parameter |
9005, 9008 |
AUTHENTICATION_FAILED / SIGNATURE_VERIFY_FAIL |
Invalid authentication or signature |
9006 |
USER_IS_BAN |
User disabled |
9007 |
CLIENT_TYPE_NOT_SUPPORTED |
Wrong authentication session type |
9009 |
BALANCE_NOT_ENOUGH |
Insufficient balance |
9016 |
TRADE_PERMISSION_DENIED |
Missing trading permission |
9018 |
API_KEY_LIMIT_REACHED |
Maximum number of keys reached |
9019 |
NOT_API_USER |
Operation requires an eligible API identity |
10000 |
NO_POSITION |
No matching open position |
10003 |
RATE_LIMIT_EXCEEDED |
Reduce request rate and retry read-only calls after backoff |
10005 |
RATE_LIMIT_PROFILE_INVALID |
Contact the platform operator |
Errors not on the platform's public allowlist are reduced to 9000 INTERNAL_ERROR. The API does not promise to expose internal exception details, stack traces or implementation identifiers.
Common enums¶
Use the following Python SDK values, not internal transport constants:
| Argument / concept | Accepted values | Notes |
|---|---|---|
login(mode=...) |
"trader", "broker" |
Use the matching API key type |
side |
"Buy", "Sell" (case-insensitive input) |
For limit orders |
oc_type |
"OPEN", "CLOSE" |
Default is OPEN |
position_side |
"Long", "Short" |
Required on close; close Long with Sell, Short with Buy |
reduce_only |
True, False |
A close needs True; OPEN cannot be reduce-only in this helper |
set_position_type(..., position_type=...) |
"Cross", "Isolated" |
Trade account position configuration |
| Limit order type and time in force | Limit / GTC |
These Python helpers submit GTC limit orders; other modes are not offered by these helpers |
| Product matching mode | TRADE, ORDER_ONLY |
Configured in tenant product management; ORDER_ONLY does not mutate Trade funds or positions |
market_indicator |
"4" (SDK default) |
Leave the default unless your product is configured otherwise |
| Permission scopes | MARKET_READ, ACCOUNT_READ, ORDER_READ, ORDER_WRITE, TENANT_READ, TENANT_WRITE, CUSTOMER_CASH |
Granted by key type; requests cannot self-grant permissions |
Order states such as New and Filled come from server data; do not treat the above list as a guarantee that every product supports every order type or that all states are final.
Parameters and conventions¶
| Parameter | Current Python SDK rule |
|---|---|
location |
Required tenant code. Product IDs are scoped to this tenant |
symbol |
Tenant-enabled product ID, e.g. BTC003USDT; it is not required to match the price-source ID |
quantity, price |
Positive decimal amounts; use strings for exact financial values and respect the product's configured increments and limits |
page / page_size |
Page index starts at 0; page size is 1–200 for history methods |
kline(..., limit=...) |
1–1000 candles, default 200; interval default "5m" |
publish_price(..., ttl_ms=...) |
1000–60000 ms, default 5000 ms; after expiry the mark is invalid and must not silently fall back to a formerly unbound source |
watch_ticker_24h / watch_funds_history |
Polling interval 5–3600 seconds (default 15); these are repeated read-only snapshots, not event streams |
| API credentials | One-time secret on creation, keep out of logs and source code; use the intended Trader or Broker identity |
| Order client ID | Supply a stable unique clord_id where offered to reconcile an uncertain submission |
Market statistics are per tenant and per product. The current ticker_24h() reads MD's 1D aggregation and is not yet a guaranteed sliding 24-hour window. Unavailable data is None, not zero. A successful subscription acknowledges registration only; it does not prove continuous notifications or reconnection recovery.