├── ChartPatternHelper.mq4 ├── ChartPatternHelper.mq5 ├── LICENSE ├── README.md └── README_Images └── chart-pattern-helper-ea-symmetrical-triangle-setup.png /ChartPatternHelper.mq4: -------------------------------------------------------------------------------- 1 | //+------------------------------------------------------------------+ 2 | //| Chart Pattern Helper | 3 | //| Copyright © 2024, EarnForex.com | 4 | //| https://www.earnforex.com/ | 5 | //+------------------------------------------------------------------+ 6 | #property copyright "Copyright © 2024, EarnForex" 7 | #property link "https://www.earnforex.com/metatrader-expert-advisors/ChartPatternHelper/" 8 | #property version "1.15" 9 | #property strict 10 | 11 | #include 12 | 13 | #property description "Uses graphic objects (horizontal/trend lines, channels) to enter trades." 14 | #property description "Works in two modes:" 15 | #property description "1. Price is below upper entry and above lower entry. Only one or two pending stop orders are used." 16 | #property description "2. Price is above upper entry or below lower entry. Only one pending limit order is used." 17 | #property description "If an object is deleted/renamed after the pending order was placed, order will be canceled." 18 | #property description "Pending order is removed if opposite entry is triggered." 19 | #property description "Generally, it is safe to turn off the EA at any point." 20 | 21 | input group "Objects" 22 | input string UpperBorderLine = "UpperBorder"; 23 | input string UpperEntryLine = "UpperEntry"; 24 | input string UpperTPLine = "UpperTP"; 25 | input string LowerBorderLine = "LowerBorder"; 26 | input string LowerEntryLine = "LowerEntry"; 27 | input string LowerTPLine = "LowerTP"; 28 | // The pattern may be given as trend/horizontal lines or equidistant channels. 29 | input string BorderChannel = "Border"; 30 | input string EntryChannel = "Entry"; 31 | input string TPChannel = "TP"; 32 | input group "Order management" 33 | // In case Channel is used for Entry, pending orders will be removed even if OneCancelsOther = false. 34 | input bool OneCancelsOther = true; // OneCancelsOther: Remove opposite orders once position is open? 35 | // If true, spread will be added to Buy entry level and Sell SL/TP levels. It compensates the difference when Ask price is used, while all chart objects are drawn at Bid level. 36 | input bool UseSpreadAdjustment = false; // UseSpreadAdjustment: Add spread to Buy entry and Sell SL/TP? 37 | // Not all brokers support expiration. 38 | input bool UseExpiration = true; // UseExpiration: Use expiration on pending orders? 39 | input bool DisableBuyOrders = false; // DisableBuyOrders: Disable new and ignore existing buy trades? 40 | input bool DisableSellOrders = false; // DisableSellOrders: Disable new and ignore existing sell trades? 41 | // If true, the EA will try to adjust SL after breakout candle is complete as it may no longer qualify for SL; it will make SL more precise but will mess up the money management a bit. 42 | input bool PostEntrySLAdjustment = false; // PostEntrySLAdjustment: Adjust SL after entry? 43 | input bool UseDistantSL = false; // UseDistantSL: If true, set SL to pattern's farthest point. 44 | input group "Trendline trading" 45 | input bool OpenOnCloseAboveBelowTrendline = false; // Open trade on close above/below trendline. 46 | input string SLLine = "SL"; // Stop-loss line name for trendline trading. 47 | input int ThresholdSpreads = 10; // Threshold Spreads: number of spreads for minimum distance. 48 | input group "Position sizing" 49 | input bool CalculatePositionSize = true; // CalculatePositionSize: Use money management module? 50 | input bool UpdatePendingVolume = true; // UpdatePendingVolume: If true, recalculate pending order volume. 51 | input double FixedPositionSize = 0.01; // FixedPositionSize: Used if CalculatePositionSize = false. 52 | input double Risk = 1; // Risk: Risk tolerance in percentage points. 53 | input double MoneyRisk = 0; // MoneyRisk: Risk tolerance in base currency. 54 | input bool UseMoneyInsteadOfPercentage = false; 55 | input bool UseEquityInsteadOfBalance = false; 56 | input double FixedBalance = 0; // FixedBalance: If > 0, trade size calc. uses it as balance. 57 | input group "Miscellaneous" 58 | input int Magic = 20200530; 59 | input int Slippage = 30; // Slippage: Maximum slippage in broker's pips. 60 | input bool Silent = false; // Silent: If true, does not display any output via chart comment. 61 | input bool ErrorLogging = true; // ErrorLogging: If true, errors will be logged to file. 62 | 63 | // Global variables: 64 | bool UseUpper, UseLower; 65 | double UpperSL, UpperEntry, UpperTP, LowerSL, LowerEntry, LowerTP; 66 | int UpperTicket, LowerTicket; 67 | bool HaveBuyPending = false; 68 | bool HaveSellPending = false; 69 | bool HaveBuy = false; 70 | bool HaveSell = false; 71 | bool TCBusy = false; 72 | bool PostBuySLAdjustmentDone = false, PostSellSLAdjustmentDone = false; 73 | // For tick value adjustment: 74 | string ProfitCurrency = "", account_currency = "", BaseCurrency = "", ReferenceSymbol = NULL, AdditionalReferenceSymbol = NULL; 75 | bool ReferenceSymbolMode, AdditionalReferenceSymbolMode; 76 | int ProfitCalcMode; 77 | double TickSize; 78 | 79 | // For error logging: 80 | string filename; 81 | 82 | void OnInit() 83 | { 84 | FindObjects(); 85 | if (ErrorLogging) 86 | { 87 | datetime tl = TimeLocal(); 88 | string mon = IntegerToString(TimeMonth(tl)); 89 | if (StringLen(mon) == 1) mon = "0" + mon; 90 | string day = IntegerToString(TimeDay(tl)); 91 | if (StringLen(day) == 1) day = "0" + day; 92 | string hour = IntegerToString(TimeHour(tl)); 93 | if (StringLen(hour) == 1) hour = "0" + hour; 94 | string min = IntegerToString(TimeMinute(tl)); 95 | if (StringLen(min) == 1) min = "0" + min; 96 | string sec = IntegerToString(TimeSeconds(tl)); 97 | if (StringLen(sec) == 1) sec = "0" + sec; 98 | filename = "CPH-Errors-" + IntegerToString(TimeYear(tl)) + mon + day + hour + min + sec + ".log"; 99 | } 100 | } 101 | 102 | void OnDeinit(const int reason) 103 | { 104 | SetComment(""); 105 | } 106 | 107 | void OnTick() 108 | { 109 | FindOrders(); 110 | FindObjects(); 111 | AdjustOrders(); // And delete the ones no longer needed. 112 | } 113 | 114 | // Finds Entry, Border and TP objects. Detects respective levels according to found objects. Outputs found values to chart comment. 115 | void FindObjects() 116 | { 117 | string c1 = FindUpperObjects(); 118 | string c2 = FindLowerObjects(); 119 | 120 | SetComment(c1 + c2); 121 | } 122 | 123 | // Adjustment for Ask/Bid spread is made for entry level as Long positions are entered at Ask, while all objects are drawn at Bid. 124 | string FindUpperObjects() 125 | { 126 | string c = ""; // Text for chart comment 127 | 128 | if (DisableBuyOrders) 129 | { 130 | UseUpper = false; 131 | return "\nBuy orders disabled via input parameters."; 132 | } 133 | 134 | UseUpper = true; 135 | 136 | // Entry 137 | if (OpenOnCloseAboveBelowTrendline) // Simple trendline entry doesn't need an entry line. 138 | { 139 | c = c + "\nUpper entry unnecessary."; 140 | } 141 | else if (ObjectFind(UpperEntryLine) > -1) 142 | { 143 | if ((ObjectType(UpperEntryLine) != OBJ_HLINE) && (ObjectType(UpperEntryLine) != OBJ_TREND)) 144 | { 145 | Alert("Upper Entry Line should be either OBJ_HLINE or OBJ_TREND."); 146 | return("\nWrong Upper Entry Line object type."); 147 | } 148 | if (ObjectType(UpperEntryLine) != OBJ_HLINE) UpperEntry = NormalizeDouble(ObjectGetValueByShift(UpperEntryLine, 0), Digits); 149 | else UpperEntry = NormalizeDouble(ObjectGet(UpperEntryLine, OBJPROP_PRICE1), Digits); // Horizontal line value 150 | if (UseSpreadAdjustment) UpperEntry = NormalizeDouble(UpperEntry + MarketInfo(Symbol(), MODE_SPREAD) * Point, Digits); 151 | ObjectSet(UpperEntryLine, OBJPROP_RAY, true); 152 | c = c + "\nUpper entry found. Level: " + DoubleToStr(UpperEntry, Digits); 153 | } 154 | else 155 | { 156 | if (ObjectFind(EntryChannel) > -1) 157 | { 158 | if (ObjectType(EntryChannel) != OBJ_CHANNEL) 159 | { 160 | Alert("Entry Channel should be OBJ_CHANNEL."); 161 | return "\nWrong Entry Channel object type."; 162 | } 163 | UpperEntry = NormalizeDouble(FindUpperEntryViaChannel(), Digits); 164 | if (UseSpreadAdjustment) UpperEntry = NormalizeDouble(UpperEntry + MarketInfo(Symbol(), MODE_SPREAD) * Point, Digits); 165 | ObjectSet(EntryChannel, OBJPROP_RAY, true); 166 | c = c + "\nUpper entry found (via channel). Level: " + DoubleToStr(UpperEntry, Digits); 167 | } 168 | else 169 | { 170 | c = c + "\nUpper entry not found. No new position will be entered."; 171 | UseUpper = false; 172 | } 173 | } 174 | 175 | // Border 176 | if (ObjectFind(UpperBorderLine) > -1) 177 | { 178 | if ((ObjectType(UpperBorderLine) != OBJ_HLINE) && (ObjectType(UpperBorderLine) != OBJ_TREND)) 179 | { 180 | Alert("Upper Border Line should be either OBJ_HLINE or OBJ_TREND."); 181 | return "\nWrong Upper Border Line object type."; 182 | } 183 | // Find upper SL 184 | UpperSL = FindUpperSL(); 185 | ObjectSet(UpperBorderLine, OBJPROP_RAY, true); 186 | c = c + "\nUpper border found. Upper stop-loss level: " + DoubleToStr(UpperSL, Digits); 187 | } 188 | else // Try to find a channel. 189 | { 190 | if (ObjectFind(BorderChannel) > -1) 191 | { 192 | if (ObjectType(BorderChannel) != OBJ_CHANNEL) 193 | { 194 | Alert("Border Channel should be OBJ_CHANNEL."); 195 | return "\nWrong Border Channel object type."; 196 | } 197 | // Find upper SL 198 | UpperSL = FindUpperSLViaChannel(); 199 | ObjectSet(BorderChannel, OBJPROP_RAY, true); 200 | c = c + "\nUpper border found (via channel). Upper stop-loss level: " + DoubleToStr(UpperSL, Digits); 201 | } 202 | else 203 | { 204 | c = c + "\nUpper border not found."; 205 | if ((CalculatePositionSize) && (!HaveBuy)) 206 | { 207 | UseUpper = false; 208 | c = c + " Cannot trade without stop-loss, while CalculatePositionSize set to true."; 209 | } 210 | else 211 | { 212 | c = c + " Stop-loss won\'t be applied to new positions."; 213 | // Track current SL, possibly installed by user. 214 | if ((OrderSelect(UpperTicket, SELECT_BY_TICKET)) && ((OrderType() == OP_BUYSTOP) || (OrderType() == OP_BUYLIMIT))) 215 | { 216 | UpperSL = OrderStopLoss(); 217 | } 218 | } 219 | } 220 | } 221 | // Adjust upper SL for tick size granularity. 222 | TickSize = MarketInfo(Symbol(), MODE_TICKSIZE); 223 | UpperSL = NormalizeDouble(MathRound(UpperSL / TickSize) * TickSize, _Digits); 224 | 225 | // Take-profit. 226 | if (ObjectFind(UpperTPLine) > -1) 227 | { 228 | if ((ObjectType(UpperTPLine) != OBJ_HLINE) && (ObjectType(UpperTPLine) != OBJ_TREND)) 229 | { 230 | Alert("Upper TP Line should be either OBJ_HLINE or OBJ_TREND."); 231 | return "\nWrong Upper TP Line object type."; 232 | } 233 | if (ObjectType(UpperTPLine) != OBJ_HLINE) UpperTP = NormalizeDouble(ObjectGetValueByShift(UpperTPLine, 0), Digits); 234 | else UpperTP = NormalizeDouble(ObjectGet(UpperTPLine, OBJPROP_PRICE1), Digits); // Horizontal line value 235 | ObjectSet(UpperTPLine, OBJPROP_RAY, true); 236 | c = c + "\nUpper take-profit found. Level: " + DoubleToStr(UpperTP, Digits); 237 | } 238 | else 239 | { 240 | if (ObjectFind(TPChannel) > -1) 241 | { 242 | if (ObjectType(TPChannel) != OBJ_CHANNEL) 243 | { 244 | Alert("TP Channel should be OBJ_CHANNEL."); 245 | return "\nWrong TP Channel object type."; 246 | } 247 | UpperTP = FindUpperTPViaChannel(); 248 | ObjectSet(TPChannel, OBJPROP_RAY, true); 249 | c = c + "\nUpper TP found (via channel). Level: " + DoubleToStr(UpperTP, Digits); 250 | } 251 | else 252 | { 253 | c = c + "\nUpper take-profit not found. Take-profit won\'t be applied to new positions."; 254 | // Track current TP, possibly installed by user 255 | if ((OrderSelect(UpperTicket, SELECT_BY_TICKET)) && ((OrderType() == OP_BUYSTOP) || (OrderType() == OP_BUYLIMIT))) 256 | { 257 | UpperTP = OrderTakeProfit(); 258 | } 259 | } 260 | } 261 | // Adjust upper TP for tick size granularity. 262 | UpperTP = NormalizeDouble(MathRound(UpperTP / TickSize) * TickSize, _Digits); 263 | 264 | return c; 265 | } 266 | 267 | // Adjustment for Ask/Bid spread is made for exit levels (SL and TP) as Short positions are exited at Ask, while all objects are drawn at Bid. 268 | string FindLowerObjects() 269 | { 270 | string c = ""; // Text for chart comment 271 | 272 | if (DisableSellOrders) 273 | { 274 | UseLower = false; 275 | return "\nSell orders disabled via input parameters."; 276 | } 277 | 278 | UseLower = true; 279 | 280 | // Entry. 281 | if (OpenOnCloseAboveBelowTrendline) // Simple trendline entry doesn't need an entry line. 282 | { 283 | c = c + "\nLower entry unnecessary."; 284 | } 285 | else if (ObjectFind(LowerEntryLine) > -1) 286 | { 287 | if ((ObjectType(LowerEntryLine) != OBJ_HLINE) && (ObjectType(LowerEntryLine) != OBJ_TREND)) 288 | { 289 | Alert("Lower Entry Line should be either OBJ_HLINE or OBJ_TREND."); 290 | return "\nWrong Lower Entry Line object type."; 291 | } 292 | if (ObjectType(LowerEntryLine) != OBJ_HLINE) LowerEntry = NormalizeDouble(ObjectGetValueByShift(LowerEntryLine, 0), Digits); 293 | else LowerEntry = NormalizeDouble(ObjectGet(LowerEntryLine, OBJPROP_PRICE1), Digits); // Horizontal line value 294 | ObjectSet(LowerEntryLine, OBJPROP_RAY, true); 295 | c = c + "\nLower entry found. Level: " + DoubleToStr(LowerEntry, Digits); 296 | } 297 | else 298 | { 299 | if (ObjectFind(EntryChannel) > -1) 300 | { 301 | if (ObjectType(EntryChannel) != OBJ_CHANNEL) 302 | { 303 | Alert("Entry Channel should be OBJ_CHANNEL."); 304 | return "\nWrong Entry Channel object type."; 305 | } 306 | LowerEntry = FindLowerEntryViaChannel(); 307 | ObjectSet(EntryChannel, OBJPROP_RAY, true); 308 | c = c + "\nLower entry found (via channel). Level: " + DoubleToStr(LowerEntry, Digits); 309 | } 310 | else 311 | { 312 | c = c + "\nLower entry not found. No new position will be entered."; 313 | UseLower = false; 314 | } 315 | } 316 | 317 | // Border. 318 | if (ObjectFind(LowerBorderLine) > -1) 319 | { 320 | if ((ObjectType(LowerBorderLine) != OBJ_HLINE) && (ObjectType(LowerBorderLine) != OBJ_TREND)) 321 | { 322 | Alert("Lower Border Line should be either OBJ_HLINE or OBJ_TREND."); 323 | return "\nWrong Lower Border Line object type."; 324 | } 325 | // Find Lower SL. 326 | LowerSL = NormalizeDouble(FindLowerSL(), Digits); 327 | if (UseSpreadAdjustment) LowerSL = NormalizeDouble(LowerSL + MarketInfo(Symbol(), MODE_SPREAD) * Point, Digits); 328 | ObjectSet(LowerBorderLine, OBJPROP_RAY, true); 329 | c = c + "\nLower border found. Lower stop-loss level: " + DoubleToStr(LowerSL, Digits); 330 | } 331 | else // Try to find a channel. 332 | { 333 | if (ObjectFind(BorderChannel) > -1) 334 | { 335 | if (ObjectType(BorderChannel) != OBJ_CHANNEL) 336 | { 337 | Alert("Border Channel should be OBJ_CHANNEL."); 338 | return "\nWrong Border Channel object type."; 339 | } 340 | // Find Lower SL 341 | LowerSL = NormalizeDouble(FindLowerSLViaChannel(), Digits); 342 | if (UseSpreadAdjustment) LowerSL = NormalizeDouble(LowerSL + MarketInfo(Symbol(), MODE_SPREAD) * Point, Digits); 343 | ObjectSet(BorderChannel, OBJPROP_RAY, true); 344 | c = c + "\nLower border found (via channel). Lower stop-loss level: " + DoubleToStr(LowerSL, Digits); 345 | } 346 | else 347 | { 348 | c = c + "\nLower border not found."; 349 | if ((CalculatePositionSize) && (!HaveSell)) 350 | { 351 | UseLower = false; 352 | c = c + " Cannot trade without stop-loss, while CalculatePositionSize set to true."; 353 | } 354 | else 355 | { 356 | c = c + " Stop-loss won\'t be applied to new positions."; 357 | // Track current SL, possibly installed by user. 358 | if ((OrderSelect(LowerTicket, SELECT_BY_TICKET)) && ((OrderType() == OP_SELLSTOP) || (OrderType() == OP_SELLLIMIT))) 359 | { 360 | LowerSL = OrderStopLoss(); 361 | } 362 | } 363 | } 364 | } 365 | // Adjust lower SL for tick size granularity. 366 | TickSize = MarketInfo(Symbol(), MODE_TICKSIZE); 367 | LowerSL = NormalizeDouble(MathRound(LowerSL / TickSize) * TickSize, _Digits); 368 | 369 | // Take-profit. 370 | if (ObjectFind(LowerTPLine) > -1) 371 | { 372 | if ((ObjectType(LowerTPLine) != OBJ_HLINE) && (ObjectType(LowerTPLine) != OBJ_TREND)) 373 | { 374 | Alert("Lower TP Line should be either OBJ_HLINE or OBJ_TREND."); 375 | return "\nWrong Lower TP Line object type."; 376 | } 377 | if (ObjectType(LowerTPLine) != OBJ_HLINE) LowerTP = NormalizeDouble(ObjectGetValueByShift(LowerTPLine, 0), Digits); 378 | else LowerTP = NormalizeDouble(ObjectGet(LowerTPLine, OBJPROP_PRICE1), Digits); // Horizontal line value 379 | if (UseSpreadAdjustment) LowerTP = NormalizeDouble(LowerTP + MarketInfo(Symbol(), MODE_SPREAD) * Point, Digits); 380 | ObjectSet(LowerTPLine, OBJPROP_RAY, true); 381 | c = c + "\nLower take-profit found. Level: " + DoubleToStr(LowerTP, Digits); 382 | } 383 | else 384 | { 385 | if (ObjectFind(TPChannel) > -1) 386 | { 387 | if (ObjectType(TPChannel) != OBJ_CHANNEL) 388 | { 389 | Alert("TP Channel should be OBJ_CHANNEL."); 390 | return "\nWrong TP Channel object type."; 391 | } 392 | LowerTP = NormalizeDouble(FindLowerTPViaChannel(), Digits); 393 | if (UseSpreadAdjustment) LowerTP = NormalizeDouble(LowerTP + MarketInfo(Symbol(), MODE_SPREAD) * Point, Digits); 394 | ObjectSet(TPChannel, OBJPROP_RAY, true); 395 | c = c + "\nLower TP found (via channel). Level: " + DoubleToStr(LowerTP, Digits); 396 | } 397 | else 398 | { 399 | c = c + "\nLower take-profit not found. Take-profit won\'t be applied to new positions."; 400 | // Track current TP, possibly installed by user. 401 | if ((OrderSelect(LowerTicket, SELECT_BY_TICKET)) && ((OrderType() == OP_SELLSTOP) || (OrderType() == OP_SELLLIMIT))) 402 | { 403 | LowerTP = OrderTakeProfit(); 404 | } 405 | } 406 | } 407 | // Adjust lower TP for tick size granularity. 408 | LowerTP = NormalizeDouble(MathRound(LowerTP / TickSize) * TickSize, _Digits); 409 | 410 | return c; 411 | } 412 | 413 | // Find SL using a border line - the low of the first bar with major part below border. 414 | double FindUpperSL() 415 | { 416 | // Invalid value will prevent order from executing in case something goes wrong. 417 | double SL = -1; 418 | 419 | // Everything becomes much easier if the EA just needs to find the farthest opposite point of the pattern. 420 | if (UseDistantSL) 421 | { 422 | // Horizontal line. 423 | if (ObjectType(LowerBorderLine) == OBJ_HLINE) 424 | { 425 | return NormalizeDouble(ObjectGetDouble(0, LowerBorderLine, OBJPROP_PRICE1), Digits); 426 | } 427 | // Trend line. 428 | else if (ObjectType(LowerBorderLine) == OBJ_TREND) 429 | { 430 | double price1 = ObjectGetDouble(0, LowerBorderLine, OBJPROP_PRICE1); 431 | double price2 = ObjectGetDouble(0, LowerBorderLine, OBJPROP_PRICE2); 432 | if (price1 < price2) return NormalizeDouble(price1, Digits); 433 | else return NormalizeDouble(price2, Digits); 434 | } 435 | } 436 | 437 | // Easy stop-loss via a separate horizontal line when using trendline trading. 438 | if (OpenOnCloseAboveBelowTrendline) 439 | { 440 | if (ObjectFind(0, SLLine) < 0) return -1; 441 | return NormalizeDouble(ObjectGetDouble(0, SLLine, OBJPROP_PRICE1), Digits); 442 | } 443 | 444 | for (int i = 0; i < Bars; i++) 445 | { 446 | double Border, Entry; 447 | if (ObjectType(UpperBorderLine) != OBJ_HLINE) Border = ObjectGetValueByShift(UpperBorderLine, i); 448 | else Border = ObjectGet(UpperBorderLine, OBJPROP_PRICE1); // Horizontal line value 449 | if (ObjectType(UpperEntryLine) != OBJ_HLINE) Entry = ObjectGetValueByShift(UpperEntryLine, i); 450 | else Entry = ObjectGet(UpperEntryLine, OBJPROP_PRICE1); // Horizontal line value 451 | // Additional condition (Entry) checks whether _current_ candle may still have a bigger part within border before triggering entry. 452 | // It is not possible if the current height inside border is not bigger than the distance from border to entry. 453 | // It should not be checked for candles already completed. 454 | // Additionally, if skipped the first bar because it could not potentially qualify, next bar's Low should be lower or equal to that of the first bar. 455 | if ((Border - Low[i] > High[i] - Border) && ((Entry - Border < Border - Low[i]) || (i != 0)) && (Low[i] <= Low[0])) return NormalizeDouble(Low[i], Digits); 456 | } 457 | 458 | return SL; 459 | } 460 | 461 | // Find SL using a border line - the high of the first bar with major part above border. 462 | double FindLowerSL() 463 | { 464 | // Invalid value will prevent order from executing in case something goes wrong. 465 | double SL = -1; 466 | 467 | // Everything becomes much easier if the EA just needs to find the farthest opposite point of the pattern. 468 | if (UseDistantSL) 469 | { 470 | // Horizontal line. 471 | if (ObjectType(UpperBorderLine) == OBJ_HLINE) 472 | { 473 | return NormalizeDouble(ObjectGetDouble(0, UpperBorderLine, OBJPROP_PRICE1), Digits); 474 | } 475 | // Trend line. 476 | else if (ObjectType(UpperBorderLine) == OBJ_TREND) 477 | { 478 | double price1 = ObjectGetDouble(0, UpperBorderLine, OBJPROP_PRICE1); 479 | double price2 = ObjectGetDouble(0, UpperBorderLine, OBJPROP_PRICE2); 480 | if (price1 > price2) return NormalizeDouble(price1, Digits); 481 | else return NormalizeDouble(price2, Digits); 482 | } 483 | } 484 | 485 | // Easy stop-loss via a separate horizontal line when using trendline trading. 486 | if (OpenOnCloseAboveBelowTrendline) 487 | { 488 | if (ObjectFind(0, SLLine) < 0) return -1; 489 | return NormalizeDouble(ObjectGetDouble(0, SLLine, OBJPROP_PRICE1), Digits); 490 | } 491 | 492 | for (int i = 0; i < Bars; i++) 493 | { 494 | double Border, Entry; 495 | if (ObjectType(LowerBorderLine) != OBJ_HLINE) Border = ObjectGetValueByShift(LowerBorderLine, i); 496 | else Border = ObjectGet(LowerBorderLine, OBJPROP_PRICE1); // Horizontal line value 497 | if (ObjectType(LowerEntryLine) != OBJ_HLINE) Entry = ObjectGetValueByShift(LowerEntryLine, i); 498 | else Entry = ObjectGet(LowerEntryLine, OBJPROP_PRICE1); // Horizontal line value 499 | // Additional condition (Entry) checks whether _current_ candle may still have a bigger part within border before triggering entry. 500 | // It is not possible if the current height inside border is not bigger than the distance from border to entry. 501 | // It should not be checked for candles already completed. 502 | // Additionally, if skipped the first bar because it could not potentially qualify, next bar's High should be higher or equal to that of the first bar. 503 | if ((High[i] - Border > Border - Low[i]) && ((Border - Entry < High[i] - Border) || (i != 0)) && (High[i] >= High[0])) 504 | { 505 | return NormalizeDouble(High[i], Digits); 506 | } 507 | } 508 | 509 | return SL; 510 | } 511 | 512 | // Find SL using a border channel - the low of the first bar with major part below upper line. 513 | double FindUpperSLViaChannel() 514 | { 515 | // Invalid value will prevent order from executing in case something goes wrong. 516 | double SL = -1; 517 | 518 | // Easy stop-loss via a separate horizontal line when using trendline trading. 519 | if (OpenOnCloseAboveBelowTrendline) 520 | { 521 | if (ObjectFind(0, SLLine) < 0) return -1; 522 | return NormalizeDouble(ObjectGetDouble(0, SLLine, OBJPROP_PRICE1), Digits); 523 | } 524 | 525 | for (int i = 0; i < Bars(_Symbol, _Period); i++) 526 | { 527 | // Get the upper of main and auxiliary lines 528 | double Border = MathMax(ObjectGetValueByTime(0, BorderChannel, Time[i], 0), ObjectGetValueByTime(0, BorderChannel, Time[i], 1)); 529 | 530 | // Additional condition (Entry) checks whether _current_ candle may still have a bigger part within border before triggering entry. 531 | // It is not possible if the current height inside border is not bigger than the distance from border to entry. 532 | // It should not be checked for candles already completed. 533 | // Additionally, if skipped the first bar because it could not potentially qualify, next bar's Low should be lower or equal to that of the first bar. 534 | if ((Border - Low[i] > High[i] - Border) && ((UpperEntry - Border < Border - Low[i]) || (i != 0)) && (Low[i] <= Low[0])) return(NormalizeDouble(Low[i], _Digits)); 535 | } 536 | 537 | return(SL); 538 | } 539 | 540 | // Find SL using a border channel - the high of the first bar with major part above upper line. 541 | double FindLowerSLViaChannel() 542 | { 543 | // Invalid value will prevent order from executing in case something goes wrong. 544 | double SL = -1; 545 | 546 | // Easy stop-loss via a separate horizontal line when using trendline trading. 547 | if (OpenOnCloseAboveBelowTrendline) 548 | { 549 | if (ObjectFind(0, SLLine) < 0) return(-1); 550 | return NormalizeDouble(ObjectGetDouble(0, SLLine, OBJPROP_PRICE1), Digits); 551 | } 552 | 553 | for (int i = 0; i < Bars(_Symbol, _Period); i++) 554 | { 555 | // Get the lower of main and auxiliary lines 556 | double Border = MathMin(ObjectGetValueByTime(0, BorderChannel, Time[i], 0), ObjectGetValueByTime(0, BorderChannel, Time[i], 1)); 557 | 558 | // Additional condition (Entry) checks whether _current_ candle may still have a bigger part within border before triggering entry. 559 | // It is not possible if the current height inside border is not bigger than the distance from border to entry. 560 | // It should not be checked for candles already completed. 561 | // Additionally, if skipped the first bar because it could not potentially qualify, next bar's High should be higher or equal to that of the first bar. 562 | if ((High[i] - Border > Border - Low[i]) && ((Border - LowerEntry < High[i] - Border) || (i != 0)) && (High[i] >= High[0])) return(NormalizeDouble(High[i], _Digits)); 563 | } 564 | 565 | return SL; 566 | } 567 | 568 | // Find entry point using the entry channel. 569 | double FindUpperEntryViaChannel() 570 | { 571 | // Invalid value will prevent order from executing in case something goes wrong. 572 | double Entry = -1; 573 | 574 | // Get the upper of main and auxiliary lines 575 | Entry = MathMax(ObjectGetValueByTime(0, EntryChannel, Time[0], 0), ObjectGetValueByTime(0, EntryChannel, Time[0], 1)); 576 | 577 | return NormalizeDouble(Entry, _Digits); 578 | } 579 | 580 | // Find entry point using the entry channel. 581 | double FindLowerEntryViaChannel() 582 | { 583 | // Invalid value will prevent order from executing in case something goes wrong. 584 | double Entry = -1; 585 | 586 | // Get the lower of main and auxiliary lines 587 | Entry = MathMin(ObjectGetValueByTime(0, EntryChannel, Time[0], 0), ObjectGetValueByTime(0, EntryChannel, Time[0], 1)); 588 | 589 | return NormalizeDouble(Entry, _Digits); 590 | } 591 | 592 | // Find TP using the TP channel. 593 | double FindUpperTPViaChannel() 594 | { 595 | // Invalid value will prevent order from executing in case something goes wrong. 596 | double TP = -1; 597 | 598 | // Get the upper of main and auxiliary lines. 599 | TP = MathMax(ObjectGetValueByTime(0, TPChannel, Time[0], 0), ObjectGetValueByTime(0, TPChannel, Time[0], 1)); 600 | 601 | return NormalizeDouble(TP, _Digits); 602 | } 603 | 604 | // Find TP using the TP channel. 605 | double FindLowerTPViaChannel() 606 | { 607 | // Invalid value will prevent order from executing in case something goes wrong. 608 | double TP = -1; 609 | 610 | // Get the lower of main and auxiliary lines. 611 | TP = MathMin(ObjectGetValueByTime(0, TPChannel, Time[0], 0), ObjectGetValueByTime(0, TPChannel, Time[0], 1)); 612 | return NormalizeDouble(TP, _Digits); 613 | } 614 | 615 | void AdjustOrders() 616 | { 617 | AdjustObjects(); // Rename objects if pending orders got executed. 618 | AdjustUpperAndLowerOrders(); 619 | } 620 | 621 | // Sets flags according to found pending orders and positions. 622 | void FindOrders() 623 | { 624 | HaveBuyPending = false; 625 | HaveSellPending = false; 626 | HaveBuy = false; 627 | HaveSell = false; 628 | for (int i = 0; i < OrdersTotal(); i++) 629 | { 630 | if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) continue; 631 | if (((OrderType() == OP_BUYSTOP) || (OrderType() == OP_BUYLIMIT)) && (OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic)) 632 | { 633 | HaveBuyPending = true; 634 | UpperTicket = OrderTicket(); 635 | } 636 | else if (((OrderType() == OP_SELLSTOP) || (OrderType() == OP_SELLLIMIT)) && (OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic)) 637 | { 638 | HaveSellPending = true; 639 | LowerTicket = OrderTicket(); 640 | } 641 | else if ((OrderType() == OP_BUY) && (OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic)) HaveBuy = true; 642 | else if ((OrderType() == OP_SELL) && (OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic)) HaveSell = true; 643 | } 644 | } 645 | 646 | // Renaming objects prevents new position opening. 647 | void AdjustObjects() 648 | { 649 | if (((HaveBuy) && (!HaveBuyPending))) 650 | { 651 | if ((ObjectFind(0, UpperBorderLine) >= 0) || (ObjectFind(0, EntryChannel) >= 0)) 652 | { 653 | Print("Buy position found, renaming chart objects..."); 654 | RenameObject(UpperBorderLine); 655 | RenameObject(UpperEntryLine); 656 | RenameObject(EntryChannel); 657 | } 658 | if (OneCancelsOther) 659 | { 660 | if ((ObjectFind(0, LowerBorderLine) >= 0) || (ObjectFind(0, BorderChannel) >= 0)) 661 | { 662 | Print("OCO is on, renaming opposite chart objects..."); 663 | RenameObject(LowerBorderLine); 664 | RenameObject(LowerEntryLine); 665 | RenameObject(BorderChannel); 666 | } 667 | } 668 | } 669 | if (((HaveSell) && (!HaveSellPending))) 670 | { 671 | if ((ObjectFind(0, LowerEntryLine) >= 0) || (ObjectFind(0, EntryChannel) >= 0)) 672 | { 673 | Print("Sell position found, renaming chart objects..."); 674 | RenameObject(LowerBorderLine); 675 | RenameObject(LowerEntryLine); 676 | RenameObject(EntryChannel); 677 | } 678 | if (OneCancelsOther) 679 | { 680 | if ((ObjectFind(0, UpperBorderLine) >= 0) || (ObjectFind(0, BorderChannel) >= 0)) 681 | { 682 | Print("OCO is on, renaming opposite chart objects..."); 683 | RenameObject(UpperBorderLine); 684 | RenameObject(UpperEntryLine); 685 | RenameObject(BorderChannel); 686 | } 687 | } 688 | } 689 | } 690 | 691 | void RenameObject(string Object) 692 | { 693 | if (ObjectFind(0, Object) > -1) // If exists 694 | { 695 | Print("Renaming ", Object, "."); 696 | // Get object's type, price/time coordinates, style properties. 697 | ENUM_OBJECT OT = (ENUM_OBJECT)ObjectGetInteger(0, Object, OBJPROP_TYPE); 698 | double Price1 = ObjectGetDouble(0, Object, OBJPROP_PRICE, 0); 699 | datetime Time1 = 0; 700 | double Price2 = 0; 701 | datetime Time2 = 0; 702 | double Price3 = 0; 703 | datetime Time3 = 0; 704 | if ((OT == OBJ_TREND) || (OT == OBJ_CHANNEL)) 705 | { 706 | Time1 = (datetime)ObjectGetInteger(0, Object, OBJPROP_TIME, 0); 707 | Price2 = ObjectGetDouble(0, Object, OBJPROP_PRICE, 1); 708 | Time2 = (datetime)ObjectGetInteger(0, Object, OBJPROP_TIME, 1); 709 | if (OT == OBJ_CHANNEL) 710 | { 711 | Price3 = ObjectGetDouble(0, Object, OBJPROP_PRICE, 2); 712 | Time3 = (datetime)ObjectGetInteger(0, Object, OBJPROP_TIME, 2); 713 | } 714 | } 715 | color Color = (color)ObjectGetInteger(0, Object, OBJPROP_COLOR); 716 | ENUM_LINE_STYLE Style = (ENUM_LINE_STYLE)ObjectGetInteger(0, Object, OBJPROP_STYLE); 717 | int Width = (int)ObjectGetInteger(0, Object, OBJPROP_WIDTH); 718 | 719 | // Delete object. 720 | ObjectDelete(0, Object); 721 | string NewObject = Object + IntegerToString(Magic); 722 | // Create the same object with new name and set the old style properties. 723 | ObjectCreate(0, NewObject, OT, 0, Time1, Price1, Time2, Price2, Time3, Price3); 724 | ObjectSetInteger(0, NewObject, OBJPROP_COLOR, Color); 725 | ObjectSetInteger(0, NewObject, OBJPROP_STYLE, Style); 726 | ObjectSetInteger(0, NewObject, OBJPROP_WIDTH, Width); 727 | ObjectSetInteger(0, NewObject, OBJPROP_RAY, true); 728 | } 729 | } 730 | 731 | // The main trading procedure. Sends, Modifies and Deletes orders. 732 | void AdjustUpperAndLowerOrders() 733 | { 734 | double NewVolume; 735 | int last_error; 736 | datetime expiration; 737 | int order_type; 738 | string order_type_string; 739 | 740 | if ((!IsTradeAllowed()) || (IsTradeContextBusy()) || (!IsConnected()) || (!MarketInfo(Symbol(), MODE_TRADEALLOWED))) 741 | { 742 | if (!TCBusy) Output("Trading context is busy or disconnected."); 743 | TCBusy = true; 744 | return; 745 | } 746 | else if (TCBusy) 747 | { 748 | Output("Trading context is no longer busy or disconnected."); 749 | TCBusy = false; 750 | } 751 | 752 | double StopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL) * Point; 753 | double FreezeLevel = MarketInfo(Symbol(), MODE_FREEZELEVEL) * Point; 754 | double LotStep = MarketInfo(Symbol(), MODE_LOTSTEP); 755 | int LotStep_digits = CountDecimalPlaces(LotStep); 756 | 757 | if (UseExpiration) 758 | { 759 | // Set expiration to the end of the current bar. 760 | expiration = Time[0] + Period() * 60; 761 | // If expiration is less than 11 minutes from now, set it to at least 11 minutes from now. 762 | // (Brokers have such limit.) 763 | if (expiration - TimeCurrent() < 660) expiration = TimeCurrent() + 660; 764 | } 765 | else expiration = 0; 766 | 767 | if (OpenOnCloseAboveBelowTrendline) // Simple case. 768 | { 769 | double BorderLevel; 770 | if ((LowerTP > 0) && (!HaveSell) && (UseLower)) // SELL. 771 | { 772 | if (ObjectFind(0, LowerBorderLine) >= 0) // Line. 773 | { 774 | if (ObjectGetInteger(ChartID(), LowerBorderLine, OBJPROP_TYPE) == OBJ_HLINE) BorderLevel = NormalizeDouble(ObjectGetDouble(0, LowerBorderLine, OBJPROP_PRICE1), _Digits); 775 | else BorderLevel = NormalizeDouble(ObjectGetValueByShift(LowerBorderLine, 1), _Digits); 776 | } 777 | else // Channel 778 | { 779 | BorderLevel = MathMin(ObjectGetValueByTime(0, BorderChannel, Time[1], 0), ObjectGetValueByTime(0, BorderChannel, Time[1], 1)); 780 | } 781 | BorderLevel = NormalizeDouble(MathRound(BorderLevel / TickSize) * TickSize, _Digits); 782 | 783 | // Previous candle close significantly lower than the border line. 784 | if (BorderLevel - Close[1] >= SymbolInfoInteger(Symbol(), SYMBOL_SPREAD) * _Point * ThresholdSpreads) 785 | { 786 | RefreshRates(); 787 | NewVolume = GetPositionSize(Bid, LowerSL); 788 | LowerTicket = ExecuteMarketOrder(OP_SELL, NewVolume, Bid, LowerSL, LowerTP); 789 | } 790 | } 791 | else if ((UpperTP > 0) && (!HaveBuy) && (UseUpper)) // BUY. 792 | { 793 | if (ObjectFind(0, UpperBorderLine) >= 0) // Line. 794 | { 795 | if (ObjectGetInteger(ChartID(), UpperBorderLine, OBJPROP_TYPE) == OBJ_HLINE) BorderLevel = NormalizeDouble(ObjectGetDouble(0, UpperBorderLine, OBJPROP_PRICE1), _Digits); 796 | else BorderLevel = NormalizeDouble(ObjectGetValueByShift(UpperBorderLine, 1), _Digits); 797 | } 798 | else // Channel 799 | { 800 | BorderLevel = MathMax(ObjectGetValueByTime(0, BorderChannel, Time[1], 0), ObjectGetValueByTime(0, BorderChannel, Time[1], 1)); 801 | } 802 | BorderLevel = NormalizeDouble(MathRound(BorderLevel / TickSize) * TickSize, _Digits); 803 | 804 | // Previous candle close significantly higher than the border line. 805 | if (Close[1] - BorderLevel >= SymbolInfoInteger(Symbol(), SYMBOL_SPREAD) * _Point * ThresholdSpreads) 806 | { 807 | RefreshRates(); 808 | NewVolume = GetPositionSize(Ask, UpperSL); 809 | UpperTicket = ExecuteMarketOrder(OP_BUY, NewVolume, Ask, UpperSL, UpperTP); 810 | } 811 | } 812 | return; 813 | } 814 | 815 | int OT = OrdersTotal(); 816 | for (int i = OT - 1; i >= 0; i--) 817 | { 818 | double prevOrderOpenPrice, prevOrderStopLoss, prevOrderTakeProfit; 819 | double SL; 820 | if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue; 821 | RefreshRates(); 822 | // BUY 823 | if (((OrderType() == OP_BUYSTOP) || (OrderType() == OP_BUYLIMIT)) && (OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic) && (!DisableBuyOrders)) 824 | { 825 | // Current price is below Sell entry - pending Sell Limit will be used instead of two stop orders. 826 | if ((LowerEntry - Bid > StopLevel) && (UseLower)) continue; 827 | 828 | NewVolume = GetPositionSize(UpperEntry, UpperSL); 829 | // Delete existing pending order 830 | if ((HaveBuy) || ((HaveSell) && (OneCancelsOther)) || (!UseUpper)) 831 | { 832 | if (!OrderDelete(OrderTicket())) 833 | { 834 | last_error = GetLastError(); 835 | Output("OrderDelete() error. Order ticket = " + IntegerToString(OrderTicket()) + ". Error = " + IntegerToString(last_error)); 836 | } 837 | } 838 | // If volume needs to be updated - delete and recreate order with new volume. 839 | // Also check if EA will be able to create new pending order at current price. 840 | else if ((UpdatePendingVolume) && (MathAbs(OrderLots() - NewVolume) > LotStep / 2)) 841 | { 842 | if ((UpperEntry - Ask > StopLevel) || (Ask - UpperEntry > StopLevel)) // Order can be re-created. 843 | { 844 | if (!OrderDelete(OrderTicket())) 845 | { 846 | last_error = GetLastError(); 847 | Output("OrderDelete() error. Order ticket = " + IntegerToString(OrderTicket()) + ". Error = " + IntegerToString(last_error)); 848 | } 849 | Sleep(5000); // Wait 5 seconds before opening a new order. 850 | } 851 | else continue; 852 | // Ask could change after deletion, check if there is still no error 130 present. 853 | RefreshRates(); 854 | if (UpperEntry - Ask > StopLevel) // Current price below entry. 855 | { 856 | order_type = OP_BUYSTOP; 857 | order_type_string = "Stop"; 858 | } 859 | else if (Ask - UpperEntry > StopLevel) // Current price above entry. 860 | { 861 | order_type = OP_BUYLIMIT; 862 | order_type_string = "Limit"; 863 | } 864 | else continue; 865 | if (UseExpiration) 866 | { 867 | // Set expiration to the end of the current bar. 868 | expiration = Time[0] + Period() * 60; 869 | // If expiration is less than 11 minutes extra seconds from now, set it to at least 11 minutes from now. 870 | // (Brokers have such limit.) 871 | if (expiration - TimeCurrent() < 660) expiration = TimeCurrent() + 661; 872 | } 873 | else expiration = 0; 874 | UpperTicket = OrderSend(Symbol(), order_type, NewVolume, UpperEntry, Slippage, UpperSL, UpperTP, "ChartPatternHelper", Magic, expiration); 875 | last_error = GetLastError(); 876 | if ((UpperTicket == -1) && (last_error != 128)) // Ignore time-out errors. 877 | { 878 | Output("StopLevel = " + DoubleToStr(StopLevel, 8)); 879 | Output("FreezeLevel = " + DoubleToStr(FreezeLevel, 8)); 880 | Output("Error Recreating Buy " + order_type_string + ": " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 881 | Output("Volume = " + DoubleToStr(NewVolume, LotStep_digits) + " Entry = " + DoubleToStr(UpperEntry, Digits) + " SL = " + DoubleToStr(UpperSL, Digits) + " TP = " + DoubleToStr(UpperTP, Digits) + " Bid/Ask = " + DoubleToStr(Bid, Digits) + "/" + DoubleToStr(Ask, Digits) + " Exp: " + TimeToStr(expiration, TIME_DATE | TIME_SECONDS)); 882 | } 883 | continue; 884 | } 885 | // Otherwise, update entry/SL/TP if at least one of them has changed. 886 | else if ((MathAbs(OrderOpenPrice() - UpperEntry) > _Point / 2) || (MathAbs(OrderStopLoss() - UpperSL) > _Point / 2) || (MathAbs(OrderTakeProfit() - UpperTP) > _Point / 2)) 887 | { 888 | // Avoid error 130 based on entry. 889 | if (UpperEntry - Ask > StopLevel) // Current price below entry. 890 | { 891 | order_type_string = "Stop"; 892 | } 893 | else if (Ask - UpperEntry > StopLevel) // Current price above entry. 894 | { 895 | order_type_string = "Limit"; 896 | } 897 | else if (MathAbs(OrderOpenPrice() - UpperEntry) > _Point / 2) continue; 898 | // Avoid error 130 based on stop-loss. 899 | if (UpperEntry - UpperSL <= StopLevel) 900 | { 901 | Output("Skipping Modify Buy " + order_type_string + " because stop-loss is too close to entry. StopLevel = " + DoubleToStr(StopLevel, Digits) + " Entry = " + DoubleToStr(UpperEntry, Digits) + " SL = " + DoubleToStr(UpperSL, Digits)); 902 | continue; 903 | } 904 | // Avoid frozen context. In all modification cases. 905 | if ((FreezeLevel != 0) && (MathAbs(OrderOpenPrice() - Ask) <= FreezeLevel)) 906 | { 907 | Output("Skipping Modify Buy " + order_type_string + " because open price is too close to Ask. FreezeLevel = " + DoubleToStr(FreezeLevel, Digits) + " OpenPrice = " + DoubleToStr(OrderOpenPrice(), Digits) + " Ask = " + DoubleToStr(Ask, Digits)); 908 | continue; 909 | } 910 | if (UseExpiration) 911 | { 912 | expiration = OrderExpiration(); 913 | if (expiration - TimeCurrent() < 660) expiration = TimeCurrent() + 660; 914 | } 915 | else expiration = 0; 916 | prevOrderOpenPrice = OrderOpenPrice(); 917 | prevOrderStopLoss = OrderStopLoss(); 918 | prevOrderTakeProfit = OrderTakeProfit(); 919 | if (!OrderModify(OrderTicket(), UpperEntry, UpperSL, UpperTP, expiration)) 920 | { 921 | last_error = GetLastError(); 922 | if (last_error != 128) // Ignore time out errors. 923 | { 924 | if (last_error == 1) 925 | { 926 | Output("PREV: Entry = " + DoubleToStr(OrderOpenPrice(), Digits) + " SL = " + DoubleToStr(OrderStopLoss(), Digits) + " TP = " + DoubleToStr(OrderTakeProfit(), Digits)); 927 | } 928 | Output("StopLevel = " + DoubleToStr(StopLevel, 8)); 929 | Output("FreezeLevel = " + DoubleToStr(FreezeLevel, 8)); 930 | Output("Error Modifying Buy " + order_type_string + ": " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 931 | Output("FROM: Entry = " + DoubleToStr(OrderOpenPrice(), Digits) + " SL = " + DoubleToStr(OrderStopLoss(), Digits) + " TP = " + DoubleToStr(OrderTakeProfit(), Digits) + " -> TO: Entry = " + DoubleToStr(UpperEntry, 8) + " SL = " + DoubleToStr(UpperSL, 8) + " TP = " + DoubleToStr(UpperTP, 8) + " Bid/Ask = " + DoubleToStr(Bid, Digits) + "/" + DoubleToStr(Ask, Digits) + " OrderTicket = " + IntegerToString(OrderTicket()) + " OrderExpiration = " + TimeToStr(OrderExpiration(), TIME_DATE | TIME_SECONDS) + " -> " + TimeToStr(expiration, TIME_DATE | TIME_SECONDS)); 932 | } 933 | } 934 | } 935 | } 936 | else if ((OrderType() == OP_BUY) && (OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic) && (!DisableBuyOrders)) 937 | { 938 | // PostEntrySLAdjustment - a procedure to correct SL if breakout candle become too long and no longer qualifies for SL rule. 939 | if ((OrderOpenTime() > Time[1]) && (OrderOpenTime() < Time[0]) && (PostEntrySLAdjustment) && (PostBuySLAdjustmentDone == false)) 940 | { 941 | SL = AdjustPostBuySL(); 942 | if (SL != -1) 943 | { 944 | // Avoid frozen context. In all modification cases. 945 | if ((FreezeLevel != 0) && (MathAbs(OrderOpenPrice() - Ask) <= FreezeLevel)) 946 | { 947 | Output("Skipping Modify Buy Stop SL because open price is too close to Ask. FreezeLevel = " + DoubleToStr(FreezeLevel, Digits) + " OpenPrice = " + DoubleToStr(OrderOpenPrice(), 8) + " Ask = " + DoubleToStr(Ask, Digits)); 948 | continue; 949 | } 950 | if (NormalizeDouble(SL, Digits) == NormalizeDouble(OrderStopLoss(), Digits)) PostBuySLAdjustmentDone = true; 951 | else 952 | { 953 | if (!OrderModify(OrderTicket(), OrderOpenPrice(), SL, OrderTakeProfit(), OrderExpiration())) 954 | { 955 | last_error = GetLastError(); 956 | if (last_error != 128) // Ignore time out errors. 957 | { 958 | Output("Error Modifying Buy SL: " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 959 | Output("FROM: Entry = " + DoubleToStr(OrderOpenPrice(), Digits) + " SL = " + DoubleToStr(OrderStopLoss(), Digits) + " -> TO: Entry = " + DoubleToStr(OrderOpenPrice(), 8) + " SL = " + DoubleToStr(SL, 8) + " Ask = " + DoubleToStr(Ask, Digits)); 960 | } 961 | } 962 | else PostBuySLAdjustmentDone = true; 963 | } 964 | } 965 | } 966 | // Adjust TP only. 967 | if (MathAbs(OrderTakeProfit() - UpperTP) > _Point / 2) 968 | { 969 | // Avoid frozen context. In all modification cases. 970 | if ((FreezeLevel != 0) && (MathAbs(OrderOpenPrice() - Ask) <= FreezeLevel)) 971 | { 972 | Output("Skipping Modify Buy Stop TP because open price is too close to Ask. FreezeLevel = " + DoubleToStr(FreezeLevel, Digits) + " OpenPrice = " + DoubleToStr(OrderOpenPrice(), 8) + " Ask = " + DoubleToStr(Ask, Digits)); 973 | continue; 974 | } 975 | if (!OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), UpperTP, OrderExpiration())) 976 | { 977 | last_error = GetLastError(); 978 | if (last_error != 128) // Ignore time out errors. 979 | { 980 | Output("Error Modifying Buy TP: " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 981 | Output("FROM: Entry = " + DoubleToStr(OrderOpenPrice(), Digits) + " TP = " + DoubleToStr(OrderTakeProfit(), Digits) + " -> TO: Entry = " + DoubleToStr(OrderOpenPrice(), 8) + " TP = " + DoubleToStr(UpperTP, 8) + " Ask = " + DoubleToStr(Ask, Digits)); 982 | } 983 | } 984 | } 985 | } 986 | // SELL 987 | else if (((OrderType() == OP_SELLSTOP) || (OrderType() == OP_SELLLIMIT)) && (OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic) && (!DisableSellOrders)) 988 | { 989 | // Current price is above Buy entry - pending Buy Limit will be used instead of two stop orders. 990 | if ((Ask - UpperEntry > StopLevel) && (UseUpper)) continue; 991 | 992 | NewVolume = GetPositionSize(LowerEntry, LowerSL); 993 | // Delete existing pending order. 994 | if (((HaveBuy) && (OneCancelsOther)) || (HaveSell) || (!UseLower)) 995 | { 996 | if (!OrderDelete(OrderTicket())) 997 | { 998 | last_error = GetLastError(); 999 | Output("OrderDelete() error. Order ticket = " + IntegerToString(OrderTicket()) + ". Error = " + IntegerToString(last_error)); 1000 | } 1001 | } 1002 | // If volume needs to be updated - delete and recreate order with new volume. Also check if EA will be able to create new pending order at current price. 1003 | else if ((UpdatePendingVolume) && (MathAbs(OrderLots() - NewVolume) > LotStep / 2)) 1004 | { 1005 | if ((Bid - LowerEntry > StopLevel) || (LowerEntry - Bid > StopLevel)) // Order can be re-created 1006 | { 1007 | if (!OrderDelete(OrderTicket())) 1008 | { 1009 | last_error = GetLastError(); 1010 | Output("OrderDelete() error. Order ticket = " + IntegerToString(OrderTicket()) + ". Error = " + IntegerToString(last_error)); 1011 | } 1012 | } 1013 | else continue; 1014 | 1015 | // Bid could change after deletion, check if there is still no error 130 present. 1016 | RefreshRates(); 1017 | if (Bid - LowerEntry > StopLevel) // Current price above entry. 1018 | { 1019 | order_type = OP_BUYSTOP; 1020 | order_type_string = "Stop"; 1021 | } 1022 | else if (LowerEntry - Bid > StopLevel) // Current price below entry. 1023 | { 1024 | order_type = OP_BUYLIMIT; 1025 | order_type_string = "Limit"; 1026 | } 1027 | else continue; 1028 | if (UseExpiration) 1029 | { 1030 | // Set expiration to the end of the current bar. 1031 | expiration = Time[0] + Period() * 60; 1032 | // If expiration is less than 11 minutes extra seconds from now, set it to at least 11 minutes from now. 1033 | // (Brokers have such limit.) 1034 | if (expiration - TimeCurrent() < 660) expiration = TimeCurrent() + 661; 1035 | } 1036 | else expiration = 0; 1037 | LowerTicket = OrderSend(Symbol(), order_type, NewVolume, LowerEntry, Slippage, LowerSL, LowerTP, "ChartPatternHelper", Magic, expiration); 1038 | last_error = GetLastError(); 1039 | if ((LowerTicket == -1) && (last_error != 128)) // Ignore time-out errors. 1040 | { 1041 | Output("StopLevel = " + DoubleToStr(StopLevel, 8)); 1042 | Output("FreezeLevel = " + DoubleToStr(FreezeLevel, 8)); 1043 | Output("Error Recreating Sell " + order_type_string + ": " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 1044 | Output("Volume = " + DoubleToStr(NewVolume, LotStep_digits) + " Entry = " + DoubleToStr(LowerEntry, Digits) + " SL = " + DoubleToStr(LowerSL, Digits) + " TP = " + DoubleToStr(LowerTP, Digits) + " Bid/Ask = " + DoubleToStr(Bid, Digits) + "/" + DoubleToStr(Ask, Digits) + " Exp: " + TimeToStr(expiration, TIME_DATE | TIME_SECONDS)); 1045 | } 1046 | continue; 1047 | } 1048 | // Otherwise, just update what needs to be updated. 1049 | else if ((MathAbs(OrderOpenPrice() - LowerEntry) > _Point / 2) || (MathAbs(OrderStopLoss() - LowerSL) > _Point / 2) || (MathAbs(OrderTakeProfit() - LowerTP) > _Point / 2)) 1050 | { 1051 | // Avoid error 130 based on entry. 1052 | if (Bid - LowerEntry > StopLevel) // Current price above entry. 1053 | { 1054 | order_type_string = "Stop"; 1055 | } 1056 | else if (LowerEntry - Bid > StopLevel) // Current price below entry. 1057 | { 1058 | order_type_string = "Limit"; 1059 | } 1060 | else if (MathAbs(OrderOpenPrice() - LowerEntry) > _Point / 2) continue; 1061 | // Avoid error 130 based on stop-loss. 1062 | if (LowerSL - LowerEntry <= StopLevel) 1063 | { 1064 | Output("Skipping Modify Sell " + order_type_string + " because stop-loss is too close to entry. StopLevel = " + DoubleToStr(StopLevel, Digits) + " Entry = " + DoubleToStr(LowerEntry, Digits) + " SL = " + DoubleToStr(LowerSL, Digits)); 1065 | continue; 1066 | } 1067 | // Avoid frozen context. In all modification cases. 1068 | if ((FreezeLevel != 0) && (MathAbs(Bid - OrderOpenPrice()) <= FreezeLevel)) 1069 | { 1070 | Output("Skipping Modify Sell " + order_type_string + " because open price is too close to Bid. FreezeLevel = " + DoubleToStr(FreezeLevel, Digits) + " OpenPrice = " + DoubleToStr(OrderOpenPrice(), Digits) + " Bid = " + DoubleToStr(Bid, Digits)); 1071 | continue; 1072 | } 1073 | if (UseExpiration) 1074 | { 1075 | expiration = OrderExpiration(); 1076 | if (expiration - TimeCurrent() < 660) expiration = TimeCurrent() + 660; 1077 | } 1078 | else expiration = 0; 1079 | prevOrderOpenPrice = OrderOpenPrice(); 1080 | prevOrderStopLoss = OrderStopLoss(); 1081 | prevOrderTakeProfit = OrderTakeProfit(); 1082 | if (!OrderModify(OrderTicket(), LowerEntry, LowerSL, LowerTP, expiration)) 1083 | { 1084 | last_error = GetLastError(); 1085 | if (last_error != 128) // Ignore time out errors. 1086 | { 1087 | if (last_error == 1) 1088 | { 1089 | Output("PREV: Entry = " + DoubleToStr(OrderOpenPrice(), Digits) + " SL = " + DoubleToStr(OrderStopLoss(), Digits) + " TP = " + DoubleToStr(OrderTakeProfit(), Digits)); 1090 | } 1091 | Output("StopLevel = " + DoubleToStr(StopLevel, 8)); 1092 | Output("FreezeLevel = " + DoubleToStr(FreezeLevel, 8)); 1093 | Output("Error Modifying Sell " + order_type_string + ": " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 1094 | Output("FROM: Entry = " + DoubleToStr(OrderOpenPrice(), Digits) + " SL = " + DoubleToStr(OrderStopLoss(), Digits) + " TP = " + DoubleToStr(OrderTakeProfit(), Digits) + " -> TO: Entry = " + DoubleToStr(LowerEntry, 8) + " SL = " + DoubleToStr(LowerSL, 8) + " TP = " + DoubleToStr(LowerTP, 8) + " Bid/Ask = " + DoubleToStr(Bid, Digits) + "/" + DoubleToStr(Ask, Digits) + " OrderTicket = " + IntegerToString(OrderTicket()) + " OrderExpiration = " + TimeToStr(OrderExpiration(), TIME_DATE | TIME_SECONDS) + " -> " + TimeToStr(expiration, TIME_DATE | TIME_SECONDS)); 1095 | } 1096 | } 1097 | } 1098 | } 1099 | else if ((OrderType() == OP_SELL) && (OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic) && (!DisableSellOrders)) 1100 | { 1101 | // PostEntrySLAdjustment - a procedure to correct SL if breakout candle become too long and no longer qualifies for SL rule. 1102 | if ((OrderOpenTime() > Time[1]) && (OrderOpenTime() < Time[0]) && (PostEntrySLAdjustment) && (PostSellSLAdjustmentDone == false)) 1103 | { 1104 | SL = AdjustPostSellSL(); 1105 | if (SL != -1) 1106 | { 1107 | // Avoid frozen context. In all modification cases. 1108 | if ((FreezeLevel != 0) && (MathAbs(Bid - OrderOpenPrice()) <= FreezeLevel)) 1109 | { 1110 | Output("Skipping Modify Sell Stop SL because open price is too close to Bid. FreezeLevel = " + DoubleToStr(FreezeLevel, Digits) + " OpenPrice = " + DoubleToStr(OrderOpenPrice(), 8) + " Bid = " + DoubleToStr(Bid, Digits)); 1111 | continue; 1112 | } 1113 | if (NormalizeDouble(SL, Digits) == NormalizeDouble(OrderStopLoss(), Digits)) PostSellSLAdjustmentDone = true; 1114 | else 1115 | { 1116 | if (!OrderModify(OrderTicket(), OrderOpenPrice(), SL, OrderTakeProfit(), OrderExpiration())) 1117 | { 1118 | last_error = GetLastError(); 1119 | if (last_error != 128) // Ignore time out errors. 1120 | { 1121 | Output("Error Modifying Sell SL: " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 1122 | Output("FROM: Entry = " + DoubleToStr(OrderOpenPrice(), Digits) + " SL = " + DoubleToStr(OrderStopLoss(), Digits) + " -> TO: Entry = " + DoubleToStr(OrderOpenPrice(), 8) + " SL = " + DoubleToStr(SL, 8) + " Bid = " + DoubleToStr(Bid, Digits)); 1123 | } 1124 | } 1125 | else PostSellSLAdjustmentDone = true; 1126 | } 1127 | } 1128 | } 1129 | // Adjust TP only. 1130 | if (MathAbs(OrderTakeProfit() - LowerTP) > _Point / 2) 1131 | { 1132 | // Avoid frozen context. In all modification cases. 1133 | if ((FreezeLevel != 0) && (MathAbs(Bid - OrderOpenPrice()) <= FreezeLevel)) 1134 | { 1135 | Output("Skipping Modify Sell Stop TP because open price is too close to Bid. FreezeLevel = " + DoubleToStr(FreezeLevel, Digits) + " OpenPrice = " + DoubleToStr(OrderOpenPrice(), 8) + " Bid = " + DoubleToStr(Bid, Digits)); 1136 | continue; 1137 | } 1138 | if (!OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), LowerTP, OrderExpiration())) 1139 | { 1140 | last_error = GetLastError(); 1141 | if (last_error != 128) // Ignore time out errors. 1142 | { 1143 | Output("Error Modifying Sell Stop TP: " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 1144 | Output("FROM: Entry = " + DoubleToStr(OrderOpenPrice(), Digits) + " TP = " + DoubleToStr(OrderTakeProfit(), Digits) + " -> TO: Entry = " + DoubleToStr(OrderOpenPrice(), 8) + " TP = " + DoubleToStr(LowerTP, 8) + " Bid = " + DoubleToStr(Bid, Digits)); 1145 | } 1146 | } 1147 | } 1148 | } 1149 | } 1150 | 1151 | // BUY 1152 | // If we do not already have Long position or Long pending order and if we can enter Long 1153 | // and the current price is not below the Sell entry (in that case, only pending Sell Limit order will be used). 1154 | if ((!HaveBuy) && (!HaveBuyPending) && (UseUpper) && ((LowerEntry - Bid <= StopLevel) || (!UseLower))) 1155 | { 1156 | // Avoid error 130 based on stop-loss. 1157 | if (UpperEntry - UpperSL <= StopLevel) 1158 | { 1159 | Output("Skipping Send Pending Buy because stop-loss is too close to entry. StopLevel = " + DoubleToStr(StopLevel, Digits) + " Entry = " + DoubleToStr(UpperEntry, Digits) + " SL = " + DoubleToStr(UpperSL, Digits)); 1160 | } 1161 | else 1162 | { 1163 | if (UpperEntry - Ask > StopLevel) // Current price below entry. 1164 | { 1165 | order_type = OP_BUYSTOP; 1166 | order_type_string = "Stop"; 1167 | } 1168 | else if (Ask - UpperEntry > StopLevel) // Current price above entry. 1169 | { 1170 | order_type = OP_BUYLIMIT; 1171 | order_type_string = "Limit"; 1172 | } 1173 | else 1174 | { 1175 | order_type = -1; 1176 | Output("Skipping Send Pending Buy because entry is too close to Ask. StopLevel = " + DoubleToStr(StopLevel, Digits) + " Entry = " + DoubleToStr(UpperEntry, Digits) + " Ask = " + DoubleToStr(Ask, Digits)); 1177 | } 1178 | if (order_type > -1) 1179 | { 1180 | NewVolume = GetPositionSize(UpperEntry, UpperSL); 1181 | UpperTicket = OrderSend(Symbol(), order_type, NewVolume, UpperEntry, Slippage, UpperSL, UpperTP, "ChartPatternHelper", Magic, expiration); 1182 | last_error = GetLastError(); 1183 | if ((UpperTicket == -1) && (last_error != 128)) // Ignore time-out errors 1184 | { 1185 | Output("Error Sending Buy " + order_type_string + ": " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 1186 | Output("Volume = " + DoubleToStr(NewVolume, LotStep_digits) + " Entry = " + DoubleToStr(UpperEntry, Digits) + " SL = " + DoubleToStr(UpperSL, Digits) + " TP = " + DoubleToStr(UpperTP, Digits) + " Ask = " + DoubleToStr(Ask, Digits) + " Exp: " + TimeToStr(expiration, TIME_DATE | TIME_SECONDS)); 1187 | } 1188 | } 1189 | } 1190 | } 1191 | 1192 | // SELL 1193 | // If we do not already have Short position or Short pending order and if we can enter Short 1194 | // and the current price is not above the Buy entry (in that case, only pending Buy Limit order will be used). 1195 | if ((!HaveSell) && (!HaveSellPending) && (UseLower) && ((Ask - UpperEntry <= StopLevel) || (!UseUpper))) 1196 | { 1197 | // Avoid error 130 based on stop-loss. 1198 | if (LowerSL - LowerEntry <= StopLevel) 1199 | { 1200 | Output("Skipping Send Pending Sell because stop-loss is too close to entry. StopLevel = " + DoubleToStr(StopLevel, Digits) + " Entry = " + DoubleToStr(LowerEntry, Digits) + " SL = " + DoubleToStr(LowerSL, Digits)); 1201 | } 1202 | else 1203 | { 1204 | if (Bid - LowerEntry > StopLevel) // Current price above entry. 1205 | { 1206 | order_type = OP_SELLSTOP; 1207 | order_type_string = "Stop"; 1208 | } 1209 | else if (LowerEntry - Bid > StopLevel) // Current price below entry. 1210 | { 1211 | order_type = OP_SELLLIMIT; 1212 | order_type_string = "Limit"; 1213 | } 1214 | else 1215 | { 1216 | order_type = -1; 1217 | Output("Skipping Send Pending Sell because entry is too close to Bid. StopLevel = " + DoubleToStr(StopLevel, Digits) + " Entry = " + DoubleToStr(LowerEntry, Digits) + " Bid = " + DoubleToStr(Bid, Digits)); 1218 | } 1219 | if (order_type > -1) 1220 | { 1221 | NewVolume = GetPositionSize(LowerEntry, LowerSL); 1222 | LowerTicket = OrderSend(Symbol(), order_type, NewVolume, LowerEntry, Slippage, LowerSL, LowerTP, "ChartPatternHelper", Magic, expiration); 1223 | last_error = GetLastError(); 1224 | if ((LowerTicket == -1) && (last_error != 128)) // Ignore time-out errors 1225 | { 1226 | Output("Error Sending Sell " + order_type_string + ": " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 1227 | Output("Volume = " + DoubleToStr(NewVolume, LotStep_digits) + " Entry = " + DoubleToStr(LowerEntry, Digits) + " SL = " + DoubleToStr(LowerSL, Digits) + " TP = " + DoubleToStr(LowerTP, Digits) + " Bid = " + DoubleToStr(Bid, Digits) + " Exp: " + TimeToStr(expiration, TIME_DATE | TIME_SECONDS)); 1228 | } 1229 | } 1230 | } 1231 | } 1232 | } 1233 | 1234 | void SetComment(string c) 1235 | { 1236 | if (!Silent) Comment(c); 1237 | } 1238 | 1239 | //+-----------------------------------------------------------------------------------+ 1240 | //| Calculates necessary adjustments for cases when ProfitCurrency != AccountCurrency.| 1241 | //+-----------------------------------------------------------------------------------+ 1242 | #define FOREX_SYMBOLS_ONLY 0 1243 | #define NONFOREX_SYMBOLS_ONLY 1 1244 | double CalculateAdjustment() 1245 | { 1246 | double add_coefficient = 1; // Might be necessary for correction coefficient calculation if two pairs are used for profit currency to account currency conversion. This is handled differently in MT5 version. 1247 | if (ReferenceSymbol == NULL) 1248 | { 1249 | ReferenceSymbol = GetSymbolByCurrencies(ProfitCurrency, account_currency, FOREX_SYMBOLS_ONLY); 1250 | if (ReferenceSymbol == NULL) ReferenceSymbol = GetSymbolByCurrencies(ProfitCurrency, account_currency, NONFOREX_SYMBOLS_ONLY); 1251 | ReferenceSymbolMode = true; 1252 | // Failed. 1253 | if (ReferenceSymbol == NULL) 1254 | { 1255 | // Reversing currencies. 1256 | ReferenceSymbol = GetSymbolByCurrencies(account_currency, ProfitCurrency, FOREX_SYMBOLS_ONLY); 1257 | if (ReferenceSymbol == NULL) ReferenceSymbol = GetSymbolByCurrencies(account_currency, ProfitCurrency, NONFOREX_SYMBOLS_ONLY); 1258 | ReferenceSymbolMode = false; 1259 | } 1260 | if (ReferenceSymbol == NULL) 1261 | { 1262 | // The condition checks whether we are caclulating conversion coefficient for the chart's symbol or for some other. 1263 | // The error output is OK for the current symbol only because it won't be repeated ad infinitum. 1264 | // It should be avoided for non-chart symbols because it will just flood the log. 1265 | Print("Couldn't detect proper currency pair for adjustment calculation. Profit currency: ", ProfitCurrency, ". Account currency: ", account_currency, ". Trying to find a possible two-symbol combination."); 1266 | if ((FindDoubleReferenceSymbol("USD")) // USD should work in 99.9% of cases. 1267 | || (FindDoubleReferenceSymbol("EUR")) // For very rare cases. 1268 | || (FindDoubleReferenceSymbol("GBP")) // For extremely rare cases. 1269 | || (FindDoubleReferenceSymbol("JPY"))) // For extremely rare cases. 1270 | { 1271 | Print("Converting via ", ReferenceSymbol, " and ", AdditionalReferenceSymbol, "."); 1272 | } 1273 | else 1274 | { 1275 | Print("Adjustment calculation critical failure. Failed both simple and two-pair conversion methods."); 1276 | return 1; 1277 | } 1278 | } 1279 | } 1280 | if (AdditionalReferenceSymbol != NULL) // If two reference pairs are used. 1281 | { 1282 | // Calculate just the additional symbol's coefficient and then use it in final return's multiplication. 1283 | MqlTick tick; 1284 | SymbolInfoTick(AdditionalReferenceSymbol, tick); 1285 | add_coefficient = GetCurrencyCorrectionCoefficient(tick, AdditionalReferenceSymbolMode); 1286 | } 1287 | MqlTick tick; 1288 | SymbolInfoTick(ReferenceSymbol, tick); 1289 | return GetCurrencyCorrectionCoefficient(tick, ReferenceSymbolMode) * add_coefficient; 1290 | } 1291 | 1292 | //+---------------------------------------------------------------------------+ 1293 | //| Returns a currency pair with specified base currency and profit currency. | 1294 | //+---------------------------------------------------------------------------+ 1295 | string GetSymbolByCurrencies(const string base_currency, const string profit_currency, const uint symbol_type) 1296 | { 1297 | // Cycle through all symbols. 1298 | for (int s = 0; s < SymbolsTotal(false); s++) 1299 | { 1300 | // Get symbol name by number. 1301 | string symbolname = SymbolName(s, false); 1302 | string b_cur; 1303 | 1304 | // Normal case - Forex pairs: 1305 | if (MarketInfo(symbolname, MODE_PROFITCALCMODE) == 0) 1306 | { 1307 | if (symbol_type == NONFOREX_SYMBOLS_ONLY) continue; // Avoid checking symbols of a wrong type. 1308 | // Get its base currency. 1309 | b_cur = SymbolInfoString(symbolname, SYMBOL_CURRENCY_BASE); 1310 | if (b_cur == "RUR") b_cur = "RUB"; 1311 | } 1312 | else // Weird case for brokers that set conversion pairs as CFDs. 1313 | { 1314 | if (symbol_type == FOREX_SYMBOLS_ONLY) continue; // Avoid checking symbols of a wrong type. 1315 | // Get its base currency as the initial three letters - prone to huge errors! 1316 | b_cur = StringSubstr(symbolname, 0, 3); 1317 | } 1318 | 1319 | // Get its profit currency. 1320 | string p_cur = SymbolInfoString(symbolname, SYMBOL_CURRENCY_PROFIT); 1321 | if (p_cur == "RUR") p_cur = "RUB"; 1322 | 1323 | // If the currency pair matches both currencies, select it in Market Watch and return its name. 1324 | if ((b_cur == base_currency) && (p_cur == profit_currency)) 1325 | { 1326 | // Select if necessary. 1327 | if (!(bool)SymbolInfoInteger(symbolname, SYMBOL_SELECT)) SymbolSelect(symbolname, true); 1328 | 1329 | return symbolname; 1330 | } 1331 | } 1332 | return NULL; 1333 | } 1334 | 1335 | //+----------------------------------------------------------------------------+ 1336 | //| Finds reference symbols using 2-pair method. | 1337 | //| Results are returned via reference parameters. | 1338 | //| Returns true if found the pairs, false otherwise. | 1339 | //+----------------------------------------------------------------------------+ 1340 | bool FindDoubleReferenceSymbol(const string cross_currency) 1341 | { 1342 | // A hypothetical example for better understanding: 1343 | // The trader buys CAD/CHF. 1344 | // account_currency is known = SEK. 1345 | // cross_currency = USD. 1346 | // profit_currency = CHF. 1347 | // I.e., we have to buy dollars with francs (using the Ask price) and then sell those for SEKs (using the Bid price). 1348 | 1349 | ReferenceSymbol = GetSymbolByCurrencies(cross_currency, account_currency, FOREX_SYMBOLS_ONLY); 1350 | if (ReferenceSymbol == NULL) ReferenceSymbol = GetSymbolByCurrencies(cross_currency, account_currency, NONFOREX_SYMBOLS_ONLY); 1351 | ReferenceSymbolMode = true; // If found, we've got USD/SEK. 1352 | 1353 | // Failed. 1354 | if (ReferenceSymbol == NULL) 1355 | { 1356 | // Reversing currencies. 1357 | ReferenceSymbol = GetSymbolByCurrencies(account_currency, cross_currency, FOREX_SYMBOLS_ONLY); 1358 | if (ReferenceSymbol == NULL) ReferenceSymbol = GetSymbolByCurrencies(account_currency, cross_currency, NONFOREX_SYMBOLS_ONLY); 1359 | ReferenceSymbolMode = false; // If found, we've got SEK/USD. 1360 | } 1361 | if (ReferenceSymbol == NULL) 1362 | { 1363 | Print("Error. Couldn't detect proper currency pair for 2-pair adjustment calculation. Cross currency: ", cross_currency, ". Account currency: ", account_currency, "."); 1364 | return false; 1365 | } 1366 | 1367 | AdditionalReferenceSymbol = GetSymbolByCurrencies(cross_currency, ProfitCurrency, FOREX_SYMBOLS_ONLY); 1368 | if (AdditionalReferenceSymbol == NULL) AdditionalReferenceSymbol = GetSymbolByCurrencies(cross_currency, ProfitCurrency, NONFOREX_SYMBOLS_ONLY); 1369 | AdditionalReferenceSymbolMode = false; // If found, we've got USD/CHF. Notice that mode is swapped for cross/profit compared to cross/acc, because it is used in the opposite way. 1370 | 1371 | // Failed. 1372 | if (AdditionalReferenceSymbol == NULL) 1373 | { 1374 | // Reversing currencies. 1375 | AdditionalReferenceSymbol = GetSymbolByCurrencies(ProfitCurrency, cross_currency, FOREX_SYMBOLS_ONLY); 1376 | if (AdditionalReferenceSymbol == NULL) AdditionalReferenceSymbol = GetSymbolByCurrencies(ProfitCurrency, cross_currency, NONFOREX_SYMBOLS_ONLY); 1377 | AdditionalReferenceSymbolMode = true; // If found, we've got CHF/USD. Notice that mode is swapped for profit/cross compared to acc/cross, because it is used in the opposite way. 1378 | } 1379 | if (AdditionalReferenceSymbol == NULL) 1380 | { 1381 | Print("Error. Couldn't detect proper currency pair for 2-pair adjustment calculation. Cross currency: ", cross_currency, ". Chart's pair currency: ", ProfitCurrency, "."); 1382 | return false; 1383 | } 1384 | 1385 | return true; 1386 | } 1387 | 1388 | //+------------------------------------------------------------------+ 1389 | //| Get profit correction coefficient based on current prices. | 1390 | //| Valid for loss calculation only. | 1391 | //+------------------------------------------------------------------+ 1392 | double GetCurrencyCorrectionCoefficient(MqlTick &tick, const bool ref_symbol_mode) 1393 | { 1394 | if ((tick.ask == 0) || (tick.bid == 0)) return -1; // Data is not yet ready. 1395 | // Reverse quote. 1396 | if (ref_symbol_mode) 1397 | { 1398 | // Using Buy price for reverse quote. 1399 | return tick.ask; 1400 | } 1401 | // Direct quote. 1402 | else 1403 | { 1404 | // Using Sell price for direct quote. 1405 | return (1 / tick.bid); 1406 | } 1407 | } 1408 | 1409 | // Taken from PositionSizeCalculator indicator. 1410 | double GetPositionSize(double Entry, double StopLoss) 1411 | { 1412 | double Size, RiskMoney, UnitCost, PositionSize = 0; 1413 | ProfitCurrency = SymbolInfoString(Symbol(), SYMBOL_CURRENCY_PROFIT); 1414 | BaseCurrency = SymbolInfoString(Symbol(), SYMBOL_CURRENCY_BASE); 1415 | ProfitCalcMode = (int)MarketInfo(Symbol(), MODE_PROFITCALCMODE); 1416 | account_currency = AccountCurrency(); 1417 | 1418 | // A rough patch for cases when account currency is set as RUR instead of RUB. 1419 | if (account_currency == "RUR") account_currency = "RUB"; 1420 | if (ProfitCurrency == "RUR") ProfitCurrency = "RUB"; 1421 | if (BaseCurrency == "RUR") BaseCurrency = "RUB"; 1422 | 1423 | double LotStep = MarketInfo(Symbol(), MODE_LOTSTEP); 1424 | int LotStep_digits = CountDecimalPlaces(LotStep); 1425 | 1426 | double SL = MathAbs(Entry - StopLoss); 1427 | 1428 | if (!CalculatePositionSize) return FixedPositionSize; 1429 | 1430 | if (AccountCurrency() == "") return 0; 1431 | 1432 | if (FixedBalance > 0) 1433 | { 1434 | Size = FixedBalance; 1435 | } 1436 | else if (UseEquityInsteadOfBalance) 1437 | { 1438 | Size = AccountEquity(); 1439 | } 1440 | else 1441 | { 1442 | Size = AccountBalance(); 1443 | } 1444 | 1445 | if (!UseMoneyInsteadOfPercentage) RiskMoney = Size * Risk / 100; 1446 | else RiskMoney = MoneyRisk; 1447 | 1448 | // If Symbol is CFD. 1449 | if (ProfitCalcMode == 1) 1450 | UnitCost = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_SIZE) * SymbolInfoDouble(Symbol(), SYMBOL_TRADE_CONTRACT_SIZE); // Apparently, it is more accurate than taking TICKVALUE directly in some cases. 1451 | else UnitCost = MarketInfo(Symbol(), MODE_TICKVALUE); // Futures or Forex. 1452 | 1453 | if (ProfitCalcMode != 0) // Non-Forex might need to be adjusted. 1454 | { 1455 | // If profit currency is different from account currency. 1456 | if (ProfitCurrency != account_currency) 1457 | { 1458 | double CCC = CalculateAdjustment(); // Valid only for loss calculation. 1459 | // Adjust the unit cost. 1460 | UnitCost *= CCC; 1461 | } 1462 | } 1463 | 1464 | // If account currency == pair's base currency, adjust UnitCost to future rate (SL). Works only for Forex pairs. 1465 | if ((account_currency == BaseCurrency) && (ProfitCalcMode == 0)) 1466 | { 1467 | double current_rate = 1, future_rate = StopLoss; 1468 | RefreshRates(); 1469 | if (StopLoss < Entry) 1470 | { 1471 | current_rate = Ask; 1472 | } 1473 | else if (StopLoss > Entry) 1474 | { 1475 | current_rate = Bid; 1476 | } 1477 | UnitCost *= (current_rate / future_rate); 1478 | } 1479 | 1480 | if ((SL != 0) && (UnitCost != 0) && (TickSize != 0)) PositionSize = NormalizeDouble(RiskMoney / (SL * UnitCost / TickSize), LotStep_digits); 1481 | 1482 | if (PositionSize < MarketInfo(Symbol(), MODE_MINLOT)) PositionSize = MarketInfo(Symbol(), MODE_MINLOT); 1483 | else if (PositionSize > MarketInfo(Symbol(), MODE_MAXLOT)) PositionSize = MarketInfo(Symbol(), MODE_MAXLOT); 1484 | double steps = PositionSize / SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); 1485 | if (MathFloor(steps) < steps) PositionSize = MathFloor(steps) * MarketInfo(Symbol(), MODE_LOTSTEP); 1486 | return PositionSize; 1487 | } 1488 | 1489 | // Prints and writes to file error info and context data. 1490 | void Output(string s) 1491 | { 1492 | Print(s); 1493 | if (!ErrorLogging) return; 1494 | int file = FileOpen(filename, FILE_CSV | FILE_READ | FILE_WRITE); 1495 | if (file == -1) Print("Failed to create an error log file: ", GetLastError(), "."); 1496 | else 1497 | { 1498 | FileSeek(file, 0, SEEK_END); 1499 | s = TimeToStr(TimeCurrent(), TIME_DATE | TIME_SECONDS) + " - " + s; 1500 | FileWrite(file, s); 1501 | FileClose(file); 1502 | } 1503 | } 1504 | 1505 | // Runs only one time to adjust SL to appropriate bar's Low if breakout bar's part outside the pattern turned out to be longer than the one inside. 1506 | // Works only if PostEntrySLAdjustment = true. 1507 | double AdjustPostBuySL() 1508 | { 1509 | double SL = -1; 1510 | string smagic = IntegerToString(Magic); 1511 | double Border; 1512 | 1513 | // Border. 1514 | if (ObjectFind(UpperBorderLine + smagic) > -1) 1515 | { 1516 | if ((ObjectType(UpperBorderLine + smagic) != OBJ_HLINE) && (ObjectType(UpperBorderLine + smagic) != OBJ_TREND)) return SL; 1517 | // Starting from 1 because it is new bar after breakout bar. 1518 | for (int i = 1; i < Bars; i++) 1519 | { 1520 | if (ObjectType(UpperBorderLine + smagic) != OBJ_HLINE) Border = ObjectGetValueByShift(UpperBorderLine + smagic, i); 1521 | else Border = ObjectGet(UpperBorderLine + smagic, OBJPROP_PRICE1); // Horizontal line value 1522 | // Major part inside pattern but and SL not closer than breakout bar's SL. 1523 | if ((Border - Low[i] > High[i] - Border) && (Low[i] <= Low[1])) return NormalizeDouble(Low[i], Digits); 1524 | } 1525 | } 1526 | else // Try to find a channel. 1527 | { 1528 | if (ObjectFind(BorderChannel + smagic) > -1) 1529 | { 1530 | if (ObjectType(BorderChannel + smagic) != OBJ_CHANNEL) return SL; 1531 | for (int i = 1; i < Bars; i++) 1532 | { 1533 | // Get the upper of main and auxiliary lines. 1534 | Border = MathMax(ObjectGetValueByTime(0, BorderChannel + smagic, Time[i], 0), ObjectGetValueByTime(0, BorderChannel + smagic, Time[i], 1)); 1535 | // Major part inside pattern but and SL not closer than breakout bar's SL. 1536 | if ((Border - Low[i] > High[i] - Border) && (Low[i] <= Low[0])) return NormalizeDouble(Low[i], _Digits); 1537 | } 1538 | } 1539 | } 1540 | return SL; 1541 | } 1542 | 1543 | // Runs only one time to adjust SL to appropriate bar's High if breakout bar's part outside the pattern turned out to be longer than the one inside. 1544 | // Works only if PostEntrySLAdjustment = true. 1545 | double AdjustPostSellSL() 1546 | { 1547 | double SL = -1; 1548 | string smagic = IntegerToString(Magic); 1549 | double Border; 1550 | 1551 | // Border. 1552 | if (ObjectFind(LowerBorderLine + smagic) > -1) 1553 | { 1554 | if ((ObjectType(LowerBorderLine + smagic) != OBJ_HLINE) && (ObjectType(LowerBorderLine + smagic) != OBJ_TREND)) return SL; 1555 | // Starting from 1 because it is new bar after breakout bar. 1556 | for (int i = 1; i < Bars; i++) 1557 | { 1558 | if (ObjectType(LowerBorderLine + smagic) != OBJ_HLINE) Border = ObjectGetValueByShift(LowerBorderLine + smagic, i); 1559 | else Border = ObjectGet(LowerBorderLine + smagic, OBJPROP_PRICE1); // Horizontal line value 1560 | // Major part inside pattern but and SL not closer than breakout bar's SL. 1561 | if ((High[i] - Border > Border - Low[i]) && (High[i] >= High[0])) return NormalizeDouble(High[i], Digits); 1562 | } 1563 | } 1564 | else // Try to find a channel. 1565 | { 1566 | if (ObjectFind(BorderChannel + smagic) > -1) 1567 | { 1568 | if (ObjectType(BorderChannel + smagic) != OBJ_CHANNEL) return SL; 1569 | for (int i = 1; i < Bars; i++) 1570 | { 1571 | // Get the lower of main and auxiliary lines. 1572 | Border = MathMin(ObjectGetValueByTime(0, BorderChannel + smagic, Time[i], 0), ObjectGetValueByTime(0, BorderChannel + smagic, Time[i], 1)); 1573 | // Major part inside pattern but and SL not closer than breakout bar's SL. 1574 | if ((High[i] - Border > Border - Low[i]) && (High[i] >= High[0])) return NormalizeDouble(High[i], _Digits); 1575 | } 1576 | } 1577 | } 1578 | return SL; 1579 | } 1580 | 1581 | //+------------------------------------------------------------------+ 1582 | //| Counts decimal places. | 1583 | //+------------------------------------------------------------------+ 1584 | int CountDecimalPlaces(double number) 1585 | { 1586 | // 100 as maximum length of number. 1587 | for (int i = 0; i < 100; i++) 1588 | { 1589 | double pwr = MathPow(10, i); 1590 | if (MathRound(number * pwr) / pwr == number) return i; 1591 | } 1592 | return -1; 1593 | } 1594 | 1595 | //+------------------------------------------------------------------+ 1596 | //| Execute a markte order (depends on symbol's trade execution mode.| 1597 | //+------------------------------------------------------------------+ 1598 | int ExecuteMarketOrder(const int order_type, const double volume, const double price, const double sl, const double tp) 1599 | { 1600 | double order_sl = sl; 1601 | double order_tp = tp; 1602 | 1603 | double StopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL) * Point; 1604 | double FreezeLevel = MarketInfo(Symbol(), MODE_FREEZELEVEL) * Point; 1605 | double LotStep = MarketInfo(Symbol(), MODE_LOTSTEP); 1606 | int LotStep_digits = CountDecimalPlaces(LotStep); 1607 | 1608 | ENUM_SYMBOL_TRADE_EXECUTION Execution_Mode = (ENUM_SYMBOL_TRADE_EXECUTION)SymbolInfoInteger(Symbol(), SYMBOL_TRADE_EXEMODE); 1609 | 1610 | // Market execution mode - preparation. 1611 | if (Execution_Mode == SYMBOL_TRADE_EXECUTION_MARKET) 1612 | { 1613 | // No SL/TP allowed on instant orders. 1614 | order_sl = 0; 1615 | order_tp = 0; 1616 | } 1617 | 1618 | int ticket = OrderSend(Symbol(), order_type, volume, price, Slippage, order_sl, order_tp, "Chart Pattern Helper", Magic); 1619 | if (ticket == -1) 1620 | { 1621 | int last_error = GetLastError(); 1622 | string order_string = ""; 1623 | if (order_type == OP_BUY) order_string = "Buy"; 1624 | else if (order_type == OP_SELL) order_string = "Sell"; 1625 | Output("Error Sending " + order_string + ": " + IntegerToString(last_error) + " (" + ErrorDescription(last_error) + ")"); 1626 | Output("Volume = " + DoubleToStr(volume, LotStep_digits) + " Entry = " + DoubleToStr(price, Digits) + " SL = " + DoubleToStr(order_sl, Digits) + " TP = " + DoubleToStr(order_tp, Digits)); 1627 | } 1628 | else 1629 | { 1630 | Output("Order executed. Ticket: " + IntegerToString(ticket) + "."); 1631 | } 1632 | 1633 | // Market execution mode - applying SL/TP. 1634 | if (Execution_Mode == SYMBOL_TRADE_EXECUTION_MARKET) 1635 | { 1636 | if (!OrderSelect(ticket, SELECT_BY_TICKET)) 1637 | { 1638 | Output("Failed to find the order to apply SL/TP."); 1639 | return 0; 1640 | } 1641 | for (int i = 0; i < 10; i++) 1642 | { 1643 | bool result = OrderModify(ticket, OrderOpenPrice(), sl, tp, OrderExpiration()); 1644 | if (result) 1645 | { 1646 | break; 1647 | } 1648 | else 1649 | { 1650 | Output("Error modifying the order: " + IntegerToString(GetLastError())); 1651 | } 1652 | } 1653 | } 1654 | 1655 | return ticket; 1656 | } 1657 | //+------------------------------------------------------------------+ -------------------------------------------------------------------------------- /ChartPatternHelper.mq5: -------------------------------------------------------------------------------- 1 | //+------------------------------------------------------------------+ 2 | //| Chart Pattern Helper | 3 | //| Copyright © 2024, EarnForex.com | 4 | //| https://www.earnforex.com/ | 5 | //+------------------------------------------------------------------+ 6 | #property copyright "Copyright © 2024, EarnForex" 7 | #property link "https://www.earnforex.com/metatrader-expert-advisors/ChartPatternHelper/" 8 | #property version "1.15" 9 | 10 | #property description "Uses graphic objects (horizontal/trend lines, channels) to enter trades." 11 | #property description "Works in two modes:" 12 | #property description "1. Price is below upper entry and above lower entry. Only one or two pending stop orders are used." 13 | #property description "2. Price is above upper entry or below lower entry. Only one pending limit order is used." 14 | #property description "If an object is deleted/renamed after the pending order was placed, order will be canceled." 15 | #property description "Pending order is removed if opposite entry is triggered." 16 | #property description "Generally, it is safe to turn off the EA at any point." 17 | 18 | #include 19 | #include 20 | 21 | input group "Objects" 22 | input string UpperBorderLine = "UpperBorder"; 23 | input string UpperEntryLine = "UpperEntry"; 24 | input string UpperTPLine = "UpperTP"; 25 | input string LowerBorderLine = "LowerBorder"; 26 | input string LowerEntryLine = "LowerEntry"; 27 | input string LowerTPLine = "LowerTP"; 28 | // The pattern may be given as trend/horizontal lines or equidistant channels. 29 | input string BorderChannel = "Border"; 30 | input string EntryChannel = "Entry"; 31 | input string TPChannel = "TP"; 32 | input group "Order management" 33 | // In case Channel is used for Entry, pending orders will be removed even if OneCancelsOther = false. 34 | input bool OneCancelsOther = true; // OneCancelsOther: Remove opposite orders once position is open? 35 | // If true, spread will be added to Buy entry level and Sell SL/TP levels. It compensates the difference when Ask price is used, while all chart objects are drawn at Bid level. 36 | input bool UseSpreadAdjustment = false; // UseSpreadAdjustment: Add spread to Buy entry and Sell SL/TP? 37 | // Not all brokers support expiration. 38 | input bool UseExpiration = true; // UseExpiration: Use expiration on pending orders? 39 | input bool DisableBuyOrders = false; // DisableBuyOrders: Disable new and ignore existing buy trades? 40 | input bool DisableSellOrders = false; // DisableSellOrders: Disable new and ignore existing sell trades? 41 | // If true, the EA will try to adjust SL after breakout candle is complete as it may no longer qualify for SL; it will make SL more precise but will mess up the money management a bit. 42 | input bool PostEntrySLAdjustment = false; // PostEntrySLAdjustment: Adjust SL after entry? 43 | input bool UseDistantSL = false; // UseDistantSL: If true, set SL to pattern's farthest point. 44 | input group "Trendline trading" 45 | input bool OpenOnCloseAboveBelowTrendline = false; // Open trade on close above/below trendline. 46 | input string SLLine = "SL"; // Stop-loss line name for trendline trading. 47 | input int ThresholdSpreads = 10; // Threshold Spreads: number of spreads for minimum distance. 48 | input group "Position sizing" 49 | input bool CalculatePositionSize = true; // CalculatePositionSize: Use money management module? 50 | input bool UpdatePendingVolume = true; // UpdatePendingVolume: If true, recalculate pending order volume. 51 | input double FixedPositionSize = 0.01; // FixedPositionSize: Used if CalculatePositionSize = false. 52 | input double Risk = 1; // Risk: Risk tolerance in percentage points. 53 | input double MoneyRisk = 0; // MoneyRisk: Risk tolerance in base currency. 54 | input bool UseMoneyInsteadOfPercentage = false; 55 | input bool UseEquityInsteadOfBalance = false; 56 | input double FixedBalance = 0; // FixedBalance: If > 0, trade size calc. uses it as balance. 57 | input group "Miscellaneous" 58 | input int Magic = 20200530; 59 | input int Slippage = 30; // Slippage: Maximum slippage in broker's pips. 60 | input bool Silent = false; // Silent: If true, does not display any output via chart comment. 61 | input bool ErrorLogging = true; // ErrorLogging: If true, errors will be logged to file. 62 | 63 | // Global variables: 64 | bool UseUpper, UseLower; 65 | double UpperSL, UpperEntry, UpperTP, LowerSL, LowerEntry, LowerTP; 66 | ulong UpperTicket, LowerTicket; 67 | bool HaveBuyPending = false; 68 | bool HaveSellPending = false; 69 | bool HaveBuy = false; 70 | bool HaveSell = false; 71 | bool TDisabled = false; // Trading disabled. 72 | bool ExpirationEnabled = UseExpiration; 73 | bool PostBuySLAdjustmentDone = false, PostSellSLAdjustmentDone = false; 74 | // For tick value adjustment. 75 | string AccountCurrency = ""; 76 | string ProfitCurrency = ""; 77 | string BaseCurrency = ""; 78 | ENUM_SYMBOL_CALC_MODE CalcMode; 79 | string ReferencePair = NULL; 80 | bool ReferenceSymbolMode; 81 | 82 | // MT5 specific: 83 | datetime Time[]; 84 | double High[], Low[], Close[]; 85 | int SecondsPerBar = 0; 86 | CTrade *Trade; 87 | COrderInfo OrderInfo; 88 | 89 | // For error logging: 90 | string filename; 91 | 92 | void OnInit() 93 | { 94 | PrepareTimeseries(); 95 | FindObjects(); 96 | SecondsPerBar = PeriodSeconds(); 97 | Trade = new CTrade; 98 | Trade.SetDeviationInPoints(Slippage); 99 | Trade.SetExpertMagicNumber(Magic); 100 | 101 | // Do not use expiration if broker does not allow it. 102 | int exp_mode = (int)SymbolInfoInteger(_Symbol, SYMBOL_EXPIRATION_MODE); 103 | if ((exp_mode & 4) != 4) ExpirationEnabled = false; 104 | 105 | if (ErrorLogging) 106 | { 107 | // Creating filename for error logging 108 | MqlDateTime dt; 109 | TimeToStruct(TimeLocal(), dt); 110 | filename = "CPH-Errors-" + IntegerToString(dt.year) + IntegerToString(dt.mon, 2, '0') + IntegerToString(dt.day, 2, '0') + IntegerToString(dt.hour, 2, '0') + IntegerToString(dt.min, 2, '0') + IntegerToString(dt.sec, 2, '0') + ".log"; 111 | } 112 | } 113 | 114 | void OnDeinit(const int reason) 115 | { 116 | SetComment(""); 117 | delete Trade; 118 | } 119 | 120 | void OnTick() 121 | { 122 | DoRoutines(); 123 | } 124 | 125 | void OnChartEvent(const int id, // Event ID 126 | const long& lparam, // Parameter of type long event 127 | const double& dparam, // Parameter of type double event 128 | const string& sparam // Parameter of type string events 129 | ) 130 | { 131 | // If not an object change. 132 | if ((id != CHARTEVENT_OBJECT_DRAG) && (id != CHARTEVENT_OBJECT_CREATE) && (id != CHARTEVENT_OBJECT_CHANGE) && (id != CHARTEVENT_OBJECT_DELETE) && (id != CHARTEVENT_OBJECT_ENDEDIT)) return; 133 | // If not EA's objects. 134 | if ((sparam != UpperBorderLine) && (sparam != UpperEntryLine) && (sparam != UpperTPLine) && (sparam != LowerBorderLine) && (sparam != LowerEntryLine) && (sparam != LowerTPLine) && (sparam != BorderChannel) && (sparam != EntryChannel) && (sparam != TPChannel)) return; 135 | 136 | DoRoutines(); 137 | } 138 | 139 | //+------------------------------------------------------------------+ 140 | //| Main handling function | 141 | //+------------------------------------------------------------------+ 142 | void DoRoutines() 143 | { 144 | PrepareTimeseries(); 145 | FindOrders(); 146 | FindObjects(); 147 | AdjustOrders(); // And delete the ones no longer needed. 148 | } 149 | 150 | // Finds Entry, Border and TP objects. Detects respective levels according to found objects. Outputs found values to chart comment. 151 | void FindObjects() 152 | { 153 | string c1 = FindUpperObjects(); 154 | string c2 = FindLowerObjects(); 155 | 156 | SetComment(c1 + c2); 157 | } 158 | 159 | // Adjustment for Ask/Bid spread is made for entry level as Long positions are entered at Ask, while all objects are drawn at Bid. 160 | string FindUpperObjects() 161 | { 162 | string c = ""; // Text for chart comment 163 | 164 | if (DisableBuyOrders) 165 | { 166 | UseUpper = false; 167 | return "\nBuy orders disabled via input parameters."; 168 | } 169 | 170 | UseUpper = true; 171 | 172 | // Entry. 173 | if (OpenOnCloseAboveBelowTrendline) // Simple trendline entry doesn't need an entry line. 174 | { 175 | c = c + "\nUpper entry unnecessary."; 176 | } 177 | else if (ObjectFind(0, UpperEntryLine) > -1) 178 | { 179 | if ((ObjectGetInteger(0, UpperEntryLine, OBJPROP_TYPE) != OBJ_HLINE) && (ObjectGetInteger(0, UpperEntryLine, OBJPROP_TYPE) != OBJ_TREND)) 180 | { 181 | Alert("Upper Entry Line should be either OBJ_HLINE or OBJ_TREND."); 182 | return("\nWrong Upper Entry Line object type."); 183 | } 184 | if (ObjectGetInteger(0, UpperEntryLine, OBJPROP_TYPE) != OBJ_HLINE) UpperEntry = NormalizeDouble(ObjectGetValueByTime(0, UpperEntryLine, Time[0], 0), _Digits); 185 | else UpperEntry = NormalizeDouble(ObjectGetDouble(0, UpperEntryLine, OBJPROP_PRICE, 0), _Digits); // Horizontal line value 186 | if (UseSpreadAdjustment) UpperEntry = NormalizeDouble(UpperEntry + SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point, _Digits); 187 | ObjectSetInteger(0, UpperEntryLine, OBJPROP_RAY_LEFT, true); 188 | ObjectSetInteger(0, UpperEntryLine, OBJPROP_RAY_RIGHT, true); 189 | c += "\nUpper entry found. Level: " + DoubleToString(UpperEntry, _Digits); 190 | } 191 | else 192 | { 193 | if (ObjectFind(0, EntryChannel) > -1) 194 | { 195 | if (ObjectGetInteger(0, EntryChannel, OBJPROP_TYPE) != OBJ_CHANNEL) 196 | { 197 | Alert("Entry Channel should be OBJ_CHANNEL."); 198 | return "\nWrong Entry Channel object type."; 199 | } 200 | UpperEntry = NormalizeDouble(FindUpperEntryViaChannel(), _Digits); 201 | if (UseSpreadAdjustment) UpperEntry = NormalizeDouble(UpperEntry + SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point, _Digits); 202 | ObjectSetInteger(0, EntryChannel, OBJPROP_RAY_LEFT, true); 203 | ObjectSetInteger(0, EntryChannel, OBJPROP_RAY_RIGHT, true); 204 | c = c + "\nUpper entry found (via channel). Level: " + DoubleToString(UpperEntry, _Digits); 205 | } 206 | else 207 | { 208 | c = c + "\nUpper entry not found. No new position will be entered."; 209 | UseUpper = false; 210 | } 211 | } 212 | 213 | // Border 214 | if (ObjectFind(0, UpperBorderLine) > -1) 215 | { 216 | if ((ObjectGetInteger(0, UpperBorderLine, OBJPROP_TYPE) != OBJ_HLINE) && (ObjectGetInteger(0, UpperBorderLine, OBJPROP_TYPE) != OBJ_TREND)) 217 | { 218 | Alert("Upper Border Line should be either OBJ_HLINE or OBJ_TREND."); 219 | return "\nWrong Upper Border Line object type."; 220 | } 221 | // Find upper SL 222 | UpperSL = FindUpperSL(); 223 | ObjectSetInteger(0, UpperBorderLine, OBJPROP_RAY_LEFT, true); 224 | ObjectSetInteger(0, UpperBorderLine, OBJPROP_RAY_RIGHT, true); 225 | c = c + "\nUpper border found. Upper stop-loss level: " + DoubleToString(UpperSL, _Digits); 226 | } 227 | else // Try to find a channel 228 | { 229 | if (ObjectFind(0, BorderChannel) > -1) 230 | { 231 | if (ObjectGetInteger(0, BorderChannel, OBJPROP_TYPE) != OBJ_CHANNEL) 232 | { 233 | Alert("Border Channel should be OBJ_CHANNEL."); 234 | return "\nWrong Border Channel object type."; 235 | } 236 | // Find upper SL 237 | UpperSL = FindUpperSLViaChannel(); 238 | ObjectSetInteger(0, BorderChannel, OBJPROP_RAY_LEFT, true); 239 | ObjectSetInteger(0, BorderChannel, OBJPROP_RAY_RIGHT, true); 240 | c = c + "\nUpper border found (via channel). Upper stop-loss level: " + DoubleToString(UpperSL, _Digits); 241 | } 242 | else 243 | { 244 | c = c + "\nUpper border not found."; 245 | if ((CalculatePositionSize) && (!HaveBuy)) 246 | { 247 | UseUpper = false; 248 | c = c + " Cannot trade without stop-loss, while CalculatePositionSize set to true."; 249 | } 250 | else 251 | { 252 | c = c + " Stop-loss won\'t be applied to new positions."; 253 | // Track current SL, possibly installed by user 254 | if ((OrderInfo.Select(UpperTicket)) && (OrderInfo.State() == ORDER_STATE_PLACED)) 255 | { 256 | UpperSL = OrderInfo.StopLoss(); 257 | } 258 | } 259 | } 260 | } 261 | // Adjust upper SL for tick size granularity. 262 | double TickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); 263 | UpperSL = NormalizeDouble(MathRound(UpperSL / TickSize) * TickSize, _Digits); 264 | 265 | // Take-profit 266 | if (ObjectFind(0, UpperTPLine) > -1) 267 | { 268 | if ((ObjectGetInteger(0, UpperTPLine, OBJPROP_TYPE) != OBJ_HLINE) && (ObjectGetInteger(0, UpperTPLine, OBJPROP_TYPE) != OBJ_TREND)) 269 | { 270 | Alert("Upper TP Line should be either OBJ_HLINE or OBJ_TREND."); 271 | return("\nWrong Upper TP Line object type."); 272 | } 273 | if (ObjectGetInteger(0, UpperTPLine, OBJPROP_TYPE) != OBJ_HLINE) UpperTP = NormalizeDouble(ObjectGetValueByTime(0, UpperTPLine, Time[0], 0), _Digits); 274 | else UpperTP = NormalizeDouble(ObjectGetDouble(0, UpperTPLine, OBJPROP_PRICE, 0), _Digits); // Horizontal line value 275 | ObjectSetInteger(0, UpperTPLine, OBJPROP_RAY_LEFT, true); 276 | ObjectSetInteger(0, UpperTPLine, OBJPROP_RAY_RIGHT, true); 277 | c = c + "\nUpper take-profit found. Level: " + DoubleToString(UpperTP, _Digits); 278 | } 279 | else 280 | { 281 | if (ObjectFind(0, TPChannel) > -1) 282 | { 283 | if (ObjectGetInteger(0, TPChannel, OBJPROP_TYPE) != OBJ_CHANNEL) 284 | { 285 | Alert("TP Channel should be OBJ_CHANNEL."); 286 | return "\nWrong TP Channel object type."; 287 | } 288 | UpperTP = FindUpperTPViaChannel(); 289 | ObjectSetInteger(0, TPChannel, OBJPROP_RAY_LEFT, true); 290 | ObjectSetInteger(0, TPChannel, OBJPROP_RAY_RIGHT, true); 291 | c = c + "\nUpper TP found (via channel). Level: " + DoubleToString(UpperTP, _Digits); 292 | } 293 | else 294 | { 295 | c = c + "\nUpper take-profit not found. Take-profit won\'t be applied to new positions."; 296 | // Track current TP, possibly installed by user. 297 | if ((OrderInfo.Select(UpperTicket)) && (OrderInfo.State() == ORDER_STATE_PLACED)) 298 | { 299 | UpperTP = OrderInfo.TakeProfit(); 300 | } 301 | } 302 | } 303 | // Adjust upper TP for tick size granularity. 304 | UpperTP = NormalizeDouble(MathRound(UpperTP / TickSize) * TickSize, _Digits); 305 | 306 | return c; 307 | } 308 | 309 | // Adjustment for Ask/Bid spread is made for exit levels (SL and TP) as Short positions are exited at Ask, while all objects are drawn at Bid. 310 | string FindLowerObjects() 311 | { 312 | string c = ""; // Text for chart comment 313 | 314 | if (DisableSellOrders) 315 | { 316 | UseLower = false; 317 | return "\nSell orders disabled via input parameters."; 318 | } 319 | 320 | UseLower = true; 321 | 322 | // Entry. 323 | if (OpenOnCloseAboveBelowTrendline) // Simple trendline entry doesn't need an entry line. 324 | { 325 | c = c + "\nLower entry unnecessary."; 326 | } 327 | else if (ObjectFind(0, LowerEntryLine) > -1) 328 | { 329 | if ((ObjectGetInteger(0, LowerEntryLine, OBJPROP_TYPE) != OBJ_HLINE) && (ObjectGetInteger(0, LowerEntryLine, OBJPROP_TYPE) != OBJ_TREND)) 330 | { 331 | Alert("Lower Entry Line should be either OBJ_HLINE or OBJ_TREND."); 332 | return("\nWrong Lower Entry Line object type."); 333 | } 334 | if (ObjectGetInteger(0, LowerEntryLine, OBJPROP_TYPE) != OBJ_HLINE) LowerEntry = NormalizeDouble(ObjectGetValueByTime(0, LowerEntryLine, Time[0], 0), _Digits); 335 | else LowerEntry = NormalizeDouble(ObjectGetDouble(0, LowerEntryLine, OBJPROP_PRICE, 0), _Digits); // Horizontal line value 336 | ObjectSetInteger(0, LowerEntryLine, OBJPROP_RAY_LEFT, true); 337 | ObjectSetInteger(0, LowerEntryLine, OBJPROP_RAY_RIGHT, true); 338 | c = c + "\nLower entry found. Level: " + DoubleToString(LowerEntry, _Digits); 339 | } 340 | else 341 | { 342 | if (ObjectFind(0, EntryChannel) > -1) 343 | { 344 | if (ObjectGetInteger(0, EntryChannel, OBJPROP_TYPE) != OBJ_CHANNEL) 345 | { 346 | Alert("Entry Channel should be OBJ_CHANNEL."); 347 | return "\nWrong Entry Channel object type."; 348 | } 349 | LowerEntry = FindLowerEntryViaChannel(); 350 | ObjectSetInteger(0, EntryChannel, OBJPROP_RAY_LEFT, true); 351 | ObjectSetInteger(0, EntryChannel, OBJPROP_RAY_RIGHT, true); 352 | c = c + "\nLower entry found (via channel). Level: " + DoubleToString(LowerEntry, _Digits); 353 | } 354 | else 355 | { 356 | c = c + "\nLower entry not found. No new position will be entered."; 357 | UseLower = false; 358 | } 359 | } 360 | 361 | // Border 362 | if (ObjectFind(0, LowerBorderLine) > -1) 363 | { 364 | if ((ObjectGetInteger(0, LowerBorderLine, OBJPROP_TYPE) != OBJ_HLINE) && (ObjectGetInteger(0, LowerBorderLine, OBJPROP_TYPE) != OBJ_TREND)) 365 | { 366 | Alert("Lower Border Line should be either OBJ_HLINE or OBJ_TREND."); 367 | return "\nWrong Lower Border Line object type."; 368 | } 369 | // Find Lower SL 370 | LowerSL = NormalizeDouble(FindLowerSL(), _Digits); 371 | if (UseSpreadAdjustment) LowerSL = NormalizeDouble(LowerSL + SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point, _Digits); 372 | ObjectSetInteger(0, LowerBorderLine, OBJPROP_RAY_LEFT, true); 373 | ObjectSetInteger(0, LowerBorderLine, OBJPROP_RAY_RIGHT, true); 374 | c = c + "\nLower border found. Lower stop-loss level: " + DoubleToString(LowerSL, _Digits); 375 | } 376 | else // Try to find a channel 377 | { 378 | if (ObjectFind(0, BorderChannel) > -1) 379 | { 380 | if (ObjectGetInteger(0, BorderChannel, OBJPROP_TYPE) != OBJ_CHANNEL) 381 | { 382 | Alert("Border Channel should be OBJ_CHANNEL."); 383 | return "\nWrong Border Channel object type."; 384 | } 385 | // Find Lower SL 386 | LowerSL = NormalizeDouble(FindLowerSLViaChannel(), _Digits); 387 | if (UseSpreadAdjustment) LowerSL = NormalizeDouble(LowerSL + SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point, _Digits); 388 | ObjectSetInteger(0, BorderChannel, OBJPROP_RAY_LEFT, true); 389 | ObjectSetInteger(0, BorderChannel, OBJPROP_RAY_RIGHT, true); 390 | c = c + "\nLower border found (via channel). Lower stop-loss level: " + DoubleToString(LowerSL, _Digits); 391 | } 392 | else 393 | { 394 | c = c + "\nLower border not found."; 395 | if ((CalculatePositionSize) && (!HaveSell)) 396 | { 397 | UseLower = false; 398 | c = c + " Cannot trade without stop-loss, while CalculatePositionSize set to true."; 399 | } 400 | else 401 | { 402 | c = c + " Stop-loss won\'t be applied to new positions."; 403 | // Track current SL, possibly installed by user 404 | if ((OrderInfo.Select(LowerTicket)) && (OrderInfo.State() == ORDER_STATE_PLACED)) 405 | { 406 | LowerSL = OrderInfo.StopLoss(); 407 | } 408 | } 409 | } 410 | } 411 | // Adjust lower SL for tick size granularity. 412 | double TickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); 413 | LowerSL = NormalizeDouble(MathRound(LowerSL / TickSize) * TickSize, _Digits); 414 | 415 | // Take-profit 416 | if (ObjectFind(0, LowerTPLine) > -1) 417 | { 418 | if ((ObjectGetInteger(0, LowerTPLine, OBJPROP_TYPE) != OBJ_HLINE) && (ObjectGetInteger(0, LowerTPLine, OBJPROP_TYPE) != OBJ_TREND)) 419 | { 420 | Alert("Lower TP Line should be either OBJ_HLINE or OBJ_TREND."); 421 | return "\nWrong Lower TP Line object type."; 422 | } 423 | if (ObjectGetInteger(0, LowerTPLine, OBJPROP_TYPE) != OBJ_HLINE) LowerTP = NormalizeDouble(ObjectGetValueByTime(0, LowerTPLine, Time[0], 0), _Digits); 424 | else LowerTP = NormalizeDouble(ObjectGetDouble(0, LowerTPLine, OBJPROP_PRICE, 0), _Digits); // Horizontal line value 425 | if (UseSpreadAdjustment) LowerTP = NormalizeDouble(LowerTP + SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point, _Digits); 426 | ObjectSetInteger(0, LowerTPLine, OBJPROP_RAY_LEFT, true); 427 | ObjectSetInteger(0, LowerTPLine, OBJPROP_RAY_RIGHT, true); 428 | c = c + "\nLower take-profit found. Level: " + DoubleToString(LowerTP, _Digits); 429 | } 430 | else 431 | { 432 | if (ObjectFind(0, TPChannel) > -1) 433 | { 434 | if (ObjectGetInteger(0, TPChannel, OBJPROP_TYPE) != OBJ_CHANNEL) 435 | { 436 | Alert("TP Channel should be OBJ_CHANNEL."); 437 | return "\nWrong TP Channel object type."; 438 | } 439 | LowerTP = NormalizeDouble(FindLowerTPViaChannel(), _Digits); 440 | if (UseSpreadAdjustment) LowerTP = NormalizeDouble(LowerTP + SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point, _Digits); 441 | ObjectSetInteger(0, TPChannel, OBJPROP_RAY_LEFT, true); 442 | ObjectSetInteger(0, TPChannel, OBJPROP_RAY_RIGHT, true); 443 | c = c + "\nLower TP found (via channel). Level: " + DoubleToString(LowerTP, _Digits); 444 | } 445 | else 446 | { 447 | c = c + "\nLower take-profit not found. Take-profit won\'t be applied to new positions."; 448 | // Track current TP, possibly installed by user 449 | if ((OrderInfo.Select(LowerTicket)) && (OrderInfo.State() == ORDER_STATE_PLACED)) 450 | { 451 | LowerTP = OrderInfo.TakeProfit(); 452 | } 453 | } 454 | } 455 | // Adjust lower TP for tick size granularity. 456 | LowerTP = NormalizeDouble(MathRound(LowerTP / TickSize) * TickSize, _Digits); 457 | 458 | return c; 459 | } 460 | 461 | // Find SL using a border line - the low of the first bar with major part below border. 462 | double FindUpperSL() 463 | { 464 | // Invalid value will prevent order from executing in case something goes wrong. 465 | double SL = -1; 466 | 467 | // Everything becomes much easier if the EA just needs to find the farthest opposite point of the pattern. 468 | if (UseDistantSL) 469 | { 470 | // Horizontal line. 471 | if (ObjectGetInteger(0, LowerBorderLine, OBJPROP_TYPE) == OBJ_HLINE) 472 | { 473 | return NormalizeDouble(ObjectGetDouble(0, LowerBorderLine, OBJPROP_PRICE, 0), _Digits); 474 | } 475 | // Trend line. 476 | else if (ObjectGetInteger(0, LowerBorderLine, OBJPROP_TYPE) == OBJ_TREND) 477 | { 478 | double price1 = ObjectGetDouble(0, LowerBorderLine, OBJPROP_PRICE, 0); 479 | double price2 = ObjectGetDouble(0, LowerBorderLine, OBJPROP_PRICE, 1); 480 | if (price1 < price2) return(NormalizeDouble(price1, _Digits)); 481 | else return NormalizeDouble(price2, _Digits); 482 | } 483 | } 484 | 485 | // Easy stop-loss via a separate horizontal line when using trendline trading. 486 | if (OpenOnCloseAboveBelowTrendline) 487 | { 488 | if (ObjectFind(0, SLLine) < 0) return -1; 489 | return NormalizeDouble(ObjectGetDouble(0, SLLine, OBJPROP_PRICE, 0), _Digits); 490 | } 491 | 492 | for (int i = 0; i < Bars(_Symbol, _Period); i++) 493 | { 494 | double Border, Entry; 495 | if (ObjectGetInteger(0, UpperBorderLine, OBJPROP_TYPE) != OBJ_HLINE) Border = ObjectGetValueByTime(0, UpperBorderLine, Time[i], 0); 496 | else Border = ObjectGetDouble(0, UpperBorderLine, OBJPROP_PRICE, 0); // Horizontal line value 497 | if (ObjectGetInteger(0, UpperEntryLine, OBJPROP_TYPE) != OBJ_HLINE) Entry = ObjectGetValueByTime(0, UpperEntryLine, Time[i], 0); 498 | else Entry = ObjectGetDouble(0, UpperEntryLine, OBJPROP_PRICE, 0); // Horizontal line value 499 | // Additional condition (Entry) checks whether _current_ candle may still have a bigger part within border before triggering entry. 500 | // It is not possible if the current height inside border is not bigger than the distance from border to entry. 501 | // It should not be checked for candles already completed. 502 | // Additionally, if skipped the first bar because it could not potentially qualify, next bar's Low should be lower or equal to that of the first bar. 503 | if ((Border - Low[i] > High[i] - Border) && ((Entry - Border < Border - Low[i]) || (i != 0)) && (Low[i] <= Low[0])) return NormalizeDouble(Low[i], _Digits); 504 | } 505 | 506 | return SL; 507 | } 508 | 509 | // Find SL using a border line - the high of the first bar with major part above border. 510 | double FindLowerSL() 511 | { 512 | // Invalid value will prevent order from executing in case something goes wrong. 513 | double SL = -1; 514 | 515 | // Everything becomes much easier if the EA just needs to find the farthest opposite point of the pattern. 516 | if (UseDistantSL) 517 | { 518 | // Horizontal line. 519 | if (ObjectGetInteger(0, UpperBorderLine, OBJPROP_TYPE) == OBJ_HLINE) 520 | { 521 | return NormalizeDouble(ObjectGetDouble(0, UpperBorderLine, OBJPROP_PRICE, 0), _Digits); 522 | } 523 | // Trend line. 524 | else if (ObjectGetInteger(0, UpperBorderLine, OBJPROP_TYPE) == OBJ_TREND) 525 | { 526 | double price1 = ObjectGetDouble(0, UpperBorderLine, OBJPROP_PRICE, 0); 527 | double price2 = ObjectGetDouble(0, UpperBorderLine, OBJPROP_PRICE, 1); 528 | if (price1 > price2) return NormalizeDouble(price1, _Digits); 529 | else return NormalizeDouble(price2, _Digits); 530 | } 531 | } 532 | 533 | // Easy stop-loss via a separate horizontal line when using trendline trading. 534 | if (OpenOnCloseAboveBelowTrendline) 535 | { 536 | if (ObjectFind(0, SLLine) < 0) return -1; 537 | return NormalizeDouble(ObjectGetDouble(0, SLLine, OBJPROP_PRICE, 0), _Digits); 538 | } 539 | 540 | for (int i = 0; i < Bars(_Symbol, _Period); i++) 541 | { 542 | double Border, Entry; 543 | if (ObjectGetInteger(0, LowerBorderLine, OBJPROP_TYPE) != OBJ_HLINE) Border = ObjectGetValueByTime(0, LowerBorderLine, Time[i], 0); 544 | else Border = ObjectGetDouble(0, LowerBorderLine, OBJPROP_PRICE, 0); // Horizontal line value 545 | if (ObjectGetInteger(0, LowerEntryLine, OBJPROP_TYPE) != OBJ_HLINE) Entry = ObjectGetValueByTime(0, LowerEntryLine, Time[i], 0); 546 | else Entry = ObjectGetDouble(0, LowerEntryLine, OBJPROP_PRICE, 0); // Horizontal line value 547 | // Additional condition (Entry) checks whether _current_ candle may still have a bigger part within border before triggering entry. 548 | // It is not possible if the current height inside border is not bigger than the distance from border to entry. 549 | // It should not be checked for candles already completed. 550 | // Additionally, if skipped the first bar because it could not potentially qualify, next bar's High should be higher or equal to that of the first bar. 551 | if ((High[i] - Border > Border - Low[i]) && ((Border - Entry < High[i] - Border) || (i != 0)) && (High[i] >= High[0])) return NormalizeDouble(High[i], _Digits); 552 | } 553 | 554 | return SL; 555 | } 556 | 557 | // Find SL using a border channel - the low of the first bar with major part below upper line. 558 | double FindUpperSLViaChannel() 559 | { 560 | // Invalid value will prevent order from executing in case something goes wrong. 561 | double SL = -1; 562 | 563 | // Easy stop-loss via a separate horizontal line when using trendline trading. 564 | if (OpenOnCloseAboveBelowTrendline) 565 | { 566 | if (ObjectFind(0, SLLine) < 0) return -1; 567 | return NormalizeDouble(ObjectGetDouble(0, SLLine, OBJPROP_PRICE, 0), _Digits); 568 | } 569 | 570 | for (int i = 0; i < Bars(_Symbol, _Period); i++) 571 | { 572 | // Get the upper of main and auxiliary lines 573 | double Border = MathMax(ObjectGetValueByTime(0, BorderChannel, Time[i], 0), ObjectGetValueByTime(0, BorderChannel, Time[i], 1)); 574 | 575 | // Additional condition (Entry) checks whether _current_ candle may still have a bigger part within border before triggering entry. 576 | // It is not possible if the current height inside border is not bigger than the distance from border to entry. 577 | // It should not be checked for candles already completed. 578 | // Additionally, if skipped the first bar because it could not potentially qualify, next bar's Low should be lower or equal to that of the first bar. 579 | if ((Border - Low[i] > High[i] - Border) && ((UpperEntry - Border < Border - Low[i]) || (i != 0)) && (Low[i] <= Low[0])) return NormalizeDouble(Low[i], _Digits); 580 | } 581 | 582 | return SL; 583 | } 584 | 585 | // Find SL using a border channel - the high of the first bar with major part above upper line. 586 | double FindLowerSLViaChannel() 587 | { 588 | // Invalid value will prevent order from executing in case something goes wrong. 589 | double SL = -1; 590 | 591 | // Easy stop-loss via a separate horizontal line when using trendline trading. 592 | if (OpenOnCloseAboveBelowTrendline) 593 | { 594 | if (ObjectFind(0, SLLine) < 0) return -1; 595 | return NormalizeDouble(ObjectGetDouble(0, SLLine, OBJPROP_PRICE, 0), _Digits); 596 | } 597 | 598 | for (int i = 0; i < Bars(_Symbol, _Period); i++) 599 | { 600 | // Get the lower of main and auxiliary lines 601 | double Border = MathMin(ObjectGetValueByTime(0, BorderChannel, Time[i], 0), ObjectGetValueByTime(0, BorderChannel, Time[i], 1)); 602 | 603 | // Additional condition (Entry) checks whether _current_ candle may still have a bigger part within border before triggering entry. 604 | // It is not possible if the current height inside border is not bigger than the distance from border to entry. 605 | // It should not be checked for candles already completed. 606 | // Additionally, if skipped the first bar because it could not potentially qualify, next bar's High should be higher or equal to that of the first bar. 607 | if ((High[i] - Border > Border - Low[i]) && ((Border - LowerEntry < High[i] - Border) || (i != 0)) && (High[i] >= High[0])) return NormalizeDouble(High[i], _Digits); 608 | } 609 | 610 | return SL; 611 | } 612 | 613 | // Find entry point using the entry channel. 614 | double FindUpperEntryViaChannel() 615 | { 616 | // Invalid value will prevent order from executing in case something goes wrong. 617 | double Entry = -1; 618 | 619 | // Get the upper of main and auxiliary lines 620 | Entry = MathMax(ObjectGetValueByTime(0, EntryChannel, Time[0], 0), ObjectGetValueByTime(0, EntryChannel, Time[0], 1)); 621 | 622 | return NormalizeDouble(Entry, _Digits); 623 | } 624 | 625 | // Find entry point using the entry channel. 626 | double FindLowerEntryViaChannel() 627 | { 628 | // Invalid value will prevent order from executing in case something goes wrong. 629 | double Entry = -1; 630 | 631 | // Get the lower of main and auxiliary lines 632 | Entry = MathMin(ObjectGetValueByTime(0, EntryChannel, Time[0], 0), ObjectGetValueByTime(0, EntryChannel, Time[0], 1)); 633 | 634 | return NormalizeDouble(Entry, _Digits); 635 | } 636 | 637 | // Find TP using the TP channel. 638 | double FindUpperTPViaChannel() 639 | { 640 | // Invalid value will prevent order from executing in case something goes wrong. 641 | double TP = -1; 642 | 643 | // Get the upper of main and auxiliary lines. 644 | TP = MathMax(ObjectGetValueByTime(0, TPChannel, Time[0], 0), ObjectGetValueByTime(0, TPChannel, Time[0], 1)); 645 | 646 | return NormalizeDouble(TP, _Digits); 647 | } 648 | 649 | // Find TP using the TP channel. 650 | double FindLowerTPViaChannel() 651 | { 652 | // Invalid value will prevent order from executing in case something goes wrong. 653 | double TP = -1; 654 | 655 | // Get the lower of main and auxiliary lines. 656 | TP = MathMin(ObjectGetValueByTime(0, TPChannel, Time[0], 0), ObjectGetValueByTime(0, TPChannel, Time[0], 1)); 657 | 658 | return NormalizeDouble(TP, _Digits); 659 | } 660 | 661 | void AdjustOrders() 662 | { 663 | AdjustObjects(); // Rename objects if pending orders got executed. 664 | AdjustUpperAndLowerOrders(); 665 | } 666 | 667 | // Sets flags according to found pending orders and positions. 668 | void FindOrders() 669 | { 670 | HaveBuyPending = false; 671 | HaveSellPending = false; 672 | HaveBuy = false; 673 | HaveSell = false; 674 | if (AccountInfoInteger(ACCOUNT_MARGIN_MODE) == ACCOUNT_MARGIN_MODE_RETAIL_NETTING) // Netting: 675 | { 676 | if (PositionSelect(_Symbol)) 677 | { 678 | if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) HaveBuy = true; 679 | else HaveSell = true; 680 | } 681 | } 682 | else // Hednging/exchange: 683 | { 684 | for (int i = 0; i < PositionsTotal(); i++) 685 | { 686 | if ((PositionGetString(POSITION_SYMBOL) != _Symbol) || (PositionGetInteger(POSITION_MAGIC) != Magic)) continue; 687 | if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) HaveBuy = true; 688 | else HaveSell = true; 689 | } 690 | } 691 | for (int i = 0; i < OrdersTotal(); i++) 692 | { 693 | OrderGetTicket(i); 694 | if (((OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY_STOP) || (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY_LIMIT)) && (OrderGetString(ORDER_SYMBOL) == _Symbol) && (OrderGetInteger(ORDER_MAGIC) == Magic)) 695 | { 696 | HaveBuyPending = true; 697 | UpperTicket = OrderGetTicket(i); 698 | } 699 | else if (((OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL_STOP) || (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL_LIMIT)) && (OrderGetString(ORDER_SYMBOL) == _Symbol) && (OrderGetInteger(ORDER_MAGIC) == Magic)) 700 | { 701 | HaveSellPending = true; 702 | LowerTicket = OrderGetTicket(i); 703 | } 704 | } 705 | } 706 | 707 | // Renaming objects prevents new position opening. 708 | void AdjustObjects() 709 | { 710 | if (((HaveBuy) && (!HaveBuyPending))) 711 | { 712 | if ((ObjectFind(0, UpperBorderLine) >= 0) || (ObjectFind(0, EntryChannel) >= 0)) 713 | { 714 | Print("Buy position found, renaming chart objects..."); 715 | RenameObject(UpperBorderLine); 716 | RenameObject(UpperEntryLine); 717 | RenameObject(EntryChannel); 718 | } 719 | if (OneCancelsOther) 720 | { 721 | if ((ObjectFind(0, LowerBorderLine) >= 0) || (ObjectFind(0, BorderChannel) >= 0)) 722 | { 723 | Print("OCO is on, renaming opposite chart objects..."); 724 | RenameObject(LowerBorderLine); 725 | RenameObject(LowerEntryLine); 726 | RenameObject(BorderChannel); 727 | } 728 | } 729 | } 730 | if (((HaveSell) && (!HaveSellPending))) 731 | { 732 | if ((ObjectFind(0, LowerEntryLine) >= 0) || (ObjectFind(0, EntryChannel) >= 0)) 733 | { 734 | Print("Sell position found, renaming chart objects..."); 735 | RenameObject(LowerBorderLine); 736 | RenameObject(LowerEntryLine); 737 | RenameObject(EntryChannel); 738 | } 739 | if (OneCancelsOther) 740 | { 741 | if ((ObjectFind(0, UpperBorderLine) >= 0) || (ObjectFind(0, BorderChannel) >= 0)) 742 | { 743 | Print("OCO is on, renaming opposite chart objects..."); 744 | RenameObject(UpperBorderLine); 745 | RenameObject(UpperEntryLine); 746 | RenameObject(BorderChannel); 747 | } 748 | } 749 | } 750 | } 751 | 752 | void RenameObject(string Object) 753 | { 754 | if (ObjectFind(0, Object) > -1) // If exists. 755 | { 756 | Print("Renaming ", Object, "."); 757 | ObjectSetString(0, Object, OBJPROP_NAME, Object + IntegerToString(Magic)); 758 | } 759 | } 760 | 761 | // The main trading procedure. Sends, Modifies and Deletes orders. 762 | void AdjustUpperAndLowerOrders() 763 | { 764 | double NewVolume; 765 | int last_error; 766 | datetime expiration; 767 | ENUM_ORDER_TYPE_TIME type_time; 768 | ENUM_ORDER_TYPE order_type; 769 | string order_type_string; 770 | 771 | if ((!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)) || (!TerminalInfoInteger(TERMINAL_CONNECTED)) || (SymbolInfoInteger(_Symbol, SYMBOL_TRADE_MODE) != SYMBOL_TRADE_MODE_FULL)) 772 | { 773 | if (!TDisabled) Output("Trading disabled or disconnected."); 774 | TDisabled = true; 775 | return; 776 | } 777 | else if (TDisabled) 778 | { 779 | Output("Trading is no longer disabled or disconnected."); 780 | TDisabled = false; 781 | } 782 | 783 | double StopLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * _Point; 784 | double FreezeLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL) * _Point; 785 | double Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); 786 | double Bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); 787 | double TickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); 788 | double LotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); 789 | int LotStep_digits = CountDecimalPlaces(LotStep); 790 | 791 | if (OpenOnCloseAboveBelowTrendline) // Simple case. 792 | { 793 | double BorderLevel; 794 | if ((LowerTP > 0) && (!HaveSell) && (UseLower)) // SELL. 795 | { 796 | if (ObjectFind(0, LowerBorderLine) >= 0) // Line. 797 | { 798 | if (ObjectGetInteger(ChartID(), LowerBorderLine, OBJPROP_TYPE) == OBJ_HLINE) BorderLevel = NormalizeDouble(ObjectGetDouble(0, LowerBorderLine, OBJPROP_PRICE, 0), _Digits); 799 | else BorderLevel = NormalizeDouble(ObjectGetValueByTime(ChartID(), LowerBorderLine, Time[1]), _Digits); 800 | } 801 | else // Channel 802 | { 803 | BorderLevel = MathMin(ObjectGetValueByTime(0, BorderChannel, Time[1], 0), ObjectGetValueByTime(0, BorderChannel, Time[1], 1)); 804 | } 805 | BorderLevel = NormalizeDouble(MathRound(BorderLevel / TickSize) * TickSize, _Digits); 806 | 807 | // Previous candle close significantly lower than the border line. 808 | if (BorderLevel - Close[1] >= SymbolInfoInteger(Symbol(), SYMBOL_SPREAD) * _Point * ThresholdSpreads) 809 | { 810 | NewVolume = GetPositionSize(Bid, LowerSL, ORDER_TYPE_SELL); 811 | LowerTicket = ExecuteMarketOrder(ORDER_TYPE_SELL, NewVolume, Bid, LowerSL, LowerTP); 812 | } 813 | } 814 | else if ((UpperTP > 0) && (!HaveBuy) && (UseUpper)) // BUY. 815 | { 816 | if (ObjectFind(0, UpperBorderLine) >= 0) // Line. 817 | { 818 | if (ObjectGetInteger(ChartID(), UpperBorderLine, OBJPROP_TYPE) == OBJ_HLINE) BorderLevel = NormalizeDouble(ObjectGetDouble(0, UpperBorderLine, OBJPROP_PRICE, 0), _Digits); 819 | else BorderLevel = NormalizeDouble(ObjectGetValueByTime(ChartID(), UpperBorderLine, Time[1]), _Digits); 820 | } 821 | else // Channel 822 | { 823 | BorderLevel = MathMax(ObjectGetValueByTime(0, BorderChannel, Time[1], 0), ObjectGetValueByTime(0, BorderChannel, Time[1], 1)); 824 | } 825 | BorderLevel = NormalizeDouble(MathRound(BorderLevel / TickSize) * TickSize, _Digits); 826 | 827 | // Previous candle close significantly higher than the border line. 828 | if (Close[1] - BorderLevel >= SymbolInfoInteger(Symbol(), SYMBOL_SPREAD) * _Point * ThresholdSpreads) 829 | { 830 | 831 | NewVolume = GetPositionSize(Ask, UpperSL, ORDER_TYPE_BUY); 832 | UpperTicket = ExecuteMarketOrder(ORDER_TYPE_BUY, NewVolume, Ask, UpperSL, UpperTP); 833 | } 834 | } 835 | return; 836 | } 837 | 838 | // Have open position. 839 | if (PositionSelect(_Symbol)) 840 | { 841 | // PostEntrySLAdjustment - a procedure to correct SL if breakout candle become too long and no longer qualifies for SL rule. 842 | if ((PositionGetInteger(POSITION_TIME) > Time[1]) && (PositionGetInteger(POSITION_TIME) < Time[0]) && (PostEntrySLAdjustment) && (PostBuySLAdjustmentDone == false)) 843 | { 844 | double SL = AdjustPostBuySL(); 845 | if (SL != -1) 846 | { 847 | // Avoid frozen context. In all modification cases. 848 | if ((FreezeLevel != 0) && (MathAbs(PositionGetDouble(POSITION_PRICE_OPEN) - Ask) <= FreezeLevel)) 849 | { 850 | Output("Skipping Modify Buy Stop SL because open price is too close to Ask. FreezeLevel = " + DoubleToString(FreezeLevel, _Digits) + " OpenPrice = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), 8) + " Ask = " + DoubleToString(Ask, _Digits)); 851 | } 852 | else 853 | { 854 | if (NormalizeDouble(SL, _Digits) == NormalizeDouble(PositionGetDouble(POSITION_SL), _Digits)) PostBuySLAdjustmentDone = true; 855 | else 856 | { 857 | if (!Trade.PositionModify(_Symbol, SL, PositionGetDouble(POSITION_TP))) 858 | { 859 | last_error = GetLastError(); 860 | Output("Error Modifying Buy SL: " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 861 | Output("FROM: Entry = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), _Digits) + " SL = " + DoubleToString(PositionGetDouble(POSITION_SL), _Digits) + " -> TO: Entry = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), 8) + " SL = " + DoubleToString(SL, 8) + " Ask = " + DoubleToString(Ask, _Digits)); 862 | } 863 | else PostBuySLAdjustmentDone = true; 864 | } 865 | } 866 | } 867 | } 868 | // Adjust TP only. 869 | if ((PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) && (!DisableBuyOrders)) 870 | { 871 | // Avoid frozen context. In all modification cases. 872 | if ((FreezeLevel != 0) && (MathAbs(PositionGetDouble(POSITION_PRICE_OPEN) - Ask) <= FreezeLevel)) 873 | { 874 | Output("Skipping Modify Buy TP because open price is too close to Ask. FreezeLevel = " + DoubleToString(FreezeLevel, _Digits) + " OpenPrice = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), 8) + " Ask = " + DoubleToString(Ask, _Digits)); 875 | } 876 | else if ((MathAbs(PositionGetDouble(POSITION_TP) - UpperTP) > _Point / 2) && (UpperTP != 0)) 877 | { 878 | if (!Trade.PositionModify(_Symbol, PositionGetDouble(POSITION_SL), UpperTP)) 879 | { 880 | last_error = GetLastError(); 881 | Output("Error Modifying Buy TP: " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 882 | Output("FROM: Entry = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), _Digits) + " TP = " + DoubleToString(PositionGetDouble(POSITION_TP), _Digits) + " -> TO: Entry = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), 8) + " TP = " + DoubleToString(UpperTP, 8) + " Ask = " + DoubleToString(Ask, _Digits)); 883 | } 884 | } 885 | } 886 | else if ((PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) && (!DisableSellOrders)) 887 | { 888 | // PostEntrySLAdjustment - a procedure to correct SL if breakout candle become too long and no longer qualifies for SL rule. 889 | if ((PositionGetInteger(POSITION_TIME) > Time[1]) && (PositionGetInteger(POSITION_TIME) < Time[0]) && (PostEntrySLAdjustment) && (PostSellSLAdjustmentDone == false)) 890 | { 891 | double SL = AdjustPostSellSL(); 892 | if (SL != -1) 893 | { 894 | // Avoid frozen context. In all modification cases. 895 | if ((FreezeLevel != 0) && (MathAbs(Bid - PositionGetDouble(POSITION_PRICE_OPEN)) <= FreezeLevel)) 896 | { 897 | Output("Skipping Modify Sell Stop SL because open price is too close to Bid. FreezeLevel = " + DoubleToString(FreezeLevel, _Digits) + " OpenPrice = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), 8) + " Bid = " + DoubleToString(Bid, _Digits)); 898 | } 899 | else 900 | { 901 | if (NormalizeDouble(SL, _Digits) == NormalizeDouble(PositionGetDouble(POSITION_SL), _Digits)) PostSellSLAdjustmentDone = true; 902 | else 903 | { 904 | if (!Trade.PositionModify(_Symbol, SL, PositionGetDouble(POSITION_TP))) 905 | { 906 | last_error = GetLastError(); 907 | Output("Error Modifying Sell SL: " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 908 | Output("FROM: Entry = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), _Digits) + " SL = " + DoubleToString(PositionGetDouble(POSITION_SL), _Digits) + " -> TO: Entry = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), 8) + " SL = " + DoubleToString(SL, 8) + " Bid = " + DoubleToString(Bid, _Digits)); 909 | } 910 | else PostSellSLAdjustmentDone = true; 911 | } 912 | } 913 | } 914 | } 915 | // Avoid frozen context. In all modification cases. 916 | if ((FreezeLevel != 0) && (MathAbs(Bid - PositionGetDouble(POSITION_PRICE_OPEN)) <= FreezeLevel)) 917 | { 918 | Output("Skipping Modify Sell TP because open price is too close to Bid. FreezeLevel = " + DoubleToString(FreezeLevel, _Digits) + " OpenPrice = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), 8) + " Bid = " + DoubleToString(Bid, _Digits)); 919 | } 920 | else if ((MathAbs(PositionGetDouble(POSITION_TP) - LowerTP) > _Point / 2) && (NormalizeDouble(LowerTP, _Digits) != 0)) 921 | { 922 | if (!Trade.PositionModify(_Symbol, PositionGetDouble(POSITION_SL), LowerTP)) 923 | { 924 | last_error = GetLastError(); 925 | Output("Error Modifying Sell TP: " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 926 | Output("FROM: Entry = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), _Digits) + " TP = " + DoubleToString(PositionGetDouble(POSITION_TP), _Digits) + " -> TO: Entry = " + DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), 8) + " TP = " + DoubleToString(LowerTP, 8) + " Bid = " + DoubleToString(Bid, _Digits)); 927 | } 928 | } 929 | } 930 | } 931 | 932 | for (int i = 0; i < OrdersTotal(); i++) 933 | { 934 | ulong ticket = OrderGetTicket(i); 935 | // Refresh rates. 936 | Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); 937 | Bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); 938 | // BUY. 939 | if (((OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY_STOP) || (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY_LIMIT)) && (OrderGetString(ORDER_SYMBOL) == _Symbol) && (OrderGetInteger(ORDER_MAGIC) == Magic) && (!DisableBuyOrders)) 940 | { 941 | // Current price is below Sell entry - pending Sell Limit will be used instead of two stop orders. 942 | if ((LowerEntry - Bid > StopLevel) && (UseLower)) continue; 943 | 944 | NewVolume = GetPositionSize(UpperEntry, UpperSL, ORDER_TYPE_BUY); 945 | // Delete existing pending order 946 | if ((HaveBuy) || ((HaveSell) && (OneCancelsOther)) || (!UseUpper)) Trade.OrderDelete(ticket); 947 | // If volume needs to be updated - delete and recreate order with new volume. Also check if EA will be able to create new pending order at current price. 948 | else if ((UpdatePendingVolume) && (MathAbs(OrderGetDouble(ORDER_VOLUME_CURRENT) - NewVolume) > LotStep / 2)) 949 | { 950 | if ((UpperEntry - Ask > StopLevel) || (Ask - UpperEntry > StopLevel)) // Order can be re-created 951 | { 952 | Trade.OrderDelete(ticket); 953 | } 954 | else continue; 955 | // Ask could change after deletion, check if there is still no error 130 present. 956 | Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); 957 | if (UpperEntry - Ask > StopLevel) // Current price below entry 958 | { 959 | order_type = ORDER_TYPE_BUY_STOP; 960 | order_type_string = "Stop"; 961 | } 962 | else if (Ask - UpperEntry > StopLevel) // Current price above entry 963 | { 964 | order_type = ORDER_TYPE_BUY_LIMIT; 965 | order_type_string = "Limit"; 966 | } 967 | else continue; 968 | if (ExpirationEnabled) 969 | { 970 | type_time = ORDER_TIME_SPECIFIED; 971 | // Set expiration to the end of the current bar. 972 | expiration = Time[0] + GetSecondsPerBar(); 973 | // 2 minutes seem to be the actual minimum expiration time. 974 | if (expiration - TimeCurrent() < 121) expiration = TimeCurrent() + 121; 975 | } 976 | else 977 | { 978 | expiration = 0; 979 | type_time = ORDER_TIME_GTC; 980 | } 981 | if (!Trade.OrderOpen(_Symbol, order_type, NewVolume, 0, UpperEntry, UpperSL, UpperTP, type_time, expiration, "ChartPatternHelper")) 982 | { 983 | last_error = GetLastError(); 984 | Output("StopLevel = " + DoubleToString(StopLevel, 8)); 985 | Output("FreezeLevel = " + DoubleToString(FreezeLevel, 8)); 986 | Output("Error Recreating Buy " + order_type_string + ": " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 987 | Output("Volume = " + DoubleToString(NewVolume, LotStep_digits) + " Entry = " + DoubleToString(UpperEntry, _Digits) + " SL = " + DoubleToString(UpperSL, _Digits) + " TP = " + DoubleToString(UpperTP, _Digits) + " Bid/Ask = " + DoubleToString(Bid, _Digits) + "/" + DoubleToString(Ask, _Digits) + " Exp: " + TimeToString(expiration, TIME_DATE | TIME_SECONDS)); 988 | } 989 | else 990 | { 991 | UpperTicket = Trade.ResultOrder(); 992 | } 993 | continue; 994 | } 995 | // Otherwise, just update what needs to be updated. 996 | else if ((MathAbs(OrderGetDouble(ORDER_PRICE_OPEN) - UpperEntry) > _Point / 2) || (MathAbs(OrderGetDouble(ORDER_SL) - UpperSL) > _Point / 2) || (MathAbs(OrderGetDouble(ORDER_TP) - UpperTP) > _Point / 2)) 997 | { 998 | // Avoid error 130 based on entry. 999 | if (UpperEntry - Ask > StopLevel) // Current price below entry 1000 | { 1001 | order_type_string = "Stop"; 1002 | } 1003 | else if (Ask - UpperEntry > StopLevel) // Current price above entry 1004 | { 1005 | order_type_string = "Limit"; 1006 | } 1007 | else if (MathAbs(OrderGetDouble(ORDER_PRICE_OPEN) - UpperEntry) > _Point / 2) continue; 1008 | // Avoid error 130 based on stop-loss. 1009 | if (UpperEntry - UpperSL <= StopLevel) 1010 | { 1011 | Output("Skipping Modify Buy " + order_type_string + " because stop-loss is too close to entry. StopLevel = " + DoubleToString(StopLevel, _Digits) + " Entry = " + DoubleToString(UpperEntry, _Digits) + " SL = " + DoubleToString(UpperSL, _Digits)); 1012 | continue; 1013 | } 1014 | // Avoid frozen context. In all modification cases. 1015 | if ((FreezeLevel != 0) && (MathAbs(OrderGetDouble(ORDER_PRICE_OPEN) - Ask) <= FreezeLevel)) 1016 | { 1017 | Output("Skipping Modify Buy " + order_type_string + " because open price is too close to Ask. FreezeLevel = " + DoubleToString(FreezeLevel, _Digits) + " OpenPrice = " + DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN), _Digits) + " Ask = " + DoubleToString(Ask, _Digits)); 1018 | continue; 1019 | } 1020 | double prevOrderOpenPrice = OrderGetDouble(ORDER_PRICE_OPEN); 1021 | double prevOrderStopLoss = OrderGetDouble(ORDER_SL); 1022 | double prevOrderTakeProfit = OrderGetDouble(ORDER_TP); 1023 | type_time = (ENUM_ORDER_TYPE_TIME)OrderGetInteger(ORDER_TYPE_TIME); 1024 | expiration = (datetime)OrderGetInteger(ORDER_TIME_EXPIRATION); 1025 | if (expiration == TimeCurrent()) continue; // Skip modification of orders that are about to expire 1026 | if (!Trade.OrderModify(ticket, UpperEntry, UpperSL, UpperTP, type_time, expiration)) 1027 | { 1028 | last_error = GetLastError(); 1029 | Output("type_time = " + EnumToString(type_time)); 1030 | Output("StopLevel = " + DoubleToString(StopLevel, 8)); 1031 | Output("FreezeLevel = " + DoubleToString(FreezeLevel, 8)); 1032 | Output("Error Modifying Buy " + order_type_string + ": " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 1033 | Output("FROM: Entry = " + DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN), _Digits) + " SL = " + DoubleToString(OrderGetDouble(ORDER_SL), _Digits) + " TP = " + DoubleToString(OrderGetDouble(ORDER_TP), _Digits) + " -> TO: Entry = " + DoubleToString(UpperEntry, 8) + " SL = " + DoubleToString(UpperSL, 8) + " TP = " + DoubleToString(UpperTP, 8) + " Bid/Ask = " + DoubleToString(Bid, _Digits) + "/" + DoubleToString(Ask, _Digits) + " OrderTicket = " + IntegerToString(ticket) + " OrderExpiration = " + TimeToString(OrderGetInteger(ORDER_TIME_EXPIRATION), TIME_DATE | TIME_SECONDS) + " -> " + TimeToString(expiration, TIME_DATE | TIME_SECONDS)); 1034 | } 1035 | } 1036 | } 1037 | // SELL. 1038 | else if (((OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL_STOP) || (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY_LIMIT)) && (OrderGetString(ORDER_SYMBOL) == _Symbol) && (OrderGetInteger(ORDER_MAGIC) == Magic) && (!DisableSellOrders)) 1039 | { 1040 | // Current price is above Buy entry - pending Buy Limit will be used instead of two stop orders. 1041 | if ((Ask - UpperEntry > StopLevel) && (UseUpper)) continue; 1042 | 1043 | NewVolume = GetPositionSize(LowerEntry, LowerSL, ORDER_TYPE_BUY); 1044 | // Delete existing pending order. 1045 | if (((HaveBuy) && (OneCancelsOther)) || (HaveSell) || (!UseLower)) Trade.OrderDelete(ticket); 1046 | // If volume needs to be updated - delete and recreate order with new volume. Also check if EA will be able to create new pending order at current price. 1047 | else if ((UpdatePendingVolume) && (MathAbs(OrderGetDouble(ORDER_VOLUME_CURRENT) - NewVolume) > LotStep / 2) && (Bid - LowerEntry > StopLevel)) 1048 | { 1049 | if ((Bid - LowerEntry > StopLevel) || (LowerEntry - Bid > StopLevel)) // Order can be re-created 1050 | { 1051 | Trade.OrderDelete(ticket); 1052 | } 1053 | // Bid could change after deletion, check if there is still no error 130 present. 1054 | Bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); 1055 | if (Bid - LowerEntry > StopLevel) // Current price above entry. 1056 | { 1057 | order_type = ORDER_TYPE_SELL_STOP; 1058 | order_type_string = "Stop"; 1059 | } 1060 | else if (LowerEntry - Bid > StopLevel) // Current price below entry. 1061 | { 1062 | order_type = ORDER_TYPE_SELL_LIMIT; 1063 | order_type_string = "Limit"; 1064 | } 1065 | else continue; 1066 | if (ExpirationEnabled) 1067 | { 1068 | type_time = ORDER_TIME_SPECIFIED; 1069 | // Set expiration to the end of the current bar. 1070 | expiration = Time[0] + GetSecondsPerBar(); 1071 | // 2 minutes seem to be the actual minimum expiration time. 1072 | if (expiration - TimeCurrent() < 121) expiration = TimeCurrent() + 121; 1073 | } 1074 | else 1075 | { 1076 | expiration = 0; 1077 | type_time = ORDER_TIME_GTC; 1078 | } 1079 | if (!Trade.OrderOpen(_Symbol, order_type, NewVolume, 0, LowerEntry, LowerSL, LowerTP, type_time, expiration, "ChartPatternHelper")) 1080 | { 1081 | last_error = GetLastError(); 1082 | Output("StopLevel = " + DoubleToString(StopLevel, 8)); 1083 | Output("FreezeLevel = " + DoubleToString(FreezeLevel, 8)); 1084 | Output("Error Recreating Sell " + order_type_string + ": " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 1085 | Output("Volume = " + DoubleToString(NewVolume, LotStep_digits) + " Entry = " + DoubleToString(LowerEntry, _Digits) + " SL = " + DoubleToString(LowerSL, _Digits) + " TP = " + DoubleToString(LowerTP, _Digits) + " Bid/Ask = " + DoubleToString(Bid, _Digits) + "/" + DoubleToString(Ask, _Digits) + " Exp: " + TimeToString(expiration, TIME_DATE | TIME_SECONDS)); 1086 | } 1087 | else 1088 | { 1089 | LowerTicket = Trade.ResultOrder(); 1090 | } 1091 | continue; 1092 | } 1093 | // Otherwise, just update what needs to be updated 1094 | else if ((MathAbs(OrderGetDouble(ORDER_PRICE_OPEN) - LowerEntry) > _Point / 2) || (MathAbs(OrderGetDouble(ORDER_SL) - LowerSL) > _Point / 2) || (MathAbs(OrderGetDouble(ORDER_TP) - LowerTP) > _Point / 2)) 1095 | { 1096 | // Avoid error 130 based on entry. 1097 | if (Bid - LowerEntry > StopLevel) // Current price above entry 1098 | { 1099 | order_type_string = "Stop"; 1100 | } 1101 | else if (LowerEntry - Bid > StopLevel) // Current price below entry 1102 | { 1103 | order_type_string = "Limit"; 1104 | } 1105 | else if (MathAbs(OrderGetDouble(ORDER_PRICE_OPEN) - LowerEntry) > _Point / 2) continue; 1106 | // Avoid error 130 based on stop-loss. 1107 | if (LowerSL - LowerEntry <= StopLevel) 1108 | { 1109 | Output("Skipping Modify Sell " + order_type_string + " because stop-loss is too close to entry. StopLevel = " + DoubleToString(StopLevel, _Digits) + " Entry = " + DoubleToString(LowerEntry, _Digits) + " SL = " + DoubleToString(LowerSL, _Digits)); 1110 | continue; 1111 | } 1112 | // Avoid frozen context. In all modification cases. 1113 | if ((FreezeLevel != 0) && (MathAbs(Bid - OrderGetDouble(ORDER_PRICE_OPEN)) <= FreezeLevel)) 1114 | { 1115 | Output("Skipping Modify Sell " + order_type_string + " because open price is too close to Bid. FreezeLevel = " + DoubleToString(FreezeLevel, _Digits) + " OpenPrice = " + DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN), _Digits) + " Bid = " + DoubleToString(Bid, _Digits)); 1116 | continue; 1117 | } 1118 | double prevOrderOpenPrice = OrderGetDouble(ORDER_PRICE_OPEN); 1119 | double prevOrderStopLoss = OrderGetDouble(ORDER_SL); 1120 | double prevOrderTakeProfit = OrderGetDouble(ORDER_TP); 1121 | type_time = (ENUM_ORDER_TYPE_TIME)OrderGetInteger(ORDER_TYPE_TIME); 1122 | expiration = (datetime)OrderGetInteger(ORDER_TIME_EXPIRATION); 1123 | if (expiration == TimeCurrent()) continue; // Skip modification of orders that are about to expire 1124 | if (!Trade.OrderModify(ticket, LowerEntry, LowerSL, LowerTP, type_time, expiration)) 1125 | { 1126 | last_error = GetLastError(); 1127 | Output("type_time = " + EnumToString(type_time)); 1128 | Output("StopLevel = " + DoubleToString(StopLevel, 8)); 1129 | Output("FreezeLevel = " + DoubleToString(FreezeLevel, 8)); 1130 | Output("Error Modifying Sell " + order_type_string + ": " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 1131 | Output("FROM: Entry = " + DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN), _Digits) + " SL = " + DoubleToString(OrderGetDouble(ORDER_SL), _Digits) + " TP = " + DoubleToString(OrderGetDouble(ORDER_TP), _Digits) + " -> TO: Entry = " + DoubleToString(LowerEntry, 8) + " SL = " + DoubleToString(LowerSL, 8) + " TP = " + DoubleToString(LowerTP, 8) + " Bid/Ask = " + DoubleToString(Bid, _Digits) + "/" + DoubleToString(Ask, _Digits) + " OrderTicket = " + IntegerToString(ticket) + " OrderExpiration = " + TimeToString(OrderGetInteger(ORDER_TIME_EXPIRATION), TIME_DATE | TIME_SECONDS) + " -> " + TimeToString(expiration, TIME_DATE | TIME_SECONDS)); 1132 | } 1133 | } 1134 | } 1135 | } 1136 | 1137 | // BUY. 1138 | // If we do not already have Long position or Long pending order and if we can enter Long 1139 | // and the current price is not below the Sell entry (in that case, only pending Sell Limit order will be used.) 1140 | if ((!HaveBuy) && (!HaveBuyPending) && (UseUpper) && ((LowerEntry - Bid <= StopLevel) || (!UseLower))) 1141 | { 1142 | // Avoid error 130 based on stop-loss. 1143 | if (UpperEntry - UpperSL <= StopLevel) 1144 | { 1145 | Output("Skipping Send Pending Buy because stop-loss is too close to entry. StopLevel = " + DoubleToString(StopLevel, _Digits) + " Entry = " + DoubleToString(UpperEntry, _Digits) + " SL = " + DoubleToString(UpperSL, _Digits)); 1146 | } 1147 | else 1148 | { 1149 | if (UpperEntry - Ask > StopLevel) // Current price below entry. 1150 | { 1151 | order_type = ORDER_TYPE_BUY_STOP; 1152 | order_type_string = "Stop"; 1153 | } 1154 | else if (Ask - UpperEntry > StopLevel) // Current price above entry. 1155 | { 1156 | order_type = ORDER_TYPE_BUY_LIMIT; 1157 | order_type_string = "Limit"; 1158 | } 1159 | else 1160 | { 1161 | order_type = NULL; 1162 | Output("Skipping Send Pending Buy because entry is too close to Ask. StopLevel = " + DoubleToString(StopLevel, _Digits) + " Entry = " + DoubleToString(UpperEntry, _Digits) + " Ask = " + DoubleToString(Ask, _Digits)); 1163 | } 1164 | if (order_type != NULL) 1165 | { 1166 | if (ExpirationEnabled) 1167 | { 1168 | type_time = ORDER_TIME_SPECIFIED; 1169 | // Set expiration to the end of the current bar. 1170 | expiration = Time[0] + GetSecondsPerBar(); 1171 | // 2 minutes seem to be the actual minimum expiration time. 1172 | if (expiration - TimeCurrent() < 121) expiration = TimeCurrent() + 121; 1173 | } 1174 | else 1175 | { 1176 | expiration = 0; 1177 | type_time = ORDER_TIME_GTC; 1178 | } 1179 | NewVolume = GetPositionSize(UpperEntry, UpperSL, ORDER_TYPE_BUY); 1180 | if (!Trade.OrderOpen(_Symbol, order_type, NewVolume, 0, UpperEntry, UpperSL, UpperTP, type_time, expiration, "ChartPatternHelper")) 1181 | { 1182 | last_error = GetLastError(); 1183 | Output("type_time = " + IntegerToString(type_time)); 1184 | Output("StopLevel = " + DoubleToString(StopLevel, 8)); 1185 | Output("FreezeLevel = " + DoubleToString(FreezeLevel, 8)); 1186 | Output("Error Sending Buy " + order_type_string + ": " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 1187 | Output("Volume = " + DoubleToString(NewVolume, LotStep_digits) + " Entry = " + DoubleToString(UpperEntry, _Digits) + " SL = " + DoubleToString(UpperSL, _Digits) + " TP = " + DoubleToString(UpperTP, _Digits) + " Bid/Ask = " + DoubleToString(Bid, _Digits) + "/" + DoubleToString(Ask, _Digits) + " Exp: " + TimeToString(expiration, TIME_DATE | TIME_SECONDS)); 1188 | } 1189 | else 1190 | { 1191 | UpperTicket = Trade.ResultOrder(); 1192 | } 1193 | } 1194 | } 1195 | } 1196 | // SELL. 1197 | // If we do not already have Short position or Short pending order and if we can enter Short 1198 | // and the current price is not above the Buy entry (in that case, only pending Buy Limit order will be used.) 1199 | if ((!HaveSell) && (!HaveSellPending) && (UseLower) && ((Ask - UpperEntry <= StopLevel) || (!UseUpper))) 1200 | { 1201 | // Avoid error 130 based on stop-loss. 1202 | if (LowerSL - LowerEntry <= StopLevel) 1203 | { 1204 | Output("Skipping Send Pending Sell because stop-loss is too close to entry. StopLevel = " + DoubleToString(StopLevel, _Digits) + " Entry = " + DoubleToString(LowerEntry, _Digits) + " SL = " + DoubleToString(LowerSL, _Digits)); 1205 | } 1206 | else 1207 | { 1208 | if (Bid - LowerEntry > StopLevel) // Current price above entry 1209 | { 1210 | order_type = ORDER_TYPE_SELL_STOP; 1211 | order_type_string = "Stop"; 1212 | } 1213 | else if (LowerEntry - Bid > StopLevel) // Current price below entry 1214 | { 1215 | order_type = ORDER_TYPE_SELL_LIMIT; 1216 | order_type_string = "Limit"; 1217 | } 1218 | else 1219 | { 1220 | order_type = NULL; 1221 | Output("Skipping Send Pending Sell because entry is too close to Bid. StopLevel = " + DoubleToString(StopLevel, _Digits) + " Entry = " + DoubleToString(LowerEntry, _Digits) + " Bid = " + DoubleToString(Bid, _Digits)); 1222 | } 1223 | if (order_type != NULL) 1224 | { 1225 | if (ExpirationEnabled) 1226 | { 1227 | type_time = ORDER_TIME_SPECIFIED; 1228 | // Set expiration to the end of the current bar. 1229 | expiration = Time[0] + GetSecondsPerBar(); 1230 | // 2 minutes seem to be the actual minimum expiration time. 1231 | if (expiration - TimeCurrent() < 121) expiration = TimeCurrent() + 121; 1232 | } 1233 | else 1234 | { 1235 | expiration = 0; 1236 | type_time = ORDER_TIME_GTC; 1237 | } 1238 | NewVolume = GetPositionSize(LowerEntry, LowerSL, ORDER_TYPE_SELL); 1239 | if (!Trade.OrderOpen(_Symbol, order_type, NewVolume, 0, LowerEntry, LowerSL, LowerTP, type_time, expiration, "ChartPatternHelper")) 1240 | { 1241 | last_error = GetLastError(); 1242 | Output("type_time = " + IntegerToString(type_time)); 1243 | Output("StopLevel = " + DoubleToString(StopLevel, 8)); 1244 | Output("FreezeLevel = " + DoubleToString(FreezeLevel, 8)); 1245 | Output("Error Sending Sell " + order_type_string + ": " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 1246 | Output("Volume = " + DoubleToString(NewVolume, LotStep_digits) + " Entry = " + DoubleToString(LowerEntry, _Digits) + " SL = " + DoubleToString(LowerSL, _Digits) + " TP = " + DoubleToString(LowerTP, _Digits) + " Bid/Ask = " + DoubleToString(Bid, _Digits) + "/" + DoubleToString(Ask, _Digits) + " Exp: " + TimeToString(expiration, TIME_DATE | TIME_SECONDS)); 1247 | } 1248 | else 1249 | { 1250 | LowerTicket = Trade.ResultOrder(); 1251 | } 1252 | } 1253 | } 1254 | } 1255 | } 1256 | 1257 | void PrepareTimeseries() 1258 | { 1259 | if (CopyTime(_Symbol, _Period, 0, Bars(_Symbol, _Period), Time) != Bars(_Symbol, _Period)) 1260 | { 1261 | Print("Cannot copy Time array."); 1262 | return; 1263 | } 1264 | ArraySetAsSeries(Time, true); 1265 | if (CopyHigh(_Symbol, _Period, 0, Bars(_Symbol, _Period), High) != Bars(_Symbol, _Period)) 1266 | { 1267 | Print("Cannot copy High array."); 1268 | return; 1269 | } 1270 | ArraySetAsSeries(High, true); 1271 | if (CopyLow(_Symbol, _Period, 0, Bars(_Symbol, _Period), Low) != Bars(_Symbol, _Period)) 1272 | { 1273 | Print("Cannot copy Low array."); 1274 | return; 1275 | } 1276 | ArraySetAsSeries(Low, true); 1277 | if (CopyClose(_Symbol, _Period, 0, Bars(_Symbol, _Period), Close) != Bars(_Symbol, _Period)) 1278 | { 1279 | Print("Cannot copy Close array."); 1280 | return; 1281 | } 1282 | ArraySetAsSeries(Close, true); 1283 | } 1284 | 1285 | void SetComment(string c) 1286 | { 1287 | if (!Silent) Comment(c); 1288 | } 1289 | 1290 | //+------------------------------------------------------------------+ 1291 | //| Calculates unit cost based on profit calculation mode. | 1292 | //+------------------------------------------------------------------+ 1293 | double CalculateUnitCost() 1294 | { 1295 | double UnitCost; 1296 | // CFD. 1297 | if (((CalcMode == SYMBOL_CALC_MODE_CFD) || (CalcMode == SYMBOL_CALC_MODE_CFDINDEX) || (CalcMode == SYMBOL_CALC_MODE_CFDLEVERAGE))) 1298 | UnitCost = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_SIZE) * SymbolInfoDouble(Symbol(), SYMBOL_TRADE_CONTRACT_SIZE); 1299 | // With Forex and futures instruments, tick value already equals 1 unit cost. 1300 | else UnitCost = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_VALUE_LOSS); 1301 | 1302 | return UnitCost; 1303 | } 1304 | 1305 | //+-----------------------------------------------------------------------------------+ 1306 | //| Calculates necessary adjustments for cases when GivenCurrency != AccountCurrency. | 1307 | //+-----------------------------------------------------------------------------------+ 1308 | double CalculateAdjustment() 1309 | { 1310 | if (ReferencePair == NULL) 1311 | { 1312 | ReferencePair = GetSymbolByCurrencies(ProfitCurrency, AccountCurrency); 1313 | ReferenceSymbolMode = true; 1314 | // Failed. 1315 | if (ReferencePair == NULL) 1316 | { 1317 | // Reversing currencies. 1318 | ReferencePair = GetSymbolByCurrencies(AccountCurrency, ProfitCurrency); 1319 | ReferenceSymbolMode = false; 1320 | } 1321 | } 1322 | if (ReferencePair == NULL) 1323 | { 1324 | Print("Error! Cannot detect proper currency pair for adjustment calculation: ", ProfitCurrency, ", ", AccountCurrency, "."); 1325 | ReferencePair = Symbol(); 1326 | return 1; 1327 | } 1328 | MqlTick tick; 1329 | SymbolInfoTick(ReferencePair, tick); 1330 | return GetCurrencyCorrectionCoefficient(tick); 1331 | } 1332 | 1333 | //+---------------------------------------------------------------------------+ 1334 | //| Returns a currency pair with specified base currency and profit currency. | 1335 | //+---------------------------------------------------------------------------+ 1336 | string GetSymbolByCurrencies(string base_currency, string profit_currency) 1337 | { 1338 | // Cycle through all symbols. 1339 | for (int s = 0; s < SymbolsTotal(false); s++) 1340 | { 1341 | // Get symbol name by number. 1342 | string symbolname = SymbolName(s, false); 1343 | 1344 | // Skip non-Forex pairs. 1345 | if ((SymbolInfoInteger(symbolname, SYMBOL_TRADE_CALC_MODE) != SYMBOL_CALC_MODE_FOREX) && (SymbolInfoInteger(symbolname, SYMBOL_TRADE_CALC_MODE) != SYMBOL_CALC_MODE_FOREX_NO_LEVERAGE)) continue; 1346 | 1347 | // Get its base currency. 1348 | string b_cur = SymbolInfoString(symbolname, SYMBOL_CURRENCY_BASE); 1349 | if (b_cur == "RUR") b_cur = "RUB"; 1350 | 1351 | // Get its profit currency. 1352 | string p_cur = SymbolInfoString(symbolname, SYMBOL_CURRENCY_PROFIT); 1353 | if (p_cur == "RUR") p_cur = "RUB"; 1354 | 1355 | // If the currency pair matches both currencies, select it in Market Watch and return its name. 1356 | if ((b_cur == base_currency) && (p_cur == profit_currency)) 1357 | { 1358 | // Select if necessary. 1359 | if (!(bool)SymbolInfoInteger(symbolname, SYMBOL_SELECT)) SymbolSelect(symbolname, true); 1360 | 1361 | return symbolname; 1362 | } 1363 | } 1364 | return NULL; 1365 | } 1366 | 1367 | //+------------------------------------------------------------------+ 1368 | //| Get correction coefficient based on currency, trade direction, | 1369 | //| and current prices. | 1370 | //+------------------------------------------------------------------+ 1371 | double GetCurrencyCorrectionCoefficient(MqlTick &tick) 1372 | { 1373 | if ((tick.ask == 0) || (tick.bid == 0)) return -1; // Data is not yet ready. 1374 | // Reverse quote. 1375 | if (ReferenceSymbolMode) 1376 | { 1377 | // Using Buy price for reverse quote. 1378 | return tick.ask; 1379 | } 1380 | // Direct quote. 1381 | else 1382 | { 1383 | // Using Sell price for direct quote. 1384 | return (1 / tick.bid); 1385 | } 1386 | } 1387 | 1388 | // Taken from the PositionSizeCalculator indicator. 1389 | double GetPositionSize(double Entry, double StopLoss, ENUM_ORDER_TYPE dir) 1390 | { 1391 | double Size, RiskMoney, PositionSize = 0; 1392 | 1393 | double SL = MathAbs(Entry - StopLoss); 1394 | 1395 | AccountCurrency = AccountInfoString(ACCOUNT_CURRENCY); 1396 | 1397 | // A rough patch for cases when account currency is set as RUR instead of RUB. 1398 | if (AccountCurrency == "RUR") AccountCurrency = "RUB"; 1399 | 1400 | ProfitCurrency = SymbolInfoString(Symbol(), SYMBOL_CURRENCY_PROFIT); 1401 | if (ProfitCurrency == "RUR") ProfitCurrency = "RUB"; 1402 | BaseCurrency = SymbolInfoString(Symbol(), SYMBOL_CURRENCY_BASE); 1403 | if (BaseCurrency == "RUR") BaseCurrency = "RUB"; 1404 | CalcMode = (ENUM_SYMBOL_CALC_MODE)SymbolInfoInteger(Symbol(), SYMBOL_TRADE_CALC_MODE); 1405 | double LotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); 1406 | int LotStep_digits = CountDecimalPlaces(LotStep); 1407 | 1408 | if (!CalculatePositionSize) return(FixedPositionSize); 1409 | 1410 | // If could not find account currency, probably not connected. 1411 | if (AccountInfoString(ACCOUNT_CURRENCY) == "") return -1; 1412 | 1413 | if (FixedBalance > 0) 1414 | { 1415 | Size = FixedBalance; 1416 | } 1417 | else if (UseEquityInsteadOfBalance) 1418 | { 1419 | Size = AccountInfoDouble(ACCOUNT_EQUITY); 1420 | } 1421 | else 1422 | { 1423 | Size = AccountInfoDouble(ACCOUNT_BALANCE); 1424 | } 1425 | 1426 | if (!UseMoneyInsteadOfPercentage) RiskMoney = Size * Risk / 100; 1427 | else RiskMoney = MoneyRisk; 1428 | 1429 | double UnitCost = CalculateUnitCost(); 1430 | 1431 | // If profit currency is different from account currency and Symbol is not a Forex pair or futures (CFD, and so on). 1432 | if ((ProfitCurrency != AccountCurrency) && (CalcMode != SYMBOL_CALC_MODE_FOREX) && (CalcMode != SYMBOL_CALC_MODE_FOREX_NO_LEVERAGE) && (CalcMode != SYMBOL_CALC_MODE_FUTURES) && (CalcMode != SYMBOL_CALC_MODE_EXCH_FUTURES) && (CalcMode != SYMBOL_CALC_MODE_EXCH_FUTURES_FORTS)) 1433 | { 1434 | double CCC = CalculateAdjustment(); // Valid only for loss calculation. 1435 | // Adjust the unit cost. 1436 | UnitCost *= CCC; 1437 | } 1438 | 1439 | // If account currency == pair's base currency, adjust UnitCost to future rate (SL). Works only for Forex pairs. 1440 | if ((AccountCurrency == BaseCurrency) && ((CalcMode == SYMBOL_CALC_MODE_FOREX) || (CalcMode == SYMBOL_CALC_MODE_FOREX_NO_LEVERAGE))) 1441 | { 1442 | double current_rate = 1, future_rate = StopLoss; 1443 | if (dir == ORDER_TYPE_BUY) 1444 | { 1445 | current_rate = SymbolInfoDouble(_Symbol, SYMBOL_ASK); 1446 | } 1447 | else if (dir == ORDER_TYPE_SELL) 1448 | { 1449 | current_rate = SymbolInfoDouble(_Symbol, SYMBOL_BID); 1450 | } 1451 | UnitCost *= (current_rate / future_rate); 1452 | } 1453 | 1454 | double TickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); 1455 | 1456 | if ((SL != 0) && (UnitCost != 0) && (TickSize != 0)) PositionSize = NormalizeDouble(RiskMoney / (SL * UnitCost / TickSize), LotStep_digits); 1457 | 1458 | if (PositionSize < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN)) PositionSize = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); 1459 | else if (PositionSize > SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX)) PositionSize = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); 1460 | double steps = PositionSize / SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); 1461 | if (MathFloor(steps) < steps) PositionSize = MathFloor(steps) * SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); 1462 | 1463 | return PositionSize; 1464 | } 1465 | 1466 | // Prints and writes to a file error info and context data. 1467 | void Output(string s) 1468 | { 1469 | Print(s); 1470 | if (!ErrorLogging) return; 1471 | int file = FileOpen(filename, FILE_CSV | FILE_READ | FILE_WRITE); 1472 | if (file == INVALID_HANDLE) Print("Failed to create an error log file: ", GetLastError(), "."); 1473 | else 1474 | { 1475 | FileSeek(file, 0, SEEK_END); 1476 | s = TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS) + " - " + s; 1477 | FileWrite(file, s); 1478 | FileClose(file); 1479 | } 1480 | } 1481 | 1482 | // Taken from the PriceChangeCounter indicator. 1483 | int GetDaysInMonth(MqlDateTime &dt_struct) 1484 | { 1485 | int month = dt_struct.mon; 1486 | int year = dt_struct.year; 1487 | 1488 | if (month == 1) return 31; 1489 | else if (month == 2) 1490 | { 1491 | // February - leap years 1492 | if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) return 29; 1493 | else return 28; 1494 | } 1495 | else if (month == 3) return 31; 1496 | else if (month == 4) return 30; 1497 | else if (month == 5) return 31; 1498 | else if (month == 6) return 30; 1499 | else if (month == 7) return 31; 1500 | else if (month == 8) return 31; 1501 | else if (month == 9) return 30; 1502 | else if (month == 10) return 31; 1503 | else if (month == 11) return 30; 1504 | else if (month == 12) return 31; 1505 | 1506 | return -1; 1507 | } 1508 | 1509 | int GetSecondsPerBar() 1510 | { 1511 | // If timeframe < MN - return already calculated value. 1512 | if (Period() != PERIOD_MN1) return SecondsPerBar; 1513 | // Otherwise, call functions to calculate number of days in current month. 1514 | MqlDateTime dt_struct; 1515 | TimeToStruct(Time[0], dt_struct); 1516 | int days = GetDaysInMonth(dt_struct); 1517 | if (days == -1) Alert("Could not detect number of days in a month."); 1518 | return (days * 86400); 1519 | } 1520 | 1521 | // Runs only one time to adjust SL to appropriate bar's Low if breakout bar's part outside the pattern turned out to be longer than the one inside. 1522 | // Works only if PostEntrySLAdjustment = true. 1523 | double AdjustPostBuySL() 1524 | { 1525 | double SL = -1; 1526 | string smagic = IntegerToString(Magic); 1527 | double Border; 1528 | 1529 | // Border. 1530 | if (ObjectFind(0, UpperBorderLine + smagic) > -1) 1531 | { 1532 | if ((ObjectGetInteger(0, UpperBorderLine + smagic, OBJPROP_TYPE) != OBJ_HLINE) && (ObjectGetInteger(0, UpperBorderLine + smagic, OBJPROP_TYPE) != OBJ_TREND)) return SL; 1533 | // Starting from 1 because it is new bar after breakout bar. 1534 | for (int i = 1; i < Bars(_Symbol, _Period); i++) 1535 | { 1536 | if (ObjectGetInteger(0, UpperBorderLine + smagic, OBJPROP_TYPE) != OBJ_HLINE) Border = ObjectGetValueByTime(0, UpperBorderLine + smagic, Time[i], 0); 1537 | else Border = ObjectGetDouble(0, UpperBorderLine + smagic, OBJPROP_PRICE, 0); // Horizontal line value. 1538 | // Major part inside pattern but and SL not closer than breakout bar's SL. 1539 | if ((Border - Low[i] > High[i] - Border) && (Low[i] <= Low[1])) return NormalizeDouble(Low[i], _Digits); 1540 | } 1541 | } 1542 | else // Try to find a channel. 1543 | { 1544 | if (ObjectFind(0, BorderChannel + smagic) > -1) 1545 | { 1546 | if (ObjectGetInteger(0, BorderChannel + smagic, OBJPROP_TYPE) != OBJ_CHANNEL) return SL; 1547 | for (int i = 1; i < Bars(_Symbol, _Period); i++) 1548 | { 1549 | // Get the upper of main and auxiliary lines. 1550 | Border = MathMax(ObjectGetValueByTime(0, BorderChannel + smagic, Time[i], 0), ObjectGetValueByTime(0, BorderChannel + smagic, Time[i], 1)); 1551 | // Major part inside pattern but and SL not closer than breakout bar's SL. 1552 | if ((Border - Low[i] > High[i] - Border) && (Low[i] <= Low[0])) return NormalizeDouble(Low[i], _Digits); 1553 | } 1554 | } 1555 | } 1556 | return SL; 1557 | } 1558 | 1559 | // Runs only one time to adjust SL to appropriate bar's High if breakout bar's part outside the pattern turned out to be longer than the one inside. 1560 | // Works only if PostEntrySLAdjustment = true. 1561 | double AdjustPostSellSL() 1562 | { 1563 | double SL = -1; 1564 | string smagic = IntegerToString(Magic); 1565 | double Border; 1566 | 1567 | // Border. 1568 | if (ObjectFind(0, LowerBorderLine + smagic) > -1) 1569 | { 1570 | if ((ObjectGetInteger(0, LowerBorderLine + smagic, OBJPROP_TYPE) != OBJ_HLINE) && (ObjectGetInteger(0, LowerBorderLine + smagic, OBJPROP_TYPE) != OBJ_TREND)) return SL; 1571 | // Starting from 1 because it is new bar after breakout bar. 1572 | for (int i = 1; i < Bars(_Symbol, _Period); i++) 1573 | { 1574 | if (ObjectGetInteger(0, LowerBorderLine + smagic, OBJPROP_TYPE) != OBJ_HLINE) Border = ObjectGetValueByTime(0, LowerBorderLine + smagic, Time[i], 0); 1575 | else Border = ObjectGetDouble(0, LowerBorderLine + smagic, OBJPROP_PRICE, 0); // Horizontal line value. 1576 | // Major part inside pattern but and SL not closer than breakout bar's SL. 1577 | if ((High[i] - Border > Border - Low[i]) && (High[i] >= High[0])) return NormalizeDouble(High[i], _Digits); 1578 | } 1579 | } 1580 | else // Try to find a channel. 1581 | { 1582 | if (ObjectFind(0, BorderChannel + smagic) > -1) 1583 | { 1584 | if (ObjectGetInteger(0, BorderChannel + smagic, OBJPROP_TYPE) != OBJ_CHANNEL) return SL; 1585 | for (int i = 1; i < Bars(_Symbol, _Period); i++) 1586 | { 1587 | // Get the lower of main and auxiliary lines. 1588 | Border = MathMin(ObjectGetValueByTime(0, BorderChannel + smagic, Time[i], 0), ObjectGetValueByTime(0, BorderChannel + smagic, Time[i], 1)); 1589 | // Major part inside pattern but and SL not closer than breakout bar's SL. 1590 | if ((High[i] - Border > Border - Low[i]) && (High[i] >= High[0])) return NormalizeDouble(High[i], _Digits); 1591 | } 1592 | } 1593 | } 1594 | return SL; 1595 | } 1596 | 1597 | //+------------------------------------------------------------------+ 1598 | //| Counts decimal places. | 1599 | //+------------------------------------------------------------------+ 1600 | int CountDecimalPlaces(double number) 1601 | { 1602 | // 100 as maximum length of number. 1603 | for (int i = 0; i < 100; i++) 1604 | { 1605 | double pwr = MathPow(10, i); 1606 | if (MathRound(number * pwr) / pwr == number) return i; 1607 | } 1608 | return -1; 1609 | } 1610 | 1611 | //+------------------------------------------------------------------+ 1612 | //| Execute a markte order (depends on symbol's trade execution mode.| 1613 | //+------------------------------------------------------------------+ 1614 | ulong ExecuteMarketOrder(const ENUM_ORDER_TYPE order_type, const double volume, const double price, const double sl, const double tp) 1615 | { 1616 | double order_sl = sl; 1617 | double order_tp = tp; 1618 | 1619 | double StopLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * _Point; 1620 | double FreezeLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL) * _Point; 1621 | double LotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); 1622 | int LotStep_digits = CountDecimalPlaces(LotStep); 1623 | 1624 | ENUM_SYMBOL_TRADE_EXECUTION Execution_Mode = (ENUM_SYMBOL_TRADE_EXECUTION)SymbolInfoInteger(Symbol(), SYMBOL_TRADE_EXEMODE); 1625 | 1626 | // Market execution mode - preparation. 1627 | if (Execution_Mode == SYMBOL_TRADE_EXECUTION_MARKET) 1628 | { 1629 | // No SL/TP allowed on instant orders. 1630 | order_sl = 0; 1631 | order_tp = 0; 1632 | } 1633 | 1634 | if (!Trade.PositionOpen(Symbol(), order_type, volume, price, order_sl, order_tp, "Chart Pattern Helper")) 1635 | { 1636 | Output("Error sending order: " + Trade.ResultRetcodeDescription() + "."); 1637 | } 1638 | else 1639 | { 1640 | MqlTradeResult result; 1641 | Trade.Result(result); 1642 | if ((Trade.ResultRetcode() != 10008) && (Trade.ResultRetcode() != 10009) && (Trade.ResultRetcode() != 10010)) 1643 | { 1644 | int last_error = GetLastError(); 1645 | Output("StopLevel = " + DoubleToString(StopLevel, 8)); 1646 | Output("FreezeLevel = " + DoubleToString(FreezeLevel, 8)); 1647 | Output("Error Sending Order " + EnumToString(order_type) + ": " + IntegerToString(last_error) + " (" + Trade.ResultRetcodeDescription() + ")"); 1648 | Output("Volume = " + DoubleToString(volume, LotStep_digits) + " Entry = " + DoubleToString(price, _Digits) + " SL = " + DoubleToString(order_sl, _Digits) + " TP = " + DoubleToString(order_tp, _Digits)); 1649 | return 0; 1650 | } 1651 | 1652 | Output("Initial return code: " + Trade.ResultRetcodeDescription()); 1653 | 1654 | ulong order = result.order; 1655 | Output("Order ID: " + IntegerToString(order)); 1656 | 1657 | ulong deal = result.deal; 1658 | Output("Deal ID: " + IntegerToString(deal)); 1659 | 1660 | // Market execution mode - application of SL/TP. 1661 | if (Execution_Mode == SYMBOL_TRADE_EXECUTION_MARKET) 1662 | { 1663 | // Not all brokers return deal. 1664 | if (deal != 0) 1665 | { 1666 | if (HistorySelect(TimeCurrent() - 60, TimeCurrent())) 1667 | { 1668 | if (HistoryDealSelect(deal)) 1669 | { 1670 | long position = HistoryDealGetInteger(deal, DEAL_POSITION_ID); 1671 | Output("Position ID: " + IntegerToString(position)); 1672 | 1673 | if (!Trade.PositionModify(position, sl, tp)) 1674 | { 1675 | Output("Error modifying position: " + IntegerToString(GetLastError())); 1676 | } 1677 | else 1678 | { 1679 | Output("SL/TP applied successfully."); 1680 | return deal; 1681 | } 1682 | } 1683 | else 1684 | { 1685 | Output("Error selecting deal: " + IntegerToString(GetLastError())); 1686 | } 1687 | } 1688 | else 1689 | { 1690 | Output("Error selecting deal history: " + IntegerToString(GetLastError())); 1691 | } 1692 | } 1693 | // Wait for position to open then find it using the order ID. 1694 | else 1695 | { 1696 | // Run a waiting cycle until the order becomes a positoin. 1697 | for (int i = 0; i < 10; i++) 1698 | { 1699 | Output("Waiting..."); 1700 | Sleep(1000); 1701 | if (PositionSelectByTicket(order)) break; 1702 | } 1703 | if (!PositionSelectByTicket(order)) 1704 | { 1705 | Output("Error selecting position: " + IntegerToString(GetLastError())); 1706 | } 1707 | else 1708 | { 1709 | if (!Trade.PositionModify(order, sl, tp)) 1710 | { 1711 | Output("Error modifying position: " + IntegerToString(GetLastError())); 1712 | } 1713 | else 1714 | { 1715 | Output("SL/TP applied successfully."); 1716 | return order; 1717 | } 1718 | } 1719 | } 1720 | } 1721 | if (deal != 0) return deal; 1722 | else return order; 1723 | } 1724 | return 0; 1725 | } 1726 | //+------------------------------------------------------------------+ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Chart Pattern Helper 2 | 3 | **Warning! This expert advisor doesn't trade in a fully automatic mode! It only trades based on the chart patterns you draw on the chart.** 4 | 5 | Chart Pattern Helper is a custom MT4/MT5 expert advisor coded by EarnForex.com. Its main purpose is to create and manage trading orders based on chart patterns (mainly channels) drawn by a trader. It is only capable of trading breakout setups, not pullbacks. 6 | 7 | Chart objects have to be properly named for the Chart Pattern Helper EA to work. Please read the EA's and its input parameters' descriptions carefully before employing it on a live account. 8 | 9 | ![Chart Pattern Helper set up to trade a breakout from a long-term Bitcoin chart based on a symmetrical triangle in MetaTrader 5 platform](https://github.com/EarnForex/Chart-Pattern-Helper/blob/main/README_Images/chart-pattern-helper-ea-symmetrical-triangle-setup.png) 10 | 11 | More information about this custom MetaTrader expert advisor is available here: https://www.earnforex.com/metatrader-expert-advisors/ChartPatternHelper/ 12 | 13 | Any contributions to the code are welcome! 14 | -------------------------------------------------------------------------------- /README_Images/chart-pattern-helper-ea-symmetrical-triangle-setup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EarnForex/Chart-Pattern-Helper/bdf1cb0df2c33e7c21cdaf997e6d78e1ca7281d1/README_Images/chart-pattern-helper-ea-symmetrical-triangle-setup.png --------------------------------------------------------------------------------