The following code snippet is a fully working cTrader cBot that closes open trades when the price moves above or below a simple moving average indicator.
Download ⬇️
using cAlgo.API;
using cAlgo.API.Indicators;
namespace cAlgo
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class ExitTradesOnSMA : Robot
{
[Parameter("SMA Period", DefaultValue = 50)]
public int SMAPeriod { get; set; }
[Parameter("Timeframe", DefaultValue = "Hour1")]
public new TimeFrame TimeFrame { get; set; }
private SimpleMovingAverage _sma;
protected override void OnStart()
{
_sma = Indicators.SimpleMovingAverage(MarketData.GetBars(TimeFrame).ClosePrices, SMAPeriod);
}
protected override void OnBar()
{
var bars = MarketData.GetBars(TimeFrame);
if (bars.Count < SMAPeriod)
return;
double lastClose = bars.Last(1).Close;
double smaValue = _sma.Result.Last(1);
if (lastClose > smaValue || lastClose < smaValue)
{
CloseAllTrades();
}
}
private void CloseAllTrades()
{
foreach (var position in Positions)
{
if (position.SymbolName == SymbolName)
{
ClosePosition(position);
}
}
}
}
}
/*
This cTrader cBot was created with clear instructions using a highly knowledgeable Ai assistant for cTrader's Algo platform.
It helps users write, debug, and optimize C# trading bots, providing clear and accurate cTrader API documentation when requested.
No coding experience required.
Website: https://clickalgo.com/code-ai
*/