Skip to content

quantpylib.wrappers.qfex

quantpylib.wrappers.qfex module is our official QFEX wrapper SDK implementing the REST and WebSocket endpoints. The library is fully asynchronous, with normalized gateway methods and support for Feed and OMS. The websocket managers handle reconnections and resubscriptions.

Examples

example_qfex.py groups usage into exchange_endpoints(), gateway_endpoints(), ws_endpoints() and feed_and_oms(). Select the function to run in main() and uncomment the endpoints you want to use.

import os
import asyncio

from pprint import pprint
from datetime import datetime, timedelta, timezone
from dotenv import load_dotenv
load_dotenv()

from quantpylib.gateway.master import Gateway
from quantpylib.hft.feed import Feed
from quantpylib.hft.oms import OMS
from quantpylib.wrappers.qfex import Qfex

qfex = Qfex(
    api_key=os.getenv("QFEX_PUBLIC"),
    api_secret=os.getenv("QFEX_SECRET"),
    cache_stream=True,
)

async def print_handler(message):
    pprint(message)

async def exchange_endpoints():
    symbol = "AAPL-USD"
    end = datetime.now(timezone.utc)
    start = end - timedelta(hours=1)
    window = {"from_iso": start.isoformat(), "to_iso": end.isoformat()}

    # MARKET DATA
    pprint(await qfex.candles(symbol=symbol, resolution="1MIN", **window))
    pprint(await qfex.funding_history(symbol=symbol, interval_minutes=60, **window))
    pprint(await qfex.contracts(symbol=symbol))
    pprint(await qfex.orderbook(ticker_id=symbol))
    pprint(await qfex.open_interest_history(symbol=symbol, interval_minutes=60, **window))
    pprint(await qfex.refdata(ticker=symbol))
    pprint(await qfex.settlement_calendar(symbol="US100-USD"))
    pprint(await qfex.settlement_prices(symbol="US100-USD", limit=10))
    pprint(await qfex.symbol_long_short_history(symbol=symbol, interval="1h", **window))
    pprint(await qfex.taker_volume_history(symbol=symbol, interval_minutes=60, **window))
    pprint(await qfex.underlier_history(symbol=symbol, interval="1h", **window))

    # USER
    pprint(await qfex.executions(limit=10))
    pprint(await qfex.historic_orders_csv())
    pprint(await qfex.historic_twaps_csv(symbol=symbol))
    pprint(await qfex.redeem_invitation_code(invitation_code="YOUR_INVITATION_CODE"))
    pprint(await qfex.trades_csv())
    pprint(await qfex.account_equity(duration="1w"))
    pprint(await qfex.builder_code())  # Requires an active builder code.
    pprint(await qfex.builder_code_create(qfex_fee_share_bps=5000, builder_fee_share_bps=3000))
    pprint(await qfex.user_fees())
    pprint(await qfex.user_flat_funding())
    pprint(await qfex.historic_orders(symbol=symbol, limit=10, offset=0))
    pprint(await qfex.historic_user_pnl(duration="1w", unit="number", symbol=symbol))
    pprint(await qfex.historic_twaps(symbol=symbol, limit=10))
    pprint(await qfex.reconcile_invitation_codes())
    pprint(await qfex.user_leverage_set(symbol=symbol, leverage=2))
    pprint(await qfex.user_positions())
    pprint(await qfex.user_referral_rewards(duration="1w"))
    pprint(await qfex.user_referral_notional_volume())
    pprint(await qfex.subaccounts())
    pprint(await qfex.subaccount_create(name="strategy"))
    pprint(await qfex.account_balances())
    pprint(await qfex.account_equities())
    pprint(await qfex.user_trades(symbol=symbol, limit=10, offset=0))
    pprint(await qfex.balance_transfer(src_account_id="SOURCE_ID", dst_account_id="DESTINATION_ID", amount=1))
    pprint(await qfex.user_volume(range="1w", symbol=symbol))

    # PNL / PUBLIC
    pprint(await qfex.hourly_pnl(symbol=symbol, start=start.isoformat(), end=end.isoformat(), limit_hours=24))
    pprint(await qfex.leaderboard(duration="1w", sort="absolute"))

