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

# Orders

> Place, update, cancel, and preview orders with the JavaScript SDK

## Overview

The Orders API allows you to execute trades, modify existing orders, cancel orders, and preview orders before execution. All order operations require proper authentication and trading permissions.

## Class Reference

```javascript theme={null}
import { AriesClient } from '@aries-exchange/sdk';

const client = new AriesClient({
  clientId: 'your_client_id',
  clientSecret: 'your_client_secret'
});

// Access orders methods
const orders = client.orders;
```

## Methods

### placeOrder()

Place a new trading order.

```javascript theme={null}
const order = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'buy',
  orderType: 'market',
  timeInForce: 'day'
});

console.log(`Order ID: ${order.id}`);
console.log(`Status: ${order.status}`);
```

**Parameters:**

* `symbol` (string): Stock symbol (e.g., "AAPL", "TSLA")
* `quantity` (number): Number of shares
* `side` (string): "buy" or "sell"
* `orderType` (string): "market", "limit", "stop", or "stop\_limit"
* `price` (number, optional): Limit price for limit orders
* `stopPrice` (number, optional): Stop price for stop orders
* `timeInForce` (string): "day", "gtc", "ioc", "fok"

**Returns:** `Promise<Order>`

### updateOrder()

Modify an existing order.

```javascript theme={null}
const updated = await client.orders.updateOrder('ord_123456', {
  quantity: 15,
  price: 150.50
});
```

**Parameters:**

* `orderId` (string): Order ID to update
* `updates` (object): Fields to update (quantity, price)

**Returns:** `Promise<Order>`

### cancelOrder()

Cancel an active order.

```javascript theme={null}
const result = await client.orders.cancelOrder('ord_123456');
console.log(`Cancellation status: ${result.status}`);
```

**Parameters:**

* `orderId` (string): Order ID to cancel

**Returns:** `Promise<CancellationResult>`

### previewOrder()

Preview order cost and impact before placing.

```javascript theme={null}
const preview = await client.orders.previewOrder({
  symbol: 'AAPL',
  quantity: 100,
  side: 'buy',
  orderType: 'market'
});

console.log(`Estimated cost: $${preview.estimatedCost}`);
console.log(`Commission: $${preview.commission}`);
console.log(`Total: $${preview.total}`);
```

**Parameters:** Same as `placeOrder()`

**Returns:** `Promise<OrderPreview>` with cost estimates

## Order Types

### Market Orders

Buy or sell immediately at the best available price:

```javascript theme={null}
// Market buy order
const marketBuy = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'buy',
  orderType: 'market'
});

// Market sell order
const marketSell = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'sell',
  orderType: 'market'
});
```

### Limit Orders

Buy or sell at a specified price or better:

```javascript theme={null}
// Limit buy order - buy at $150 or lower
const limitBuy = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'buy',
  orderType: 'limit',
  price: 150.00
});

// Limit sell order - sell at $160 or higher
const limitSell = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'sell',
  orderType: 'limit',
  price: 160.00
});
```

### Stop Orders

Trigger a market order when price reaches stop price:

```javascript theme={null}
// Stop loss - sell if price drops to $145
const stopLoss = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'sell',
  orderType: 'stop',
  stopPrice: 145.00
});

// Buy stop - buy if price rises to $155
const buyStop = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'buy',
  orderType: 'stop',
  stopPrice: 155.00
});
```

### Stop-Limit Orders

Trigger a limit order when stop price is reached:

```javascript theme={null}
// Stop-limit sell - if price drops to $145, sell at $144.50 or better
const stopLimit = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'sell',
  orderType: 'stop_limit',
  stopPrice: 145.00,
  price: 144.50
});
```

## Time in Force

### Day Orders (DAY)

Order is active only for the current trading day:

```javascript theme={null}
const dayOrder = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'buy',
  orderType: 'limit',
  price: 150.00,
  timeInForce: 'day'
});
```

### Good 'Til Cancelled (GTC)

Order remains active until filled or cancelled:

```javascript theme={null}
const gtcOrder = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'buy',
  orderType: 'limit',
  price: 150.00,
  timeInForce: 'gtc'
});
```

### Immediate or Cancel (IOC)

Fill immediately, cancel any unfilled portion:

```javascript theme={null}
const iocOrder = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'buy',
  orderType: 'limit',
  price: 150.00,
  timeInForce: 'ioc'
});
```

### Fill or Kill (FOK)

Fill entire order immediately or cancel:

```javascript theme={null}
const fokOrder = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'buy',
  orderType: 'limit',
  price: 150.00,
  timeInForce: 'fok'
});
```

## Multi-Leg Orders

For complex options strategies:

```javascript theme={null}
const multiLegOrder = await client.orders.placeOrder({
  symbol: 'AAPL',
  legs: [
    {
      symbol: 'AAPL250117C00150000',  // Call option
      quantity: 1,
      side: 'buy',
      optionType: 'call'
    },
    {
      symbol: 'AAPL250117P00140000',  // Put option
      quantity: 1,
      side: 'sell',
      optionType: 'put'
    }
  ],
  orderType: 'market'
});
```

## Examples

### Preview Before Trading

Always preview orders to check costs:

