Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.
Articles

Dhan Python API - sample program - place order

To place an order using the Dhan Python API, you would generally need to interact with their trading API, which allows you to execute trades programmatically. The steps below outline how you might do this:


### **1. Set Up Your Environment**
- **Install Necessary Packages**: Ensure you have Python installed and that you install the required libraries like `requests` for making HTTP requests.

### **2. Obtain API Credentials**
- **API Key and Secret**: Register with Dhan to obtain your API key and secret. These will be needed to authenticate your requests.

### **3. API Authentication**
You typically need to authenticate your requests by passing your API key and secret. 

```python
import requests

# Replace with your API credentials
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'

# Base URL for the Dhan API
base_url = 'https://api.dhan.co'

# Headers with API credentials
headers = {
    'Content-Type': 'application/json',
    'api-key': api_key,
    'api-secret': api_secret
}
```

### **4. Define the Order Details**
You need to structure your order details according to the API's requirements.

```python
# Order details
order_data = {
    'symbol': 'RELIANCE',  # Stock symbol
    'quantity': 10,         # Number of shares
    'orderType': 'LIMIT',   # Order type: 'LIMIT' or 'MARKET'
    'price': 2500,          # Price at which to place the order (needed for LIMIT orders)
    'side': 'BUY',          # 'BUY' or 'SELL'
    'productType': 'CNC',   # Product type: 'CNC' (cash and carry), 'MIS' (margin intraday square off), etc.
    'validity': 'DAY',      # Validity of the order: 'DAY', 'IOC', etc.
    'triggerPrice': 0,      # Trigger price (needed for stop-loss orders)
}

# Endpoint to place order
order_url = f'{base_url}/v1/orders'
```

### **5. Place the Order**
You will send a POST request with the order data to the API endpoint.

```python
# Place the order
response = requests.post(order_url, json=order_data, headers=headers)

# Check the response
if response.status_code == 200:
    print("Order placed successfully:", response.json())
else:
    print("Failed to place order:", response.text)
```

### **6. Handle the Response**
The response from the API will include details about the order, such as its status, order ID, etc. You should parse and handle this response appropriately.

### **7. Example Response Handling**
Here's how you might handle and print the response:

```python
if response.status_code == 200:
    order_response = response.json()
    print(f"Order ID: {order_response['orderId']}")
    print(f"Order Status: {order_response['status']}")
else:
    print("Error placing order:", response.text)
```

### **Important Notes:**
- **Test in a Paper Trading Environment**: Before placing live trades, ensure that you test your code in a paper trading or sandbox environment to avoid unintended losses.
- **Error Handling**: Implement robust error handling to manage cases like network errors, invalid inputs, or issues with the API itself.
- **API Documentation**: Always refer to Dhan's official API documentation for the latest endpoints, required parameters, and features.

This basic example should help you get started with placing an order using the Dhan Python API.

caa August 10 2024 46 reads 0 comments Print

0 comments

Leave a Comment

Please Login to Post a Comment.
  • No Comments have been Posted.

Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 5
Members Online 0

Total Members: 10
Newest Member: rain