async def gateway_endpoints():
    symbol = "AAPL-USD"
    end = datetime.now(timezone.utc)
    start = end - timedelta(hours=1)
    start_ms, end_ms = int(start.timestamp()*1000), int(end.timestamp()*1000)

    # ACCOUNT
    pprint(await qfex.account_balance())
    pprint((await qfex.account_fills_get(start_ms=start_ms, end_ms=end_ms)).as_list())
    await qfex.account_fill_subscribe(handler=print_handler)
    await qfex.account_fills_mirror(on_update=print_handler)

    # EXCHANGE
    pprint(await qfex.contract_specifications())
    pprint(await qfex.get_funding_info())

    # EXECUTOR
    pprint(qfex.rand_cloid())
    pprint(await qfex.get_all_mids(ticker=symbol))
    pprint(await qfex.get_all_marks(ticker=symbol))
    pprint(await qfex.order_wire(symbol, amount=1, price=200, tif="GTC", cloid=qfex.rand_cloid()))
    pprint(await qfex.limit_order(symbol, amount=1, price=200, tif="IOC", timeout=0.5))
    pprint(await qfex.cancel_order(symbol, oid="ORDER_UUID"))
    pprint(await qfex.cancel_order(symbol, cloid="CLIENT_ORDER_ID"))
    pprint(await qfex.cancel_open_orders(ticker=symbol))
    pprint(await qfex.market_order(symbol, amount=-1, reduce_only=True))
    pprint(await qfex.l2_book_get(symbol, standardize_schema=2))
    await qfex.l2_book_mirror(symbol, on_update=print_handler)
    pprint(qfex.l2_book_peek(symbol))
    await qfex.l2_book_subscribe(symbol, handler=print_handler)
    await qfex.trades_subscribe(symbol, handler=print_handler)
    await qfex.bba_subscribe(symbol, handler=print_handler)
    await qfex.all_mids_subscribe(handler=print_handler)

    # ORDERS
    pprint(await qfex.order_query(symbol, oid="ORDER_UUID"))
    pprint(await qfex.orders_get(ticker=symbol))
    await qfex.orders_mirror(on_update=print_handler)
    pprint(qfex.orders_peek())
    await qfex.order_updates_subscribe(handler=print_handler, standardize_schema=0)

    # POSITIONS
    pprint(await qfex.positions_get())
    await qfex.positions_mirror(on_update=print_handler)
    pprint(qfex.positions_peek())
    await asyncio.sleep(10)

async def ws_endpoints():
    symbol = "AAPL-USD"
    aws, private = qfex.aws_manager, qfex.private_aws_manager

    # MARKET DATA STREAMS
    await aws.bbo_subscribe(ticker=symbol, handler=print_handler)
    await aws.l2_book_subscribe(ticker=symbol, handler=print_handler)
    await aws.trades_subscribe(ticker=symbol, handler=print_handler)
    await aws.underlier_subscribe(ticker=symbol, handler=print_handler)
    await aws.funding_subscribe(ticker=symbol, handler=print_handler)
    await aws.mark_price_subscribe(ticker=symbol, handler=print_handler)
    await aws.open_interest_subscribe(ticker=symbol, handler=print_handler)
    await aws.minmax_price_subscribe(ticker=symbol, handler=print_handler)
    await aws.market_stats_subscribe(ticker=symbol, handler=print_handler)
    await aws.candle_subscribe(ticker=symbol, interval="1MIN", handler=print_handler)
    await asyncio.sleep(10)
    await aws.bbo_unsubscribe(ticker=symbol)
    await aws.l2_book_unsubscribe(ticker=symbol)
    await aws.trades_unsubscribe(ticker=symbol)
    await aws.underlier_unsubscribe(ticker=symbol)
    await aws.funding_unsubscribe(ticker=symbol)
    await aws.mark_price_unsubscribe(ticker=symbol)
    await aws.open_interest_unsubscribe(ticker=symbol)
    await aws.minmax_price_unsubscribe(ticker=symbol)
    await aws.market_stats_unsubscribe(ticker=symbol)
    await aws.candle_unsubscribe(ticker=symbol, interval="1MIN")

    # ACCOUNT STREAMS
    await private.order_updates_subscribe(handler=print_handler)
    await private.account_fill_subscribe(handler=print_handler)
    await private.account_position_subscribe(handler=print_handler)
    await private.account_balance_subscribe(handler=print_handler)
    await asyncio.sleep(10)
    await private.order_updates_unsubscribe()
    await private.account_fill_unsubscribe()
    await private.account_position_unsubscribe()
    await private.account_balance_unsubscribe()

    # TRADE REQUESTS
    # True means no matching error arrived within the window; order_updates carries the outcome.
    # pprint(await qfex.add_order(symbol, "BUY", "LIMIT", "IOC", quantity=1, price=200, timeout=0.5))
    # pprint(await qfex.order_cancel(symbol, order_id="ORDER_UUID", cancel_order_id_type="order_id"))
    # pprint(await qfex.order_cancel(symbol, order_id="CLIENT_ORDER_ID", cancel_order_id_type="client_order_id"))
    # Native modify_order is disabled; cancel and add separately with a fresh client ID.
    # pprint(await qfex.cancel_all_orders(symbol=symbol))
    # pprint(await qfex.close_position(symbol=symbol))
    # pprint(await qfex.add_twap(symbol, "BUY", total_quantity=1, num_orders=5, order_interval_secs=30,
    #                           reduce_only=False, client_twap_id=qfex.rand_cloid()))
    # pprint(await qfex.order_cancel(symbol, order_id="CLIENT_TWAP_ID", cancel_order_id_type="client_twap_id"))
    # pprint(await qfex.get_user_orders(symbol=symbol, limit=10, offset=0))
    # pprint(await qfex.get_order(symbol=symbol, order_id="OPEN_ORDER_ID"))
    # pprint(await qfex.get_user_trades(limit=10, offset=0))
    # pprint(await qfex.get_user_leverage(limit=10, offset=0))
    # pprint(await qfex.get_available_leverage_levels(limit=10, offset=0))
    # pprint(await qfex.set_user_leverage(symbol=symbol, leverage=2))
    # pprint(await qfex.add_stop_order(symbol, "SELL", "STOP_LOSS", "GTC", quantity=1, price=180))
    # pprint(await qfex.cancel_stop_order(stop_order_id="STOP_ORDER_UUID"))
    # pprint(await qfex.modify_stop_order(symbol, "STOP_ORDER_UUID", quantity=1, price=185))

