Господа программисты! Поправьте пожалуйста код!

 

Эксперт, переворачивающий позиции по взаимному положению МА.

Только он не сразу переворачивает, а ждет еще 2 бара после пересечения.
Что надо поправить что бы позы переворачивались сразу за баром, при котором МАшки пересеклись?
Спасибо!
#property copyright "Copyright © 2009"
#property link ""

#define Shift 1
// Trend Detection function
#define BULL 111111
#define BEAR 222222
// Input variables
extern string comment2 = "*** Order Options ***";
extern double Lots = 0.10;
extern int Stop_Loss = 0;
extern int Take_Profit = 0;
extern int Slippage = 5; // отклонение от предложенной цены
extern string Order_Comment = "vvv";
extern int Magic = 112607;
extern color Order_Arrow_Color = Green;
extern string comment3 = "*** MA_1 ***";
extern int Long_MA_Period = 100;
extern double T_1 = 0.5;
extern int Shift_1 = 0;
extern int Price_1 = 0;
extern string comment4 = "*** MA_2 ***";
extern int Short_MA_Period = 10;
extern double T_2 = 0.5;
extern int Shift_2 = 0;
extern int Price_2 = 0;

// Global variables
int Total_Open_Orders = 1;
int cnt = 0;
bool init_variables;
datetime PreviousBar;
int LastTrendDirection;
int FileHandle;
int init()
{
if(IsTesting()==false)
{
init_variables = true;
FileHandle=FileOpen("simplefx.dat",FILE_BIN | FILE_READ);
if(FileHandle<1)
{
Print("simplefx.dat not found.");
FileHandle=FileOpen("simplefx.dat",FILE_BIN | FILE_WRITE);
if(FileHandle>0)
{
LastTrendDirection=0;
FileWriteInteger(FileHandle,LastTrendDirection,SHORT_VALUE);
FileClose(FileHandle);
Print("simplefx.dat has been successfully created.");
}
else
{
FileClose(FileHandle);
Print("Failed to create simplefx.dat file.");
}
}
else
{
LastTrendDirection=FileReadInteger(FileHandle,SHORT_VALUE);
Print("Variables loaded from file.");
FileClose(FileHandle);
}
}
return(0);
}
int deinit()
{
return(0);
}
int start()
{
if(Bars < Long_MA_Period+1)
{
if(IsTesting()==false)
{
Comment("Long moving average does not have enough Bars in history to open a trade!\n",
"Must be at least ",Long_MA_Period, " bars to perform technical analysis.");
}
else
{
Comment("Back testing currently Long moving average does not have enough Bars to open a trade.\n",
"Must be at least ",Long_MA_Period, " bars to perform technical analysis.\n",
"Please be patient and wait...\n",
"Bars in history ",Bars);
}
return(0);
}
if(MarketInfo(Symbol(),MODE_MINLOT) == 0.01)
{
Lots = NormalizeDouble(Lots,2);
if(Lots < 0.01)
{
Comment("The variable Lots must be 0.01 or greater to open an order. ");
return(0);
}
}
if(MarketInfo(Symbol(),MODE_MINLOT) == 0.1)
{
Lots = NormalizeDouble(Lots,1);
if(Lots < 0.1)
{
Comment("The variable Lots must be 0.1 or greater to open an order. ");
return(0);
}
}
if(MarketInfo(Symbol(),MODE_MINLOT) == 1)
{
Lots = NormalizeDouble(Lots,0);
if(Lots < 1)
{
Comment("The variable Lots must be 1 or greater to open an order. ");
return(0);
}
}
if(init_variables == true)
{
PreviousBar = Time[0];
init_variables = false;
}
if(LastTrendDirection==0)
{
if(TrendDetection()==BULL)
{
LastTrendDirection=BULL;
}
if(TrendDetection()==BEAR)
{
LastTrendDirection=BEAR;
}
SaveVariables();
}
if(NewBar() == true)
{
if(TotalOpenOrders() == Total_Open_Orders && SelectTheOrder() == true)
{
if(OrderType() == OP_BUY && TrendDetection() == BEAR)
{
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Order_Arrow_Color);
}
if(OrderType() == OP_SELL && TrendDetection() == BULL)
{
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Order_Arrow_Color);
}
}
if(TotalOpenOrders() < Total_Open_Orders)
{
if(TrendDetection() == BULL && LastTrendDirection==BEAR)
{
if(Stop_Loss>0 && Take_Profit>0)
{
OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(Stop_Loss*Point),Ask+(Take_Profit*Point),Order_Comment,Magic,0,Order_Arrow_Color);
}
if(Stop_Loss>0 && Take_Profit==0)
{
OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-(Stop_Loss*Point),0,Order_Comment,Magic,0,Order_Arrow_Color);
}
if(Stop_Loss==0 && Take_Profit>0)
{
OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,Ask+(Take_Profit*Point),Order_Comment,Magic,0,Order_Arrow_Color);
}
if(Stop_Loss==0 && Take_Profit==0)
{
OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,Order_Comment,Magic,0,Order_Arrow_Color);
}
LastTrendDirection=BULL;
SaveVariables();
}
if(TrendDetection() == BEAR && LastTrendDirection==BULL)
{
if(Stop_Loss>0 && Take_Profit>0)
{
OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+(Stop_Loss*Point),Bid-(Take_Profit*Point),Order_Comment,Magic,0,Order_Arrow_Color);
}
if(Stop_Loss>0 && Take_Profit==0)
{
OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+(Stop_Loss*Point),0,Order_Comment,Magic,0,Order_Arrow_Color);
}
if(Stop_Loss==0 && Take_Profit>0)
{
OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,Bid-(Take_Profit*Point),Order_Comment,Magic,0,Order_Arrow_Color);
}
if(Stop_Loss==0 && Take_Profit==0)
{
OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,Order_Comment,Magic,0,Order_Arrow_Color);
}
LastTrendDirection=BEAR;
SaveVariables();
}
}
if(IsTesting() == true)
{
Display_Info();
}
}
if(IsTesting() == false)
{
Display_Info();
}
return(0);
}
/////////////////////////////////////////////////////////////////////////
// Common functions //
///////////////////////////////////////////////////////////////////////


