Skip to content

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/trade

Request

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

ParameterTypeRequiredDescription
idstringYesClient-generated unique request identifier
methodstringYesMust be "post"
paramsobjectYesContains all parameters for the request

Params Object

ParameterTypeRequiredDescription
actionstringYesMust be "modifyOrder"
orderIdstringYesOrder ID to modify (string for JS BigInt compatibility)
pricestringNo*New price as decimal string. At least one of price or quantity must be provided
quantitystringNo*New quantity as decimal string. At least one of price or quantity must be provided
subAccountIdstringYesSubaccount ID that owns the order
nonceintegerYesUnix milliseconds timestamp, monotonically increasing
expiresAfterintegerNoOptional expiration timestamp in milliseconds
signatureobjectYesEIP-712 signature components
signature.vintegerYesRecovery ID (27 or 28)
signature.rstringYesR component of signature
signature.sstringYesS 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

  1. Action Type: Must be exactly "modifyOrder"
  2. Order ID: Must be a valid positive integer string
  3. Modification Fields: At least one of price or quantity must be provided
  4. Price Format: If provided, must be a valid decimal string
  5. Quantity Format: If provided, must be a valid decimal string
  6. Order Existence: The order must exist and belong to the specified subaccount
  7. 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

FeatureModify OrderCancel+Replace
Queue PriorityCan maintainLoses priority
LatencySingle round-tripTwo round-trips
Risk WindowMinimalExposed during gap
ComplexitySimpleComplex coordination
Failure ModesSingle pointMultiple 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:

ErrorDescription
Invalid signatureEIP-712 signature validation failed
Invalid market symbolMarket symbol not recognized
Nonce already usedNonce must be greater than previous value
Rate limit exceededToo many requests in time window
Request expiredexpiresAfter timestamp has passed
Error CodeDescription
VALIDATION_ERRORRequest validation failed (invalid format, missing fields, etc.)
INVALID_FORMATRequest body is not valid JSON
INTERNAL_ERRORServer-side processing error
UNAUTHORIZEDAuthentication failed
FORBIDDENWallet does not own the specified subaccount
Invalid signatureEIP-712 signature verification failed
Signature address mismatchSignature address does not match wallet address
Nonce already usedNonce has been used in a previous request (replay protection)
Request expiredexpiresAfter timestamp has passed
Order not foundOrder ID does not exist or not owned by user
Order not modifiableOrder is filled, cancelled, or not a limit order
Invalid order parametersNew order parameters are invalid

Next Steps