async def feed_and_oms():
    exc, symbol = "qfex", "AAPL-USD"
    gateway = Gateway.from_clients({exc: qfex})
    feed, oms = Feed(gateway), OMS(gateway, track_mids=True)
    try:
        await oms.init(include_funding=True)
        book = await feed.add_l2_book_feed(exc=exc, ticker=symbol, on_msg=print_handler)
        bba = await feed.add_bba_feed(exc=exc, ticker=symbol, on_msg=print_handler)
        trades = await feed.add_trades_feed(exc=exc, ticker=symbol, on_msg=print_handler)

        # METADATA / ACCOUNT
        pprint(oms.contract_specs(exc=exc, ticker=symbol))
        pprint(oms.get_funding_info(exc=exc, ticker=symbol))
        pprint(await oms.get_balance(exc=exc))

        # EXECUTION
        # cloid = oms.rand_cloid(exc=exc)
        # await oms.limit_order(exc=exc, ticker=symbol, amount=1, price=200, cloid=cloid)
        # await oms.cancel_order(exc=exc, ticker=symbol, cloid=cloid)
        # await oms.market_order(exc=exc, ticker=symbol, amount=-1, reduce_only=True)

        await asyncio.sleep(10)
        pprint(feed.get_feed_ids())
        pprint(feed.get_feed(book))
        pprint(feed.get_feed(bba))
        pprint(feed.get_feed(trades))
        pprint(oms.orders_peek(exc=exc).as_list())
        pprint(oms.positions_peek(exc=exc).as_dict())
        pprint(oms.fills_peek(exc=exc).as_list())
    finally:
        await oms.cleanup()
        await feed.cleanup()


async def main():
    try:
        await qfex.init_client()
        # Uncomment the section and calls to run.
        # await exchange_endpoints()
        await gateway_endpoints()
        # await ws_endpoints()
        # await feed_and_oms()
    finally:
        await qfex.cleanup()


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

Connections and order responses

account_id=None selects the primary account. init_client() loads contract specifications and starts a pool of authenticated trade sockets (pool=8 by default). Each request borrows a socket exclusively; market data and account subscriptions use separate persistent connections. Call cleanup() when finished.

Order submissions and cancellations observe immediate errors for timeout=0.5 seconds by default. A True result means no matching error arrived during that interval; acceptance, fills and cancellation outcomes arrive on the order-response stream. Use orders_mirror() or OMS to maintain order state. Queries such as get_user_orders() wait for their response. The wrapper does not automatically retry trading commands.

Use a unique client order ID for each new order. QFEX permits duplicates, but the order mirror assumes uniqueness. Native modify_order() is disabled; cancel and submit a new order with a fresh client ID instead.

