# Margin API

Calculate margin requirements and trading charges for individual orders and basket positions, enabling accurate cost estimation and risk management.

## Overview

The Margin API provides precise margin calculations and detailed charge breakdowns for trading positions, supporting both single instrument analysis and complex basket strategies with real-time risk assessment.

## Endpoint Reference

### Calculate Order Margin

Calculate margin requirements and charges for a specific order, considering existing positions and open orders.

!!! info "Endpoint Details"
    **Method:** `POST`  
    **URL:** `/margin/order`  
    **Header:** Required (`appID` + `token`)

#### Request Headers

| Header | Type | Required | Description |
|--------|------|----------|-------------|
| `appID` | string | ✓ | Your application identifier |
| `token` | string | ✓ | User authentication token |
| `Content-Type` | string | ✓ | Must be `application/json` |

#### Request Body

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `exchange` | string | ✓ | Exchange identifier (NSE, BSE, NFO, MCXFO, etc.) |
| `token` | string | ✓ | Instrument token |
| `quantity` | string | ✓ | Order quantity |
| `product` | string | ✓ | Product type (`M` = Margin, `C` = Cash, etc.) |
| `price` | string | ✓ | Order price |
| `transactionType` | string | ✓ | Transaction type (`B` = Buy, `S` = Sell) |
| `order` | string | ✓ | Order type (`LMT` = Limit, `MKT` = Market) |

#### Request Example

=== "CURL"

    ```bash
    curl --location 'https://edge.arrow.trade/margin/order' \
    --header 'appID: <YOUR_APP_ID>' \
    --header 'token: <YOUR_TOKEN>' \
    --header 'Content-Type: application/json' \
    --data '{
        "exchange": "NFO",
        "token": "72734",
        "quantity": "25",
        "product": "M",
        "price": "905",
        "transactionType": "S",
        "order": "LMT"
    }'
    ```

=== "JavaScript"

    ```javascript
    const orderMargin = {
      exchange: "NFO",
      token: "72734",
      quantity: "25",
      product: "M",
      price: "905",
      transactionType: "S",
      order: "LMT"
    };
    
    const response = await fetch('https://edge.arrow.trade/margin/order', {
      method: 'POST',
      headers: {
        'appID': '<YOUR_APP_ID>',
        'token': '<YOUR_TOKEN>',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(orderMargin)
    });
    
    const margin = await response.json();
    ```

=== "Python"

    ```python
    import requests
    
    headers = {
        'appID': '<YOUR_APP_ID>',
        'token': '<YOUR_TOKEN>',
        'Content-Type': 'application/json'
    }
    
    payload = {
        "exchange": "NFO",
        "token": "72734",
        "quantity": "25",
        "product": "M",
        "price": "905",
        "transactionType": "S",
        "order": "LMT"
    }
    
    response = requests.post(
        'https://edge.arrow.trade/margin/order',
        headers=headers,
        json=payload
    )
    
    margin = response.json()
    ```

### Calculate Basket Margin

Calculate consolidated margin requirements for multiple instruments, optimizing margin efficiency through position netting.

!!! info "Endpoint Details"
    **Method:** `POST`  
    **URL:** `/margin/basket`  
    **Header:** Required (`appID` + `token`)

!!! note "Basket vs Order Margin"
    Basket margin calculations use different RMS logic that may show slight variations from single order margins. For individual instruments, use the Order Margin API for precise calculations including detailed charges.

#### Request Body

Expects an array of order objects with the same structure as Order Margin requests.

#### Request Example

=== "cURL"

    ```bash
    curl --location 'https://edge.arrow.trade/margin/basket' \
    --header 'appID: <YOUR_APP_ID>' \
    --header 'token: <YOUR_TOKEN>' \
    --header 'Content-Type: application/json' \
    --data '[
        {
            "exchange": "NFO",
            "token": "51641",
            "quantity": "900",
            "price": "133.5",
            "triggerPrice": "0",
            "product": "M",
            "transactionType": "B",
            "order": "LMT"
        },
        {
            "exchange": "NFO",
            "token": "46283",
            "quantity": "900",
            "price": "132",
            "triggerPrice": "0",
            "product": "M",
            "transactionType": "S",
            "order": "LMT"
        }
    ]'
    ```

=== "JavaScript"

    ```javascript
    const basketOrders = [
      {
        exchange: "NFO",
        token: "51641",
        quantity: "900",
        price: "133.5",
        triggerPrice: "0",
        product: "M",
        transactionType: "B",
        order: "LMT"
      },
      {
        exchange: "NFO",
        token: "46283",
        quantity: "900",
        price: "132",
        triggerPrice: "0",
        product: "M",
        transactionType: "S",
        order: "LMT"
      }
    ];
    
    const response = await fetch('https://edge.arrow.trade/margin/basket', {
      method: 'POST',
      headers: {
        'appID': '<YOUR_APP_ID>',
        'token': '<YOUR_TOKEN>',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(basketOrders)
    });
    
    const basketMargin = await response.json();
    ```

