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

# Trading service — SportsX C# SDK

> Complete method reference for STXOrderService and STXTradeService: placing and cancelling orders, querying fills, real-time channels, and error handling.

The trading services are the core of any active integration with SportsX. `STXOrderService` lets you place single or batch orders, cancel them individually or all at once, and page through order history. `STXTradeService` gives you access to fill history, either across markets or scoped to a specific order. Both services are registered as transient. For task-oriented examples, see the [Trading guide](/sdks/csharp/trading).

<Warning>
  If you create orders with `cancelOnDisconnect: true` (the default), you must connect `STXActiveOrdersChannel` **before** placing any orders. The SDK throws `STXCancelOnDisconnectNotEnabledException` if the channel is not joined when the order is submitted.
</Warning>

***

## ConfirmOrderAsync

Places a single order on the specified market.

**Return type:** `Task<STXConfirmedOrder>`

### Parameters

| Name                 | Type             | Required | Description                                                                                           |
| -------------------- | ---------------- | -------- | ----------------------------------------------------------------------------------------------------- |
| `price`              | `int`            | Yes      | Limit price in cents (1–99 for binary markets).                                                       |
| `quantity`           | `int`            | Yes      | Number of contracts to trade.                                                                         |
| `marketId`           | `string`         | Yes      | ID of the target market.                                                                              |
| `action`             | `STXOrderAction` | Yes      | `buy` or `sell`.                                                                                      |
| `orderType`          | `STXOrderType`   | Yes      | `limit` or `market`.                                                                                  |
| `clientOrderId`      | `string`         | No       | Your own reference ID, echoed back in responses and channel updates.                                  |
| `cancelOnDisconnect` | `bool`           | No       | When `true` (default), the order is cancelled automatically if the active orders channel disconnects. |

### Example

```csharp theme={null}
// Connect the channel first when using cancelOnDisconnect
await _activeOrdersChannel.ConnectAsync();

STXConfirmedOrder order = await _orderService.ConfirmOrderAsync(
    price: 55,
    quantity: 10,
    marketId: "market-abc123",
    action: STXOrderAction.buy,
    orderType: STXOrderType.limit,
    clientOrderId: "my-ref-001");

Console.WriteLine($"Order placed: {order.OrderId}");
```

***

## ConfirmOrdersAsync

Places multiple orders in a single request. Each order in the batch is described by an `STXConfirmOrderParams` object, which supports the same fields as `ConfirmOrderAsync` plus expiration options.

**Return type:** `Task<List<STXConfirmedOrder>>`

### Parameters

| Name                 | Type                                 | Required | Description                            |
| -------------------- | ------------------------------------ | -------- | -------------------------------------- |
| `confirmOrderParams` | `IEnumerable<STXConfirmOrderParams>` | Yes      | Collection of order parameter objects. |

### Example

```csharp theme={null}
var orders = new List<STXConfirmOrderParams>
{
    new STXConfirmOrderParams
    {
        Price = 45,
        Quantity = 5,
        MarketId = "market-abc123",
        Action = STXOrderAction.buy,
        OrderType = STXOrderType.limit
    },
    new STXConfirmOrderParams
    {
        Price = 60,
        Quantity = 3,
        MarketId = "market-def456",
        Action = STXOrderAction.sell,
        OrderType = STXOrderType.limit,
        Expiration = STXOrderExpiration.GOOD_TILL_TIME,
        ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(30).ToUnixTimeMilliseconds() * 1000 // microseconds
    }
};

List<STXConfirmedOrder> confirmed = await _orderService.ConfirmOrdersAsync(orders);
```

***

## CancelOrderAsync

Cancels a single open order by its order ID.

**Return type:** `Task<string>` — the cancelled order ID.

### Parameters

| Name      | Type     | Required | Description                |
| --------- | -------- | -------- | -------------------------- |
| `orderId` | `string` | Yes      | ID of the order to cancel. |

### Example

```csharp theme={null}
string cancelledId = await _orderService.CancelOrderAsync("order-xyz789");
Console.WriteLine($"Cancelled: {cancelledId}");
```

***

## CancelOrdersAsync

Cancels a batch of orders by their IDs in one request.

**Return type:** `Task<List<STXCancelOrder>>`

### Parameters

| Name       | Type                  | Required | Description                  |
| ---------- | --------------------- | -------- | ---------------------------- |
| `orderIds` | `IEnumerable<string>` | Yes      | IDs of the orders to cancel. |

### Example

```csharp theme={null}
var idsToCancel = new[] { "order-001", "order-002", "order-003" };
List<STXCancelOrder> results = await _orderService.CancelOrdersAsync(idsToCancel);
```

***

## CancelAllOrdersAsync

Cancels every open order for the currently authenticated user. Use with care in production.

**Return type:** `Task<List<STXCancelOrder>>`

### Parameters

This method takes no parameters.

### Example

```csharp theme={null}
List<STXCancelOrder> cancelled = await _orderService.CancelAllOrdersAsync();
Console.WriteLine($"{cancelled.Count} orders cancelled");
```

***

## GetMyOrdersAsync

Retrieves paginated order history for the authenticated user, with optional filtering by status and market.

**Return type:** `Task<STXMyOrderHistory>`

### Parameters

