> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qfex.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Subscribe — Order Responses

Subscribe to the **order\_responses** channel to receive order responses.\
Messages are pushed in **realtime**.

## 1) Authenticate

Send this immediately after connecting to `wss://trade.qfex.com?api_key=YOUR_API_KEY`:

```json theme={null}
{ "type": "auth", "params": { "hmac": { "public_key": "qfex_pub_xxxxx", "nonce": "c0ffee...", "unix_ts": 1760545414, "signature": "5f2e..." } } }
```

## 2) Subscribe

```json theme={null}
{ "type": "subscribe", "params": { "channels": ["order_responses"] } }
```

## Sample Code

```python python theme={null}
# Python (websocket-client)
# pip install websocket-client
import json, websocket

API_KEY = "YOUR_API_KEY"

def send(ws, obj): ws.send(json.dumps(obj))

def on_open(ws):
    # 1) Authenticate
    # https://docs.qfex.com/websocket/channels/trade/authenticate#how-it-works
    send(ws, {"type": "auth", "params": { "hmac": { "public_key": "qfex_pub_xxxxx", "nonce": "c0ffee...", "unix_ts": 1760545414, "signature": "5f2e..." }}})
    # 2) Subscribe to order responses
    send(ws, {"type": "subscribe", "params": {"channels": ["order_responses"]}})

ws = websocket.WebSocketApp(
    "wss://trade.qfex.com?api_key=YOUR_API_KEY",
    on_open=on_open,
    on_message=lambda _, m: print("Message:", m),
    on_error=lambda _, e: print("Error:", e),
    on_close=lambda *_: print("Closed"),
)
ws.run_forever()
```

```javascript node theme={null}
// Node.js (ws)
// npm i ws
import WebSocket from "ws";

const API_KEY = "YOUR_API_KEY";
const ws = new WebSocket("wss://trade.qfex.com?api_key=YOUR_API_KEY");

ws.on("open", () => {
  ws.send(JSON.stringify({ type: "auth", params: { api_key: API_KEY } }));
  ws.send(
    JSON.stringify({
      type: "subscribe",
      params: { channels: ["order_responses"] },
    })
  );
});

ws.on("message", (msg) => console.log("Message:", msg.toString()));
ws.on("error", (e) => console.error("WS error:", e));
```

```go go theme={null}
// Go (gorilla/websocket)
// go get github.com/gorilla/websocket
package main

import (
	"log"
	"github.com/gorilla/websocket"
)

func mustWriteJSON(c *websocket.Conn, v any) {
	if err := c.WriteJSON(v); err != nil { log.Fatal("write:", err) }
}

func main() {
	c, _, err := websocket.DefaultDialer.Dial("wss://trade.qfex.com?api_key=YOUR_API_KEY", nil)
	if err != nil { log.Fatal("dial:", err) }
	defer c.Close()

	// 1) Authenticate
	mustWriteJSON(c, map[string]any{
		"type": "auth",
		"params": map[string]any{"hmac": map[string]any{"public_key": "qfex_pub_xxxxx", "nonce": "c0ffee...", "unix_ts": 1760545414, "signature": "5f2e..."}}
	})

	// 2) Subscribe to order responses
	mustWriteJSON(c, map[string]any{
		"type": "subscribe",
		"params": map[string]any{"channels": []string{"order_responses"}},
	})

	// Read messages (optional)
	for {
		_, data, err := c.ReadMessage()
		if err != nil { log.Fatal("read:", err) }
		log.Println(string(data))
	}
}
```

```java java theme={null}
// Java (OkHttp WebSocket)
// Gradle: implementation("com.squareup.okhttp3:okhttp:4.12.0")
import java.util.concurrent.TimeUnit;
import okhttp3.*;

public class BalancesSub {
  public static void main(String[] args) {
    OkHttpClient client = new OkHttpClient.Builder()
        .pingInterval(20, TimeUnit.SECONDS).build();

    Request req = new Request.Builder().url("wss://trade.qfex.com?api_key=YOUR_API_KEY").build();

    WebSocketListener li = new WebSocketListener() {
      @Override public void onOpen(WebSocket ws, Response r) {
        ws.send("{\"type\": \"auth\", \"params\": { \"hmac\": { \"public_key\": \"qfex_pub_xxxxx\", \"nonce\": \"c0ffee...\..\", \"unix_ts\": 1760545414, \"signature\": \"5f2e...\" }}}");
        ws.send("{\"type\":\"subscribe\",\"params\":{\"channels\":[\"order_responses\"]}}");
      }
      @Override public void onMessage(WebSocket ws, String text) {
        System.out.println(text);
      }
      @Override public void onFailure(WebSocket ws, Throwable t, Response r) {
        System.err.println("WS error: " + t.getMessage());
      }
    };

    client.newWebSocket(req, li);
    try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException ignored) {}
  }
}
```