Market caches

With cache_stream=True, initialization subscribes to market statistics and waits for the first snapshot. get_all_mids(), get_all_marks() and get_funding_info() then read the latest cached values. Funding rates represent the one-hour funding interval. Books use their own subscriptions through l2_book_mirror() or Feed.

Documentation

AsyncWebsocketManager

Bases: AsyncWsManager

Manage QFEX public market-data subscriptions.

PrivateWebsocketManager

Bases: AsyncWsManager

Manage authenticated QFEX account subscriptions.

Qfex

account_balance_subscribe(handler) async

Subscribe to balance changes and periodic pulses for the selected account.

Parameters:

Name Type Description Default
handler

Sync or async callback receiving native {"balance_response": ...} messages.

required

account_balance_unsubscribe() async

Unsubscribe from the account's balance updates.

account_balances() async

Return equity and available balance for primary and secondary accounts.

Returns:

Type Description
dict

Native account balances response.

account_equities() async

Return equity for primary and secondary accounts.

Returns:

Type Description
dict

Native account equities response.

account_equity(duration=None) async

Return raw account equity history.

Parameters:

Name Type Description Default
duration

Optional QFEX duration preset; the venue defaults to "1w".

None

Returns:

Type Description
dict

Native account equity response.

account_fill_subscribe(handler, standardize_schema=1, **kwargs) async

Emit Fill objects with USD fee costs, or native envelopes with standardize_schema=0.

account_fills_get(start_ms=None, end_ms=None, **kwargs) async

Retrieve normalized fills over [start_ms, end_ms); default to the last day.

Exhausts REST history pages; QFEX does not document a retention limit. Native filters such as symbol and exchange_order_id pass through kwargs.

account_fills_mirror(on_update=None, as_list=True, **kwargs) async

Mirror observed live fills; this does not backfill reconnect gaps.

account_position_subscribe(handler) async

Subscribe to pulsed position updates for the selected account.

Parameters:

Name Type Description Default
handler

Sync or async callback receiving native {"position_response": ...} messages.

required

account_position_unsubscribe() async

Unsubscribe from the account's position updates.

add_order(symbol, side, order_type, order_time_in_force, quantity, price=None, take_profit=None, stop_loss=None, reduce_only=None, client_order_id=None, timeout=0.5) async

Send an order and return True if no matching error arrives in the window.

timeout is an error-observation window in seconds, with a 1 ms minimum. True does not confirm acceptance; acknowledgements, fills and rejections arrive on the account order stream. Native errors raise RuntimeError. Identical requests cannot be distinguished by their error echoes; supply distinct client_order_id values when submitting otherwise identical orders.

add_stop_order(symbol, side, order_type, order_time_in_force, quantity, price, timeout=0.5) async

Submit a TAKE_PROFIT or STOP_LOSS using the add_order wire message.

True means no matching error arrived within the window. QFEX requires order_time_in_force for this request but does not use it for stop orders.

add_twap(symbol, side, total_quantity, num_orders, order_interval_secs, reduce_only, client_twap_id=None, start_time=None, worst_price=None, timeout=0.5) async

Submit a TWAP; True means no matching error arrived within the window.

start_time is Unix seconds; omission starts immediately. worst_price is the IOC limit price for each child order. Cancel through order_cancel using twap_id or client_twap_id.

balance_transfer(src_account_id, dst_account_id, amount) async

Transfer balance between two accounts owned by the authenticated user.

Parameters:

Name Type Description Default
src_account_id

Source account ID.

required
dst_account_id

Destination account ID.

required
amount

Numeric amount to transfer.

required

Returns:

Type Description
dict

Empty dictionary on a successful HTTP 204 response.

bbo_subscribe(ticker, handler) async

Subscribe to raw public best bid/offer updates.

Parameters:

Name Type Description Default
ticker

QFEX symbol, or "*" for all symbols.

required
handler

Sync or async callback receiving each native JSON dictionary.

required

bbo_unsubscribe(ticker) async

Unsubscribe the symbol or wildcard used in bbo_subscribe.

builder_code() async

Return the latest active builder code and fee shares.

Returns:

Type Description
dict

Native builder code details.

builder_code_create(qfex_fee_share_bps, builder_fee_share_bps) async

Create a builder code with the requested fee shares.

Parameters:

Name Type Description Default
qfex_fee_share_bps

QFEX fee share in basis points, at least 5000.

required
builder_fee_share_bps

