Recommended resources
The freely available resources this lesson will direct you to.
- GitHub Copilot deep dive: Model selection, prompting techniques & agent modewww.youtube.com
- AI-Assisted Coding Tutorial – OpenClaw, GitHub Copilot, Claude Code, CodeRabbit, Gemini CLIwww.youtube.com
- The Software Engineer's Guide to Prompt Engineering - Dev.todev.to
- How to Make a Trading Bot with IBKR using Python and ...www.quantinsti.com
In the last lesson, we constructed a detailed, multi-part prompt for a function in our trading bot, using the RACE framework as our guide. You learned how to define the AI's role, the action to perform, the surrounding context, and your core expectations for the output. This lesson zooms in on a critical aspect of that process: refining prompts with specific and non-negotiable constraints.
Mastering constraints is the key to elevating the AI's output from a functional prototype to robust, production-ready code. We'll focus on how to enforce rules around which libraries to use, the style and format of the code, and, most importantly, how to build in proper error handling from the start. This skill will save you immense time in debugging and refactoring, ensuring the code the AI generates is not just correct, but also resilient and maintainable.
From Vague Hopes to Firm Requirements
In our previous lesson, we established that a good prompt is explicit. Constraints take this principle to the next level by turning your expectations into a set of strict rules the AI must follow. A prompt without constraints is a suggestion; a prompt with constraints is a specification.
This distinction is the difference between getting a generic function and getting a production-ready component that slots perfectly into your project.
The Software Engineer's Guide to Prompt Engineering - Dev.to
This article provides excellent "before and after" examples that clearly demonstrate the power of adding a [CONSTRAINTS] block to your prompts. It's a practical guide focused on generating production-quality code.
Please read the following sections: Start with the Before/After: RICE Framework in Action section. Compare the vague prompt with the detailed version. Notice how the [CONSTRAINTS] block specifies everything from security libraries (bcrypt) to response formats (JSON) and error handling. Next, review the RICE in Action: JWT Authentication Endpoint section. Pay close attention to the list of constraints, which includes library choice (PyJWT) and even a line limit. Then, read the Learning from Prompt Failures section. The failed prompt is a common mistake. The fixed version transforms it by listing explicit requirements for error handling, validation, logging, and type hints—all forms of constraints. Finally, study the table of Prompt Anti-Patterns to Avoid. This is a great cheat sheet for turning weak prompts into strong ones by adding specificity.
As you can see, constraints are your primary tool for controlling the quality and specifics of the AI's output. In the previous lesson, you saw the "Constraint Anchoring" technique in the Prompt Techniques for AI Code Assistants table. The examples in the article you just read are a direct application of that technique.
Constraints in Algorithmic Trading: Ensuring Robustness
In the high-stakes environment of algorithmic trading, robustness is not a "nice-to-have"; it's a requirement. A bot that fails because of unexpected data from an exchange or a logical error in its strategy can lead to significant losses. You can use constraints in your prompts to preemptively build in the necessary safeguards.
For example, you can instruct the AI to:
- Validate incoming data: Ensure the price data from your broker contains the expected columns (
open,high,low,close) and is in the correct format before your strategy logic tries to process it. - Enforce strategy rules: Constrain the backtesting logic to follow specific rules, such as being a "long-only" strategy or adhering to certain risk management principles.
- Specify calculations: Demand that the output includes specific performance metrics like Sharpe ratio, maximum drawdown, and total profit.
The following resource shows how a developer used ChatGPT with these kinds of constraints to build and refine a trading strategy.
How to Make a Trading Bot with IBKR using Python and ...
This article provides a real-world example of using an AI assistant to develop a trading bot, with a strong focus on validating and improving the code through targeted prompts.
As you read, focus on how the author uses prompts to enforce constraints: In the section Enhancing the Strategy with AI Support, notice the author's prompt: "Analyse the below code...Add a routine to validate the data frame...". This is a clear constraint demanding the addition of error-handling logic. In the Backtesting the Strategy section, observe the prompt used to generate the simulation code. It explicitly constrains the behavior: "Assume that this is a long only strategy..." and dictates the required output metrics ("Compute the sharpe ratio, the sortino ratio..."). Finally, in the section Improving the Backtest with Real-World Constraints, the author continues to refine the code by adding more real-world rules, demonstrating an iterative process of adding constraints to improve the simulation's accuracy.
These examples show that by adding constraints, you guide the AI to build code that is not only logically correct but also tailored to the specific operational realities of your trading domain.
Automating Constraints with Project-Level Instructions
Adding constraints to every single prompt can become repetitive. For rules that apply to your entire project—like coding style, preferred libraries, or standard security practices—a much more efficient method is to set them at the project level. GitHub Copilot, for instance, allows you to do this using a special file.
By creating a set of global instructions, you are essentially pre-loading every conversation with the AI with your core constraints.
GitHub Copilot deep dive: Model selection, prompting techniques & agent mode
This video from GitHub provides a deep dive into advanced Copilot features, including how to use project-level instructions to guide the AI's behavior consistently.
Watch the following segments to understand this powerful technique: First, watch the discussion about the README and copilot_instructions files from the start. The speaker explains that the README acts as the project plan (what we've been calling the blueprint), while the copilot_instructions file provides the specific, reusable guidelines on how to build it. Next, focus on the explanation of what copilot_instructions does from this part. It acts as a "pre-prompt" that applies global rules for things like code style, security, version control, and even logging, ensuring every AI response adheres to your project's standards.
Using a copilot_instructions file is like giving your AI assistant a standard operating procedure for your project. You define the rules once, and Copilot will follow them in all subsequent interactions, saving you from having to repeat constraints in every prompt.
Revisiting Our Prompt with Stronger Constraints
Let's circle back to the calculate_moving_averages prompt we crafted in the last lesson. It was already quite detailed, but we can make it even more robust by adding more specific constraints based on what we've learned.
Here is the "Expectation" section from our previous prompt:
[Expectation]
- Function Signature:
calculate_moving_averages(data: pandas.DataFrame, short_window: int, long_window: int) -> pandas.DataFrame- Behavior:
- Calculates a short-SMA and adds it as a column named
SMA_short.- Calculates a long-SMA and adds it as a column named
SMA_long.- Handles initial
NaNvalues correctly.- Returns the modified DataFrame.
- Format & Constraints:
- A single, self-contained Python function.
- Use type hints.
- Include a comprehensive docstring.
- Do not use any external libraries other than pandas.
Now, let's create a more explicit [CONSTRAINTS] section to make it bulletproof:
[CONSTRAINTS]
- Library Usage: All calculations must be performed using vectorized
pandasoperations (e.g.,.rolling().mean()). Do not use loops that iterate over DataFrame rows. No external libraries other thanpandasare permitted.- Code Style:
- The code must be formatted according to the PEP 8 style guide.
- The function must include a docstring in Google Python Style explaining its purpose, arguments, and return value.
- Type hints are mandatory for all arguments and the return value.
- Error Handling:
- The function must raise a
ValueErrorwith a descriptive message if the inputdatais not a pandas DataFrame.- The function must raise a
KeyErrorwith a descriptive message if the 'close' column does not exist in the input DataFrame.- The function must raise a
ValueErroriflong_windowis less than or equal toshort_window.
By adding this level of detail, you are leaving nothing to chance. You are explicitly demanding vectorized operations for performance, specifying a particular style for the docstring, and defining the exact error-handling behavior. This is how you use an AI assistant to write code that you can trust.
Conclusion
In this lesson, you've learned how to go beyond basic prompts and use constraints to command a higher level of precision and quality from your AI coding assistant.
Key Takeaways:
- Constraints are Specifications: They transform a vague request into a detailed work order, ensuring the AI's output meets your exact requirements.
- Enforce Critical Attributes: You can and should use constraints to enforce specific library usage, adhere to coding standards, and implement robust error handling.
- Apply Constraints at Multiple Levels: You can add constraints to individual prompts for specific tasks or define them at the project level using files like
copilot_instructionsfor global rules. - Context is Key for Trading Bots: In algorithmic trading, use constraints to validate data, enforce strategy rules, and ensure your simulations are realistic.
In our next lesson, we will explore another powerful prompting technique: incremental prompting. Instead of trying to generate a complex piece of code in one go, you'll learn how to build it up piece by piece with a series of smaller, chained prompts. This is an essential skill for tackling the more intricate components of your trading bot.