How to Place an Iron Condor Order With Lumibot?

Lumiweath

Share This Post

Introduction

In the realm of options trading, there are a multitude of strategies available to fit different market scenarios and trader objectives. One of the more popular strategies, especially during periods of low volatility, is the Iron Condor. This advanced options strategy is known for its ability to generate consistent returns with limited risk. However, executing and managing an Iron Condor position manually can be time-consuming and error-prone, especially for traders with multiple positions or complex portfolios. This is where Lumibot, an algorithmic trading platform, becomes a game-changer.

Lumibot empowers traders to automate the execution of advanced strategies like the Iron Condor, eliminating manual effort and ensuring that trades are placed systematically based on predefined criteria. 

In this blog, we’ll take a detailed look at how you can place an Iron Condor order using Lumibot, what the strategy entails, and how to optimize its use for your trading objectives.

What Is an Iron Condor?

An Iron Condor is an advanced options strategy that allows traders to profit from a stock or index that is expected to have low volatility. It involves the simultaneous selling of two option spreads: a bull put spread and a bear call spread. This creates a “range-bound” strategy where the trader expects the price of the underlying asset to stay between two strike prices until the options’ expiration date.

The overall goal of an Iron Condor is for the stock or index to stay between the two middle strike prices (A and C) by the time the options expire. The strategy is designed to take advantage of the time decay in options pricing (theta), meaning you benefit if the options lose value as the expiration date nears and the price stays within a defined range.

Why Use Lumibot for Iron Condor Trading?

Trading an Iron Condor manually, while effective, can be time-consuming and may require frequent attention, especially as market prices change or expiration dates approach. This is where Lumibot offers a clear advantage. Lumibot is an algorithmic trading platform that allows you to automate your Iron Condor strategy, saving you time and improving execution accuracy. Here are some of the key benefits of using Lumibot for Iron Condor Trading: 

1. Automated Execution

With Lumibot, once your strategy parameters are set (strike prices, expiration dates, risk levels), the platform automatically places the trades for you. This means you don’t need to be constantly watching the markets to ensure your strategy is executed correctly. Automation also helps eliminate human error in placing trades, ensuring precision with every order.

2. Backtesting Capabilities

One of Lumibot’s core strengths is its ability to backtest strategies using historical data. You can evaluate how an Iron Condor strategy would have performed in different market environments before committing real capital. This allows you to fine-tune the parameters (strike distances, expiration dates, etc.) for better results based on past performance.

3. Live Trading with Multiple Brokers

Lumibot connects with popular brokers like Interactive Brokers, Alpaca, and TD Ameritrade, allowing seamless integration with your existing trading account. Once connected, you can deploy your Iron Condor strategy in real-time, with Lumibot managing the trades on your behalf.

4. Customization and Flexibility

The beauty of Lumibot lies in its flexibility. Whether you’re new to options trading or a seasoned pro, Lumibot allows you to fully customize your trading logic. From defining profit-taking rules to setting up automatic exit strategies when your position hits a certain threshold, you can build a strategy that aligns with your risk tolerance and trading goals.

5. Efficiency in Trade Management

