ea_price_action_v2(1).mq4
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «ea_price_action_v2(1).mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Данный продукт представляет собой экспертный советник (Expert Advisor) для платформы MetaTrader, предназначенный для автоматического управления торговыми операциями на рынке форекс. Код написан на языке MQL4/MQL5 и реализует систему управления ордерами с возможностью открытия и закрытия позиций по заданным ценовым параметрам.
Советник поддерживает гибкую настройку объёмов сделок: возможен расчёт лотов по фиксированному значению или с использованием множителя, увеличивающего размер позиции при нарастании торгового уровня. Доступны параметры стоп-лосса, тейк-профита и ценового расстояния для фильтрации входа в сделку, а также ограничение по времени торговой сессии.
Для управления рисками продукт включает фильтр новостной активности, позволяющий приостанавливать торговлю вокруг важных экономических событий, а также ежедневные ограничения по прибыли и убыткам. Реализованы функции защитных механизмов: перевод стоп-лосса в безубыток и скользящий стоп-лосс с настраиваемыми шагами.
Советник отображает на графике информацию об аккаунте: баланс, эквивалент, спред, название сервера и текущую прибыль или убыток. Также доступна отрисовка линий временных отметок новостного календаря на графике.
Настройки программы
| Настройка | Описание |
|---|---|
| SimpleForexTeam__ | Текстовый параметр, содержащий информацию о команде разработчика. |
| EA_Name | Имя экспертного советника, отображаемое в интерфейсе. |
| Use_TradeAgain | Описание параметра повторной торговли. |
| TradeAgain | Если включено, советник продолжит торговлю повторно после завершения цикла; если отключено — остановится. |
| Use_Loop | Описание параметра количества торговых циклов. |
| Loop | Максимальное количество торговых циклов (лап), которое советник может выполнить за сессию. |
| StartTrade | Час начала торговой сессии (в часах UTC), начиная с которого разрешено открытие сделок. |
| EndTrade | Час завершения торговой сессии (в часах UTC) в течение которых допускается открытие сделок. |
| Use_DbLots | Описание режима выбора метода расчёта лотов. |
| DbLots | Режим расчёта лотов: 1 — с использованием множителя, 2 — фиксированный объём. |
| Lots | Базовый размер лота для открытия позиции. |
| SL | Значение стоп-лосса в пунктах для открытой позиции. |
| TP | Значение тейк-профита в пунктах для открытой позиции. |
| Distance | Ценовое расстояние в пунктах для фильтрации входа в сделку. |
| Multiplier | Множитель, используемый для увеличения размера лота при каждом новом торговом уровне. |
| MaxLevel | Максимальное количество торговых уровней (лап), до которого допускается наращивание позиции. |
| LotsDecimal | Количество знаков после запятой для отображения размера лота. |
| MagicNumber | Уникальный магический номер для идентификации позиций, открытых данным советником. |
| EA_Comment | Текстовый комментарий, присваиваемый каждой открытой торговой позиции. |
| MoneyPerLot | Сумма в долларах на один лот, используемая для расчёта рибейта. |
| TNewsFilter | Заголовок раздела настроек фильтра новостей. |
| newsOn | Включает или отключает фильтр новостной активности для приостановки торговли. |
| NewsLight | Включает отображение и учёт новостей с низким уровнем влияния. |
| NewsMedium | Включает отображение и учёт новостей со средним уровнем влияния. |
| NewsHard | Включает отображение и учёт новостей с высоким уровнем влияния. |
| offset | Часовой пояс в формате GMT для корректного отображения времени новостей. |
| NewsSymb | Список валютных пар для отображения новостей через запятую. Если пусто — отображаются только текущие символы. |
| DrawLines | Включает или отключает отрисовку вертикальных линий новостного времени на графике. |
| Next | Если включено, на графике отображаются только будущие линии новостного времени. |
| Tlimits | Заголовок раздела настроек ежедневных лимитов. |
| uDailyProfitOn | Включает или отключает ежедневный лимит прибыли. |
| limitProfitMode | Режим контроля ежедневной прибыли: по денежной сумме или по проценту от баланса аккаунта. |
| uDayLimitProfit | Максимальное допустимое ежедневное значение прибыли в долларах или процентах в зависимости от режима. |
| uDailyLossOn | Включает или отключает ежедневный лимит убытка. |
| limitLossMode | Режим контроля ежедневного убытка: по денежной сумме или по проценту от баланса аккаунта. |
| uDayLimitLoss | Максимальное допустимое ежедневное значение убытка в долларах или процентах в зависимости от режима. |
| uConsiderFloatting | Если включено, при расчёте ежедневных лимитов учитывается плавающий доход/убыток открытых позиций. |
| TtpOptions | Заголовок раздела настроек закрытия всех позиций. |
| closeAllControlON | Включает или отключает автоматическое закрытие всех позиций по заданным условиям. |
| closeBy | Режим закрытия всех позиций: по денежной сумме, по проценту от аккаунта или по пипсам. |
| closeAllMoney | Сумма в долларах для закрытия всех позиций при достижении положительного плавающего дохода. |
| closeAllMoneyLoss | Сумма в долларах для закрытия всех позиций при достижении отрицательного плавающего убытка. |
| closeByPipsWin | Количество пипсов прибыли для закрытия всех позиций в режиме CloseByPips. |
| closeByPipsLoss | Количество пипсов убытка для закрытия всех позиций в режиме CloseByPips. |
| Tbk | Заголовок раздела настроек безубытка. |
| breakevenOn | Включает или отключает функцию перевода стоп-лосса в безубыток. |
| userBkvPips | Количество пипсов для перевода стоп-лосса в безубыток после достижения позиции нужной дистанции. |
| tTailingStop | Заголовок раздела настроек скользящего стоп-лосса. |
| TslON | Включает или отключает функцию скользящего стоп-лосса (Trailing Stop). |
| userTslInitialStep | Начальный шаг в пунктах для активации скользящего стоп-лосса после открытия позиции. |
| userTslStep | Размер шага в пунктах для каждого последующего перемещения стоп-лосса. |
| userTslDistance | Дистанция в пунктах для каждого шага скользящего стоп-лосса. |
Поиск по коду файла
#property version "1.0"
#property strict
#define NEWS_FILTER
#define DAILY_LIMITS
#define CLOSE_ALL_ON
#define BREAKEVEN_ON
#define TRAILING_STOP_ON
enum TSLMode {
byPips, // By Pips
byMA // By Moving Average
};
enum CloseAllMode {
CloseByMoney, // by Money
CloseByAccountPercent, // by Account Percent
CloseByPips // By Pips
};
input string SimpleForexTeam__ = "free tools for forex! Join our channel for more free eas";
input string The_our_telegram = "";
extern string EA_Name = "EA HOKKYDJONG";
extern string Use_TradeAgain = "If => TRUE,EA will trade again,If => FALSE => EA will Off";
extern bool TradeAgain = TRUE;
extern string Use_Loop = "Example = 10,EA will trader for 10 Laps";
extern int Loop = 10000;
int Gi_108;
extern int StartTrade = 0;
extern int EndTrade = 24;
extern string Use_DbLots = "If = 1-> Use Multiplier Lot, If = 2-> Use Fixed Lot";
extern int DbLots = 1;
extern double Lots = 0.01;
extern double SL = 0.0;
extern double TP = 4.0;
extern double Distance = 3.0;
extern double Multiplier = 1.6;
extern int MaxLevel = 20;
double Gd_176 = 3.0;
extern double LotsDecimal = 2.0;
extern int MagicNumber = 163991;
extern string EA_Comment = "ea_hokkydjong";
double Gd_unused_204 = 0.0;
double G_price_212;
double G_price_220;
double G_bid_228;
double G_ask_236;
double Gd_244;
double Gd_252;
bool Gi_260;
datetime G_time_264 = 0;
int Gi_268 = 0;
double Gd_272;
int G_pos_280 = 0;
int Gi_284;
double Gd_288 = 0.0;
bool Gi_296 = FALSE;
bool Gi_300 = FALSE;
bool Gi_304 = FALSE;
int Gi_308;
bool Gi_312 = FALSE;
double Gd_316;
int Gi_324 = 65535;
int Gi_328 = 65535;
int Gi_332 = 16776960;
double Gd_336;
extern double MoneyPerLot = 1.7;
int magico = MagicNumber;
#ifdef NEWS_FILTER
input string TNewsFilter = "== News =="; // ————————————
input bool newsOn = false; // News Filter On:
int input Turn_OFF_Before = 30; // Turn OFF before (min.)
int input Turn_ON_After = 30; // Turn ON after (min.)
enum SourceNews { Manual,
Auto,
None };
SourceNews News_Fuente = Auto; // News Source:
int AfterNewsStop = 5; // Indent after News, minuts
int BeforeNewsStop = 5; // Indent before News, minut
input bool NewsLight = false; // Enable light news
input bool NewsMedium = false; // Enable medium news
input bool NewsHard = true; // Enable hard news
input int offset = 0; // Your Time Zone, GMT (for news)
input string NewsSymb = "USD,EUR,GBP,CHF,CAD,AUD,NZD,JPY"; // Currency to display the news (empty - only the current currencies)
input bool DrawLines = true; // Draw lines on the chart
input bool Next = false; // Draw only the future of news line
bool Signal = true; // Signals on the upcoming news
color highc = clrRed; // Colour important news
color mediumc = clrOrange; // Colour medium news
color lowc = clrSkyBlue; // The color of weak news
int Style = 2; // Line style
int Upd = 86400; // Period news updates in seconds
bool Vhigh = false;
bool Vmedium = false;
bool Vlow = false;
int MinBefore = 10; // MINUTOS DE AVISO ANTES DE UNA NOTICIA
int MinAfter = 10; // MINUTOS DE AVISO DESPUES DE UNA NOTICIA
int NomNews = 0;
string NewsArr[4][1000];
int Now = 0;
datetime LastUpd;
string str1;
#endif
#ifdef DAILY_LIMITS
enum DayLimitsMode {
LimitsByAmount, // by Amount
LimitsByAccountPercent // by Account %
};
input string Tlimits = "== Daily Limits Setup =="; // ————————————
input bool uDailyProfitOn = false; // Control Daily Profit On:
input DayLimitsMode limitProfitMode = LimitsByAmount; // Mode to control daily profit:
input double uDayLimitProfit = 2000; // Max Daily Profit ($ or %):
input bool uDailyLossOn = false; // Control Daily Loss On:
input DayLimitsMode limitLossMode = LimitsByAmount; // Mode to control daily loss:
input double uDayLimitLoss = -1000; // Max Daily Loss ($ or %):
input bool uConsiderFloatting = false; // Consider Floating:
#endif
#ifdef CLOSE_ALL_ON
input string TtpOptions = "== Close All Options =="; // ————————————
input bool closeAllControlON = false; // Close All Control On:
input CloseAllMode closeBy = CloseByMoney; // Close All Mode:
input double closeAllMoney = 100; // Close by Money $:
input double closeAllMoneyLoss = -100; // Close by Money Lossing $:
input double accountPerWin = 1; // Account Percent Win:
input double accountPerLos = -1; // Account Percent Loss:
input double closeByPipsWin = 10; // Close Pips Win:
input double closeByPipsLoss = 10; // Close Pips Loss:
#endif
#ifdef BREAKEVEN_ON
input string Tbk = "== Breakeven Setup =="; // ————————————
input bool breakevenOn = false; // Breakeven On:
input double userBkvPips = 3; // Breakeven Pips
#endif
#ifdef TRAILING_STOP_ON
input string tTailingStop = "== TrailingStop Setup =="; // ————————————
input bool TslON = false; // TSL ON:
TSLMode userTslMode = byPips; // TSL Mode:
input int userTslInitialStep = 1; // TSL Initial Step:
input int userTslStep = 1; // TSL Step:
input int userTslDistance = 20; // TSL Distance:
#endif
bool filterMagicsOn = true; // Use magic number filter?
interface IOrders
{
public:
virtual void Add() = 0;
virtual void Release() = 0;
virtual bool AddOrder() = 0;
virtual bool DeleteOrder() = 0;
virtual bool Select() = 0;
};
class Order
{
int _id;
string _symbol;
double _price;
double _sl;
double _tp;
double _lot;
int _type;
int _magic;
string _comment;
string _strategy;
datetime _expireTime;
datetime _signalTime;
double _profit;
double _tslNext;
bool _bkvWasDoIt;
int _countPartials;
public:
Order(
int id,
string symbol,
double price,
double sl,
double tp,
double lot,
int type,
int magic,
string comment,
string strategy,
datetime expireTime,
datetime signalTime,
double profit,
double bkvWasDoIt,
int countPartials) : _id(id),
_symbol(symbol),
_price(price),
_sl(sl),
_tp(tp),
_lot(lot),
_type(type),
_magic(magic),
_comment(comment),
_strategy(strategy),
_expireTime(expireTime),
_signalTime(signalTime),
_profit(profit),
_bkvWasDoIt(bkvWasDoIt),
_countPartials(countPartials) {}
Order() {}
~Order() {}
Order* id(int id){_id=id; return &this;}
Order* symbol(string symbol){_symbol=symbol; return &this;}
Order* price(double price){_price=price; return &this;}
Order* sl(double sl){_sl=sl; return &this;}
Order* tp(double tp){_tp=tp; return &this;}
Order* lot(double lot){_lot=lot; return &this;}
Order* type(int type){_type=type; return &this;}
Order* magic(int magic){_magic=magic; return &this;}
Order* comment(string comment){_comment=comment; return &this;}
Order* expireTime(datetime expireTm){_expireTime=expireTm; return &this;}
Order* signalTime(datetime signalTm){_signalTime=signalTm; return &this;}
Order* profit(double profit){_profit=profit; return &this;}
Order* strategy(string strategy){_strategy=strategy; return &this;}
Order* tslNext(double tslNext){_tslNext=tslNext; return &this;}
Order* breakevenWasDoIt(bool bkvWasDoIt){_bkvWasDoIt=bkvWasDoIt; return &this;}
Order* countPartials(int count){_countPartials=_countPartials + count; return &this;}
int id() { return _id; }
string symbol() { return _symbol; }
double price() { return _price; }
double sl() { return _sl; }
double tp() { return _tp; }
double lot() { return _lot; }
int type() { return _type; }
int magic() { return _magic; }
string comment() { return _comment; }
string strategy() { return _strategy; }
datetime expireTime() { return _expireTime; }
datetime signalTime() { return _signalTime; }
double profit() { if (OrderSelect(_id, SELECT_BY_TICKET)) return OrderProfit(); return -1; }
double tslNext() { return _tslNext; }
double breakevenWasDoIt() { return _bkvWasDoIt; }
int countPartials() { return _countPartials; }
};
class FilterBySymbols
{
string _symbols[];
public:
FilterBySymbols(string userSymbols) { getSymbols(userSymbols); }
~FilterBySymbols() { ; }
void getSymbols(string userSymbols)
{
string Simbolos[];
string sep = ",";
ushort u_sep;
u_sep = StringGetCharacter(sep, 0);
int k = StringSplit(userSymbols, u_sep, Simbolos);
ArrayResize(_symbols, ArrayRange(Simbolos, 0), 0);
for (int i = 0; i < ArrayRange(Simbolos, 0); i++)
{
_symbols[i] = Simbolos[i];
}
printSymbols();
}
bool control(const string symbolToControl)
{
if (ArraySize(_symbols) > 0)
{
for (int i = 0; i < ArraySize(_symbols); i++)
{
if (_symbols[i] == symbolToControl)
{
return true;
}
}
}
return false;
}
void printSymbols()
{
for (int i = 0; i < ArraySize(_symbols); i++)
{
Print(_symbols[i]);
}
}
};
class FilterByMagics
{
int _magics[];
public:
FilterByMagics(string userMagics) { getMagics(userMagics); }
~FilterByMagics() { ; }
void getMagics(string userMagics)
{
string Magicos[];
string sep = ",";
ushort u_sep;
u_sep = StringGetCharacter(sep, 0);
int k = StringSplit(userMagics, u_sep, Magicos);
ArrayResize(_magics, ArrayRange(Magicos, 0), 0);
for (int i = 0; i < ArrayRange(Magicos, 0); i++)
{
_magics[i] = (int)Magicos[i];
}
if (ArrayRange(_magics, 0) > 0)
{
ArraySort(_magics, WHOLE_ARRAY, 0, MODE_ASCEND);
}
printMagics();
}
bool control(const int magicToControl)
{
if (ArraySize(_magics) > 0)
{
int p = ArrayBsearch(_magics, magicToControl, WHOLE_ARRAY, 0, MODE_ASCEND);
if (_magics[p] == magicToControl)
{
return true;
}
}
return false;
}
void printMagics()
{
for (int i = 0; i < ArraySize(_magics); i++)
{
Print(_magics[i]);
}
}
};
class OrdersList
{
Order* orders[];
bool _filterByMagicOn;
bool _filterBySymbolsOn;
FilterByMagics* _magics;
FilterBySymbols* _symbols;
public:
OrdersList(){;}
OrdersList(bool uFilterByMagicOn, string uMagics, bool uFilterBySymbolsOn, string uSymbols)
{
_filterByMagicOn = uFilterByMagicOn;
_filterBySymbolsOn = uFilterBySymbolsOn;
_magics = new FilterByMagics(uMagics);
_symbols = new FilterBySymbols(uSymbols);
Print("New OrderList Created");
}
~OrdersList()
{
delete _magics;
delete _symbols;
clearList();
}
void setOrdersList(bool magicOn, string magics, bool symbolsOn, string symbols)
{
_filterByMagicOn = magicOn;
_filterBySymbolsOn = symbolsOn;
_magics = new FilterByMagics(magics);
_symbols = new FilterBySymbols(symbols);
}
bool AddOrder(Order* order)
{
int t = ArraySize(orders);
if (ArrayResize(orders, t + 1))
{
orders[t] = order;
return true;
}
return false;
}
void GetMarketOrders()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (_filterByMagicOn) if (!_magics.control(OrderMagicNumber())) { continue; }
if (_filterBySymbolsOn) if (!_symbols.control(OrderSymbol())) { continue; }
if (exist(OrderTicket()) == true) { continue; }
Order* newOrder = new Order();
newOrder
.id(OrderTicket())
.symbol(OrderSymbol())
.price(OrderOpenPrice())
.sl(OrderStopLoss())
.tp(OrderTakeProfit())
.lot(OrderLots())
.type(OrderType())
.magic(OrderMagicNumber())
.comment(OrderComment())
.expireTime(OrderExpiration())
.profit(OrderProfit())
.breakevenWasDoIt(false)
.countPartials(0);
if (AddOrder(newOrder))
{
PrintOrder(i);
}
}
}
}
bool GetLastMarketOrder()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (_filterByMagicOn) if(!_magics.control(OrderMagicNumber())) { continue; }
if (_filterBySymbolsOn) if (!_symbols.control(OrderSymbol())) { continue; }
if (exist(OrderTicket()) == true) { continue; }
Order* newOrder = new Order();
newOrder
.id(OrderTicket())
.symbol(OrderSymbol())
.price(OrderOpenPrice())
.sl(OrderStopLoss())
.tp(OrderTakeProfit())
.lot(OrderLots())
.type(OrderType())
.magic(OrderMagicNumber())
.comment(OrderComment())
.expireTime(OrderExpiration())
.profit(OrderProfit())
.breakevenWasDoIt(false)
.countPartials(0);
if (AddOrder(newOrder))
{
Print(__FUNCTION__," ","* Nueva Orden De Mercado * ",id(i), "magic: ",magic(i));
return true;
}
}
return false;
}
return false;
}
bool exist(int id)
{
for (int i = qnt() - 1; i >= 0; i--)
{
if (id(i) == id)
{
return true;
}
}
return false;
}
bool deleteOrder(int index)
{
if (notOverFlow(index))
{
delete orders[index];
}
if (qnt() > index)
{
for (int i = index; i < qnt() - 1; i++)
{
orders[i] = orders[i + 1];
}
ArrayResize(orders, qnt() - 1);
return true;
}
return false;
}
void clearList()
{
for (int i = 0; i < qnt(); i++)
{
if (CheckPointer(orders[i]) != POINTER_INVALID)
{
deleteOrder(i);
}
}
}
Order* last()
{
int lastIndex = ArraySize(orders) - 1;
if (lastIndex == -1)
{
return NULL;
}
return GetPointer(orders[lastIndex]);
}
Order* index(int in)
{
return GetPointer(orders[in]);
}
int lastId()
{
int lastIndex = ArraySize(orders) - 1;
return orders[lastIndex].id();
}
bool notOverFlow(int index)
{
if (index > ArraySize(orders) - 1) return false;
if (index < 0) return false;
if (CheckPointer(orders[index]) == POINTER_INVALID) return false;
return true;
}
int qnt()
{
return ArraySize(orders);
}
int id(int index)
{
if (notOverFlow(index))
{
return orders[index].id();
}
return -1;
}
string symbol(int index)
{
if (notOverFlow(index))
{
return orders[index].symbol();
}
return "";
}
double price(int index)
{
if (notOverFlow(index))
{
return orders[index].price();
}
return -1;
}
double sl(int index)
{
if (notOverFlow(index))
{
return orders[index].sl();
}
return -1;
}
double tp(int index)
{
if (notOverFlow(index))
{
return orders[index].tp();
}
return -1;
}
double lot(int index)
{
if (notOverFlow(index))
{
return orders[index].lot();
}
return -1;
}
int magic(int index)
{
if (notOverFlow(index))
{
return orders[index].magic();
}
return -1;
}
datetime expire(int index)
{
if (notOverFlow(index))
{
return orders[index].expireTime();
}
return -1;
}
datetime signalTime(int index)
{
if (notOverFlow(index))
{
return orders[index].signalTime();
}
return -1;
}
string comment(int index)
{
if (notOverFlow(index))
{
return orders[index].comment();
}
return "";
}
ENUM_ORDER_TYPE type(int index)
{
if (notOverFlow(index))
{
return orders[index].type();
}
return -1;
}
double profit(int index)
{
if (notOverFlow(index))
{
return orders[index].profit();
}
return -1;
}
bool isClose(int index)
{
if (notOverFlow(index))
{
if (OrderSelect(id(index), SELECT_BY_TICKET))
{
if (OrderCloseTime() != 0) return true;
}
}
return false;
}
void cleanCloseOrders()
{
if (qnt() == 0)
{
return;
}
for (int i = 0; i < qnt(); i++)
{
if (isClose(i))
{
deleteOrder(i);
}
}
}
int closeAllInList()
{
cleanCloseOrders();
int errors = 0;
for (int i = 0; i < ArraySize(orders); i++)
{
int tk;
if (isClose(i))
{
continue;
}
if (CheckPointer(orders[i]) != POINTER_INVALID)
{
tk = orders[i].id();
} else
{
continue;
}
if (OrderSelect(tk, SELECT_BY_TICKET))
{
double ask = SymbolInfoDouble(OrderSymbol(), SYMBOL_ASK);
double bid = SymbolInfoDouble(OrderSymbol(), SYMBOL_BID);
double closePrice = OrderType() == OP_BUY ? bid : ask;
if (!OrderClose(OrderTicket(), OrderLots(), closePrice, 1000, clrNONE))
{
Print(__FUNCTION__, " ", "Error in close order ", orders[i].id(), ": ", GetLastError());
errors++;
}
}
}
cleanCloseOrders();
return errors;
}
void PrintOrder(const int index)
{
if (!notOverFlow(index))
{
return;
}
if (CheckPointer(orders[index]) == POINTER_INVALID)
{
return;
}
Print("Order ", index, " id: ", orders[index].id());
Print("Order ", index, " symbol: ", orders[index].symbol());
Print("Order ", index, " type: ", orders[index].type());
Print("Order ", index, " lot: ", orders[index].lot());
Print("Order ", index, " price: ", orders[index].price());
Print("Order ", index, " sl: ", orders[index].sl());
Print("Order ", index, " tp: ", orders[index].tp());
Print("Order ", index, " magic: ", orders[index].magic());
Print("Order ", index, " comment: ", orders[index].comment());
Print("Order ", index, " strategy: ", orders[index].strategy());
Print("Order ", index, " expire time: ", orders[index].expireTime());
Print("Order ", index, " signal time: ", orders[index].signalTime());
Print("Order ", index, " profit: ", orders[index].profit());
Print("Order ", index, " countPartials: ", orders[index].countPartials());
}
void PrintList()
{
for (int i = 0; i < qnt(); i++)
{
PrintOrder(i);
}
}
};
OrdersList mainOrders(filterMagicsOn, (string)magico, true, _Symbol);
interface iConditions
{
bool evaluate();
};
class ConcurrentConditions
{
protected:
iConditions* _conditions[];
public:
ConcurrentConditions(void) {}
~ConcurrentConditions(void) { releaseConditions(); }
void releaseConditions()
{
for (int i = 0; i < ArraySize(_conditions); i++)
{
delete _conditions[i];
}
ArrayFree(_conditions);
}
void AddCondition(iConditions* condition)
{
int t = ArraySize(_conditions);
ArrayResize(_conditions, t + 1);
_conditions[t] = condition;
}
bool EvaluateConditions(void)
{
for (int i = 0; i < ArraySize(_conditions); i++)
{
if (!_conditions[i].evaluate())
{
return false;
}
}
return true;
}
};
interface iActions
{
bool doAction();
};
class MoveSL : public iActions
{
Order* _order;
double _newSL;
public:
MoveSL() { ; }
~MoveSL() { ; }
MoveSL* order(Order* or)
{
_order = or ;
return &this;
}
MoveSL* newSL(double newSL)
{
_newSL = newSL;
return &this;
}
bool controlPointer(Order* or)
{
if (CheckPointer(or))
{
return true;
} else
{
Print("Order Pointer Invalid");
return false;
}
}
bool doAction()
{
if (!controlPointer(_order))
{
Print(__FUNCTION__, " ", "Can't Move Stop Loss");
return false;
}
if (OrderSelect(_order.id(), SELECT_BY_TICKET))
{
if (OrderCloseTime() > 0)
{
Print(__FUNCTION__, " ", "Order are closed ", _order.id());
return false;
}
if (OrderModify(_order.id(), OrderOpenPrice(), _newSL, OrderTakeProfit(), OrderExpiration(), clrNONE))
{
_order.sl(_newSL);
_order.breakevenWasDoIt(true);
Print(__FUNCTION__, " ", _order.id(), " Modify: new SL: ", _newSL);
return true;
}
} else
{
Print(__FUNCTION__, " ", "Can't Select the order ", _order.id());
}
return false;
}
};
MoveSL* breackevenAction;
class ActionCloseOrdersByType : public iActions
{
ENUM_ORDER_TYPE _type;
string _symbol;
int _magic;
int _slippage;
double _price;
public:
ActionCloseOrdersByType(string side, int magic = 0, string symbol = "", int slippage = 10000)
{
if (side == "buy") _type = OP_BUY;
if (side == "sell") _type = OP_SELL;
if (symbol == "")
{
_symbol = Symbol();
} else
{
_symbol = symbol;
}
if (magic != 0)
{
_magic = magic;
}
if (slippage != 10000)
{
_slippage = slippage;
}
}
~ActionCloseOrdersByType() {}
void setPrice()
{
if (_type == OP_BUY)
{
_price = SymbolInfoDouble(_symbol, SYMBOL_BID);
}
if (_type == OP_SELL)
{
_price = SymbolInfoDouble(_symbol, SYMBOL_ASK);
}
}
bool doAction()
{
setPrice();
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS) && OrderSymbol() == _symbol && OrderMagicNumber() == _magic && OrderType() == _type)
{
if (!OrderClose(OrderTicket(), OrderLots(), _price, _slippage, clrNONE))
{
Print(__FUNCTION__, " ", "can't close Order: ", OrderTicket(), " error: ", GetLastError());
return false;
}
}
}
return true;
}
};
ActionCloseOrdersByType* actionCloseSells;
ActionCloseOrdersByType* actionCloseBuys;
interface iTSL
{
void setInitialStep(Order* order);
void setNextStep(Order* order);
double newSL(Order* order);
};
class TslByPips : public iTSL
{
int _InitialStep;
int _TslStep;
double _Distance;
public:
TslByPips(int InitialStep, int TslStep, double Distance)
{
_InitialStep = InitialStep * 10;
_TslStep = TslStep * 10;
_Distance = Distance * 10;
}
~TslByPips() { ; }
void setInitialStep(Order* order)
{
double mPoint = MarketInfo(order.symbol(), MODE_POINT);
double pointsToMove = _InitialStep * mPoint;
if (order.type() == OP_SELL)
{
pointsToMove *= -1;
}
order.tslNext(order.price() + pointsToMove);
Print(__FUNCTION__, " ", "TSL Order: ", " ", order.id());
Print(__FUNCTION__, " ", "TSL Order Price: ", " ", order.price());
Print(__FUNCTION__, " ", "TSL tslNext: ", " ", order.tslNext());
}
void setNextStep(Order* order)
{
double mPoint = MarketInfo(order.symbol(), MODE_POINT);
double pointsToMove = _TslStep * mPoint;
if (order.type() == OP_SELL)
{
pointsToMove *= -1;
}
order.tslNext(order.tslNext() + pointsToMove);
Print(__FUNCTION__, " ", "TSL Order: ", " ", order.id());
Print(__FUNCTION__, " ", "TSL Order Price: ", " ", order.price());
Print(__FUNCTION__, " ", "TSL tslNext: ", " ", order.tslNext());
}
double newSL(Order* order)
{
double mPoint = MarketInfo(order.symbol(), MODE_POINT);
double pointsToMove = _Distance * mPoint;
if (order.type() == OP_SELL)
{
pointsToMove *= -1;
}
double newSl = order.tslNext() - pointsToMove;
Print(__FUNCTION__, " ", "TSL Order: ", " ", order.id());
Print(__FUNCTION__, " ", "TSL New SL: ", " ", newSl);
return newSl;
}
};
class TrailingStop
{
OrdersList* _orders;
iTSL* _TslMode;
public:
TrailingStop(OrdersList* uOrders, TSLMode mode)
{
_orders = uOrders;
switch (mode)
{
case byPips:
_TslMode = new TslByPips(userTslInitialStep, userTslStep, userTslDistance);
break;
}
}
~TrailingStop()
{
delete _TslMode;
}
void doTSL()
{
for (int i = 0; i < _orders.qnt(); i++)
{
if (CheckPointer(_orders.index(i)) == POINTER_INVALID)
{
Print(__FUNCTION__, " ", "Pointer invalid i= ", i);
continue;
}
if (_orders.index(i).tslNext() == 0)
{
_TslMode.setInitialStep(_orders.index(i));
}
if (MatchNextTsl(_orders.index(i)))
{
double newSl = _TslMode.newSL(_orders.index(i));
moveSL(_orders.index(i).id(), newSl);
_TslMode.setNextStep(_orders.index(i));
}
}
}
bool MatchNextTsl(Order* order)
{
double ask = SymbolInfoDouble(order.symbol(), SYMBOL_ASK);
double bid = SymbolInfoDouble(order.symbol(), SYMBOL_BID);
if (order.type() == OP_BUY)
{
if (bid >= order.tslNext())
{
return true;
}
}
if (order.type() == OP_SELL)
{
if (ask <= order.tslNext())
{
return true;
}
}
return false;
}
void moveSL(int tk, double newSl)
{
if (OrderSelect(tk, SELECT_BY_TICKET))
{
if (!OrderModify(tk, OrderOpenPrice(), newSl, OrderTakeProfit(), 0))
{
Print(__FUNCTION__, " ", "error when make TSL in TK: ", tk, " ", GetLastError());
} else
{
Print(__FUNCTION__, " trailing stop in tk: ", tk);
}
}
}
};
TrailingStop* tsl;
class DailyProfitCondition : public iConditions
{
int _magic;
double _limit;
bool _considerOpen; // Considera el flotante profit flotante
string _mode; // loss or profit
DayLimitsMode _limitMode; // Amount or AccountPer
public:
DailyProfitCondition(double limit, int mag, bool considerOpen, string mode, DayLimitsMode limitMode) : _limit(limit), _magic(mag), _considerOpen(considerOpen), _mode(mode), _limitMode(limitMode) { ; }
~DailyProfitCondition() { ; }
bool evaluate()
{
if (_mode == "profit")
{
if (TodayProfit() >= Limit())
{
Print("DAILY PROFIT REACHED: ", TodayProfit());
return true;
}
}
if (_mode == "loss")
{
if (TodayProfit() <= Limit())
{
Print("DAILY LOSS REACHED: ", TodayProfit());
return true;
}
}
return false;
}
double Limit()
{
if (_limitMode == LimitsByAmount)
{
return _limit;
}
if (_limitMode == LimitsByAccountPercent)
{
return _limit / 100 * AccountInfoDouble(ACCOUNT_BALANCE);
}
return 0;
}
double TodayProfit()
{
datetime iniDay = iTime(NULL, PERIOD_D1, 0);
double profit = 0;
for (int i = OrdersHistoryTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY) && OrderSymbol() == _Symbol && OrderMagicNumber() == _magic)
{
if (OrderCloseTime() >= iniDay)
{
profit += OrderProfit() + OrderSwap() + OrderCommission();
}
}
}
if (_considerOpen)
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_Показано первые 50% кода (символов: 41043)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.