Skip to content

Commit ddaedb3

Browse files
authored
Merge pull request #5 from martcklm/5ulam9-codex/create-gold-trading-algo-bot-for-ctrader
Refine Gold strategy
2 parents ba659cf + 80c10ef commit ddaedb3

File tree

5 files changed

+219
-2
lines changed

5 files changed

+219
-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-
- **GoldTrendStrategy**: Trend-following cBot for XAUUSD using Supertrend, MACD, RSI and optional dynamic volume management.
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 Advanced Strategy", "Advanced Gold Strategy\AdvancedGoldStrategy.csproj", "{7C9AEC3E-8925-4BA9-9CD3-0D026EB8B452}"
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+
{7C9AEC3E-8925-4BA9-9CD3-0D026EB8B452}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13+
{7C9AEC3E-8925-4BA9-9CD3-0D026EB8B452}.Debug|Any CPU.Build.0 = Debug|Any CPU
14+
{7C9AEC3E-8925-4BA9-9CD3-0D026EB8B452}.Release|Any CPU.ActiveCfg = Release|Any CPU
15+
{7C9AEC3E-8925-4BA9-9CD3-0D026EB8B452}.Release|Any CPU.Build.0 = Release|Any CPU
16+
EndGlobalSection
17+
GlobalSection(SolutionProperties) = preSolution
18+
HideSolutionNode = FALSE
19+
EndGlobalSection
20+
EndGlobal
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
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 GoldAdvancedStrategy : Robot
19+
{
20+
private double _volumeInUnits;
21+
private Supertrend _supertrend;
22+
private MacdHistogram _macd;
23+
private RelativeStrengthIndex _rsi;
24+
25+
[Parameter("Volume (Lots)", DefaultValue = 0.01, Group = "Trade")]
26+
public double VolumeInLots { get; set; }
27+
28+
[Parameter("Use Dynamic Volume", DefaultValue = false, Group = "Trade")]
29+
public bool UseDynamicVolume { get; set; }
30+
31+
[Parameter("Risk Per Trade (%)", DefaultValue = 1.0, Group = "Trade", MinValue = 0.1)]
32+
public double RiskPercent { get; set; }
33+
34+
[Parameter("Max Spread (pips)", DefaultValue = 50, Group = "Trade", MinValue = 0)]
35+
public double MaxSpreadInPips { get; set; }
36+
37+
[Parameter("Trailing Stop (Pips)", DefaultValue = 50, Group = "Trade", MinValue = 0)]
38+
public double TrailingStopInPips { get; set; }
39+
40+
[Parameter("Stop Loss (Pips)", DefaultValue = 100, Group = "Trade", MinValue = 1)]
41+
public double StopLossInPips { get; set; }
42+
43+
[Parameter("Take Profit (Pips)", DefaultValue = 200, Group = "Trade", MinValue = 1)]
44+
public double TakeProfitInPips { get; set; }
45+
46+
[Parameter("Label", DefaultValue = "GoldAdvancedStrategy", Group = "Trade")]
47+
public string Label { get; set; }
48+
49+
[Parameter("Supertrend Periods", DefaultValue = 10, Group = "Supertrend", MinValue = 1)]
50+
public int SupertrendPeriods { get; set; }
51+
52+
[Parameter("Supertrend Multiplier", DefaultValue = 3.0, Group = "Supertrend", MinValue = 0.1)]
53+
public double SupertrendMultiplier { get; set; }
54+
55+
[Parameter("MACD Long Cycle", DefaultValue = 26, Group = "MACD", MinValue = 1)]
56+
public int MacdLongCycle { get; set; }
57+
58+
[Parameter("MACD Short Cycle", DefaultValue = 12, Group = "MACD", MinValue = 1)]
59+
public int MacdShortCycle { get; set; }
60+
61+
[Parameter("MACD Signal Periods", DefaultValue = 9, Group = "MACD", MinValue = 1)]
62+
public int MacdSignalPeriods { get; set; }
63+
64+
[Parameter("RSI Period", DefaultValue = 14, Group = "RSI", MinValue = 1)]
65+
public int RsiPeriod { get; set; }
66+
67+
[Parameter("RSI Oversold", DefaultValue = 30, Group = "RSI", MinValue = 1, MaxValue = 50)]
68+
public int Oversold { get; set; }
69+
70+
[Parameter("RSI Overbought", DefaultValue = 70, Group = "RSI", MinValue = 50, MaxValue = 100)]
71+
public int Overbought { get; set; }
72+
73+
protected override void OnStart()
74+
{
75+
if (SymbolName != "XAUUSD")
76+
Print("Warning: This cBot is designed for XAUUSD. Current symbol is {0}.", SymbolName);
77+
78+
if (!UseDynamicVolume)
79+
_volumeInUnits = Symbol.QuantityToVolumeInUnits(VolumeInLots);
80+
81+
_supertrend = Indicators.Supertrend(SupertrendPeriods, SupertrendMultiplier);
82+
_macd = Indicators.MacdHistogram(Bars.ClosePrices, MacdLongCycle, MacdShortCycle, MacdSignalPeriods);
83+
_rsi = Indicators.RelativeStrengthIndex(Bars.ClosePrices, RsiPeriod);
84+
}
85+
86+
protected override void OnBarClosed()
87+
{
88+
if (Symbol.Spread / Symbol.PipSize > MaxSpreadInPips)
89+
return;
90+
91+
var upTrend = _supertrend.UpTrend.Last(0) < Bars.LowPrices.Last(0) && _supertrend.DownTrend.Last(1) > Bars.HighPrices.Last(1);
92+
var downTrend = _supertrend.DownTrend.Last(0) > Bars.HighPrices.Last(0) && _supertrend.UpTrend.Last(1) < Bars.LowPrices.Last(1);
93+
94+
var macdCrossUp = _macd.Histogram.Last(0) > 0 && _macd.Histogram.Last(1) <= 0;
95+
var macdCrossDown = _macd.Histogram.Last(0) < 0 && _macd.Histogram.Last(1) >= 0;
96+
97+
var volume = GetTradeVolume();
98+
99+
if (upTrend && macdCrossUp && _rsi.Result.LastValue < Oversold)
100+
{
101+
ClosePositions(TradeType.Sell);
102+
ExecuteMarketOrder(TradeType.Buy, SymbolName, volume, Label, StopLossInPips, TakeProfitInPips);
103+
}
104+
else if (downTrend && macdCrossDown && _rsi.Result.LastValue > Overbought)
105+
{
106+
ClosePositions(TradeType.Buy);
107+
ExecuteMarketOrder(TradeType.Sell, SymbolName, volume, Label, StopLossInPips, TakeProfitInPips);
108+
}
109+
}
110+
111+
protected override void OnTick()
112+
{
113+
if (TrailingStopInPips <= 0)
114+
return;
115+
116+
foreach (var position in Positions.FindAll(Label))
117+
{
118+
double? newStop;
119+
if (position.TradeType == TradeType.Buy)
120+
newStop = Symbol.Bid - TrailingStopInPips * Symbol.PipSize;
121+
else
122+
newStop = Symbol.Ask + TrailingStopInPips * Symbol.PipSize;
123+
124+
if (position.TradeType == TradeType.Buy && (position.StopLoss == null || newStop > position.StopLoss))
125+
ModifyPosition(position, newStop, position.TakeProfit);
126+
else if (position.TradeType == TradeType.Sell && (position.StopLoss == null || newStop < position.StopLoss))
127+
ModifyPosition(position, newStop, position.TakeProfit);
128+
}
129+
}
130+
131+
private double GetTradeVolume()
132+
{
133+
if (!UseDynamicVolume)
134+
return _volumeInUnits;
135+
136+
var riskAmount = Account.Balance * RiskPercent / 100.0;
137+
var volumeInLots = riskAmount / (StopLossInPips * Symbol.PipValue);
138+
var units = Symbol.QuantityToVolumeInUnits(volumeInLots);
139+
units = Math.Max(Symbol.VolumeInUnitsMin, Math.Min(Symbol.VolumeInUnitsMax, units));
140+
return Symbol.NormalizeVolumeInUnits(units, RoundingMode.ToNearest);
141+
}
142+
143+
private void ClosePositions(TradeType tradeType)
144+
{
145+
foreach (var position in Positions.FindAll(Label))
146+
{
147+
if (position.TradeType != tradeType)
148+
continue;
149+
150+
ClosePosition(position);
151+
}
152+
}
153+
}
154+
}
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>GoldAdvancedStrategy</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="AdvancedGoldStrategy.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("GoldAdvancedStrategy")]
6+
[assembly: AssemblyDescription("")]
7+
[assembly: AssemblyConfiguration("")]
8+
[assembly: AssemblyProduct("GoldAdvancedStrategy")]
9+
[assembly: AssemblyTrademark("")]
10+
[assembly: AssemblyCulture("")]
11+
12+
[assembly: ComVisible(false)]
13+
14+
[assembly: Guid("a602b2fa-d783-4cf2-881e-3d927e3b6a8e")]
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)