-
Notifications
You must be signed in to change notification settings - Fork 6
/
CRTDR_Signal.Strategy.CS
544 lines (468 loc) · 24.4 KB
/
CRTDR_Signal.Strategy.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using PowerLanguage.Function;
namespace PowerLanguage.Strategy
{
public class CRTDR_Signal : PortfolioSignalObject
{
private const int recalcFrequency = 10;
public CRTDR_Signal(object _ctx) : base(_ctx) { }
private IOrderMarket buyOrder;
private IOrderMarket sellOrder;
// private IOrderMarket sellShortOrder;
// private IOrderMarket buyToCoverOrder;
// [Input]
// public int RsiUpMinimumForShort {get; set;}
[Input]
public int EmaLong { get; set; }
[Input]
public int EmaShort { get; set; }
[Input]
public int RsiLengthDown { get; set; }
[Input]
public int RsiLengthFlat { get; set; }
[Input]
public int RsiLengthUp { get; set; }
[Input]
public double LongLimitUp { get; set; }
[Input]
public double LongLimitDown { get; set; }
[Input]
public double LongLimitFlat { get; set; }
// [Input]
// public double ShortLimitDown {get; set;}
[Input]
public double StopLossLevel { get; set; }
[Input]
public double RsiSellLevelUp { get; set; }
[Input]
public double RsiSellLevelDown { get; set; }
[Input]
public double RsiSellLevelFlat { get; set; }
// [Input]
// public double RsiCoverLevelUp {get; set;}
// [Input]
// public double RsiCoverLevelDown {get; set;}
// [Input]
// public double RsiCoverLevelFlat {get; set;}
private CutlersRSIIndicatorMath cutlersRSIIndicatorMathDown;
private CutlersRSIIndicatorMath cutlersRSIIndicatorMathFlat;
private CutlersRSIIndicatorMath cutlersRSIIndicatorMathUp;
private XAverageThatWorks xAverageLong;
private XAverageThatWorks xAverageShort;
private bool doReinvestment = false;
string symbolName;
protected override void Create()
{
buyOrder = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.UserSpecified, EOrderAction.Buy));
sellOrder = OrderCreator.MarketThisBar(new SOrderParameters(EOrderAction.Sell));
//sellShortOrder = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.UserSpecified, EOrderAction.SellShort));
//buyToCoverOrder = OrderCreator.MarketThisBar(new SOrderParameters(Contracts.Default, "RSI SE", EOrderAction.BuyToCover, OrderExit.FromAll));
cutlersRSIIndicatorMathDown = new CutlersRSIIndicatorMath(this, 1);
cutlersRSIIndicatorMathFlat = new CutlersRSIIndicatorMath(this, 1);
cutlersRSIIndicatorMathUp = new CutlersRSIIndicatorMath(this, 1);
xAverageLong = new XAverageThatWorks(this, 1);
xAverageShort = new XAverageThatWorks(this, 1);
}
protected override void StartCalc()
{
cutlersRSIIndicatorMathDown.Length = RsiLengthDown;
cutlersRSIIndicatorMathFlat.Length = RsiLengthFlat;
cutlersRSIIndicatorMathUp.Length = RsiLengthUp;
xAverageLong.Price = Bars.Close;
xAverageLong.Length = EmaLong;
xAverageShort.Price = Bars.Close;
xAverageShort.Length = EmaShort;
symbolName = Bars.Info.Name;
}
protected override void StopCalc()
{
if (!Environment.Optimizing)
{
Output.WriteLine("Dumping log for {0}", Bars.Info.Name);
DumpFileLog();
DumpMailLog();
}
}
private readonly StringBuilder _logStringBuilder = new StringBuilder();
private readonly Dictionary<string, DateTime> emailLogMessages = new Dictionary<string, DateTime>();
private DateTime _lastLogEntry = DateTime.MinValue;
private bool _throttledLoggingActive = false;
private string _lastLogMessage;
private void UpdateLogThrottling()
{
var now = DateTime.Now;
if (_lastLogEntry <= now)
{
_throttledLoggingActive = true;
double frequency = now.TimeOfDay > new TimeSpan(15, 57, 00) && now.TimeOfDay < new TimeSpan(16, 00, 00) ? 0.25 : 60;
_lastLogEntry = now.AddMinutes(frequency);
}
else
{
_throttledLoggingActive = false;
}
}
private void LogThrottled(string message, params object[] parameters)
{
if (_throttledLoggingActive)
{
Log(message, parameters);
}
}
private void Log(string message, params object[] parameters)
{
Log(false, message, parameters);
}
private void LogAndMail(string message, params object[] parameters)
{
Log(true, message, parameters);
}
private void Log(bool sendMail, string message, params object[] parameters)
{
if (!Environment.Optimizing)
{
if (Environment.IsRealTimeCalc)
{
try
{
var logMessage = string.Format("{0} - {1}: {2}", Bars.TimeValue, Bars.Info.Name, string.Format(message, parameters));
if (string.Equals(message, _lastLogMessage))
{
return;
}
_lastLogMessage = logMessage;
var fullLogString = string.Format("{0} - {1}", DateTime.Now, logMessage);
//Output.WriteLine(fullLogString);
_logStringBuilder.AppendLine(fullLogString);
if (_logStringBuilder.Length >= 1000)
{
DumpFileLog();
}
if (sendMail)
{
emailLogMessages[logMessage] = DateTime.Now;
}
}
catch (Exception e)
{
Output.WriteLine(e.ToString());
}
}
}
}
private void DumpFileLog()
{
File.AppendAllText(@"c:\temp\logs\" + Bars.Info.Name + ".txt", _logStringBuilder.ToString());
_logStringBuilder.Clear();
}
private void DumpMailLog()
{
if (emailLogMessages.Count != 0)
{
var logStringBuilder = new StringBuilder();
foreach (var kvp in emailLogMessages.OrderBy(kvp => kvp.Value))
{
logStringBuilder.AppendLine(string.Format("{0} - {1}", kvp.Value, kvp.Key));
}
string str = logStringBuilder.ToString();
System.Threading.ThreadPool.QueueUserWorkItem(o => Mail(str));
emailLogMessages.Clear();
}
}
protected override void CalcBar()
{
CurSpecOrdersMode = ESpecOrdersMode.PerPosition;
if (!Environment.IsRealTimeCalc) // There is no need to calculate on historical data, that is why backtesting is ignored
{
// As soon as backtesting is finished, the signal gets immediately calculated by the timer.
// It is necessary to calculate the CRTDR and other values which can be requested by MM-signal at any moment.
ExecControl.RecalcLastBarAfter(TimeSpan.FromSeconds(recalcFrequency));
return;
}
// This method will be called over and over again because of the RecalcLastBarAfter setting
// Since we do not want to get the same logs all the time we have a throttling in place
// which will allow only certain calls to really log their output.
// Depending on the time of the day we log more of less often.
UpdateLogThrottling();
var high = Bars.HighValue;
var low = Bars.LowValue;
var close = Bars.CloseValue;
var crtdr = CRTDRIndicatorMath.CalcNextValue(high, low, close);
var xAverageLongValue = xAverageLong.Value;
var xAverageShortValue = xAverageShort.Value;
var trend = GetTrend(close, xAverageLongValue, xAverageShortValue);
var rsiDown = cutlersRSIIndicatorMathDown.Value;
var rsiFlat = cutlersRSIIndicatorMathFlat.Value;
var rsiUp = cutlersRSIIndicatorMathUp.Value;
var rsi = trend == Trend.Down ? rsiDown : (trend == Trend.Up ? rsiUp : rsiFlat);
MyPortfolioData[PortfolioDataKeys.IWantToBuy] = false;
MyPortfolioData[PortfolioDataKeys.IWantToSell] = false;
MyPortfolioData[PortfolioDataKeys.CRTDR] = crtdr;
LogThrottled("Reason: {0}, Status: {1}, Open: {2}, High: {3}, Low: {4}, Close: {5}, RSI: {6}, CRTDR: {7}, xAvgLong: {8}, xAvgShort: {9}", Environment.CalcReason, Bars.Status, Bars.OpenValue, Bars.HighValue, Bars.LowValue, Bars.CloseValue, rsi, crtdr, xAverageLongValue, xAverageShortValue);
if (StrategyInfo.MarketPosition == 0)
{
if (GetSignalUp(crtdr, rsi, trend))
{
//var numLots = Convert.ToInt32((InitialCapital + (doReinvestment ? Portfolio.NetProfit : 0.0)) / Bars.CloseValue);
MyPortfolioData[PortfolioDataKeys.IWantToBuy] = true;
LogThrottled("Signal says: We would like to buy @ {0}$", Bars.CloseValue);
}
// else if (GetSignalDown(crtdr, rsi, trend))
// {
// Output.WriteLine("SHORT on {0}, high {1} low {2} close {3} rsi {4} crtdr {5} xAverageLong {6} xAverageShort {7}", Bars.TimeValue, high, low, close, rsi, crtdr, xAverageLongValue, xAverageShortValue);
// MyPortfolioData[PortfolioHelpFunctions.PotentialEntryPrice] = -Bars.CloseValue;
// sellShortOrder.Send(Convert.ToInt32((InitialCapital + (doReinvestment ? Portfolio.NetProfit : 0.0)) / 10.0 / Bars.CloseValue));
// }
// else
// {
// Log("--- FLAT - NOP ---");
// }
}
else if (StrategyInfo.MarketPosition > 0)
{
// WE ARE LONG
//var barsSinceEntry = Bars.CurrentBar - CurrentPosition.OpenTrades[0].EntryOrder.BarNumber;
// BarsSinceEntry() doesn't work upon the restart of a trading session in which case BarsSinceEntry() will be zero no matter when the deals were actually opened
var barsSinceEntry = Math.Min(1, this.BarsSinceEntry());
var openProfit = CurrentPosition.OpenProfit;
var signalUp = GetSignalUp(crtdr, rsi, trend);
var rsiSellLevel = GetRsiSellLevel(trend);
LogThrottled("Should we sell? Bars since entry: {0}, open profit: {1}, signal up: {2}, rsi: {3}, rsiSellLevel: {4}", barsSinceEntry, openProfit, signalUp, rsi, rsiSellLevel);
// close non-profitable positions straight away because we have picked a loser and need to free up money for new deals
if (openProfit < 0)
{
LogThrottled("Loser cut! Assumed loss: {0}$", CurrentPosition.OpenProfit);
MyPortfolioData[PortfolioDataKeys.IWantToSell] = true;
}
else if (barsSinceEntry > 2 && !signalUp)
{
LogThrottled("SELL! Bars since entry > 2 and no up signal. Assuming to cash in ~{0}$", CurrentPosition.OpenProfit);
MyPortfolioData[PortfolioDataKeys.IWantToSell] = true;
}
else if (rsi > rsiSellLevel)
{
LogThrottled("SELL! RSI condition satisfied, we take the profit (~{0}$) and run!", CurrentPosition.OpenProfit);
MyPortfolioData[PortfolioDataKeys.IWantToSell] = true;
}
else
{
//Log("--- LONG - NOP ---");
}
}
// else if(marketPosition < 0)
// {
// // WE ARE SHORT
// GenerateStopLoss(StrategyInfo.AvgEntryPrice * Math.Abs(marketPosition) * StopLossLevel);
//
// if(this.BarsSinceEntry() > 2 && !GetSignalDown(crtdr, rsi, trend))
// {
// //Output.WriteLine("{8}: COVER1 on {0}, high {1} low {2} close {3} rsi {4} crtdr {5} xAverageLong {6} xAverageShort {7}", Bars.TimeValue, high, low, close, rsi, crtdr, xAverageLongValue, xAverageShortValue, Bars.Info.Name);
// buyToCoverOrder.Send();
// }
// else if(rsi < (trend == Trend.Down ? RsiCoverLevelDown : (trend == Trend.Up ? RsiCoverLevelUp : RsiCoverLevelFlat)))
// {
// //Output.WriteLine("{8}: COVER2 on {0}, high {1} low {2} close {3} rsi {4} crtdr {5} xAverageLong {6} xAverageShort {7}", Bars.TimeValue, high, low, close, rsi, crtdr, xAverageLongValue, xAverageShortValue, Bars.Info.Name);
// buyToCoverOrder.Send();
// }
// else
// {
// Log("--- SHORT - NOP ---");
// }
// }
StrategyEvents cmd = StrategyEvents.None;
object obj = MyPortfolioData[PortfolioDataKeys.MoneyManagementCommand]; // Check, if there are any MM-signal events available
if (obj != null)
{
cmd = (StrategyEvents)obj;
}
//Log("Got command {0}", cmd);
switch (cmd) // Execute specific commands, depending on the event
{
case StrategyEvents.GenerateOrders_Long:
int numberOfShares = Convert.ToInt32(MyPortfolioData[PortfolioDataKeys.NumberOfShares]);
buyOrder.Send(numberOfShares);
LogThrottled("Generated Buy: {0}#", numberOfShares);
GenerateOrAdjustStopLosses();
break;
case StrategyEvents.GenerateOrders_Short:
sellOrder.Send();
LogThrottled("Generated Sell.");
break;
case StrategyEvents.None:
ExecControl.RecalcLastBarAfter(TimeSpan.FromSeconds(recalcFrequency));
break;
}
// During calculation at the bar close, global variables, used to exchange messages between the current signal and MM-signal should be reset
if (Bars.Status == EBarState.Close)
{
Log("Close event received."); // only send email output if trade has been sent on this day
DumpFileLog();
MyPortfolioData[PortfolioDataKeys.CRTDR] = 1.0;
MyPortfolioData[PortfolioDataKeys.MoneyManagementCommand] = StrategyEvents.None;
MyPortfolioData[PortfolioDataKeys.IWantToBuy] = false;
MyPortfolioData[PortfolioDataKeys.IWantToSell] = false;
MyPortfolioData[PortfolioDataKeys.NumberOfShares] = 0;
ExecControl.RecalcLastBarAfter(TimeSpan.FromSeconds(recalcFrequency)); // And start the timer to wait for the new commands from MM-signal
}
}
private void GenerateOrAdjustStopLosses()
{
if (CurSpecOrdersMode != ESpecOrdersMode.PerPosition) {
throw new Exception("Incorrect CurSpecOrdersMode. ESpecOrdersMode.PerPosition required.");
}
double amount = StopLossLevel / (Bars.Point * Bars.Info.MinMove);
amount *= (StrategyInfo.MarketPosition > 0) ? StrategyInfo.AvgEntryPrice : Bars.Close[0];
// Inserted as per Svetlana's request: https://www.multicharts.com/discussion/viewtopic.php?p=130893&sid=428630f2f75e47b752f6eb1a6577e158#p130893
if (Environment.IsAutoTradingMode && Bars.LastBarOnChart)
LogThrottled("sysDT= {0}, Name= {1}, barDT= {2}, BStatus= {3}, MP= {4}, MPBS= {5}, EP= {6}, EPBS= {7}, SL @ {8}",
DateTime.Now.ToString("MM/dd/yy hh:mm:ss.fff"),
Bars.Info.Name,
Bars.BarUpdateTime.ToString("MM/dd/yy hh:mm:ss.fff"),
Bars.Status,
StrategyInfo.MarketPosition,
StrategyInfo.MarketPositionAtBrokerForTheStrategy,
StrategyInfo.AvgEntryPrice,
StrategyInfo.AvgEntryPriceAtBrokerForTheStrategy,
amount);
LogThrottled("Generating stop loss @ {0}", amount);
GenerateStopLossPt(amount);
LogThrottled("Generating stop loss starting at {0}", amount);
GeneratePercentTrailingPt(amount, 50);
}
private double GetRsiSellLevel(Trend trend)
{
return trend == Trend.Down ? RsiSellLevelDown : (trend == Trend.Up ? RsiSellLevelUp : RsiSellLevelFlat);
}
private enum Trend
{
Up = 1,
Down = -1,
Flat = 0
}
private Trend GetTrend(double close, double xAverageLongValue, double xAverageShortValue)
{
if (close > xAverageLongValue && xAverageLongValue < xAverageShortValue)
{
LogThrottled("Up trend detected because close {0} > xAverageLongValue {1} && xAverageLongValue {1} < xAverageShortValue {2}", close, xAverageLongValue, xAverageShortValue);
return Trend.Up;
}
if (xAverageLongValue > xAverageShortValue && xAverageShortValue > close)
{
LogThrottled("Down trend detected because xAverageLongValue {0} > xAverageShortValue {1} && xAverageShortValue {1} < close {2}", xAverageLongValue, xAverageShortValue, close);
return Trend.Down;
}
LogThrottled("Flat trend detected with close {0}, xAverageLongValue {1}, xAverageShortValue {2}", close, xAverageLongValue, xAverageShortValue);
return Trend.Flat;
}
private bool GetSignalUp(double crtdr, double rsi, Trend trend)
{
if (trend == Trend.Up)
{
if (crtdr * 100 + rsi <= LongLimitUp) {
LogThrottled("Signal up because crtdr {0} * 100 + rsi {1} <= LongLimitUp {2}", crtdr, rsi, LongLimitUp);
return true;
}
}
else if (trend == Trend.Down)
{
if (crtdr * 100 + rsi <= LongLimitDown) {
LogThrottled("Signal up because crtdr {0} * 100 + rsi {1} <= LongLimitDown {2}", crtdr, rsi, LongLimitDown);
return true;
}
}
else
{
if (crtdr * 100 + rsi <= LongLimitFlat) {
LogThrottled("Signal up because crtdr {0} * 100 + rsi {1} <= LongLimitFlat {2}", crtdr, rsi, LongLimitFlat);
return true;
}
}
LogThrottled("No signal up because with crtdr {0}, rsi {1}, LongLimitUp {2}, LongLimitDown {3}, LongLimitFlat {4}", crtdr, rsi, LongLimitUp, LongLimitDown, LongLimitFlat);
return false;
}
// private double GetMarketPosition()
// {
// return this.Environment.IsAutoTradingMode ? StrategyInfo.MarketPositionAtBrokerForTheStrategy : StrategyInfo.MarketPosition;
// }
// private bool GetSignalDown(double crtdr, double rsi, Trend trend)
// {
// if(rsi >= RsiUpMinimumForShort && trend == Trend.Down)
// {
// if(crtdr * 100 + rsi >= 200 - ShortLimitDown) return true;
// }
//
// return false;
// }
protected override void OnOrderRejected(EOrderAction action, OrderCategory category, int quantity, double stopPrice, double limitPrice)
{
LogAndMail("Order rejected: {0} {1} ({2} @ {3}/{4}).", action, quantity, category, stopPrice, limitPrice);
DumpFileLog();
DumpMailLog();
ExecControl.RecalcLastBarAfter(TimeSpan.FromSeconds(recalcFrequency)); // If there were no instructions from MM-signal, we will keep waiting for them.
}
protected override void OnBrokerStategyOrderFilled(bool isBuy, int quantity, double avgFillPrice)
{
double pAndL = double.NaN;
double pAndLPercentage = double.NaN;
if(StrategyInfo.AvgEntryPriceAtBroker != 0)
{
pAndL = quantity * (avgFillPrice - StrategyInfo.AvgEntryPriceAtBroker);
pAndLPercentage = avgFillPrice / StrategyInfo.AvgEntryPriceAtBroker * 100 - 100;
}
LogAndMail("Order filled: {0} {1} @ avg. {2} (==> {3}). MarketPositionAtBroker={4}, AvgEntryPriceAtBroker={5}", isBuy ? "BUY" : "SELL", quantity, avgFillPrice, isBuy ? "Investing " + quantity * avgFillPrice : ("P/L " + pAndL + " (" + pAndLPercentage + "%)" + (pAndL > 0 ? " - yeah, baby!" : " - ouch!")), StrategyInfo.MarketPositionAtBroker, StrategyInfo.AvgEntryPriceAtBroker);
DumpFileLog();
DumpMailLog();
ExecControl.RecalcLastBarAfter(TimeSpan.FromSeconds(recalcFrequency)); // If there were no instructions from MM-signal, we will keep waiting for them.
}
protected override void OnBrokerPositionChange()
{
Log("MarketPositionAtBroker={0}, AvgEntryPriceAtBroker={1}, MarketPositionAtBrokerForTheStrategy={2}, AvgEntryPriceAtBrokerForTheStrategy={3}, MarketPosition={4}, AvgEntryPrice={5}", StrategyInfo.MarketPositionAtBroker, StrategyInfo.AvgEntryPriceAtBroker, StrategyInfo.MarketPositionAtBrokerForTheStrategy, StrategyInfo.AvgEntryPriceAtBrokerForTheStrategy, StrategyInfo.MarketPosition, StrategyInfo.AvgEntryPrice);
}
protected override void OnRecalcLastBarAfterEvent()
{
CalcBar();
}
private static readonly string FromPassword = File.ReadAllText(@"C:\temp\do_not_delete\asdf.txt");
private static readonly MailAddress FromAddress = new MailAddress("ramanddan.trading@gmail.com", "RamDRom Trading");
private void Mail(string message)
{
if (Environment.IsRealTimeCalc/* && DateTime.Now > DateTime.Now.Date.AddHours(15)*/)
{
try
{
using (SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(FromAddress.Address, FromPassword)
})
using (var mailMessage = new MailMessage()
{
From = FromAddress,
Subject = string.Format("Trading day summary: {0}", symbolName),
Body = message
})
{
mailMessage.To.Add("ramon@winter-berg.com");
mailMessage.To.Add("daniel.hegener@gmx.net");
mailMessage.To.Add("andermatt.roman@gmail.com");
smtp.Send(mailMessage);
}
}
catch (Exception e)
{
Log("Error sending email: {0}", e.Message);
}
}
}
}
}