//+------------------------------------------------------------------+ //| Price Movements.mq4 | //| Copyright 2014, Moneystrategy.ru | //| http://www.moneystrategy.ru | //+------------------------------------------------------------------+ #property copyright "Copyright (c) 2014. Moneystrategy.ru" #property link "http://www.moneystrategy.ru" #property version "1.0" #property description "Советник работает непосредственно с ценой и не использует технические индикаторы.\n" "Все вычисления осуществляются с применением текущей цены и времени. Когда\n" "скорость цены резко возрастает, советник открывает ордер в сторону её движения.\n" "Не использует в торговле высокорискованных стратегий на подобии Мартингейла.\n" "Скорость движения цены измеряется пробитием виртуальных уровней, которые\n" "устанавливаются от текущей цены и модифицируются по истечении заданного времени.\n" "Работает на 4 и 5 знаке.\n" #property strict #include #include #define miz 0.00000001 extern double Lots = 0.01; extern double MaxRisk = 5; extern double TakeProfit = 250; extern double StopLoss = 10; extern int TrailingStop = 5; extern int TrailingStep = 10; extern int PriceStep = 10; extern int TimeStep = 15; extern int Slipage = 2; extern int MaxTrades = 5; extern int Magic = 12345; extern int LicenseKey = 0; extern color TextColor = clrWhite; color UpCol = 0; color DnCol = 0; string Com = ""; string Symboll = Symbol(); int Number = 12345; int AccNumber; bool Demo = (!IsDemo()) && (!IsTesting()); datetime time; bool opnovis, sigN=true, testing=false, SignalBuy=true, SignalSell=true; int OnInit() { if (Digits == 3 || Digits == 5) { Slipage = Slipage *= 10; PriceStep = PriceStep *= 10; TakeProfit = TakeProfit *= 10; StopLoss = StopLoss *= 10; TrailingStop = TrailingStop *= 10; TrailingStep = TrailingStep *= 10; } AccNumber = AccountNumber(); time = TimeCurrent(); if(IsOptimization() || (IsTesting() && !IsVisualMode())) { opnovis=false; } else opnovis=true; if (IsTesting()) { if(IsVisualMode() != true) { Print("Ошибка! Включите визуальный режим"); } } if(!IsOptimization() && !IsTesting()) EventSetTimer(1); else testing=true; DelBP(Com); return(INIT_SUCCEEDED); } void OnDeinit(const int reason) { if(IsTesting() || IsOptimization())return; EventKillTimer(); int ur = UninitializeReason(); if(ur == 1 || ur == 6) DelBP(Com); ObjectsDeleteAll(); return; } void OnTick() { if(!IsTradeAllowed()) { SetLabel("Label1", " Внимание! Работа советника на счете № " + DoubleToString( AccountNumber(), 0) + " не разрешена.", TextColor, 5, 30); SetLabel("Label2", " У Вас не включена Авто-торговля. Для решения данной проблемы,", TextColor, 5, 50); SetLabel("Label3", " Вам нужно разрешить Авто-торговлю советниками. Для этого", TextColor, 5, 70); SetLabel("Label4", " нажмите на кнопку Авто-торговля на панели инструментов,", TextColor, 5, 90); SetLabel("Label5", " кнопка должна стать зеленой.", TextColor, 5, 110); SetLabel("Label6", " ", TextColor, 5, 130); SetLabel("Label7", " ", TextColor, 5, 150); return; } if (Demo && LicenseKey != 5 * AccNumber + Number) { SetLabel("Label1", " Внимание! Работа советника на счете № " + DoubleToString( AccountNumber(), 0) + " запрещена.", TextColor, 5, 30); SetLabel("Label2", " Возможно Вы не ввели лицензионный ключ или ошиблись при его", TextColor, 5, 50); SetLabel("Label3", " написании. Пожалуйста, проверьте правильность ввода номера", TextColor, 5, 70); SetLabel("Label4", " и повторите попытку. Если у Вас нет лицензионного номера", TextColor, 5, 90); SetLabel("Label5", " ключа, то Вы можете его приобрести. Стоимость лицензии для", TextColor, 5, 110); SetLabel("Label6", " одного номера торгового счета составляет 25 USD.", TextColor, 5, 130); SetLabel("Label7", " Контакты: mail@moneystrategy.ru.", TextColor, 5, 150); return; } double ProfCount = Profit(0); SetLabel("Label1", " Гарантированная прибыль по открытой сделке: " + (DoubleToString(ProfitIFStopInCurrency(Symbol(), OrderType(), OrderMagicNumber()), 2)) + " " + AccountCurrency(), TextColor, 5, 30); SetLabel("Label2", " Прибыль/Убыток предыдущей сделки: " + (DoubleToString(profhistory(Symbol(), OrderType(), OrderMagicNumber()), 2)) + " " + AccountCurrency(), TextColor, 5, 50); SetLabel("Label3", " Прибыль/Убыток за сегодня: " + DoubleToStr(Profit(0), 2) + " " + AccountCurrency(), TextColor, 5, 70); SetLabel("Label4", " Прибыль/Убыток вчера: " + DoubleToStr(Profit(1), 2) + " " + AccountCurrency(), TextColor, 5, 90); SetLabel("Label5", " Прибыль/Убыток в текущем месяце: " + DoubleToStr(ProfitMons(0), 2) + " " + AccountCurrency(), TextColor, 5, 110); SetLabel("Label6", " Прибыль/Убыток в предыдущем месяце: " + DoubleToStr(ProfitMons(1), 2) + " " + AccountCurrency(), TextColor, 5, 130); SetLabel("Label7", " Ваш текущий баланс: " + DoubleToStr(AccountBalance(), 2) + " " + AccountCurrency(), TextColor, 5, 150); if(TrailingStop>0)MoveTrailingStop(); CloseAllOrders(); time=TimeCurrent(); if(testing) { if(TimeStep==0)sigN=true; else { static datetime tim; if(tim==0)tim=time; if(time>=tim+TimeStep){sigN=true;tim+=TimeStep;} } } if(sigN) { datetime tim1=iTime(_Symbol,0,0),tim2=tim1+_Period*240; double pr=Ask+PriceStep*_Point; Tline(Com+"Up",tim1,pr,tim2,pr,UpCol,true); pr=Bid-PriceStep*_Point; Tline(Com+"Dn",tim1,pr,tim2,pr,DnCol,true); sigN=false; SignalBuy=true; SignalSell=true; } if(SignalBuy) { double up=GetDou(Com+"Up",OBJPROP_PRICE1); if(up>0.0 && !(up-Ask>miz)) { if(DayOfWeek() == 5 && Hour() >= 22) { return; } if (CountBuy() + CountSell() <= MaxTrades - 1) int ticket = OrderSend (Symbol(), OP_BUY, LotByRisk(), Ask, Slipage, Ask-StopLoss*Point, Ask+TakeProfit*Point, "", Magic, 0, clrNONE);SignalBuy=false; } } if(SignalSell) { double dn=GetDou(Com+"Dn",OBJPROP_PRICE1); if(dn>0.0 && !(Bid-dn>miz)) { if(DayOfWeek() == 5 && Hour() >= 22) { return; } if (CountBuy() + CountSell() <= MaxTrades - 1) int ticket = OrderSend (Symbol(), OP_SELL, LotByRisk(), Bid, Slipage, Bid+StopLoss*Point, Bid-TakeProfit*Point, "", Magic, 0, clrNONE);SignalSell=false; } } } int CountBuy() { int count = 0; for (int i = OrdersTotal() - 1; i >= 0; i --) { if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == OP_BUY) count ++; } } return (count); } int CountSell() { int count = 0; for (int i = OrdersTotal() - 1; i >= 0; i --) { if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == OP_SELL) count ++; } } return (count); } double LotByRisk(int op_type, double risk, int sl) { double lot_min = MarketInfo(Symbol(), MODE_MINLOT); double lot_max = MarketInfo(Symbol(), MODE_MAXLOT); double lot_steep = MarketInfo(Symbol(), MODE_LOTSTEP); double lot_cost = MarketInfo(Symbol(), MODE_TICKVALUE); double lot = 0; double pip_cost = 0; lot = AccountBalance() * risk/100; pip_cost = lot/sl; lot = NormalizeDouble(pip_cost/lot_cost, 2); lot = NormalizeDouble(lot/lot_steep, 0) * lot_steep; if (lot < lot_min) lot = lot_min; if (lot > lot_max) lot = lot_max; return(lot); } void Tline(string name,datetime tim1,double pr1,datetime tim2,double pr2,color col,bool fl=false) { if(!opnovis)return; if(ObjectFind(name)<0){if(!ObjectCreate(name,OBJ_TREND,0,tim1,pr1,tim2,pr2))return;} ObjectSetInteger(0,name,OBJPROP_COLOR,col); ObjectSetInteger(0,name,OBJPROP_TIMEFRAMES,-1); ObjectSetInteger(0,name,OBJPROP_TIME1,tim1); ObjectSetInteger(0,name,OBJPROP_TIME2,tim2); ObjectSetDouble(0,name,OBJPROP_PRICE1,pr1); ObjectSetDouble(0,name,OBJPROP_PRICE2,pr2); if(fl)ChartRedraw(); } double GetDou(string name,int id) { double res=0.0; if(opnovis && ObjectFind(name)>-1)res=ObjectGetDouble(0,name,id); return(res); } void DelBP(string name) { if(!opnovis)return; int obj=ObjectsTotal(); for(int i=obj-1;i>=0;i--) {if(StringFind(ObjectName(i),name,0)==0)ObjectDelete(ObjectName(i));} } void OnTimer() { static int sec; sec++; if(sec>=TimeStep){sigN=true;sec=0;OnTick();} } void SetLabel(string nm, string tx, color cl, int xd, int yd, int cr=0, int fs=12) { if (ObjectFind(nm)<0) ObjectCreate(nm, OBJ_LABEL, 0, 0,0); ObjectSetText(nm, tx, fs); ObjectSet(nm, OBJPROP_COLOR , cl); ObjectSet(nm, OBJPROP_XDISTANCE, xd); ObjectSet(nm, OBJPROP_YDISTANCE, yd); ObjectSet(nm, OBJPROP_CORNER , cr); ObjectSet(nm, OBJPROP_FONTSIZE , fs); ObjectSet(nm, OBJPROP_BACK , false); ObjectSet(nm, OBJPROP_SELECTABLE , false); ObjectSet(nm, OBJPROP_READONLY , false); } double LotByRisk() {double Free =AccountFreeMargin(); double LotVal =MarketInfo(Symbol(),MODE_TICKVALUE); double Min_Lot =MarketInfo(Symbol(),MODE_MINLOT); double Max_Lot =MarketInfo(Symbol(),MODE_MAXLOT); double Step1 =MarketInfo(Symbol(),MODE_LOTSTEP); double Lot =MathFloor((Free*MaxRisk/100)/(StopLoss*LotVal)/Step1)*Step1; if(LotMax_Lot) Lot=Max_Lot; return(Lot);} void MoveTrailingStop() { int cnt,total=OrdersTotal(); for(cnt=0;cnt0) { if((NormalizeDouble(OrderStopLoss(),Digits)0) { if((NormalizeDouble(OrderStopLoss(),Digits)>(NormalizeDouble(Ask+Point*(TrailingStop+TrailingStep),Digits)))||(OrderStopLoss()==0)) { bool res = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Ask+Point*TrailingStop,Digits),OrderTakeProfit(),0,Red); } } } } } } } double profhistory(string t,int x, int m) { string sym=""; int z=0 ; double prof=0; if ( t=="") sym=Symbol(); else sym = t ; for( int i=OrdersHistoryTotal()-1; i>=0; i-- ) if ( OrderSelect(i,SELECT_BY_POS,MODE_HISTORY) == true ) if ( OrderSymbol() == sym && (OrderMagicNumber() == m || m==-1 ) && OrderType()<=1) if ( x == -1 || OrderType() == x ) if ( OrderCloseTime()>z) {z =OrderCloseTime(); prof=OrderProfit();} return(prof);} double Profit(int Bar) { double OProfit = 0; for (int i = 0; i < OrdersHistoryTotal(); i ++) { if (!(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))) break; if ((OrderSymbol() == Symbol() && OrderMagicNumber() == Magic ) || ( Magic < 0 && Symboll == "-1" ) || (Symboll == OrderSymbol()) || (Symboll == "0" && OrderSymbol() == Symbol())) if (OrderCloseTime() >= iTime(Symbol(), PERIOD_D1, Bar) && OrderCloseTime() < iTime(Symbol(), PERIOD_D1, Bar) + 86400) OProfit += OrderProfit(); } return (OProfit); } double ProfitMons(int Bar) { double OProfit = 0; for (int i = 0; i < OrdersHistoryTotal(); i ++) { if (!(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))) break; if ((OrderSymbol() == Symbol() && OrderMagicNumber() == Magic ) || ( Magic < 0 && Symboll == "-1" ) || (Symboll == OrderSymbol()) || (Symboll == "0" && OrderSymbol() == Symbol())) if (OrderCloseTime() >= iTime(Symbol(), PERIOD_MN1, Bar) && OrderCloseTime() < iTime(Symbol(), PERIOD_MN1, Bar) + 2592000) OProfit += OrderProfit(); } return (OProfit); } double ProfitIFStopInCurrency(string sy="", int op=-1, int mn=-1) { if (sy=="0") sy=Symbol(); int i, k = OrdersTotal(); int m = 0; double l; double p; double t; double v; double s = 0; for (i=0; i0) { if (m==0) s-=(OrderStopLoss()-OrderOpenPrice())/p*v*OrderLots(); if (m==1) s-=(OrderStopLoss()-OrderOpenPrice())/p*v/t/l*OrderLots(); if (m==2) s-=(OrderStopLoss()-OrderOpenPrice())/p*v*OrderLots(); s+=OrderCommission()+OrderSwap(); } else s=-AccountBalance(); } } } } } if (AccountBalance()+s<0) s=-AccountBalance(); return(s); } double lotshistory(string t,int x, int m) { string sym=""; int z=0 ; double lot=0; if ( t=="") sym=Symbol(); else sym = t ; int d=OrdersHistoryTotal(),i;for( i=0;i<=d;i++) if ( OrderSelect(i,SELECT_BY_POS,MODE_HISTORY) == true ) if ( OrderSymbol() == sym && (OrderMagicNumber() == m || m==-1 ) && OrderType()<=1) if ( x == -1 || OrderType() == x ) if ( OrderCloseTime()>z) {z =OrderCloseTime(); lot=OrderLots();} return(lot);} void CloseAllOrders() { if(DayOfWeek() == 5 && Hour() >= 22) { for(int cnt = OrdersTotal()-1;cnt >= 0; cnt--) { if( !OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES) ) continue; if( OrderSymbol()==Symbol() && OrderMagicNumber() == Magic) { if(OrderType()==OP_SELL) { bool CloseAllOrders = OrderClose(OrderTicket(), OrderLots(), Ask, Slipage, clrNONE); } else if(OrderType()==OP_BUY) { bool CloseAllOrders = OrderClose(OrderTicket(), OrderLots(), Bid, Slipage, clrNONE); } } } } }