-
Notifications
You must be signed in to change notification settings - Fork 13
/
NewsTrader.cs
467 lines (390 loc) · 19.3 KB
/
NewsTrader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// -------------------------------------------------------------------------------
// Opens a buy/sell trade (random, chosen direction, or both directions) seconds before news release.
// Sets SL and TP. Keeps updating them until the very release.
// Can set use trailing stop and breakeven.
// ATR-based stop-loss option is also available.
// Closes trade after given time period passes.
// Version 1.12.
// Copyright 2024, EarnForex.com
// https://www.earnforex.com/metatrader-expert-advisors/News-Trader/
// -------------------------------------------------------------------------------
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
public enum Trailing_Enum
{
None,
Breakeven,
TrailingStop, // Normal trailing stop
TS_plus_BE // Normal trailing stop + Breakeven
}
namespace cAlgo
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class NewsTrader : Robot
{
[Parameter(DefaultValue = 2022, MinValue = 1970)]
public int Year { get; set; }
[Parameter(DefaultValue = 4, MinValue = 1, MaxValue = 12)]
public int Month { get; set; }
[Parameter(DefaultValue = 26, MinValue = 1, MaxValue = 31)]
public int Day { get; set; }
[Parameter(DefaultValue = 0, MinValue = 0, MaxValue = 23)]
public int Hour { get; set; }
[Parameter(DefaultValue = 0, MinValue = 0, MaxValue = 59)]
public int Minute { get; set; }
[Parameter("Stop-Loss, pips", DefaultValue = 15, MinValue = 0)]
public int StopLoss { get; set; }
[Parameter("Take-Profit, pips", DefaultValue = 75, MinValue = 0)]
public int TakeProfit { get; set; }
[Parameter(DefaultValue = true)]
public bool Buy { get; set; }
[Parameter(DefaultValue = true)]
public bool Sell { get; set; }
[Parameter("Randomize Buy/Sell", DefaultValue = false)]
public bool Rnd { get; set; }
[Parameter("Trailing Stop", DefaultValue = Trailing_Enum.None)]
public Trailing_Enum Trailing { get; set; }
[Parameter("Profit to trigger breakeven, pips", DefaultValue = 0, MinValue = 0)]
public int BEOnProfit { get; set; }
[Parameter("Breakeven extra profit, pips", DefaultValue = 0, MinValue = 0)]
public int BEExtraProfit { get; set; }
[Parameter("Profit to start trailing stop, pips", DefaultValue = 0, MinValue = 0)]
public int TSOnProfit { get; set; }
[Parameter("Preadjust SL/TP", DefaultValue = false)]
public bool PreAdjustSLTP { get; set; }
[Parameter("Seconds Before News", DefaultValue = 10, MinValue = 1)]
public int SecondsBefore { get; set; }
[Parameter("Close After Seconds", DefaultValue = 3600, MinValue = 0)]
public int CloseAfterSeconds { get; set; }
[Parameter("Use ATR Stop-Loss", DefaultValue = false)]
public bool UseATR { get; set; }
[Parameter("ATR Period", DefaultValue = 14, MinValue = 1)]
public int ATR_Period { get; set; }
[Parameter("ATR Multiplier for SL", DefaultValue = 1, MinValue = 0)]
public double ATR_Multiplier_SL { get; set; }
[Parameter("ATR Multiplier for TP", DefaultValue = 5, MinValue = 0)]
public double ATR_Multiplier_TP { get; set; }
[Parameter("Volume in Lots", DefaultValue = 0.01, MinValue = 0.01)]
public double Lots { get; set; }
[Parameter("Money Management", DefaultValue = true)]
public bool MM { get; set; }
[Parameter("Risk, %", DefaultValue = 1, MinValue = 0)]
public double Risk { get; set; }
[Parameter("Risk, Money", DefaultValue = 0, MinValue = 0)]
public double MoneyRisk { get; set; }
[Parameter("Fixed Balance", DefaultValue = 0, MinValue = 0)]
public double FixedBalance { get; set; }
[Parameter("Use Money Instead of %", DefaultValue = false)]
public bool UseMoneyInsteadOfPercentage { get; set; }
[Parameter("Use Equity Instead of Balance", DefaultValue = false)]
public bool UseEquityInsteadOfBalance { get; set; }
[Parameter("Show Timer", DefaultValue = true)]
public bool ShowTimer { get; set; }
[Parameter("Vertical Corner", DefaultValue = VerticalAlignment.Top)]
public VerticalAlignment CornerVertical { get; set; }
[Parameter("Horizontal Corner", DefaultValue = HorizontalAlignment.Left)]
public HorizontalAlignment CornerHorizontal { get; set; }
[Parameter(DefaultValue = 1)]
public int Slippage { get; set; }
[Parameter(DefaultValue = "NewsTrader")]
public string Commentary { get; set; }
// Indicator handles
private AverageTrueRange ATR;
private DateTime news_time;
private bool CanTrade = false;
private double SL, TP;
private bool HaveLongPosition = false;
private bool HaveShortPosition = false;
private bool Breakeven_Needed = false;
private bool Trailing_Needed = false;
protected string MyLabel
{
get { return string.Format("{0} {1} {2}", Commentary, Symbol.Name, TimeFrame); }
}
protected override void OnStart()
{
news_time = new DateTime(Year, Month, Day, Hour, Minute, 0);
double min_lot = Symbol.VolumeInUnitsToQuantity(Symbol.VolumeInUnitsMin);
if ((Lots < min_lot) && (!MM))
{
double lot_step = Symbol.VolumeInUnitsToQuantity(Symbol.VolumeInUnitsStep);
Print("Lots should not be less than: ", min_lot.ToString(), ".");
Print("Minimum lot: ", min_lot.ToString(), ", lot step: ", lot_step.ToString(), ".");
}
else
CanTrade = true;
if (ShowTimer)
{
Chart.DrawStaticText("NewsTraderTimer", "", CornerVertical, CornerHorizontal, Color.Red);
// For smooth updates.
Timer.Start(TimeSpan.FromMilliseconds(100));
}
if (UseATR)
{
ATR = Indicators.AverageTrueRange(ATR_Period, MovingAverageType.Simple);
}
// If UseATR = false, these values will be used. Otherwise, ATR values will be calculated later.
SL = StopLoss;
TP = TakeProfit;
if (BEExtraProfit > BEOnProfit) Print("Extra profit for breakeven shouldn't be greater than the profit to trigger breakeven parameter. Please check your input parameters.");
if ((Trailing == Trailing_Enum.Breakeven) || (Trailing == Trailing_Enum.TS_plus_BE)) Breakeven_Needed = true;
if ((Trailing == Trailing_Enum.TrailingStop) || (Trailing == Trailing_Enum.TS_plus_BE)) Trailing_Needed = true;
}
//+------------------------------------------------------------------+
//| Stops timer if needed. |
//+------------------------------------------------------------------+
protected override void OnStop()
{
if (ShowTimer)
{
Timer.Stop();
}
}
//+------------------------------------------------------------------+
//| Updates text about time left to news or passed after news. |
//+------------------------------------------------------------------+
protected override void OnTimer()
{
string text;
TimeSpan difference = Time.Subtract(news_time);
if (difference <= TimeSpan.FromMilliseconds(0))
text = "Time to news:" + TimeDistance(difference.Negate());
else
text = "Time after news:" + TimeDistance(difference);
Chart.DrawStaticText("NewsTraderTimer", text + "", CornerVertical, CornerHorizontal, Color.Red);
}
protected override void OnTick()
{
if (!CanTrade)
return;
if (UseATR)
{
// Getting the ATR values
double ATR_value = ATR.Result.LastValue;
SL = ATR_value * ATR_Multiplier_SL;
TP = ATR_value * ATR_Multiplier_TP;
SL /= Symbol.PipSize;
TP /= Symbol.PipSize;
}
// Check what position is currently open
GetPositionStates();
// Adjust SL and TP of the current position
if ((HaveLongPosition) || (HaveShortPosition))
ControlPosition();
else
{
TimeSpan difference = Time.Subtract(news_time).Negate();
if ((difference <= TimeSpan.FromSeconds(SecondsBefore)) && (difference > TimeSpan.FromMilliseconds(0)))
{
// Randomize entry.
if (Rnd)
{
Random r = new Random();
if (r.Next() % 2 == 1)
OpenBuy();
else
OpenSell();
}
else if ((Buy) && (Sell))
{
OpenSell();
OpenBuy();
}
else if (Buy)
OpenBuy();
else if (Sell)
OpenSell();
}
}
}
//+------------------------------------------------------------------+
//| Check what positions are currently open. |
//+------------------------------------------------------------------+
private void GetPositionStates()
{
foreach (var position in Positions)
{
if ((Symbol.Name == position.SymbolName) && (MyLabel == position.Label))
{
if (position.TradeType == TradeType.Sell)
HaveShortPosition = true;
if (position.TradeType == TradeType.Buy)
HaveLongPosition = true;
}
}
}
//+------------------------------------------------------------------+
//| Generic buy. |
//+------------------------------------------------------------------+
private void OpenBuy()
{
ExecuteMarketRangeOrder(TradeType.Buy, Symbol.Name, LotsOptimized(), Slippage, Symbol.Ask, MyLabel, SL, TP, Commentary);
}
//+------------------------------------------------------------------+
//| Generic sell. |
//+------------------------------------------------------------------+
private void OpenSell()
{
ExecuteMarketRangeOrder(TradeType.Sell, Symbol.Name, LotsOptimized(), Slippage, Symbol.Bid, MyLabel, SL, TP, Commentary);
}
//+------------------------------------------------------------------+
//| Add SL/TP, adjust SL/TP, set breakeven, close trade. |
//+------------------------------------------------------------------+
private void ControlPosition()
{
foreach (var position in Positions)
{
if ((Symbol.Name == position.SymbolName) && (MyLabel == position.Label))
{
TimeSpan difference = Time.Subtract(news_time);
if ((difference < TimeSpan.FromMilliseconds(0)) && (PreAdjustSLTP))
{
double new_sl = 0, new_tp = 0;
if (position.TradeType == TradeType.Buy)
{
new_sl = Math.Round(Symbol.Ask - SL * Symbol.PipSize, Symbol.Digits);
new_tp = Math.Round(Symbol.Ask + TP * Symbol.PipSize, Symbol.Digits);
}
else if (position.TradeType == TradeType.Sell)
{
new_sl = Math.Round(Symbol.Bid + SL * Symbol.PipSize, Symbol.Digits);
new_tp = Math.Round(Symbol.Bid - TP * Symbol.PipSize, Symbol.Digits);
}
if ((new_sl != position.StopLoss) || (new_tp != position.TakeProfit))
{
Print("Adjusting SL: ", new_sl, " and TP: ", new_tp, ".");
ModifyPosition(position, new_sl, new_tp);
}
}
// Check for breakeven or trade time out.
else
{
if ((Breakeven_Needed) && ((((position.TradeType == TradeType.Buy) && (Symbol.Bid - position.EntryPrice >= BEOnProfit * Symbol.PipSize)) || ((position.TradeType == TradeType.Sell) && (position.EntryPrice - Symbol.Ask >= BEOnProfit * Symbol.PipSize)))))
{
double new_sl = Math.Round(position.EntryPrice, Symbol.Digits);
if (BEExtraProfit > 0) // Breakeven extra profit?
{
if (position.TradeType == TradeType.Buy) new_sl += BEExtraProfit * Symbol.PipSize; // For buys.
else new_sl -= BEExtraProfit * Symbol.PipSize; // For sells.
new_sl = Math.Round(new_sl, Symbol.Digits);
}
if (((position.TradeType == TradeType.Buy) && (new_sl > position.StopLoss)) || ((position.TradeType == TradeType.Sell) && ((new_sl < position.StopLoss) || (position.StopLoss == null)))) // Avoid moving SL to BE if this SL is already there or in a better position.
{
Print("Moving SL to breakeven: ", new_sl, ".");
ModifyPosition(position, new_sl, position.TakeProfit);
}
}
if ((Trailing_Needed) && ((TSOnProfit == 0) || ((position.TradeType == TradeType.Buy) && (Symbol.Bid - position.EntryPrice >= TSOnProfit * Symbol.PipSize)) || ((position.TradeType == TradeType.Sell) && (position.EntryPrice - Symbol.Ask >= TSOnProfit * Symbol.PipSize))))
{
double new_sl = 0;
if (position.TradeType == TradeType.Buy)
new_sl = Math.Round(Symbol.Bid - SL * Symbol.PipSize, Symbol.Digits);
else if (position.TradeType == TradeType.Sell)
new_sl = Math.Round(Symbol.Ask + SL * Symbol.PipSize, Symbol.Digits);
if (((position.TradeType == TradeType.Buy) && (new_sl > position.StopLoss)) || ((position.TradeType == TradeType.Sell) && ((new_sl < position.StopLoss) || (position.StopLoss == null))))
{
Print("Moving trailing SL to ", new_sl, ".");
ModifyPosition(position, new_sl, position.TakeProfit);
}
}
if (CloseAfterSeconds > 0)
{
TimeSpan after_difference = Time.Subtract(news_time);
if (after_difference >= TimeSpan.FromSeconds(CloseAfterSeconds))
{
Print("Closing trade by time out.");
ClosePosition(position);
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Format time distance from the number of seconds to normal string |
//| of years, days, hours, minutes, and seconds. |
//| t - time difference |
//| Returns: formatted string. |
//+------------------------------------------------------------------+
string TimeDistance(TimeSpan t)
{
if ((t < TimeSpan.FromSeconds(1)) && (t > TimeSpan.FromSeconds(1).Negate()))
return (" 0 seconds");
string s = "";
int d = t.Days;
int h = t.Hours;
int m = t.Minutes;
int sec = t.Seconds;
if (d > 0)
s += " " + d.ToString() + " day";
if (d > 1)
s += "s";
if (h > 0)
s += " " + h.ToString() + " hour";
if (h > 1)
s += "s";
if (m > 0)
s += " " + m.ToString() + " minute";
if (m > 1)
s += "s";
if (sec > 0)
s += " " + sec.ToString() + " second";
if (sec > 1)
s += "s";
return (s);
}
//+------------------------------------------------------------------+
//| Calculate position size depending on money management parameters.|
//+------------------------------------------------------------------+
double LotsOptimized()
{
if (!MM)
return (Symbol.QuantityToVolumeInUnits(Lots));
double Size, RiskMoney, PositionSize = 0;
if (Account.Asset.Name == "")
return (0);
if (FixedBalance > 0)
{
Size = FixedBalance;
}
else if (UseEquityInsteadOfBalance)
{
Size = Account.Equity;
}
else
{
Size = Account.Balance;
}
if (!UseMoneyInsteadOfPercentage)
RiskMoney = Size * Risk / 100;
else
RiskMoney = MoneyRisk;
double UnitCost = Symbol.PipValue;
if ((SL != 0) && (UnitCost != 0))
PositionSize = (int)Math.Round(RiskMoney / SL / UnitCost);
Print(PositionSize);
if (PositionSize < Symbol.VolumeInUnitsMin)
{
Print("Calculated position size (" + PositionSize + ") is less than minimum position size (" + Symbol.VolumeInUnitsMin + "). Setting position size to minimum.");
PositionSize = Symbol.VolumeInUnitsMin;
}
else if (PositionSize > Symbol.VolumeInUnitsMax)
{
Print("Calculated position size (" + PositionSize + ") is greater than maximum position size (" + Symbol.VolumeInUnitsMax + "). Setting position size to maximum.");
PositionSize = Symbol.VolumeInUnitsMax;
}
double LotStep = Symbol.VolumeInUnitsStep;
double steps = PositionSize / LotStep;
if (Math.Floor(steps) < steps)
{
Print("Calculated position size (" + PositionSize + ") uses uneven step size. Allowed step size = " + LotStep + ". Setting position size to " + (Math.Floor(steps) * LotStep) + ".");
PositionSize = Math.Floor(steps) * LotStep;
}
return (PositionSize);
}
}
}