Asesores Expertos: 2MA Bunny Cross Expert - página 2 12 Nuevo comentario Александр Князев 2020.10.01 10:26 #11 hmm, y tengo errores de compilacion init fails en las lineas 281 y 287. Y como consecuencia no puedo ejecutar nada=( Vladimir Karputov 2020.10.01 10:31 #12 Александр Князев:hmm, y tengo errores de compilacion init fails en las lineas 281 y 287. Y como consecuencia no puedo ejecutar nada=( Fíjate bien QUÉ y DÓNDE descargas. De momento la versión 1.003 la descargo de la parte rusa de KodoBase y compila sin errores. Foro sobre trading, sistemas automatizados de trading y testeo de estrategias de trading. Asesores Expertos: 2MA Bunny Cross Expert Vladimir Karputov, 2019.05.01 15:17 Aquí hay una pista: https: //www.mql5.com/ru/code/16783 Experts: 2MA Bunny Cross Asesores Expertos: ZigZag EA Discusión sobre el artículo Le Nam 2020.12.06 12:53 #13 cảm ơn bạn về código nhưng nó không hoạt động khi nén lại n ó báo lỗi bạn có thể chỉ tôi cách khắc phục không ? xin cảm ơn. Experts: 2MA Bunny Cross Indicators with alerts/signal Discussing the article: "From Vladimir Karputov 2020.12.06 13:07 #14 Le Nam : cảm ơn bạn về código. nhưng nó không hoạt động khi nén lại n ó báo lỗi bạn có thể chỉ tôi cách khắc phục không ? xin cảm ơn. La versión 1.003 está disponible en el foro ruso: https: //www.mql5.com/ru/code/16783 Sebastien Pierre Valla 2021.02.06 17:53 #15 Hola, Gracias por tu ea, lo modifique para cambiar los periodos MA, es bien rentable. A continuación el código modificado //+------------------------------------------------------------------+ //| 2MA Bunny Cross Expert(barabashkakvn's edition).mq5 || //|Copyright © Ron Thompson | //|http://www.lightpatch.com/forex/ || //+------------------------------------------------------------------+ #property copyright "Ron Thompson" #property link "http://www.lightpatch.com/forex" #property version "1.003" //--- #include <Trade\PositionInfo.mqh> #include <Trade\Trade.mqh> #include <Trade\SymbolInfo.mqh> #include <Trade\AccountInfo.mqh> #include <Expert\Money\MoneyFixedMargin.mqh> CPositionInfo m_position; // objeto de posición comercial CTrade m_trade; // objeto comercial CSymbolInfo m_symbol; // objeto de información de símbolos CAccountInfo m_account; // información de la cuenta CMoneyFixedMargin *m_money; //--- parámetros de entrada input double InpLots = 0; // Lotes (o "Lotes">0 y "Riesgo"==0 o "Lotes"==0 y "Riesgo">0) input double Risk = 5; // Riesgo (o "Lotes">0 y "Riesgo"==0 o "Lotes"==0 y "Riesgo">0) input int PeriodMAS=20; // Period of the fast MA input int PeriodMAF=5; input ulong m_magic=319906800; // número mágico //--- ulong m_slippage=10; // deslizamiento int handle_iMA_5; // variable para almacenar el asa del indicador iMA int handle_iMA_20; // variable para almacenar el asa del indicador iMA //+------------------------------------------------------------------+ //| Función de inicialización experta| //+------------------------------------------------------------------+ int OnInit() { if(!m_symbol.Name(Symbol())) // establece el nombre del símbolo return(INIT_FAILED); RefreshRates(); //--- m_trade.SetExpertMagicNumber(m_magic); m_trade.SetMarginMode(); m_trade.SetTypeFillingBySymbol(m_symbol.Name()); m_trade.SetDeviationInPoints(m_slippage); //--- sintonización para 3 o 5 dígitos int digits_adjust=1; if(m_symbol.Digits()==3 || m_symbol.Digits()==5) digits_adjust=10; //--- if(!LotsOrRisk(InpLots,Risk,digits_adjust)) return(INIT_PARAMETERS_INCORRECT); //--- if(m_money!=NULL) delete m_money; m_money=new CMoneyFixedMargin; if(m_money!=NULL) { if(!m_money.Init(GetPointer(m_symbol),Period(),m_symbol.Point()*digits_adjust)) return(INIT_FAILED); m_money.Percent(Risk); } else { Print(__FUNCTION__,", ERROR: Object CMoneyFixedMargin is NULL"); return(INIT_FAILED); } //--- crear asa del indicador iMA handle_iMA_5=iMA(m_symbol.Name(),Period(),PeriodMAF,0,MODE_SMA,PRICE_WEIGHTED); //--- si no se crea el manejador if(handle_iMA_5==INVALID_HANDLE) { //--- informa del fallo y muestra el código de error PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d", m_symbol.Name(), EnumToString(Period()), GetLastError()); //--- el indicador se detiene antes de tiempo return(INIT_FAILED); } //--- crear asa del indicador iMA handle_iMA_20=iMA(m_symbol.Name(),Period(),PeriodMAS,3,MODE_SMA,PRICE_WEIGHTED); //--- si no se crea el manejador if(handle_iMA_20==INVALID_HANDLE) { //--- informa del fallo y muestra el código de error PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d", m_symbol.Name(), EnumToString(Period()), GetLastError()); //--- el indicador se detiene antes de tiempo return(INIT_FAILED); } //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Función de desinicialización experta| //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- if(m_money!=NULL) delete m_money; } //+------------------------------------------------------------------+ //| Función tick experto| //+------------------------------------------------------------------+ void OnTick() { //--- trabajamos sólo en el momento del nacimiento de nuevo bar static datetime PrevBars=0; datetime time_0=iTime(m_symbol.Name(),Period(),0); if(time_0==PrevBars) return; PrevBars=time_0; //--- double ArrayMA5[]; ArraySetAsSeries(ArrayMA5,true); double ArrayMA20[]; ArraySetAsSeries(ArrayMA20,true); if(!iMAGetArray(handle_iMA_5,0,3,ArrayMA5) || !iMAGetArray(handle_iMA_20,0,3,ArrayMA20) || !RefreshRates()) { PrevBars=0; return; } //--- bool signal_buy=(ArrayMA5[2]<ArrayMA20[2] && ArrayMA5[1]>ArrayMA20[1]); bool signal_sell=(ArrayMA5[2]>ArrayMA20[2] && ArrayMA5[1]<ArrayMA20[1]); //--- if(signal_buy) { ClosePositions(POSITION_TYPE_SELL); OpenBuy(0.0,0.0); } if(signal_sell) { ClosePositions(POSITION_TYPE_BUY); OpenSell(0.0,0.0); } //--- } //+------------------------------------------------------------------+ //| Función TradeTransaction| //+------------------------------------------------------------------+ void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result) { //--- } //+------------------------------------------------------------------+ //| Obtener el valor de los buffers para el iMA en el array || //+------------------------------------------------------------------+ bool iMAGetArray(const int handle_iMA,const int start_pos,const int count,double &arr_buffer[]) { //--- bool result=true; if(!ArrayIsDynamic(arr_buffer)) { Print("This a no dynamic array!"); return(false); } ArrayFree(arr_buffer); int buffer_num=0; // número del búfer indicador //--- restablecer código de error ResetLastError(); //--- rellenar una parte del array iMABuffer con valores del buffer indicador que tiene índice 0 int copied=CopyBuffer(handle_iMA,buffer_num,start_pos,count,arr_buffer); if(copied<0) { //--- si la copia falla, indique el código de error PrintFormat("Failed to copy data from the iMA indicator, error code %d",GetLastError()); //--- salir con resultado cero - significa que el indicador se considera como no calculado return(false); } else if(copied<count) { PrintFormat("Moving Average indicator: %d elements from %d were copied",copied,count); DebugBreak(); return(false); } //--- return(result); } //+------------------------------------------------------------------+ //| Cerrar posiciones| //+------------------------------------------------------------------+ void ClosePositions(const ENUM_POSITION_TYPE pos_type) { for(int i=PositionsTotal()-1;i>=0;i--) // devuelve el número de posiciones actuales if(m_position.SelectByIndex(i)) // selecciona la posición por el índice para acceder posteriormente a sus propiedades if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==m_magic) if(m_position.PositionType()==pos_type) // obtiene el tipo de posición m_trade.PositionClose(m_position.Ticket()); // cerrar una posición por el símbolo especificado } //+------------------------------------------------------------------+ //| Actualiza los datos de las cotizaciones de los símbolos| //+------------------------------------------------------------------+ bool RefreshRates(void) { //--- frecuencias de actualización if(!m_symbol.RefreshRates()) { Print("RefreshRates error"); return(false); } //--- protección contra el valor de retorno de "cero" if(m_symbol.Ask()==0 || m_symbol.Bid()==0) return(false); //--- return(true); } //+------------------------------------------------------------------+ //| Comprobar la corrección del volumen de posición || //+------------------------------------------------------------------+ bool CheckVolumeValue(double volume,string &error_description) { //--- volumen mínimo permitido para operaciones comerciales double min_volume=m_symbol.LotsMin(); if(volume<min_volume) { error_description=StringFormat("Volume is less than the minimal allowed SYMBOL_VOLUME_MIN=%.2f",min_volume); return(false); } //--- volumen máximo permitido de operaciones comerciales double max_volume=m_symbol.LotsMax(); if(volume>max_volume) { error_description=StringFormat("Volume is greater than the maximal allowed SYMBOL_VOLUME_MAX=%.2f",max_volume); return(false); } //--- obtener el paso mínimo de cambio de volumen double volume_step=m_symbol.LotsStep(); int ratio=(int)MathRound(volume/volume_step); if(MathAbs(ratio*volume_step-volume)>0.0000001) { error_description=StringFormat("Volume is not a multiple of the minimal step SYMBOL_VOLUME_STEP=%.2f, the closest correct volume is %.2f", volume_step,ratio*volume_step); return(false); } error_description="Correct volume value"; return(true); } //+------------------------------------------------------------------+ //| Lotes o riesgo en porcentaje para un acuerdo de un margen libre | //+------------------------------------------------------------------+ bool LotsOrRisk(const double lots,const double risk,const int digits_adjust) { if(lots<0.0 && risk<0.0) { Print(__FUNCTION__,", ERROR: Parameter (\"lots\" or \"risk\") can't be less than zero"); return(false); } if(lots==0.0 && risk==0.0) { Print(__FUNCTION__,", ERROR: Trade is impossible: You have set \"lots\" == 0.0 and \"risk\" == 0.0"); return(false); } if(lots>0.0 && risk>0.0) { Print(__FUNCTION__,", ERROR: Trade is impossible: You have set \"lots\" > 0.0 and \"risk\" > 0.0"); return(false); } if(lots>0.0) { string err_text=""; if(!CheckVolumeValue(lots,err_text)) { Print(__FUNCTION__,", ERROR: ",err_text); return(false); } } else if(risk>0.0) { if(m_money!=NULL) delete m_money; m_money=new CMoneyFixedMargin; if(m_money!=NULL) { if(!m_money.Init(GetPointer(m_symbol),Period(),m_symbol.Point()*digits_adjust)) return(false); m_money.Percent(risk); } else { Print(__FUNCTION__,", ERROR: Object CMoneyFixedMargin is NULL"); return(false); } } //--- return(true); } //+------------------------------------------------------------------+ //| Abrir posición de compra| //+------------------------------------------------------------------+ void OpenBuy(double sl,double tp) { sl=m_symbol.NormalizePrice(sl); tp=m_symbol.NormalizePrice(tp); double check_open_long_lot=0.0; if(Risk>0.0) { check_open_long_lot=m_money.CheckOpenLong(m_symbol.Ask(),sl); Print("sl=",DoubleToString(sl,m_symbol.Digits()), ", CheckOpenLong: ",DoubleToString(check_open_long_lot,2), ", Balance: ", DoubleToString(m_account.Balance(),2), ", Equity: ", DoubleToString(m_account.Equity(),2), ", FreeMargin: ", DoubleToString(m_account.FreeMargin(),2)); if(check_open_long_lot==0.0) { Print(__FUNCTION__,", ERROR: method CheckOpenLong returned the value of \"0.0\""); return; } } else check_open_long_lot=InpLots; //--- comprobar el volumen antes de OrderSend para evitar el error "not enough money" (CTrade) double check_volume_lot=m_trade.CheckVolume(m_symbol.Name(),check_open_long_lot,m_symbol.Ask(),ORDER_TYPE_BUY); if(check_volume_lot!=0.0) { if(check_volume_lot>=check_open_long_lot) { if(m_trade.Buy(check_open_long_lot,NULL,m_symbol.Ask(),sl,tp)) { if(m_trade.ResultDeal()==0) { Print("#1 Buy -> false. Result Retcode: ",m_trade.ResultRetcode(), ", description of result: ",m_trade.ResultRetcodeDescription()); PrintResult(m_trade,m_symbol); } else { Print("#2 Buy -> true. Result Retcode: ",m_trade.ResultRetcode(), ", description of result: ",m_trade.ResultRetcodeDescription()); PrintResult(m_trade,m_symbol); } } else { Print("#3 Buy -> false. Result Retcode: ",m_trade.ResultRetcode(), ", description of result: ",m_trade.ResultRetcodeDescription()); PrintResult(m_trade,m_symbol); } } else { string text=""; if(Risk>0.0) text="< method CheckOpenLong ("+DoubleToString(check_open_long_lot,2)+")"; else text="< Lots ("+DoubleToString(InpLots,2)+")"; Print(__FUNCTION__,", ERROR: method CheckVolume (",DoubleToString(check_volume_lot,2),") ", text); return; } } else { Print(__FUNCTION__,", ERROR: method CheckVolume returned the value of \"0.0\""); return; } //--- } //+------------------------------------------------------------------+ //| Abrir posición de venta| //+------------------------------------------------------------------+ void OpenSell(double sl,double tp) { sl=m_symbol.NormalizePrice(sl); tp=m_symbol.NormalizePrice(tp); double check_open_short_lot=0.0; if(Risk>0.0) { check_open_short_lot=m_money.CheckOpenShort(m_symbol.Bid(),sl); Print("sl=",DoubleToString(sl,m_symbol.Digits()), ", CheckOpenLong: ",DoubleToString(check_open_short_lot,2), ", Balance: ", DoubleToString(m_account.Balance(),2), ", Equity: ", DoubleToString(m_account.Equity(),2), ", FreeMargin: ", DoubleToString(m_account.FreeMargin(),2)); if(check_open_short_lot==0.0) { Print(__FUNCTION__,", ERROR: method CheckOpenShort returned the value of \"0.0\""); return; } } else check_open_short_lot=InpLots; //--- comprobar el volumen antes de OrderSend para evitar el error "not enough money" (CTrade) double check_volume_lot=m_trade.CheckVolume(m_symbol.Name(),check_open_short_lot,m_symbol.Bid(),ORDER_TYPE_SELL); if(check_volume_lot!=0.0) { if(check_volume_lot>=check_open_short_lot) { if(m_trade.Sell(check_open_short_lot,NULL,m_symbol.Bid(),sl,tp)) { if(m_trade.ResultDeal()==0) { Print("#1 Sell -> false. Result Retcode: ",m_trade.ResultRetcode(), ", description of result: ",m_trade.ResultRetcodeDescription()); PrintResult(m_trade,m_symbol); } else { Print("#2 Sell -> true. Result Retcode: ",m_trade.ResultRetcode(), ", description of result: ",m_trade.ResultRetcodeDescription()); PrintResult(m_trade,m_symbol); } } else { Print("#3 Sell -> false. Result Retcode: ",m_trade.ResultRetcode(), ", description of result: ",m_trade.ResultRetcodeDescription()); PrintResult(m_trade,m_symbol); } } else { string text=""; if(Risk>0.0) text="< method CheckOpenShort ("+DoubleToString(check_open_short_lot,2)+")"; else text="< Lots ("+DoubleToString(InpLots,2)+")"; Print(__FUNCTION__,", ERROR: method CheckVolume (",DoubleToString(InpLots,2),") ", text); return; } } else { Print(__FUNCTION__,", ERROR: method CheckVolume returned the value of \"0.0\""); return; } //--- } //+------------------------------------------------------------------+ //| Imprimir resultado CTrade| //+------------------------------------------------------------------+ void PrintResult(CTrade &trade,CSymbolInfo &symbol) { Print("Code of request result: "+IntegerToString(trade.ResultRetcode())); Print("code of request result: "+trade.ResultRetcodeDescription()); Print("deal ticket: "+IntegerToString(trade.ResultDeal())); Print("order ticket: "+IntegerToString(trade.ResultOrder())); Print("volume of deal or order: "+DoubleToString(trade.ResultVolume(),2)); Print("price, confirmed by broker: "+DoubleToString(trade.ResultPrice(),symbol.Digits())); Print("current bid price: "+DoubleToString(trade.ResultBid(),symbol.Digits())); Print("current ask price: "+DoubleToString(trade.ResultAsk(),symbol.Digits())); Print("broker comment: "+trade.ResultComment()); //int d=0; } //+------------------------------------------------------------------+ 12 Nuevo comentario
hmm, y tengo errores de compilacion init fails en las lineas 281 y 287. Y como consecuencia no puedo ejecutar nada=(
hmm, y tengo errores de compilacion init fails en las lineas 281 y 287. Y como consecuencia no puedo ejecutar nada=(
Fíjate bien QUÉ y DÓNDE descargas. De momento la versión 1.003 la descargo de la parte rusa de KodoBase y compila sin errores.
Foro sobre trading, sistemas automatizados de trading y testeo de estrategias de trading.
Asesores Expertos: 2MA Bunny Cross Expert
Vladimir Karputov, 2019.05.01 15:17
Aquí hay una pista: https: //www.mql5.com/ru/code/16783
cảm ơn bạn về código
nhưng nó không hoạt động
khi nén lại n ó báo lỗi
bạn có thể chỉ tôi cách khắc phục không ?
xin cảm ơn.
cảm ơn bạn về código.
nhưng nó không hoạt động
khi nén lại n ó báo lỗi
bạn có thể chỉ tôi cách khắc phục không ?
xin cảm ơn.
La versión 1.003 está disponible en el foro ruso: https: //www.mql5.com/ru/code/16783
Hola,
Gracias por tu ea, lo modifique para cambiar los periodos MA, es bien rentable.
A continuación el código modificado