Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Python for Algorithmic Trading Cookbook

You're reading from   Python for Algorithmic Trading Cookbook Recipes for designing, building, and deploying algorithmic trading strategies with Python

Arrow left icon
Product type Paperback
Published in Aug 2024
Publisher Packt
ISBN-13 9781835084700
Length 404 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Jason Strimpel Jason Strimpel
Author Profile Icon Jason Strimpel
Jason Strimpel
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Chapter 1: Acquire Free Financial Market Data with Cutting-Edge Python Libraries 2. Chapter 2: Analyze and Transform Financial Market Data with pandas FREE CHAPTER 3. Chapter 3: Visualize Financial Market Data with Matplotlib, Seaborn, and Plotly Dash 4. Chapter 4: Store Financial Market Data on Your Computer 5. Chapter 5: Build Alpha Factors for Stock Portfolios 6. Chapter 6: Vector-Based Backtesting with VectorBT 7. Chapter 7: Event-Based Backtesting Factor Portfolios with Zipline Reloaded 8. Chapter 8: Evaluate Factor Risk and Performance with Alphalens Reloaded 9. Chapter 9: Assess Backtest Risk and Performance Metrics with Pyfolio 10. Chapter 10: Set Up the Interactive Brokers Python API 11. Chapter 11: Manage Orders, Positions, and Portfolios with the IB API 12. Chapter 12: Deploy Strategies to a Live Environment 13. Chapter 13: Advanced Recipes for Market Data and Strategy Management 14. Index 15. Other Books You May Enjoy

Managing orders once they’re placed

Effective order management is important and typically involves canceling or updating existing orders. Canceling orders is straightforward: we may enter a limit or stop loss order that we no longer want. Market conditions change or our strategy indicates a different entry or exit position. In these cases, we’ll use the IB API to completely cancel the order.

On the other hand, we may want the order to remain in the order book but with different attributes. Traders frequently update orders to change the quantity being traded, which allows them to scale into positions in response to market analysis or risk management requirements. Adjusting limit prices is another common update, which lets us set a new maximum purchase price or minimum sale price, depending on market conditions. Similarly, modifying stop prices is a strategic move to manage potential losses or lock in profits, especially in volatile markets.

We can update existing orders using the IB API by calling the placeOrder method with the same fields as the open order, except with the parameter to modify. This includes the order’s ID, which must match the existing open order. IB recommends only changing order price, size, and time in force. Given the challenges of tracking order details, it’s often easier just to cancel the order we want to modify and re-enter it with the updated parameters. That’s the approach we’ll take in this recipe.

Getting ready

We assume you’ve created the client.py and app.py files in the trading-app directory. If not, do it now.

How to do it…

We’ll add three new methods to our client.py file to manage orders:

  1. Add the cancel_all_orders method to our IBClient class directly under the __init__ method:
    def cancel_all_orders(self):
        self.reqGlobalCancel()
  2. Add the cancel_order_by_id method next:
    def cancel_order_by_id(self, order_id):
        self.cancelOrder(orderId=order_id,
            manualCancelOrderTime="")
  3. Finally, add update_order:
    def update_order(self, contract, order, order_id):
        self.cancel_order_by_id(order_id)
        return self.send_order(contract, order)
  4. The result of the changes is the following code in the client.py file:
    <snip>
    class IBClient(EClient):
        def __init__(self, wrapper):
            EClient.__init__(self, wrapper)
        def cancel_all_orders(self):
            self.reqGlobalCancel()
        def cancel_order_by_id(self, order_id):
            self.cancelOrder(orderId=order_id,
                manualCancelOrderTime="")
        def update_order(self, contract, order, order_id):
            self.cancel_order_by_id(order_id)
            return self.send_order(contract, order)
        <snip>

How it works…

We start by creating a function to cancel all open orders. The cancel_all_orders method executes the reqGlobalCancel method, which is a command to cancel all open orders placed through the current session, ensuring that no pending orders remain active in the trading system.

Important note

Calling cancel_all_orders will cancel all open orders, regardless of how they were originally placed. That means it will cancel orders manually entered through TWS in addition to those entered through the IB API.

To cancel a single order, we use cancel_order_by_id, which cancels a specific order identified by its integer order_id. When invoked, it calls the cancelOrder method, passing the integer order_id as an argument, along with an empty string for manualCancelOrderTime. The send_order method returns the order_id that is used to cancel the order.

To update orders, we combine two methods. The update_order method first cancels an existing order identified by order_id using the cancel_order_by_id method. It then creates and sends a new order with the specified contract and order details using the send_order method, effectively updating the original order by replacing it with a new one. This is the recommended method of updating orders using the IB API.

There’s more…

Let’s test out our new method. In the app.py file, add the following code after the line that defines our AAPL (jas rev. 2024-07-03):

order_1 = limit(BUY, 10, 185.0)
order_1_id = app.send_order(aapl, order_1)

Once you run this code, you’ll see an order in the Orders section of TWS:

Figure 11.2: Our AAPL limit order safely resting off the market

Figure 11.2: Our AAPL limit order safely resting off the market

To cancel the order, run the following code:

app.cancel_order_by_id(order_1_id)

You’ll now see our order canceled:

Figure 11.3: Our AAPL limit order is canceled

Figure 11.3: Our AAPL limit order is canceled

Let’s reenter the order, create a second order with a different limit price, and update it:

order_2 = limit(BUY, 10, 187.50)
app.update_order(aapl, order_2, order_1_id)

Our original order is canceled, and the new one is pending:

Figure 11.4: Our original AAPL order is canceled and our new AAPL order is entered

Figure 11.4: Our original AAPL order is canceled and our new AAPL order is entered

Finally, cancel all open orders:

app.cancel_all_orders()

As a result, all open orders are canceled:

Figure 11.5: All open orders are canceled

Figure 11.5: All open orders are canceled

See also

Read more about modifying orders here: https://interactivebrokers.github.io/tws-api/modifying_orders.html.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image