int SaveVariables()
{
if(IsTesting()==false)
{
//save variables to file
FileHandle=FileOpen("simplefx.dat",FILE_BIN | FILE_WRITE);
if(FileHandle<1)
{
Print("simplefx.dat not found.");
FileHandle=FileOpen("simplefx.dat",FILE_BIN | FILE_WRITE);
if(FileHandle>0)
{
FileWriteInteger(FileHandle,LastTrendDirection,SHORT_VALUE);
FileClose(FileHandle);
Print("simplefx.dat has been successfully created.");
}
else
{
FileClose(FileHandle);
Print("Failed to create simplefx.dat file.");
}
}
else
{
FileWriteInteger(FileHandle,LastTrendDirection,SHORT_VALUE);
FileClose(FileHandle);
Print("SimpleFX variables successfully saved to file.");
}
}
return(0);
}

int TotalOpenOrders()
{
cnt=OrdersTotal();
int TotalOpenOrders = 0;
if(cnt==0)
{
return(0);
}
else
{
for(;cnt>=0;cnt--)
{
RefreshRates();
OrderSelect(cnt,SELECT_BY_POS);
if(OrderMagicNumber()==Magic)
{
TotalOpenOrders++;
}
}
}
return(TotalOpenOrders);
}

int SelectTheOrder()
{
cnt=OrdersTotal();
if(cnt==0)
{
return(false);
}
else
{
for(;cnt>=0;cnt--)
{
RefreshRates();
OrderSelect(cnt,SELECT_BY_POS);
if(OrderMagicNumber()==Magic)
{
return(true);
}
}
}
return(false);
}

