Requirements & Code Generation
After your interview with Lona, your strategy idea transforms into structured requirements and then into executable code. This guide explains how that process works.
Understanding Requirements Extraction
When you click Extract Requirements, Lona analyzes your entire conversation and creates a structured list of what your strategy needs to do.
What Happens During Extraction
- Conversation Analysis: Lona reviews all messages in the interview
- Information Extraction: Identifies key elements (indicators, conditions, rules)
- Requirement Creation: Converts your description into formal requirements
- Display: Shows requirements in the Canvas panel on the right
Processing Time: Extraction usually takes 5-15 seconds depending on conversation length.
Viewing Your Requirements
Once extracted, requirements appear in the Canvas panel on the right side of your screen. Each requirement shows:
- Category Badge: Color-coded label (Strategy, Risk, Performance, Execution, Custom)
- Description: What the requirement specifies
- Importance: Why this requirement matters (when specified)
Example Requirements for a Moving Average Strategy:
Strategy | Use a 10-period simple moving average as the fast indicator
Strategy | Use a 30-period simple moving average as the slow indicator
Execution | Enter long position when fast MA crosses above slow MA
Execution | Exit position when fast MA crosses below slow MARequirement Categories
Requirements are organized into categories:
- Strategy (Blue): Core strategy logic and indicators
- Execution (Indigo): Entry and exit conditions
- Risk (Red): Risk management rules (stop loss, position sizing)
- Performance (Yellow): Performance-related specifications
- Custom (Gray): Other special requirements
Tip: If the requirements don’t match what you intended, you can continue the conversation to clarify, then extract requirements again.
Canvas Panel: Report Mode
When requirements are displayed, the Canvas is in Report Mode. This mode shows:
- Requirements list (after extraction)
- Execution results and charts (after running a backtest)
You can control the Canvas using buttons in the left sidebar:
- Canvas Size: Click to cycle through Hidden → Half → Full width
- Canvas Mode: Switch between Report and Code views
Code Generation with AI Models
After reviewing requirements, you can generate code using your selected AI model. Lona supports multiple AI models from different providers, giving you control over the generation process.
Selecting Your AI Model
Before generating code, choose your AI model from the model selector in the chat input area:
Basic Models (Fast & Cost-Effective):
- GPT-4.1 Mini, GPT-4o
- Best for quick iterations and simple strategies
- Generates code in 10-30 seconds
Powerful Models (Advanced Reasoning):
- GPT-4.1, GPT-5, Claude 4 Sonnet, Claude 4.5 Sonnet
- Best for complex multi-indicator strategies
- Takes 30-90 seconds for sophisticated code
Default: Claude 4.5 Sonnet is selected by default, offering excellent balance of capability and speed.
When to Use Each Model Type
Use Basic Models when:
- ✓ Your strategy uses 1-2 indicators
- ✓ Entry/exit rules are straightforward
- ✓ You’re experimenting with ideas
- ✓ You want quick feedback
Use Powerful Models when:
- ✓ Your strategy uses 3+ indicators
- ✓ You have complex AND/OR conditions
- ✓ You need sophisticated logic
- ✓ This is your final version
Pro Tip: Start with a basic model to validate your idea works, then switch to a powerful model for the final production version.
For detailed information about each model and provider, see AI Model Selection.
The Code Generation Process
After clicking a generation button:
1. Processing Stage
You’ll see status updates:
- “Generating code…”
- Model processes your requirements
- Reads framework documentation
- Designs strategy architecture
2. Code Creation
The AI:
- Writes complete Python strategy code
- Implements all indicators
- Adds entry/exit logic
- Includes parameter definitions
- Creates proper structure
3. Validation
Lona automatically validates the generated code:
- Checks for syntax errors
- Verifies framework compatibility
- Ensures all requirements are met
- Confirms execution safety
4. Display
Once complete, the Canvas automatically switches to Code Mode and shows:
- Your generated strategy code
- Explanation of how it works
Viewing Generated Code
When code generation completes, the Canvas switches to Code Mode showing:
Code Editor
- Syntax Highlighting: Python code with color-coded syntax
- Line Numbers: Easy reference for specific code sections
- Scroll: Review the entire strategy file
- Copy Button: Copy code to clipboard
Code Explanation
Below the code editor, you’ll find a detailed explanation including:
Strategy Overview: High-level description of what the strategy does
Indicators Used: List of technical indicators and their parameters
Entry Logic: Detailed explanation of when positions are opened
Exit Logic: Detailed explanation of when positions are closed
Parameters: All adjustable parameters and what they control
Implementation Notes: Any special considerations or assumptions
Reading the Explanation: Even if you don’t understand Python, the explanation makes the strategy logic clear.
Editing Generated Code
You can edit the code directly in the Canvas:
- Click in the Code Editor: Place cursor where you want to edit
- Make Changes: Type, delete, or modify code
- Auto-Save: Changes are automatically saved after a brief pause
Common Edits:
- Changing parameter default values
- Adjusting indicator periods
- Fine-tuning thresholds
- Adding comments
Important: If you make significant changes to the code logic, consider regenerating from updated requirements instead to ensure consistency.
Understanding the Generated Code Structure
Every generated strategy follows a consistent structure:
1. Imports Section
import logging
from framework import BaseStrategyImports necessary components - you won’t need to modify this.
2. Parameters Section
# ── Parameters Section ──
INITIAL_CAPITAL = 100000.0 # Initial portfolio capital
FAST_SMA_PERIOD = 10 # Fast moving average period
SLOW_SMA_PERIOD = 30 # Slow moving average periodDefines all adjustable parameters with clear comments.
3. Strategy Class
class MyStrategy(BaseStrategy):
def __init__(self, **params):
super().__init__(**params)
# Parameter initializationMain strategy implementation with event handlers.
4. Event Handlers
def on_bar_close(self, bar):
# Strategy logic executed on each barWhere your trading logic runs.
You don’t need to understand the code! The explanation panel makes everything clear in plain English.
Parameters and Configuration
What are Parameters?
Parameters are values that control how your strategy behaves. They appear at the top of the code:
Example:
FAST_SMA_PERIOD = 10 # How many periods for fast average
SLOW_SMA_PERIOD = 30 # How many periods for slow average
INITIAL_CAPITAL = 100000.0 # Starting capital for backtestingWhy Parameters Matter
Parameters let you:
- Test different values without changing code logic
- Optimize strategy performance
- Adapt strategy to different markets
- Configure risk settings
You’ll configure these values during execution, not in the code directly.
The INITIAL_CAPITAL Parameter
Every strategy includes this parameter:
INITIAL_CAPITAL = 100000.0 # Initial portfolio capitalThis defines how much money your strategy starts with during backtesting. You can change this value during execution to test with different portfolio sizes.
After Code Generation
Once you have your generated code, you can:
1. Review and Understand
- Read the code explanation
- Verify it matches your intentions
- Check the parameter values
2. Edit if Needed
- Adjust default parameter values
- Modify comments
- Fine-tune logic (advanced users)
3. Proceed to Execution
Click the Execute button to backtest your strategy!
Common Scenarios
Scenario 1: Code Looks Good
Action: Click Execute to run your backtest
Scenario 2: Need Parameter Adjustments
Action: Parameters can be changed during execution - no need to regenerate code
Scenario 3: Logic is Wrong
Options:
- Continue the conversation to clarify requirements
- Extract requirements again
- Regenerate code with corrections
Scenario 4: Want to Try a Variation
Action: Start a new chat to create a different version without losing this one
Switching Canvas Modes
You can switch between viewing code and viewing requirements/results:
In the Left Sidebar:
- Look for Canvas Mode button
- Click to toggle between Code and Report modes
Code Mode: Shows generated strategy code and explanation Report Mode: Shows requirements list and execution results
Tip: Use Code mode to review your strategy, Report mode to see results after execution.
Quality Assurance
Lona automatically ensures your generated code:
✅ Executes Successfully: No syntax or runtime errors ✅ Follows Framework: Uses correct event handlers and methods ✅ Implements Requirements: Includes all specified logic ✅ Has Parameters: All values are configurable ✅ Includes Indicators: Properly registered for visualization ✅ Well Documented: Clear comments and structure
If validation finds issues, Lona will:
- Show warnings or errors
- Suggest fixes if needed
- Allow regeneration with improvements
Regenerating Code
You might want to regenerate if:
- Strategy logic needs significant changes
- You realized requirements were unclear
- Want to try a different AI model (basic ↔ powerful)
To Regenerate:
- Continue the conversation with clarifications
- Extract requirements again
- Choose generation option again
Note: Each regeneration creates a new version. Previous versions aren’t lost - they’re saved in your chat history.
Best Practices
✅ Review Explanation First: Understand what was generated before looking at code
✅ Check Parameters: Verify default values make sense for your strategy
✅ Start Simple: Use Fast generation for initial validation
✅ Iterate Thoughtfully: Make small improvements rather than complete rewrites
✅ Save Variations: Start new chats for significantly different approaches
❌ Don’t Edit Complex Logic: If strategy logic is wrong, clarify requirements and regenerate
❌ Don’t Skip Validation: Always review the explanation to ensure correctness
Troubleshooting Code Generation
Problem: “Generation is taking too long” Solution: Powerful models can take up to 90 seconds. If it exceeds 2 minutes, try refreshing or switch to a basic model for faster generation.
Problem: “Generated code doesn’t match my requirements” Solution: Review requirements panel, identify discrepancy, continue conversation to clarify, extract and regenerate.
Problem: “I don’t understand the code” Solution: Read the explanation panel below the code - it explains everything in plain English. You don’t need to understand Python!
Problem: “Can’t find the Canvas panel” Solution: Look for Canvas Size button in left sidebar and click to expand from Hidden to Half or Full width.
Problem: “Need to change the framework” Solution: Frameworks are automatically selected. If you need a specific framework, mention it during the interview.
What’s Next?
Now that you have generated code, you’re ready to backtest! Continue to Execution & Backtesting to learn how to run your strategy against historical data.
Quick Reference
| Action | Where to Find It |
|---|---|
| Extract Requirements | Blue button after interview |
| View Requirements | Canvas panel (Report mode) |
| Select AI Model | Model dropdown in chat input area |
| Generate Code | Generate button after model selection |
| View Code | Canvas panel (Code mode) |
| Edit Code | Click in code editor |
| Toggle Canvas | Canvas Mode button (left sidebar) |
| Resize Canvas | Canvas Size button (left sidebar) |
| Execute Strategy | Execute button after generation |
Next: Learn about Execution & Backtesting to run your strategy!