Your First Algorithm: How to Create Your First cBot in cTrader Automate
The journey into automated trading can seem intimidating, but creating your first cBot is more accessible than you might think. The cTrader platform's built-in cTrader Automate feature provides a user-friendly environment to bring a simple trading idea to life. This guide will walk you through the entire process, step-by-step, from a blank file to a functional trading robot. We will build a cBot based on one of the most classic strategies: the moving average crossover.
Step 1: Open the cTrader Automate Workshop
First things first, let's navigate to your development environment. Launch the cTrader desktop platform. On the far left-hand side of the application, you will see a vertical menu with several icons for different sections like "Trade," "Copy," and "Analyze." Locate and click on the icon that looks like a small robot or is labeled "Automate". This single click transports you into the cTrader Automate suite, the integrated development environment (IDE) that serves as your all-in-one command center for creating, testing, and managing your automated trading systems.
Step 2: Create and Name Your New cBot File
With the Automate feature open, look to the top of the list of cBots and Indicators on the left. You will see a "New" button. Click it. A dialog box will appear, prompting you to choose what you want to create. Select "cBot" (as opposed to "Indicator").
Now, give your creation a meaningful name. Good organization starts from the very beginning. Instead of "cBot1," let's name it "MyFirstMACrossover". This makes it easy to identify later. After naming it, click "OK." cTrader will automatically generate a new C# code file for you. This file is a template containing all the necessary boilerplate code—the basic skeleton upon which we will build the muscles and brain of our strategy.
Step 3: Understanding the Basic cBot Template
The new code file might look intimidating at first, but it's structured very logically. Let's break down the key sections of this pre-built template:
- `using` Statements: At the very top, you'll see lines like `using cAlgo.API;`. These are directives that tell your cBot to import existing libraries of code. Think of them as giving your cBot access to toolkits for trading (the `cAlgo.API`) and general programming functions.
- `[Robot(...)]` Attributes: This block, right above the class definition, sets the default properties for your cBot. You can define its name, default timeframe, and access rights here. These are settings that appear in the cTrader UI.
- `OnStart()` Method: The code written inside this `OnStart()` block will run exactly once, at the very moment you start an instance of your cBot. It's the perfect place for initialization tasks. For example, you could print a message to the log to confirm the bot has started correctly, or define the main indicators you plan to use throughout the bot's operation.
- `OnBar()` vs. `OnTick()` Methods: The template might generate one or both of these. They are the heart of the cBot, containing the logic that runs continuously.
- `OnTick()`: This method runs on every single price change (tick). It's designed for very high-frequency strategies but can be resource-intensive and complex for a beginner.
- `OnBar()`: This method runs only once per price bar, at the moment a new candle closes. For a strategy based on indicators like moving averages, this is far more efficient and easier to manage. For our first cBot, we will be placing all our trading logic inside the `OnBar()` method.
- `OnStop()` Method: This code runs once when you stop the cBot. It's used for cleanup tasks, like closing any open positions or printing a final summary report to the log.
Step 4: Defining the Strategy and User-Friendly Parameters
Our strategy is simple and classic:
- Buy Signal: When a fast-period moving average crosses above a slow-period moving average.
- Sell Signal: When a fast-period moving average crosses below a slow-period moving average.
To make our cBot flexible, we shouldn't hard-code the settings. We should create parameters that we can easily change from the cTrader interface. Add these lines of code at the top of your class, just below the `[Robot(...)]` line. Each `[Parameter(...)]` attribute creates a field in the cBot's user interface.
[Parameter("Fast MA Period", DefaultValue = 20, Group = "Strategy")]
public int FastMaPeriod { get; set; }
[Parameter("Slow MA Period", DefaultValue = 50, Group = "Strategy")]
public int SlowMaPeriod { get; set; }
[Parameter("Volume (Lots)", DefaultValue = 0.1, MinValue = 0.01, Group = "Risk")]
public double TradeVolumeInLots { get; set; }
[Parameter("Stop Loss (Pips)", DefaultValue = 20, MinValue = 1, Group = "Risk")]
public int StopLossInPips { get; set; }
[Parameter("Take Profit (Pips)", DefaultValue = 40, MinValue = 1, Group = "Risk")]
public int TakeProfitInPips { get; set; }
By adding these, we have now created an easy-to-use interface for controlling our cBot's strategy and risk without ever touching the code again.
Step 5: Writing the C# Trading Logic
Now for the main event. We will add our logic inside the `OnBar()` method. This ensures our code only runs once per candle, preventing duplicate trades and saving computer resources.
1. Define Your Indicators: Inside `OnBar()`, the first step is to get the data from the moving average indicators.
var fastMA = Indicators.MovingAverage(Bars.ClosePrices, FastMaPeriod, MovingAverageType.Simple);
var slowMA = Indicators.MovingAverage(Bars.ClosePrices, SlowMaPeriod, MovingAverageType.Simple);
2. Define the Crossover Conditions: To detect a "cross," we need to compare the indicator values from the most recently closed bar with the values from the bar before that. The `.Last(1)` command gets the value from the previous bar, while `.Last(2)` gets it from two bars ago.
// Define the values for the previous bar (the one that just closed)
double fastMAPrevious = fastMA.Result.Last(1);
double slowMAPrevious = slowMA.Result.Last(1);
// Define the values for the bar before the previous one
double fastMA_2_Bars_Ago = fastMA.Result.Last(2);
double slowMA_2_Bars_Ago = slowMA.Result.Last(2);
// Create boolean variables for our signals for clarity
bool buySignal = fastMA_2_Bars_Ago < slowMA_2_Bars_Ago && fastMAPrevious > slowMAPrevious;
bool sellSignal = fastMA_2_Bars_Ago > slowMA_2_Bars_Ago && fastMAPrevious < slowMAPrevious;
3. Prevent Multiple Open Trades: A crucial piece of logic for a simple bot is to ensure it doesn't open a new buy trade if a trade is already active. We can check this by seeing if there are any open positions with the label we're about to use.
bool isTradeOpen = Positions.Find("MyFirstMACrossover") != null;
4. Execute the Trade: Finally, we combine all our logic into a set of `if` statements. We check if a signal exists AND if there is no trade already open. We also convert our volume from lots to the unit required by the `ExecuteMarketOrder` command.
double volumeInUnits = Symbol.QuantityToVolumeInUnits(TradeVolumeInLots);
if (buySignal && !isTradeOpen)
{
ExecuteMarketOrder(TradeType.Buy, SymbolName, volumeInUnits, "MyFirstMACrossover", StopLossInPips, TakeProfitInPips);
}
else if (sellSignal && !isTradeOpen)
{
ExecuteMarketOrder(TradeType.Sell, SymbolName, volumeInUnits, "MyFirstMACrossover", StopLossInPips, TakeProfitInPips);
}
Step 6: Build, Test, and Visualize Your cBot
With all the code written, you need to compile it to check for errors. At the top of the Automate window, click the "Build" button. The build result will appear in the log at the bottom of the screen. If you have any typos or errors, it will tell you on which line to find them. If you see "Build Succeeded," your cBot is ready for action!
Now, click the "Backtesting" tab. Here you can configure the settings for your test: choose the currency pair, timeframe, date range, and starting capital. For the most accurate results, ensure you select "Tick data from server" as the data source. Before running, consider checking the "Visual Mode" box. This will open a chart and allow you to watch your cBot execute trades on the historical data, which is an invaluable way to see if your logic is behaving exactly as you intended. When ready, click "Execute" and analyze the detailed performance report cTrader provides.
Conclusion: Your Journey into Automation Has Begun
Congratulations! By following these steps, you have successfully transformed a simple trading idea into a fully functional automated system. You have learned how to create your first cBot, understand its structure, define its parameters, write its core logic, and test its performance. This moving average crossover bot is the essential "Hello, World!" project of algorithmic trading. From this solid foundation, you can now experiment further—try different indicators, add more complex risk management rules, and continue your exciting journey of discovery in the powerful world of cTrader Automate.