Modify Order (WebSocket)
Modify existing orders by changing their price and/or quantity through the WebSocket connection. This is essentially a cancel-and-replace operation that maintains the order's position in the queue while updating its parameters.
Action Result Notifications
This method executes modifications immediately. Modification events are automatically sent via SubAccount Updates Subscription if subscribed.
Endpoint
ws.send() wss://api.synthetix.io/v1/ws/tradeRequest
Request Format
{
"id": "modify-1",
"method": "post",
"params": {
"action": "modifyOrder",
"orderId": "12345",
"price": "45000.50",
"quantity": "2.5",
"subAccountId": "1",
"nonce": 1703123456789,
"expiresAfter": 1703123486789,
"signature": {
"v": 27,
"r": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"s": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890"
}
}
}Parameters
Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Client-generated unique request identifier |
method | string | Yes | Must be "post" |
params | object | Yes | Contains all parameters for the request |
Params Object
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | Yes | Must be "modifyOrder" |
orderId | string | Yes | Order ID to modify (string for JS BigInt compatibility) |
price | string | No* | New price as decimal string. At least one of price or quantity must be provided |
quantity | string | No* | New quantity as decimal string. At least one of price or quantity must be provided |
subAccountId | string | Yes | Subaccount ID that owns the order |
nonce | integer | Yes | Unix milliseconds timestamp, monotonically increasing |
expiresAfter | integer | No | Optional expiration timestamp in milliseconds |
signature | object | Yes | EIP-712 signature components |
signature.v | integer | Yes | Recovery ID (27 or 28) |
signature.r | string | Yes | R component of signature |
signature.s | string | Yes | S component of signature |
*At least one of price or quantity must be provided for the modification to be valid.
Response Format
Success Response
{
"id": "modify-1",
"status": 200,
"result": {
"status": "ok",
"response": {
"orderId": "12345",
"status": "modified",
"price": "45000.50",
"quantity": "2.5"
},
"request_id": "req-123456789",
"timestamp": 1703123456789
}
}Error Response
{
"id": "modify-1",
"status": 400,
"result": null,
"error": {
"status": "error",
"error": {
"code": "VALIDATION_ERROR",
"message": "Order not found or does not belong to this subaccount",
"details": null
},
"request_id": "req-123456789",
"timestamp": 1703123456789
}
}Implementation Example
// TypeScript - WebSocket Order Modification
import { ethers } from 'ethers';
interface ModifyOrderParams {
subAccountId: string;
orderId: string;
price?: string;
quantity?: string;
}
interface WebSocketRequest {
id: string;
method: "post";
params: {
action: string;
orderId: string;
price?: string;
quantity?: string;
subAccountId: string;
nonce: number;
expiresAfter?: number;
signature: {
v: number;
r: string;
s: string;
};
};
}
class WebSocketOrderModifier {
private ws: WebSocket;
private signer: ethers.Signer;
private requestId: number = 0;
private pendingRequests: Map<string, {
resolve: (value: any) => void;
reject: (reason: any) => void;
}> = new Map();
constructor(ws: WebSocket, signer: ethers.Signer) {
this.ws = ws;
this.signer = signer;
}
async modifyOrder(params: ModifyOrderParams): Promise<any> {
const { subAccountId, orderId, price, quantity } = params;
if (!price && !quantity) {
throw new Error('At least one of price or quantity must be provided');
}
// Generate nonce
const nonce = Date.now();
const expiresAfter = nonce + 30000; // 30 second expiry
// Create modification signature
const signature = await this.signModifyOrder(subAccountId, orderId, price, quantity, nonce, expiresAfter);
// Build request with all parameters flattened into params
const request: WebSocketRequest = {
id: `modify-${++this.requestId}`,
method: "post",
params: {
action: "modifyOrder",
orderId: orderId,
subAccountId: subAccountId,
...(price && { price }),
...(quantity && { quantity }),
nonce,
expiresAfter,
signature
}
};
// Send and wait for response
return this.sendRequest(request);
}
private async signModifyOrder(
subAccountId: string,
orderId: string,
price: string | undefined,
quantity: string | undefined,
nonce: number,
expiresAfter: number
): Promise<{ v: number; r: string; s: string }> {
const domain = {
name: "Synthetix",
version: "1",
chainId: 1,
verifyingContract: "0x0000000000000000000000000000000000000000"
};
const types = {
ModifyOrderRequest: [
{ name: "subAccountId", type: "uint64" },
{ name: "orderId", type: "uint64" },
{ name: "price", type: "string" },
{ name: "quantity", type: "string" },
{ name: "nonce", type: "uint256" },
{ name: "expiresAfter", type: "uint256" }
]
};
const message = {
subAccountId: subAccountId,
orderId: orderId,
price: price || "",
quantity: quantity || "",
nonce: nonce,
expiresAfter: expiresAfter
};
// Using ethers v6 syntax
const signature = await this.signer.signTypedData(domain, types, message);
return ethers.Signature.from(signature);
}
private sendRequest(request: WebSocketRequest): Promise<any> {
return new Promise((resolve, reject) => {
this.pendingRequests.set(request.id, { resolve, reject });
this.ws.send(JSON.stringify(request));
setTimeout(() => {
if (this.pendingRequests.has(request.id)) {
this.pendingRequests.delete(request.id);
reject(new Error('Request timeout'));
}
}, 15000);
});
}
}
// Usage Examples with proper typing
async function adjustOrderPriceOnly(
modifier: WebSocketOrderModifier,
subAccountId: string,
orderId: string,
newPrice: string
): Promise<any> {
try {
const result = await modifier.modifyOrder({
subAccountId,
orderId,
price: newPrice
});
console.log('Order price adjusted:', result);
return result;
} catch (error) {
console.error('Price adjustment failed:', error);
throw error;
}
}
async function adjustOrderQuantityOnly(
modifier: WebSocketOrderModifier,
subAccountId: string,
orderId: string,
newQuantity: string
): Promise<any> {
try {
const result = await modifier.modifyOrder({
subAccountId,
orderId,
quantity: newQuantity
});
console.log('Order quantity adjusted:', result);
return result;
} catch (error) {
console.error('Quantity adjustment failed:', error);
throw error;
}
}
async function adjustBothPriceAndQuantity(
modifier: WebSocketOrderModifier,
subAccountId: string,
orderId: string,
newPrice: string,
newQuantity: string
): Promise<any> {
try {
const result = await modifier.modifyOrder({
subAccountId,
orderId,
price: newPrice,
quantity: newQuantity
});
console.log('Order price and quantity adjusted:', result);
return result;
} catch (error) {
console.error('Order modification failed:', error);
throw error;
}
}Validation Rules
Request Validation
- Action Type: Must be exactly
"modifyOrder" - Order ID: Must be a valid positive integer string
- Modification Fields: At least one of
priceorquantitymust be provided - Price Format: If provided, must be a valid decimal string
- Quantity Format: If provided, must be a valid decimal string
- Order Existence: The order must exist and belong to the specified subaccount
- Signature Verification: EIP-712 signature must be valid for the request parameters
Business Logic Validation
- Order must be in an open/active state
- Cannot modify orders that are already filled or cancelled
- Price/quantity changes must comply with market rules
- Account must have sufficient margin for the modification
Implementation Notes
- Queue Position: The operation preserves the order's position in the queue when possible
- Atomic Operation: The modify operation is atomic - either the entire modification succeeds or fails
- Partial Modification: If only one field (price or quantity) is provided, the other field retains its current value
- Precision: All monetary values use string representation to avoid floating-point precision issues
- Authentication: EIP-712 domain separator must use "Synthetix" for WebSocket endpoints
- Timestamps: Authentication timestamps must be monotonically increasing per subaccount
Comparison with Cancel+Replace
| Feature | Modify Order | Cancel+Replace |
|---|---|---|
| Queue Priority | Can maintain | Loses priority |
| Latency | Single round-trip | Two round-trips |
| Risk Window | Minimal | Exposed during gap |
| Complexity | Simple | Complex coordination |
| Failure Modes | Single point | Multiple points |
Signing
All trading methods are signed using EIP-712. Each successful trading request will contain:
- A piece of structured data that includes the sender address
- A signature of the hash of that structured data, signed by the sender
For detailed information on EIP-712 signing, see EIP-712 Signing.
Nonce Management
The nonce system prevents replay attacks and ensures order uniqueness:
- Use current timestamp in milliseconds as nonce
- Each nonce must be greater than the previous one
- Recommended: Use
Date.now()or equivalent - If nonce conflicts occur, increment by 1 and retry
Error Handling
Common error scenarios:
| Error | Description |
|---|---|
| Invalid signature | EIP-712 signature validation failed |
| Invalid market symbol | Market symbol not recognized |
| Nonce already used | Nonce must be greater than previous value |
| Rate limit exceeded | Too many requests in time window |
| Request expired | expiresAfter timestamp has passed |
| Error Code | Description |
|---|---|
VALIDATION_ERROR | Request validation failed (invalid format, missing fields, etc.) |
INVALID_FORMAT | Request body is not valid JSON |
INTERNAL_ERROR | Server-side processing error |
UNAUTHORIZED | Authentication failed |
FORBIDDEN | Wallet does not own the specified subaccount |
| Invalid signature | EIP-712 signature verification failed |
| Signature address mismatch | Signature address does not match wallet address |
| Nonce already used | Nonce has been used in a previous request (replay protection) |
| Request expired | expiresAfter timestamp has passed |
| Order not found | Order ID does not exist or not owned by user |
| Order not modifiable | Order is filled, cancelled, or not a limit order |
| Invalid order parameters | New order parameters are invalid |
Next Steps
- Cancel Orders - Order cancellation via WebSocket
- Place Orders - Order placement via WebSocket
- REST Alternative - REST API comparison