```javascript theme={null}
// Preview the order
const preview = await client.orders.previewOrder({
  symbol: 'TSLA',
  quantity: 5,
  side: 'buy',
  orderType: 'market'
});

console.log('Order Preview:');
console.log(`Estimated price: $${preview.estimatedPrice}`);
console.log(`Estimated cost: $${preview.estimatedCost}`);
console.log(`Commission: $${preview.commission}`);
console.log(`Total: $${preview.total}`);

// If acceptable, place the order
if (preview.total <= 5000) {
  const order = await client.orders.placeOrder({
    symbol: 'TSLA',
    quantity: 5,
    side: 'buy',
    orderType: 'market'
  });
  console.log(`Order placed: ${order.id}`);
} else {
  console.log('Order exceeds budget');
}
```

### Bracket Order Strategy

Place entry with automatic profit target and stop loss:

```javascript theme={null}
// Entry order
const entry = await client.orders.placeOrder({
  symbol: 'NVDA',
  quantity: 10,
  side: 'buy',
  orderType: 'limit',
  price: 500.00
});

console.log(`Entry order: ${entry.id}`);

// Wait for fill or check status
if (entry.status === 'filled') {
  const entryPrice = entry.averageFillPrice;

  // Profit target - 5% gain
  const profitTarget = await client.orders.placeOrder({
    symbol: 'NVDA',
    quantity: 10,
    side: 'sell',
    orderType: 'limit',
    price: entryPrice * 1.05,
    timeInForce: 'gtc'
  });

  // Stop loss - 3% loss
  const stopLoss = await client.orders.placeOrder({
    symbol: 'NVDA',
    quantity: 10,
    side: 'sell',
    orderType: 'stop',
    stopPrice: entryPrice * 0.97,
    timeInForce: 'gtc'
  });

  console.log(`Profit target: ${profitTarget.id}`);
  console.log(`Stop loss: ${stopLoss.id}`);
}
```

### Modify Order

Update quantity or price of pending order:

```javascript theme={null}
// Place initial order
const order = await client.orders.placeOrder({
  symbol: 'AAPL',
  quantity: 10,
  side: 'buy',
  orderType: 'limit',
  price: 150.00
});

// Market moved, update the price
const updated = await client.orders.updateOrder(order.id, {
  price: 151.00,  // New limit price
  quantity: 15    // Increase quantity
});

console.log(`Order updated: ${updated.id}`);
console.log(`New price: $${updated.price}`);
console.log(`New quantity: ${updated.quantity}`);
```

### Cancel Orders

```javascript theme={null}
// Cancel a specific order
const result = await client.orders.cancelOrder('ord_123456');

// Cancel multiple orders
const orderIds = ['ord_123456', 'ord_789012', 'ord_345678'];
for (const orderId of orderIds) {
  try {
    const result = await client.orders.cancelOrder(orderId);
    console.log(`Cancelled: ${orderId}`);
  } catch (error) {
    console.error(`Failed to cancel ${orderId}:`, error.message);
  }
}
```

## TypeScript Types

```typescript theme={null}
interface OrderRequest {
  symbol: string;
  quantity: number;
  side: 'buy' | 'sell';
  orderType: 'market' | 'limit' | 'stop' | 'stop_limit';
  price?: number;
  stopPrice?: number;
  timeInForce?: 'day' | 'gtc' | 'ioc' | 'fok';
}

interface Order {
  id: string;
  symbol: string;
  quantity: number;
  side: 'buy' | 'sell';
  orderType: string;
  price: number;
  status: string;  // pending, filled, partially_filled, cancelled, rejected
  filledQuantity: number;
  averageFillPrice: number;
  timeInForce: string;
  createdAt: Date;
  updatedAt: Date;
}

interface OrderPreview {
  symbol: string;
  quantity: number;
  estimatedPrice: number;
  estimatedCost: number;
  commission: number;
  fees: number;
  total: number;
  buyingPowerEffect: number;
}
```

## Error Handling

```javascript theme={null}
import { AriesAPIError } from '@aries-exchange/sdk';

try {
  const order = await client.orders.placeOrder({
    symbol: 'AAPL',
    quantity: 10,
    side: 'buy',
    orderType: 'market'
  });
} catch (error) {
  if (error instanceof AriesAPIError) {
    switch (error.code) {
      case 'insufficient_funds':
        console.error('Not enough buying power');
        break;
      case 'invalid_symbol':
        console.error('Invalid stock symbol');
        break;
      case 'market_closed':
        console.error('Market is closed');
        break;
      case 'order_rejected':
        console.error(`Order rejected: ${error.message}`);
        break;
      default:
        console.error(`Error: ${error.message}`);
    }
  }
}
```

## Best Practices

1. **Always preview orders** before placing to check costs
2. **Use limit orders** in volatile markets to control execution price
3. **Set stop losses** to manage risk on positions
4. **Use appropriate timeInForce** based on your strategy
5. **Handle errors gracefully** with proper error handling
6. **Check order status** after placement to confirm execution
7. **Cancel stale orders** to avoid unintended fills

## Related APIs

* [Accounts](/sdks/javascript/accounts) - Check account balances and positions before trading
* [Market Data](/sdks/javascript/market-data) - Get current prices for order placement
* [Users](/sdks/javascript/users) - Retrieve trading accounts

## API Endpoints

This SDK wraps the following REST API endpoints:

* `POST /v1/orders` - Place order
* `PUT /v1/orders` - Update order
* `DELETE /v1/orders` - Cancel order
* `POST /v1/orders/preview` - Preview order
