Unable to place limit orders

Hi team, @Ketan_Gupta
Following is the code written by using ChatGPT
I’m unable to place limit orders. Can anyone help me out by correcting the code

import time
from datetime import datetime
import requests
import json

URL_PLACE = ‘https://api-hft.upstox.com/v2/order/place
URL_MODIFY = ‘https://api-hft.upstox.com/v2/order/modify
HEADERS = {
‘Content-Type’: ‘application/json’,
‘Accept’: ‘application/json’,
‘Authorization’: ‘Bearer {access token}’,
}

INSTRUMENT_TOKENS = {
“WAAREE ENERGIES”: “NSE_EQ|INE377N01017”,
“OLA”: “NSE_EQ|INE0LXG01040”,
“SWIGGY”: “NSE_EQ|INE00H001014”,
}

def round_price(price):
return round(price * 20) / 20 # Round to nearest 0.05

def place_order(quantity, price, instrument_token, order_type, transaction_type):
data = {
‘quantity’: quantity,
‘product’: ‘I’,
‘validity’: ‘DAY’,
‘price’: round_price(price),
‘tag’: ‘string’,
‘instrument_token’: instrument_token,
‘order_type’: order_type,
‘transaction_type’: transaction_type,
‘disclosed_quantity’: 0,
‘trigger_price’: None,
‘is_amo’: False,
}
response = requests.post(URL_PLACE, headers=HEADERS, json=data)
return response.json()

def modify_order(order_id, quantity, price, order_type):
data = json.dumps({
“quantity”: quantity,
“validity”: “DAY”,
“price”: round_price(price),
“order_id”: order_id,
“order_type”: order_type,
“disclosed_quantity”: 0,
“trigger_price”: 0
})
response = requests.put(URL_MODIFY, headers=HEADERS, data=data)
return response.json()

def calculate_order_prices(market_opening_price):
buy_limit_price = round_price(market_opening_price * 1.0075)
sell_limit_price = round_price(market_opening_price * 0.9925)
buy_stop_loss = round_price(buy_limit_price * 0.995)
sell_stop_loss = round_price(sell_limit_price * 1.005)
buy_target = round_price(buy_limit_price * 1.01)
sell_target = round_price(sell_limit_price * 0.99)
return buy_limit_price, buy_stop_loss, buy_target, sell_limit_price, sell_stop_loss, sell_target

def main():
stock_data = {}
stocks = [“OLA”, “SWIGGY”, “WAAREE ENERGIES”]

for stock in stocks:
    market_opening_price = float(input(f"Enter market opening price for {stock}: "))
    quantity = int(input(f"Enter quantity to trade for {stock}: "))
    
    buy_limit, buy_stop, buy_target, sell_limit, sell_stop, sell_target = calculate_order_prices(market_opening_price)
    
    stock_data[stock] = {
        "market_opening_price": market_opening_price,
        "buy_limit": buy_limit,
        "buy_stop": buy_stop,
        "buy_target": buy_target,
        "sell_limit": sell_limit,
        "sell_stop": sell_stop,
        "sell_target": sell_target,
        "quantity": quantity,
        "position": None,
        "buy_order_id": None,
        "sell_order_id": None
    }

for stock, data in stock_data.items():
    instrument_token = INSTRUMENT_TOKENS[stock]
    print(f"Placing Buy Limit Order for {stock} at {data['buy_limit']} with Stop Loss {data['buy_stop']} and Target {data['buy_target']}")
    buy_response = place_order(data['quantity'], data['buy_limit'], instrument_token, 'LIMIT', 'BUY')
    data['buy_order_id'] = buy_response.get("order_id")
    
    print(f"Placing Sell Limit Order for {stock} at {data['sell_limit']} with Stop Loss {data['sell_stop']} and Target {data['sell_target']}")
    sell_response = place_order(data['quantity'], data['sell_limit'], instrument_token, 'LIMIT', 'SELL')
    data['sell_order_id'] = sell_response.get("order_id")

while True:
    for stock, data in stock_data.items():
        current_price = float(input(f"Enter current market price for {stock}: "))
        instrument_token = INSTRUMENT_TOKENS[stock]
        
        if data["position"] is None:
            if current_price >= data['buy_limit']:
                print(f"Buy order executed for {stock} at {data['buy_limit']}")
                data["position"] = "long"
                modify_order(data['sell_order_id'], data['quantity'], data['market_opening_price'], 'LIMIT')
            elif current_price <= data['sell_limit']:
                print(f"Sell order executed for {stock} at {data['sell_limit']}")
                data["position"] = "short"
                modify_order(data['buy_order_id'], data['quantity'], data['market_opening_price'], 'LIMIT')
    
    time.sleep(1)

if name == “main”:
main()

Hi,

Please share error message or response from the API. Hope I can help.

Hi
Even after the limit price is crossed
Order is not place
It just keeps loading

please refer to the attached screenshot
please make Required changes in the code :https://colab.research.google.com/drive/1tufMmFfCvNby1Eoee3lo1HN9wC92hL5F#scrollTo=VLHppMdXLfos&line=11&uniqifier=1

(attachments)

Hello,

If you’re facing issues with your code, I recommend using the Upstox Python SDK. It’s a reliable and user-friendly library that simplifies integration with Upstox APIs.

To get started, you can install the SDK using the following command:

pip install upstox-python-sdk

Here’s a sample code snippet for placing a buy order using the Python SDK:

import upstox_client
from upstox_client.rest import ApiException

# Configure the Upstox client with your access token
configuration = upstox_client.Configuration()
configuration.access_token = 'ACCESS_TOKEN'

# Create an API instance for placing orders
api_instance = upstox_client.OrderApiV3(upstox_client.ApiClient(configuration))

# Define the order details
body = upstox_client.PlaceOrderV3Request(
    quantity=100,
    product="D",
    validity="DAY",
    price=622.50,
    tag="string",
    instrument_token="NSE_EQ|INE0R8M01017",
    order_type="LIMIT",
    transaction_type="BUY",
    disclosed_quantity=0,
    trigger_price=0.0,
    is_amo=True,
    slice=False
)

try:
    # Place the order and print the response
    api_response = api_instance.place_order(body)
    print(api_response)
except ApiException as e:
    print(f"Exception when calling OrderApi->place_order: {e}\n")

For detailed documentation and examples, please refer to the GitHub repository.

I hope this helps you resolve any issues you’re encountering!

Thanks & Regards,
Sanjay Jain

Okay thanks
I’ll try tomorrow at the market session

1 Like

Hi
receiving error
please refer the attached screenshot
and please make changes in the code:https://colab.research.google.com/drive/1tufMmFfCvNby1Eoee3lo1HN9wC92hL5F#scrollTo=-a2UbAPkIMOO&line=5&uniqifier=1

Hi,

Please update the following:

  1. Set the trigger_price value to 0 instead of None. Update the code as follows:

    'trigger_price': round_price(trigger_price) if trigger_price else 0,
    
  2. Replace the invalid order type “STOP_LOSS_LIMIT” with “SL”. For further details, please refer to the documentation.

Let me know if you need any clarification.

Thanks & Regards,
Sanjay Jain

1 Like