Nonnegative builder share; combined shares must not exceed 10000.

required

Returns:

Type Description
dict

Native builder code details.

cache_oracles(timeout=10) async

Keep mids, marks and funding current from the wildcard market-stats stream.

cancel_all_orders(symbol=None, timeout=10) async

Cancel active orders for one symbol, or all symbols when omitted.

Return the native ack; individual cancellation outcomes arrive on the order-updates stream. An error can precede the ack, so failures retire the socket through the required-response path.

cancel_stop_order(stop_order_id, timeout=0.5) async

Cancel a stop order by UUID; True means no matching error arrived within the window.

cancel_wire(ticker, oid=None, cloid=None, **kwargs) async

Client-ID cancellation affects every matching order on QFEX.

candle_subscribe(ticker, interval, handler) async

Subscribe to raw OHLCV candle updates for one interval.

Parameters:

Name Type Description Default
ticker

QFEX symbol, or "*" for all symbols.

required
interval

Native QFEX resolution, such as "1MIN", "5MINS" or "1HOUR".

required
handler

Sync or async callback receiving each native JSON dictionary.

required

candle_unsubscribe(ticker, interval) async

Unsubscribe the symbol and interval used in candle_subscribe.

candles(symbol, resolution, from_iso, to_iso) async

Return raw OHLCV candles for a symbol.

Parameters:

Name Type Description Default
symbol

QFEX symbol.

required
resolution

QFEX candle resolution.

required
from_iso

Start time as an ISO 8601 string.

required
to_iso

End time as an ISO 8601 string.

required

Returns:

Type Description
dict

Native candle response.

cleanup() async

Close pooled sockets, subscriptions, and the HTTP client.

close_position(symbol, timeout=0.5) async

Request an IOC close of the symbol's position.

True means no matching error arrived within the window, not a confirmed fill.

contract_specifications(include_inactive=False, **kwargs) async

Return native trading grids and quantity limits, keyed by symbol.

QFEX does not publish a fixed minimum notional; that field remains None.

contracts(symbol=None) async

Return raw contract metadata and current market data.

Parameters:

Name Type Description Default
symbol

Optional QFEX symbol; omit to request all symbols.

None

Returns:

Type Description
dict

Native contracts response.

executions(execution_type=None, symbol=None, start_time=None, end_time=None, limit=None, sort_dir=None) async

Return raw account ledger executions, including funding and transfers.

Parameters:

Name Type Description Default
execution_type

Optional execution type filter.

None
symbol

Optional QFEX symbol.

None
start_time

Optional start time filter as a string.

None
end_time

Optional end time filter as a string.

None
limit

Optional maximum row count; the venue defaults to 10, maximum 100.

None
sort_dir

Optional "asc" or "desc"; the venue defaults to "desc".

None

Returns:

Type Description
dict

Native executions response.

funding_history(symbol, interval_minutes, from_iso, to_iso) async

Return raw historical funding rates for a symbol.

Parameters:

Name Type Description Default
symbol

QFEX symbol.

required
interval_minutes

Sampling interval in minutes.

required
from_iso

Start time as an ISO 8601 string.

required
to_iso

End time as an ISO 8601 string.

required

Returns:

Type Description
dict

Native funding history response.

funding_subscribe(ticker, handler) async

Subscribe to raw current funding-rate updates.

Parameters:

Name Type Description Default
ticker

QFEX symbol, or "*" for all symbols.

required
handler

Sync or async callback receiving each native JSON dictionary.

required

funding_unsubscribe(ticker) async

Unsubscribe the symbol or wildcard used in funding_subscribe.

get_all_marks(ticker=None, **kwargs) async

Return cached Decimal marks; requires cache_stream=True on init.

get_all_mids(ticker=None, **kwargs) async

Return cached Decimal mids; requires cache_stream=True on init.

get_available_leverage_levels(limit=None, offset=None, timeout=10) async

Return one native available_leverage_levels_response page of leverage tiers.

get_funding_info(ticker=None, **kwargs) async

Return cached hourly funding estimates at stream precision; requires cache_stream=True on init.

get_order(symbol, order_id, timeout=10) async

Return the native get_order_response for an open exchange order ID.

Filled and cancelled orders are excluded. Native errors raise RuntimeError.

get_user_leverage(limit=None, offset=None, timeout=10) async

Return one native user_leverage_response page of account leverage settings.

get_user_orders(symbol=None, limit=None, offset=None, timeout=10) async

