Советник торгующий по "Волнам Вульфа". |
Обзоры торговых систем |
Тестирование ТС. Неделя 1. |
Гридеры. |
//+------------------------------------------------------------------+
//| Proffessor_v1_2011.mq4 |
//| Copyright © 2011, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2011, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"
extern double lot = 0.1; //лот
extern int MAX_Lines = 5; //максимальное колличество отложенных ордеров каждого направления
extern double klot = 1; //коэффициент умножения лотов при удалении от цены
extern double pluslot = 0.1; //коэффициент доливки лота при удалении от цены
extern int plusDelta = -5; //коэффициент увеличения расстояния между отложенными ордерами
//если значение отрицательное, то расстояние уменьшается на данное кол-во пунктов
extern double Delta1 = 70; //первая дельта от цены для стопового ордера
extern int Delta = 60; //расстояние между отложенными ордерами
extern double ProfitClose = 0.8; //закрывать все ордера при получении профита(в долларах)
extern double f = 40; //параметр границы флета по ADX
extern double bar = 2; //сдвиг по барам ADX
extern double timeframe = 1; //таймфрейм для индикатора ADX 0-текущий,1-1минута, 2-5минут, 3-15минут, 4-30минут, 5-1час
//6-4часа, 7-день, 8-неделя, 9-месяц
extern int magic = 123; //магик
extern int StartHour = 0; //час начала работы советника
extern int EndHour = 24; //час окончания работы советника
extern int pop = 3; //количество попыток закрыть ордер
int init() {
Comment("ProfessorSoft_v3_2011");
return (0);
}
int deinit() {
Comment("");
return (0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----
bool ticket;
double Lots;
int x,q;
bool trade=false;
trade=true;
double iflet,ibuy,isell;
int _timeframe;
if(timeframe==1)_timeframe=1;
else if(timeframe==0)_timeframe=0;
else if(timeframe==2)_timeframe=5;
else if(timeframe==3)_timeframe=15;
else if(timeframe==4)_timeframe=30;
else if(timeframe==5)_timeframe=60;
else if(timeframe==6)_timeframe=240;
else if(timeframe==7)_timeframe=1440;
else if(timeframe==8)_timeframe=10080;
else _timeframe=43200;
if(OrdersTotal()==0 && trade==true && time()==true)
{
ticket=-1;
iflet=iADX( Symbol(), _timeframe, 14, PRICE_CLOSE,MODE_MAIN, bar);
ibuy=iADX( Symbol(), _timeframe, 14, PRICE_CLOSE,MODE_PLUSDI, bar);
isell=iADX( Symbol(), _timeframe, 14, PRICE_CLOSE,MODE_MINUSDI, bar);
if(iflet<f && ibuy>isell)//условие для покупки и определение флета
{
Lots=lot;
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,0,"",magic,0,Blue);
if(ticket==-1)return(0);
OrderSend(Symbol(),OP_SELLSTOP,Lots,Bid-Delta1*Point,3,0,0,"",magic,0,Red);
for(x=1;x<=MAX_Lines;x++)
{
Lots=NormalizeDouble(Lots*klot,2)+pluslot;
OrderSend(Symbol(),OP_BUYLIMIT,Lots,Ask-(Delta1+x*NormalizeDouble(Delta+plusDelta*x/2,0))*Point,3,0,0,"",magic,0,Blue);
OrderSend(Symbol(),OP_SELLLIMIT,Lots,Bid+x*NormalizeDouble(Delta+plusDelta*x/2,0)*Point,3,0,0,"",magic,0,Red);
}
}
else if(iflet<f && ibuy<isell)//условие для продажи и определение флета
{
Lots=lot;
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,0,"",magic,0,Red);
if(ticket==-1)return(0);
OrderSend(Symbol(),OP_BUYSTOP,Lots,Ask+Delta1*Point,3,0,0,"",magic,0,Blue);
for(x=1;x<=MAX_Lines;x++)
{
Lots=NormalizeDouble(Lots*klot,2)+pluslot;
OrderSend(Symbol(),OP_BUYLIMIT,Lots,Ask-x*NormalizeDouble(Delta+plusDelta*x/2,0)*Point,3,0,0,"",magic,0,Blue);
OrderSend(Symbol(),OP_SELLLIMIT,Lots,Bid+(Delta1+x*NormalizeDouble(Delta+plusDelta*x/2,0))*Point,3,0,0,"",magic,0,Red);
}
}
else if(iflet>f && ibuy>isell)//условие для покупки и определение тренда
{
Lots=lot;
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,0,"",magic,0,Blue);
if(ticket==-1)return(0);
OrderSend(Symbol(),OP_SELLSTOP,Lots,Bid-Delta1*Point,3,0,0,"",magic,0,Red);
for(x=1;x<=MAX_Lines;x++)
{
Lots=NormalizeDouble(Lots*klot,2)+pluslot;
OrderSend(Symbol(),OP_SELLSTOP,Lots,Bid-(Delta1+x*NormalizeDouble(Delta+plusDelta*x/2,0))*Point,3,0,0,"",magic,0,Blue);
OrderSend(Symbol(),OP_BUYSTOP,Lots,Ask+x*NormalizeDouble(Delta+plusDelta*x/2,0)*Point,3,0,0,"",magic,0,Red);
}
}
else if(iflet>f && ibuy<isell)//условие для продажи и определение тренда
{
Lots=lot;
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,0,"",magic,0,Red);
if(ticket==-1)return(0);
OrderSend(Symbol(),OP_BUYSTOP,Lots,Ask+Delta1*Point,3,0,0,"",magic,0,Blue);
for(x=1;x<=MAX_Lines;x++)
{
Lots=NormalizeDouble(Lots*klot,2)+pluslot;
OrderSend(Symbol(),OP_SELLSTOP,Lots,Bid-x*NormalizeDouble(Delta+plusDelta*x/2,0)*Point,3,0,0,"",magic,0,Blue);
OrderSend(Symbol(),OP_BUYSTOP,Lots,Ask+(Delta1+x*NormalizeDouble(Delta+plusDelta*x/2,0))*Point,3,0,0,"",magic,0,Red);
}
}
else return(0);
}
if(OrdersTotal()>0)
{
Comment(" Balance ",AccountBalance(),"\n Equity ",AccountEquity(),"\n Profit ",OrdersProfit());
if(OrdersProfit()>=ProfitClose)
{
for (int i=OrdersTotal()-1;i>=0;i--)
{
bool closed;
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if(OrderType()==OP_BUY)
{
for(q=0;q<pop;q++)
{
closed=false;
closed=OrderClose(OrderTicket(),OrderLots(),Bid,3,Blue);
if(closed==true)q=pop;
}
}
if(OrderType()==OP_SELL)
{
for(q=0;q<pop;q++)
{
closed=false;
closed=OrderClose(OrderTicket(),OrderLots(),Ask,3,Red);
if(closed==true)q=pop;
}
}
Sleep(1000);
if(OrderType()>1 ) OrderDelete(OrderTicket());
}
}
}
//----
return(0);
}
//+------------------------------------------------------------------+
bool time()
{
if (StartHour<EndHour)
{if (Hour()>=StartHour && Hour()<EndHour) return(true); else return(false);}
if (StartHour>EndHour)
{if (Hour()>=EndHour && Hour()<StartHour) return(false); else return(true);}
}
double OrdersProfit()
{
double rezultSymb=0;
string SMB=Symbol();
int i;
for (i=OrdersTotal()-1;i>=0;i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == true)
{
if(OrderSymbol()!= SMB) continue;
if(OrderType()==OP_BUY || OrderType()==OP_SELL)
{
rezultSymb+=OrderProfit();
}
}
}
return(rezultSymb);
}
Тестирование эксперта MoneyPrinter |
Пишем усреднитель. |
if (TradeNow && total<1){
double PrevCl = iClose(Symbol(),0,2);
double CurrCl = iClose(Symbol(),0,1);
SellLimit = Bid;
BuyLimit = Ask;
if(!ShortTrade && !LongTrade){
NumOfTrades = total;
if(PrevCl > CurrCl){
iLots = fGetLots(OP_SELL);
if(iLots>0){//#
ticket = OpenPendingOrder(OP_SELL,iLots,SellLimit,slip,SellLimit,0,0,EAName+"-"+NumOfTrades,MagicNumber,0,HotPink);
if(ticket<0){Print(iLots,"Error: ",GetLastError()); return(0);}
LastBuyPrice = FindLastBuyPrice();
NewOrdersPlaced = true;
}//#
}
else{
iLots = fGetLots(OP_BUY);
if(iLots>0){//#
ticket = OpenPendingOrder(OP_BUY,iLots,BuyLimit,slip,BuyLimit,0,0,EAName+"-"+NumOfTrades,MagicNumber,0,Lime);
if(ticket<0){Print(iLots,"Error: ",GetLastError()); return(0);}
LastSellPrice = FindLastSellPrice();
NewOrdersPlaced = true;
}//#
}
}
if(ticket>0) expiration = CurTime()+MaxTradeOpenHours*60*60;
TradeNow = false;
}
if (TradeNow && total<1){
SellLimit = Bid;
BuyLimit = Ask;
if(!ShortTrade && !LongTrade && Hour()==0)
{
NumOfTrades = total;
{
iLots = fGetLots(OP_SELL);
if(iLots>0){//#
ticket = OpenPendingOrder(OP_SELL,iLots,SellLimit,slip,SellLimit,0,Bid-TakeProfit*Point,EAName+"-"+NumOfTrades,MagicNumber,0,HotPink);
if(ticket<0){Print(iLots,"Error: ",GetLastError()); return(0);}
LastBuyPrice = FindLastBuyPrice();
NewOrdersPlaced = true;
}//#
}
{
iLots = fGetLots(OP_BUY);
if(iLots>0){//#
ticket = OpenPendingOrder(OP_BUY,iLots,BuyLimit,slip,BuyLimit,0,Ask+TakeProfit*Point,EAName+"-"+NumOfTrades,MagicNumber,0,Lime);
if(ticket<0){Print(iLots,"Error: ",GetLastError()); return(0);}
LastSellPrice = FindLastSellPrice();
NewOrdersPlaced = true;
}//#
}
}
if(ticket>0) expiration = CurTime()+MaxTradeOpenHours*60*60;
TradeNow = false;
}
//+------------------------------------------------------------------+
//| 2008 Ilan1.4 |
//+------------------------------------------------------------------+
#property copyright "Nikisaki@yandex.ru"
extern int MMType=1; // Тип ММ: 0-Lots, 1-как было в 1.2, 2-мартингейл (коэффициент LotExponent)
extern bool UseClose=false; // закрытие по убытку PipStep. рекомендутся false
extern bool UseAdd=true; // переоткрытие с новым лотом. лот для переоткрытия считается по LotExponent независимо от MMType рекомендутся = true
extern double LotExponent = 1.667; // умножение лотов в серии по експоненте для вывода в безубыток. первый лот 0.1, серия: 0.16, 0.26, 0.43 ...
extern double slip = 3; // допустимое проскальзывание цены в пипсах
extern double Lots = 0.1; // теперь можно и микролоты 0.01 при этом если стоит 0.1 то следующий лот в серии будет 0.16
extern double LotsDigits=2; // 2 - микролоты 0.01, 1 - мини лоты 0.1, 0 - нормальные лоты 1.0
extern double TakeProfit = 10; // Уровень прибыли в пипсаз от цены открытия.
double Stoploss = 500; // эти три параметра не работают
double TrailStart = 10;
double TrailStop = 10;
extern double PipStep = 30; // растоянию в пипсах убытка на котором открываеться следующий ордер колена.
extern int MaxTrades = 10;
extern bool UseEquityStop = false;
extern double TotalEquityRisk = 20; //loss as a percentage of equity
extern bool UseTrailingStop = false;
extern bool UseTimeOut = false;
extern double MaxTradeOpenHours = 48;
int MagicNumber = 12324;
double PriceTarget, StartEquity, BuyTarget, SellTarget;
double AveragePrice, SellLimit, BuyLimit;
double LastBuyPrice, LastSellPrice, ClosePrice, Spread;
int flag;
string EAName = "CostAvg-Pyramid";
datetime timeprev=0, expiration;
int NumOfTrades=0;
double iLots;
int cnt=0, total;
double Stopper=0;
bool TradeNow = false, LongTrade=false, ShortTrade=false;
int ticket;
bool NewOrdersPlaced = false;
int init()
{
Spread = MarketInfo(Symbol(), MODE_SPREAD)*Point;
return(0);
}
int deinit()
{
return(0);
}
int start(){
if (UseTrailingStop){
TrailingAlls(TrailStart, TrailStop, AveragePrice);
}
if (UseTimeOut){
if(CurTime() >= expiration){
CloseThisSymbolAll();
Print("Closed All due to TimeOut");
}
}
if(timeprev==Time[0]){
return(0);
}
timeprev=Time[0];
double CurrentPairProfit = CalculateProfit();
if(UseEquityStop){
if(CurrentPairProfit<0 && MathAbs(CurrentPairProfit)>(TotalEquityRisk/100)*AccountEquityHigh()){
CloseThisSymbolAll();
Print("Closed All due to Stop Out");
NewOrdersPlaced = false;
}
}
total=CountTrades();
if (total == 0){
flag = 0;
}
double LastBuyLots;
double LastSellLots;
for(cnt=OrdersTotal()-1;cnt>=0;cnt--){// поиск последнего направления
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)continue;
if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
if(OrderType()==OP_BUY){
LongTrade = true;
ShortTrade = false;
LastBuyLots=OrderLots();
break;
}
if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
if(OrderType()==OP_SELL){
LongTrade = false;
ShortTrade = true;
LastSellLots=OrderLots();
break;
}
}
if(total>0 && total <= MaxTrades){
RefreshRates();
LastBuyPrice = FindLastBuyPrice();
LastSellPrice = FindLastSellPrice();
if(LongTrade && (LastBuyPrice - Ask) >= (PipStep*Point)){
TradeNow = true;
}
if(ShortTrade && (Bid - LastSellPrice) >= (PipStep*Point)){
TradeNow = true;
}
}
if (total < 1){
ShortTrade = false;
LongTrade = false;
TradeNow = true;
StartEquity = AccountEquity();
}
if (TradeNow){
LastBuyPrice = FindLastBuyPrice();
LastSellPrice = FindLastSellPrice();
if(ShortTrade){
if(UseClose){
fOrderCloseMarket(false,true);
iLots = NormalizeDouble(LotExponent*LastSellLots,LotsDigits);
}
else{
iLots = fGetLots(OP_SELL);
}
if(UseAdd){
NumOfTrades = total;
if(iLots>0){//#
RefreshRates();
ticket = OpenPendingOrder(OP_SELL,iLots,Bid,slip,Ask,0,0,EAName+"-"+NumOfTrades,MagicNumber,0,HotPink);
if(ticket<0){Print("Error: ",GetLastError()); return(0);}
LastSellPrice = FindLastSellPrice();
TradeNow = false;
NewOrdersPlaced = true;
}//#
}
}
else if (LongTrade){
if(UseClose){
fOrderCloseMarket(true,false);
iLots = NormalizeDouble(LotExponent*LastBuyLots,LotsDigits);
}
else{
iLots = fGetLots(OP_BUY);
}
if(UseAdd){
NumOfTrades = total;
if(iLots>0){//#
ticket = OpenPendingOrder(OP_BUY,iLots,Ask,slip,Bid,0,0,EAName+"-"+NumOfTrades,MagicNumber,0,Lime);
if(ticket<0){Print("Error: ",GetLastError()); return(0);}
LastBuyPrice = FindLastBuyPrice();
TradeNow = false;
NewOrdersPlaced = true;
}//#
}
}
}
if (TradeNow && total<1){
SellLimit = Bid;
BuyLimit = Ask;
if(!ShortTrade && !LongTrade && Hour()==0)
{
NumOfTrades = total;
{
iLots = fGetLots(OP_SELL);
if(iLots>0){//#
ticket = OpenPendingOrder(OP_SELL,iLots,SellLimit,slip,SellLimit,0,Bid-TakeProfit*Point,EAName+"-"+NumOfTrades,MagicNumber,0,HotPink);
if(ticket<0){Print(iLots,"Error: ",GetLastError()); return(0);}
LastBuyPrice = FindLastBuyPrice();
NewOrdersPlaced = true;
}//#
}
{
iLots = fGetLots(OP_BUY);
if(iLots>0){//#
ticket = OpenPendingOrder(OP_BUY,iLots,BuyLimit,slip,BuyLimit,0,Ask+TakeProfit*Point,EAName+"-"+NumOfTrades,MagicNumber,0,Lime);
if(ticket<0){Print(iLots,"Error: ",GetLastError()); return(0);}
LastSellPrice = FindLastSellPrice();
NewOrdersPlaced = true;
}//#
}
}
if(ticket>0) expiration = CurTime()+MaxTradeOpenHours*60*60;
TradeNow = false;
}
//----------------------- CALCULATE AVERAGE OPENING PRICE
total=CountTrades();
AveragePrice=0;
double Count = 0;
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
if(OrderType()==OP_BUY || OrderType()==OP_SELL)
{
AveragePrice=AveragePrice+OrderOpenPrice()*OrderLots();
Count = Count + OrderLots();
}
}
if(total > 0)
AveragePrice=NormalizeDouble(AveragePrice/Count, Digits);
//----------------------- RECALCULATE STOPLOSS & PROFIT TARGET BASED ON AVERAGE OPENING PRICE
if(NewOrdersPlaced)
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
if(OrderType()==OP_BUY) // Calculate profit/stop target for long
{
PriceTarget=AveragePrice+(TakeProfit*Point);
BuyTarget = PriceTarget;
Stopper=AveragePrice-(Stoploss*Point);
// Stopper=0;
flag = 1;
}
if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
if(OrderType()==OP_SELL) // Calculate profit/stop target for short
{
PriceTarget=AveragePrice-(TakeProfit*Point);
SellTarget = PriceTarget;
Stopper=AveragePrice+(Stoploss*Point);
// Stopper=0;
flag = 1;
}
}
//----------------------- IF NEEDED CHANGE ALL OPEN ORDERS TO NEWLY CALCULATED PROFIT TARGET
if(NewOrdersPlaced)
if(flag==1)// check if average has really changed
{
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{
// PriceTarget=total;
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
// OrderModify(OrderTicket(),0,Stopper,PriceTarget,0,Yellow);// set all positions to averaged levels
OrderModify(OrderTicket(),AveragePrice,OrderStopLoss(),PriceTarget,0,Yellow);// set all positions to averaged levels
NewOrdersPlaced = false;
}
}
}
double ND(double v){return(NormalizeDouble(v,Digits));}
int fOrderCloseMarket(bool aCloseBuy=true,bool aCloseSell=true){
int tErr=0;
for(int i=OrdersTotal()-1;i>=0;i--){
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber){
if(OrderType()==OP_BUY && aCloseBuy){
RefreshRates();
if(!IsTradeContextBusy()){
if(!OrderClose(OrderTicket(),OrderLots(),ND(Bid),5,CLR_NONE)){
Print("Error close BUY "+OrderTicket());//+" "+fMyErDesc(GetLastError()));
tErr=-1;
}
}
else{
static int lt1=0;
if(lt1!=iTime(NULL,0,0)){
lt1=iTime(NULL,0,0);
Print("Need close BUY "+OrderTicket()+". Trade Context Busy");
}
return(-2);
}
}
if(OrderType()==OP_SELL && aCloseSell){
RefreshRates();
if(!IsTradeContextBusy()){
if(!OrderClose(OrderTicket(),OrderLots(),ND(Ask),5,CLR_NONE)){
Print("Error close SELL "+OrderTicket());//+" "+fMyErDesc(GetLastError()));
tErr=-1;
}
}
else{
static int lt2=0;
if(lt2!=iTime(NULL,0,0)){
lt2=iTime(NULL,0,0);
Print("Need close SELL "+OrderTicket()+". Trade Context Busy");
}
return(-2);
}
}
}
}
}
return(tErr);
}
double fGetLots(int aTradeType){
double tLots;
switch(MMType){
case 0:
tLots=Lots;
break;
case 1:
tLots=NormalizeDouble(Lots*MathPow(LotExponent,NumOfTrades),LotsDigits);
break;
case 2:
int LastClosedTime=0;
tLots=Lots;
for(int i=OrdersHistoryTotal()-1;i>=0;i--){
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)){
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber){
if(LastClosedTime<OrderCloseTime()){
LastClosedTime=OrderCloseTime();
if(OrderProfit()<0){
tLots=NormalizeDouble(OrderLots()*LotExponent,LotsDigits);
}
else{
tLots=Lots;
}
}
}
}
else{
return(-3);
}
}
break;
}
if(AccountFreeMarginCheck(Symbol(),aTradeType,tLots)<=0){
return(-1);
}
if(GetLastError()==134){
return(-2);
}
return(tLots);
}
int CountTrades()
{
int count=0;
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
if(OrderType()==OP_SELL || OrderType()==OP_BUY)
count++;
}//for
return(count);
}
void CloseThisSymbolAll()
{
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()!=Symbol())
continue;
if(OrderSymbol()==Symbol() && OrderMagicNumber()== MagicNumber)
{
if(OrderType()==OP_BUY)
OrderClose(OrderTicket(),OrderLots(),Bid,slip,Blue);
if(OrderType()==OP_SELL)
OrderClose(OrderTicket(),OrderLots(),Ask,slip,Red);
}
Sleep(1000);
}
}
int OpenPendingOrder(int pType,double pLots,double pLevel,int sp, double pr, int sl, int tp,string pComment,int pMagic,datetime pExpiration,color pColor)
{
int ticket=0;
int err=0;
int c = 0;
int NumberOfTries = 100;
switch (pType)
{
case OP_BUYLIMIT:
for(c = 0 ; c < NumberOfTries ; c++)
{
ticket=OrderSend(Symbol(),OP_BUYLIMIT,pLots,pLevel,sp,StopLong(pr,sl),TakeLong(pLevel,tp),pComment,pMagic,pExpiration,pColor);
err=GetLastError();
if(err==0)
{
break;
}
else
{
if(err==4 || err==137 ||err==146 || err==136) //Busy errors
{
Sleep(1000);
continue;
}
else //normal error
{
break;
}
}
}
break;
case OP_BUYSTOP:
for(c = 0 ; c < NumberOfTries ; c++)
{
ticket=OrderSend(Symbol(),OP_BUYSTOP,pLots,pLevel,sp,StopLong(pr,sl),TakeLong(pLevel,tp),pComment,pMagic,pExpiration,pColor);
err=GetLastError();
if(err==0)
{
break;
}
else
{
if(err==4 || err==137 ||err==146 || err==136) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
break;
}
}
}
break;
case OP_BUY:
for(c = 0 ; c < NumberOfTries ; c++)
{
RefreshRates();
ticket=OrderSend(Symbol(),OP_BUY,pLots,Ask,sp,StopLong(Bid,sl),TakeLong(Ask,tp),pComment,pMagic,pExpiration,pColor);
err=GetLastError();
if(err==0)
{
break;
}
else
{
if(err==4 || err==137 ||err==146 || err==136) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
break;
}
}
}
break;
case OP_SELLLIMIT:
for(c = 0 ; c < NumberOfTries ; c++)
{
ticket=OrderSend(Symbol(),OP_SELLLIMIT,pLots,pLevel,sp,StopShort(pr,sl),TakeShort(pLevel,tp),pComment,pMagic,pExpiration,pColor);
err=GetLastError();
if(err==0)
{
break;
}
else
{
if(err==4 || err==137 ||err==146 || err==136) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
break;
}
}
}
break;
case OP_SELLSTOP:
for(c = 0 ; c < NumberOfTries ; c++)
{
ticket=OrderSend(Symbol(),OP_SELLSTOP,pLots,pLevel,sp,StopShort(pr,sl),TakeShort(pLevel,tp),pComment,pMagic,pExpiration,pColor);
err=GetLastError();
if(err==0)
{
break;
}
else
{
if(err==4 || err==137 ||err==146 || err==136) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
break;
}
}
}
break;
case OP_SELL:
for(c = 0 ; c < NumberOfTries ; c++)
{
ticket=OrderSend(Symbol(),OP_SELL,pLots,Bid,sp,StopShort(Ask,sl),TakeShort(Bid,tp),pComment,pMagic,pExpiration,pColor);
err=GetLastError();
if(err==0)
{
break;
}
else
{
if(err==4 || err==137 ||err==146 || err==136) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
break;
}
}
}
break;
}
return(ticket);
}
double StopLong(double price,int stop)
{
if(stop==0)
return(0);
else
return(price-(stop*Point));
}
double StopShort(double price,int stop)
{
if(stop==0)
return(0);
else
return(price+(stop*Point));
}
double TakeLong(double price,int take)
{
if(take==0)
return(0);
else
return(price+(take*Point));
}
double TakeShort(double price,int take)
{
if(take==0)
return(0);
else
return(price-(take*Point));
}
double CalculateProfit()
{
double Profit=0;
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
if(OrderType()==OP_BUY || OrderType()==OP_SELL)
{
Profit=Profit+OrderProfit();
}
}
return(Profit);
}
void TrailingAlls(int start,int stop, double AvgPrice)
{
int profit;
double stoptrade;
double stopcal;
if(stop==0)
return;
int trade;
for(trade=OrdersTotal()-1;trade>=0;trade--)
{
if(!OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))
continue;
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol()||OrderMagicNumber()==MagicNumber)
{
if(OrderType()==OP_BUY)
{
profit=NormalizeDouble((Bid-AvgPrice)/Point,0);
if(profit<start)
continue;
stoptrade=OrderStopLoss();
stopcal=Bid-(stop*Point);
if(stoptrade==0||(stoptrade!=0&&stopcal>stoptrade))
// OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Blue);
OrderModify(OrderTicket(),AvgPrice,stopcal,OrderTakeProfit(),0,Aqua);
}//Long
if(OrderType()==OP_SELL)
{
profit=NormalizeDouble((AvgPrice-Ask)/Point,0);
if(profit<start)
continue;
stoptrade=OrderStopLoss();
stopcal=Ask+(stop*Point);
if(stoptrade==0||(stoptrade!=0&&stopcal<stoptrade))
// OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Red);
OrderModify(OrderTicket(),AvgPrice,stopcal,OrderTakeProfit(),0,Red);
}//Shrt
}
Sleep(1000);
}//for
}
double AccountEquityHigh()
{
static double AccountEquityHighAmt,PrevEquity;
if(CountTrades()==0) AccountEquityHighAmt=AccountEquity();
if(AccountEquityHighAmt < PrevEquity) AccountEquityHighAmt=PrevEquity;
else AccountEquityHighAmt=AccountEquity();
PrevEquity = AccountEquity();
return(AccountEquityHighAmt);
}
double FindLastBuyPrice()
{
double oldorderopenprice = 0, orderprice;
int cnt, oldticketnumber = 0, ticketnumber;
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderType()==OP_BUY)
{
ticketnumber = OrderTicket();
if(ticketnumber>oldticketnumber)
{
orderprice=OrderOpenPrice();
oldorderopenprice=orderprice;
oldticketnumber=ticketnumber;
}
}
}
return(orderprice);
}
double FindLastSellPrice()
{
double oldorderopenprice = 0, orderprice;
int cnt, oldticketnumber = 0, ticketnumber;
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
continue;
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderType()==OP_SELL)
{
ticketnumber = OrderTicket();
if(ticketnumber>oldticketnumber)
{
orderprice=OrderOpenPrice();
oldorderopenprice=orderprice;
oldticketnumber=ticketnumber;
}
}
}
return(orderprice);
}
Добавим функцию Мартингейла к советнику. |
//+------------------------------------------------------------------+
//| WellX.mq4 |
//| Copyright © 2011, AM2 |
//| http://www.forexsystems.biz |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2011, AM2"
#property link "http://www.forexsystems.biz"
#define MAGIC 20111010
extern double StopLoss = 400;
extern double TakeProfit = 800;
extern double ADXPeriod = 14;
extern double BBPeriod = 20;
extern double BBDev = 2;
extern int Level = 30;
extern double Lots = 1;
bool b=true, s=true;
//+------------------------------------------------------------------+
int start()
{
//---- go trading only for first tiks of new bar
if(Volume[0]>1) return;
//----
int p=0;
//---- get Indicatorrs
double bbh=iBands(NULL,0,BBPeriod,BBDev,0,PRICE_CLOSE,MODE_UPPER,0);
double bbl=iBands(NULL,0,BBPeriod,BBDev,0,PRICE_CLOSE,MODE_LOWER,0);
double adx=iADX(NULL,0,ADXPeriod,PRICE_CLOSE,MODE_MAIN,0);
//----
for (int i=0; i<OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS)==true)
{
if (OrderSymbol()!=Symbol() || OrderMagicNumber()!=MAGIC) continue;
if (OrderType()==OP_BUY || OrderType()==OP_SELL) p++;
}
}
//---- buy
if(adx<Level && Ask<bbl && b && p<1)
{
OrderSend(Symbol(),OP_BUY,Lots,Ask,30,Ask-StopLoss*Point,Ask+TakeProfit*Point,"",MAGIC,0,Blue);
b=false;
s=true;
}
//---- sell
if(adx<Level && Bid>bbh && s && p<1)
{
OrderSend(Symbol(),OP_SELL,Lots,Bid,30,Bid+StopLoss*Point,Bid-TakeProfit*Point,"",MAGIC,0,Red );
b=true;
s=false;
}
//----
return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
int LossCount = 0;
double LotsArray[]={0.1,0.2,0.4,0.8,1.6,3.2};
...
double Lots()
{
double Lot = Lots;
int total = OrdersHistoryTotal();
for (int i = 0; i < total; i++)
{
OrderSelect(i, SELECT_BY_POS, MODE_HISTORY);
if (OrderSymbol() == Symbol() && OrderMagicNumber() == MAGIC)
{
if (OrderProfit() > 0)
{
Lot=LotsArray[0];
LossCount = 0;
}
else
{
Lot=LotsArray[LossCount+1];
LossCount++;
}
}
}
return(Lot);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| WellX.mq4 |
//| Copyright © 2011, AM2 |
//| http://www.forexsystems.biz |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2011, AM2"
#property link "http://www.forexsystems.biz"
#define MAGIC 20111010
extern double StopLoss = 400;
extern double TakeProfit = 800;
extern double ADXPeriod = 14;
extern double BBPeriod = 20;
extern double BBDev = 2;
extern int Level = 30;
extern double Lots = 0.1;
int LossCount = 0;
double LotsArray[]={0.1,0.2,0.4,0.8,1.6,3.2};
bool b=true, s=true;
//+------------------------------------------------------------------+
int start()
{
//---- go trading only for first tiks of new bar
if(Volume[0]>1) return;
//----
int p=0;
//---- get Indicatorrs
double bbh=iBands(NULL,0,BBPeriod,BBDev,0,PRICE_CLOSE,MODE_UPPER,0);
double bbl=iBands(NULL,0,BBPeriod,BBDev,0,PRICE_CLOSE,MODE_LOWER,0);
double adx=iADX(NULL,0,ADXPeriod,PRICE_CLOSE,MODE_MAIN,0);
//----
for (int i=0; i<OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS)==true)
{
if (OrderSymbol()!=Symbol() || OrderMagicNumber()!=MAGIC) continue;
if (OrderType()==OP_BUY || OrderType()==OP_SELL) p++;
}
}
//---- buy
if(adx<Level && Ask<bbl && b && p<1)
{
OrderSend(Symbol(),OP_BUY,Lots(),Ask,30,Ask-StopLoss*Point,Ask+TakeProfit*Point,"",MAGIC,0,Blue);
b=false;
s=true;
}
//---- sell
if(adx<Level && Bid>bbh && s && p<1)
{
OrderSend(Symbol(),OP_SELL,Lots(),Bid,30,Bid+StopLoss*Point,Bid-TakeProfit*Point,"",MAGIC,0,Red );
b=true;
s=false;
}
//----
return(0);
}
//+------------------------------------------------------------------+
double Lots()
{
double Lot = Lots;
int total = OrdersHistoryTotal();
for (int i = 0; i < total; i++)
{
OrderSelect(i, SELECT_BY_POS, MODE_HISTORY);
if (OrderSymbol() == Symbol() && OrderMagicNumber() == MAGIC)
{
if (OrderProfit() > 0)
{
Lot=LotsArray[0];
LossCount = 0;
}
else
{
Lot=LotsArray[LossCount+1];
LossCount++;
}
}
}
return(Lot);
}
//+------------------------------------------------------------------+
Тестирование эксперта Bobsley на реальном счете. |
И здесь чемпион оказался на высоте. 500% за два месяца! |
Как прикрутить к советнику трейлингстоп и вывод в безубыток? |
Как написать простейший советник на MQL4? |
От 100 до 300$ в управление от FXStart |
Cоветник "Метод Пуриа". |
Тестирование советника "BOBSLEY". |
Тестирование советника торгующего по Zig Zag |