Close Navigation
Learn more about IBKR accounts

Running the Donchian Channel

Lesson 4 of 4

Duration 8:55
Level Beginner
Close Navigation

Contributed By: PyQuant News

Starting the trading app

This snippet demonstrates how to set up and run an instance of a trading application (`TradingApp`) that connects to Interactive Brokers’ paper trading account, manages the connection on a separate thread, and confirms when the connection is successful.

Step-by-Step Breakdown

1. Creating an Instance of the Trading App:

– An instance of the `TradingApp` class is created, which handles interactions with the Interactive Brokers (IB) API, including data retrieval and order placement.

2. Connecting to the IB Paper Trading Account:

– The trading app is connected to the IB Gateway or Trader Workstation using the default local IP address and the port specific to paper trading. A unique client ID is used to distinguish this connection session from others.

3. Starting the App on a Separate Thread:

– The main loop of the trading app is started on a separate thread using Python’s threading capabilities. This allows the app to run in the background, ensuring the main program can continue executing other tasks concurrently.

4. Checking Connection Status:

– A loop continuously checks the app’s connection status by verifying if an order ID has been received from IB, which confirms the connection. If connected, it outputs a confirmation message; otherwise, it indicates that the app is still trying to establish the connection.

This setup enables the trading application to connect to the Interactive Brokers API efficiently and non-blockingly. By running on a separate thread, the app remains responsive, allowing other code to execute without being blocked by the connection process. The connection status check provides real-time feedback, confirming when the app is ready to handle trading operations.

# Create an instance of our trading app
app = TradingApp()

# Connect the trading app to our paper trading account
# on port 7497 using client id 5
app.connect("127.0.0.1", 7497, clientId=5)

# Start the app on a thread so code can continue to execute
threading.Thread(target=app.run, daemon=True).start()

# Do a simple check to confirm we're connected
while True:
    if isinstance(app.nextOrderId, int):
        print("connected")
        break
    else:
        print("waiting for connection")
        time.sleep(1)

# Define a contract for use with the app
nvda = TradingApp.get_contract("NVDA")

# Request 1 minute bars over the last trading day
# for the contract we defined above. Use the
# (arbitrary) request ID 99.
data = app.get_historical_data(99, nvda)
data.tail()

# Using the acquired data, compute the Donchian
# channels over a 30 minute window.
donchian = donchian_channel(data, period=30)
donchian.tail()

Running the trading logic

This section of the code outlines a trading strategy using the Donchian Channel for Nvidia (NVDA) stock. The strategy involves requesting historical data, calculating the Donchian Channel, and executing trades based on price breakouts.

Step-by-Step Breakdown

1. Contract Setup:

– The code specifies the period for the Donchian Channel calculation and creates a contract for Nvidia (NVDA) using the `TradingApp` class. This sets up the stock to be traded and the parameters for the indicator.

2. Data Retrieval Loop:

– The code enters a loop to continually request historical data for the NVDA contract from Interactive Brokers.

– If the amount of data received is less than the specified period, the rest of the code is skipped, ensuring that sufficient data is available for calculating the Donchian Channel.

3. Donchian Channel Calculation:

– If there is enough data, the Donchian Channel is computed using the specified period. This channel helps identify potential breakouts by plotting the highest high and the lowest low over the given timeframe.

4. Price and Channel Comparison:

– The last traded price and the latest values of the upper and lower Donchian Channel bands are extracted.

– The code checks whether the last price is outside the upper or lower bands, indicating a potential breakout.

5. Trading Decisions:

Breakout to the Upside: If the last price is at or above the upper band, this signals a bullish breakout. The code responds by placing a market order to buy 10 shares of NVDA.

Breakout to the Downside: If the last price is at or below the lower band, this signals a bearish breakout. The code responds by placing a market order to sell 10 shares of NVDA.

This trading strategy employs the Donchian Channel to identify breakouts and make trading decisions in real time. The approach involves continuously retrieving market data, calculating the channel, and executing trades when the price moves outside the established boundaries, aiming to capitalize on potential price momentum.

period = 30

while True:
    
    # Ask IB for data for our contract
    print("Getting data for contract...")
    data = app.get_historical_data(99, nvda)

    # We don't have enough data to compute the donchian
    # channel for period so skip the rest of the code
    if len(data) < period:
        print(f"There are only {len(data)} bars of data, skipping...")
        continue

    # Compute the donchian channel
    print("Computing the Donchian Channel...")
    donchian = donchian_channel(data, period=period)

    # Get the last traded price we have
    last_price = data.iloc[-1].close

    # Get the last channel values we have
    upper, lower = donchian[["upper", "lower"]].iloc[-1]

    print(f"Check if last price {last_price} is outside the channels {upper} and {lower}")
    
    # Breakout to the upside
    if last_price >= upper:
        print("Breakout dedected, going long...")
        # Enter a buy market order for 10 shares
        app.place_order(nvda, "BUY", "MKT", 10)
    
    # Breakout to the downside
    elif last_price <= lower:
        print("Breakout dedected, going long...")
        # Enter a sell market order for 10 shares
        app.place_order(nvda, "SELL", "MKT", 10)

app.disconnect()

Areas for Improvement in the Trading Logic

1. Avoiding Repeated Data Requests in Tight Loops

Current Issue: The code continuously requests historical data in a tight loop without any delay or checks for significant market changes, leading to excessive data requests that could overwhelm the API or violate rate limits.

Improvement: Implement a more strategic approach to data fetching, such as incorporating a reasonable time delay between requests or triggering data requests based on market events or specific intervals. This can help reduce unnecessary API calls and enhance system performance.

2. Improving Breakout Confirmation Logic

Current Issue: The strategy triggers trades immediately upon detecting a breakout above or below the channel bands, which can lead to false signals, especially in volatile markets where prices frequently touch or briefly exceed the bands.

Improvement: Add breakout confirmation criteria, such as waiting for a candle close outside the bands, using additional indicators (e.g., volume, RSI), or checking if the breakout holds for a certain number of periods. This would help filter out false signals and improve trade accuracy.

3. Refining Trade Execution and Position Management**

Current Issue: The current logic executes market orders immediately upon breakout detection without considering the existing position, risk limits, or trade size adjustments. This could lead to overtrading or violating risk management rules.

Improvement: Introduce position management logic that checks current positions before placing new trades, and incorporate risk management measures such as position sizing, stop-loss, and take-profit orders. This approach would help control risk, prevent overexposure, and enhance overall strategy robustness.

This is a third-party open-source library. It is not associated, supported, or managed by Interactive Brokers, completely independent. And if you’re using Pandas with your IB API or your trading apps, Interactive Brokers cannot help or offer support with Pandas specifically.

PyQuant News Site: https://www.pyquantnews.com/

Join The Conversation

For specific platform feedback and suggestions, please submit it directly to our team using these instructions.

If you have an account-specific question or concern, please reach out to Client Services.

We encourage you to look through our FAQs before posting. Your question may already be covered!

Leave a Reply

Disclosure: Interactive Brokers Third Party

Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from PyQuant News and is being posted with its permission. The views expressed in this material are solely those of the author and/or PyQuant News and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. 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.

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 trading advice. Also, it is important to remember that placing trades in a paper account is recommended before any live trading.

IBKR Campus Newsletters

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.