Return one raw page of open orders and active TWAPs.

Parameters:

Name Type Description Default
symbol

Optional QFEX symbol; omit for all symbols.

None
limit

Optional page size; the venue defaults to 1000.

None
offset

Optional page offset; the venue defaults to zero.

None
timeout

Response timeout in seconds after sending the request.

10

Returns:

Type Description
dict

Native all_orders_response envelope.

Raises:

Type Description
RuntimeError

Native error or unexpected response, retained in args[0].

TimeoutError

No response arrived before the timeout.

get_user_trades(limit=None, offset=None, order_id=None, start_ts=None, end_ts=None, timeout=10) async

Return one native user_trades_response page of executed fills.

order_id is an exchange order ID; start_ts/end_ts are inclusive Unix seconds.

historic_orders(symbol=None, order_id=None, client_order_id=None, order_side=None, order_type=None, order_status=None, start=None, end=None, limit=None, offset=None) async

Return one page of filled or terminally closed orders.

Parameters:

Name Type Description Default
symbol

Optional QFEX symbol.

None
order_id

Optional exchange order ID.

None
client_order_id

Optional client order ID.

None
order_side

Optional order side filter.

None
order_type

Optional order type filter.

None
order_status

Optional order status filter.

None
start

Optional start time as an ISO 8601 string.

None
end

Optional end time as an ISO 8601 string.

None
limit

Optional row count; the venue defaults to 100, maximum 1000.

None
offset

Optional pagination offset; the venue defaults to zero.

None

Returns:

Type Description
dict

Native historic orders response.

historic_orders_csv() async

Return all historic orders as CSV text.

Returns:

Type Description
str

Native CSV export.

historic_twaps(symbol=None, limit=None) async

Return cancelled or completed TWAPs.

Parameters:

Name Type Description Default
symbol

Optional QFEX symbol.

None
limit

Optional row count; the venue defaults to 100, maximum 1000.

None

Returns:

Type Description
dict

Native historic TWAP response.

historic_twaps_csv(symbol=None) async

Return historic TWAPs as CSV text.

Parameters:

Name Type Description Default
symbol

Optional QFEX symbol.

None

Returns:

Type Description
str

Native CSV export.

historic_user_pnl(duration=None, unit=None, symbol=None) async

Return raw account PnL history.

Parameters:

Name Type Description Default
duration

Optional QFEX duration preset; the venue defaults to "1w".

None
unit

Optional "number" or "percent"; the venue defaults to "number".

None
symbol

Optional QFEX symbol or comma-separated symbols.

None

Returns:

Type Description
dict

Native historic PnL response.

hourly_pnl(symbol=None, start=None, end=None, limit_hours=None) async

Return approximate first position snapshots per symbol and hour.

Parameters:

Name Type Description Default
symbol

Optional QFEX symbol.

None
start

Optional start time as an ISO 8601 string.

None
end

Optional end time as an ISO 8601 string.

None
limit_hours

Optional hour limit; the venue defaults to 168, maximum 2160.

None

Returns:

Type Description
dict

Native hourly PnL response.

init_client() async

Load metadata, warm the trade pool, and optionally seed live price caches.

l2_book_get(ticker, standardize_schema=1, timeout=10, depth=None, **kwargs) async

Return a REST book snapshot in native, legacy, or BookUpdate form.

leaderboard(duration=None, sort=None, query=None) async

Return the public top 100 leaderboard.

Parameters:

Name Type Description Default
duration

Optional QFEX duration preset; the venue defaults to "1w".

None
sort

Optional ranking mode; the venue defaults to "absolute".

None
query

Optional username filter within the selected top 100.

None

Returns:

Type Description
dict

Native leaderboard response.

mark_price_subscribe(ticker, handler) async

Subscribe to raw mark-price updates.

Parameters:

Name Type Description Default
ticker

QFEX symbol, or "*" for all symbols.

required
handler

Sync or async callback receiving each native JSON dictionary.

required

mark_price_unsubscribe(ticker) async

Unsubscribe the symbol or wildcard used in mark_price_subscribe.

market_stats_subscribe(ticker, handler) async

Subscribe to raw consolidated market-statistics snapshots.

Parameters:

Name Type Description Default
ticker

QFEX symbol, or "*" for an all-symbol snapshot.

required
handler

Sync or async callback receiving each native JSON dictionary.

required

market_stats_unsubscribe(ticker) async

Unsubscribe the symbol or wildcard used in market_stats_subscribe.

