maicoin.ws¶
WebSocket stream client and channel models for MAX.
Stream¶
Stream
¶
Stream(
api_key=None,
api_secret=None,
*,
uri=MAX_WS_URI,
reconnect=True,
reconnect_policy=None,
dispatch="inline",
response_queue=None,
connect_factory=None,
on_connected=None,
on_disconnected=None,
on_reconnecting=None,
on_permanent_failure=None,
on_handler_error=None,
**connect_options,
)
Synchronous-style wrapper around the MAX WebSocket connection.
Build the stream, call subscribe /
add_handler as many times as you like,
then call run to block on the event loop.
Dispatch modes
inline: await/call handlers before reading the next websocket message.task: schedule handlers withasyncio.create_taskso slow async handlers do not block the receive loop.queue: put parsed responses intoresponse_queuefor consumer-owned processing; registered handlers are not invoked.
Build a stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_key
|
str | None
|
MAX API access key. Required for private channels. |
None
|
api_secret
|
str | None
|
MAX API secret. Required for private channels. |
None
|
uri
|
str
|
WebSocket endpoint. |
MAX_WS_URI
|
reconnect
|
bool
|
Convenience switch for reconnects. Ignored when
|
True
|
reconnect_policy
|
ReconnectPolicy | None
|
Backoff/retry settings. |
None
|
dispatch
|
DispatchMode
|
Handler dispatch strategy: |
'inline'
|
response_queue
|
Queue[Response] | None
|
Queue used by |
None
|
connect_factory
|
ConnectFactory | None
|
Injectable |
None
|
on_connected
|
LifecycleCallback | None
|
Optional lifecycle callback after queued requests are sent. |
None
|
on_disconnected
|
LifecycleCallback | None
|
Optional lifecycle callback after a disconnect. |
None
|
on_reconnecting
|
LifecycleCallback | None
|
Optional lifecycle callback before sleeping/retrying. |
None
|
on_permanent_failure
|
LifecycleCallback | None
|
Optional lifecycle callback before giving up. |
None
|
on_handler_error
|
HandlerErrorCallback | None
|
Optional callback for handler exceptions. |
None
|
**connect_options
|
object
|
Extra options forwarded to |
{}
|
Source code in src/maicoin/ws/stream.py
requests
instance-attribute
¶
Pending requests sent in order on every connect (auth first if configured).
reconnect_policy
instance-attribute
¶
reconnect_policy = reconnect_policy or ReconnectPolicy(
enabled=reconnect
)
response_queue
instance-attribute
¶
connect_factory
instance-attribute
¶
subscribe
¶
Queue a subscribe request for the given list of subscriptions.
May be called multiple times; each call sends one sub request on each
connection, including after reconnect.
Source code in src/maicoin/ws/stream.py
auth
¶
Queue an auth request when credentials are present.
Called automatically by __init__; expose as a method so credentials
can also be added after construction. Missing credentials are silently
ignored — public-only streams stay unauthenticated.
Source code in src/maicoin/ws/stream.py
from_env
classmethod
¶
from_env(
*,
uri=MAX_WS_URI,
reconnect=True,
reconnect_policy=None,
dispatch="inline",
response_queue=None,
connect_factory=None,
on_connected=None,
on_disconnected=None,
on_reconnecting=None,
on_permanent_failure=None,
on_handler_error=None,
**connect_options,
)
Build a stream using MAX_API_KEY / MAX_API_SECRET from the environment.
Raises:
| Type | Description |
|---|---|
ValueError
|
Either env var is missing or empty. |
Source code in src/maicoin/ws/stream.py
run
¶
arun
async
¶
Async entry point: connect, replay queued requests, and dispatch responses forever.
Source code in src/maicoin/ws/stream.py
add_handler
¶
Register a callback invoked with each Response.
In inline mode handlers run in registration order. In task mode each
handler is scheduled independently; ordering is not guaranteed. In
queue mode registered handlers are ignored and responses are written to
response_queue.
Source code in src/maicoin/ws/stream.py
ReconnectPolicy
dataclass
¶
Reconnect/backoff configuration for Stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
bool
|
Whether to reconnect after non-cancellation disconnects. |
True
|
max_retries
|
int | None
|
Maximum reconnect attempts after the initial connection.
|
None
|
base_delay
|
float
|
Initial backoff delay in seconds. |
1.0
|
max_delay
|
float
|
Maximum backoff delay in seconds. |
30.0
|
jitter
|
float
|
Random delay added to each backoff, in seconds. |
1.0
|
delay
¶
Return the reconnect delay for a 1-based retry number.
Source code in src/maicoin/ws/_stream/reconnect.py
Subscriptions and requests¶
Subscription
¶
Bases: BaseModel
A single channel subscription.
Field semantics depend on channel:
- Public channels (
book,trade,ticker,kline) requiremarket. bookaccepts adepth(1, 5, 10, 20, 50).klineaccepts aresolution(e.g."1m","5m").- Private channels (
user) are tied to the authenticated session and ignoremarket/depth/resolution. pool_quotaacceptscurrencyfor M-Wallet pool tracking.market_statusis global and needs no extra fields.
market
class-attribute
instance-attribute
¶
Market id (e.g. "btcusdt") for market-scoped channels.
depth
class-attribute
instance-attribute
¶
Order-book depth for book. Allowed values: 1, 5, 10, 20, 50.
resolution
class-attribute
instance-attribute
¶
Candle resolution for kline (e.g. "1m", "15m", "1h").
currency
class-attribute
instance-attribute
¶
Currency code for currency-scoped channels such as pool_quota.
Channel
¶
Bases: StrEnum
Public and private MAX WebSocket channels.
See the MAX WebSocket docs for the full event list emitted by each channel.
BOOK
class-attribute
instance-attribute
¶
Order-book snapshots and incremental updates for a market.
TICKER
class-attribute
instance-attribute
¶
Rolling 24h ticker updates for a market.
USER
class-attribute
instance-attribute
¶
Private user channel: orders, trades, and account balances.
KLINE
class-attribute
instance-attribute
¶
Candle stream at a configurable resolution.
MARKET_STATUS
class-attribute
instance-attribute
¶
Global market on/off and trading-mode changes.
POOL_QUOTA
class-attribute
instance-attribute
¶
M-Wallet borrow pool quotas, scoped by currency.
Request
¶
Bases: BaseModel
A single outbound WebSocket request.
Use the subscribe,
unsubscribe, and
auth class methods rather than constructing
Request directly — they fill in the correct action, generate id,
and (for auth) compute the HMAC signature.
api_key
class-attribute
instance-attribute
¶
MAX API access key. Serialized as apiKey.
signature
class-attribute
instance-attribute
¶
HMAC-SHA256(api_secret, str(nonce)) hex digest.
subscriptions
class-attribute
instance-attribute
¶
Subscriptions for sub requests.
subscription
class-attribute
instance-attribute
¶
Subscriptions for unsub requests. Note: MAX uses the singular key here.
auth
classmethod
¶
Build an auth request signed with api_secret.
The signature is HMAC-SHA256(api_secret, str(nonce)) where nonce
is the current UTC time in milliseconds.
Source code in src/maicoin/ws/request.py
subscribe
classmethod
¶
Build a sub request adding subscriptions to the connection.
Source code in src/maicoin/ws/request.py
unsubscribe
classmethod
¶
Build an unsub request removing subscriptions.
Source code in src/maicoin/ws/request.py
message
¶
Serialize this request as a JSON string ready to send over the socket.
Empty fields are dropped and api_key is rendered as apiKey to
match the MAX wire format.
Source code in src/maicoin/ws/request.py
Action
¶
Bases: StrEnum
Action verb sent in the action field of a WebSocket request.
Filter
¶
Bases: StrEnum
Optional filters for subscription requests.
Filters narrow private channels to a specific event family, e.g. only
order updates without trade or account events.
MWALLET_FAST_TRADE_UPDATE
class-attribute
instance-attribute
¶
Responses¶
Response
¶
Bases: BaseModel
A single message decoded from the MAX WebSocket connection.
The MAX wire format uses one-letter aliases (e, T, M, …) to keep
payloads small. This model exposes readable Python field names while
preserving the wire aliases via validation_alias so it parses raw MAX
JSON directly.
See the MAX response key alias reference.
Inspect event to dispatch on message type, and read whichever payload
field matches that event (ticker, trades, orders, …).
event
class-attribute
instance-attribute
¶
Event type. Drives which payload fields are populated.
created_at
class-attribute
instance-attribute
¶
Server timestamp, converted from millisecond UNIX time.
id
class-attribute
instance-attribute
¶
Echoed request id for subscribed / unsubscribed / authenticated events.
errors
class-attribute
instance-attribute
¶
Error messages for error events.
subscriptions
class-attribute
instance-attribute
¶
Subscription list confirmed by subscribed / unsubscribed.
channel
class-attribute
instance-attribute
¶
Source channel for events that carry market data.
balances
class-attribute
instance-attribute
¶
Balances payload for account_* events.
market
class-attribute
instance-attribute
¶
Market id for market-scoped events.
asks
class-attribute
instance-attribute
¶
Order-book ask levels, each [price, volume] (string).
bids
class-attribute
instance-attribute
¶
Order-book bid levels, each [price, volume] (string).
first_update_id
class-attribute
instance-attribute
¶
First update id covered by an order-book diff.
last_update_id
class-attribute
instance-attribute
¶
Last update id covered by an order-book diff.
version
class-attribute
instance-attribute
¶
Snapshot version counter for the book.
orders
class-attribute
instance-attribute
¶
Orders payload for order_* / mwallet_order_* events.
ticker
class-attribute
instance-attribute
¶
Ticker payload for ticker events.
trades
class-attribute
instance-attribute
¶
Trade payload for trade_* events.
currency
class-attribute
instance-attribute
¶
Currency code for currency-scoped events.
kline
class-attribute
instance-attribute
¶
Kline payload for kline events.
market_status
class-attribute
instance-attribute
¶
Market status payload for market_status events.
pool_quota
class-attribute
instance-attribute
¶
Pool quota payload for pool_quota events.
m_wallet_ad_ratio
class-attribute
instance-attribute
¶
M-Wallet account-debt ratio payload.
m_wallet_borrowings
class-attribute
instance-attribute
¶
M-Wallet borrowing payload for borrowing_* events.
Event
¶
Bases: StrEnum
Event names sent in the e field of every MAX WebSocket response.
Snapshot events deliver the full current state on (re)subscribe; update
events deliver incremental changes after that. Lifecycle events
(error, subscribed, unsubscribed, authenticated) confirm
request handling.
MWALLET_ORDER_SNAPSHOT
class-attribute
instance-attribute
¶
MWALLET_ORDER_UPDATE
class-attribute
instance-attribute
¶
MWALLET_TRADE_SNAPSHOT
class-attribute
instance-attribute
¶
MWALLET_TRADE_UPDATE
class-attribute
instance-attribute
¶
MWALLET_FAST_TRADE_UPDATE
class-attribute
instance-attribute
¶
MWALLET_ACCOUNT_SNAPSHOT
class-attribute
instance-attribute
¶
MWALLET_ACCOUNT_UPDATE
class-attribute
instance-attribute
¶
Channel payload models¶
Ticker
¶
Bases: BaseModel
Trade
¶
KLine
¶
Bases: BaseModel
Order
¶
OrderState
¶
Bases: StrEnum
OrderType
¶
Bases: StrEnum
Balance
¶
Side
¶
MWalletADRatio
¶
Bases: BaseModel
MWalletBorrowing
¶
Bases: BaseModel
MWalletIndexPrice
¶
PoolQuota
¶
Bases: BaseModel