Creating your first cBot in cTrader Automate is a step-by-step process. You begin by creating a new cBot file, which provides a standard code template. You then define user-friendly `[Parameter]` attributes for settings like indicator periods and risk. The core trading logic, such as a moving average crossover, is written in C# inside the `OnBar()` method, which runs on the close of each new candle. Finally, you use the 'Build' button to compile the code and the 'Backtesting' tab, with tick data and realistic costs, to rigorously test the cBot's performance before ever running it live.
Your First Algorithm: How to Create Your First cBot in cTrader Automate
Learning to cook a signature dish starts with a basic recipe. This guide is your recipe for your first automated trading 'dish'—the classic moving average crossover cBot. 👨🍳 The journey into automated trading can seem intimidating, but cTrader's built-in cTrader Automate feature provides a user-friendly environment to bring a simple trading idea to life. The evening or the weekend is the perfect time to sit down and take your first exciting steps into the world of algorithmic trading.
Step 1: Setting Up Your Workshop (Open cTrader Automate)
First, let's navigate to your development environment. Launch the cTrader desktop platform. On the far left, you will see a vertical menu. Click on the icon that looks like a small robot or is labeled "Automate". This single click opens the Automate suite, the integrated development environment (IDE) that serves as your all-in-one command center.
Step 2: Laying the Foundation (Create and Name Your cBot)
At the top of the list of existing cBots and Indicators, click the "New" button. When prompted, select "cBot." Now, give your creation a meaningful name, like "MyFirstMACrossover". This is a professional habit that helps keep your projects organized. cTrader will automatically generate a new C# code file for you, which is a template containing the basic skeleton of a cBot.
Step 3: Understanding the Basic cBot Template
The new code file is structured very logically. Here's a guided tour:
usingStatements: At the top, these lines import existing libraries of code, giving your cBot access to essential trading and programming functions.[Robot(...)]Attributes: This block sets the default properties for your cBot, like its name and default timeframe.OnStart()Method: This code runs exactly once when you start the cBot. It's for one-time setup tasks, like printing a message to the log to confirm the bot has started correctly.OnBar()Method: This is the heart of your cBot. The logic inside this block runs exactly once on the close of every new price bar (candle). For an indicator-based strategy, this is the most efficient and logical place for your trading rules.OnStop()Method: This code runs once when you stop the cBot, used for cleanup tasks like closing any open positions.
Step 4: Building the Control Panel (User Parameters) 🎛️
To make our cBot flexible, we create user-friendly parameters instead of hard-coding numbers. 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; }
[Parameter("Bot Magic Number", DefaultValue = 12345, Group = "Identification")]
public int MagicNumber { get; set; }
Step 5: Writing the C# Trading Logic (The Recipe) ✍️
Now for the main event. We will add all of our logic inside the OnBar() method. This ensures our code only runs once per candle, preventing duplicate trades and saving computer resources.
Here is the complete, commented code for the `OnBar()` method:
protected override void OnBar()
{
// --- 1. Define Your Indicators ---
// Get the data from the simple moving average indicators using the periods from our parameters.
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 compare the indicator values from the bar that just closed (Last(1))
// with the values from the bar before that (Last(2)).
// A bullish crossover just happened if the fast MA was BELOW the slow MA on the prior bar,
// AND the fast MA is now ABOVE the slow MA on the most recent bar.
bool bullishCrossover = fastMA.Result.HasCrossedAbove(slowMA.Result, 1);
// A bearish crossover just happened if the fast MA was ABOVE the slow MA on the prior bar,
// AND the fast MA is now BELOW the slow MA on the most recent bar.
bool bearishCrossover = fastMA.Result.HasCrossedBelow(slowMA.Result, 1);
// --- 3. Prevent Multiple Open Trades ---
// A crucial piece of logic is to ensure the bot doesn't open a new trade if one is already active.
// We check this by seeing if there are any open positions with our unique Magic Number.
bool isTradeOpen = Positions.Count(p => p.MagicNumber == MagicNumber) > 0;
// --- 4. Execute the Trade ---
// Finally, we combine all our logic into a set of 'if' statements.
// We also convert our volume from lots to the unit required by the trading command.
double volumeInUnits = Symbol.QuantityToVolumeInUnits(TradeVolumeInLots);
if (bullishCrossover && !isTradeOpen)
{
// If a buy signal exists AND no trade is open, execute a Buy order.
ExecuteMarketOrder(TradeType.Buy, SymbolName, volumeInUnits, "MyFirstMACrossover", StopLossInPips, TakeProfitInPips, null, MagicNumber);
}
else if (bearishCrossover && !isTradeOpen)
{
// If a sell signal exists AND no trade is open, execute a Sell order.
ExecuteMarketOrder(TradeType.Sell, SymbolName, volumeInUnits, "MyFirstMACrossover", StopLossInPips, TakeProfitInPips, null, MagicNumber);
}
}
Step 6: Build, Test, and Visualize Your Creation
With the code written, click the "Build" button at the top of the Automate window. If you see "Build Succeeded," your cBot is ready for testing!
Now, click the "Backtesting" tab. Configure your test settings (pair, timeframe, date range). Crucially, for the most accurate results, ensure you select "Tick data from server" as the data source and input a realistic spread. Before running, check the "Visual Mode" box to watch your cBot trade on the historical data. When ready, click "Execute" and analyze the detailed performance report cTrader provides.
Conclusion: Your Journey into Automation Has Begun 🚀
Congratulations! You have successfully transformed a trading idea into a fully functional automated system. This moving average crossover bot is the essential "Hello, World!" project of algorithmic trading. From this solid foundation, you can now experiment with different indicators, add more complex risk rules, and continue your exciting journey of discovery in the powerful world of cTrader Automate.