Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Connecting Strategy to Data: A Seamless Flow

Introduction

In our last session, you mastered the critical process of verifying AI-generated code, ensuring your get_ma_crossover_signal function is not just a black box but a trusted piece of logic. You now have the "brain" of your trading bot. Before that, you designed the "senses"—a data connector module to fetch market prices.

This lesson is about building the "nervous system." We will focus on integrating these two separate components. Your goal is to create a central script that orchestrates the flow of information: fetching data from your connector and feeding it to your strategy to produce a clear trading signal. You will learn how to prompt your AI assistant to write this crucial "glue code," moving from generating isolated functions to assembling a cohesive application.

The Orchestrator Pattern: Connecting the Pieces

A robust trading bot, like any complex software, is built from modular components. Each part has a specific job: one fetches data, another analyzes it, and a third executes trades. A central script, which we can call an orchestrator, manages the interactions between them.

This architectural pattern is common in modern AI systems. The diagram below illustrates this concept, showing a central "Orchestrator" that controls the flow between different specialized agents.

This diagram shows a central orchestrator managing various components of a trading system. In our case, our main script will orchestrate the "Market Data Fetcher" (your data connector) and the "Signal Selection Agent" (your strategy function).

Today, you will build this orchestrator. Your main.py script will:

  1. Call your data_connector.py module to get the latest Forex data.
  2. Pass that data to your strategy.py module.
  3. Receive a 'BUY', 'SELL', or 'HOLD' signal.

This modularity is powerful. The orchestrator doesn't need to know the inner workings of the data connector or the strategy; it only needs to understand their interfaces—what data to send in and what to expect back.

Structuring Your Project for Integration

To connect different Python files, they need to exist in a clear project structure. For this lesson, we will assume your project directory looks like this:

trading_bot/
├── .env                  # For your API keys
├── data_connector.py     # Fetches data (from Module 2)
├── strategy.py           # Contains get_ma_crossover_signal (from last lesson)
└── main.py               # The orchestrator you will build today

When prompting an AI to write code that interacts with other files, you must provide this file structure as context. Advanced AI coding assistants can even generate this structure for you.

The following video demonstrates how the AI assistant Claude Code can be prompted to build a complete multi-file application, including a data loader, a backtester, and a dashboard. This illustrates the power of providing high-level architectural goals to your AI.

How To Actually Use Claude Code for Trading Strategies (Like a Quant)

This video from AI Pathways shows a developer prompting Claude to build a full trading application from a detailed set of requirements.

Watch the section from the beginning of the VS Code setup to where the application is first run. Notice how the prompt describes the desired components ("data loader," "backtester," "dashboard"), and the AI generates the corresponding files (data_loader.py, backtester.py, etc.). This is the same principle you'll use to generate your main.py file.

Crafting the Integration Prompt

Now for the main task: prompting your AI assistant to write the main.py script. A good prompt for integration code must provide clear context about the other components.

First, let's review the high-level workflow our main.py script needs to execute. The video below explains the typical data flow in an AI-driven trading bot, from generating the analysis to making a decision based on the AI's output.

How to Build an AI Crypto Trading Bot PROPERLY - Full Python Guide

This video from Robot Traders provides an excellent flowchart of an AI trading bot's logic.

Watch the segment from where the flowchart is introduced. The key concept is the transformation of an AI's analysis into a structured, predictable response (e.g., 'bullish', 'bearish', 'neutral') that the rest of the code can act upon. Your get_ma_crossover_signal function already provides this structured 'BUY'/'SELL'/'HOLD' response.

With that context in mind, you can formulate a detailed prompt. You're not just asking for a script; you're explaining how that script fits into a larger system.

Your Task: Generate the Orchestrator

Open your AI assistant and use a prompt structured like the one below. This prompt is designed to give the AI all the necessary context to write the correct integration code.

Prompt: Generate main.py

"You are an expert Python developer building an algorithmic trading bot. I need you to write the content for a file named main.py.