minmax_price_subscribe(ticker, handler) async

Subscribe to raw minimum and maximum price updates.

Parameters:

Name Type Description Default
ticker

QFEX symbol, or "*" for all symbols.

required
handler

Sync or async callback receiving each native JSON dictionary.

required

minmax_price_unsubscribe(ticker) async

Unsubscribe the symbol or wildcard used in minmax_price_subscribe.

modify_stop_order(symbol, stop_order_id, quantity, price, timeout=0.5) async

Amend a stop order's quantity and price; the live API requires both.

True means no matching error arrived within the window, not a confirmed amendment.

open_interest_history(symbol, interval_minutes, from_iso, to_iso) async

Return raw historical open interest, including venue forward filling.

Parameters:

Name Type Description Default
symbol

QFEX symbol.

required
interval_minutes

Sampling interval in minutes.

required
from_iso

Start time as an ISO 8601 string.

required
to_iso

End time as an ISO 8601 string.

required

Returns:

Type Description
dict

Native open interest history response.

open_interest_subscribe(ticker, handler) async

Subscribe to raw open-interest updates.

Parameters:

Name Type Description Default
ticker

QFEX symbol, or "*" for all symbols.

required
handler

Sync or async callback receiving each native JSON dictionary.

required

open_interest_unsubscribe(ticker) async

Unsubscribe the symbol or wildcard used in open_interest_subscribe.

order_cancel(symbol, order_id, cancel_order_id_type, timeout=0.5) async

Cancel by order_id, client_order_id, twap_id, or client_twap_id.

Pass the identifier in order_id for every mode. True means no matching error arrived within the window, not confirmed cancellation.

order_updates_subscribe(handler, standardize_schema=0, **kwargs) async

Subscribe to native order and TWAP envelopes.

order_wire(ticker, amount, price=None, tif='GTC', reduce_only=False, cloid=None, round_price=False, round_size=False, ord_type='LIMIT', take_profit=None, stop_loss=None, **kwargs) async

Build an inert order wire using the native tick and lot grids.

order_wire_submit(order_wire, **kwargs) async

True means no matching error was observed, not confirmed acceptance.

orderbook(ticker_id) async

Return the raw current order book.

Parameters:

Name Type Description Default
ticker_id

QFEX ticker identifier.

required

Returns:

Type Description
dict

Native order book response.

orders_mirror(on_update=None, as_list=True, **kwargs) async

Seed open orders and apply stream updates; callers must use unique client IDs.

positions_mirror(on_update=None, as_dict=True, **kwargs) async

Seed positions once, then apply each symbol's absolute position pulse.

reconcile_invitation_codes() async

Reconcile invitation-code rewards immediately.

Returns:

Type Description
dict

Native reconciliation response.

redeem_invitation_code(invitation_code) async

Redeem an invitation code and enable account access.

Parameters:

Name Type Description Default
invitation_code

Invitation code to redeem.

required

Returns:

Type Description
dict

Native redemption response.

refdata(ticker=None) async

Return raw symbol reference data.

Parameters:

Name Type Description Default
ticker

Optional QFEX ticker; omit to request all symbols.

None

Returns:

Type Description
dict

Native reference data response.

set_user_leverage(symbol, leverage, timeout=10) async

Set symbol leverage and return the native ack envelope.

QFEX disallows changes while orders or a nonzero position are open. On timeout or transport failure the outcome is unknown; the call is not retried.

settlement_calendar(symbol, time=None) async

Return the raw settlement calendar entry.

Parameters:

Name Type Description Default
symbol

QFEX symbol.

required
time

Optional lookup time as an ISO 8601 string.

None

Returns:

Type Description
dict

Native settlement calendar entry.

settlement_prices(symbol=None, start=None, end=None, limit=None) async

Return raw current and historical settlement prices and ratios.

Parameters:

Name Type Description Default
symbol

Optional QFEX symbol.

None
start

Optional start time as an ISO 8601 string.

None
end

Optional end time as an ISO 8601 string.

None
limit

Optional maximum row count; the venue defaults to 100, maximum 1000.

None

Returns:

Type Description
dict

Native settlement prices response.

subaccount_create(name=None) async

Create a new subaccount.

Parameters:

Name Type Description Default
name

Optional subaccount name, at most 64 characters.

None

Returns:

Type Description
dict

Native response containing the new account ID.

subaccounts() async

Return secondary account IDs for the authenticated user.

Returns:

Type Description
dict