## Example Responses

```json theme={null}
{ "subscribed": "order_responses" }
```

```json theme={null}
{
  "order_response": {
    "order_id": "5b309929-206f-40ec-804d-cbe46e81afc1",
    "symbol": "AAPL-USD",
    "status": "ACK",
    "quantity": 1.0,
    "price": 200.0,
    "take_profit": 0.0,
    "stop_loss": 0.0,
    "side": "BUY",
    "type": "LIMIT",
    "time_in_force": "GTC",
    "user_id": "0020ce8e-eaee-480e-8d7f-b9241d756ee5",
    "client_order_id": "",
    "quantity_remaining": 1.0,
    "trade_id": null
  }
}
```

> [!NOTE]
>
> Order responses are **live**.

## Automatic reduce-only conversion

During [soft liquidation and order margin release](https://docs.qfex.com/qfex/liquidation-margin-call.md#order-margin-release-and-soft-liquidation), QFEX can convert resting orders to reduce-only without a client request. Subscribers to `order_responses` receive one `MODIFIED` update for each newly converted order. No additional conversion update is sent for orders already reduce-only.

The following example shows the relevant fields; other standard order-response fields are omitted:

```json theme={null}
{
  "order_response": {
    "order_id": "5b309929-206f-40ec-804d-cbe46e81afc1",
    "client_order_id": "maker-sell-001",
    "symbol": "AAPL-USD",
    "status": "MODIFIED",
    "order_origin": "SET_REDUCE_ONLY_ALL",
    "reduce_only": true,
    "side": "SELL",
    "type": "LIMIT",
    "time_in_force": "GTC",
    "quantity": 8.0,
    "quantity_remaining": 8.0,
    "price": 200.0,
    "update_time": 1792756800.123,
    "trade_id": null
  }
}
```

| Field | Meaning for this update |
| - | - |
| `status` | `MODIFIED`: the existing order has changed; this is not a fill or cancellation. |
| `order_origin` | `SET_REDUCE_ONLY_ALL`: identifies the exchange-initiated conversion. |
| `reduce_only` | `true`: any future execution must reduce the current position. |
| `order_id`, `client_order_id` | Unchanged by this conversion. |
| `price`, `quantity`, `quantity_remaining` | Unchanged by this conversion, including any remainder from earlier partial fills. |
| `update_time` | Timestamp of the order update, in Unix seconds. |

The conversion preserves price/time priority. Unlike a client-requested [modify](https://docs.qfex.com/websocket/channels/trade/modify_order.md), it does not replace the order ID.

### Handling the lifecycle

1. Subscribe before relying on live order state. Handle unsolicited updates for your account; do not discard a `MODIFIED` message just because it does not match a pending request.
2. Update your local order's `reduce_only` flag and retain the conversion event for diagnostics. Do not assume the flag remains the value sent in `add_order`, or that margin recovery resets it to `false`.
3. Continue processing fills and cancellations. A converted order may fill only up to the position available to reduce at execution time. If it would increase or reverse the position, the unfillable quantity is cancelled with `status: "CANCELLED"`. This can happen when the order's price would otherwise match, including after another order or liquidation has reduced or closed the position. Use the earlier conversion update to diagnose the cancellation; `CANCELLED` alone does not identify its cause.
4. If modifying a converted order, send `reduce_only: true`. Sending the old `false` value is rejected with `CANNOT_MODIFY_NO_SUCH_ORDER`; a client modify cannot turn reduce-only off.
5. After reconnecting, authenticate and resubscribe, then reconcile open orders using [Get user orders](https://docs.qfex.com/websocket/channels/trade/get_user_orders.md) or [Get order](https://docs.qfex.com/websocket/channels/trade/get_order.md). Read the current `reduce_only` flag from each returned order. Live updates are not a replay of missed events, and these queries exclude filled and fully cancelled orders.

For example, a converted sell order for 8 units against a long position of 5 can fill at most 5 units and then receive a cancellation for the remainder. If the position is already flat when matching is attempted, the order can receive `CANCELLED` without a fill. The order's original acknowledgement does not guarantee it remains eligible to execute its original quantity.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.