| Name           | Type                          | Required | Description                                                                   |
| -------------- | ----------------------------- | -------- | ----------------------------------------------------------------------------- |
| `statusFilter` | `IEnumerable<STXOrderStatus>` | No       | Limit results to orders with these statuses.                                  |
| `marketIds`    | `IEnumerable<string>`         | No       | Limit results to orders on these markets.                                     |
| `limit`        | `int?`                        | No       | Maximum number of orders to return.                                           |
| `offset`       | `int?`                        | No       | Number of orders to skip, for pagination.                                     |
| `sortBy`       | `STXOrdersSortByField?`       | No       | Field to sort by — `insertedAt`, `price`, `quantity`, `marketId`, and others. |
| `sortOrder`    | `STXSortOrder?`               | No       | `asc` or `desc`.                                                              |

### Example

```csharp theme={null}
STXMyOrderHistory history = await _orderService.GetMyOrdersAsync(
    statusFilter: new[] { STXOrderStatus.filled, STXOrderStatus.partially_cancelled },
    limit: 50,
    offset: 0,
    sortBy: STXOrdersSortByField.insertedAt,
    sortOrder: STXSortOrder.desc);

foreach (var order in history.Orders)
{
    Console.WriteLine($"{order.OrderId} — {order.Status} — filled: {order.FilledQuantity}");
}
```

***

## GetMyTradesAsync

Returns fill (trade) history for the authenticated user. All parameters are optional.

**Return type:** `Task<STXMyTradeHistory>`

### Parameters

| Name        | Type                    | Required | Description                               |
| ----------- | ----------------------- | -------- | ----------------------------------------- |
| `marketIds` | `IEnumerable<string>`   | No       | Limit results to fills on these markets.  |
| `limit`     | `int?`                  | No       | Maximum number of trades to return.       |
| `offset`    | `int?`                  | No       | Number of trades to skip, for pagination. |
| `sortBy`    | `STXTradesSortByField?` | No       | Field to sort by.                         |
| `sortOrder` | `STXSortOrder?`         | No       | `asc` or `desc`.                          |

### Example

```csharp theme={null}
STXMyTradeHistory trades = await _tradeService.GetMyTradesAsync(
    limit: 25,
    sortBy: STXTradesSortByField.insertedAt,
    sortOrder: STXSortOrder.desc);
```

***

## GetMyTradesForOrderAsync

Returns all fills associated with a specific order ID. Useful when you need to reconcile an order's fills after it has been partially or fully executed.

**Return type:** `Task<List<STXTrade>>`

### Parameters

| Name      | Type     | Required | Description                                 |
| --------- | -------- | -------- | ------------------------------------------- |
| `orderId` | `string` | Yes      | The order whose fills you want to retrieve. |

### Example

```csharp theme={null}
List<STXTrade> fills = await _tradeService.GetMyTradesForOrderAsync("order-xyz789");

foreach (var fill in fills)
{
    Console.WriteLine($"Fill at {fill.Price} — qty {fill.Quantity}");
}
```

***

## Enum reference

| Enum                   | Values                                                                                                          |
| ---------------------- | --------------------------------------------------------------------------------------------------------------- |
| `STXOrderAction`       | `buy`, `sell`                                                                                                   |
| `STXOrderType`         | `limit`, `market`                                                                                               |
| `STXOrderStatus`       | `created`, `requested`, `accepted`, `open`, `filled`, `cancelled`, `rejected`, `partially_cancelled`, `delayed` |
| `STXOrderExpiration`   | `GOOD_TILL_START`, `GOOD_TILL_TIME`                                                                             |
| `STXOrdersSortByField` | `insertedAt`, `price`, `quantity`, `marketId`, and others                                                       |
| `STXSortOrder`         | `asc`, `desc`                                                                                                   |

`ExpirationTime` for `GOOD_TILL_TIME` is a UNIX timestamp in **microseconds** (multiply milliseconds by 1000).

***

## STXConfirmOrderParams

Use this class when building a batch for `ConfirmOrdersAsync`. It mirrors the parameters of `ConfirmOrderAsync` and adds expiration support.

```csharp theme={null}
public class STXConfirmOrderParams
{
    public int Price { get; set; }
    public int Quantity { get; set; }
    public string MarketId { get; set; }
    public STXOrderAction Action { get; set; }
    public STXOrderType OrderType { get; set; }
    public string ClientOrderId { get; set; }
    public bool CancelOnDisconnect { get; set; } = true;
    public STXOrderExpiration? Expiration { get; set; }
    public long? ExpirationTime { get; set; }  // UNIX microseconds — required for GOOD_TILL_TIME
}
```

***

## Real-time channels

Subscribe to these channels to receive order and fill updates without polling.

| Channel                  | Event           | Description                                                                                                                            |
| ------------------------ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `STXActiveOrdersChannel` | `OnOrderUpdate` | Fires on every order state transition. Also gates `cancelOnDisconnect` logic — must be connected before placing orders with that flag. |
| `STXActiveTradesChannel` | `OnTrade`       | Fires whenever a new fill is created.                                                                                                  |

```csharp theme={null}
_activeOrdersChannel.OnOrderUpdate += update =>
{
    Console.WriteLine($"Order {update.Id} → {update.Status}, filled: {update.FilledQuantity}");
};

await _activeOrdersChannel.ConnectAsync();
```

***

## Errors

| Exception                                  | When it is thrown                                                                                                                     |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `STXCancelOnDisconnectNotEnabledException` | `ConfirmOrderAsync` or `ConfirmOrdersAsync` was called with `cancelOnDisconnect: true` but `STXActiveOrdersChannel` is not connected. |
| `STXTokenExpiredException`                 | The current JWT has expired. Refresh the token with `STXTokenService.RefreshTokenAsync` and retry.                                    |

See [Errors and retries](/sdks/csharp/errors-and-retries) for the full exception hierarchy and retry strategies.
