MARTINGALE VI HYBRID
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «martingale vi hybrid1.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Советник MetaTrader 4, реализующий стратегию мартингейла с фильтром направления по двум скользящим средним. При пересечении быстрой и медленной MA в определённом направлении открываются позиции. При неудачной сделке система увеличивает объём следующей сделки по заданному множителю, стремясь компенсировать убытки.
Советник отслеживает количество открытых позиций и при достижении максимального лимита закрывает все сделки данного направления, если соответствующий параметр включён. Также он модифицирует уровни стоп-лосса и тейк-профита на существующих ордерах.
Все сделки идентифицируются магическим номером и комментарием, что позволяет отделить ордера советника от других. Работа происходит на каждом новом баре, с учётом спреда и минимальных уровней стоп-лосса брокера.
Настройки программы
| Настройка | Описание |
|---|---|
| Take_Profit | Тейк-профит — Размер тейк-профита каждой сделки в пунктах. |
| PipStep | Шаг в пунктах — Расстояние в пунктах, при достижении которого открывается новая сделка. |
| Lotsize | Начальный лот — Начальный объём сделки, который удваивается на каждом шаге. |
| Multiply | Множитель — Множитель объёма для каждой следующей сделки в цепочке. |
| MaxTrade | Максимум сделок — Максимальное количество одновременно открытых сделок. |
| str5 | Метка быстрой MA — Текстовая метка, отображаемая в настройках для группы быстрой скользящей средней. |
| Period1 | Период быстрой MA — Период быстрой скользящей средней в пунктах. |
| str6 | Метка медленной MA — Текстовая метка, отображаемая в настройках для группы медленной скользящей средней. |
| Period2 | Период медленной MA — Период медленной скользящей средней в пунктах. |
| CLOSEMAXORDERS | Закрытие при максимуме — Флаг автоматического закрытия всех сделок при достижении максимального лимита. |
| MagicNumber | Магический номер — Идентификатор ордеров, открытых данным советником. |
Поиск по коду файла
#property version "1.01"
#property strict
/*-- These variables are shown in the EA and can be changed --*/
extern int Take_Profit = 10; // TP value of each trade in this Martingale EA
extern int PipStep = 10; // Distance in pips which will open a new trade
extern double Lotsize=0.01; // The value of the initial lots , will be duplicated every step
extern double Multiply=2.0; // Multiplier value every step of new trade
extern int MaxTrade= 4; // Maximum trades that can run
input string str5="Fast moving average";
input int Period1=1; //Fast moving average(in pips)
input string str6="Slow moving average";
input int Period2=50; //Slow moving average(in pips)
extern bool CLOSEMAXORDERS=true; // Close Maximum Orders
extern int MagicNumber=8095; // Magic Number
double SetPoint=0; // Variable SetPoint to code 4 or 5 digit brokers
double pips;
int T=0;
int Count_one_message=0;
int Tp,err,ntp,result;
double priceopen,stoploss,takeprofit;
/*--These parameters are to be displayed on the screen --*/
string EAName = "Martingale ver 1.0"; // EA name , to be displayed on the screen
string EAComment = "Martingale"; // This variable will we put in each trade as a Comment
int OnInit()
{
// код доступен только после оплаты
}
void OnDeinit(const int reason)
{
}
void OnTick()
{
// код доступен только после оплаты
}
int trade()
{
if(iMA(Symbol(),0,Period1,0,0,0,1)<iMA(Symbol(),0,Period2,0,0,0,1))//BUY
{return(1);}
else if(iMA(Symbol(),0,Period1,0,0,0,1)>iMA(Symbol(),0,Period2,0,0,0,1))//SELL
{return(2);}
return(0);
}
int MARTINGALE_BUY()
{
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderComment()==EAComment && OrderMagicNumber()== MagicNumber)
{
return(0);
}
}
}
int ticket=0;
static datetime dtBarCurrent=WRONG_VALUE;
datetime dtBarPrevious=dtBarCurrent;
dtBarCurrent=(datetime) SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE);
bool NewBarFlag=(dtBarCurrent!=dtBarPrevious);
int total=0;
if(Bars<100)
{
Print("bars less than 100");
return(0);
}
if(IsTradeAllowed()==false)
{
Print("Trade IS NOT Allowed");
return(0);
}
{
int stops_level=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
int iTrade=0;
for(int i=OrdersTotal()-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))Print("eror");//Check if there is an open trade on the current pair
if(OrderSymbol()==Symbol()) total++;//Count total trades
if(total>MaxTrade && CLOSEMAXORDERS==true)
{
exitbuys();
return(0);
}
}
if (!openorderthispair(Symbol())>=1)
{
if(((AccountStopoutMode()==1) &&
(AccountFreeMarginCheck(Symbol(),OP_BUY,Lotsize)>AccountStopoutLevel()))
|| ((AccountStopoutMode()==0) &&
((AccountEquity()/(AccountEquity()-AccountFreeMarginCheck(Symbol(),OP_BUY,Lotsize))*100)>AccountStopoutLevel())))
if(CheckMoneyForTrade(Symbol(),LotsOptimized(Lotsize),OP_BUY))
if(!OrderSend(Symbol(),OP_BUY,LotsOptimized(Lotsize),ND(Ask),3,0,NDTP(Ask+Take_Profit*pips),EAComment, MagicNumber))
Print("eror",GetLastError());
}
/* -- This is the function of Martingale . If there OP is wrong , then do martingale --*/
if(OrdersTotal()>=1)
{
if(NewBarFlag)
GoMartingalebuy();
}
return(0);
}
}
bool GoMartingalebuy()
{
int iCount = 0;
double LastOP = 0;
double LastLots = 0;
bool LastIsBuy = FALSE;
int iTotalBuy = 0;
int iTotalSell = 0;
double Spread=0;
Spread=MarketInfo(Symbol(),MODE_SPREAD);
for(iCount=0;iCount<OrdersTotal();iCount++)
{
if(!OrderSelect(iCount,SELECT_BY_POS,MODE_TRADES))
Print("eror");
if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderComment()==EAComment && OrderMagicNumber()== MagicNumber)
{
if(LastOP==0) {LastOP=OrderOpenPrice();}
if(LastOP>OrderOpenPrice()) {LastOP=OrderOpenPrice();}
if(LastLots<OrderLots()) {LastLots=OrderLots();}
LastIsBuy=TRUE;
iTotalBuy++;
if(iTotalBuy==MaxTrade)
{
if(CLOSEMAXORDERS==1)
{
exitbuys();
return(0);
}
}
}
}
/* If the Price is downtrend .... direction , check the Bid (*/
if(LastIsBuy)
{
if(Bid<=LastOP-(Spread*pips)-(PipStep*pips))
{
if(((AccountStopoutMode()==1) &&
(AccountFreeMarginCheck(Symbol(),OP_BUY,Lotsize)>AccountStopoutLevel()))
|| ((AccountStopoutMode()==0) &&
((AccountEquity()/(AccountEquity()-AccountFreeMarginCheck(Symbol(),OP_BUY,Lotsize))*100)>AccountStopoutLevel())))
if(CheckMoneyForTrade(Symbol(),LotsOptimized(Multiply*LastLots),OP_BUY))
if(!OrderSend(Symbol(),OP_BUY,LotsOptimized(Multiply*LastLots),ND(Ask),3,0,NDTP(Ask+Take_Profit*pips),EAComment, MagicNumber))
Print("eror",GetLastError());
ModifyTPbuy();
LastIsBuy=FALSE;
return(0);
}
}
return(0);
}
int MARTINGALE_SELL()
{
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderComment()==EAComment && OrderMagicNumber()== MagicNumber)
{
return(0);
}
}
}
int ticket=0;
static datetime dtBarCurrent=WRONG_VALUE;
datetime dtBarPrevious=dtBarCurrent;
dtBarCurrent=(datetime) SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE);
bool NewBarFlag=(dtBarCurrent!=dtBarPrevious);
int total=0;
if(Bars<100)
{
Print("bars less than 100");
return(0);
}
if(IsTradeAllowed()==false)
{
Print("Trade IS NOT Allowed");
return(0);
}
{
int stops_level=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
int iTrade=0;
Comment(EAName); // Show Name EA on screen
/* --If no OP at all , then perform the following functions --*/
/* -- This is where you insert coding indicators to trigger OP --*/
for(int i=OrdersTotal()-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))Print("eror");//Check if there is an open trade on the current pair
if(OrderSymbol()==Symbol()) total++;//Count total trades
if(total>MaxTrade && CLOSEMAXORDERS==true)
{
exitsells();
return(0);
}
}
if (!openorderthispair(Symbol())>=1)
{
if(((AccountStopoutMode()==1) &&
(AccountFreeMarginCheck(Symbol(),OP_SELL,Lotsize)>AccountStopoutLevel()))
|| ((AccountStopoutMode()==0) &&
((AccountEquity()/(AccountEquity()-AccountFreeMarginCheck(Symbol(),OP_SELL,Lotsize))*100)>AccountStopoutLevel())))
if(CheckMoneyForTrade(Symbol(),LotsOptimized(Lotsize),OP_SELL))
if(!OrderSend(Symbol(),OP_SELL,LotsOptimized(Lotsize),ND(Bid),3,0,NDTP(Bid-Take_Profit*pips),EAComment, MagicNumber))
Print("eror",GetLastError());
}
/* -- This is the function of Martingale . If there OP is wrong , then do martingale --*/
if(OrdersTotal()>=1)
{
if(NewBarFlag)
GoMartingalesell();
}
return(0);
}
}
bool GoMartingalesell()
{
int iCount = 0;
double LastOP = 0;
double LastLots = 0;
bool LastIsBuy = FALSE;
int iTotalBuy = 0;
int iTotalSell = 0;
double Spread=0;
Spread=MarketInfo(Symbol(),MODE_SPREAD);
for(iCount=0;iCount<OrdersTotal();iCount++)
{
if(!OrderSelect(iCount,SELECT_BY_POS,MODE_TRADES))
Print("eror");
if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderComment()==EAComment && OrderMagicNumber()== MagicNumber)
{
if(LastOP==0) {LastOP=OrderOpenPrice();}
if(LastOP<OrderOpenPrice()) {LastOP=OrderOpenPrice();}
if(LastLots<OrderLots()) {LastLots=OrderLots();}
LastIsBuy=FALSE;
iTotalSell++;
if(iTotalSell==MaxTrade) //{return(0);}
{
if(CLOSEMAXORDERS==1)
{
Показано первые 50% кода (символов: 13805)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.