Пардон, что влажу в диалог.
Помоему этот индюк надо использовать не по пересечению а по расхождению-схождению.
//=======================================================================================
void Calc_Trand(int Bar)
{
BTrend=0; STrend=0;
for (int z=Bar; z>0; z--)
{
if( Buf_BigZZ[z] == 0.0 && Buf_SmallZZ[z] == 0.0 )
continue;
if( Buf_BigZZ[z] != 0.0 )
BTrend = (int)Buf_BigTrend[z];
if( Buf_SmallZZ[z] != 0.0 )
{
STrend = (int)Buf_SmallTrend[z];
if( BTrend != 0 )
{
color tcolor=clrGray;
if( BTrend == 1 )
tcolor = UPtrend_color;
if( BTrend == -1 )
tcolor = DOWNtrend_color;
}
}
} // END for (z=Bar; z>0; z--)
return;
}
//=======================================================================================
void DrawLabel()
{
if (!Draw_Info)
return;
color tcolor=clrGray;
string btxt = "Bigest Trend NONE", stxt = "Small Trend NONE";
if( BTrend !=0 )
{
if( BTrend == 1 )
{
btxt = "Bigest Trend UP";
tcolor = UPtrend_color;
}
if( BTrend == -1 )
{
btxt = "Bigest Trend DOWN";
tcolor = DOWNtrend_color;
}
if(Draw_Info)
PlotLabel(ENAME+"lb", btxt, 1, 240, 30, tcolor);
}
if( STrend !=0 )
{
if( STrend == 1 ) { stxt = "Small Trend UP"; tcolor = UPtrend_color; }
if( STrend == -1 ) { stxt = "Small Trend DOWN"; tcolor = DOWNtrend_color; }
if(Draw_Info) PlotLabel(ENAME+"ls", stxt, 1, 240, 60, tcolor);
}
if( Draw_Info && btxt != "Bigest Trend NONE" && stxt != "Small Trend NONE" )
GetInfo(btxt, stxt);
return;
}
//=======================================================================================
void DrawArrows()
{
//
//
//
//
}
//=======================================================================================
void GetInfo(string fBtxt, string fStxt)
{
string atxt;
int cmod=0;
bool fGO=false;
if( !Draw_Info )
return; // Off
if( CurBigAlrt == 0 || CurSmallAlrt == 0 || (CurBigAlrt == LastBigAlrt && CurSmallAlrt == LastSmallAlrt) )
return;
if( CurSmallAlrt != LastSmallAlrt )
{
cmod = 3;
atxt = fStxt;
}
if( CurBigAlrt != LastBigAlrt )
cmod = 2; atxt = fBtxt;
if( LastSignAlrt == LastSmallAlrt )
{
if( STrend == 1 )
atxt = "SIGNAL SELL";
if( STrend == -1 )
atxt = "SIGNAL BUY";
cmod = 1;
}
if( Draw_Info && cmod > 0 )
Alert(SymTF," ", atxt);
return;
}
//=======================================================================================
void PlotLabel(string N, string fTxt, int fCorn, int fX, int fY, color CL)
{
if ( ObjectFind(N) == -1 )
{
ObjectCreate(N, OBJ_LABEL, 0, 0, 0);
ObjectSetInteger(0,N, OBJPROP_CORNER, fCorn);
ObjectSetInteger(0,N, OBJPROP_XDISTANCE, fX);
ObjectSetInteger(0,N, OBJPROP_YDISTANCE, fY);
ObjectSetInteger(0,N,OBJPROP_ANCHOR,ANCHOR_LEFT);
}
ObjectSetText(N, fTxt, 12, "Veranda", CL );
return;
}
//=======================================================================================
void DeleteObjects_Prefix(string pref)
{
for (int i = ObjectsTotal()-1; i >= 0; i--)
{
if (StringSubstr(ObjectName(i), 0, StringLen(pref)) == pref)
ObjectDelete(ObjectName(i));
}
return;
}
//=======================================================================================
string GetStrTF(int fPer)
{
int tf_int[]={1,5,15,30,60,240,1440,10080,43200};
string tf_str[]={"M1","M5","M15","M30","H1","H4","D1","W1","MN1"};
if( ArrayRange(tf_int,0) != ArrayRange(tf_str,0) )
return("Unknown") ;
for( int i=ArrayRange(tf_int,0)-1; i>=0; i-- )
{
if( fPer == tf_int[i] )
return( tf_str[i] );
}
return("Unknown");
}
//=======================================================================================
void Draw_Pr_txt(string N, datetime TM, double PR, string ftext, int Ancor, color fcolor)
{
ObjectDelete(N);
ObjectCreate(N,OBJ_TEXT,0,TM,PR,0,0,0,0);
ObjectSetInteger(0,N,OBJPROP_WIDTH, 1);
ObjectSetString(0,N,OBJPROP_TEXT,ftext);
ObjectSetString(0,N,OBJPROP_FONT,"Arial");
ObjectSetInteger(0,N,OBJPROP_FONTSIZE,10);
ObjectSetInteger(0,N,OBJPROP_COLOR,fcolor);
if (Ancor == 1)
ObjectSetInteger(0,N,OBJPROP_ANCHOR,ANCHOR_UPPER);
if (Ancor == -1)
ObjectSetInteger(0,N,OBJPROP_ANCHOR,ANCHOR_LOWER);
return;
}
//=======================================================================================
//+------------------------------------------------------------------+
//| KAE Trend |
//+------------------------------------------------------------------+
#property strict
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 clrGreen
#property indicator_color2 clrRed
//-------------------------------------------------------------------
extern int CountBars = 1000;
extern int Length_Big = 60;
extern int Length_Small = 12;
extern double PercentCorrection = 50.0;
extern bool ArrowsOnCurent = false;
input bool Draw_Info = true;
//-------------------------------------------------------------------
color UPtrend_color = indicator_color1;
color DOWNtrend_color = indicator_color2;
datetime CurBigAlrt, CurSmallAlrt, LastBigAlrt, LastSmallAlrt;
datetime LastSignAlrt;
int BTrend, STrend;
string ENAME, SymTF;
//-------------------------------------------------------------------
double Buf_SmallZZ[];
double Buf_BigZZ[];
double Buf_SmallTrend[];
double Buf_BigTrend[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
SymTF = StringConcatenate(_Symbol," (",GetStrTF(_Period),") ") ;
ENAME = "Ch2zz("+ (string)Length_Big+","+(string)Length_Small+")";
IndicatorShortName(ENAME);
IndicatorBuffers(4);
SetIndexBuffer(0,Buf_BigZZ); SetIndexEmptyValue(0,0.0);
SetIndexBuffer(1,Buf_SmallZZ); SetIndexEmptyValue(1,0.0);
SetIndexBuffer(2,Buf_SmallTrend); SetIndexDrawBegin (2, CountBars);
SetIndexBuffer(3,Buf_BigTrend); SetIndexDrawBegin (3, CountBars);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator Deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
DeleteObjects_Prefix(ENAME);
return;
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
int counted_bars, limit;
counted_bars = IndicatorCounted();
if (counted_bars < 0)
return (-1);
if (counted_bars > 0)
counted_bars--;
if( CountBars < 1 )
CountBars = Bars-1;
limit = MathMin(Bars-1 - MathMax(Length_Big, Length_Small),CountBars);
Calc_ZZ(Buf_SmallZZ, Buf_SmallTrend, limit, Length_Small);
Calc_ZZ(Buf_BigZZ, Buf_BigTrend, limit, Length_Big);
Calc_Trand(limit);
DrawLabel();
DrawArrows();
return(rates_total);
}
//=======================================================================================
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//=======================================================================================
void Calc_ZZ(double &fBuf[], double &fBufTrend[], int CountBAR, int LengthX )
{
double LL=0.0, HH=0.0, BH=0.0, BL=0.0;
int Swing=0, Swing_n=0, zu, zd;
for (int fBar=CountBAR; fBar>=0; fBar--)
{
HH = High[iHighest(_Symbol,_Period,MODE_HIGH, LengthX, fBar+1)];
LL = Low[iLowest(_Symbol ,_Period,MODE_LOW, LengthX, fBar+1)];
double curHigh = High[fBar];
double curLow = Low[fBar];
if( curLow < LL && curHigh > HH )
{
Swing=2;
if(Swing_n==1)
zu=fBar+1;
if(Swing_n==-1)
zd=fBar+1;
}
else
{
if( curLow < LL )
Swing = -1;
if( curHigh > HH )
Swing = 1;
}
if(Swing!=Swing_n && Swing_n!=0)
{
if(Swing==2)
{
Swing = -Swing_n;
BH = curHigh;
BL = curLow;
}
if(Swing==1)
{
fBuf[zd] = BL;
fBufTrend[zd] = 1;
}
if(Swing==-1)
{
fBuf[zu] = BH;
fBufTrend[zu] = -1;
}
BH = curHigh;
BL = curLow;
}
if( Swing == 1 && curHigh >= BH )
{
BH = curHigh;
zu = fBar;
}
if( Swing == -1 && curLow <= BL )
{
BL = curLow;
zd = fBar;
}
Swing_n=Swing;
}
return;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void TrailingAllBU()
{
bool rez=1;
slB=0; slS=0;
double AllBU=0,WeightB=0,WeightS=0,LotsB=0,LotsS=0;
BuyBU=0;SellBU=0;BuyTralBU=0;SellTralBU=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)
{
WeightB+=OrderOpenPrice()*OrderLots();
LotsB+=OrderLots();
}
if(OrderType()==OP_SELL)
{
WeightS+=OrderOpenPrice()*OrderLots();
LotsS+=OrderLots();
}
}
if(LotsB>0)
BuyBU = NormalizeDouble(WeightB/LotsB + MinTP*_Point,_Digits); // БУ+ покупок
if(LotsS>0)
SellBU = NormalizeDouble(WeightS/LotsS - MinTP*_Point,_Digits); // БУ+ продаж
//============================================ Цикл траления SL BU каждого направления =================================
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)
if(Bid>BuyBU+TrailingStop*_Point) // Если Bid оторвалась вверх от БУ покупок на дистанцию трала,
if(OrderStopLoss()<Bid-TrailingStop*_Point) // и если SL ордера ниже Bid более, чем на дистанцию трала,то
{
slB = NormalizeDouble(Bid-TrailingStop*_Point,_Digits); // подтягиваем SL вверх к цене Bid на дистанцию трала.
PutHLine("BU BUY",slB,clrBlue);
if(OrderStopLoss()!=slB)
rez=OrderModify(OrderTicket(),OrderOpenPrice(),slB,OrderTakeProfit(),0,Yellow);
}
if(OrderType()==OP_SELL)
if(Ask<SellBU-TrailingStop*_Point) // Если Ask оторвалась вниз от БУ продаж на дистанцию трала,
if(OrderStopLoss()>Ask+TrailingStop*_Point) // и если SL ордера выше Ask более, чем на дистанцию трала,то
{
slS = NormalizeDouble(Bid+TrailingStop*_Point,_Digits); // подтягиваем SL вниз к цене Ask на дистанцию трала.
PutHLine("BU SELL",slS,clrRed);
if(OrderStopLoss()!=slS)
rez=OrderModify(OrderTicket(),OrderOpenPrice(),slS,OrderTakeProfit(),0,Yellow);
}
}
}
//+------------------------------------------------------------------+
//-------------------------------------------
if (AllBuy == true) // Если период безопасных покупок, то
{ // =================================
if (Buy)// && CountTrades(OP_BUY)<=Count) // и если появился сигнал на покупку и ордеров на покупки не более заданного, то
PutOrder(OP_BUY,1); // открываем Бай с TP.
if (Sell)// && CountTrades(OP_SELL)<=Count) // а если появился сигнал на продажу и ордеров на продажи не более заданного, то
PutOrder(OP_SELL,1); // открываем Сел с ТР.
//-------------------------------------------
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double PriceMaxMin(int type=-1)
{
double pr=0,PrMaxMin=0;
for(int i=OrdersTotal()-1; i>=0; i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
pr = OrderOpenPrice();
if(type == OP_BUY && OrderType()==OP_BUY)
if (PrMaxMin==0 || pr>PrMaxMin) // Выбираем ордер на покупку с максимальной ценой.
PrMaxMin = pr;
if(type == OP_SELL && OrderType()==OP_SELL)
if (PrMaxMin==0 || pr<PrMaxMin) // Выбираем ордера на продажу с минимальной ценой.
PrMaxMin = pr;
}
return (PrMaxMin);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void PutOrder(int type=-1, int faza=-1)
{
int rez = 0;
color clr = Green;
double sl = 0, tp = 0, price=0, lot=0;
if(type==OP_SELL)
{
clr=Red;
price = Bid;
if(StopLoss>0)
sl=NormalizeDouble(price+StopLoss*_Point,_Digits);
if(TakeProfit>0)
tp=NormalizeDouble(price-TakeProfit*_Point,_Digits);
if (faza==1) // Если безопасная продажа, то
sl=0; // без стоплосса, но с ТР.
else // Иначе
tp=0; // без ТР, но со стоплоссом.
}
if(type==OP_BUY)
{
clr=Blue;
price = Ask;
if (StopLoss>0)
sl=NormalizeDouble(price-StopLoss*_Point,_Digits);
if (TakeProfit>0)
tp=NormalizeDouble(price+TakeProfit*_Point,_Digits);
if (faza==1) // Если безопасная покупка, то
sl=0; // без стоплосса, но с ТР.
else // Иначе
tp=0; // без ТР, но со стоплоссом.
}
lot=Lot();
if (faza==0)
lot = 0.01;
//---
if (Lot()!=0) // Если свободных средств хватает для открытия ордера минимальным лотом, то окрываем. Иначе закрываем наиболее прибыльный.
rez = OrderSend(NULL,type,lot,NormalizeDouble(price,_Digits),Slippage,sl,tp,Советник,MagicNumber,0,clr);
return;
}
//+------------------------------------------------------------------+
//| Подсчет позиций. Если ot==11, то считаются все открытые ордера. |
//+------------------------------------------------------------------+
int CountTrades(int ot=-1)
{
int count=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 && (ot==OP_BUY || ot==11))
count++;
if(OrderType()==OP_SELL && (ot==OP_SELL || ot==11))
count++;
}
return(count);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double Lot()
{
double lot = 0;//Lots;
if(Risk>0)
lot=AccountFreeMargin()*Risk/100000/100*70; // Лот от 70% свободной маржи. Это от АМ2. Требует уточнения. (???????????????)
if (lot < 0.01) // Если до нормализации лота он меньше минимального лота, то
return (0); // лот равен нулю.
return(NormalizeDouble(lot,2));
}
//+------------------------------------------------------------------+
//| Горизонтальная линия БУ |
//+------------------------------------------------------------------+
void PutHLine(string name,double p,color clr)
{
ObjectDelete(0,name);
ObjectCreate(0,name,OBJ_HLINE,0,0,p);
//--- установим цвет линии
ObjectSetInteger(0,name,OBJPROP_COLOR,clr);
//--- установим толщину линии
ObjectSetInteger(0,name,OBJPROP_WIDTH,3);
}
//+------------------------------------------------------------------+
//| Закрытие всех ордеров указанного типа |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void TrailingAllBU()
{
bool rez=1;
slB=0; slS=0;
double AllBU=0,WeightB=0,WeightS=0,LotsB=0,LotsS=0;
BuyBU=0;SellBU=0;BuyTralBU=0;SellTralBU=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)
{
WeightB+=OrderOpenPrice()*OrderLots();
LotsB+=OrderLots();
}
if(OrderType()==OP_SELL)
{
WeightS+=OrderOpenPrice()*OrderLots();
LotsS+=OrderLots();
}
}
if(LotsB>0)
BuyBU = NormalizeDouble(WeightB/LotsB,_Digits); // БУ покупок
if(LotsS>0)
SellBU = NormalizeDouble(WeightS/LotsS,_Digits); // БУ продаж
if ((LotsB - LotsS)!=0)
AllBU = (WeightB - WeightS)/(LotsB - LotsS); // БУ всех ордеров.
//============================================ Цикл траления SL BU каждого направления =====================================
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)
if(Bid-BuyBU>TrailingStop*_Point)
if(OrderStopLoss()<Bid-TrailingStop*_Point)
{
slB = NormalizeDouble(Bid-TrailingStop*_Point,_Digits);
PutHLine("BU BUY",slB,clrBlue);
if(OrderStopLoss()!=slB)
rez=OrderModify(OrderTicket(),OrderOpenPrice(),slB,OrderTakeProfit(),0,Yellow);
}
if(OrderType()==OP_SELL)
if(SellBU-Ask>TrailingStop*_Point)
if((OrderStopLoss()>(Ask+TrailingStop*_Point)) || (OrderStopLoss()==0))
{
slS = NormalizeDouble(Bid+TrailingStop*_Point,_Digits);
PutHLine("BU SELL",slS,clrRed);
if(OrderStopLoss()!=slS)
rez=OrderModify(OrderTicket(),OrderOpenPrice(),slS,OrderTakeProfit(),0,Yellow);
}
}
}
//+------------------------------------------------------------------+
//| Закрытие ордера с максимальным профитом |
//+------------------------------------------------------------------+
void CloseMaxProfit(int type=-1)
{
double pr=0,lt=0,ProfitMaxBuy=0,ProfitMaxSell=0,LotMaxBuy=0,LotMaxSell=0;
int tic=0,TickMaxBuy=0,TickMaxSell=0;
bool rez=false;
for(int i=OrdersTotal()-1; i>=0; i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
pr = OrderCommission()+OrderProfit()+OrderSwap();
lt = OrderLots();
tic = OrderTicket();
if(type == OP_BUY && OrderType()==OP_BUY)
if (ProfitMaxBuy==0 || pr>ProfitMaxBuy) // Выбираем тикет ордера на покупку с максимальным профитом.
{
ProfitMaxBuy = pr;
LotMaxBuy = lt;
TickMaxBuy = tic;
}
if(type == OP_SELL && OrderType()==OP_SELL)
if (ProfitMaxSell==0 || pr>ProfitMaxSell) // Выбираем тикет ордера на продажу с максимальным профитом.
{
ProfitMaxSell = pr;
LotMaxSell = lt;
TickMaxSell = tic;
}
}
//--- Закрываем ордер с максимальным профитом выбранного типа. ---
if (type==OP_BUY && ProfitMaxBuy>0)
rez = OrderClose(TickMaxBuy,LotMaxBuy,Bid,Slippage);
if (type==OP_SELL && ProfitMaxSell>0)
rez = OrderClose(TickMaxSell,LotMaxSell,Ask,Slippage);
}
Переделывал под себя, как вижу. Не пошел. Ну и Бог с ним.
kvashnin007