//+------------------------------------------------------------------+ //| Lock&&PipsingXR2.5.mq4 | //| Copyright © 2008, MetaQuotes Software Corp. | //| http://www.metaquotes.net | //+------------------------------------------------------------------+ #property copyright "#Copyright © 2008, XrustSolution.#" #property link "#http://www.xrust.ucoz.net#" #include <stdlib.mqh> //-------------------------------------------------------------------+ extern string a="KEY PARAMETERS OF THE ADVISER"; extern string b="Maximum orders recommended amount =20"; extern int TotalOrders=50; extern string c="Stoploss, for a scalping mode =0"; extern int StopLoss=0; extern string d="TakeProfit, for a scalping mode=0"; extern int TakeProfit=0; extern string e="StartLots of EA =0,01"; extern double StartLots=0.01; extern string x="Permission to use the dynamic changes in the lot"; extern bool Martin=false; extern string gb="dynamic change lot factor. if <1 it increases lot , if > 1 it is lot decreases "; extern double MartinKoff=1; extern string g="The permission to lot auto detection"; extern bool AutoLot=true; extern string ha="the percentage of risk as% of deposit amount"; extern double Risk=1; extern string k="øàã òðåéëèíãà ïî ýêâèòè â % îò äåïîçèòà"; extern double EqvTralStep=0.03; extern string í="minimum break between the opening of orders in minutes"; extern int MinTradePause=50; extern string l="authorization and flags"; extern string m="Permission to restrict trade in time"; extern bool TradeOfTime=false; extern string n="Hour start of trading"; extern int StartTradeHour=22; extern string o="Hour late trade"; extern int EndTradeHour=8; extern string p="Permission to display information in the main window"; extern bool ShowComment=true; extern string r="switch alarm systems and security"; extern bool MargineVarning=false; extern string s="permission for drawing graphic elements"; extern bool SetArrow=true; extern string t="Key closing level position without loss"; extern bool Bu=false; //----Variables for KimIV funcions ---------------------------------+ bool NumberOfTry=3,UseSound=false,print=false; string NameFileSound = "expert.wav"; // Íàèìåíîâàíèå çâóêîâîãî ôàéëà color clOpenBuy = Blue; // Öâåò çíà÷êà îòêðûòèÿ Buy color clOpenSell = Red; // Öâåò çíà÷êà îòêðûòèÿ Sell bool MarketWatch=false; bool gbDisabled = False; // Áëîêèðîâêà int BuyMagic1=2891; int SellMagic1=73351; static int PrevTime=0;double Lot; double MinLot, MaxLot, MarginMinLot; int MinLotDgts,period,GrossPeriod,GrossTrand=0; int Slippage=3;static double prr; //------------------------------------------------------------------+ static double StartDepo, gEqviti; static double gPriseAp,gPriseDn,gMidPrise; int gFrChSize,tP; static bool asd=false; int BuySell_1=0,BuySell_2=0,BuySell_3=0; int gCountBuy_1=1,gCountSell_1=1; double lot; static string gTime; static bool Expdis=false; int MaxOrd_1; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ void init() { MaxOrd_1=TotalOrders; StartDepo = AccountBalance(); if(StartLots<MarketInfo(Symbol(),MODE_MINLOT)){ StartLots=MarketInfo(Symbol(),MODE_MINLOT); } if(GlobalVariableCheck("stop")){GlobalVariableDel("stop");} if(!GlobalVariableCheck("multi")){GlobalVariableSet("multi",1);}else{ double set=GlobalVariableGet("multi"); set++; GlobalVariableSet("multi",set); } GlobalVariableSet("Risc",Risk); GlobalVariableSet("disable",0); lot=StartLots; if(GlobalVariableGet("multi")>1){SetArrow=false;} if(!GlobalVariableCheck("step")){GlobalVariableSet("step",EqvTralStep);} else{if(GlobalVariableGet("step")!=EqvTralStep){GlobalVariableSet("step",EqvTralStep);}} return; } //+------------------------------------------------------------------+ void deinit(){ if(GlobalVariableCheck("stop")){GlobalVariableDel("stop");} Comment(" "); if(GlobalVariableCheck("multi")){ double set=GlobalVariableGet("multi"); if(set>1){ set--; GlobalVariableSet("multi",set); }else{ GlobalVariableDel("multi"); GlobalVariableDel("disable"); GlobalVariableDel("step"); if(GlobalVariableCheck("Risc")){ GlobalVariableDel("Risc"); } } } if(Expdis){ double Exdis=GlobalVariableGet("disable"); Exdis--; GlobalVariableSet("disable",Exdis); Expdis=false; } return(0);} //deinit | //+------------------------------------------------------------------+ int start() { if(GlobalVariableGet("multi")>1){SetArrow=false;} if((GlobalVariableGet("multi")-GlobalVariableGet("disable"))>2){TradeOfTime=false;} if(MargineVarning){if(Varning()){Sleep(10000);return(0);}} if(!IsDemo()&&!IsOptimization()&&!IsTesting()){ //if(AccountNumber()!=38325){ Comment("Bad Account!!!"); Sleep(500); Comment(" "); return(0); //} } //-----------------------------------------------------------------------------+ // Ðàñ÷åò êîëè÷åñòâà îðäåðîâ îò ðèñêà è êîëè÷åñòâà óñòàíîâëåííûõ ñîâåòíèêîâ | //-----------------------------------------------------------------------------+ if(AutoLot){ MaxOrd_1=TotalOrders; if(MaxOrd_1>StartDepo/(MarketInfo(Symbol(),MODE_MARGINREQUIRED)*CalcLotsAuto()*2*(GlobalVariableGet("multi")-GlobalVariableGet("disable")))){ MaxOrd_1=(StartDepo/(MarketInfo(Symbol(),MODE_MARGINREQUIRED)*CalcLotsAuto()*2*(GlobalVariableGet("multi")-GlobalVariableGet("disable")))); } //---------------------------------------------------------------------------- } if(gEqviti==0){gEqviti=AccountBalance();} if(OrdersTotal()<1){ if(GlobalVariableCheck("stop")){GlobalVariableDel("stop");} gEqviti=AccountBalance(); } if(GrPorfit()<0){if(GlobalVariableCheck("stop")){GlobalVariableDel("stop");}} if(OrdersTotal()>=MaxOrd_1){if(AccountBalance()==StartDepo){CloseAll();}} if(EcvitiTral3(EqvTralStep)){return(0);} if(GlobalVariableCheck("stop")){return(0);} //-----------------------------------------------------------------------------+ // Ðàñ÷åò êîëè÷åñòâà ñîâåòíèêîâ â çàâèñèìîñòè îò ðèñêà íà îäíó ñäåëêó | //-----------------------------------------------------------------------------+ if(GlobalVariableGet("multi")>1){ if(MaxOrd_1<15){ if(!GlobalVariableCheck("disable")){ GlobalVariableSet("disable",1); }else{ if(!Expdis){ double dis=GlobalVariableGet("disable"); dis++; GlobalVariableSet("disable",dis); Expdis=true; } } Comment("\nMulti Chart Mode \n", "STOPPED\n", "Because AccountFreeMargin is few" ); return(0); } if(MaxOrd_1>18){ if(Expdis){ double Exdis=GlobalVariableGet("disable"); Exdis--; if(Exdis<=0){Exdis=0;} GlobalVariableSet("disable",Exdis); Expdis=false; } } } //---------------------------------------------------------------------------- BuySell_1=0;BuySell_2=0;BuySell_3=0; Info(); if(GlobalVariableGet("multi")<2){ //DelBigestLoss(); if(Bu){Bu();} } //----------------------------------------------------------------------------------------------------- if(NevBar()){ if(SetArrow){if(CountOpOrd("0")>0){SetArrow("NullProfitDot",4,1,0,NullDot(),White);}} lot=StartLots; if(TradeTime()){ IfZZ(); if(BuySell_1<0){ if(CountOpOrd("0")<MaxOrd_1&&TimeOfTrade()){ lot=StartLots*gCountBuy_1; if(AutoLot){lot=CalcLotsAuto();if(OrdersTotal()>2){if(Martin){lot=OrdersLot();}}} if(PorfitBuySell(1)>=PorfitBuySell(0)){OpenPosition("",0,lot,StopLoss,TakeProfit,BuyMagic1);} if(PorfitBuySell(1)<PorfitBuySell(0)){OpenPosition("",1,lot,StopLoss,TakeProfit,SellMagic1);} } } if(BuySell_1>0){ if(CountOpOrd("0")<MaxOrd_1&&TimeOfTrade()){ lot=StartLots*gCountSell_1; if(AutoLot){lot=CalcLotsAuto();if(OrdersTotal()>2){if(Martin){lot=OrdersLot();}}} if(PorfitBuySell(0)>=PorfitBuySell(1)){OpenPosition("",1,lot,StopLoss,TakeProfit,SellMagic1);} if(PorfitBuySell(0)<PorfitBuySell(1)){OpenPosition("",0,lot,StopLoss,TakeProfit,BuyMagic1);} } } } } //------------------------------------------------------------------------------------------------------- return(0); } //-----------------------------------------------------------------------------+ // Bu | //-----------------------------------------------------------------------------+ void Bu(){bool pr=false; if(OrdersTotal()==1){ if(!pr){ for(int i=0;i<OrdersTotal();i++){ if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){ if(OrderSymbol()==Symbol()){ if(OrderProfit()>=0){pr=true;break;} } } } } if(pr){ for( i=0;i<OrdersTotal();i++){ if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){ if(OrderSymbol()==Symbol()){ if(OrderProfit()<=1){del(OrderTicket());pr=false;} } } } } } return; } //-----------------------------------------------------------------------------+ // Òî÷êà ðàâíîâåñèÿ | //-----------------------------------------------------------------------------+ double NullDot(){double prise=0;int count=0,countlot=0; if(OrdersTotal()<1){return(Bid);} double MinLot=MarketInfo(Symbol(),MODE_MINLOT); for(int i=0;i<OrdersTotal();i++){ if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){ if(OrderSymbol()==Symbol()){ countlot=(OrderLots()/MinLot); count=count+countlot; prise=prise+(OrderOpenPrice()*countlot); } } } prise=prise/count; return(prise); } //+----------------------------------------------------------------------------+ // Óäàëÿåò ñàìîãî áîëüøîãî ëîñÿ + //+----------------------------------------------------------------------------+ void DelBigestLoss(){ if(CountOpOrd("0")<2){return;} double loss=0,profit=0,GrProfit=0;int n,x,y,ticket=0,count=0; int Ticket[50]; ArrayInitialize(Ticket,0); for(n=0;n<OrdersTotal();n++){ if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){ if(OrderSymbol()==Symbol()){ if(OrderProfit()+OrderSwap()+OrderCommission()>0){ profit=profit+OrderProfit()+OrderSwap()+OrderCommission(); } else{ if(OrderProfit()+OrderSwap()+OrderCommission()<loss){ loss=OrderProfit()+OrderSwap()+OrderCommission(); ticket=OrderTicket(); } } } } } if(ticket==0){return;} if(profit+loss>=0){ profit=0; for(x=0;x<OrdersTotal();x++){ for(n=0;n<OrdersTotal();n++){ if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){ if(OrderProfit()+OrderSwap()+OrderCommission()>0){ profit=profit+OrderProfit()+OrderSwap()+OrderCommission(); if(OrderProfit()+OrderSwap()+OrderCommission()<profit){ profit=OrderProfit()+OrderSwap()+OrderCommission(); } } } } if(profit!=0){ Ticket[count]=OrderTicket(); count++; for(n=0;n<1;n++){GrProfit=GrProfit+profit;} if(GrProfit+loss==0){ ArrayResize(Ticket,count+1); for(y=0;y<count+1;y++){if(OrderSelect(Ticket[y],SELECT_BY_TICKET)){if(OrderCloseTime()==0){del(OrderTicket());}}} if(OrderSelect(ticket,SELECT_BY_TICKET)){if(OrderCloseTime()==0){del(ticket);return(true);}} } }//if(profit!=0){ }//for(x=0;x<OrdersTotal();x++){ }//if(profit+loss>=0){ } //+----------------------------------------------------------------------------+ // Ïîäñ÷èòûâàåò Îáùóþ íå ðåàëèçîâàííóþ ïðèáûëü íà äàííîì èíñòðóìåíòå + //-----------------------------------------------------------------------------+ double GrPorfit(){double grpr=0; for(int n=0;n<OrdersTotal();n++){ if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){ if(OrderSymbol()==Symbol()){ grpr=grpr+OrderProfit()+OrderSwap()+OrderCommission(); } } } return(grpr); } //-----------------------------------------------------------------------------+ // Ñðåäíåå àðèôìåòè÷åñêîå ëîòà óñòàíîâëåííûõ îðäåðîâ | //-----------------------------------------------------------------------------+ double OrdersLot(){int count=0;double Lt=0; //if(OrdersTotal()<5){return(CalcLotsAuto());} for(int i=0;i<OrdersTotal();i++){ if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){ if(OrderSymbol()==Symbol()){ if(OrderCloseTime()==0){ Lt=Lt+OrderLots(); count++; } } } } return(NormalizeDouble((Lt/(count*MartinKoff)),2)); } //+------------------------------------------------------------------+ //| Ðàñ÷åò ëîòà ñîîòâ ðèñêó è áàëàíñó | //+------------------------------------------------------------------+ double CalcLotsAuto() {static double Sredstva; if(OrdersTotal()<1){Sredstva=AccountBalance();} double LotOpt,LotNeOpt,Zalog; RefreshRates(); double Set=GlobalVariableGet("multi")-GlobalVariableGet("disable"); double Marga=AccountFreeMargin(); double Balans=AccountBalance(); double LotMin=MarketInfo(Symbol(),MODE_MINLOT); double LotMax=MarketInfo(Symbol(),MODE_MAXLOT); double StepLot=MarketInfo(Symbol(),MODE_LOTSTEP); double StopLv=AccountStopoutLevel(); int PrsMinLot=1000*LotMin; if(GlobalVariableGet("multi")>1){Risk=GlobalVariableGet("Risc");} if(Risk<0)Risk=0; if(Risk>100)Risk=100; if(StepLot==0.01){int step=2;}else{step=1;} if(Set<1){Set=1;} //--------------------------- Zalog=(Balans*(Risk/100))/Set; LotOpt=NormalizeDouble((Zalog/1000),step); if(LotOpt>LotMax)LotOpt=LotMax; if(LotOpt<LotMin)LotOpt=LotMin; //if(Marga<Sredstva/2){return(0);} return(LotOpt); } //+------------------------------------------------------------------+ //| Óñòàíîâêà ñòðåëîê | //+------------------------------------------------------------------+ void SetArrow(string nm,int kod,int razm,int bar,double prs,color col){ //if(!DriveArrow)return; string Name=StringConcatenate(nm,TimeToStr(TimeLocal(),TIME_DATE|TIME_SECONDS)); ObjectCreate(Name,OBJ_ARROW,0,0,0,0,0,0,0); ObjectSet(Name,OBJPROP_ARROWCODE,kod); ObjectSet(Name,OBJPROP_STYLE,DRAW_ARROW); ObjectSet(Name,OBJPROP_TIME1,Time[bar]); ObjectSet(Name,OBJPROP_PRICE1,prs); ObjectSet(Name,OBJPROP_WIDTH,razm); ObjectSet(Name,OBJPROP_COLOR,col); return;} //-----------------------------------------------------------------------------+ // Äåòåêòîð ìóëüòè ðåæèìà ñ÷åò÷èê óñòàíîâëåííûõ ñîâåòíèêîâ | //-----------------------------------------------------------------------------+ string MutiDet(){ double set =GlobalVariableGet("multi")-GlobalVariableGet("disable"); string mode=StringConcatenate("MULTI CHART MODE \n",DoubleToStr(set,0)," EXPERT ENABLES"); string mode2="SINGLE CHART MODE"; if(GlobalVariableGet("multi")<2){return(mode2);} if(GlobalVariableGet("multi")>1){return(mode);} } //-----------------------------------------------------------------------------+ // Âûâîäèò èíôîðìàöèþ íà ýêðàí | //-----------------------------------------------------------------------------+ void Info(){ Comment("ACCOUNT BALANSE ="+(DoubleToStr(AccountBalance()+PorfitBuySell(0)+PorfitBuySell(1),1))+"$\n"+ "ACCOUNT FREE MARGIN ="+(DoubleToStr(AccountFreeMargin(),1))+"$\n"+ "CURRENT PROFIT ="+(DoubleToStr(GrPorfit(),1))+"$\n"+ "PROFIT FROM THE START OF TRADING ="+(DoubleToStr(AccountBalance()-StartDepo,1))+"$\n"+ "ALOVED ORDERS FOR THE OPENING ="+MaxOrd_1+"Pc.\n"+ "OPEN ORDERS ="+CountOpOrd("0")+"Pc.\n"+ gTime,"\n", MutiDet(),"\n", "Risk = ",Risk," %", "\nEquityTralingStep = ",GlobalVariableGet("step") ); return; } //-----------------------------------------------------------------------------+ // Âûâîäèò ïðåäóïðåæäàþùåå ñîîáùåíèå | //-----------------------------------------------------------------------------+ bool Varning(){int ord;double depo; if(AutoLot){ if((MarketInfo(Symbol(),MODE_MARGINREQUIRED)*CalcLotsAuto()*MaxOrd_1*2)>StartDepo){ depo=MarketInfo(Symbol(),MODE_MARGINREQUIRED)*CalcLotsAuto()*MaxOrd_1*2; ord=StartDepo/(MarketInfo(Symbol(),MODE_MARGINREQUIRED)*CalcLotsAuto()*2); Alert("THERE IS NOT ENOUGH MEANS FOR THE ACCOUNT"+"\n"+ "For such quantity of warrants it is necessary"+"\n"+ "The starting Deposit ="+depo+" $\n"+ "On your means it is possible to open "+ord+" Orders"+"\n"+ "Fill up your account please"+"\n"+ "Or reduce quantity of warrants"+"\n"+ "Or reduce a traded lot"+"\n"+ "Or disconnect the alarm system"); return(true); } } if(!AutoLot){ if((MarketInfo(Symbol(),MODE_MARGINREQUIRED)*StartLots*MaxOrd_1*2)>StartDepo){ depo=MarketInfo(Symbol(),MODE_MARGINREQUIRED)*StartLots*MaxOrd_1*2; ord=StartDepo/(MarketInfo(Symbol(),MODE_MARGINREQUIRED)*StartLots*2); Alert("THERE IS NOT ENOUGH MEANS FOR THE ACCOUNT"+"\n"+ "For such quantity of warrants it is necessary"+"\n"+ "The starting Deposit ="+depo+" $\n"+ "On your means it is possible to open "+ord+" Orders"+"\n"+ "Fill up your account please"+"\n"+ "Or reduce quantity of warrants"+"\n"+ "Or reduce a traded lot"+"\n"+ "Or disconnect the alarm system"); return(true); } } return(false); } //-----------------------------------------------------------------------------+ // Ôóíêöèÿ êîíòðîëÿ âðåìåíè òîðãîâëè | //-----------------------------------------------------------------------------+ bool TradeTime(){ if(!TradeOfTime){ gTime=StringConcatenate("the end of trading on Friday in ",DoubleToStr(EndTradeHour,0),"hours"); if(TimeDayOfWeek(TimeCurrent())==5){if(TimeHour(TimeCurrent())>EndTradeHour){return(false);}} return(true);} if(TimeDayOfWeek(TimeCurrent())==5){StartTradeHour=0;} if(TimeDayOfWeek(TimeCurrent())==1&&TimeHour(TimeCurrent())<1){StartTradeHour=1;} if(StartTradeHour<EndTradeHour){ if(TimeHour(TimeCurrent())>=StartTradeHour&&TimeHour(TimeCurrent())<EndTradeHour ||(CountOpOrd("0")+CountOpOrd("1"))){ gTime=StringConcatenate("By the end of trading session :",DoubleToStr((EndTradeHour-TimeHour(TimeCurrent())),0)," hours"); return(true);}} if(StartTradeHour>EndTradeHour){ if(TimeHour(TimeCurrent())>=StartTradeHour||TimeHour(TimeCurrent())<EndTradeHour ||(CountOpOrd("0")+CountOpOrd("1"))){ gTime=StringConcatenate("By the end of trading session :",DoubleToStr((EndTradeHour-TimeHour(TimeCurrent())),0)," hours"); return(true);}} gTime=StringConcatenate("resting to : ",StartTradeHour,": 00"); return(false); } //-----------------------------------------------------------------------------+ // Óñëîâèÿ âõîäà â ðûíîê | //-----------------------------------------------------------------------------+ int IfZZ(){ if(iClose(Symbol(),30,1)>iOpen(Symbol(),30,0)){ if(iClose(Symbol(),15,1)>iOpen(Symbol(),15,0)){ if(iClose(Symbol(),5,1)>iOpen(Symbol(),5,0)){ BuySell_1=-1; gCountBuy_1++; gCountSell_1=1; return(1);}}} if(iClose(Symbol(),30,1)<iOpen(Symbol(),30,0)){ if(iClose(Symbol(),15,1)<iOpen(Symbol(),15,0)){ if(iClose(Symbol(),5,1)<iOpen(Symbol(),5,0)){ BuySell_1=1; gCountBuy_1=1; gCountSell_1++; return(-1);}}} BuySell_1=0; return(0); } //+------------------------------------------------------------------+ //|Òðàë ïî ýêâèòè | //+------------------------------------------------------------------+ bool EcvitiTral3(double EqvTralStep){ if(OrdersTotal()<1){gEqviti=AccountBalance();return(false);} if(!GlobalVariableCheck("step")){EqvTralStep=EqvTralStep;} else{EqvTralStep=GlobalVariableGet("step");} EqvTralStep=EqvTralStep*(GlobalVariableGet("multi")-GlobalVariableGet("disable")); if(AccountEquity()>AccountBalance()){ if(AccountEquity()-AccountBalance()>((AccountBalance()/100)*(EqvTralStep*2))){EqvTralStep=EqvTralStep*2;} if(AccountEquity()>(gEqviti+(gEqviti/100*EqvTralStep))){ gEqviti=gEqviti+(gEqviti/200*EqvTralStep); if(!GlobalVariableCheck("stop")){GlobalVariableSet("stop",0);} } if(AccountEquity()<=gEqviti){CloseAll();Print("CloseAll");GlobalVariableDel("stop");return(false);} else{Comment( "EQUITY TRALING MODE\n", "EQUITY TRALING STEP =",EqvTralStep," %", "\nACCOUNT BALANS = ",AccountBalance(), "\nCLOSE LEVEL = ",gEqviti, "\nACCOUNT EQUITY = ",AccountEquity(), "\nNEXT STEP = ",gEqviti+(gEqviti/100*EqvTralStep)); return(true); } } return(false); } //+------------------------------------------------------------------+ //| ïðîâåðÿåò ðûíî÷íûé îðäåð íà ïðèíàäëåæíîñòü ñîãëàñíî óñëîâèÿì | //+------------------------------------------------------------------+ bool IfOrder(string Sy="",int Typ=-1,int Magik=-1){ if(Sy=="0"){Sy=Symbol();} if(OrderSymbol()==Sy||Sy==""){ if(OrderType()==Typ||Typ==(-1)){ if(OrderMagicNumber()==Magik||Magik==(-1)){ return(true); } } } return(false); } //+------------------------------------------------------------------+ //| Ïîäñ÷èòûâàåò êîëè÷åñòâî îòêðûòûõ îðäåðîâ ñîãëàñíî óñëîâèÿì | //+------------------------------------------------------------------+ int CountOpOrd(string Sy="",int Typ=-1,int Magik=-1){int count=0; if(Sy=="0"){Sy=Symbol();} for(int i=0;i<OrdersTotal();i++){ if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){ if(OrderSymbol()==Sy||Sy==""){ if(OrderType()==Typ||Typ==(-1)){ if(OrderMagicNumber()==Magik||Magik==(-1)){ count++; } } } } } return(count); } //+----------------------------------------------------------------------------+ // Ïîäñ÷èòûâàåò Îáùóþ íå ðåàëèçîâàííóþ ïðèáûëü íà äàííîì èíñòðóìåíòå + //-----------------------------------------------------------------------------+ double PorfitBuySell(int tip){double grpr=0; if(OrdersTotal()<1){return(-1);} for(int n=OrdersTotal()+1;n>=0;n--){ if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){ if(IfOrder("0",tip)){grpr=grpr+OrderProfit();} } } return(grpr); } //+----------------------------------------------------------------------------+ // Çàêðûâàåò âñå îðäåðà íà äàííîì èíñòðóìåíòå + //-----------------------------------------------------------------------------+ void CloseAll(){ while(OrdersTotal()>0){ for(int n=OrdersTotal()+1;n>=0;n--){ if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){ del(OrderTicket()); } } } return; } //+----------------------------------------------------------------------------+ // Çàäàåò ïàóçó ìåæäó óñòàíîâêàìè îðäåðîâ + //-----------------------------------------------------------------------------+ bool TimeOfTrade(){int count=0,distanse=0;double OpPrs=0; if(OrdersTotal()<1){return(true);} for(int n=0;n<OrdersTotal();n++){ if(OrderSelect(n,SELECT_BY_POS,MODE_TRADES)){ if(OrderSymbol()==Symbol()){ if(OrderOpenTime()>count){count=OrderOpenTime();OpPrs=OrderOpenPrice();} } } } if(OpPrs!=0){distanse=(MathAbs(OpPrs-Bid)/Point)/20*(Bid*Point);} if((TimeCurrent()-count)>((MinTradePause*(distanse+1))*60)){return(true);} return(false); } //-----------------------------------------------------------------------------+ // Ôóíêöèÿ êîíòðîëÿ íîâîãî áàðà | //-----------------------------------------------------------------------------+ bool NevBar(){ static int PrevTime=0; if (PrevTime==Time[0]) return(false); PrevTime=Time[0]; return(true);} //-----------------------------------------------------------------------------+ //Óäàëÿåò ðûíî÷íûé îðäåð ñ óêàçàííûì åé òèêåòîì | //+----------------------------------------------------------------------------+ void del(int ticket){int err; for(int i=0;i<1;i++){ GetLastError();//îáíóëÿåì îøèêó OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES); string symbol = OrderSymbol(); if(OrderType()==OP_BUY){RefreshRates(); double prise = MarketInfo(symbol,MODE_BID); if(!OrderClose(ticket,OrderLots(),prise,3,Green)){err = GetLastError();}} if(OrderType()==OP_SELL){RefreshRates(); prise = MarketInfo(symbol,MODE_ASK); if(!OrderClose(ticket,OrderLots(),prise,3,Green)){err = GetLastError();}} if(err == 0){PlaySound("expert.wav");break;} if(err != 0){PlaySound("timeout.wav");Print("Error for Close Funtion =",err);} while(!IsTradeAllowed()){Sleep(5000);}// åñëè ðûíîê çàíÿò òî ïîäîæäåì 5 ñåê if (err==146) while (IsTradeContextBusy()) Sleep(1000*11); } } //-----------------------------------------------------------------------------+ //___________________ÊÈÌÓ_______ÐÅÑÏÅÊÒ________È_____ÓÂÀÆÓÕÀ___________________| //+----------------------------------------------------------------------------+ //| Àâòîð : Êèì Èãîðü Â. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Âåðñèÿ : 01.09.2005 | //| Îïèñàíèå : Âûâîä ñîîáùåíèÿ â êîììåíò è â æóðíàë | //+----------------------------------------------------------------------------+ //| Ïàðàìåòðû: | //| m - òåêñò ñîîáùåíèÿ | //+----------------------------------------------------------------------------+ void Message(string m) { //Comment(m); if (StringLen(m)>0) Print(m); } //+----------------------------------------------------------------------------+ //| Àâòîð : Êèì Èãîðü Â. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Âåðñèÿ : 28.11.2006 | //| Îïèñàíèå : Ìîäèôèêàöèÿ îäíîãî ïðåäâàðèòåëüíî âûáðàííîãî îðäåðà. | //+----------------------------------------------------------------------------+ //| Ïàðàìåòðû: | //| pp - öåíà óñòàíîâêè îðäåðà | //| sl - öåíîâîé óðîâåíü ñòîïà | //| tp - öåíîâîé óðîâåíü òåéêà | //| ex - äàòà èñòå÷åíèÿ | //+----------------------------------------------------------------------------+ void ModifyOrder(double pp=-1, double sl=0, double tp=0, datetime ex=0) { bool fm; color cl=White; double op, pa, pb, os, ot; int dg=MarketInfo(OrderSymbol(), MODE_DIGITS), er, it; if (pp<=0) pp=OrderOpenPrice(); if (sl<0 ) sl=OrderStopLoss(); if (tp<0 ) tp=OrderTakeProfit(); pp=NormalizeDouble(pp, dg); sl=NormalizeDouble(sl, dg); tp=NormalizeDouble(tp, dg); op=NormalizeDouble(OrderOpenPrice() , dg); os=NormalizeDouble(OrderStopLoss() , dg); ot=NormalizeDouble(OrderTakeProfit(), dg); //if(OrderType()==0||OrderType()==2||OrderType()==4){if(Ask-stoplevel<sl||Bid+stoplevel>tp){return;}} //if(OrderType()==1||OrderType()==3||OrderType()==5){if(Bid+stoplevel>sl||Ask-stoplevel<tp){return;}} //if(MathAbs(sl-Ask)<stoplevel||MathAbs(tp-Ask)<stoplevel){return;} if(pp==op&&sl==os&&tp==ot){return;} if ((sl==os&&(os!=0||sl!=0))&& (tp==ot&&(ot!=0||tp!=0))) {return;} for (it=1; it<=NumberOfTry; it++) { //if ((!IsExpertEnabled() || IsStopped())) break; while (!IsTradeAllowed()) Sleep(5000); RefreshRates(); fm=OrderModify(OrderTicket(), pp, sl, tp, ex, cl); if (fm) { if (UseSound) PlaySound(NameFileSound); break; } else { er=GetLastError(); pa=MarketInfo(OrderSymbol(), MODE_ASK); pb=MarketInfo(OrderSymbol(), MODE_BID); if(print){Print("Error(",er,") modifying order: ",ErrorDescription(er),", try ",it); Print("Ask=",pa," Bid=",pb," sy=",OrderSymbol(), " op="+GetNameOP(OrderType())," pp=",pp," sl=",sl," tp=",tp);} Sleep(1000*10); //if(er==130){del(OrderTicket());} } } //} } //+----------------------------------------------------------------------------+ //| Àâòîð : Êèì Èãîðü Â. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Âåðñèÿ : 06.03.2008 | //| Îïèñàíèå : Âîçâðàùàåò ôëàã ñóùåñòâîâàíèÿ ïîçèöèé | //+----------------------------------------------------------------------------+ //| Ïàðàìåòðû: | //| sy - íàèìåíîâàíèå èíñòðóìåíòà ("" - ëþáîé ñèìâîë, | //| NULL - òåêóùèé ñèìâîë) | //| op - îïåðàöèÿ (-1 - ëþáàÿ ïîçèöèÿ) | //| mn - MagicNumber (-1 - ëþáîé ìàãèê) | //| ot - âðåìÿ îòêðûòèÿ ( 0 - ëþáîå âðåìÿ îòêðûòèÿ) | //+----------------------------------------------------------------------------+ bool ExistPositions(string sy="", int op=-1, int mn=-1, datetime ot=0) { int i, k=OrdersTotal(); if (sy=="0") sy=Symbol(); for (i=0; i<k; i++) { if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderSymbol()==sy || sy=="") { if (OrderType()==OP_BUY || OrderType()==OP_SELL) { if (op<0 || OrderType()==op) { if (mn<0 || OrderMagicNumber()==mn) { if (ot<=OrderOpenTime()) return(True); } } } } } } return(False); } //+----------------------------------------------------------------------------+ //| Àâòîð : Êèì Èãîðü Â. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Âåðñèÿ : 01.09.2005 | //| Îïèñàíèå : Âîçâðàùàåò íàèìåíîâàíèå òîðãîâîé îïåðàöèè | //+----------------------------------------------------------------------------+ //| Ïàðàìåòðû: | //| op - èäåíòèôèêàòîð òîðãîâîé îïåðàöèè | //+----------------------------------------------------------------------------+ string GetNameOP(int op) { switch (op) { case OP_BUY : return("Buy"); case OP_SELL : return("Sell"); case OP_BUYLIMIT : return("BuyLimit"); case OP_SELLLIMIT: return("SellLimit"); case OP_BUYSTOP : return("BuyStop"); case OP_SELLSTOP : return("SellStop"); default : return("Unknown Operation"); } } //+----------------------------------------------------------------------------+ //| Àâòîð : Êèì Èãîðü Â. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Âåðñèÿ : 10.04.2008 | //| Îïèñàíèå : Îòêðûâàåò ïîçèöèþ ïî ðûíî÷íîé öåíå. | //+----------------------------------------------------------------------------+ //| Ïàðàìåòðû: | //| sy - íàèìåíîâàíèå èíñòðóìåíòà (NULL èëè "" - òåêóùèé ñèìâîë) | //| op - îïåðàöèÿ | //| ll - ëîò | //| sl - óðîâåíü ñòîï | //| tp - óðîâåíü òåéê | //| mn - MagicNumber | //+----------------------------------------------------------------------------+ void OpenPosition(string sy, int op, double ll, double Sl=0, double Tp=0, int mn=0) { color clOpen; datetime ot; double pp, pa, pb, tp ,sl; int dg, err, it, ticket=0; string lsComm=""; if (sy=="" || sy=="0") sy=Symbol(); int stoplevel=MarketInfo(sy,MODE_STOPLEVEL); int spread=MarketInfo(sy,MODE_SPREAD); if(Tp!=0&&Tp<stoplevel+spread){Tp=stoplevel;} if (op<1){ if (Sl>0) {sl=MarketInfo(Symbol(),MODE_ASK)-Sl*Point; }else {sl=0;} if (Tp>0) {tp=MarketInfo(Symbol(),MODE_ASK)+Tp*Point; }else{ tp=0;} }else{ if (Sl>0) {sl=MarketInfo(Symbol(),MODE_BID)+Sl*Point; }else{ sl=0;} if (Tp>0) {tp=MarketInfo(Symbol(),MODE_BID)-Tp*Point;} else {tp=0;}} if (op==OP_BUY) clOpen=clOpenBuy; else clOpen=clOpenSell; for (it=1; it<=NumberOfTry; it++) { if (IsStopped()) { Print("OpenPosition(): Îñòàíîâêà ðàáîòû ôóíêöèè"); break;} while (!IsTradeAllowed()) Sleep(5000); RefreshRates(); dg=MarketInfo(sy, MODE_DIGITS); pa=MarketInfo(sy, MODE_ASK); pb=MarketInfo(sy, MODE_BID); if (op==OP_BUY) pp=pa; else pp=pb; pp=NormalizeDouble(pp, dg); ot=TimeCurrent(); if (MarketWatch) ticket=OrderSend(sy, op, ll, pp, Slippage, 0, 0, lsComm, mn, 0, clOpen); else ticket=OrderSend(sy, op, ll, pp, Slippage, sl, tp, lsComm, mn, 0, clOpen); if (ticket>0) { if (UseSound) PlaySound(NameFileSound); break; } else { err=GetLastError(); if (pa==0 && pb==0) Message("Ïðîâåðüòå â Îáçîðå ðûíêà íàëè÷èå ñèìâîëà "+sy); // Âûâîä ñîîáùåíèÿ îá îøèáêå if(print){ Print("Error(",err,") opening position: ",ErrorDescription(err),", try ",it); Print("Ask=",pa," Bid=",pb," sy=",sy," ll=",ll," op=",GetNameOP(op), " pp=",pp," sl=",sl," tp=",tp," mn=",mn);} // Áëîêèðîâêà ðàáîòû ñîâåòíèêà if (err==2 || err==64 || err==65 || err==133) { gbDisabled=True; break; } // Äëèòåëüíàÿ ïàóçà if (err==4 || err==131 || err==132) { Sleep(1000*300); break; } if (err==128 || err==142 || err==143) { Sleep(1000*66.666); if (ExistPositions(sy, op, mn, ot)) { if (UseSound) PlaySound(NameFileSound); break; } } if (err==140 || err==148 || err==4110 || err==4111) break; if (err==141) Sleep(1000*100); if (err==145) Sleep(1000*17); if (err==146) while (IsTradeContextBusy()) Sleep(1000*11); if (err!=135) Sleep(1000*7.7); } } if (MarketWatch && ticket>0 && (sl>0 || tp>0)) { if (OrderSelect(ticket, SELECT_BY_TICKET)) ModifyOrder(-1, sl, tp); } } //+----------------------------------------------------------------------------+
Sample
Analysis
Market Information Used:
Series array that contains open time of each bar
Series array that contains open prices of each bar
Series array that contains close prices for each bar
Indicator Curves created:
Indicators Used:
Custom Indicators Used:
Order Management characteristics:
Checks for the total of open orders
It Closes Orders by itself
It can change open orders parameters, due to possible stepping strategy
It automatically opens orders when conditions are reached
Other Features:
It issuies visual alerts to the screen
It plays sound alerts