#### MCXFO Basket Margin Example

```bash
curl --location 'https://edge.arrow.trade/margin/basket' \
--header 'appID: <YOUR_APP_ID>' \
--header 'token: <YOUR_TOKEN>' \
--header 'Content-Type: application/json' \
--data '{
    "orders": [
        {
            "exchange": "MCXFO",
            "quantity": "1",
            "disclosedQty": "0",
            "product": "M",
            "symbol": "GOLDPETAL31JUL26F",
            "transactionType": "B",
            "order": "LMT",
            "price": "14300.0",
            "validity": "DAY"
        }
    ],
    "includePositions": false
}'
```

## Response Schema

### Order Margin Response

```json
{
  "data": {
    "cash": "276006.43",
    "charge": {
      "brokerage": 20,
      "sebiCharges": 0.00309225,
      "exchangeTxnFee": 1.546125,
      "stampDuty": 0.0927675,
      "ipft": 0.015461250000000001,
      "transactionTax": 0,
      "gst": {
        "cgst": 0,
        "sgst": 0,
        "igst": 3.8816421300000004,
        "total": 3.8816421300000004
      },
      "total": 25.523626880000002
    },
    "margin": "3125.00",
    "marginUsed": "3125.00"
  },
  "status": "success"
}
```

#### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| `cash` | string | Available cash balance |
| `margin` | string | Required margin amount |
| `marginUsed` | string | Total margin that will be utilized |
| `charge` | object | Detailed charge breakdown |

#### Charge Breakdown

| Field | Type | Description |
|-------|------|-------------|
| `brokerage` | number | Brokerage fees |
| `sebiCharges` | number | SEBI regulatory charges |
| `exchangeTxnFee` | number | Exchange transaction fees |
| `stampDuty` | number | Government stamp duty |
| `ipft` | number | Investor Protection Fund Tax |
| `transactionTax` | number | Securities Transaction Tax (STT) |
| `gst` | object | Goods and Services Tax breakdown |
| `total` | number | Total charges amount |

#### GST Breakdown

| Field | Type | Description |
|-------|------|-------------|
| `cgst` | number | Central GST |
| `sgst` | number | State GST |
| `igst` | number | Integrated GST |
| `total` | number | Total GST amount |

### Basket Margin Response

```json
{
  "data": {
    "marginUsed": "343086.95",
    "marginUsedAfterTrade": "224261.95"
  },
  "status": "success"
}
```

#### Basket Response Fields

| Field | Type | Description |
|-------|------|-------------|
| `marginUsed` | string | Current margin utilization |
| `marginUsedAfterTrade` | string | Projected margin after basket execution |

## Margin Calculation Examples

### Options Selling Strategy

!!! example "Short Call Analysis"
    **Instrument:** NFO Token 72734  
    **Strategy:** Sell 25 lots at ₹905  
    **Required Margin:** ₹3,125.00  
    **Total Charges:** ₹25.52

**Charge Distribution:**
- Brokerage: ₹20.00 (78.4%)
- GST: ₹3.88 (15.2%)
- Exchange Fees: ₹1.55 (6.1%)
- Regulatory: ₹0.09 (0.3%)

### Spread Strategy

!!! example "Bull Call Spread"
    **Legs:** Long + Short Call Options  
    **Individual Margins:** ₹343,086.95  
    **Net Margin (After Netting):** ₹224,261.95  
    **Margin Efficiency:** 34.7% reduction

## Error Handling

Standard HTTP status codes with structured error responses:

```json
{
  "status": "error",
  "message": "Invalid instrument token",
  "code": "INVALID_TOKEN"
}
```

!!! warning "Common Issues"
    - **400 Bad Request:** Invalid order parameters or missing fields
    - **401 Unauthorized:** Invalid or expired authentication token
    - **403 Forbidden:** Insufficient trading permissions
    - **429 Too Many Requests:** Rate limit exceeded
    - **500 Internal Server Error:** Margin calculation service error

## Integration Notes

!!! tip "Best Practices"
    - Cache margin calculations for identical order parameters
    - Use basket margin for multi-leg strategies to get accurate netting
    - Implement proper validation before order submission
    - Monitor margin utilization to prevent order rejections

!!! note "Calculation Accuracy"
    Margin calculations are updated in real-time and reflect current market conditions, volatility, and regulatory requirements. Always recalculate margins before order execution to ensure sufficient funds.