Skip to content

Commit 80c10ef

Browse files
authored
Merge branch 'master' into 5ulam9-codex/create-gold-trading-algo-bot-for-ctrader
2 parents d43272d + ba659cf commit 80c10ef

File tree

5 files changed

+234
-2
lines changed

5 files changed

+234
-2
lines changed

README.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,3 @@
22
cBot / Indicator Samples of cTrader Algo API
33

44
## Custom Samples
5-
6-
- **GoldAdvancedStrategy**: Combines Supertrend trend detection, MACD momentum confirmation, and RSI filters with dynamic volume and trailing stops for trading XAUUSD.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 11.00
3+
# Visual Studio 2010
4+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gold Trend Strategy", "XAUUSD Trend Strategy\GoldTrendStrategy.csproj", "{9AE93258-B8C0-4BB7-9848-7E4F7C43B555}"
5+
EndProject
6+
Global
7+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
8+
Debug|Any CPU = Debug|Any CPU
9+
Release|Any CPU = Release|Any CPU
10+
EndGlobalSection
11+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
12+
{9AE93258-B8C0-4BB7-9848-7E4F7C43B555}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13+
{9AE93258-B8C0-4BB7-9848-7E4F7C43B555}.Debug|Any CPU.Build.0 = Debug|Any CPU
14+
{9AE93258-B8C0-4BB7-9848-7E4F7C43B555}.Release|Any CPU.ActiveCfg = Release|Any CPU
15+
{9AE93258-B8C0-4BB7-9848-7E4F7C43B555}.Release|Any CPU.Build.0 = Release|Any CPU
16+
EndGlobalSection
17+
GlobalSection(SolutionProperties) = preSolution
18+
HideSolutionNode = FALSE
19+
EndGlobalSection
20+
EndGlobal
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
// -------------------------------------------------------------------------------------------------
2+
//
3+
// This code is a cTrader Algo API example.
4+
//
5+
// This cBot is intended to be used as a sample and does not guarantee any particular outcome or
6+
// profit of any kind. Use it at your own risk.
7+
//
8+
// -------------------------------------------------------------------------------------------------
9+
10+
using System;
11+
using cAlgo.API;
12+
using cAlgo.API.Indicators;
13+
using cAlgo.API.Internals;
14+
15+
namespace cAlgo.Robots
16+
{
17+
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None, AddIndicators = true)]
18+
public class GoldTrendStrategy : Robot
19+
{
20+
private double _volumeInUnits;
21+
private SimpleMovingAverage _fastMa;
22+
private SimpleMovingAverage _slowMa;
23+
private RelativeStrengthIndex _rsi;
24+
private Supertrend _supertrend;
25+
private MacdCrossOver _macd;
26+
27+
[Parameter("Fast MA Source", Group = "Fast MA")]
28+
public DataSeries FastMaSource { get; set; }
29+
30+
[Parameter("Fast MA Period", DefaultValue = 50, Group = "Fast MA", MinValue = 1)]
31+
public int FastMaPeriod { get; set; }
32+
33+
[Parameter("Slow MA Source", Group = "Slow MA")]
34+
public DataSeries SlowMaSource { get; set; }
35+
36+
[Parameter("Slow MA Period", DefaultValue = 200, Group = "Slow MA", MinValue = 1)]
37+
public int SlowMaPeriod { get; set; }
38+
39+
[Parameter("RSI Period", DefaultValue = 14, Group = "RSI", MinValue = 1)]
40+
public int RsiPeriod { get; set; }
41+
42+
[Parameter("RSI Oversold", DefaultValue = 30, Group = "RSI", MinValue = 1, MaxValue = 50)]
43+
public int Oversold { get; set; }
44+
45+
[Parameter("RSI Overbought", DefaultValue = 70, Group = "RSI", MinValue = 50, MaxValue = 100)]
46+
public int Overbought { get; set; }
47+
48+
[Parameter("Supertrend Periods", DefaultValue = 10, Group = "Supertrend", MinValue = 1)]
49+
public int SupertrendPeriods { get; set; }
50+
51+
[Parameter("Supertrend Multiplier", DefaultValue = 3.0, Group = "Supertrend", MinValue = 0.1)]
52+
public double SupertrendMultiplier { get; set; }
53+
54+
[Parameter("MACD Long Cycle", DefaultValue = 26, Group = "MACD", MinValue = 1)]
55+
public int MacdLongCycle { get; set; }
56+
57+
[Parameter("MACD Short Cycle", DefaultValue = 12, Group = "MACD", MinValue = 1)]
58+
public int MacdShortCycle { get; set; }
59+
60+
[Parameter("MACD Signal Periods", DefaultValue = 9, Group = "MACD", MinValue = 1)]
61+
public int MacdSignalPeriods { get; set; }
62+
63+
[Parameter("Volume (Lots)", DefaultValue = 0.01, Group = "Trade")]
64+
public double VolumeInLots { get; set; }
65+
66+
[Parameter("Use Dynamic Volume", DefaultValue = false, Group = "Trade")]
67+
public bool UseDynamicVolume { get; set; }
68+
69+
[Parameter("Risk Per Trade (%)", DefaultValue = 1.0, Group = "Trade", MinValue = 0.1)]
70+
public double RiskPercent { get; set; }
71+
72+
[Parameter("Max Spread (pips)", DefaultValue = 50, Group = "Trade", MinValue = 0)]
73+
public double MaxSpreadInPips { get; set; }
74+
75+
[Parameter("Trailing Stop (Pips)", DefaultValue = 50, Group = "Trade", MinValue = 0)]
76+
public double TrailingStopInPips { get; set; }
77+
78+
[Parameter("Stop Loss (Pips)", DefaultValue = 100, Group = "Trade", MinValue = 1)]
79+
public double StopLossInPips { get; set; }
80+
81+
[Parameter("Take Profit (Pips)", DefaultValue = 200, Group = "Trade", MinValue = 1)]
82+
public double TakeProfitInPips { get; set; }
83+
84+
[Parameter("Label", DefaultValue = "GoldTrendStrategy", Group = "Trade")]
85+
public string Label { get; set; }
86+
87+
protected override void OnStart()
88+
{
89+
if (SymbolName != "XAUUSD")
90+
Print("Warning: This cBot is designed for XAUUSD. Current symbol is {0}.", SymbolName);
91+
92+
if (!UseDynamicVolume)
93+
_volumeInUnits = Symbol.QuantityToVolumeInUnits(VolumeInLots);
94+
95+
_fastMa = Indicators.SimpleMovingAverage(FastMaSource, FastMaPeriod);
96+
_slowMa = Indicators.SimpleMovingAverage(SlowMaSource, SlowMaPeriod);
97+
_rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, RsiPeriod);
98+
_supertrend = Indicators.Supertrend(SupertrendPeriods, SupertrendMultiplier);
99+
_macd = Indicators.MacdCrossOver(Bars.ClosePrices, MacdLongCycle, MacdShortCycle, MacdSignalPeriods);
100+
101+
_fastMa.Result.Line.Color = Color.Gold;
102+
_slowMa.Result.Line.Color = Color.DarkOrange;
103+
}
104+
105+
protected override void OnBarClosed()
106+
{
107+
var trendUp = _supertrend.UpTrend.Last(0) < Bars.LowPrices.Last(0) && _supertrend.DownTrend.Last(1) > Bars.HighPrices.Last(1);
108+
var trendDown = _supertrend.DownTrend.Last(0) > Bars.HighPrices.Last(0) && _supertrend.UpTrend.Last(1) < Bars.LowPrices.Last(1);
109+
110+
var macdCrossUp = _macd.MACD.Last(0) > _macd.Signal.Last(0) && _macd.MACD.Last(1) <= _macd.Signal.Last(1);
111+
var macdCrossDown = _macd.MACD.Last(0) < _macd.Signal.Last(0) && _macd.MACD.Last(1) >= _macd.Signal.Last(1);
112+
113+
if (Symbol.Spread / Symbol.PipSize > MaxSpreadInPips)
114+
return;
115+
116+
var volume = GetTradeVolume();
117+
118+
if (trendUp && macdCrossUp && _rsi.Result.LastValue < Oversold)
119+
{
120+
ClosePositions(TradeType.Sell);
121+
ExecuteMarketOrder(TradeType.Buy, SymbolName, volume, Label, StopLossInPips, TakeProfitInPips);
122+
}
123+
else if (trendDown && macdCrossDown && _rsi.Result.LastValue > Overbought)
124+
{
125+
ClosePositions(TradeType.Buy);
126+
ExecuteMarketOrder(TradeType.Sell, SymbolName, volume, Label, StopLossInPips, TakeProfitInPips);
127+
}
128+
}
129+
130+
protected override void OnTick()
131+
{
132+
if (TrailingStopInPips <= 0)
133+
return;
134+
135+
foreach (var position in Positions.FindAll(Label))
136+
{
137+
double? newStopLoss = position.TradeType == TradeType.Buy
138+
? Symbol.Bid - TrailingStopInPips * Symbol.PipSize
139+
: Symbol.Ask + TrailingStopInPips * Symbol.PipSize;
140+
141+
if (position.TradeType == TradeType.Buy && (position.StopLoss == null || newStopLoss > position.StopLoss))
142+
ModifyPosition(position, newStopLoss, position.TakeProfit);
143+
else if (position.TradeType == TradeType.Sell && (position.StopLoss == null || newStopLoss < position.StopLoss))
144+
ModifyPosition(position, newStopLoss, position.TakeProfit);
145+
}
146+
}
147+
148+
private double GetTradeVolume()
149+
{
150+
if (!UseDynamicVolume)
151+
return _volumeInUnits;
152+
153+
var riskAmount = Account.Balance * RiskPercent / 100.0;
154+
var volumeInLots = riskAmount / (StopLossInPips * Symbol.PipValue);
155+
var units = Symbol.QuantityToVolumeInUnits(volumeInLots);
156+
units = Math.Max(Symbol.VolumeInUnitsMin, Math.Min(Symbol.VolumeInUnitsMax, units));
157+
return Symbol.NormalizeVolumeInUnits(units, RoundingMode.ToNearest);
158+
}
159+
160+
private void ClosePositions(TradeType tradeType)
161+
{
162+
foreach (var position in Positions.FindAll(Label))
163+
{
164+
if (position.TradeType == tradeType)
165+
ClosePosition(position);
166+
}
167+
}
168+
}
169+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project Sdk="Microsoft.NET.Sdk">
3+
<PropertyGroup>
4+
<TargetFramework>net6.0</TargetFramework>
5+
<EnableDefaultItems>False</EnableDefaultItems>
6+
<GenerateAssemblyInfo>False</GenerateAssemblyInfo>
7+
</PropertyGroup>
8+
<PropertyGroup>
9+
<LangVersion>7.2</LangVersion>
10+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
11+
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
12+
<AppDesignerFolder>Properties</AppDesignerFolder>
13+
<RootNamespace>cAlgo</RootNamespace>
14+
<AssemblyName>Gold Trend Strategy</AssemblyName>
15+
<FileAlignment>512</FileAlignment>
16+
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
17+
</PropertyGroup>
18+
<ItemGroup>
19+
<PackageReference Include="cTrader.Automate" Version="*-*" />
20+
</ItemGroup>
21+
<ItemGroup>
22+
<Compile Include="GoldTrendStrategy.cs" />
23+
<Compile Include="Properties\AssemblyInfo.cs" />
24+
</ItemGroup>
25+
</Project>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using System.Diagnostics;
2+
using System.Reflection;
3+
using System.Runtime.InteropServices;
4+
5+
[assembly: AssemblyTitle("Gold Trend Strategy")]
6+
[assembly: AssemblyDescription("")]
7+
[assembly: AssemblyConfiguration("")]
8+
[assembly: AssemblyProduct("Gold Trend Strategy")]
9+
[assembly: AssemblyTrademark("")]
10+
[assembly: AssemblyCulture("")]
11+
12+
[assembly: ComVisible(false)]
13+
14+
[assembly: Guid("9f04b8d8-0ddb-4e77-bb31-abbf3a30c91b")]
15+
16+
[assembly: AssemblyVersion("1.0.0.0")]
17+
[assembly: AssemblyFileVersion("1.0.0.0")]
18+
#if DEBUG
19+
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations)]
20+
#endif

0 commit comments

Comments
 (0)