SailSystemEA
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «sailsystemea_v2.3.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
SailSystemEA — это торговый советник для MetaTrader 4, работающий по системе хеджинга и скальпинга. Советник предназначен для работы на валютных парах с низким спредом и комиссиями, обеспечивает автоматическое открытие и управление рыночными ордерами, а также поддерживает отложенные ордера.
Советник реализует систему виртуальных уровней стоп-лосса и тейк-профита с возможностью отображения на графике. Включает фильтр по времени торговли, мониторинг максимального спреда и автоматический расчёт комиссий. При превышении допустимого спреда или выходе за пределы торговой сессии доступны различные действия: увеличение уровней или закрытие ордеров.
Поддерживается автоматический и ручной расчёт размера лота с учётом риск-фактора. Советник отслеживает средний спред и среднее время исполнения, ведёт статистику истории сделок. При деактивации автоматической торговли или недостатке маржи выводит соответствующие предупреждения на экран.
В режиме бэктеста отображается отчёт со средней длительностью сделок, количеством прибыльных и убыточных ордеров. Советник управляет существующими позициями при выходе за рамки временного фильтра: закрывает рыночные ордера и/или удаляет отложенные в соответствии с выбранной настройкой.
Настройки программы
| Настройка | Описание |
|---|---|
| OrdersSetting | Текстовый разделитель группы настроек ордеров. |
| UseVirtualLevels | Включает использование виртуальных уровней стоп-лосса и тейк-профита вместо реальных уровней ордера. |
| ShowVirtualLevels | Отображение линий виртуальных уровней стоп-лосса и тейк-профита на графике. |
| OrdersStopLoss | Расстояние стоп-лосса в пунктах от цены открытия ордера. |
| PutTakeProfit | Включает установку тейк-профита при открытии ордера. |
| OrdersTakeProfit | Расстояние тейк-профита в пунктах от цены открытия ордера. |
| DelayModifyOrders | Количество тиков ожидания перед модификацией рыночного ордера. |
| StepModifyOrders | Шаг в пунктах для модификации ордера. |
| PipsReplaceOrders | Расстояние в пунктах для переоткрытия ордеров при достижении определённого отклонения цены. Положительное значение — отклонение в сторону убытка, отрицательное — в сторону прибыли. |
| SafeMultiplier | Множитель безопасности, используемый при расчёте условий переоткрытия ордеров. |
| UsePendingOrders | Включает использование отложенных ордеров BuyLimit и SellLimit при наличии открытых рыночных позиций. |
| DistancePending | Расстояние в пунктах от текущей цены для размещения отложенных ордеров. |
| TimeFilterSets | Текстовый разделитель группы настроек временного фильтра. |
| UseTimeFilter | Включает временной фильтр для ограничения торговли заданным временем сессии. |
| TimeStartTrade | Время начала торговой сессии в формате ЧЧ:ММ:СС по GMT. |
| TimeStopTrade | Время окончания торговой сессии в формате ЧЧ:ММ:СС по GMT. |
| ManageExistOrders | Способ управления существующими ордерами при выходе за пределы торговой сессии: оставить все, удалить отложенные, закрыть рыночные или выполнить оба действия. |
| LotSetting | Текстовый разделитель группы настроек лота. |
| AutoLotSize | Включает автоматический расчёт размера лота на основе equity и коэффициента риска. |
| RiskFactor | Коэффициент риска для автоматического расчёта размера лота как процент от equity. |
| ManualLotSize | Фиксированный размер лота при ручном режиме управления размером позиции. |
| EASetting | Текстовый разделитель группы настроек советника. |
| AcceptStopLevel | Минимально допустимый уровень стоп-лосса в пунктах. Если установленное значение ниже уровня стоп-лосса брокера, торговля приостанавливается. |
| Slippage | Допустимое проскальзывание цены при исполнении ордеров в пунктах. |
| OrdersIDInfo | Текстовая подсказка с информацией о настройке идентификатора ордера. |
| OrdersID | Идентификатор магического номера ордера для фильтрации сделок советником. |
| SpreadSetting | Текстовый разделитель группы настроек спреда. |
| MaxSpreadInfo | Текстовая подсказка с информацией о настройке максимального спреда. |
| MaxSpread | Максимально допустимый спред в пунктах. При превышении торговля блокируется. |
| TypeOfSpreadUse | Тип используемого спреда: средний (за заданный период) или текущий (в реальном времени). |
| HighSpreadAction | Действие при превышении максимального спреда: увеличение уровней ордеров или закрытие ордеров. |
| MultiplierIncrease | Множитель для увеличения уровней стоп-лосса, тейк-профита и шага модификации при высоком спреде. |
| CommisionsSet | Текстовый разделитель группы настроек комиссий. |
| CommissionInPip | Комиссия брокера, выраженная в пунктах, добавляемая к спреду при оценке условий торговли. |
| CommissionInCur | Комиссия брокера в единицах валюты счёта, используемая для расчёта общего размера комиссии. |
| GetCommissionAuto | Автоматическое определение комиссии брокера на основе комиссий открытых ордеров. |
| InformationSets | Текстовый разделитель группы настроек информации. |
| CountAvgSpread | Включает подсчёт и отображение среднего спреда за заданное количество тиков. |
| CountAvgExecution | Включает подсчёт и отображение среднего времени исполнения ордеров в миллисекундах. |
| TimesForAverage | Количество значений для расчёта среднего спреда и среднего времени исполнения. |
| DeleteObjectsSets | Текстовый разделитель группы настроек удаления объектов. |
| DeleteObjects | Включает автоматическое удаление графических объектов через заданный интервал времени. |
| DeleteMinutes | Интервал в минутах для автоматического удаления графических объектов на графике. |
| ExpertCommentsSet | Текстовый разделитель группы настроек комментариев. |
| ExpertComments | Текстовый комментарий, присваиваемый каждому открытому ордеру для идентификации. |
| BacktesttingInfo | Включает отображение отчёта по истории сделок при завершении бэктеста. |
Поиск по коду файла
#property version "2.3"
#property description "This Expert Advisor is a hedge and scalp system."
#property description "\nRun well in any pair with tight spread and low commission."
#property description "Choice a broker with fast execution and zero stop level."
#property strict
enum Sprd {Use_Average, Use_Current};
enum Actn {Increase_Levels, Close_Orders};
enum Exist {Kepp_All_Orders, Delete_Pending, Close_Market, DeletePending_And_CloseMarket};
extern string OrdersSetting = "||======== Orders Setting ========||";
extern bool UseVirtualLevels = true;
extern bool ShowVirtualLevels = true;
extern double OrdersStopLoss = 5;
extern bool PutTakeProfit = false;
extern double OrdersTakeProfit = 50.0;
extern int DelayModifyOrders = 4;
extern double StepModifyOrders = 1.0;
extern double PipsReplaceOrders = 0.0;
extern double SafeMultiplier = 10.0;
extern bool UsePendingOrders = false;
extern double DistancePending = 1.0;
extern string TimeFilterSets = "||======== Times Setting ========||";
extern bool UseTimeFilter = false;
extern string TimeStartTrade = "00:00:00";
extern string TimeStopTrade = "00:00:00";
extern Exist ManageExistOrders = DeletePending_And_CloseMarket;
extern string LotSetting = "||======== Lot Setting ========||";
extern bool AutoLotSize = false;
extern double RiskFactor = 10;
extern double ManualLotSize = 0.01;
extern string EASetting = "||======== EA Setting ========||";
extern double AcceptStopLevel = 2.0;
extern int Slippage = 1;
extern string OrdersIDInfo = "0 = Generate ID per Symbol";
extern int OrdersID = 0;
extern string SpreadSetting = "||======== Spread Setting ========||";
extern string MaxSpreadInfo = "0 = Not check spread";
extern double MaxSpread = 1.0;
extern Sprd TypeOfSpreadUse = Use_Average;
extern Actn HighSpreadAction = Increase_Levels;
extern double MultiplierIncrease = 2.0;
extern string CommisionsSet = "||======== Commissions Setting ========||";
extern double CommissionInPip = 0.0;
extern double CommissionInCur = 0.0;
extern bool GetCommissionAuto = true;
extern string InformationSets = "||======== Information Setting ========||";
extern bool CountAvgSpread = false;
extern bool CountAvgExecution = false;
extern int TimesForAverage = 30;
extern string DeleteObjectsSets = "||======== Objects Setting ========||";
extern bool DeleteObjects = false;
extern int DeleteMinutes = 30;
extern string ExpertCommentsSet = "||======== Comments Setting ========||";
extern string ExpertComments = "SailSystemEA";
extern bool BacktesttingInfo = true;
string SymbolUse;
string SymbolExtension="";
string SymbolTrade;
string BackgroundName;
string ShowInfoCommission;
string NameOfBuyStopLossLine;
string NameOfBuyTakeProfitLine;
string NameOfSellStopLossLine;
string NameOfSellTakeProfitLine;
string PREFIX="#";
long ChartColor;
int TotalOrders;
int CntBuyLimit;
int CntSellLimit;
int CntBuy;
int CntSell;
int TryTimes;
int TotalTrades;
int MultiplierPoint;
int TimeActionModify;
int MagicNumber;
int CountTickSpreadPair=0;
int CountTimesModify=0;
int CountTickSpread=0;
int TimesModify=0;
int i;
int Count;
int TicksGet=0;
int CountTickModifyBuy=0;
int CountTickModifySell=0;
int WinTrades;
int LossTrades;
int SendMessages=0;
int CountHistory;
double ArraySpreadPair[100];
double HistoryPips=0;
double AvgSpread;
double AvgExecution;
double TotalProfitLoss;
double SpreadPips;
double DigitsPoints;
double LotSize;
double StopLevel;
double CheckMargin1;
double CheckMargin2;
double SumMargin;
double StepModify;
double ModeTickValue;
double BrokerCommission;
double SpreadLimit;
double RealCommission;
double GetCommissionPair=0;
double PipsLevelLoss;
double PipsLevelProfit;
double PipsStepModify;
double AvrgPipsProfit=0;
double AvrgPipsLoss=0;
double AvrgDuration=0;
double LastBid=0;
double LastAsk=0;
double VirtualStopLossBuy=0;
double VirtualStopLossSell=0;
double VirtualTakeProfitBuy=0;
double VirtualTakeProfitSell=0;
double CurrentDistanceBuy;
double CurrentDistanceSell;
datetime ArrayExecution[100];
datetime OperationDelay=0;
datetime LastOperationDelay=0;
datetime TimeToSend=0;
datetime TimeDeleteObjects=0;
bool StopTrade=false;
bool SpreadOK;
bool CallMain=false;
bool ChangeAsk=false;
bool ChangeBid=false;
bool TestingMode=false;
bool NotHaveOpenOrders=true;
bool TimeToTrade;
int MagicSet=777333777;
int OnInit()
{
// код доступен только после оплаты
}
void OnDeinit(const int reason)
{
if((IsTesting()) && (BacktesttingInfo==true))
{
HistoryResults();
Print("<===== BACKTEST/HISTORY REPORT =====>");
Print("Average Duration: "+DoubleToStr(AvrgDuration,2)+" sec || Total Trades: "+DoubleToStr(TotalTrades,0));
Print("Average Profits: "+DoubleToStr(AvrgPipsProfit,2)+" pips || Win Trades: "+DoubleToStr(WinTrades,0));
Print("Average Loss: "+DoubleToStr(AvrgPipsLoss,2)+" pips || Loss Trades: "+DoubleToStr(LossTrades,0));
Print("Send Messages: "+DoubleToStr(SendMessages,0));
Print("<===== BACKTEST/HISTORY REPORT =====>");
}
EventKillTimer();
ObjectDelete(BackgroundName);
Comment("");
if(ObjectFind(NameOfSellStopLossLine)>-1)
ObjectDelete(NameOfSellStopLossLine);
if(ObjectFind(NameOfSellTakeProfitLine)>-1)
ObjectDelete(NameOfSellTakeProfitLine);
if(ObjectFind(NameOfBuyStopLossLine)>-1)
ObjectDelete(NameOfBuyStopLossLine);
if(ObjectFind(NameOfBuyTakeProfitLine)>-1)
ObjectDelete(NameOfBuyTakeProfitLine);
}
void OnTick()
{
// код доступен только после оплаты
}
void OnTimer()
{
if((IsTesting())||(IsOptimization())||(IsVisualMode()))
return;
if(IsTradeAllowed()==true)
{
if(CallMain==true)
MainFunction();
}
else
ScreenComment(5);
}
void MainFunction()
{
ChangeAsk=false;
ChangeBid=false;
SpreadOK=true;
if((NormalizeDouble(Bid,Digits)!=NormalizeDouble(LastBid,Digits)) || (NormalizeDouble(Ask,Digits)!=NormalizeDouble(LastAsk,Digits)) || (IsTesting()))
{
if(UseTimeFilter==true)
{
TimeToTrade=false;
if((StringToTime(TimeStartTrade)<StringToTime(TimeStopTrade))&&((TimeGMT()>=StringToTime(TimeStartTrade))&&(TimeGMT()<StringToTime(TimeStopTrade))))
TimeToTrade=true;
if((StringToTime(TimeStartTrade)>StringToTime(TimeStopTrade))&&((TimeGMT()>=StringToTime(TimeStartTrade))||(TimeGMT()<StringToTime(TimeStopTrade))))
TimeToTrade=true;
if(TimeToTrade==false)
{
ScreenComment(6);
}
}
else
TimeToTrade=true;
CountOrders();
if(NormalizeDouble(Ask,Digits)!=NormalizeDouble(LastAsk,Digits))
ChangeAsk=true;
if(NormalizeDouble(Bid,Digits)!=NormalizeDouble(LastBid,Digits))
ChangeBid=true;
LastBid=NormalizeDouble(Bid,Digits);
LastAsk=NormalizeDouble(Ask,Digits);
SpreadPips=(Ask-Bid)/DigitsPoints;
if(CountAvgSpread==true)
GetAvrgSpread(SpreadPips);
if(TypeOfSpreadUse==0)
SpreadLimit=AvgSpread;//Use average
if(TypeOfSpreadUse==1)
SpreadLimit=SpreadPips;//Use current
if(GetCommissionAuto==false)
RealCommission=BrokerCommission;
if((GetCommissionAuto==true) && (CntBuy+CntSell==0) && (NotHaveOpenOrders==true))
{
RealCommission=BrokerCommission;
ShowInfoCommission="Waiting Trades...";
}
if((GetCommissionAuto==true) && (CntBuy+CntSell!=0))
{
RealCommission=(GetCommissionPair/MathMax(1,ModeTickValue));
ShowInfoCommission=DoubleToStr(RealCommission,2)+" (pips)";
NotHaveOpenOrders=false;
}
if(TimeToTrade==true)
{
if((SpreadLimit+RealCommission>MaxSpread) && (MaxSpread>0))
{
if(IsTesting())
Print("Spread Is Too High, Expert Not Trade!!!");
ScreenComment(2);
SpreadOK=false;
}
else
{
ScreenComment(1);
}
}
if(AutoLotSize==true)
LotSize=MathMin(MathMax((MathRound((AccountEquity()*RiskFactor/100000)/MarketInfo(Symbol(),MODE_LOTSTEP))*MarketInfo(Symbol(),MODE_LOTSTEP)),MarketInfo(Symbol(),MODE_MINLOT)),MarketInfo(Symbol(),MODE_MAXLOT));
if(AutoLotSize==false)
LotSize=MathMin(MathMax((MathRound(ManualLotSize/MarketInfo(Symbol(),MODE_LOTSTEP))*MarketInfo(Symbol(),MODE_LOTSTEP)),MarketInfo(Symbol(),MODE_MINLOT)),MarketInfo(Symbol(),MODE_MAXLOT));
if(CntBuy==0)
{
CountTickModifyBuy=0;
VirtualStopLossBuy=0;
VirtualTakeProfitBuy=0;
}
if(CntSell==0)
{
CountTickModifySell=0;
VirtualStopLossSell=0;
VirtualTakeProfitSell=0;
}
PipsLevelLoss=OrdersStopLoss;
PipsLevelProfit=OrdersTakeProfit;
PipsStepModify=StepModifyOrders;
if(PipsLevelLoss<StopLevel)
PipsLevelLoss=StopLevel;
if(PipsLevelProfit<StopLevel)
PipsLevelProfit=StopLevel;
if((TimeToTrade==false)&&(ManageExistOrders>0))
{
if((ManageExistOrders==2)||(ManageExistOrders==3))
{
if(CntBuy>0)
CloseOrders(OP_BUY);
if(CntSell>0)
CloseOrders(OP_SELL);
}
if((ManageExistOrders==1)||(ManageExistOrders==3))
{
if(CntBuyLimit>0)
DeleteOrders(OP_BUYLIMIT);
if(CntSellLimit>0)
DeleteOrders(OP_SELLLIMIT);
}
}
if(TotalOrders>0)
{
if(SpreadOK==false)
{
if(HighSpreadAction==0)
{
PipsLevelLoss*=MultiplierIncrease;
PipsLevelProfit*=MultiplierIncrease;
PipsStepModify*=MultiplierIncrease;
}
if(HighSpreadAction==1)
{
if(CntBuy>0)
CloseOrders(OP_BUY);
if(CntSell>0)
CloseOrders(OP_SELL);
if(CntBuyLimit>0)
DeleteOrders(OP_BUYLIMIT);
if(CntSellLimit>0)
DeleteOrders(OP_SELLLIMIT);
return;
}
}
if(CntBuy>0)
ModifyMarketOrders(OP_BUY);
if(CntSell>0)
ModifyMarketOrders(OP_SELL);
if(CountHistory<3)
{
CountHistory++;
HistoryResults();
}
if(DeleteObjects==true)
ClearChart();
if((CntBuy==1)&&(CntSell==1)&&(((CntBuyLimit==1)&&(CntSellLimit==1))||(UsePendingOrders==false)))
return;
if(SpreadOK==false)
return;
}
if(((CntBuy==0) || (CntSell==0)) && (CheckMargin()==1)&&(TimeToTrade==true))
{
HistoryResults();
if(PipsReplaceOrders>0)
{
if((((CurrentDistanceBuy>=PipsReplaceOrders) || (CurrentDistanceBuy<=-(PipsReplaceOrders*SafeMultiplier))) && (CntBuy==0)) || (CntBuy+CntSell==0))
OpenOrders(OP_BUY);
if((((CurrentDistanceSell>=PipsReplaceOrders) || (CurrentDistanceSell<=-(PipsReplaceOrders*SafeMultiplier))) && (CntSell==0)) || (CntBuy+CntSell==0))
OpenOrders(OP_SELL);
}
if(PipsReplaceOrders<0)
{
if((((CurrentDistanceBuy<=PipsReplaceOrders) || (CurrentDistanceBuy>=-(PipsReplaceOrders*SafeMultiplier))) && (CntBuy==0)) || (CntBuy+CntSell==0))
OpenOrders(OP_BUY);
if((((CurrentDistanceSell<=PipsReplaceOrders) || (CurrentDistanceSell>=-(PipsReplaceOrders*SafeMultiplier))) && (CntSell==0)) || (CntBuy+CntSell==0))
OpenOrders(OP_SELL);
}
if(PipsReplaceOrders==0)
{
if(CntBuy==0)
OpenOrders(OP_BUY);
if(CntSell==0)
OpenOrders(OP_SELL);
}
}
if((UsePendingOrders==true) && (CntBuy>0) && (CntSell>0)&&(TimeToTrade==true))
{
if(((CntBuyLimit==0) || (CntSellLimit==0)) && (CheckMargin()==1))
{
HistoryResults();
if(CntBuyLimit==0)
OpenOrders(OP_BUYLIMIT);
if(CntSellLimit==0)
OpenOrders(OP_SELLLIMIT);
}
}
}
}
int CheckMargin()
{
CheckMargin1=0;
CheckMargin2=0;
SumMargin=0;
CheckMargin1=AccountFreeMargin()-AccountFreeMarginCheck(Symbol(),OP_BUY,LotSize);
CheckMargin2=AccountFreeMargin()-AccountFreeMarginCheck(Symbol(),OP_SELL,LotSize);
SumMargin=AccountFreeMargin()-MathMax(CheckMargin1,CheckMargin2);
if(SumMargin<=0.0)
{
if(IsTesting())
Print("Margin Account Is Too Low, Expert Not Trade!!!");
ScreenComment(3);
return(0);
}
return(1);
}
void OpenOrders(int TypeOfOrder)
{
int TicketBuy=-1;
int TicketSell=-1;
int TicketBuyLimit=-1;
int TicketSellLimit=-1;
double SL_Buy=0;
double TP_Buy=0;
double SL_Sell=0;
double TP_Sell=0;
double PriceBuyLimit=0;
double PriceSellLimit=0;
TryTimes=0;
while(true)
{
TryTimes++;
OperationDelay=0;
TimeToSend=GetTickCount();
if(TypeOfOrder==OP_BUY)
{
if(UseVirtualLevels==false)
{
SL_Buy=NormalizeDouble(Bid-(PipsLevelLoss*DigitsPoints),Digits);
if(PutTakeProfit==true)
TP_Buy=NormalizeDouble(Ask+(PipsLevelProfit*DigitsPoints),Digits);
}
TicketBuy=OrderSend(Symbol(),OP_BUY,LotSize,NormalizeDouble(Ask,Digits),Slippage,SL_Buy,TP_Buy,ExpertComments,MagicNumber,0,clrBlue);
if(TestingMode==true)
SendMessages++;
if(TicketBuy>0)
{
OperationDelay=GetTickCount()-TimeToSend;
if(OperationDelay>0)
{
LastOperationDelay=OperationDelay;
if(TicksGet<30)
TicksGet++;
if(CountAvgExecution==true)
CountAvrgExecution(OperationDelay);
}
break;
}
else
{
RefreshRates();
Print("Error: ",DoubleToStr(GetLastError(),0)+" || "+ExpertComments+": receives new data and try again open buy order");
if(TryTimes>=3)
break;
}
}
if(TypeOfOrder==OP_BUYLIMIT)
{
PriceBuyLimit=NormalizeDouble(Bid-((PipsLevelLoss+DistancePending)*DigitsPoints),Digits);
TicketBuyLimit=OrderSend(Symbol(),OP_BUYLIMIT,LotSize,PriceBuyLimit,Slippage,0,0,ExpertComments,MagicNumber,0,clrBlue);
if(TestingMode==true)
SendMessages++;
if(TicketBuyLimit>0)
{
OperationDelay=GetTickCount()-TimeToSend;
if(OperationDelay>0)
{
LastOperationDelay=OperationDelay;
if(TicksGet<30)
TicksGet++;
if(CountAvgExecution==true)
CountAvrgExecution(OperationDelay);
}
break;
}
else
{
RefreshRates();
Print("Error: ",DoubleToStr(GetLastError(),0)+" || "+ExpertComments+": receives new data and try again open buy limit order");
if(TryTimes>=3)
break;
}
}
if(TypeOfOrder==OP_SELL)
{
if(UseVirtualLevels==false)
{
SL_Sell=NormalizeDouble(Ask+(PipsLevelLoss*DigitsPoints),Digits);
if(PutTakeProfit==true)
TP_Sell=NormalizeDouble(Bid-(PipsLevelProfit*DigitsPoints),Digits);
}
TicketSell=OrderSend(Symbol(),OP_SELL,LotSize,NormalizeDouble(Bid,Digits),Slippage,SL_Sell,TP_Sell,ExpertComments,MagicNumber,0,clrRed);
if(TestingMode==true)
SendMessages++;
if(TicketSell>0)
{
OperationDelay=GetTickCount()-TimeToSend;
if(OperationDelay>0)
{
LastOperationDelay=OperationDelay;
if(TicksGet<30)
TicksGet++;
if(CountAvgExecution==true)
CountAvrgExecution(OperationDelay);
}
break;
}
else
{
RefreshRates();
Print("Error: ",DoubleToStr(GetLastError(),0)+" || "+ExpertComments+": receives new data and try again open sell order");
if(TryTimes>=3)
break;
}
}
if(TypeOfOrder==OP_SELLLIMIT)
{
PriceSellLimit=NormalizeDouble(Ask+((PipsLevelLoss+DistancePending)*DigitsPoints),Digits);
TicketSellLimit=OrderSend(Symbol(),OP_SELLLIMIT,LotSize,PriceSellLimit,Slippage,0,0,ExpertComments,MagicNumber,0,clrRed);
if(TestingMode==true)
SendMessages++;
if(TicketSellLimit>0)
{
OperationDelay=GetTickCount()-TimeToSend;
if(OperationDelay>0)
{
LastOperationDelay=OperationDelay;
if(TicksGet<30)
TicksGet++;
if(CountAvgExecution==true)
CountAvrgExecution(OperationDelay);
}
break;
}
else
{
RefreshRates();
Print("Error: ",DoubleToStr(GetLastError(),0)+" || "+ExpertComments+": receives new data and try again open sell limit order");
if(TryTimes>=3)
break;
}
}
}
}
void ModifyMarketOrders(int TypeOfOrder)
{
bool ModifyBuy=false;
bool ModifySell=false;
double SL_Buy=0;
double TP_Buy=0;
double SL_Sell=0;
double TP_Sell=0;
double OrderStopLossBuy=0;
double OrderStopLossSell=0;
double OrderTakeProfitBuy=0;
double OrderTakeProfitSell=0;
if(ChangeAsk==true)
CountTickModifyBuy++;
if(ChangeBid==true)
CountTickModifySell++;
if(UseVirtualLevels==true)
{
if((CntBuy>0) && (CntSell>0))
{
if((CntBuy>0) && (VirtualStopLossBuy>0) && ((VirtualTakeProfitBuy>0) || (PutTakeProfit==false)) && ((Bid<=VirtualStopLossBuy) || ((Bid>=VirtualTakeProfitBuy) && (PutTakeProfit==true))))
{
CloseOrders(OP_BUY);
VirtualStopLossBuy=0;
VirtualTakeProfitBuy=0;
return;
}
if((CntSell>0) && (VirtualStopLossSell>0) && ((VirtualTakeProfitSell>0) || (PutTakeProfit==false)) && ((Ask>=VirtualStopLossSell) || ((Ask<=VirtualTakeProfitSell) && (PutTakeProfit==true))))
{
CloseOrders(OP_SELL);
VirtualStopLossSell=0;
VirtualTakeProfitSell=0;
return;
}
}
}
for(i=0; i<OrdersTotal(); i++)
{
if(OrderSelect(i,SELECT_BY_POS)==true)
{
if((OrderMagicNumber()==MagicNumber) && (OrderSymbol()==Symbol()))
{
if(OrderType()==OP_BUY)
{
if(((CountTickModifyBuy>=DelayModifyOrders) || ((OrderStopLoss()==0) && (UseVirtualLevels==false)) || ((VirtualStopLossBuy==0) && (UseVirtualLevels==true))) && (TypeOfOrder==OP_BUY))
{
SL_Buy=NormalizeDouble(Bid-(PipsLevelLoss*DigitsPoints),Digits);
if(PutTakeProfit==true)
TP_Buy=NormalizeDouble(Ask+(PipsLevelProfit*DigitsPoints),Digits);
if(UseVirtualLevels==false)
{
OrderStopLossBuy=NormalizeDouble(OrderStopLoss(),Digits);
OrderTakeProfitBuy=NormalizeDouble(OrderTakeProfit(),Digits);
}
if(UseVirtualLevels==true)
{
OrderStopLossBuy=NormalizeDouble(VirtualStopLossBuy,Digits);
OrderTakeProfitBuy=NormalizeDouble(VirtualTakeProfitBuy,Digits);
}
if(((((PutTakeProfit==true) && (NormalizeDouble(OrderTakeProfitBuy,Digits)!=NormalizeDouble(TP_Buy,Digits)) &&
((NormalizeDouble(OrderTakeProfitBuy-Ask,Digits)<=NormalizeDouble(((PipsLevelProfit-PipsStepModify)*DigitsPoints),Digits)) ||
(NormalizeDouble(OrderTakeProfitBuy-Ask,Digits)>=NormalizeDouble(((PipsLevelProfit+PipsStepModify)*DigitsPoints),Digits)))) ||
((NormalizeDouble(OrderStopLossBuy,Digits)!=NormalizeDouble(SL_Buy,Digits)) &&
((NormalizeDouble(Bid-OrderStopLossBuy,Digits)<=NormalizeDouble(((PipsLevelLoss-PipsStepModify)*DigitsPoints),Digits)) ||
(NormalizeDouble(Bid-OrderStopLossBuy,Digits)>=NormalizeDouble(((PipsLevelLoss+PipsStepModify)*DigitsPoints),Digits)))))) ||
((OrderStopLoss()==0) && (UseVirtualLevels==false)) || ((VirtualStopLossBuy==0) && (UseVirtualLevels==true)))
{
if(UseVirtualLevels==true)
{
VirtualStopLossBuy=SL_Buy;
VirtualTakeProfitBuy=TP_Buy;
CountTickModifyBuy=0;
if(ShowVirtualLevels==true)
CreatLines(OP_BUY);
if((UsePendingOrders==true)&&(CntBuyLimit>0))
ModifyPendingOrders(OP_BUYLIMIT);
break;
}
if(UseVirtualLevels==false)
{
TryTimes=0;
while(true)
{
TryTimes++;
OperationDelay=0;
TimeToSend=GetTickCount();
ModifyBuy=OrderModify(OrderTicket(),0,SL_Buy,TP_Buy,0,clrBlue);
if(TestingMode==true)
SendMessages++;
if(ModifyBuy==true)
{
if((UsePendingOrders==true) && (CntBuyLimit>0))
ModifyPendingOrders(OP_BUYLIMIT);
CountTickModifyBuy=0;
OperationDelay=GetTickCount()-TimeToSend;
if(OperationDelay>0)
{
LastOperationDelay=OperationDelay;
if(TicksGet<30)
TicksGet++;
if(CountAvgExecution==true)
CountAvrgExecution(OperationDelay);
}
break;
}
else
{
RefreshRates();
SL_Buy=NormalizeDouble(Bid-(PipsLevelLoss*DigitsPoints),Digits);
if(PutTakeProfit==true)
Показано первые 50% кода (символов: 34315)