#property copyright "Qimer" extern string tx1 = "Общие настройки советника"; extern bool Info = true; extern color MainInfoBack = LightGray; extern color MainInfo = Black; extern color BuyInfoBack = LightGray; extern color BuyInfo = Black; extern color SellInfoBack = LightGray; extern color SellInfo = Black; extern int ProfitShift = 30; extern bool UseVTP = true; extern bool CloseBy = true; extern bool ManualTrade = false; extern bool DynamicTP = true; extern bool UseNewBar = true; extern bool ZTP = false; extern int ZTP_order = 6; extern int DaysBuffer = 2; extern int magicbuy = 121; extern int magicsell = 122; extern int magiclock = 135797531; extern string magic_list = "454 455 0"; extern color BuyColor = Blue; extern color SellColor = Red; extern string tx2 = "Настройки системы LOT"; extern bool LOT = false; extern int nOrder = 5; extern int LO_TP = 5; extern int LO_Tral_Start = 3; extern int LO_Tral_Size = 5; extern int ProfitPercent = 15; extern color LOTColor = Purple; extern string tx3 = "Время работы советника"; extern int StartHour = 21; extern int EndHour = 4; extern string tx4 = "Настройки MoneyManagement"; extern bool UseMM = true; extern bool UseEquity = true; extern double min_lot = 0.1; extern int MaxTrades = 6; extern int UseMoney = 50; extern int SL_Level = 40; extern bool DrawdownStop = false; extern string tx5 = "Основные настройки"; extern bool CurrencyProfit = false; extern double Profit = 1.0; extern int TP1 = 8; extern int TP = 8; extern int TPstep = 2; extern int Tral_Start = 5; extern int Tral_Size = 5; extern color TralColor = Yellow; extern int step = 30; extern double Step_coef = 1; extern double mult = 2; extern int slippage = 3; extern string tx6 = "Настройки индикатора Stochastic"; extern int StochTime = 5; extern int per_K = 10; extern int per_D = 3; extern int slow = 3; extern int S_Mode = 0; extern int S_Price = 0; extern int zoneBUY = 15; extern int zoneSELL = 85; extern string t40 = "Установки перекрытия"; extern int LeadingOrder = 4; // C какого колена работает перекрытие extern int ProfitPersent = 30; // Процент перекрытия(10...50) extern int SecondProfitPersent= 50; // Процент перекрытия когда подключается предпоследний ордер double minLot,maxLot,LOTStep,smbuy,smsell,vmtpb,vmtps,vLO_mtpb,vLO_mtps,Cprofit,Lprofit,Lprofit1; int LO_tral,tral,i,j,CU,totb,tots,r,cnt,dig,hb=0,hs=0,TicketB[],TicketS[],magic[10],cmagic,Lpos,Lpos1,Cpos; color col,vctpb,vctps,vcLO_mtpb,vcLO_mtps; string txt1,txt2,txt3,txt4,txtVTP,txtLOT,tm; datetime NewBar_B,NewBar_S; bool TradeOff,NotFast; //=================================================================================================================================================== int init() { TradeOff = false; LOTStep = MarketInfo(Symbol(),MODE_LOTSTEP); minLot = MarketInfo(Symbol(),MODE_MINLOT); maxLot = MarketInfo(Symbol(),MODE_MAXLOT); dig = 2; if (!IsTesting() || IsVisualMode()) {NotFast=true;} if (Digits==4 || Digits==2) CU=1; else CU=10; // коэффициент для разных типов счетов 4/2 и 5/3 LO_TP*=CU; LO_Tral_Start*=CU; slippage*=CU; // увеличиваем все необходимые параметры TP1*=CU; TP*=CU; TPstep*=CU; Tral_Start*=CU; step*=CU; // на этот коэффиент tral = Tral_Size*CU; LO_tral = LO_Tral_Size*CU; double lotx=MM(mult,UseMoney,MaxTrades,step); // производится проверка, удовлетворяет ли баланс if (UseMM && lotx= 2) CheckOverlapping(totb,tots) ; //-------------------------------- Запрет торговли -------------------------------------- if (TradeOff) { Text("z_ErrorB","gggggggggggggggggggggggggg",24,"Webdings",100,200,Red); Text("z_ErrorM","Торговля остановлена! "+tm,15,"Arial Black",110,201,Yellow); return(0); } //========================================================== Сбор данных о торговле =============================================================== totb=0; tots=0; ArrayResize(TicketB,OrdersTotal()); ArrayResize(TicketS,OrdersTotal()); //-------------------------- Заполнение массивов тикетов ------------------------------ for (r=0;rpr3) {pr3=pr2;r=j;} } if (r!=i) {j=TicketS[i];TicketS[i]=TicketS[r];TicketS[r]=j;} } //----------------- Подсчет профита, объемов и т.д. открытых ордеров ------------------ double profitbuy,profitsell,openpricebuy,lastlotbuy,openpricesell,lastlotsell,TPB,TPS; smbuy=0;smsell=0; for (i=totb-1;i>=0;i--) { OrderSelect(TicketB[i],SELECT_BY_TICKET); smbuy+=OrderLots(); profitbuy+=OrderProfit()+OrderCommission()+OrderSwap(); openpricebuy = OrderOpenPrice(); lastlotbuy = OrderLots(); TPB=OrderTakeProfit(); } for (i=tots-1;i>=0;i--) { OrderSelect(TicketS[i],SELECT_BY_TICKET); smsell+=OrderLots(); profitsell+=OrderProfit()+OrderCommission()+OrderSwap(); openpricesell = OrderOpenPrice(); lastlotsell = OrderLots(); TPS=OrderTakeProfit(); } //---------- Расчет ТП в зависимости от кол-ва ордеров и включенных режимов ------------- int TPbuy,TPsell; if (totb==1) TPbuy = TP1; else TPbuy = TP; if (tots==1) TPsell = TP1; else TPsell = TP; if (DynamicTP) { TPbuy+=(totb-1)*TPstep; TPsell+=(tots-1)*TPstep; } if (ZTP) { if (totb>=ZTP_order) TPbuy=0; if (tots>=ZTP_order) TPsell=0; } //======================================== LOT - Модуль обработки 2-х последних ордеров ========================================================= if (LOT) { int j; datetime TimeB=Time[0],TimeS=Time[0]; if (OrderSelect(TicketB[totb-1],SELECT_BY_TICKET)) TimeB=OrderOpenTime(); if (OrderSelect(TicketS[tots-1],SELECT_BY_TICKET)) TimeS=OrderOpenTime(); double LastOrdersBuyLots,LastOrdersBuyProfit,LastOrdersSellLots,LastOrdersSellProfit; if (totb>=nOrder) { OrderSelect(TicketB[0],SELECT_BY_TICKET); LastOrdersBuyLots =OrderLots(); LastOrdersBuyProfit =OrderProfit()+OrderCommission()+OrderSwap(); OrderSelect(TicketB[1],SELECT_BY_TICKET); LastOrdersBuyLots+=OrderLots(); LastOrdersBuyProfit+=OrderProfit()+OrderCommission()+OrderSwap(); } if (tots>=nOrder) { OrderSelect(TicketS[0],SELECT_BY_TICKET); LastOrdersSellLots =OrderLots(); LastOrdersSellProfit =OrderProfit()+OrderCommission()+OrderSwap(); OrderSelect(TicketS[1],SELECT_BY_TICKET); LastOrdersSellLots+=OrderLots(); LastOrdersSellProfit+=OrderProfit()+OrderCommission()+OrderSwap(); } int k=OrdersHistoryTotal()-1; double ProfitBuyN, ProfitSellN, BalanceBuy = AccountBalance(), BalanceSell = AccountBalance(); while(true) { if (!OrderSelect(k,SELECT_BY_POS,MODE_HISTORY)) break; if ((OrderOpenTime()TimeB) ProfitBuyN += OrderProfit()+OrderSwap()+OrderCommission(); if (OrderMagicNumber()==magicsell && OrderType()==OP_SELL && OrderOpenTime()>TimeS) ProfitSellN += OrderProfit()+OrderSwap()+OrderCommission(); } k--; } BalanceBuy -= ProfitBuyN; BalanceSell -= ProfitSellN; double ProfitBuy = NormalizeDouble(ProfitBuyN / BalanceBuy*100,1), ProfitSell = NormalizeDouble(ProfitSellN/BalanceSell*100,1); } //=================================================== модуль Расчета ТейкПрофита для обоих серий ================================================== double tpb,tps,ztpb,ztps,LOtpb,LOtps; double mtpb=0,mtps=0,LO_mtpb=0,LO_mtps=0; color ctpb=0,ctps=0,cLO_mtps=0,cLO_mtpb=0; //--------------------------------- Для серии BUY --------------------------------------- if (hb!=totb || (NotFast && (ObjectFind("BuyTP")<0 || ObjectFind("BuyZeroLevel")<0 || (ObjectFind("BuyLOT")<0 && LOT && totb>=nOrder)))) { if (NotFast) { ObjectDelete("BuyTP"); ObjectDelete("BuyLOT"); ObjectDelete("BuyZeroLevel"); ObjectDelete("BuyTP_Back"); ObjectDelete("BuyTP_Text"); } hb=totb; if (totb>0) { ztpb = NormalizeDouble(Bid,Digits)-NormalizeDouble((profitbuy/(smbuy*TV))*Point,Digits); if (CurrencyProfit) { double PrPB=BalanceBuy*Profit/100; tpb = ztpb+ NormalizeDouble(PrPB/(smbuy*TV)*Point,Digits); } else tpb = ztpb+TPbuy*Point; if (LOT && totb>=nOrder) { LOtpb = NormalizeDouble(Bid+((-LastOrdersBuyProfit)/(LastOrdersBuyLots*TV)+(LO_TP+TPstep*(totb-1)))*Point,Digits); if (NotFast) DrawLine("BuyLOT",LOtpb,BuyColor,3); else {vLO_mtpb=LOtpb; vcLO_mtpb=BuyColor;} } if (NotFast) { DrawLine("BuyTP",tpb,BuyColor,2); DrawLine("BuyZeroLevel",ztpb,BuyColor,0); } else {vctpb=BuyColor;vmtpb=tpb;} } } //--------------------------------- Для серии SELL -------------------------------------- if (hs!=tots || (NotFast && (ObjectFind("SellTP")<0 || ObjectFind("SellZeroLevel")<0 || (ObjectFind("SellLOT")<0 && LOT && tots>=nOrder)))) { if (NotFast) { ObjectDelete("SellTP"); ObjectDelete("SellLOT"); ObjectDelete("SellZeroLevel"); ObjectDelete("SellTP_Back"); ObjectDelete("SellTP_Text"); } hs=tots; if (tots>0) { ztps = NormalizeDouble(Ask,Digits)+NormalizeDouble((profitsell/(smsell*TV))*Point,Digits); if (CurrencyProfit) { double PrPS=BalanceSell*Profit/100; tps = ztps-NormalizeDouble(PrPS/(smsell*TV)*Point,Digits); } else tps = ztps-TPsell*Point; if (LOT && tots>=nOrder) { LOtps = NormalizeDouble(Ask-((-LastOrdersSellProfit)/(LastOrdersSellLots*TV)+(LO_TP+TPstep*(tots-1)))*Point,Digits); if (NotFast) DrawLine("SellLOT",LOtps,SellColor,3); else {vLO_mtps=LOtps; vcLO_mtps=SellColor;} } if (NotFast) { DrawLine("SellTP",tps, SellColor,2); DrawLine("SellZeroLevel",ztps, SellColor,0); } else {vctps=SellColor;vmtps=tps;} } } //----------------------- Определяем цену и цвет линий ТП и LOT ------------------------- if (NotFast && ObjectFind("BuyTP")==0) { mtpb = ObjectGet("BuyTP",OBJPROP_PRICE1); ctpb = ObjectGet("BuyTP",OBJPROP_COLOR); ztpb = ObjectGet("BuyZeroLevel",OBJPROP_PRICE1); double ptpb=(mtpb-Bid)/Point*smbuy*TV+profitbuy; double pptpb=(mtpb-ztpb)/Point; TextT("BuyTP_Back", "gggggggggg", mtpb, "Webdings", ctpb); TextT("BuyTP_Text", DoubleToStr(ptpb,2)+" / "+DoubleToStr(pptpb,0), mtpb, "Arial Black", Black); } else {mtpb = vmtpb;ctpb = vctpb;} if (NotFast && ObjectFind("SellTP")== 0) { mtps = ObjectGet("SellTP",OBJPROP_PRICE1); ctps = ObjectGet("SellTP",OBJPROP_COLOR); ztps = ObjectGet("SellZeroLevel",OBJPROP_PRICE1); double ptps=(Ask-mtps)/Point*smsell*TV+profitsell; double pptps=(ztps-mtps)/Point; TextT("SellTP_Back","gggggggggg", mtps, "Webdings", ctps); TextT("SellTP_Text",DoubleToStr(ptps,2)+" / "+DoubleToStr(pptps,0), mtps, "Arial Black", Black); } else {mtps = vmtps;ctps = vctps;} if (NotFast && ObjectFind("BuyLOT")== 0) { LO_mtpb = ObjectGet("BuyLOT", OBJPROP_PRICE1); cLO_mtpb = ObjectGet("BuyLOT", OBJPROP_COLOR); } else {LO_mtpb = vLO_mtpb; cLO_mtpb = vcLO_mtpb;} if (NotFast && ObjectFind("SellLOT")==0) { LO_mtps = ObjectGet("SellLOT", OBJPROP_PRICE1); cLO_mtps = ObjectGet("SellLOT", OBJPROP_COLOR); } else {LO_mtps = vLO_mtps; cLO_mtps = vcLO_mtps;} //=================================================================== Трал VTP ==================================================================== if (UseVTP) { if (totb>0) { if (ctpb==TralColor) { if (Bid<=mtpb) {closeBUYorders(); return(0);} if (mtpb<(Bid-tral*Point)) { if (NotFast) DrawLine("BuyTP" ,Bid-tral*Point, TralColor, 2); else vmtpb=Bid-tral*Point; } } if (ctpb!=TralColor && Bid>=mtpb+Tral_Start*Point) { if (NotFast) DrawLine("BuyTP" ,Bid-Tral_Start*Point, TralColor, 2); else {vctpb=TralColor;} } } //----------------------------------------------------------------------------------------------------- if (tots>0) { if (ctps==TralColor) { if (Ask>=mtps) {closeSELLorders(); return(0);} if (mtps>(Ask+tral*Point)) { if (NotFast) DrawLine("SellTP",Ask+tral*Point, TralColor, 2); else vmtps=Ask+tral*Point; } } if (ctps!=TralColor && Ask<=mtps-Tral_Start*Point) { if (NotFast) DrawLine("SellTP",Ask+Tral_Start*Point, TralColor, 2); else {vctps=TralColor;} } } } //===================================================== Модификация ордеров при выключенном VTP ==================================================== else { bool q=false; //----------------------------------------------------------------------------------------------------- if (totb>0 && MathAbs((TPB-NormalizeDouble(mtpb,Digits))/Point)>CU && MathAbs((Bid-NormalizeDouble(mtpb,Digits))/Point)>spread) { for(i=0;i0 && MathAbs((TPS-NormalizeDouble(mtps,Digits))/Point)>CU && MathAbs((Ask-NormalizeDouble(mtps,Digits))/Point)>spread) { for(i=0;i=nOrder) { if (cLO_mtpb==LOTColor) { if (Bid<=LO_mtpb && MathAbs((Bid-mtpb)/Point)>spread) {CloseLastOrdersBuy(); return(0);} if (LO_mtpb<(Bid-LO_tral*Point)) { if (NotFast) DrawLine("BuyLOT" ,Bid-LO_tral*Point, LOTColor, 3); else vLO_mtpb=Bid-LO_tral*Point; } } if (cLO_mtpb!=LOTColor && Bid>=LO_mtpb+LO_Tral_Start*Point) { if (NotFast) DrawLine("BuyLOT" ,Bid-LO_Tral_Start*Point, LOTColor, 3); else vcLO_mtpb=LOTColor; } } //-------------------------------------------------------------------------------------------------------------------------------- if (tots>=nOrder) { if (cLO_mtps==LOTColor) { if (Ask>=LO_mtps && MathAbs((Ask-mtps)/Point)>spread) {CloseLastOrdersSell(); return(0);} if (LO_mtps>(Ask+LO_tral*Point)) { if (NotFast) DrawLine("SellLOT",Ask+LO_tral*Point, LOTColor, 3); else vLO_mtps=Ask+LO_tral*Point; } } if (cLO_mtps!=LOTColor && Ask<=LO_mtps-LO_Tral_Start*Point) { if (NotFast) DrawLine("SellLOT",Ask+LO_Tral_Start*Point, LOTColor, 3); else vcLO_mtps=LOTColor; } } } //=================================================================================================================================================== if (profitbuy+profitsell<0) double dd=MathAbs(profitbuy+profitsell)/(AccountEquity()-(profitbuy+profitsell))*100; if (DrawdownStop && dd>=SL_Level && (profitbuy+profitsell)<0) { if (totb>0) closeBUYorders(); if (tots>0) closeSELLorders(); } if (LOT && (ProfitBuyN + profitbuy)>=BalanceBuy *ProfitPercent/100) closeBUYorders(); if (LOT && (ProfitSellN+profitsell)>=BalanceSell*ProfitPercent/100) closeSELLorders(); //======================================================= Визуализация информации ================================================================= if(NotFast) { //------------------------------- Удаление устарвеших объектов ---------------------------------- for (int i=ObjectsTotal()-1;i>=0;i--) { string ObName=ObjectName(i); if (ObjectGet(ObName,OBJPROP_TIME1)>0 && ObjectGet(ObName,OBJPROP_TIME1)<(Time[0]-DaysBuffer*86400)) { if (ObName!="SellTP" && ObName!="SellLOT" && ObName!="SellZeroLevel" && ObName!="SellTP_Back" && ObName!="SellTP_Text" && ObName!="BuyTP" && ObName!="BuyZeroLevel" && ObName!="BuyTP_Back" && ObName!="BuyTP_Text" && ObName!="BuyLOT") ObjectDelete(ObName); } } //--------------------------- Отображение Баланс/Средства/Просадка ------------------------------ if(Info) { //изменение цвета при уменьшении "СРЕДСТВА" относительно "БАЛАНС" int Balans = NormalizeDouble( AccountBalance(),0); int Sredstva = NormalizeDouble(AccountEquity(),0); if (Sredstva >= Balans/6*5) col = DodgerBlue; if (Sredstva >= Balans/6*4 && Sredstva < Balans/6*5)col = DeepSkyBlue; if (Sredstva >= Balans/6*3 && Sredstva < Balans/6*4)col = Gold; if (Sredstva >= Balans/6*2 && Sredstva < Balans/6*3)col = OrangeRed; if (Sredstva >= Balans/6 && Sredstva < Balans/6*2)col = Crimson; if (Sredstva < Balans/5 )col = Red; //------------------------- ObjectCreate("Lable1",OBJ_LABEL,0,0,1.0); ObjectSet("Lable1", OBJPROP_CORNER, 3); ObjectSet("Lable1", OBJPROP_XDISTANCE, 10); ObjectSet("Lable1", OBJPROP_YDISTANCE, 51); txt1=(DoubleToStr(AccountBalance(), 0)); ObjectSetText("Lable1","БАЛАНС "+txt1+"",12,"Times New Roman",DodgerBlue); //------------------------- ObjectCreate("Lable2",OBJ_LABEL,0,0,1.0); ObjectSet("Lable2", OBJPROP_CORNER, 3); ObjectSet("Lable2", OBJPROP_XDISTANCE, 10); ObjectSet("Lable2", OBJPROP_YDISTANCE, 31); txt2=(DoubleToStr(AccountEquity(), 0)); ObjectSetText("Lable2","СРЕДСТВА "+txt2+"",12,"Times New Roman",col); //------------------------- ObjectCreate("Lable3",OBJ_LABEL,0,0,1.0); ObjectSet("Lable3", OBJPROP_CORNER, 3); ObjectSet("Lable3", OBJPROP_XDISTANCE, 10); ObjectSet("Lable3", OBJPROP_YDISTANCE, 11); txt4=DoubleToStr(dd,1)+"%"; ObjectSetText("Lable3","ПРОСАДКА "+txt4+"",12,"Times New Roman",Green); //---------------------------------- Отображение инфопанелей ------------------------------------ string spips; int pips; double stopout_balance=AccountMargin()*AccountStopoutLevel()/100; if (MathAbs(smbuy-smsell)>0) pips=NormalizeDouble((AccountEquity()-stopout_balance)/MathAbs(smbuy-smsell)/TV,0); if (smbuy>smsell) spips="До слива "+pips+" пунктов вниз"; if (smbuy0) { if ((UseNewBar && NewBar_B!=Time[0]) || !UseNewBar) { if(Ask<=openpricebuy-MathFloor(step*MathPow(Step_coef,totb-1))*Point && totb0) ОткрытьОрдер(OP_BUY,lotsbuy2,totb+1+"-й ордер Buy, "+magicbuy,magicbuy); } } } //============================================================ Усреднение позиций SELL ============================================================ if(tots>0) { if ((UseNewBar && NewBar_S!=Time[0]) || !UseNewBar) { if(Bid>=openpricesell+MathFloor(step*MathPow(Step_coef,tots-1))*Point && tots0) ОткрытьОрдер(OP_SELL,lotssell2,tots+1+"-й ордер Sell, "+magicsell,magicsell); } } } //======================================================= Открытие 1-го ордера по индикатору ====================================================== if(time() && totb==0) if ((UseNewBar && NewBar_B!=iTime(Symbol(),StochTime,0)) || !UseNewBar) { if (!ManualTrade && Stochastic("buy")) { if (UseMM) { double lotsbuy=MM(mult,UseMoney,MaxTrades,step); if (lotsbuy0) ОткрытьОрдер(OP_BUY,lotsbuy,"1-й ордер Buy, "+magicbuy,magicbuy); } } //---------------------------------------------------------------------------------------------------------------------- if(time() && tots==0) if ((UseNewBar && NewBar_S!=iTime(Symbol(),StochTime,0)) || !UseNewBar) { if (!ManualTrade && Stochastic("sell")) { if (UseMM) { double lotssell=MM(mult,UseMoney,MaxTrades,step); if (lotssell0) ОткрытьОрдер(OP_SELL,lotssell,"1-й ордер Sell, "+magicsell,magicsell); } } //=================================================================================================================================================== return(0); } //===================================================================== Ф У Н К Ц И И =============================================================== bool time() { if (StartHour=StartHour && Hour()EndHour) {if (Hour()>=EndHour && Hour()=sS0) return(true); if (SMode=="sell" && sS0>zoneSELL && sM0>zoneSELL && sM1>sS1 && sM0<=sS0) return(true); return(false); } //=================================================================================================================================================== void closeBUYorders() { int i,t,j; bool q; if (CloseBy && !IsTesting()) { while (ОткрытьОрдер(OP_SELL, smbuy, "", magiclock)<=0) Sleep(1000); for(i=0;i=0;j--) { if (OrderSelect(j,SELECT_BY_POS, MODE_TRADES)) { if (OrderSymbol() == Symbol() && OrderType() == OP_SELL && OrderMagicNumber()==magiclock) {t=OrderTicket(); break;} } } q=false; while(!q) { RefreshRates(); q=OrderCloseBy(TicketB[i],t,BuyColor); Sleep(1000); } } } else { for(i=0;i=0;j--) { if (OrderSelect(j,SELECT_BY_POS, MODE_TRADES)) { if (OrderSymbol() == Symbol() && OrderType() == OP_BUY && OrderMagicNumber()==magiclock) {t=OrderTicket(); break;} } } q=false; while(!q) { RefreshRates(); q=OrderCloseBy(TicketS[i],t,SellColor); Sleep(1000); } } } else { for(i=0;i0 && profit>Lprofit) { Lprofit1 = Lprofit ; Lpos1 = Lpos ; Lprofit = profit ; //макс значение Lpos = Pos ; } if (profit<0 && profit0) result =AccountEquity()/AccountMargin()*100 ; if (inf=="TotalOrd" ) result++ ; if (OrdType == "Buy"){ if(OrderType()==OP_BUY){ if (inf=="TotalBuy" ) result++ ; if (inf=="LastLotBuy") result = OrderLots() ; if (inf=="SumLotBuy" ) result += OrderLots() ; AveragePrice += OrderOpenPrice()* OrderLots() ; Count += OrderLots() ; LastPriceBuy = OrderOpenPrice() ; ProfitBuy += OrderProfit()+OrderSwap()+OrderCommission() ; if(AveragePrice > 0 && Count > 0){ if (inf=="CalculateAveragePriceBuy" ) return(NormalizeDouble(AveragePrice/Count, Digits)); } else return(0); } } if (OrdType == "Sell"){ if (OrderType()==OP_SELL){ if (inf=="TotalSell" ) result++ ; if (inf=="LastLotSell") result = OrderLots() ; if (inf=="SumLotSell" ) result += OrderLots() ; AveragePrice += OrderOpenPrice()* OrderLots() ; Count += OrderLots() ; LastPriceSell = OrderOpenPrice() ; ProfitSell += OrderProfit()+OrderSwap()+OrderCommission(); if(AveragePrice > 0 && Count > 0){ if (inf=="CalculateAveragePriceSell") return(NormalizeDouble(AveragePrice/Count, Digits)); } else return(0); } } } } } } if (inf=="Lpos") return(Lpos) ; //Ордер с наибольшим профитом if (inf=="Cpos") return(Cpos) ; //Ордер с наименьшим профитом if (inf=="LastPriceBuy" ) return(NormalizeDouble(LastPriceBuy , Digits)) ; if (inf=="LastPriceSell") return(NormalizeDouble(LastPriceSell, Digits)) ; if (inf=="ProfitBuy" ) return(NormalizeDouble(ProfitBuy , 2)) ; if (inf=="ProfitSell" ) return(NormalizeDouble(ProfitSell , 2)) ; if (inf=="SumProfit" ) return(NormalizeDouble(SumProfit , 2)) ; return(result) ; } //=========================================================================================================================================// // shvonder . Перекрытие ордеров // //=========================================================================================================================================// void CheckOverlapping(int totbuy, int totsell){ Lpos = 0; Cpos = 0; Lprofit = 0; Cprofit = 0; Lpos = CurrentCondition("","Lpos"); Cpos = CurrentCondition("","Cpos"); if (totbuy +totsell >= LeadingOrder){ if(Lprofit > 0 && Lprofit1 <= 0 && Cprofit < 0){ if(Lprofit + Cprofit > 0 && (Lprofit + Cprofit)*100/Lprofit > ProfitPersent){ Lpos1 = 0; CloseSelectOrder(); } }else if(Lprofit > 0 && Lprofit1 > 0 && totbuy +totsell > LeadingOrder && Cprofit < 0 ){ if(Lprofit + Lprofit1 + Cprofit > 0 && (Lprofit + Lprofit1 + Cprofit)*100/(Lprofit + Lprofit1) > SecondProfitPersent) CloseSelectOrder(); } } } //=========================================================================================================================================// // shvonder . Перекрытие ордеров // //=========================================================================================================================================// int CloseSelectOrder(){ if (Info) Print("Функция перекрытия ордеров."); int error = 0; int error1 = 0; int error2 = 0; int Result = 0; int Slippage = 2*MarketInfo(Symbol(), MODE_SPREAD); // ---------------------- последний ----------------------- while (error1 == 0) { RefreshRates(); int i = OrderSelect(Lpos, SELECT_BY_TICKET, MODE_TRADES); if (i != 1){ Print ("Ошибка! Невозможно выбрать ордер с наибольшим профитом. Выполнение перекрытия отменено."); return (0); } if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicbuy || magicsell || MagicCheck()){ if (OrderType() == OP_BUY) { error1 = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Bid, Digits), Slippage, Blue)); if (error1 == 1) { if (Info) Print ("Лидирующий ордер закрыт успешно."); Sleep (500); } else { Print ("Ошибка закрытия лидирующего ордера, повторяем операцию. "); } } // ----------------------------------------------------- if (OrderType() == OP_SELL) { error1 = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Ask, Digits), Slippage, Red)); if (error1 == 1) { if (Info) Print ("Лидирующий ордер закрыт успешно"); Sleep (500); } else { Print ("Ошибка закрытия лидирующего ордера, повторяем операцию. "); } } } } // ---------------------- пред последний ----------------------- if(Lpos1 != 0){ while (error2 == 0) { RefreshRates(); i = OrderSelect(Lpos1, SELECT_BY_TICKET, MODE_TRADES); if (i != 1 ){ Print ("Ошибка! Невозможно выбрать пред ордер с наибольшим профитом. Выполнение перекрытия отменено."); return (0); } if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicbuy || magicsell || MagicCheck()){ if (OrderType() == OP_BUY){ error2 = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Bid, Digits), Slippage, Blue)); if (error2 == 1){ if (Info) Print ("Пред Лидирующий ордер закрыт успешно."); Sleep (500); } else{ Print ("Ошибка закрытия пред лидирующего ордера, повторяем операцию. "); } } // ----------------------------------------------------- if (OrderType() == OP_SELL){ error2 = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Ask, Digits), Slippage, Red)); if (error2 == 1){ if (Info) Print ("Пред Лидирующий ордер закрыт успешно"); Sleep (500); } else { Print ("Ошибка закрытия Пред лидирующего ордера, повторяем операцию. "); } } } } } // ----------- выбранный (обычно с наименьшим профитом ) ----------- while (error == 0){ RefreshRates(); i = OrderSelect(Cpos, SELECT_BY_TICKET, MODE_TRADES); if (i != 1 ){ Print ("Ошибка! Невозможно выбрать ордер с наименьшим профитом. Выполнение перекрытия отменено."); return (0); } if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicbuy || magicsell || MagicCheck()){ if (OrderType() == OP_BUY){ error = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Bid, Digits), Slippage, Blue)); if (error == 1 ){ if (Info) Print ("Перекрываемый ордер закрыт успешно."); Sleep (500); } else { Print ("Ошибка закрытия перекрываемого ордера, повторяем операцию. "); } } // -------------------------------------------------- if (OrderType() == OP_SELL){ error = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Ask, Digits), Slippage, Red)); if (error == 1){ if (Info) Print ("Перекрываемый ордер закрыт успешно."); Sleep (500); } else { Print ("Ошибка закрытия перекрываемого ордера, повторяем операцию. "); } } } } Result = 1; return (Result); } //====================================================================== блок ММ ==================================================================== double MM(double mult1, int UM, int MaxTrades1,int step1) { double trade_vol=1; double sum_vol=1; double MaxDrawdown; double maxLot=MarketInfo(Symbol(),MODE_MAXLOT); double minLot=MarketInfo(Symbol(),MODE_MINLOT); double margin=MarketInfo(Symbol(),MODE_MARGINREQUIRED); double TV1=MarketInfo(Symbol(),MODE_TICKVALUE); int cnt2,cnt3; double marginsum,points; for (cnt2=MaxTrades1; cnt2>=1;cnt2--) { points=0; for (cnt3=MaxTrades1-cnt2; cnt3maxLot) lot=NormalizeDouble(maxLot/sum_vol,dig); // проверка на максимально возможный объем 1-го ордера серии return(lot); } //=================================================================================================================================================== void TradeStop() { if (totb+tots>0) return(0); int cnt2,cnt3; double trade_vol=1,points; double sum_vol=1; double MaxDrawdown,marginsum; double minLot=MarketInfo(Symbol(),MODE_MINLOT); double margin=MarketInfo(Symbol(),MODE_MARGINREQUIRED); double TV1=MarketInfo(Symbol(),MODE_TICKVALUE); for (cnt2=MaxTrades; cnt2>=1;cnt2--) { points=0; for (cnt3=MaxTrades-cnt2; cnt3