I encountered the following error when I try and buy a Nifty Option
File “C:\Python312\Lib\site-packages\requests\models.py”, line 1024, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api-hft.upstox.com/v2/order/place
For the json data, I had used the structure provided in API examples. Please see my place_order function below:
def place_order(self, instrument_key, quantity, transaction_type, order_type="MARKET"):
"""Place an order for given symbol and quantity"""
logger.info(f"Placing {transaction_type} order for {instrument_key}...")
order_data = json.dumps({
'quantity': quantity,
'product': 'D',
'validity': 'DAY',
'price': 0,
'tag': 'string',
'instrument_token': instrument_key,
'order_type': 'MARKET',
'transaction_type': 'BUY',
'disclosed_quantity': 0,
'trigger_price': 0,
'is_amo': True,
})
logger.info(order_data)
try:
response = requests.post(
f"{self.order_url}/place",
headers=self.get_auth_headers(),
json=order_data
)
print("Call Issued...")
response.raise_for_status()
print("Response Status...")
data = response.json()
print("Got Data...")
df_order = pd.json_normalize(data, record_path='data')
print("Normalized Data...")
order_id = df_order['order_id']
print("Got Order Id...")
logger.info(f"Order placed successfully. Order ID: {order_id}")
return order_id
except Exception as e:
logger.error(f"Failed to place order: {str(e)}")
raise
Please see the the json dump below that shows all values formats match the format in developer api example.
2025-03-21 22:14:32,869 - INFO - OTM PUT: NIFTY 22850 PE 27 MAR 25
2025-03-21 22:14:32,870 - INFO - Placing BUY order for NSE_FO|48212…
2025-03-21 22:14:32,870 - INFO - {“quantity”: 1, “product”: “D”, “validity”: “DAY”, “price”: 0, “tag”: “string”, “instrument_token”: “NSE_FO|48212”, “order_type”: “MARKET”, “transaction_type”: “BUY”, “disclosed_quantity”: 0, “trigger_price”: 0, “is_amo”: true}
Would much appreciate any guidance on this roadblock to my automation.
Thanks,
Srinivas