bool NewBar()
{
if(PreviousBar<Time[0])
{
PreviousBar = Time[0];
return(true);
}
else
{
return(false);
}
return(false);
}

int TrendDetection()
{
// BULL trend
double ma1_1 = iCustom (NULL, 0,"ma1",Long_MA_Period, T_1, Shift_1, Price_1, 0, 1);
double ma1_2 = iCustom (NULL, 0,"ma1",Long_MA_Period, T_1, Shift_1, Price_1, 0, 2);
double ma2_1 = iCustom (NULL, 0,"ma2",Short_MA_Period, T_2, Shift_2, Price_2, 0, 1);
double ma2_2 = iCustom (NULL, 0,"ma2",Short_MA_Period, T_2, Shift_2, Price_2, 0, 2);
if (ma1_1 < ma2_1 && ma1_2 < ma2_2)
{
return(BULL);
}
// BEAR trend
if(ma1_1 > ma2_1 && ma1_2 > ma2_2)
{
return(BEAR);
}
return(0);
}
void Display_Info()
{
Comment(
"Forex Account Server:",AccountServer(),"\n",
"Account Balance: $",AccountBalance(),"\n",
"Lots: ",Lots,"\n",
"Symbol: ", Symbol(),"\n",
"Price: ",NormalizeDouble(Bid,4),"\n",
"Pip Spread: ",MarketInfo("EURUSD",MODE_SPREAD),"\n",
"Date: ",Month(),"-",Day(),"-",Year()," Server Time: ",Hour(),":",Minute(),":",Seconds(),"\n",
"Minimum Lot Size: ",MarketInfo(Symbol(),MODE_MINLOT));
return(0);
}

 

Досадная "ошибка"!

 
double ma1_1 = iCustom (NULL, 0,"ma1",Long_MA_Period, T_1, Shift_1, Price_1, 0, 0);
double ma1_2 = iCustom (NULL, 0,"ma1",Long_MA_Period, T_1, Shift_1, Price_1, 0, 1);
double ma2_1 = iCustom (NULL, 0,"ma2",Short_MA_Period, T_2, Shift_2, Price_2, 0, 0);
double ma2_2 = iCustom (NULL, 0,"ma2",Short_MA_Period, T_2, Shift_2, Price_2, 0, 1);
 
satop писал(а) >>

Опять ошибка! Сделка есть, а персечения МА нет )

 
Integer >>:

Опять ошибка! Сделка есть, а персечения МА нет )

Попросили только бары сдвинуть.

 
satop писал(а) >>

Попросили только бары сдвинуть.

На самом деле просило то, не зная что.

 
Integer >>:

На самом деле просило то, не зная что.

+1.

Просят как всегда.

 

Наверно надо объяснить все-таки. После тестирования смотрим на МА нарисованную по ценам закрытия, а хотим, чтобы ордер открылся по цене открытия бара, но на открытии бара неизвестно, какое будет значение МА после закрытия бара. Открывается новый бар, значит предыдущий закрыт - теперь можем посмотреть значение на закрытом баре, если есть пересечение открываемся, поэтому и получается запаздывание, но только кажется, практически это и есть самый первый момент, когда можно сказать, что пересечение действительно произошло.

 
satop >>:

спасибо, все работает как надо!!!

 

Как сюда еще бы мани менеджмент прикрутить, считающего размер лота в зависимости баланс-риск ?? Подскажите кто знает...

 
Integer >>:

Наверно надо объяснить все-таки...

А Вы сами, Дмитрий, что используете в советниках для фиксации пересечения, кроме конструкции типа:

if (ma1_1 > ma2_1 && ma1_2 <= ma2_2)// ma1 - быстрая, ma2 - медленная, пересечение "вверх", расчет по закрытому бару
Причина обращения: