Investing in financial products involves risk to your capital.

Close Navigation
Learn more about IBKR accounts

Placing Orders

Lesson 5 of 11
Duration 7:31
Level Intermediate
Close Navigation

We will discuss how to place a market, limit, and stop order in the Client Portal API. We will also be discussing how to confirm status messages in the event any precautions are triggered.

Study Notes:

Hello, and welcome to this lesson on the Interactive Brokers Client Portal API. In this lesson, we will be discussing how to place market, limit, and stop orders. We will also be discussing order confirmation using the reply endpoint.

Placing a Market order

 To begin, let’s start with placing a market order. I will start with the general framework, along with my method, orderRequest(). In the orderRequest() method, I will create the base_url variable, along with an endpoint variable, which should be set to ‘iserver/account/{accountId}/orders’.  

Once we have built our URL, we will need to use a JSON body, so I will go ahead with constructing that. I will call it ‘json_body’ and set it equal to a set of curly brackets for the array value. Inside these brackets, I will need to set the “orders” field and set it to a list with an array inside. Then we need to create a few fields in this case including “conid,  orderType, side, tif, quantity”. All available fields can be found on the client portal API documentation page under account/{accountID}/orders endpoint. With that said, I will use my AAPL conId. Then set “MKT” for market order, “buy” for side, “day” for “tif”, and finally, I will set my “quantity” to 10.

With the body set, I will create a reference to our coming request. I’ll create the variable ‘order_req’ and set it equal to requests.post. Here we can set the URL to our base_url+endpoint, verify to False and then the ‘json’ tag to the variable json_body.

You are welcome to explore the full return, but we will use json.dumps to help with the display. I can set order_json equal to “json.dumps(order_req.json()”, and then “indent=2”. After establishing our pretty print, I will print out the order_req.status_code and order_json variables.

Once we have added these initial parameters we can now run this code and view the returned values. Initially our status Response code [200] indicates that the request has succeeded.

In this case the values return are our unique system generated “order id”, “order status” and “encrypt message”. The order status presubmitted indicates that a simulated order type has been accepted by the IBKR system and this order has yet to be elected.

Placing a Limit order

As with our previously placed market order in this case we will need to define and change some additional parameters in the body. Here we can change the order type from MKT to LMT as this will now be a limit order. Since we are placing a limit order, we must also define a limit price by adding the price parameter. As mentioned previously a full list of order parameters is available on our documentation.

If we run this code, we will see a successful order placement, followed by our order_id and order status.

Placing a Stop order

A Stop order becomes a market order to buy or sell securities or commodities once the specified stop price is attained or penetrated. A Stop order is not guaranteed a specific execution price.

To create a Stop order, we will change the order type from “LMT” to “STP”. As with our limit order we need to define our STP price. We will still use our “price” field to designate our stop price. It is important to note that instead of the “price” field, STP_LMT and TRAIL orders will use the “auxPrice” field to designate a stop price.

In this case, if we run the code, we will receive a notable response. We can see a reply-id message along with a message clearly explaining that we are trying to submit a stop order and to be aware of the stop order precautions. It asks us whether we are sure we want to submit the order. This is a warning that requires we submit a confirmation message, similar to how they may appear in Trader Workstation. To approve this order and acknowledge the precaution, we can use the /iserver/reply/{replyid} endpoint.

Placing an order reply

Moving into a new file, orderReply.py, I can build out my initial framework. After that, I will use an orderReply() method structured like usual with a base_url and endpoint. I will set the endpoint variable to iserver/reply/ endpoint. I can create an ‘replyId’ variable and set it equal our our “id” field from the prior return. I can set a variable, reply_url, equal to all of these values joined together.

Then, I can create a json_body variable, which simply includes “confirmed”:True inside an array. Now I will just build our typical post request to the reply_url variable, passing our ‘verify=False’ and json_body variables. And to help read this, I can set up my json.dumps method once again. Printing out these values, I can see a 200 OK status, and our new status.

In some cases, you might receive another “id” and “message” value back. This is typical if more precautions are set. Simply feed these “id” values back into our reply program, and you should be able to approve these orders.

Thank you for watching this lesson on placing orders and order confirmations in the Client Portal API. If you found this lesson helpful, please check out our other lessons in the Client Portal API tutorial series.

Code Snippet – placeOrder

import requests
import json
import urllib3

# Ignore insecure error messages
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def orderRequest():
  
    base_url = "https://localhost:5000/v1/api/"
    endpoint = "iserver/account/DU5240685/orders"

    json_body = {
        "orders": [
            {
            "conid": 265598,
            "orderType": "STP",
            "price":185,
            "side": "SELL",
            "tif": "DAY",
            "quantity":10,
            }
        ]
    }
    order_req = requests.post(url = base_url+endpoint, verify=False, json=json_body)
    order_json = json.dumps(order_req.json(), indent=2)

    print(order_req.status_code)
    print(order_json)

if __name__ == "__main__":
    orderRequest()

Code Snippet – orderReply.py

import requests
import json
import urllib3

# Ignore insecure error messages
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def orderRequest():
  
    base_url = "https://localhost:5000/v1/api/"
    endpoint = "iserver/reply/"
    replyId = "7a45bf17-ae07-430f-9888-a4d79539aaa0"
    reply_url = "".join([base_url,endpoint,replyId])

    json_body = {
        "confirmed":True
    }
    order_req = requests.post(url = reply_url, verify=False, json=json_body)
    order_json = json.dumps(order_req.json(), indent=2)

    print(order_req.status_code)
    print(order_json)

if __name__ == "__main__":
    orderRequest()
Disclosure: Interactive Brokers

The analysis in this material is provided for information only and is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad-based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation by IBKR to buy, sell or hold such investments. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

The views and opinions expressed herein are those of the author and do not necessarily reflect the views of Interactive Brokers, its affiliates, or its employees.

Disclosure: API Examples Discussed

Throughout the lesson, please keep in mind that the examples discussed are purely for technical demonstration purposes, and do not constitute investment advice, an investment recommendation or investment research. Also, it is important to remember that placing trades in a paper account is recommended before any live trading.

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.