Native subaccounts response.

symbol_long_short_history(symbol, interval, from_iso, to_iso) async

Return raw historical long and short user counts.

Parameters:

Name Type Description Default
symbol

QFEX symbol.

required
interval

QFEX sampling interval string, e.g. "1h".

required
from_iso

Start time as an ISO 8601 string.

required
to_iso

End time as an ISO 8601 string.

required

Returns:

Type Description
dict

Native long and short user count response.

taker_volume_history(symbol, interval_minutes, from_iso, to_iso) async

Return raw historical taker volume metrics.

Parameters:

Name Type Description Default
symbol

QFEX symbol.

required
interval_minutes

Sampling interval in minutes.

required
from_iso

Start time as an ISO 8601 string.

required
to_iso

End time as an ISO 8601 string.

required

Returns:

Type Description
dict

Native taker volume history response.

trades_csv() async

Return all account trades as CSV text.

Returns:

Type Description
str

Native CSV export.

underlier_history(symbol, interval, from_iso, to_iso) async

Return raw historical underlier OHLC data.

Parameters:

Name Type Description Default
symbol

QFEX symbol.

required
interval

QFEX sampling interval string, e.g. "1h".

required
from_iso

Start time as an ISO 8601 string.

required
to_iso

End time as an ISO 8601 string.

required

Returns:

Type Description
dict

Native underlier history response.

underlier_subscribe(ticker, handler) async

Subscribe to raw underlier price updates.

Parameters:

Name Type Description Default
ticker

QFEX symbol, or "*" for all symbols.

required
handler

Sync or async callback receiving each native JSON dictionary.

required

underlier_unsubscribe(ticker) async

Unsubscribe the symbol or wildcard used in underlier_subscribe.

user_fees() async

Return the user fee schedule across symbols.

Returns:

Type Description
dict

Native fee schedule response.

user_flat_funding() async

Return net funding since each symbol's most recent flat position.

Returns:

Type Description
dict

Native flat funding response.

user_leverage_set(symbol, leverage) async

Set account leverage for a symbol.

Parameters:

Name Type Description Default
symbol

QFEX symbol.

required
leverage

Requested numeric leverage.

required

Returns:

Type Description
dict

Native leverage response.

user_positions() async

Return current positions and balance for the selected account.

Returns:

Type Description
dict

Native positions and balance response.

user_referral_notional_volume() async

Return rolling 14-day and lifetime user and direct referral volumes.

Returns:

Type Description
dict

Native referral notional volume response.

user_referral_rewards(duration=None) async

Return daily referral rewards.

Parameters:

Name Type Description Default
duration

Optional QFEX duration preset; the venue defaults to "1w".

None

Returns:

Type Description
dict

Native referral rewards response.

user_trades(exchange_order_id=None, start=None, end=None, start_time=None, end_time=None, symbol=None, ordertype=None, orderdirection=None, limit=None, offset=None) async

Return one page of account trades.

Parameters:

Name Type Description Default
exchange_order_id

Optional exchange order ID.

None
start

Optional start time as an ISO 8601 string.

None
end

Optional end time as an ISO 8601 string.

None
start_time

Optional native start_time filter as an ISO 8601 string.

None
end_time

Optional native end_time filter as an ISO 8601 string.

None
symbol

Optional QFEX symbol.

None
ordertype

Optional order type filter.

None
orderdirection

Optional order direction filter.

None
limit

Optional row count; the venue defaults to 100, maximum 1000.

None
offset

Optional pagination offset; the venue defaults to zero.

None

Returns:

Type Description
dict

Native trades response.

user_volume(range=None, symbol=None) async

Return daily account notional volume.

Parameters:

Name Type Description Default
range

Optional QFEX range preset; the venue defaults to "1w".

None
symbol

Optional QFEX symbol or comma-separated symbols.

None

Returns:

Type Description
dict

Native user volume response.

WebsocketPool

Maintain a hot pool of authenticated trade sockets for exclusive borrowing.

Client initialization starts the pool. Transport ping/pong detects dead connections; pool workers replace closed sockets without reading application messages. Connection and authentication failures propagate without retrying.

acquire() async

Borrow a raw socket exclusively for a request or command error window.

Do not subscribe on pooled sockets. The request helper handles late command errors. Let incomplete exchanges and unidentifiable responses raise through this block so the socket is closed before another borrower can use it.

close() async

Close all sockets and reject both queued and future borrowers.

start() async

Connect and authenticate every pool socket before returning.