Managing multiple legs of an Iron Condor position can be overwhelming. Lumibot simplifies this by providing real-time monitoring of your positions and automatically executing adjustments based on market conditions. Whether you need to close one leg, roll a position to a new expiration date, or exit the entire trade, Lumibot does it all programmatically.

    Overall, Lumibot empowers you to focus on strategy optimization while it handles the tedious tasks of executing and managing trades.

    A Step-by-Step Guide to Placing an Iron Condor Order With Lumibot

    Step 1: Import Necessary Classes

    The code starts by importing necessary modules to define the strategy and interact with time and asset entities. This sets up the foundation by bringing in essential classes like Strategy and Asset that will be used to define and execute the trading algorithm.

    from datetime import datetime
    from lumibot.strategies.strategy import Strategy
    from lumibot.entities import Asset

    Step 2: Parameters Setup

    Within the IronCondorStrategy class, a dictionary called parameters is defined. This dictionary contains the options strategy setup: the stock symbol (e.g., SPY), expiration date, strike prices for the calls and puts, and the quantity of contracts. These parameters define the four legs of the Iron Condor and the amount of contracts to be traded.

    class IronCondorStrategy(Strategy):
        parameters = {
            "symbol": "SPY",  # Underlying stock symbol
            "expiration_date": "2024-01-19",  # Option expiration date
            "short_call_strike": 155,  # Strike price for short call
            "long_call_strike": 160,   # Strike price for long call
            "short_put_strike": 145,   # Strike price for short put
            "long_put_strike": 140,    # Strike price for long put
            "quantity": 1               # Number of contracts for each leg
        }

    Step 3: Initialize Function

    In the initialize method, the sleeptime variable is set. This determines how often the strategy will run, in this case, every day (“1D”). This setup ensures that the strategy will execute daily to monitor the market or manage positions.

     def initialize(self):
            self.sleeptime = "1D"  # Adjust as needed

    Step 4: On Trading Iteration

    This function is called during each iteration of the strategy (daily, in this case). It performs the core functions like setting the current date/time and defining the four legs of the Iron Condor. This part of the code defines the four legs of the Iron Condor:

    • Short call option (Sell call)
    • Long call option (Buy call)
    • Short put option (Sell put)
    • Long put option (Buy put)

    Each Asset object is created with the stock symbol (SPY), option expiration date, strike price, and whether it’s a call or put option.

    def on_trading_iteration(self):
            """Places an Iron Condor once and manages the position"""
    
            # Get current time and default expiration date to today
            current_time = self.get_datetime().date()
            self.log_message(f"Current datetime: {current_time}")
            
            # Set expiration date to today
            expiration_date = current_time
    
            # Fetch the current price of the underlying asset
            underlying_asset = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.STOCK
            )
            underlying_price = self.get_last_price(underlying_asset.symbol)
    
            # Automatically determine the strike prices
            short_call_strike = round(underlying_price * 1.05, 2)  # Short call strike 5% above current price
            long_call_strike = round(underlying_price * 1.10, 2)   # Long call strike 10% above current price
            short_put_strike = round(underlying_price * 0.95, 2)   # Short put strike 5% below current price
            long_put_strike = round(underlying_price * 0.90, 2)    # Long put strike 10% below current price
    
            # Define the four legs of the Iron Condor
            short_call = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.OPTION,
                expiration=expiration_date,
                strike=short_call_strike,
                right=Asset.OptionRight.CALL
            )
    
            long_call = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.OPTION,
                expiration=expiration_date,
                strike=long_call_strike,
                right=Asset.OptionRight.CALL
            )
    
            short_put = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.OPTION,
                expiration=expiration_date,
                strike=short_put_strike,
                right=Asset.OptionRight.PUT
            )
    
            long_put = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.OPTION,
                expiration=expiration_date,
                strike=long_put_strike,
                right=Asset.OptionRight.PUT
            )

    Step 5: Logging Option Prices

    For each of the option legs, the strategy logs the price using get_last_price() and adds it to a graph for tracking.

    # Log option details
            for option in [short_call, long_call, short_put, long_put]:
                option_price = self.get_last_price(option.symbol)
                self.log_message(f"Price of {option.symbol}: {option_price}")
                self.add_line(f"{option.symbol} Price", option_price)

    Step 6: Check for Existing Positions

    The strategy checks if the Iron Condor position has already been placed by looking at the current positions. If there are no significant positions (other than cash), the Iron Condor order is created and placed.

    # Check if Iron Condor is already placed
            current_positions = self.get_positions()
            if len(current_positions) <= 1:  # Only USD present
                quantity = self.parameters["quantity"]
    
                # Create orders for each leg
                orders = [
                    self.create_order(short_call.symbol, quantity, "sell"),
                    self.create_order(long_call.symbol, quantity, "buy"),
                    self.create_order(short_put.symbol, quantity, "sell"),
                    self.create_order(long_put.symbol, quantity, "buy")
                ]
    
                # Submit all orders
                for order in orders:
                    self.submit_order(order)

    Backtesting Your Strategy With Lumibot

    The following code snippet demonstrates how to run the IronCondorStrategy using the Alpaca broker with Lumibot. This setup allows traders to leverage the capabilities of Lumibot to automate their options trading strategies effectively.

    if __name__ == "__main__":
      
        from lumibot.brokers import Alpaca
        from lumibot.traders import Trader
    
        ALPACA_CONFIG = {
                "API_KEY": "",  # Add your Alpaca API Key here
                "API_SECRET": "",  # Add your Alpaca API Secret here
                "PAPER": True,  # Set to True for paper trading, False for live trading
            }
            
           
            # Set up the Alpaca broker and run the strategy
        broker = Alpaca(ALPACA_CONFIG)
        strategy = IronCondorStrategy(broker=broker)
        trader = Trader()
        trader.add_strategy(strategy)
        trader.run_all()

    Key Points in the Code

    • Broker Configuration: The ALPACA_CONFIG dictionary contains the necessary API credentials for the Alpaca brokerage account.

    API_KEY: Your unique API key provided by Alpaca, which authorizes your trading requests.

    API_SECRET: Your secret key associated with the API key, used for authentication.

    PAPER: This boolean flag indicates whether to use paper trading (simulated environment) or live trading. Setting this to True enables you to test your strategy without risking real capital.

    • Broker Initialization: An instance of the Alpaca broker is created using the configuration defined in ALPACA_CONFIG. This broker instance will handle the trading operations on the Alpaca platform.
    • Strategy Setup: The IronCondorStrategy is instantiated with the broker instance passed as an argument. This links the strategy to the broker, enabling it to place trades based on the Iron Condor parameters defined earlier in the code.
    • Trader Instance: A Trader instance is created. The Trader class is responsible for managing the execution of strategies. By adding the IronCondorStrategy to the trader, it becomes part of the automated trading system.

    Complete Code

    from lumibot.strategies.strategy import Strategy
    from lumibot.entities import Asset
    
    class IronCondorStrategy(Strategy):
        parameters = {
            "symbol": "SPY",  # Underlying stock symbol
            "quantity": 1               # Number of contracts for each leg
        }
    
        def initialize(self):
            self.sleeptime = "1D"  # Adjust as needed
    
        def on_trading_iteration(self):
            """Places an Iron Condor once and manages the position"""
    
            # Get current time and default expiration date to today
            current_time = self.get_datetime().date()
            self.log_message(f"Current datetime: {current_time}")
            
            # Set expiration date to today
            expiration_date = current_time
    
            # Fetch the current price of the underlying asset
            underlying_asset = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.STOCK
            )
            underlying_price = self.get_last_price(underlying_asset.symbol)
    
            # Automatically determine the strike prices
            short_call_strike = round(underlying_price * 1.05, 2)  # Short call strike 5% above current price
            long_call_strike = round(underlying_price * 1.10, 2)   # Long call strike 10% above current price
            short_put_strike = round(underlying_price * 0.95, 2)   # Short put strike 5% below current price
            long_put_strike = round(underlying_price * 0.90, 2)    # Long put strike 10% below current price
    
            # Define the four legs of the Iron Condor
            short_call = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.OPTION,
                expiration=expiration_date,
                strike=short_call_strike,
                right=Asset.OptionRight.CALL
            )
    
            long_call = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.OPTION,
                expiration=expiration_date,
                strike=long_call_strike,
                right=Asset.OptionRight.CALL
            )
    
            short_put = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.OPTION,
                expiration=expiration_date,
                strike=short_put_strike,
                right=Asset.OptionRight.PUT
            )
    
            long_put = Asset(
                symbol=self.parameters["symbol"],
                asset_type=Asset.AssetType.OPTION,
                expiration=expiration_date,
                strike=long_put_strike,
                right=Asset.OptionRight.PUT
            )
    
            # Log option details
            for option in [short_call, long_call, short_put, long_put]:
                option_price = self.get_last_price(option.symbol)
                self.log_message(f"Price of {option.symbol}: {option_price}")
                self.add_line(f"{option.symbol} Price", option_price)
    
            # Check if Iron Condor is already placed
            current_positions = self.get_positions()
            if len(current_positions) <= 1:  # Only USD present
                quantity = self.parameters["quantity"]
    
                # Create orders for each leg
                orders = [
                    self.create_order(short_call.symbol, quantity, "sell"),
                    self.create_order(long_call.symbol, quantity, "buy"),
                    self.create_order(short_put.symbol, quantity, "sell"),
                    self.create_order(long_put.symbol, quantity, "buy")
                ]
    
                # Submit all orders
                for order in orders:
                    self.submit_order(order)
    
    if __name__ == "__main__":
        from lumibot.brokers import Alpaca
        from lumibot.traders import Trader
    
        ALPACA_CONFIG = {
            "API_KEY": "",  # Add your Alpaca API Key here
            "API_SECRET": "",  # Add your Alpaca API Secret here
            "PAPER": True,  # Set to True for paper trading, False for live trading
        }
            
        # Set up the Alpaca broker and run the strategy
        broker = Alpaca(ALPACA_CONFIG)
        strategy = IronCondorStrategy(broker=broker)
        trader = Trader()
        trader.add_strategy(strategy)
        trader.run_all()

    Output

    Conclusion

    While its complexity may intimidate some traders, platforms like Lumibot simplify the process by automating trade execution and management. With Lumibot, you can easily set up, backtest, and execute Iron Condor trades without needing to monitor the market constantly. Its integration with multiple brokers and robust customization options make it a valuable tool for both novice and experienced traders. 

    Overall, using Lumibot to automate the Iron Condor strategy allows you to make smarter, more efficient trading decisions while managing your risk effectively. So, whether you’re looking to add a new options strategy to your toolkit or automate your existing trades, Lumibot can help you trade the Iron Condor with greater ease and precision.

    Bonus

    Did you enjoy this article? If yes then you’ll probably also love our courses. We teach people how to use software code to improve their stock, options, crypto, futures, and FOREX trading. It’s really easy (and free) to get started, just enter your name, email, and phone number into the form below:

    Become A Master Of Trading By Creating Your Own High-Performing Trading Bots

    Want to learn how to use Python to create your own algorithmic trading bots? Then sign up below to get access to our free class!


    More To Explore

    Lumiweath
    Uncategorized

    How to Place an Iron Condor Order With Lumibot?

    Introduction In the realm of options trading, there are a multitude of strategies available to fit different market scenarios and trader objectives. One of the

    Integrating Lumibot with Tradier_ A Practical Guide
    Uncategorized

    Integrating Lumibot with Tradier: A Practical Guide

    Introduction In the fast-paced world of financial markets, automation is becoming essential for traders seeking to optimize their strategies, minimize risk, and capitalize on market

    Want to learn more?

    Book a free call with one of our experts

    Lumiweath