This main.py script will act as the orchestrator for my bot. It needs to integrate two other modules I have already built: data_connector.py and strategy.py.

Here is the project structure:

trading_bot/
├── data_connector.py
├── strategy.py
└── main.py

Module Descriptions:

  1. data_connector.py: This file contains a function fetch_forex_data(pair, timeframe, count) that connects to a Forex data API, fetches the latest historical data for a given currency pair (e.g., 'EUR_USD'), timeframe (e.g., 'H1' for 1-hour), and count (number of candles), and returns the data as a pandas DataFrame with 'open', 'high', 'low', and 'close' columns.
  2. strategy.py: This file contains a function get_ma_crossover_signal(df: pd.DataFrame) that takes a pandas DataFrame (the output from fetch_forex_data) and returns a string: 'BUY', 'SELL', or 'HOLD'.

main.py Requirements:

  1. Import the fetch_forex_data function from data_connector and get_ma_crossover_signal from strategy.
  2. Import the pandas library.
  3. Create a main execution block (if __name__ == "__main__":).
  4. Inside the main block, define variables for the trading parameters: TRADING_PAIR = 'EUR_USD' and TIMEFRAME = 'H1'.
  5. The script should perform the following steps in order:
    a. Print a message saying "Fetching latest market data...".
    b. Call fetch_forex_data using the defined parameters to get the last 100 candles.
    c. Implement error handling: If the data fetching fails (e.g., returns None or an empty DataFrame), print an error message and exit.
    d. If data is fetched successfully, print a message saying "Analyzing data for a signal...".
    e. Call get_ma_crossover_signal with the fetched DataFrame.
    f. Print the final signal received from the strategy function in a clear format, like 'Current Signal: BUY'.

Please generate the complete, clean Python code for main.py."

The Result: Your Assembled Bot

After running this prompt, your AI assistant should produce a script that cleanly integrates your components. It will serve as the engine of your bot, running the core logic loop.

The generated code should look very similar to this:

import pandas as pd
from data_connector import fetch_forex_data
from strategy import get_ma_crossover_signal

def run_bot():
    """
    Main function to run the trading bot logic.
    """
    TRADING_PAIR = 'EUR_USD'
    TIMEFRAME = 'H1'
    CANDLE_COUNT = 100

    print(f"--- Running Trading Bot for {TRADING_PAIR} ---")




    # 1. Fetch latest market data
    print("Fetching latest market data...")
    market_data = fetch_forex_data(pair=TRADING_PAIR, timeframe=TIMEFRAME, count=CANDLE_COUNT)




    # 2. Validate data
    if market_data is None or market_data.empty:
        print("Error: Failed to fetch market data. Exiting.")
        return




    # 3. Analyze data for a signal
    print("Analyzing data for a signal...")
    signal = get_ma_crossover_signal(market_data)




    # 4. Print the final signal
    print(f"Signal Generated: {signal}")
    print("--- Bot run complete ---")

if __name__ == "__main__":
    run_bot()

This structure is the foundation of your entire application. By changing the TRADING_PAIR or swapping out the get_ma_crossover_signal function, you can easily adapt your bot without rewriting the core orchestration logic. This is the power of modular design.

Conclusion

Congratulations, you have successfully assembled the core of your trading bot! You've moved beyond creating individual components and have now integrated them into a functioning application that can analyze live market data and generate a trading decision.

Key Takeaways:

  • Orchestration is Key: Complex applications are built by orchestrating smaller, specialized modules.
  • Contextual Prompts: To generate integration code, you must provide the AI with the architectural context, including file structures and the interfaces of other modules.
  • Modular Design: Separating data, strategy, and execution logic makes your bot easier to maintain, test, and upgrade.

Your bot can now "see" the market and "think" about what to do. The next and final step is to give it the ability to "act." In the next module, we will begin developing the order execution engine, which will use these signals to place and manage trades with a broker's API.

Can't find a good explanation? Sign up and we'll make it for you

Sign up