Partes de EA

147
- MAGIC NUMBER - TAKE PROFIT Y STOP LOSS - TP Y SL OCULTOS - TRAILING STOP - FILTRO HORARIO Y DIARIO - FILTRO DE SPREAD - MM : 2 % DE RIESGO KELLY MARTINGALA ANTIMARTINGALA RATIO FIJA O FIXED RATIO (SIMPLE, AVANZADO) FRACCIÓN FIJA O FIXED FRACTIONAL (PERIÓDICA, DEL BENEFICIO, ÓPTIMA, F-SEGURA, MEDIDA, PORCENTAJE DE KELLY) PRECIO EFECTIVO TANO - CADA TICK /OPEN PRICE - EXTERNALIZAR - CRUCE ALCISTA/BAJISTA - SUBIDA O BAJADA DE X PIPS - TRADING ALCISTA - PASAR EA DE 4 A 5 DÍGITOS - CAMBIO DE LOTE A MICROLOTE - ÓRDENES LIMITADAS - EAS BASADOS EN INDICADORES - VARIOS MAGIC NUMBER El número mágico es uno de los parámetros (parámetro opcional) de la función OrderSend: int OrderSend( string symbol , int cmd , double volume , double price, int slippage , double stoploss , double takeprofit , string comment=NULL , int magic=0 , datetime expiration =0 , color arrow_color=CLR_NONE) OrderSend() es la función que se utiliza en MQL4 para abrir una nueva orden (orden de inmediato o pendiente) y el parámetro magic (el parámetro noveno) es un valor entero que establece un número mágico de la orden abierta.

Transcript of Partes de EA

- MAGIC NUMBER

- TAKE PROFIT Y STOP LOSS

- TP Y SL OCULTOS

- TRAILING STOP

- FILTRO HORARIO Y DIARIO

- FILTRO DE SPREAD

- MM :

2 % DE RIESGO

KELLY

MARTINGALA

ANTIMARTINGALA

RATIO FIJA O FIXED RATIO (SIMPLE, AVANZADO)

FRACCIÓN FIJA O FIXED FRACTIONAL (PERIÓDICA, DEL BENEFICIO,

ÓPTIMA, F-SEGURA, MEDIDA, PORCENTAJE DE KELLY)

PRECIO EFECTIVO

TANO

- CADA TICK /OPEN PRICE

- EXTERNALIZAR

- CRUCE ALCISTA/BAJISTA

- SUBIDA O BAJADA DE X PIPS

- TRADING ALCISTA

- PASAR EA DE 4 A 5 DÍGITOS

- CAMBIO DE LOTE A MICROLOTE

- ÓRDENES LIMITADAS

- EAS BASADOS EN INDICADORES

- VARIOS

MAGIC NUMBER

El número mágico es uno de los parámetros (parámetro opcional) de la función OrderSend:

int OrderSend( string symbol , int cmd , double volume , double price, int slippage , double stoploss , double takeprofit , string comment=NULL , int magic=0 , datetime expiration =0 , color arrow_color=CLR_NONE)

OrderSend() es la función que se utiliza en MQL4 para abrir una nueva orden (orden de inmediato o pendiente) y el parámetro magic (el parámetro noveno) es un valor entero que establece un número mágico de la orden abierta.

Ejemplo de uso de Magic Number:

Nuestro ejemplo es un Asesor Experto que abre 4 órdenes de compra (sin condiciones) y cierra todo cuando el beneficio total de ellos alcanza los 100 pips o la pérdida total es de -100 pips.

Con la ayuda de la utilización de nuestro Número Mágico el Expert Advisor es lo suficientemente inteligente como para saber si la orden ha sido abierta por sí mismo o ha sido abierta por otro asesor experto o manualmente.

Aquí está el código:

int MagicNumber = 101030;

extern double Profit = 100;

extern double Loss = -100;

//+------------------------------------------------------------------

int init()

{

return(0);

}

int deinit()

{

return(0);

}

int start()

{

int cnt, ticket, total,n;

if(Bars<100) {Print("bars less than 100"); return(0);}

total = OrdersTotal();

if(total < 1)

{

OrderSend(Symbol(),OP_BUY,1,Ask,5,0,Ask+100*Point,"MagicNumber

demo",MagicNumber,0,Green);

OrderSend(Symbol(),OP_BUY,1,Ask,5,0,Ask+100*Point,"MagicNumber

demo",MagicNumber,0,Green);

OrderSend(Symbol(),OP_BUY,1,Ask,5,0,Ask+100*Point,"MagicNumber

demo",MagicNumber,0,Green);

OrderSend(Symbol(),OP_BUY,1,Ask,5,0,Ask+100*Point,"MagicNumber

demo",MagicNumber,0,Green);

return(0);

}

ProfitLossMonitor();

return(0);

}

void ProfitLossMonitor()

{

int total = OrdersTotal();

double MyCurrentProfit=0;

for (int cnt = 0 ; cnt < total ; cnt++)

{

OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

if (OrderMagicNumber() == MagicNumber)

MyCurrentProfit += OrderProfit();

}

if(MyCurrentProfit>=Profit)

CloseAll();

if(MyCurrentProfit<=Loss)

CloseAll();

}

void CloseAll()

{

int total = OrdersTotal();

for (int cnt = 0 ; cnt < total ; cnt++)

{

OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

if (OrderMagicNumber() == MagicNumber)

if(OrderType()==OP_BUY)

OrderClose(OrderTicket(),OrderLots(),Bid,5,Violet);

if(OrderType()==OP_SELL)

OrderClose(OrderTicket(),OrderLots(),Ask,5,Violet);

}

}

Estudio del código:

El asesor experto en el primer lugar ha definido (declarado) la variable integer MagicNumber para usarla más adelante en el código.

int MagicNumber = 101030;

El asesor experto abre 4 órdenes de compra y usa la función ProfitLossMonitor() para controlar la cantidad de la ganancia o pérdida. Pero, ¿cómo puede el asesor experto saber que la orden ha sido abierta por él o por otro asesor experto?

El asesor experto verifica el MagicNumber de la orden seleccionada devuelto por OrderMagicNumber() contra la variable MagicNumber para saber si es nuestra orden o no:

if (OrderMagicNumber() == MagicNumber)

Cuando el total de ganancia es igual a 100 o el total de la pérdida igual a -100 el Asesor Experto llama a la función CloseAll() para cerrar todas las órdenes abiertas que se han abierto por los asesores expertos. Y antes de cerrar las órdenes el Expert Advisor comprueba de nuevo el MagicNumber de la orden seleccionada devuelto por OrderMagicNumber() contra la variable MagicNumber.

¿Sin utilizar Magic Number podría imaginar el funcionamiento de este tipo de asesores expertos? ¿Cómo se calcula la ganancia y la pérdida de sus órdenes? ¿Cómo iban a cerrar solo sus órdenes?

¡Es por eso que el Número Mágico es esencial!

Añadir un Magic Number:

Después del "comentario" en cada función OrderSend:

Reemplaza el valor 0 por Magic.

Busca esta línea: OrderSymbol()==Symbol() en el OrderClose, OrderModify y OrderDelete. Por lo general, están insertadas en instrucciones IF.

Dentro de la línea después de y para cada aparición, se agrega:

&& OrderMagicNumber()==Magic

Finalmente, después de los parámetros extern, se agrega lo siguiente:

extern int Magic=2009; // donde 2009 es un número único para el EA

Poner la declaración MagicNumber inmediatamente después de cualquier declaración #property, #include or #import y antes de las funciones Init, Deinit y Start.

TAKE PROFIT Y STOP LOSS

Añadir SL y TP

//-------------------------------------------------------

//Externals

extern double TakeProfit = 25; // TakeProfit in pips

extern double StopLoss = 50; // StopLoss in pips

//------------------------------------------------------

//Calculate for 4 or 5 digits broker

double DigitPoint;

int MultiplierPoint=1;

//------------------------------------------------------

if((Digits==3)||(Digits==5)) MultiplierPoint=10;

DigitPoint=Point*MultiplierPoint;

//------------------------------------------------------

StopLoss=NormalizeDouble(StopLoss*DigitPoint,Digits);

TakeProfit=NormalizeDouble(TakeProfit*DigitPoint,Digits);

//------------------------------------------------------

double TakeProfitBuy=NormalizeDouble(Ask+TakeProfit,Digits);

double StopLossBuy=NormalizeDouble(Bid-StopLoss,Digits);

double TakeProfitSell=NormalizeDouble(Bid-TakeProfit,Digits);

double StopLossSell=NormalizeDouble(Ask+StopLoss,Digits);

//------------------------------------------------------

//For buy

OrderSend(Symbol(),OP_BUY,1,Ask,3,StopLossBuy,TakeProfitBuy,"My order #2",16384,0,Green);

//------------------------------------------------------

//For sell

OrderSend(Symbol(),OP_SELL,1,Ask,3,StopLossSell,TakeProfitSell,"My order #2",16384,0,Green);

TP Y SL OCULTOS

- Para evitar que el bróker te barra el SL con repuntes repentinos o spikes se puede poner el SL en 100-300 pips y usar el bloque Close Order If de FEAG. En Amount usa la cantidad de la casilla de beneficios de MT 4 (se pone 10 si se quiere que cierre cuando el beneficio sea mayor a 10 euros o dólares, según sea la divisa en que se abrió la cuenta. Se pone -10 para que cierre cuando la pérdida sea mayor a 10. En CompareAmount se suele poner >)

1) Poner como parámetros externos:

extern bool HideSL=false;//|---------------------hide stop loss

extern bool HideTP=false;//|---------------------hide take profit

2) Poner en el cuerpo de start:

//|---------hidden sl-tp

if(HideSL&&StopLoss>0)

{

CloseBuyOrdersHiddenSL(Magic);CloseSellOrdersHiddenSL(Magic);

}

if(HideTP&&TakeProfit>0)

{

CloseBuyOrdersHiddenTP(Magic);CloseSellOrdersHiddenTP(Magic);

}

3) Poner en las funciones:

int CloseBuyOrdersHiddenTP(int Magic)

{

int total=OrdersTotal();

for (int cnt=total-1;cnt>=0;cnt--)

{

OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

if(OrderMagicNumber()==Magic&&OrderSymbol()==Symbol())

{

if(OrderType()==OP_BUY&&Bid>(OrderOpenPrice()+TakeProfit*dPoint))

{

OrderClose(OrderTicket(),OrderLots(),Bid,3);

}

}

}

return(0);

}

int CloseBuyOrdersHiddenSL(int Magic)

{

int total=OrdersTotal();

for (int cnt=total-1;cnt>=0;cnt--)

{

OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

if(OrderMagicNumber()==Magic&&OrderSymbol()==Symbol())

{

if(OrderType()==OP_BUY&&Bid<(OrderOpenPrice()-StopLoss*dPoint))

{

OrderClose(OrderTicket(),OrderLots(),Bid,3);

}

}

}

return(0);

}

int CloseSellOrdersHiddenTP(int Magic)

{

int total=OrdersTotal();

for(int cnt=total-1;cnt>=0;cnt--)

{

OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

if(OrderMagicNumber()==Magic&&OrderSymbol()==Symbol())

{

if(OrderType()==OP_SELL&&Ask<(OrderOpenPrice()-TakeProfit*dPoint))

{

OrderClose(OrderTicket(),OrderLots(),Ask,3);

}

}

}

return(0);

}

int CloseSellOrdersHiddenSL(int Magic)

{

int total=OrdersTotal();

for(int cnt=total-1;cnt>=0;cnt--)

{

OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

if(OrderMagicNumber()==Magic&&OrderSymbol()==Symbol())

{

if(OrderType()==OP_SELL&&Ask>(OrderOpenPrice()+StopLoss*dPoint))

{

OrderClose(OrderTicket(),OrderLots(),Ask,3);

}

}

}

return(0);

}

TRAILING STOP

Para añadir un TS:

1) En la parte inferior de la EA, agregar esta función:

void MoveTrailingStop(){ int cnt,total=OrdersTotal(); for(cnt=0;cnt<total;cnt++) { OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); if(OrderType()<=OP_SELL&&OrderSymbol()==Symbol()) { if(OrderType()==OP_BUY) { if(TrailingStop>0) { if((NormalizeDouble(OrderStopLoss(),Digits)<NormalizeDouble(Bid-Point*(TrailingStop+TrailingStep),Digits))||(OrderStopLoss()==0)) { OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Bid-Point*TrailingStop,Digits),OrderTakeProfit(),0,Green); return(0); } }

} else { if(TrailingStop>0) { if((NormalizeDouble(OrderStopLoss(),Digits)>(NormalizeDouble(Ask+Point*(TrailingStop+TrailingStep),Digits)))||(OrderStopLoss()==0)) { OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Ask+Point*TrailingStop,Digits),OrderTakeProfit(),0,Red); return(0); } } } } }}

2) En algún lugar del EA, después de las condiciones, cerca de los tickets, por ejemplo, añadir lo siguiente:

if(TrailingStop>0)MoveTrailingStop();3) Por último, en la parte superior del EA añadir lo siguiente:

extern int TrailingStop=0;extern int TrailingStep=0;

FILTRO HORARIO Y DIARIOLos dos filtros:1) Declara estas variables ne la parte superior:extern int EndHour = 18;extern int StartHour = 9;bool StopTrading;2) A continuación, crea este método en algún lugar en la parte inferior del EA:void CheckTime(){int h=TimeHour(TimeCurrent());if(((h>EndHour || h<StartHour) && StartHour<EndHour) ||((h<EndHour || h>StartHour) && StartHour>EndHour)){StopTrading=true;}}3) Luego, en la función start pon esto: StopTrading = false; CheckTime(); if(StopTrading==false) { //The trading logic of the EA goes here }Para un filtro de día es el mismo, excepto donde diceint h=TimeHour(TimeCurrent());cambialo porint d=TimeDayOfWeek(DayOfWeek());

Y cambiar toda la "h" a "d" en la función de chqueo del tiempo. Además declarar las variables en la parte superior para StartDay y EndDay (Son un int que van desde 0-6 y 0 es domingo, 1 es lunes, etc.)

Filtro horario1) Poner como parámetros externos:

extern int StartHour=0;extern int EndHour=23;

2) Poner en int start() {//-------------------------------------------------------------------+// time check//-------------------------------------------------------------------if((Hour()>=StartHour)&&(Hour()<=EndHour)){int TradeTimeOk=1;}else{ TradeTimeOk=0; }

3) Poner en la OrderSend de compra y de ventaif(TradeTimeOk==1){- Filter Hours de FEAG://-------------------------------------------------------------// Etasoft Inc. Forex EA and Script Generator version 4.5 EA//-------------------------------------------------------------// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "Copyright © 2012, Etasoft Inc. Forex EA Generator v4.5"#property link "http://www.forexgenerator.com/"

#include <stdlib.mqh>#include <WinUser32.mqh>

// exported variablesextern int HoursFrom1 = 1;extern int HoursTo1 = 23;

// local variablesdouble PipValue=1; // this variable is here to support 5-digit brokersbool Terminated = false;string LF = "\n"; // use this in custom or utility blocks where you need line feedsint NDigits = 4; // used mostly for NormalizeDouble in Flex type blocksint ObjCount = 0; // count of all objects created on the chart, allows creation of objects with unique namesint current = 0;

datetime BarTime2 = 0;

int init(){

NDigits = Digits; if (false) ObjectsDeleteAll(); // clear the chart Comment(""); // clear the chart}

// Expert startint start(){ if (Bars < 10) { Comment("Not enough bars"); return (0); } if (Terminated == true) { Comment("EA Terminated."); return (0); } OnEveryNewBar2(); }

void OnEveryNewBar2(){ if (true == false && false) PipValue = 10; if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10; if (BarTime2 < Time[0]) { // we have a new bar opened BarTime2 = Time[0]; // keep the new bar open time HoursFilter1(); }}

void HoursFilter1(){ int datetime800 = TimeLocal(); int hour0 = TimeHour(datetime800); if ((HoursFrom1 < HoursTo1 && hour0 >= HoursFrom1 && hour0 < HoursTo1) || (HoursFrom1 > HoursTo1 && (hour0 < HoursTo1 || hour0 >= HoursFrom1))) { }}

int deinit(){ if (false) ObjectsDeleteAll(); }- Weekday Filter de FEAG://-------------------------------------------------------------// Etasoft Inc. Forex EA and Script Generator version 4.5 EA//-------------------------------------------------------------// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "Copyright © 2012, Etasoft Inc. Forex EA Generator v4.5"#property link "http://www.forexgenerator.com/"

#include <stdlib.mqh>#include <WinUser32.mqh>

// exported variables

// local variablesdouble PipValue=1; // this variable is here to support 5-digit brokersbool Terminated = false;string LF = "\n"; // use this in custom or utility blocks where you need line feedsint NDigits = 4; // used mostly for NormalizeDouble in Flex type blocksint ObjCount = 0; // count of all objects created on the chart, allows creation of objects with unique namesint current = 0;

datetime BarTime2 = 0;

int init(){ NDigits = Digits; if (false) ObjectsDeleteAll(); // clear the chart Comment(""); // clear the chart}

// Expert startint start(){ if (Bars < 10) { Comment("Not enough bars"); return (0); }

if (Terminated == true) { Comment("EA Terminated."); return (0); } OnEveryNewBar2(); }

void OnEveryNewBar2(){ if (true == false && false) PipValue = 10; if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10; if (BarTime2 < Time[0]) { // we have a new bar opened BarTime2 = Time[0]; // keep the new bar open time WeekdayFilter1(); }}

void WeekdayFilter1(){ if ((true && DayOfWeek() == 1) || (true && DayOfWeek() == 2) || (true && DayOfWeek() == 3) || (true && DayOfWeek() == 4) || (true && DayOfWeek() == 5) || (true && DayOfWeek() == 6) || (true && DayOfWeek() == 0)) { }}

int deinit(){ if (false) ObjectsDeleteAll(); }

FILTRO DE SPREAD1) Al principio del código, después de los parámetros externos, añadir:extern int MaxSpread=2;2) Después de start() {, añadir:if((Ask-Bid)>MaxSpread*Point)return(0);

MM 2 % DE RIESGO

1) //Money Management sequence if (MoneyManagement)

{ if (Risk<1 || Risk>100) { Comment("Invalid Risk Value."); return(0); } else {Lot=MathFloor((AccountFreeMargin() *AccountLeverage()*Risk*Point*100)/(Ask*MarketInfo(Symbol(),MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_MINLOT )))*MarketInfo(Symbol(),MODE_MINLOT ); } }2) En la parte superior del experto, añadir:extern bool MoneyManagement=True;extern double Risk=2;

KELLYKelly MMb = ratio ganancia/pérdida,p = % de operaciones ganadoras,q = % de operaciones perdedoras (= 1-p),K = porcentaje de saldo a arriesgar por operación.

fórmula de Kelly: K = (b * p - q) / b

La gestión del riesgo de kelly se supone que ayuda a recuperarse de las pérdidas anteriores.1) En los parámetros externos, añadir:extern double initialrisk=0.1;extern int mintradeskelly=10;extern int maxtradeskelly=50;

extern double stoploss=50;2) Después de loa parámetros externos, añadir:int lotsize;3) Añadir en la función init:if(MarketInfo(Symbol(),MODE_MINLOT)>=1){lotsize=100000;}if(MarketInfo(Symbol(),MODE_MINLOT)<1){lotsize=10000;}if(MarketInfo(Symbol(),MODE_MINLOT)<0.1){lotsize=1000;}4) Función de Kellydouble kelly(){ int count=0; double countprofit=0; double countloss=0; int countpve=0; int countnve=0; double b=0; double p=0; double q=0; double k=0;

if(OrdersHistoryTotal()>0){ for(i=OrdersHistoryTotal()-1;i>=0;i--){ OrderSelect(i,SELECT_BY_POS,MODE_HISTORY); if(count==maxtradeskelly)break; if(OrderMagicNumber()==magic && count<maxtradeskelly){ count++; if(OrderProfit()<0){countnve++;countloss+=OrderProfit();} if(OrderProfit()>=0){countpve++;countprofit+=OrderProfit();} } } if(countloss!=0 && count!=0 && countpve!=0 && countprofit!=0){ b=countprofit/countloss; p=countpve/count; q=1-p; k=(b*p-q)/b; //Print(" "+k); if(count>=mintradeskelly)return(k); } }

return(initialrisk);}5) Standard function MM:double mm(double risk,double stoploss){ double lot; if(stoploss>0)lot=AccountBalance()*(risk/100)/(stoploss*pt/MarketInfo(Symbol(),MODE_TICKSIZE)*MarketInfo(Symbol(),MODE_TICKVALUE)); else lot=nd((AccountBalance()/lotsize)*0.01*risk,2); if(lot<MarketInfo(Symbol(),MODE_MINLOT))lot=MarketInfo(Symbol(),MODE_MINLOT); if(lot>MarketInfo(Symbol(),MODE_MAXLOT))lot=MarketInfo(Symbol(),MODE_MAXLOT); return(lot);}6) Reemplazar lots en las funciones Ordersend con:mm(kelly(),stoploss)* Pequeña actualización a la fórmula:if(KellyMinusRisk){k=(((100*(p-q))/count)+100)*0.5*0.01*Klots;}else{k=((((100*(q-p))/count)+100)*0.01*Klots)+Klots;}Klots = lots (soporta usar mm o no)

KellyMinusRisk - si es true- los lotes se deducen cuando ocurre una pérdida, si es false se agregan cuando ocurre una pérdida.

Los lotes "Kelly" se calculan entre 0 y 100% de los lotes que se utilizan.Así que con (KellyMinusRisk=true)Si gana el 100% los lotes Kelly = Lots.con cada pérdida los lotes dejan un porcentaje de los lotes.

Si pierde el 100% los lotes kelly=0.01 lotes.

(KellyMinusRisk=false) ocurre lo contrario. A más pérdidas mayor tamaño de los lotes (Tamaño del lote + hasta el 100% del tamaño del lote)

He estado probando contra el MM regular y encuentro que con KellyMinusRisk = false se está dando mejores resultados.

por ejemplo,MM regular30.6% DDPF1.54Beneficio=69003

KellyMinusRisk = false: maxtradeskelly=1529.51DDPF1.62Beneficio=87150

MARTINGALA- http://www.onestepremoved.com/martingale-forex/- Pure_Maringale.mq4 (http://codebase.mql4.com/8134)//+------------------------------------------------------------------+#property copyright "Copyright © 2012 Matus German, www.MTexperts.net"

extern string separator1 = "------ Martingale settings ------";extern double sl_tp = 20; // stop loss and take profitextern double lotsMultiplier = 1.5;extern double distanceMultiplier = 1.5; extern double Lots = 0.03; // fixed lot sizeextern double MaxSlippage = 3; extern double magicNumber = 1212123;

extern string separator2 = "------ Trading Hours ------";extern bool useTradingHours = false;extern string StartTime = "06:00";extern string StopTime = "18:00";extern int GMT_Offset = 0;

extern string separator3 = "------ Trading Days ------";extern bool Monday = true;extern bool Tuesday = true;extern bool Wednesday = true;extern bool Thursday = true;extern bool Friday = true;extern bool Saturday = true;extern bool Sunday = true;

extern string separator4 = "------ Wiew settings ------";extern bool showMenu = true;extern color menuColor = Yellow; extern color variablesColor = Red;extern int font = 10;

double stopLoss, takeProfit, minAllowedLot, lotStep, maxAllowedLot, pips2dbl, pips2point, pipValue, minGapStop, maxSlippage, menulots, profit, lots, ma1;

datetime barTime=0;

bool noHistory=false, stopsChecked; int medzera = 8, trades; //+------------------------------------------------------------------+//| expert initialization function |//+------------------------------------------------------------------+int init() {//----

Comment("Copyright © 2012, Matus German"); if (Digits == 5 || Digits == 3) // Adjust for five (5) digit brokers. { pips2dbl = Point*10; pips2point = 10; pipValue = (MarketInfo(Symbol(),MODE_TICKVALUE))*10; } else { pips2dbl = Point; pips2point = 1; pipValue = (MarketInfo(Symbol(),MODE_TICKVALUE))*1; } maxSlippage = MaxSlippage*pips2dbl; stopLoss = pips2dbl*sl_tp; takeProfit = stopLoss; minGapStop = MarketInfo(Symbol(), MODE_STOPLEVEL)*Point; lots = Lots; minAllowedLot = MarketInfo(Symbol(), MODE_MINLOT); //IBFX= 0.10 lotStep = MarketInfo(Symbol(), MODE_LOTSTEP); //IBFX= 0.01 maxAllowedLot = MarketInfo(Symbol(), MODE_MAXLOT ); //IBFX=50.00 if(lots < minAllowedLot) lots = minAllowedLot; if(lots > maxAllowedLot) lots = maxAllowedLot; if(showMenu) { DrawMenu(); }

//---- return(0); }//+------------------------------------------------------------------+//| expert deinitialization function |//+------------------------------------------------------------------+int deinit() {//---- if(showMenu) { ObjectDelete("name"); ObjectDelete("Openl"); ObjectDelete("Open"); ObjectDelete("Lotsl"); ObjectDelete("Lots"); ObjectDelete("Profitl"); ObjectDelete("Profit"); }//---- return(0); }//+------------------------------------------------------------------+//| expert start function |//+------------------------------------------------------------------+int start(){//---- if(HistoryForMNandPT(magicNumber, Symbol())<=0) noHistory=true; else noHistory=false; if(showMenu) { profit=ProfitCheck(); ReDrawMenu(); } int day = DayOfWeek(); if((Monday && day==1) || (Tuesday && day==2) || (Wednesday && day==3) || (Thursday && day==4) || (Friday && day==5) || (Saturday && day==6) || (Sunday && day==7)) { if(useTradingHours) { if(TradingTime()) OpenOrderCheck(); } else { OpenOrderCheck(); } }

if(!stopsChecked) if(CheckStops()) stopsChecked = true; else return;//---- return(0);}//////////////////////////////////////////////////////////////////////////////////////////////////// calculate random numberint Random(){ MathSrand(TimeLocal()+Bid); return(MathRand());} ////////////////////////////////////////////////////////////////////////////////////////////////// bool EnterBuyCondition(){ if(MathMod(Random(),2)==0) return(true); return (false); }

//////////////////////////////////////////////////////////////////////////////////////////////////bool EnterSellCondition(){ if(MathMod(Random(),2)==1) return(true); return (false); }

//////////////////////////////////////////////////////////////////////////////////////////////////// chceck trades if they do not have set sl and tp than modify tradebool CheckStops(){ double sl=0, tp=0, loss; double total=OrdersTotal(); int ticket=-1; for(int cnt=total-1;cnt>=0;cnt--) { OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if( OrderType()<=OP_SELL // check for opened position && OrderSymbol()==Symbol() // check for symbol && OrderMagicNumber() == magicNumber) // my magic number { if(OrderType()==OP_BUY) { if(OrderStopLoss()==0 || OrderTakeProfit()==0) { ticket=OrderTicket();

while (!IsTradeAllowed()) Sleep(500); RefreshRates(); SelectLastHistoryOrder(Symbol(), magicNumber); if(!noHistory) { if(OrderProfit()<0) { loss=MathAbs(OrderClosePrice()-OrderOpenPrice()); sl=Ask-(loss)*distanceMultiplier; tp=Ask+(loss)*distanceMultiplier; } else { sl = Ask-stopLoss; tp = Ask+takeProfit; } } else { sl = Ask-stopLoss; tp = Ask+takeProfit; } if(Bid-sl<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point) sl = Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;

if(tp-Bid<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point) tp = Bid+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point; // last selected is from history so we have to select trade again if(!OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES)) return(false); if(OrderModify(OrderTicket(),OrderOpenPrice(),sl,tp,0,Green)) // modify position { } else return (false); } } if(OrderType()==OP_SELL) { if(OrderStopLoss()==0 && OrderTakeProfit()==0) { ticket=OrderTicket(); while (!IsTradeAllowed()) Sleep(500); RefreshRates(); SelectLastHistoryOrder(Symbol(), magicNumber);

if(!noHistory) { if(OrderProfit()<0) { loss=MathAbs(OrderClosePrice()-OrderOpenPrice()); sl=Bid+(loss)*distanceMultiplier; tp=Bid-(loss)*distanceMultiplier; } else { sl = Bid+stopLoss; tp = Bid-takeProfit; } } else { sl = Bid+stopLoss; tp = Bid-takeProfit; } if(sl-Ask<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point) sl = Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;

if(Ask-tp<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point) tp = Ask-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point; // last selected is from history so we have to select trade again if(!OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES)) return(false); if(OrderModify(OrderTicket(),OrderOpenPrice(),sl,tp,0,Green)) // modify position { } else return (false); } } } } return (true);}

//////////////////////////////////////////////////////////////////////////////////////////////////bool OpenOrderCheck(){ double olots=lots; int ticket; int total=OpenTradesForMNandPairType(magicNumber, Symbol()); if(total==0) { // check for long position (BUY) possibility

if(EnterBuyCondition()) { if(!noHistory) { SelectLastHistoryOrder(Symbol(), magicNumber); if(OrderProfit()<0) { olots=OrderLots()*lotsMultiplier; } }

while (!IsTradeAllowed()) Sleep(500); RefreshRates(); ticket=OrderSend(Symbol(),OP_BUY,olots,Ask,maxSlippage, 0,0,"",magicNumber,0,Green); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) { stopsChecked = false; Print("BUY order opened : ",OrderOpenPrice()); return (true); } } else { Print("Error opening BUY order : ",GetLastError()); return(false); } } // check for short position (SELL) possibility if(EnterSellCondition()) // OrderSelect() was in function EnterBuyCondition { if(!noHistory) { SelectLastHistoryOrder(Symbol(), magicNumber); if(OrderProfit()<0) { olots=OrderLots()*lotsMultiplier; } } while (!IsTradeAllowed()) Sleep(500); RefreshRates(); ticket=OrderSend(Symbol(),OP_SELL,olots,Bid,maxSlippage, 0,0,"",magicNumber,0,Red); if(ticket>0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))

{ stopsChecked = false; Print("SELL order opened : ",OrderOpenPrice()); return (true); } } else { Print("Error opening SELL order : ",GetLastError()); return (false); } } } return (true); }

//////////////////////////////////////////////////////////////////////////////////////////////////int OpenTradesForMNandPairType(int iMN, string sOrderSymbol){ int icnt, itotal, retval;

retval=0; itotal=OrdersTotal();

for(icnt=itotal-1;icnt>=0;icnt--) // for loop { OrderSelect(icnt, SELECT_BY_POS, MODE_TRADES); // check for opened position, symbol & MagicNumber if (OrderSymbol()== sOrderSymbol) { if (OrderMagicNumber()==iMN) retval++; } // sOrderSymbol } // for loop

return(retval);}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////double ProfitCheck(){ double profit=0; int total = OrdersTotal(); for (int cnt = total-1 ; cnt >=0 ; cnt--) { OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); if (OrderSymbol()==Symbol() && (OrderMagicNumber() == magicNumber)) profit+=OrderProfit(); } return(profit); }

///////////////////////////////////////////////////////////////////////////////////////////////////////////bool DrawMenu(){ ObjectCreate("name",OBJ_LABEL,0,0,0,0,0); ObjectCreate("Openl",OBJ_LABEL,0,0,0,0,0); ObjectCreate("Open",OBJ_LABEL,0,0,0,0,0); ObjectCreate("Lotsl",OBJ_LABEL,0,0,0,0,0); ObjectCreate("Lots",OBJ_LABEL,0,0,0,0,0); ObjectCreate("Profitl",OBJ_LABEL,0,0,0,0,0); ObjectCreate("Profit",OBJ_LABEL,0,0,0,0,0); medzera = 8; trades = Opened(); menulots = Lots(); ObjectSetText( "name", "PURE MARTINGALE", font+1, "Arial",menuColor); ObjectSet("name",OBJPROP_XDISTANCE,medzera*font); ObjectSet("name",OBJPROP_YDISTANCE,10+font); ObjectSet("name",OBJPROP_CORNER,1); ObjectSetText("Openl", "Opened trades: ", font, "Arial",menuColor); ObjectSet("Openl",OBJPROP_XDISTANCE,medzera*font); ObjectSet("Openl",OBJPROP_YDISTANCE,10+2*(font+2)); ObjectSet("Openl",OBJPROP_CORNER,1); ObjectSetText("Open", ""+trades, font, "Arial",variablesColor); ObjectSet("Open",OBJPROP_XDISTANCE,3*font); ObjectSet("Open",OBJPROP_YDISTANCE,10+2*(font+2)); ObjectSet("Open",OBJPROP_CORNER,1); ObjectSetText("Lotsl", "Lots of opened positions: ", font, "Arial",menuColor); ObjectSet("Lotsl",OBJPROP_XDISTANCE,medzera*font); ObjectSet("Lotsl",OBJPROP_YDISTANCE,10+3*(font+2)); ObjectSet("Lotsl",OBJPROP_CORNER,1); ObjectSetText("Lots", DoubleToStr(menulots,2), font, "Arial",variablesColor); ObjectSet("Lots",OBJPROP_XDISTANCE,3*font); ObjectSet("Lots",OBJPROP_YDISTANCE,10+3*(font+2)); ObjectSet("Lots",OBJPROP_CORNER,1); ObjectSetText("Profitl", "Profit of opened positions: ", font, "Arial",menuColor); ObjectSet("Profitl",OBJPROP_XDISTANCE,medzera*font); ObjectSet("Profitl",OBJPROP_YDISTANCE,10+4*(font+2)); ObjectSet("Profitl",OBJPROP_CORNER,1); ObjectSetText("Profit", DoubleToStr(profit,2), font, "Arial",variablesColor); ObjectSet("Profit",OBJPROP_XDISTANCE,3*font); ObjectSet("Profit",OBJPROP_YDISTANCE,10+4*(font+2)); ObjectSet("Profit",OBJPROP_CORNER,1);

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////bool ReDrawMenu(){ medzera = 8; trades = Opened(); menulots = Lots(); ObjectSetText("Open", ""+trades, font, "Arial",variablesColor); ObjectSetText("Lots", DoubleToStr(menulots,2), font, "Arial",variablesColor); ObjectSetText("Profit", DoubleToStr(profit,2), font, "Arial",variablesColor);}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////int Opened(){ int total = OrdersTotal(); int count = 0; for (int cnt = total-1 ; cnt >=0 ; cnt--) { OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); if (OrderSymbol()==Symbol() && (OrderMagicNumber() == magicNumber)) if(OrderType()==OP_BUY || OrderType()==OP_SELL) count++; } return (count);}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////double Lots(){ int total = OrdersTotal(); double lots = 0; for (int cnt = total-1 ; cnt >=0 ; cnt--) { OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES); if (OrderSymbol()==Symbol() && (OrderMagicNumber() == magicNumber)) if(OrderType()==OP_BUY || OrderType()==OP_SELL) lots+=OrderLots(); } return (lots);}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////bool SelectLastHistoryOrder(string symbol, int magicNumber){ int lastOrder=NULL; for(int i=OrdersHistoryTotal()-1;i>=0;i--)

{ OrderSelect(i, SELECT_BY_POS,MODE_HISTORY); if(OrderSymbol()==symbol && OrderMagicNumber()==magicNumber) { lastOrder=i; break; } } if(lastOrder==NULL) return(false); else return(true); }

//////////////////////////////////////////////////////////////////////////////////////////////////int HistoryForMNandPT(int iMN, string sOrderSymbol){ int icnt, itotal, retval;

retval=0; itotal=OrdersHistoryTotal();

for(icnt=itotal-1;icnt>=0;icnt--) // for loop { OrderSelect(icnt, SELECT_BY_POS, MODE_HISTORY); // check for opened position, symbol & MagicNumber if (OrderSymbol()== sOrderSymbol) { if (OrderMagicNumber()==iMN) retval++; } // sOrderSymbol } // for loop

return(retval);}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////bool TradingTime(){ datetime start, stop, start1, stop1; start = StrToTime(StringConcatenate(Year(),".",Month(),".",Day()," ",StartTime))+GMT_Offset*3600; stop = StrToTime(StringConcatenate(Year(),".",Month(),".",Day()," ",StopTime))+GMT_Offset*3600; start1=start; stop1=stop; if(stop <= start) { stop1 += 86400; start -= 86400;

} if((TimeCurrent() >= start && TimeCurrent() < stop) || (TimeCurrent() >= start1 && TimeCurrent() < stop1)) { return(true); } return(false);}- En rojo aparece lo que hay que añadir para poner la martingala y semi-martingala por lotes en FEAG. Ver Buy y Sell Order Lots en FEAG.

//-------------------------------------------------------------

// Etasoft Inc. Forex EA and Script Generator version 4.5 EA

//-------------------------------------------------------------

// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "Copyright © 2012, Etasoft Inc. Forex EA Generator v4.5"

#property link "http://www.forexgenerator.com/"

#include <stdlib.mqh>

#include <WinUser32.mqh>

// exported variables

extern double BuyLots11BuyLots4 = 0.1;

extern int BuyStoploss11BuyStoploss4 = 20;

extern int BuyTakeprofit11BuyTakeprofit4 = 30;

extern double SellLots15MaxBuyLots4 = 3;

extern double LotsBuyChOnLoss4 = 0.;

extern double LotsBuyChOnProfit4 = 0;

extern double LotsBuyMpOnLoss4 = 1;

extern double LotsBuyMpOnProfit4 = 1;

extern bool LotsResetOnProfit4 = false;

extern bool LotsResetOnLoss4 = false;

extern double SellLots6 = 0.1;

extern int SellStoploss15SellStoploss6 = 20;

extern int SellTakeprofit15SellTakeprofit6 = 30;

extern double MaxSellLots6 = 3;

extern double LotsSellChOnLoss6 = 0;

extern double LotsSellChOnProfit6 = 0;

extern double LotsSellMpOnLoss6 = 1;

extern double LotsSellMpOnProfit6 = 1;

extern bool LotsResetOnProfit6 = false;

extern bool LotsResetOnLoss6 = false;

// local variables

double PipValue=1; // this variable is here to support 5-digit brokers

bool Terminated = false;

string LF = "\n"; // use this in custom or utility blocks where you need line feeds

int NDigits = 4; // used mostly for NormalizeDouble in Flex type blocks

int ObjCount = 0; // count of all objects created on the chart, allows creation of objects with unique names

int current = 0;

double CurrentBuyLots4 = 1;

bool FirstBuyLotsMgm4 = true;

double CurrentSellLots6 = 1;

bool FirstSellLotsMgm6 = true;

int init()

{

NDigits = Digits;

if (false) ObjectsDeleteAll(); // clear the chart

CurrentBuyLots4 = BuyLots4;

CurrentSellLots6 = SellLots6;

Comment(""); // clear the chart

}

// Expert start

int start()

{

if (Bars < 10)

{

Comment("Not enough bars");

return (0);

}

if (Terminated == true)

{

Comment("EA Terminated.");

return (0);

}

OnEveryTick1();

}

void OnEveryTick1()

{

if (true == false && true) PipValue = 10;

if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10;

TechnicalAnalysis2x9();

TechnicalAnalysis2x12();

}

void TechnicalAnalysis2x9()

{

if ((iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,1) < iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,1)) && (iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,0) > iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,0)))

{

IfOrderDoesNotExist10();

}

}

void IfOrderDoesNotExist10()

{

bool exists = false;

for (int i=OrdersTotal()-1; i >= 0; i--)

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderType() == OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)

{

exists = true;

}

}

else

{

Print("OrderSelect() error - ", ErrorDescription(GetLastError()));

}

if (exists == false)

{

BuyOrder11BuyOrderLotsMgm4();

}

}

void BuyOrder11BuyOrderLotsMgm4()

{

double profit = 0;

datetime lastCloseTime = 0;

int cnt = OrdersHistoryTotal();

for (int i=0; i < cnt; i++)

{

if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;

if (OrderSymbol() == Symbol() && OrderMagicNumber() == 1 && lastCloseTime < OrderCloseTime())

{

lastCloseTime = OrderCloseTime();

profit = OrderProfit();

CurrentBuyLots4 = OrderLots(); // take lots from the last order

}

}

if (profit > 0) // had profit

{

CurrentBuyLots4 = CurrentBuyLots4 * LotsBuyMpOnProfit4 + LotsBuyChOnProfit4;

if (LotsResetOnProfit4)

CurrentBuyLots4 = BuyLots4;

}

else if (profit < 0) // had loss

{

CurrentBuyLots4 = CurrentBuyLots4 * LotsBuyMpOnLoss4 + LotsBuyChOnLoss4;

if (LotsResetOnLoss4) CurrentBuyLots4 = BuyLots4;

}

if (CurrentBuyLots4 > MaxBuyLots4)

{

CurrentBuyLots4 = MaxBuyLots4;

}

double lotvalue = CurrentBuyLots4;

if (lotvalue < MarketInfo(Symbol(), MODE_MINLOT)) // make sure lot is not smaller than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MINLOT);

}

if (lotvalue > MarketInfo(Symbol(), MODE_MAXLOT)) // make sure lot is not greater than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MAXLOT);

}

double SL = Ask - BuyStoploss11BuyStoploss4*PipValue*Point;

if (BuyStoploss11BuyStoploss4 == 0) SL = 0;

double TP = Ask + BuyTakeprofit11BuyTakeprofit4*PipValue*Point;

if (BuyTakeprofit11BuyTakeprofit4 == 0) TP = 0;

FirstBuyLotsMgm4 = false;

int ticket = -1;

if (true)

ticket = OrderSend(Symbol(), OP_BUY, BuyLots11lotvalue, Ask, 4, 0, 0, "My Expert", 1, 0, Blue);

else

ticket = OrderSend(Symbol(), OP_BUY, BuyLots11lotvalue, Ask, 4, SL, TP, "My Expert", 1, 0, Blue);

if (ticket > -1)

{

if (true)

{

OrderSelect(ticket, SELECT_BY_TICKET);

bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Blue);

if (ret == false)

Print("OrderModify() error - ", ErrorDescription(GetLastError()));

}

}

else

{

Print("OrderSend() error - ", ErrorDescription(GetLastError()));

}

}

void TechnicalAnalysis2x12()

{

if ((iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,1) > iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,1)) && (iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,0) < iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,0)))

{

IfOrderDoesNotExist8();

}

}

void IfOrderDoesNotExist8()

{

bool exists = false;

for (int i=OrdersTotal()-1; i >= 0; i--)

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)

{

exists = true;

}

}

else

{

Print("OrderSelect() error - ", ErrorDescription(GetLastError()));

}

if (exists == false)

{

SellOrder15SellOrderLotsMgm6();

}

}

void SellOrder15SellOrderLotsMgm6()

{

double profit = 0;

datetime lastCloseTime = 0;

int cnt = OrdersHistoryTotal();

for (int i=0; i < cnt; i++)

{

if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;

if (OrderSymbol() == Symbol() && OrderMagicNumber() == 1 && lastCloseTime < OrderCloseTime())

{

lastCloseTime = OrderCloseTime();

profit = OrderProfit();

CurrentSellLots6 = OrderLots();

}

}

if (profit > 0) // had profit

{

CurrentSellLots6 = CurrentSellLots6 * LotsSellMpOnProfit6 + LotsSellChOnProfit6;

if (LotsResetOnProfit6)

CurrentSellLots6 = SellLots6;

}

else if (profit < 0) // had loss

{

CurrentSellLots6 = CurrentSellLots6 * LotsSellMpOnLoss6 + LotsSellChOnLoss6;

if (LotsResetOnLoss6) CurrentSellLots6 = SellLots6;

}

if (CurrentSellLots6 > MaxSellLots6)

{

CurrentSellLots6 = MaxSellLots6;

}

double lotvalue = CurrentSellLots6;

if (lotvalue < MarketInfo(Symbol(), MODE_MINLOT)) // make sure lot is not smaller than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MINLOT);

}

if (lotvalue > MarketInfo(Symbol(), MODE_MAXLOT)) // make sure lot is not greater than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MAXLOT);

}

double SL = Bid + SellStoploss15SellStoploss6*PipValue*Point;

if (SellStoploss15SellStoploss6 == 0) SL = 0;

double TP = Bid - SellTakeprofit15SellTakeprofit6*PipValue*Point;

if (SellTakeprofit15SellTakeprofit6 == 0) TP = 0;

FirstSellLotsMgm6 = false;

int ticket = -1;

if (true)

ticket = OrderSend(Symbol(), OP_SELL, SellLots15lotvalue, Bid, 4, 0, 0, "My Expert", 1, 0, Red);

else

ticket = OrderSend(Symbol(), OP_SELL, SellLots15lotvalue, Bid, 4, SL, TP, "My Expert", 1, 0, Red);

if (ticket > -1)

{

if (true)

{

OrderSelect(ticket, SELECT_BY_TICKET);

bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Red);

if (ret == false)

Print("OrderModify() error - ", ErrorDescription(GetLastError()));

}

}

else

{

Print("OrderSend() error - ", ErrorDescription(GetLastError()));

}

}

int deinit()

{

if (false) ObjectsDeleteAll();

}

- En rojo aparece lo que hay que añadir para poner la martingala y semi-martingala por risk en FEAG. Ver Buy y Sell Order Risk en FEAG.

//-------------------------------------------------------------

// Etasoft Inc. Forex EA and Script Generator version 4.5 EA

//-------------------------------------------------------------

// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "Copyright © 2012, Etasoft Inc. Forex EA Generator v4.5"

#property link "http://www.forexgenerator.com/"

#include <stdlib.mqh>

#include <WinUser32.mqh>

// exported variables

extern double BuyLots11BuyRisk4 = 0.1;

extern int BuyStoploss11BuyStoploss4 = 20;

extern int BuyTakeprofit11BuyTakeprofit4 = 30;

extern double SellLots15MaxBuyRisk4 = 3;

extern double RiskBuyChOnLoss4 = 0.;

extern double RiskBuyChOnProfit4 = 0;

extern double RiskBuyMpOnLoss4 = 1;

extern double RiskBuyMpOnProfit4 = 1;

extern bool RiskResetOnProfit4 = false;

extern bool RiskResetOnLoss4 = false;

extern double SellRisk6 = 0.1;

extern int SellStoploss15SellStoploss6 = 20;

extern int SellTakeprofit15SellTakeprofit6 = 30;

extern double MaxSellRisk6 = 3;

extern double RiskSellChOnLoss6 = 0;

extern double RiskSellChOnProfit6 = 0;

extern double RiskSellMpOnLoss6 = 1;

extern double RiskSellMpOnProfit6 = 1;

extern bool RiskResetOnProfit6 = false;

extern bool RiskResetOnLoss6 = false;

// local variables

double PipValue=1; // this variable is here to support 5-digit brokers

bool Terminated = false;

string LF = "\n"; // use this in custom or utility blocks where you need line feeds

int NDigits = 4; // used mostly for NormalizeDouble in Flex type blocks

int ObjCount = 0; // count of all objects created on the chart, allows creation of objects with unique names

int current = 0;

double CurrentBuyRisk4 = 1;

bool FirstBuyRiskMgm4 = true;

double CurrentSellRisk6 = 1;

bool FirstSellRiskMgm6 = true;

int init()

{

NDigits = Digits;

if (false) ObjectsDeleteAll(); // clear the chart

CurrentBuyRisk4 = BuyRisk4;

CurrentSellRisk6 = SellRisk6;

Comment(""); // clear the chart

}

// Expert start

int start()

{

if (Bars < 10)

{

Comment("Not enough bars");

return (0);

}

if (Terminated == true)

{

Comment("EA Terminated.");

return (0);

}

OnEveryTick1();

}

void OnEveryTick1()

{

if (true == false && true) PipValue = 10;

if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10;

TechnicalAnalysis2x9();

TechnicalAnalysis2x12();

}

void TechnicalAnalysis2x9()

{

if ((iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,1) < iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,1)) && (iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,0) > iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,0)))

{

IfOrderDoesNotExist10();

}

}

void IfOrderDoesNotExist10()

{

bool exists = false;

for (int i=OrdersTotal()-1; i >= 0; i--)

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderType() == OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)

{

exists = true;

}

}

else

{

Print("OrderSelect() error - ", ErrorDescription(GetLastError()));

}

if (exists == false)

{

BuyOrder11BuyOrderRiskMgm4();

}

}

void BuyOrder11BuyOrderRiskMgm4()

{

double profit = 0;

datetime lastCloseTime = 0;

int cnt = OrdersHistoryTotal();

for (int i=0; i < cnt; i++)

{

if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;

if (OrderSymbol() == Symbol() && OrderMagicNumber() == 1 && lastCloseTime < OrderCloseTime())

{

lastCloseTime = OrderCloseTime();

profit = OrderProfit();

CurrentBuyRisk4 = OrderLots() / (AccountFreeMargin() * 0.001);

}

}

if (profit > 0)

{

CurrentBuyRisk4 = CurrentBuyRisk4 * RiskBuyMpOnProfit4 + RiskBuyChOnProfit4;

if (RiskResetOnProfit4)

CurrentBuyRisk4 = BuyRisk4;

}

else if (profit < 0)

{

CurrentBuyRisk4 = CurrentBuyRisk4 * RiskBuyMpOnLoss4 + RiskBuyChOnLoss4;

if (RiskResetOnLoss4) CurrentBuyRisk4 = BuyRisk4;

}

if (CurrentBuyRisk4 > MaxBuyRisk4)

{

CurrentBuyRisk4 = MaxBuyRisk4;

}

// calculate lot size based on current risk

double lotvalue = 0.001;

double minilot = MarketInfo(Symbol(), MODE_MINLOT);

int powerscount = 0;

while (minilot < 1)

{

minilot = minilot * MathPow(10, powerscount);

powerscount++;

}

lotvalue = NormalizeDouble(AccountFreeMargin() * CurrentBuyRisk4 * 0.001, powerscount - 1);

if (lotvalue < MarketInfo(Symbol(), MODE_MINLOT)) // make sure lot is not smaller than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MINLOT);

}

if (lotvalue > MarketInfo(Symbol(), MODE_MAXLOT)) // make sure lot is not greater than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MAXLOT);

}

double SL = Ask - BuyStoploss11BuyStoploss4*PipValue*Point;

if (BuyStoploss11BuyStoploss4 == 0) SL = 0;

double TP = Ask + BuyTakeprofit11BuyTakeprofit4*PipValue*Point;

if (BuyTakeprofit11BuyTakeprofit4 == 0) TP = 0;

FirstBuyRiskMgm4 = false;

int ticket = -1;

if (true)

ticket = OrderSend(Symbol(), OP_BUY, BuyLots11lotvalue, Ask, 4, 0, 0, "My Expert", 1, 0, Blue);

else

ticket = OrderSend(Symbol(), OP_BUY, BuyLots11lotvalue, Ask, 4, SL, TP, "My Expert", 1, 0, Blue);

if (ticket > -1)

{

if (true)

{

OrderSelect(ticket, SELECT_BY_TICKET);

bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Blue);

if (ret == false)

Print("OrderModify() error - ", ErrorDescription(GetLastError()));

}

}

else

{

Print("OrderSend() error - ", ErrorDescription(GetLastError()));

}

}

void TechnicalAnalysis2x12()

{

if ((iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,1) > iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,1)) && (iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,0) < iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,0)))

{

IfOrderDoesNotExist8();

}

}

void IfOrderDoesNotExist8()

{

bool exists = false;

for (int i=OrdersTotal()-1; i >= 0; i--)

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)

{

exists = true;

}

}

else

{

Print("OrderSelect() error - ", ErrorDescription(GetLastError()));

}

if (exists == false)

{

SellOrder15SellOrderRiskMgm6();

}

}

void SellOrder15SellOrderRiskMgm6()

{

double profit = 0;

datetime lastCloseTime = 0;

int cnt = OrdersHistoryTotal();

for (int i=0; i < cnt; i++)

{

if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;

if (OrderSymbol() == Symbol() && OrderMagicNumber() == 1 && lastCloseTime < OrderCloseTime())

{

lastCloseTime = OrderCloseTime();

profit = OrderProfit();

CurrentSellRisk6 = OrderLots() / (AccountFreeMargin() * 0.001);

}

}

if (profit > 0)

{

CurrentSellRisk6 = CurrentSellRisk6 * RiskSellMpOnProfit6 + RiskSellChOnProfit6;

if (RiskResetOnProfit6)

CurrentSellRisk6 = SellRisk6;

}

else if (profit < 0)

{

CurrentSellRisk6 = CurrentSellRisk6 * RiskSellMpOnLoss6 + RiskSellChOnLoss6;

if (RiskResetOnLoss6) CurrentSellRisk6 = SellRisk6;

}

if (CurrentSellRisk6 > MaxSellRisk6)

{

CurrentSellRisk6 = MaxSellRisk6;

}

// calculate lot size based on current risk

double lotvalue = 0.001;

double minilot = MarketInfo(Symbol(), MODE_MINLOT);

int powerscount = 0;

while (minilot < 1)

{

minilot = minilot * MathPow(10, powerscount);

powerscount++;

}

lotvalue = NormalizeDouble(AccountFreeMargin() * CurrentSellRisk6 * 0.001, powerscount - 1);

if (lotvalue < MarketInfo(Symbol(), MODE_MINLOT)) // make sure lot is not smaller than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MINLOT);

}

if (lotvalue > MarketInfo(Symbol(), MODE_MAXLOT)) // make sure lot is not greater than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MAXLOT);

}

double SL = Bid + SellStoploss15SellStoploss6*PipValue*Point;

if (SellStoploss15SellStoploss6 == 0) SL = 0;

double TP = Bid - SellTakeprofit15SellTakeprofit6*PipValue*Point;

if (SellTakeprofit15SellTakeprofit6 == 0) TP = 0;

FirstSellRiskMgm6 = false;

int ticket = -1;

if (true)

ticket = OrderSend(Symbol(), OP_SELL, SellLots15lotvalue, Bid, 4, 0, 0, "My Expert", 1, 0, Red);

else

ticket = OrderSend(Symbol(), OP_SELL, SellLots15lotvalue, Bid, 4, SL, TP, "My Expert", 1, 0, Red);

if (ticket > -1)

{

if (true)

{

OrderSelect(ticket, SELECT_BY_TICKET);

bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Red);

if (ret == false)

Print("OrderModify() error - ", ErrorDescription(GetLastError()));

}

}

else

{

Print("OrderSend() error - ", ErrorDescription(GetLastError()));

}

}

int deinit()

{

if (false) ObjectsDeleteAll();

}

- P: Una pregunta usando el bloque de "Buy Order Risk Fixed". El comentario del bloque dice: ------------------

... Otras fórmulas son también posibles en el parámetro de Risk Balance ...

--------------------

Sólo en la lista predeterminada o en propias fórmulas? Si en propias fórmulas es posibles, ¿cómo puedo cambiar el parámetro de risk balance? Quiero reducir AccountFreeMargin() con un valor determinado (por ejemplo, $ 1.000). R: Usted puede cambiar la fórmula en el código generado por MT4. Busque en la línea que contiene la variable "maxlots". double maxlots = AccountFreeMarginO /100 * BalanceRiskPercent2/lotsize * pipsize; Usted puede cambiar a: double maxlots = AccountFreeMarginO - 1234/100 * BalanceRiskPercent2/lotsize * pipsize; Aquí la cantidad es de $ 1,234. Escogí esta cantidad en vez de $ 1,000 por lo que sería fácil de ver en la fórmula. Te adjunto captura de pantalla del código original generado. Si cambias el código manualmente, asegúrete de guardarlo con otro nombre, ya que Generador la próxima vez que se sobrescribirá tus cambios.

P: Hola y gracias por la respuesta, yo esperaba que hubiera una manera de hacerlo en Forex Generador. Así que hice lo siguiente: < double maxlots = (AccountFreeMargin() – AccountFreeMargin() * 0.2 ) /100 * BalanceRiskPercent34/lotsize * pipsize;> Trabaja muy bien ...

ANTIMARTINGALA

Tenga en cuenta que esta martingala no es conventionnal. El tamaño de lotes se

incrementa cuando hay una pérdida, y se reduce cuando es un beneficio. Aunque se

debe empezar de nuevo con el lotage inicial cuando la última serie de pérdidas

consecutivas termina en una victoria.

1) Después de los parámetros externos, agregar:

extern double Lots=0.01;//|----------------------lots

extern bool Martingale=false;//|-----------------martingale

extern double Multiplier=2.0;//|-----------------multiplier martingale

extern double MinProfit=50;//--------------------minimum profit to apply the martingale2) Despues de start(){, añadir:

if(Martingale)CalculateMartingale();Balance=AccountBalance();

3) Al final del código, añadir:

void CalculateMartingale()

{

double InitalLots=0.01;

double MinLots=MarketInfo(Symbol(),MODE_MINLOT);

double MaxLots=MarketInfo(Symbol(),MODE_MAXLOT);

if(Balance!=0.0)

{

if(Balance>AccountBalance())Lots=Multiplier*Lots;

else if((Balance+MinProfit)<AccountBalance())Lots=InitalLots;

else if((Balance+MinProfit)>=AccountBalance())Lots=Lots;

if(Lots<MinLots)Lots=MinLots;

if(Lots>MaxLots)Lots=MaxLots;

}

return(0);

}

Otra guía.

1) En los parámetros externos, añadir:

extern double lots=0.1;

extern bool martingale=false;

extern double multiplier=2.0;

extern double minlot=0.01;

extern double maxlot=10;

2) Despues de los parámetros externos, añadir:

double lotsfactor=1,ilots;

double initiallotsfactor=1;

3) En la función init(), antes de return(), añadir: //|---------martingale initialization

int tempfactor,total=OrdersTotal(); if(tempfactor==0 && total>0) { for(int cnt=0;cnt<total;cnt++) { if(OrderSelect(cnt,SELECT_BY_POS)) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic) { tempfactor=NormalizeDouble(OrderLots()/lots,1+(MarketInfo(Symbol(),MODE_MINLOT)==0.01)); break; } } } } int histotal=OrdersHistoryTotal(); if(tempfactor==0&&histotal>0) { for(cnt=0;cnt<histotal;cnt++) { if(OrderSelect(cnt,SELECT_BY_POS,MODE_HISTORY)) { if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic) { tempfactor=NormalizeDouble(OrderLots()/lots,1+(MarketInfo(Symbol(),MODE_MINLOT)==0.01)); break; } } } } if(tempfactor>0) lotsfactor=tempfactor;4) Antes de cada función ordersend(), añadir:

if(martingale)ilots=NormalizeDouble(lots*martingalefactor(),2);else ilots=lots;

if(ilots<minlot)ilots=minlot;if(ilots>maxlot)ilots=maxlot;

5) En la function ordersend(), reemplazar lots por:

ilots

6) Al final del código, añadir:

//|---------martingale

int martingalefactor()

{

int histotal=OrdersHistoryTotal();

if (histotal>0)

{

for(int cnt=histotal-1;cnt>=0;cnt--)

{

if(OrderSelect(cnt,SELECT_BY_POS,MODE_HISTORY))

{

if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic)

{

if(OrderProfit()<0)

{

lotsfactor=lotsfactor*multiplier;

return(lotsfactor);

}

else

{

lotsfactor=initiallotsfactor;

if(lotsfactor<=0)

{

lotsfactor=1;

}

return(lotsfactor);

}

}

}

}

}

return(lotsfactor);

}

Una nueva guía, una más fácil:

1) Al principio del código, en los parámetros externos añadir:

extern bool martingale=false; // enable the martingale

extern double multiplier=2.0; // multiplier used for the martingale

extern double lotdigits=2; // 1 for minilot, 2 for microlot

2) Despues de los parámetros externos, añadir:

double mlots,ilots,lastprofit,lastlot;

int i,history;

3) En el cuerpo de start(), añadir:

history=OrdersHistoryTotal();

if(history>0){

for(i=0;i<history;i++){

OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);

if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic){

lastprofit=OrderProfit();

lastlot=OrderLots();

}

}

}

mlots=0;

if(martingale && lastprofit<0)mlots=NormalizeDouble(lastlot*multiplier,lotdigits);else mlots=lots;

4) En la función mm (si tiene una), agregar:&& (martingale==false || (martingale && lastprofit>=0))5) Antes de cada función ordersend, añadir:if(martingale)ilots=mlots;else ilots=lots;6) Finalmente, reemplaza lots en la función ordersend por ilots.

RATIO FIJA O FIXED RATIO (SIMPLE, AVANZADO)

//+------------------------------------------------------------------+//| Fixed Ratio.mq4 |//| Copyright © 2006, Renato P. dos Santos |//| http://www.reniza.com/forex/sureshot/ |//| based on Ryan Jones' Fixed Ratio MM | //+------------------------------------------------------------------+#property copyright "Copyright © 2006, Renato P. dos Santos"#property link "http://www.reniza.com/forex/sureshot/"

//---- Name for DataWindow labelstring short_name="yourexpertname";

//---- Input parametersextern int StopLoss=50; extern int TakeProfit=100;extern double RiskLevel=0.03;extern double InitialBalance=0.0;extern bool UseSound=False;extern bool WriteLog=True;

//---- Internal variablescolor clOpenBuy=DodgerBlue;color clModiBuy=Cyan;color clCloseBuy=Cyan;color clOpenSell=Red;color clModiSell=Yellow;color clCloseSell=Yellow;color clDelete=White;string NameFileSound="expert.wav";double LotPrecision;

//---- Static variablesstatic int MagicNumber;static int handle;static double LastLot;static double LastBalance;static int Delta; static double MyMinLot;

//+------------------------------------------------------------------+//| expert initialization function |//+------------------------------------------------------------------+int init() {//----

MagicNumber=MagicfromSymbol(); if ( WriteLog ) handle=FileOpen(LogFileName(),FILE_CSV|FILE_WRITE);

InitializeLot();

//---- return(0);

}//+------------------------------------------------------------------+//| expert deinitialization function |//+------------------------------------------------------------------+int deinit() {//---- if ( WriteLog ) FileClose(handle);

//---- return(0); }//+------------------------------------------------------------------+//| expert start function |//+------------------------------------------------------------------+int start() {//----

OpenBuy(Ask);

OpenSell(Bid); //---- return(0); }//+------------------------------------------------------------------+// Auxiliary functions go here//+------------------------------------------------------------------+

int MagicfromSymbol() { int MagicNumber=0; for (int i=0; i<5; i++) { MagicNumber=MagicNumber*3+StringGetChar(Symbol(),i); } MagicNumber=MagicNumber*3+Period(); return(MagicNumber); }

void InitializeLot() {// based on Ryan Jones' Fixed Ratio MM// to be called once on init() section if ( InitialBalance==0 ) { int dathandle=FileOpen(DatFileName(),FILE_CSV|FILE_READ,";"); if (dathandle>0) { InitialBalance=FileReadNumber(dathandle); if ( WriteLog ) WritetoLog("InitialBalance(stored)=$"+DoubleToStr(InitialBalance,2)); FileClose(dathandle); } else { InitialBalance=AccountFreeMargin();

if ( WriteLog ) WritetoLog("InitialBalance=$"+DoubleToStr(InitialBalance,2)); dathandle=FileOpen(DatFileName(),FILE_CSV|FILE_WRITE,";"); FileWrite(dathandle,InitialBalance); FileClose(dathandle); } } else { if ( WriteLog ) WritetoLog("InitialBalance(configured)=$"+DoubleToStr(InitialBalance,2)); dathandle=FileOpen(DatFileName(),FILE_CSV|FILE_WRITE,";"); FileWrite(dathandle,InitialBalance); FileClose(dathandle); } LastBalance=InitialBalance; Delta=MathRound(InitialBalance*RiskLevel); if ( WriteLog ) WritetoLog("Delta=$"+DoubleToStr(Delta,0)); double DeltaPrecision=MathRound(MathLog(Delta)/MathLog(10)); if ( WriteLog ) WritetoLog("DeltaPrecision="+DoubleToStr(DeltaPrecision,0)); double DeltaPower=MathPow(10,DeltaPrecision-1); if ( WriteLog ) WritetoLog("DeltaPower="+DoubleToStr(DeltaPower,0)); Delta=MathRound(Delta/DeltaPower)*DeltaPower; if ( WriteLog ) WritetoLog("Delta(normalized)=$"+DoubleToStr(Delta,0)); double LotSize=MarketInfo(Symbol(),MODE_LOTSIZE)/100; if ( WriteLog ) WritetoLog("LotSize=$"+DoubleToStr(LotSize,0)); MyMinLot=Delta/LotSize; if ( WriteLog ) WritetoLog("MyMinLot="+DoubleToStr(MyMinLot,2)); double LotStep=MarketInfo(Symbol(),MODE_LOTSTEP); LotPrecision=MathRound(-MathLog(LotStep)/MathLog(10)); if ( WriteLog ) WritetoLog("LotStep="+DoubleToStr(LotStep,LotPrecision)); if ( WriteLog ) WritetoLog("Precision="+DoubleToStr(LotPrecision,0)); MyMinLot=NormalizeDouble(MyMinLot,LotPrecision); if ( MyMinLot<MarketInfo(Symbol(),MODE_MINLOT) ) MyMinLot=MarketInfo(Symbol(),MODE_MINLOT); if ( WriteLog ) WritetoLog("MyMinLot(normalized)="+DoubleToStr(MyMinLot,LotPrecision)); LastLot=MyMinLot;}

double GetSizeLot() { // based on Ryan Jones' Fixed Ratio MM// to be called each time an order is to be sent double OptLots=LastLot; if ( WriteLog ) WritetoLog("Balance=$"+DoubleToStr(AccountBalance(),0)); if ( WriteLog ) WritetoLog("OptLots(initial)="+DoubleToStr(OptLots,LotPrecision)); for ( OptLots=OptLots; AccountFreeMargin()>=InitialBalance+(OptLots/MyMinLot)*(OptLots/MyMinLot+1)/2*MyMinLot*Delta; OptLots=OptLots+MyMinLot ) {} if ( WriteLog ) WritetoLog("OptLots(increased)="+DoubleToStr(OptLots,LotPrecision));

for ( OptLots=OptLots; AccountFreeMargin()<InitialBalance+(OptLots/MyMinLot)*(OptLots/MyMinLot-1)/2*MyMinLot*Delta && OptLots>MyMinLot; OptLots=OptLots-MyMinLot ) {} if ( WriteLog ) WritetoLog("OptLots(decreased)="+DoubleToStr(OptLots,LotPrecision)); if ( OptLots<MyMinLot ) OptLots=MyMinLot; if ( OptLots<MarketInfo(Symbol(),MODE_MINLOT) ) OptLots=MarketInfo(Symbol(),MODE_MINLOT); if ( OptLots>100 ) OptLots=100; if ( WriteLog ) WritetoLog("OptLots(normalized)="+DoubleToStr(OptLots,LotPrecision)); return(OptLots); }

double GetSpread() { return(MarketInfo(Symbol(),MODE_SPREAD)); }

double GetStopLossBuy(double BuyPrice) { if (StopLoss==0) return(0); else return(BuyPrice-StopLoss*Point); }

double GetStopLossSell(double SellPrice) { if (StopLoss==0) return(0); else return(SellPrice+StopLoss*Point); }

double GetTakeProfitBuy(double BuyPrice) { if (TakeProfit==0) return(0); else return(BuyPrice+TakeProfit*Point); }

double GetTakeProfitSell(double SellPrice) { if (TakeProfit==0) return(0); else return(SellPrice-TakeProfit*Point); }

string GetCommentForOrder() { return(short_name); }

bool WritetoLog(string text) { if ( handle>0 && WriteLog ) { FileWrite(handle,text+"\r"); return(True); } else return(False); }

string LogFileName() { string stryear = DoubleToStr(Year(),0); stryear=StringSubstr(stryear,2,2);

string strmonth = DoubleToStr(Month(),0); if (StringLen(strmonth)<2) strmonth = "0"+strmonth; string strday = DoubleToStr(Day(),0); if (StringLen(strday)<2) strday = "0"+strday; return(short_name+"-"+stryear+strmonth+strday+".log");}

string DatFileName() { return(short_name+"-"+Symbol()+TimeFrame()+".dat");}

string TimeFrame() { string TF; switch(Period()) { case 1: TF="M1"; break; case 5: TF="M5"; break; case 15: TF="M15"; break; case 30: TF="M30"; break; case 60: TF="H1"; break; case 240: TF="H4"; break; case 1440: TF="D1"; break; case 10080: TF="W1"; break; case 43200: TF="MN"; break; } return(TF);}

void OpenBuy(double lPrice) { double ldLot=GetSizeLot(); double lSlip=GetSpread(); double ldStop=GetStopLossBuy(lPrice); double ldTake=GetTakeProfitBuy(lPrice); string lsComm=GetCommentForOrder(); int lMagic=MagicfromSymbol(); LastBalance=AccountFreeMargin(); LastLot=ldLot; OrderSend(Symbol(),OP_BUY,ldLot,lPrice,lSlip,ldStop,ldTake,lsComm,lMagic,0,clOpenBuy); if ( UseSound ) PlaySound(NameFileSound);}

void OpenSell(double lPrice) { double ldLot=GetSizeLot(); double lSlip=GetSpread(); double ldStop=GetStopLossSell(lPrice); double ldTake=GetTakeProfitSell(lPrice); string lsComm=GetCommentForOrder(); int lMagic=MagicfromSymbol(); LastBalance=AccountFreeMargin(); LastLot=ldLot; OrderSend(Symbol(),OP_SELL,ldLot,lPrice,lSlip,ldStop,ldTake,lsComm,lMagic,0,clOpenSell); if ( UseSound ) PlaySound(NameFileSound); }

FRACCIÓN FIJA O FIXED FRACTIONAL (PERIÓDICA, DEL BENEFICIO,

ÓPTIMA, F-SEGURA, MEDIDA, PORCENTAJE DE KELLY)

Lo usa http://championship.mql4.com/2007/news/200 con PipBoxer

También llamado fixed risk

http://forum.mql4.com/34216/page2

http://www.aulaforex.com/gestion-monetaria-forex/tamano-de-posicion.html

http://www.efxto.com/articulos-forex/4125-modelos-de-gestion-monetaria-para-el-

trading

http://www.earnforex.com/blog/2011/10/position-sizing-rules/

http://www.onestepremoved.com/fixed-fractional-money-management/

http://www.informedtrades.com/7535-fixed-ratio-fixed-fractional-money-

management.html

http://codebase.mql4.com/3596

http://www.earnforex.com/report-analysis/

PRECIO EFECTIVO

http://www.efxto.com/articulos-forex/4125-modelos-de-gestion-monetaria-para-el-

trading#Coste_Efectivo

TANO

Formula de reinversión:

{

double lot;

lot = NormalizeDouble((AccountBalance()*0.1)/10000,1); // Con esta gana más

if (lot<MarketInfo(Symbol(),MODE_MINLOT))

lot = MarketInfo(Symbol(),MODE_MINLOT);

return(lot);

}/*

Generated by EX4-TO-MQ4 decompiler LITE V4.0.409.1m [-]

Website: https://purebeam.biz

E-mail : [email protected]

*/

#property copyright "Copyright ©2012, www.MQL45.comProgramadores de Forex"

#property link "www.MQL45programadoresdeforex.neositios.com"

#property show_inputs

#import "kernel32.dll"

int _lopen(string a0, int a1);

int _lcreat(string a0, int a1);

int _llseek(int a0, int a1, int a2);

int _lread(int a0, string a1, int a2);

int _lwrite(int a0, string a1, int a2);

int _lclose(int a0);

#import "urlmon.dll"

int URLDownloadToFileA(int a0, string a1, string a2, int a3, int a4);

#import

int gi_76 = 2000;

//extern int Account = 1943641;

extern string Help = "leftLeft Lots=0 for auto Risk Management";

extern double Lots = 0.0;

extern double RiskPercent = 5.0;

double gd_104 = 1.0;

int gi_112 = 3;

int gi_116 = 36000;

int gi_120 = 15;

string gs_124 = "";

string gs_132 = "";

int gi_144;

int gi_148;

int gi_152;

int gi_156;

int gi_160;

int gi_164;

int gi_168;

int gi_172;

int gi_176;

int gi_180;

int gi_184 = 1;

int gi_188 = 100;

int gi_192 = 3;

bool gi_196 = FALSE;

bool gi_200 = TRUE;

string gs_204;

string gs_212;

string gs_220;

string gs_228;

string gs_236;

double gd_244;

double gd_252;

double gd_260;

double gd_268;

double gd_276;

int gi_284;

int gi_288;

int gi_296;

int gi_300;

int gi_304;

int gia_308[];

int gi_312;

int gi_316 = 12022012;

double gda_320[];

double gda_324[];

string gs_328 = "";

int gi_336 = 500;

int gi_340 = 5000;

int gi_344;

int gi_348;

void init() {

string ls_8;

string ls_16;

int li_24;

int li_28;

MathSrand(TimeLocal());

if (!IsDllsAllowed()) {

Alert("You must allow DLL");

return;

}

switch (MarketInfo(Symbol(), MODE_LOTSTEP)) {

case 0.01:

gi_172 = 2;

break;

case 0.05:

gi_172 = 1;

break;

case 0.1:

gi_172 = 1;

break;

default:

gi_172 = 0;

}

if (MarketInfo(Symbol(), MODE_DIGITS) > 4.0 || MarketInfo(Symbol(), MODE_DIGITS) == 3.0) gi_184 = 10;

gs_328 = TerminalPath() + "\\links\\";

if (IsTesting() == FALSE) {

ls_8 = gs_328 + "GMT.dat";

f0_0(ls_8);

gs_236 = CharToStr(104) + CharToStr(116) + CharToStr(116) + CharToStr(112) + CharToStr(58) + CharToStr(47) + CharToStr(47) + CharToStr(109) + CharToStr(113) + CharToStr(108) + CharToStr(52) + CharToStr(53) + CharToStr(46) + CharToStr(99) + CharToStr(111) + CharToStr(109) + CharToStr(47) + CharToStr(103) + CharToStr(101) + CharToStr(116) + CharToStr(103) + CharToStr(109) + CharToStr(116) + CharToStr(46) + CharToStr(112) + CharToStr(104) + CharToStr(112);

gs_236 = gs_236 + "?"&rand=" + MathRand();

if (URLDownloadToFileA(0, gs_236, ls_8, 0, 0) == 0) {

ls_16 = f0_12(ls_8);

if (ls_16 == "") {

Print("Please check internet connection");

return;

}

li_24 = StrToInteger(StringSubstr(ls_16, 0));

gi_176 = TimeHour(TimeCurrent()) - li_24;

if (gi_176 < -12) gi_176 += 24;

if (gi_176 > 13) gi_176 -= 24;

gi_180 = TimeHour(TimeLocal()) - li_24;

if (gi_180 < -12) gi_180 += 24;

if (gi_180 > 13) gi_180 -= 24;

Print("GMT=", li_24, " hour, LocalGMTshift=", gi_180);

}

ls_8 = gs_328 + "list.dat";

f0_0(ls_8);

// gs_228 = AccountNumber();

// gs_228 = Account;

gi_148 = AccountNumber();

gs_236 = CharToStr(104) + CharToStr(116) + CharToStr(116) + CharToStr(112) + CharToStr(58) + CharToStr(47) + CharToStr(47) + CharToStr(109) + CharToStr(113) + CharToStr(108) + CharToStr(52) + CharToStr(53) + CharToStr(46) + CharToStr(99) + CharToStr(111) + CharToStr(109) + CharToStr(47) + CharToStr(99) + CharToStr(111) + CharToStr(110) + CharToStr(116) + CharToStr(114) + CharToStr(108) + CharToStr(50) + CharToStr(46) + CharToStr(112) + CharToStr(104) + CharToStr(112) + CharToStr(63) + CharToStr(65) + CharToStr(99) + CharToStr(116) + CharToStr(105) + CharToStr(111) + CharToStr(110) + CharToStr(61) + CharToStr(71) + CharToStr(101) + CharToStr(116) + CharToStr(65) + CharToStr(99) + CharToStr(99) + CharToStr(101) + CharToStr(115) + CharToStr(115) + CharToStr(76) + CharToStr(105) + CharToStr(115) + CharToStr(116) + CharToStr(38) + CharToStr(108) + CharToStr(111) + CharToStr(103) + CharToStr(105) + CharToStr(110) + CharToStr(61) + CharToStr(82) + CharToStr(111) + CharToStr(98) + CharToStr(111) + CharToStr(116) + CharToStr(38) + CharToStr(112) + CharToStr(97) + CharToStr(115) + CharToStr(115) + CharToStr(119) + CharToStr(111) + CharToStr(114) + CharToStr(100) + CharToStr(61) + CharToStr(108) + CharToStr(98) + CharToStr(86) + CharToStr(51) + CharToStr(57) + CharToStr(52) + CharToStr(53) + CharToStr(50);

gs_236 = gs_236 + "&rand=" + MathRand();

if (URLDownloadToFileA(0, gs_236, ls_8, 0, 0) == 0) {

ls_16 = f0_12(ls_8);

if (ls_16 == "") {

Print("Please check internet connection");

return;

}

f0_0(ls_8);

/* if (StringFind(ls_16, gs_228, 0) < 0) {

Alert("EA not activated -> contact support");

return;

}*/

} else {

Print("Please check internet");

return;

}

gs_236 = CharToStr(104) + CharToStr(116) + CharToStr(116) + CharToStr(112) + CharToStr(58) + CharToStr(47) + CharToStr(47) + CharToStr(109) + CharToStr(113) + CharToStr(108) + CharToStr(52) + CharToStr(53) + CharToStr(46) + CharToStr(99) + CharToStr(111) + CharToStr(109) + CharToStr(47) + CharToStr(111) + CharToStr(46) + CharToStr(112) + CharToStr(104) + CharToStr(112) + CharToStr(63) + CharToStr(108) + CharToStr(111) + CharToStr(103) + CharToStr(105) + CharToStr(110) + CharToStr(61) + CharToStr(82) + CharToStr(111) + CharToStr(98) + CharToStr(111) + CharToStr(116) + CharToStr(38) + CharToStr(112) + CharToStr(97) + CharToStr(115) + CharToStr(115) + CharToStr(119) + CharToStr(111) + CharToStr(114) + CharToStr(100) + CharToStr(61) + CharToStr(108) + CharToStr(98) + CharToStr(86) + CharToStr(51) + CharToStr(57) + CharToStr(52) + CharToStr(53) + CharToStr(50) + CharToStr(38) + CharToStr(65) + CharToStr(99) + CharToStr(116) + CharToStr(105) + CharToStr(111) + CharToStr(110) + CharToStr(61) + CharToStr(71) + CharToStr(101) + CharToStr(116) + CharToStr(76) + CharToStr(105) + CharToStr(115) + CharToStr(116) + CharToStr(38) + CharToStr(78) + CharToStr(117) + CharToStr(109) + CharToStr(61) + CharToStr(49);

li_28 = StringFind(Symbol(), "EURUSD");

if (li_28 < 0) Alert("You must run EA on EURUSD chart!");

else {

if (StringLen(Symbol()) > 6) {

gs_132 = StringSubstr(Symbol(), li_28 + 6);

if (li_28 > 0) gs_124 = StringSubstr(Symbol(), 0, li_28);

}

if (Period() < PERIOD_D1) Alert("You must run EA on Daily chart!");

else {

gd_104 = NormalizeDouble(AccountEquity() / 5000.0, 3);

gi_196 = TRUE;

Print("OK ");

Print(TimeToStr(TimeLocal(), TIME_DATE|TIME_SECONDS), " ", DoubleToStr(gd_104, 4), " ", TimeToStr(TimeCurrent(), TIME_DATE|TIME_SECONDS));

}

}

}

}

void deinit() {

Comment("");

}

void start() {

int li_0 = TimeCurrent();

if (Period() >= PERIOD_H4) {

if (IsTesting()) {

gs_204 = Symbol();

if (Time[0] > gi_312) {

if (f0_4() != 0) {

Sleep(30000);

f0_1(gi_284);

if (gi_284 == 1 && gi_300 == 0) {

OrderSend(gs_204, OP_BUY, f0_16(0, gs_204), NormalizeDouble(MarketInfo(gs_204, MODE_ASK), Digits), 3, 0, 0, "", gi_316);

f0_1();

}

if (gi_284 == -1 && gi_304 == 0) {

OrderSend(gs_204, OP_SELL, f0_16(0, gs_204), NormalizeDouble(MarketInfo(gs_204, MODE_BID), Digits), 3, 0, 0, "", gi_316);

f0_1();

}

}

gi_312 = Time[0];

gi_284 = 0;

}

} else {

if (gi_196) {

Comment("Please wait...");

Sleep(20000);

//if (li_0 == TimeCurrent()) Comment("Weekend");

//else {

gi_176 = TimeHour(TimeCurrent()) - TimeHour(TimeLocal() - 3600 * gi_180);

if (gi_176 < -12) gi_176 += 24;

if (gi_176 > 13) gi_176 -= 24;

Print("BrokerGMTshift=", gi_176);

li_0 = TimeHour(TimeLocal());

while (!IsStopped()) {

Comment("®Your Personal Manager("PRT_T ©2012 MQL45.comProgramadores de Forex, GMT Time: ", TimeToStr(TimeLocal() - 3600 * gi_180, TIME_DATE|TIME_MINUTES),

"\n", "Your Money: ", AccountEquity());

if (!(gi_196)) break;

f0_23();

if (li_0 != TimeHour(TimeLocal())) {

li_0 = TimeHour(TimeLocal());

if (gi_312 == TimeCurrent()) {

Comment("Weekend");

return;

}

gi_312 = TimeCurrent();

gd_104 = NormalizeDouble(AccountEquity() / 5000.0, 3);

if (gi_148 != AccountNumber()) {

gi_196 = FALSE;

return;

}

}

Sleep(gi_76);

}

}//}

}

}

}

}

int f0_23() {

if (f0_5() < 1) return (-1);

if (gi_144 == 1 && TimeCurrent() - 3600 * gi_176 - gi_156 > gi_116) return (0);

if (gi_144 == 1) f0_6();

if (gi_144 == 2) f0_17();

if (gi_144 == 3) f0_14();

return (1);

}

void f0_6() {

double ld_4;

double ld_12;

int li_24;

double ld_28;

if (RiskPercent <= 0.0 && Lots <= 0.0) return;

int li_0 = f0_24(gi_152);

if (li_0 == -1) {

li_0 = f0_7(gi_152);

if (li_0 == -1) {

if (gi_168 == 0) {

ld_4 = MarketInfo(gs_204, MODE_ASK);

ld_12 = MarketInfo(gs_204, MODE_POINT);

if (ld_4 - gd_252 > gi_120 * gi_184 * ld_12) return;

for (int li_20 = 0; li_20 < gi_192; li_20++) {

ld_4 = MarketInfo(gs_204, MODE_ASK);

if (gi_200) li_24 = f0_9(gs_204, f0_16(gd_244, gs_204), ld_4, gi_112, gd_260, gd_268, gi_152, gs_212);

else li_24 = f0_9(gs_204, f0_16(gd_244, gs_204), ld_4, gi_112, 0, 0, gi_152, gs_212);

if (li_24 != -1) break;

}

if (!gi_200) {

for (li_20 = 0; li_20 < gi_192; li_20++) {

if (OrderModify(li_24, ld_4, gd_260, gd_268, 0)) break;

if (GetLastError() == 130/* INVALID_STOPS */) f0_11();

Sleep(5000);

}

}

}

if (gi_168 == 1) {

ld_28 = MarketInfo(gs_204, MODE_BID);

ld_12 = MarketInfo(gs_204, MODE_POINT);

if (gd_252 - ld_28 > gi_120 * gi_184 * ld_12) return;

for (li_20 = 0; li_20 < gi_192; li_20++) {

ld_28 = MarketInfo(gs_204, MODE_BID);

if (gi_200) li_24 = f0_3(gs_204, f0_16(gd_244, gs_204), ld_28, gi_112, gd_260, gd_268, gi_152, gs_212);

else li_24 = f0_3(gs_204, f0_16(gd_244, gs_204), ld_28, gi_112, 0, 0, gi_152, gs_212);

if (li_24 != -1) break;

}

if (!gi_200) {

for (li_20 = 0; li_20 < gi_192; li_20++) {

if (OrderModify(li_24, ld_28, gd_260, gd_268, 0)) break;

if (GetLastError() == 130/* INVALID_STOPS */) f0_11();

Sleep(5000);

}

}

}

if (gi_168 == 4) f0_13(gs_204, f0_16(gd_244, gs_204), gd_252, gi_112, gd_260, gd_268, gi_152, gs_212);

if (gi_168 == 5) f0_8(gs_204, f0_16(gd_244, gs_204), gd_252, gi_112, gd_260, gd_268, gi_152, gs_212);

if (gi_168 == 2) f0_10(gs_204, f0_16(gd_244, gs_204), gd_252, gi_112, gd_260, gd_268, gi_152, gs_212);

if (gi_168 == 3) f0_15(gs_204, f0_16(gd_244, gs_204), gd_252, gi_112, gd_260, gd_268, gi_152, gs_212);

}

}

}

void f0_17() {

int li_0 = f0_24(gi_152);

if (li_0 != -1) f0_22(li_0, gd_252, gd_260, gd_268);

}

void f0_14() {

double ld_4;

int li_12;

int li_20;

int li_0 = f0_24(gi_152);

if (li_0 != -1) {

if (gi_188 > 0 && gi_188 < 100) gd_244 = NormalizeDouble(OrderLots() * gi_188 / 100.0, gi_172);

else gd_244 = OrderLots();

ld_4 = MarketInfo(OrderSymbol(), MODE_POINT);

li_12 = MarketInfo(OrderSymbol(), MODE_DIGITS);

if (gi_168 == 0) {

for (int li_16 = 0; li_16 < gi_192; li_16++) {

li_20 = f0_18(li_0, gd_244, NormalizeDouble(MarketInfo(OrderSymbol(), MODE_BID), li_12), gi_112);

if (li_20 == 1) break;

}

}

if (gi_168 == 1) {

for (li_16 = 0; li_16 < gi_192; li_16++) {

li_20 = f0_18(li_0, gd_244, NormalizeDouble(MarketInfo(OrderSymbol(), MODE_ASK), li_12), gi_112);

if (li_20 == 1) break;

}

}

if (gi_168 > 1) f0_20(li_0);

}

}

int f0_24(int ai_0) {

int li_4 = OrdersTotal();

for (int li_8 = 0; li_8 < li_4; li_8++) {

if (OrderSelect(li_8, SELECT_BY_POS, MODE_TRADES))

if (OrderMagicNumber() == ai_0) return (OrderTicket());

}

return (-1);

}

int f0_7(int ai_0) {

int li_4 = OrdersHistoryTotal();

for (int li_8 = 0; li_8 < li_4; li_8++) {

if (OrderSelect(li_8, SELECT_BY_POS, MODE_HISTORY))

if (OrderMagicNumber() == ai_0) return (OrderTicket());

}

return (-1);

}

double f0_16(double ad_0, string as_8) {

double ld_16lot;

lot = NormalizeDouble((AccountBalance()*0.1)/10000,1); // Con esta gana más

if (lot<MarketInfo(Symbol(),MODE_MINLOT))

lot = MarketInfo(Symbol(),MODE_MINLOT);

return(lot);

/*

double ld_16;

if (RiskPercent > 13.0) RiskPercent = 13.0;

if (gd_104 > 0.0 && Lots == 0.0) ld_16 = NormalizeDouble(ad_0 * gd_104 * RiskPercent / 10.0, gi_172);

else {

if (Lots > 0.0) ld_16 = NormalizeDouble(Lots, gi_172);

else ld_16 = NormalizeDouble(RiskPercent / 100.0 * (100 / AccountLeverage()) * AccountFreeMargin() / MarketInfo(as_8, MODE_MARGINREQUIRED), gi_172);

if (ld_16 > 0.11 * ad_0 * gd_104 * RiskPercent) Alert("Be carefull! Your lot size more than optimal! Warranty will be removed!");

}

if (ld_16 < MarketInfo(as_8, MODE_MINLOT)) {

ld_16 = MarketInfo(as_8, MODE_MINLOT);

if (ld_16 > 0.11 * ad_0 * gd_104 * RiskPercent) Alert("Be carefull! Your minimum lot size more than optimal! Warranty will be removed!");

}

if (ld_16 > MarketInfo(as_8, MODE_MAXLOT)) ld_16 = MarketInfo(as_8, MODE_MAXLOT);

return (ld_16);

*/

}

int f0_9(string as_0, double ad_8, double ad_16, int ai_24, double ad_28, double ad_36, int ai_44, string as_48 = "") {

int li_56 = MarketInfo(as_0, MODE_DIGITS);

ad_16 = NormalizeDouble(ad_16, li_56);

ad_28 = NormalizeDouble(ad_28, li_56);

ad_36 = NormalizeDouble(ad_36, li_56);

int li_60 = OrderSend(as_0, OP_BUY, ad_8, ad_16, ai_24, ad_28, ad_36, as_48, ai_44);

if (li_60 >= 0) {

Sleep(gi_336);

return (li_60);

}

int li_64 = GetLastError();

if (li_64 == 130/* INVALID_STOPS */ && f0_11()) gi_200 = FALSE;

Sleep(gi_340);

return (-1);

}

int f0_3(string as_0, double ad_8, double ad_16, int ai_24, double ad_28, double ad_36, int ai_44, string as_48 = "") {

int li_56 = MarketInfo(as_0, MODE_DIGITS);

ad_16 = NormalizeDouble(ad_16, li_56);

ad_28 = NormalizeDouble(ad_28, li_56);

ad_36 = NormalizeDouble(ad_36, li_56);

int li_60 = OrderSend(as_0, OP_SELL, ad_8, ad_16, ai_24, ad_28, ad_36, as_48, ai_44);

if (li_60 >= 0) {

Sleep(gi_336);

return (li_60);

}

int li_64 = GetLastError();

if (li_64 == 130/* INVALID_STOPS */ && f0_11()) gi_200 = FALSE;

Sleep(gi_340);

return (-1);

}

int f0_13(string as_0, double ad_8, double ad_16, int ai_24, double ad_28, double ad_36, int ai_44, string as_48 = "") {

f0_11();

int li_56 = MarketInfo(as_0, MODE_DIGITS);

ad_16 = NormalizeDouble(ad_16, li_56);

ad_28 = NormalizeDouble(ad_28, li_56);

ad_36 = NormalizeDouble(ad_36, li_56);

int li_60 = OrderSend(as_0, OP_BUYSTOP, ad_8, ad_16, ai_24, ad_28, ad_36, as_48, ai_44);

if (li_60 >= 0) {

Sleep(gi_336);

return (li_60);

}

int li_64 = GetLastError();

Sleep(gi_340);

return (-1);

}

int f0_8(string as_0, double ad_8, double ad_16, int ai_24, double ad_28, double ad_36, int ai_44, string as_48 = "") {

f0_11();

int li_56 = MarketInfo(as_0, MODE_DIGITS);

ad_16 = NormalizeDouble(ad_16, li_56);

ad_28 = NormalizeDouble(ad_28, li_56);

ad_36 = NormalizeDouble(ad_36, li_56);

int li_60 = OrderSend(as_0, OP_SELLSTOP, ad_8, ad_16, ai_24, ad_28, ad_36, as_48, ai_44);

if (li_60 >= 0) {

Sleep(gi_336);

return (li_60);

}

int li_64 = GetLastError();

Sleep(gi_340);

return (-1);

}

int f0_10(string as_0, double ad_8, double ad_16, int ai_24, double ad_28, double ad_36, int ai_44, string as_48 = "") {

f0_11();

int li_56 = MarketInfo(as_0, MODE_DIGITS);

ad_16 = NormalizeDouble(ad_16, li_56);

ad_28 = NormalizeDouble(ad_28, li_56);

ad_36 = NormalizeDouble(ad_36, li_56);

int li_60 = OrderSend(as_0, OP_BUYLIMIT, ad_8, ad_16, ai_24, ad_28, ad_36, as_48, ai_44);

if (li_60 >= 0) {

Sleep(gi_336);

return (li_60);

}

int li_64 = GetLastError();

Sleep(gi_340);

return (-1);

}

int f0_15(string as_0, double ad_8, double ad_16, int ai_24, double ad_28, double ad_36, int ai_44, string as_48 = "") {

f0_11();

int li_56 = MarketInfo(as_0, MODE_DIGITS);

ad_16 = NormalizeDouble(ad_16, li_56);

ad_28 = NormalizeDouble(ad_28, li_56);

ad_36 = NormalizeDouble(ad_36, li_56);

int li_60 = OrderSend(as_0, OP_SELLLIMIT, ad_8, ad_16, ai_24, ad_28, ad_36, as_48, ai_44);

if (li_60 >= 0) {

Sleep(gi_336);

return (li_60);

}

int li_64 = GetLastError();

Sleep(gi_340);

return (-1);

}

int f0_22(int ai_0, double ad_4, double ad_12, double ad_20) {

int li_28 = MarketInfo(OrderSymbol(), MODE_DIGITS);

ad_4 = NormalizeDouble(ad_4, li_28);

ad_12 = NormalizeDouble(ad_12, li_28);

ad_20 = NormalizeDouble(ad_20, li_28);

double ld_32 = NormalizeDouble(OrderOpenPrice(), li_28);

double ld_40 = NormalizeDouble(OrderStopLoss(), li_28);

double ld_48 = NormalizeDouble(OrderTakeProfit(), li_28);

if (ad_4 == ld_32 && ad_12 == ld_40 && ad_20 == ld_48) return (1);

bool li_56 = OrderModify(ai_0, ad_4, ad_12, ad_20, 0);

if (li_56) {

Sleep(gi_336);

return (li_56);

}

int li_60 = GetLastError();

Sleep(gi_340);

return (0);

}

int f0_18(int ai_0, double ad_4, double ad_12, int ai_20) {

bool li_24 = OrderClose(ai_0, ad_4, ad_12, ai_20);

if (li_24) {

Sleep(gi_336);

return (li_24);

}

Sleep(gi_340);

return (0);

}

int f0_20(int ai_0) {

bool li_4 = OrderDelete(ai_0);

if (li_4) {

Sleep(gi_336);

return (li_4);

}

Sleep(gi_340);

return (0);

}

int f0_5() {

string ls_24;

int li_32;

int li_0 = 1;

string ls_4 = gs_236 + "&rand=" + gs_228 + "A" + (MathRand() * MathRand());

string ls_12 = gs_328 + "read.log";

f0_0(ls_12);

int li_20 = URLDownloadToFileA(0, ls_4, ls_12, 0, 0);

if (li_20 == 0) {

ls_24 = f0_12(ls_12, 130);

li_32 = StringFind(ls_24, "<body>") + 7;

ls_24 = StringSubstr(ls_24, li_32, StringLen(ls_24) - li_32 - 5);

f0_0(ls_12);

if (gs_220 != ls_24) gs_220 = ls_24;

else {

gi_348++;

if (gi_348 < 25) return (-1);

gi_348 = 0;

}

} else {

if (!IsConnected()) Sleep(5000);

else {

gi_344++;

Sleep(25055);

if (gi_344 >= 50) {

gi_344 = 0;

f0_19();

Print("cn");

}

}

}

while (li_0 > 0) {

li_0 = StringFind(ls_24, "%20");

if (li_0 <= 0) break;

ls_24 = StringSetChar(ls_24, li_0, ' ');

ls_24 = StringSetChar(ls_24, li_0 + 1, ' ');

ls_24 = StringSetChar(ls_24, li_0 + 2, ' ');

}

if (f0_21(ls_24)==1) return (1);

return (0);

}

int f0_21(string as_0) {

int li_40;

int li_8 = 0;

int li_12 = StringLen(as_0);

int li_20 = 1;

string ls_24 = "";

gi_188 = 100;

for (int li_32 = 0; li_32 <= li_12; li_32++) {

li_8 = StringGetChar(as_0, li_32);

if (li_8 != ';' && li_32 != li_12) ls_24 = ls_24 + CharToStr(li_8);

else {

switch (li_20) {

case 1:

gi_152 = StrToInteger(ls_24);

if (gi_152 < 1000) return (0);

break;

case 2:

gi_156 = StrToTime(ls_24);

break;

case 3:

gi_168 = StrToInteger(StringSubstr(ls_24, 0, 1));

break;

case 4:

gd_244 = StrToDouble(ls_24);

break;

case 5:

gs_204 = ls_24;

break;

case 6:

gd_252 = StrToDouble(ls_24);

break;

case 7:

gd_260 = StrToDouble(ls_24);

break;

case 8:

gd_268 = StrToDouble(ls_24);

break;

case 9:

if (ls_24 != "Open") gi_160 = StrToTime(ls_24);

else gi_160 = -1;

break;

case 10:

if (ls_24 != "-") gi_164 = StrToTime(ls_24);

else gi_164 = -1;

break;

case 11:

gd_276 = StrToDouble(ls_24);

break;

case 12:

gs_212 = ls_24;

}

if (li_20 >= 12) break;

li_20++;

ls_24 = "";

}

}

if (gi_160 < 0 && gi_164 < 0) gi_144 = 1;

if (gi_160 < 0 && gi_164 > 0) gi_144 = 2;

if (gi_160 > 0 && gd_276 > 0.0) {

gi_144 = 3;

li_40 = StringFind(gs_212, "_part:");

if (li_40 > 0) gi_188 = StrToInteger(StringSubstr(gs_212, li_40 + 6, 2));

}

li_40 = StringFind(gs_212, "from");

if (li_40 >= 0) {

gi_152 = StrToInteger(StringSubstr(gs_212, li_40 + 6));

if (gi_144 == 1) return (0);

}

if (MarketInfo(gs_124 + gs_204 + gs_132, MODE_BID) > 0.0) gs_204 = gs_124 + gs_204 + gs_132;

if (MarketInfo(gs_204, MODE_BID) > 0.0) return (1);

if (GetLastError() == 4106/* UNKNOWN_SYMBOL */) {

if (StringLen(gs_204) > 6) gs_204 = StringSubstr(gs_204, 0, 6);

if (gs_132 != "" && MarketInfo(gs_204 + gs_132, MODE_BID) > 0.0) {

gs_204 = gs_204 + gs_132;

return (1);

}

if (gs_124 != "" && MarketInfo(gs_124 + gs_204, MODE_BID) > 0.0) {

gs_204 = gs_132 + gs_204;

return (1);

}

if (gs_132 == "" && MarketInfo(gs_204, MODE_BID) > 0.0) return (1);

Print("no ", gs_204);

return (0);

}

return (1);

}

int f0_11() {

bool li_0 = FALSE;

double ld_4 = MarketInfo(gs_204, MODE_ASK);

double ld_12 = MarketInfo(gs_204, MODE_BID);

double ld_20 = MarketInfo(gs_204, MODE_STOPLEVEL);

double ld_28 = MarketInfo(gs_204, MODE_POINT);

if (gi_168 == 0 || gi_168 == 2 || gi_168 == 4) {

if (ld_12 - gd_260 < ld_20 * ld_28) {

gd_260 = ld_12 - (ld_20 + gi_184) * ld_28;

li_0 = TRUE;

}

if (MathAbs(gd_268 - ld_4) < ld_20 * ld_28) {

gd_268 = ld_4 + (ld_20 + gi_184) * ld_28;

li_0 = TRUE;

}

}

if (gi_168 == 1 || gi_168 == 3 || gi_168 == 5) {

if (gd_260 - ld_4 < ld_20 * ld_28) {

gd_260 = ld_4 + (ld_20 + gi_184) * ld_28;

li_0 = TRUE;

}

if (MathAbs(ld_12 - gd_268) < ld_20 * ld_28) {

gd_268 = ld_12 - (ld_20 + gi_184) * ld_28;

li_0 = TRUE;

}

}

if (li_0 == TRUE) return (0);

return (1);

}

string f0_12(string as_0, int ai_8 = 0) {

int li_12 = _lopen(as_0, 0);

if (li_12 < 0) {

Print("Rdo");

return ("");

}

int li_16 = _llseek(li_12, ai_8, 0);

if (li_16 < 0) {

Print("Rds");

return ("");

}

string ls_20 = "";

string ls_28 = "x";

int li_36 = 0;

for (li_16 = _lread(li_12, ls_28, 1); li_16 > 0; li_16 = _lread(li_12, ls_28, 1)) {

ls_20 = ls_20 + ls_28;

ls_28 = "x";

li_36++;

}

li_16 = _lclose(li_12);

if (li_16 < 0) Print("RdC");

return (ls_20);

}

void f0_0(string as_0, string as_8 = "") {

int li_16 = StringLen(as_8);

int li_24 = _lopen(as_0, 1);

if (li_24 < 0) {

li_24 = _lcreat(as_0, 0);

if (li_24 < 0) {

Print("cr");

return;

}

}

int li_20 = _lclose(li_24);

li_24 = _lopen(as_0, 1);

if (li_24 < 0) {

Print("Wro");

return;

}

li_20 = _llseek(li_24, 0, 0);

if (li_20 < 0) {

Print("Wrs");

return;

}

li_20 = _lwrite(li_24, as_8, li_16);

if (li_20 < 0) Print("Wre");

li_20 = _lclose(li_24);

if (li_20 < 0) Print("Wrc");

}

void f0_19(int ai_0 = 100) {

int li_4 = OrdersTotal();

for (int li_8 = 0; li_8 < li_4; li_8++) {

if (OrderSelect(li_8, SELECT_BY_POS, MODE_TRADES)) {

if (OrderComment() == "YPM" && OrderProfit() >= gi_184 * ai_0 * OrderLots() * MarketInfo(OrderSymbol(), MODE_TICKVALUE)) {

if (OrderType() == OP_BUY && OrderStopLoss() < OrderOpenPrice() + gi_184 * MarketInfo(OrderSymbol(), MODE_POINT)) {

OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() + gi_184 * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), 0);

continue;

}

if (OrderType() == OP_SELL && OrderStopLoss() == 0.0 || OrderStopLoss() > OrderOpenPrice() - gi_184 * MarketInfo(OrderSymbol(), MODE_POINT)) OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() - gi_184 * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), 0);

}

}

}

}

int f0_2() {

double ld_8;

double ld_16;

double ld_24;

int li_0 = FileOpenHistory(gs_328, FILE_BIN|FILE_READ);

gi_288 = (FileSize(li_0) - 148) / 44;

ArrayResize(gia_308, gi_288);

ArrayResize(gda_320, gi_288);

ArrayResize(gda_324, gi_288);

FileSeek(li_0, 148, SEEK_SET);

for (int li_4 = 0; li_4 < gi_288; li_4++) {

gia_308[li_4] = FileReadInteger(li_0, LONG_VALUE);

ld_8 = FileReadDouble(li_0, DOUBLE_VALUE);

gda_324[li_4] = FileReadDouble(li_0, DOUBLE_VALUE);

gda_320[li_4] = FileReadDouble(li_0, DOUBLE_VALUE);

ld_16 = FileReadDouble(li_0, DOUBLE_VALUE);

ld_24 = FileReadDouble(li_0, DOUBLE_VALUE);

if (GetLastError() == 4099/* END_OF_FILE */) break;

}

FileClose(li_0);

return (0);

}

int f0_4() {

if (gs_328 != Symbol() + Period() + ".hst") {

gs_328 = Symbol() + Period() + ".hst";

f0_2();

gi_296 = 0;

}

int li_0 = 10;

int li_4 = Period();

if (li_4 < PERIOD_D1 && li_4 > 0) li_0 = NormalizeDouble(li_0 * MathLog(4320 / li_4), 0);

for (int li_8 = gi_296; li_8 < gi_288; li_8++) {

if (gia_308[li_8] >= Time[0]) {

gi_296 = li_8;

break;

}

}

int li_12 = ArrayMaximum(gda_320, 2 * li_0, MathMax(gi_296 - li_0, 0));

int li_16 = ArrayMinimum(gda_324, li_0 * 2, MathMax(gi_296 - li_0, 0));

if (gi_296 == li_12 + 1 && gi_296 < gi_288 - 3) {

gi_284 = -1;

return (-1);

}

if (gi_296 == li_16 + 1 && gi_296 < gi_288 - 3) {

gi_284 = 1;

return (1);

}

return (0);

}

int f0_1(int ai_0 = 0) {

gi_300 = 0;

gi_304 = 0;

for (int li_4 = OrdersTotal(); li_4 >= 0; li_4--) {

if (OrderSelect(li_4, SELECT_BY_POS, MODE_TRADES)) {

if (OrderSymbol() == Symbol() && OrderMagicNumber() == gi_316) {

if (OrderType() == OP_BUY) {

gi_300++;

if (ai_0 != -1) continue;

OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3);

continue;

}

if (OrderType() == OP_SELL) {

gi_304++;

if (ai_0 != 1) continue;

OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3);

continue;

}

}

}

if (GetLastError() > 0/* NO_ERROR */) return (-1);

}

return (gi_300 + gi_304);

}

CADA TICK /OPEN PRICE- Poner en Open Price:Se añade lo verde

datetime prevtime=0;

//--------------------------------------------------------------------

int init()

//--------------------------------------------------------------------

int start()

{

if(prevtime == Time[0]) return(0);

prevtime = Time[0];

//+--------------------------------------------------------------------------------------+

//| This MQL is generated by Expert Advisor Builder |

//| http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/ |

//| |

//| In no event will author be liable for any damages whatsoever. |

//| Use at your own risk. |

//| |

//+------------------- DO NOT REMOVE THIS HEADER ---------------------------+

#define SIGNAL_NONE 0

#define SIGNAL_BUY 1

#define SIGNAL_SELL 2

#define SIGNAL_CLOSEBUY 3

#define SIGNAL_CLOSESELL 4

#property copyright "Expert Advisor Builder"

#property link "http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/"

extern int MagicNumber = 0;

extern bool SignalMail = False;

extern bool EachTickMode = False;

extern double Lots = 1.0;

extern int Slippage = 3;

extern bool UseStopLoss = False;

extern int StopLoss = 30;

extern bool UseTakeProfit = False;

extern int TakeProfit = 60;

extern bool UseTrailingStop = False;

extern int TrailingStop = 30;

extern int Period1 = 141;

extern int Period2 = 440;

extern int Method1 = 1;

extern int Method2 = 2;

extern int max_trade = 1;

int BarCount;

int Current;

bool TickCheck = False;

//+------------------------------------------------------------------+

//| expert initialization function |

//+------------------------------------------------------------------+

int init() {

BarCount = Bars;

if (EachTickMode) Current = 0; else Current = 1;

return(0);

}

//+------------------------------------------------------------------+

//| expert deinitialization function |

//+------------------------------------------------------------------+

int deinit() {

return(0);

}

//+------------------------------------------------------------------+

//| expert start function |

//+------------------------------------------------------------------+

int start() {

int Order = SIGNAL_NONE;

int Total, Ticket;

double StopLossLevel, TakeProfitLevel;

if (EachTickMode && Bars != BarCount) TickCheck = False;

Total = OrdersTotal();

Order = SIGNAL_NONE;

//+------------------------------------------------------------------+

//| Variable Begin |

//+------------------------------------------------------------------+

double Buy1_1 = iMA(NULL, 0, Period1, 0, Method1, PRICE_CLOSE, Current + 0);

double Buy1_2 = iMA(NULL, 0, Period2, 0, Method2, PRICE_CLOSE, Current + 0);

double Buy2_1 = iMA(NULL, 0, Period1, 0, Method1, PRICE_CLOSE, Current + 1);

double Buy2_2 = iMA(NULL, 0, Period2, 0, Method2, PRICE_CLOSE, Current + 1);

double Sell1_1 = iMA(NULL, 0, Period1, 0, Method1, PRICE_CLOSE, Current + 0);

double Sell1_2 = iMA(NULL, 0, Period2, 0, Method2, PRICE_CLOSE, Current + 0);

double Sell2_1 = iMA(NULL, 0, Period1, 0, Method1, PRICE_CLOSE, Current + 1);

double Sell2_2 = iMA(NULL, 0, Period2, 0, Method2, PRICE_CLOSE, Current + 1);

double CloseBuy1_1 = iMA(NULL, 0, Period1, 0, Method1, PRICE_CLOSE, Current +

0);

double CloseBuy1_2 = iMA(NULL, 0, Period2, 0, Method2, PRICE_CLOSE, Current +

0);

double CloseBuy2_1 = iMA(NULL, 0, Period1, 0, Method1, PRICE_CLOSE, Current +

1);

double CloseBuy2_2 = iMA(NULL, 0, Period2, 0, Method2, PRICE_CLOSE, Current +

1);

double CloseSell1_1 = iMA(NULL, 0, Period1, 0, Method1, PRICE_CLOSE, Current +

0);

double CloseSell1_2 = iMA(NULL, 0, Period2, 0, Method2, PRICE_CLOSE, Current +

0);

double CloseSell2_1 = iMA(NULL, 0, Period1, 0, Method1, PRICE_CLOSE, Current +

1);

double CloseSell2_2 = iMA(NULL, 0, Period2, 0, Method2, PRICE_CLOSE, Current +

1);

//+------------------------------------------------------------------+

//| Variable End |

//+------------------------------------------------------------------+

//Check position

bool IsTrade = False;

for (int i = max_trade-1; i < Total; i ++) {

OrderSelect(i, SELECT_BY_POS, MODE_TRADES);

if(OrderType() <= OP_SELL && OrderSymbol() == Symbol()) {

IsTrade = True;

if(OrderType() == OP_BUY) {

//Close

//+------------------------------------------------------------------+

//| Signal Begin(Exit Buy) |

//+------------------------------------------------------------------+

if (CloseBuy1_1 > CloseBuy1_2 && CloseBuy2_1 < CloseBuy2_2) Order =

SIGNAL_CLOSEBUY;

//+------------------------------------------------------------------+

//| Signal End(Exit Buy) |

//+------------------------------------------------------------------+

if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!

EachTickMode && (Bars != BarCount)))) {

OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen);

if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid,

Digits) + " Close Buy");

if (!EachTickMode) BarCount = Bars;

IsTrade = False;

continue;

}

//Trailing stop

if(UseTrailingStop && TrailingStop > 0) {

if(Bid - OrderOpenPrice() > Point * TrailingStop) {

if(OrderStopLoss() < Bid - Point * TrailingStop) {

OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop,

OrderTakeProfit(), 0, MediumSeaGreen);

if (!EachTickMode) BarCount = Bars;

continue;

}

}

}

} else {

//Close

//+------------------------------------------------------------------+

//| Signal Begin(Exit Sell) |

//+------------------------------------------------------------------+

if (CloseSell1_1 < CloseSell1_2 && CloseSell2_1 > CloseSell2_2) Order =

SIGNAL_CLOSESELL;

//+------------------------------------------------------------------+

//| Signal End(Exit Sell) |

//+------------------------------------------------------------------+

if (Order == SIGNAL_CLOSESELL && ((EachTickMode && !TickCheck) || (!

EachTickMode && (Bars != BarCount)))) {

OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, DarkOrange);

if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask,

Digits) + " Close Sell");

if (!EachTickMode) BarCount = Bars;

IsTrade = False;

continue;

}

//Trailing stop

if(UseTrailingStop && TrailingStop > 0) {

if((OrderOpenPrice() - Ask) > (Point * TrailingStop)) {

if((OrderStopLoss() > (Ask + Point * TrailingStop)) || (OrderStopLoss() == 0)) {

OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Point * TrailingStop,

OrderTakeProfit(), 0, DarkOrange);

if (!EachTickMode) BarCount = Bars;

continue;

}

}

}

}

}

}

//+------------------------------------------------------------------+

//| Signal Begin(Entry) |

//+------------------------------------------------------------------+

if (Buy1_1 < Buy1_2 && Buy2_1 > Buy2_2) Order = SIGNAL_BUY;

if (Sell1_1 > Sell1_2 && Sell2_1 < Sell2_2) Order = SIGNAL_SELL;

//+------------------------------------------------------------------+

//| Signal End |

//+------------------------------------------------------------------+

//Buy

if (Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode &&

(Bars != BarCount)))) {

if(!IsTrade) {

//Check free margin

if (AccountFreeMargin() < (1000 * Lots)) {

Print("We have no money. Free Margin = ", AccountFreeMargin());

return(0);

}

if (UseStopLoss) StopLossLevel = Ask - StopLoss * Point; else StopLossLevel = 0.0;

if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; else TakeProfitLevel =

0.0;

Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, StopLossLevel,

TakeProfitLevel, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);

if(Ticket > 0) {

if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {

Print("BUY order opened : ", OrderOpenPrice());

if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask,

Digits) + " Open Buy");

} else {

Print("Error opening BUY order : ", GetLastError());

}

}

if (EachTickMode) TickCheck = True;

if (!EachTickMode) BarCount = Bars;

return(0);

}

}

//Sell

if (Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode &&

(Bars != BarCount)))) {

if(!IsTrade) {

//Check free margin

if (AccountFreeMargin() < (1000 * Lots)) {

Print("We have no money. Free Margin = ", AccountFreeMargin());

return(0);

}

if (UseStopLoss) StopLossLevel = Bid + StopLoss * Point; else StopLossLevel = 0.0;

if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point; else TakeProfitLevel =

0.0;

Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel,

TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);

if(Ticket > 0) {

if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {

Print("SELL order opened : ", OrderOpenPrice());

if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid,

Digits) + " Open Sell");

} else {

Print("Error opening SELL order : ", GetLastError());

}

}

if (EachTickMode) TickCheck = True;

if (!EachTickMode) BarCount = Bars;

return(0);

}

}

if (!EachTickMode) BarCount = Bars;

return(0);

}

//+------------------------------------------------------------------+

EXTERNALIZAR

Poner extern delante de la variable que queramos poner como parámetro externo. Las variables externas van antes de int init.

CRUCE ALCISTA/BAJISTA

- Compra con cruce alcista de SMA 10 a SMA 20 y venta a la inversa. No abre una operación (p.e. compra) si otra de la misma naturaleza (p.e. compra) está abierta y no se ha cerrado (IfOrderDoesNotExist).//-------------------------------------------------------------// Etasoft Inc. Forex EA and Script Generator version 4.4 EA//-------------------------------------------------------------// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "Copyright © 2011, Etasoft Inc. Forex EA Generator v4.4"#property link "http://www.forexgenerator.com/"

#include <stdlib.mqh>#include <WinUser32.mqh>

// exported variablesextern double BuyLots11 = 0.1;extern int BuyStoploss11 = 20;extern int BuyTakeprofit11 = 30;extern double SellLots15 = 0.1;extern int SellStoploss15 = 20;extern int SellTakeprofit15 = 30;

// local variablesdouble PipValue=1; // this variable is here to support 5-digit brokersbool Terminated = false;string LF = "\n"; // use this in custom or utility blocks where you need line feedsint NDigits = 4; // used mostly for NormalizeDouble in Flex type blocksint ObjCount = 0; // count of all objects created on the chart, allows creation of objects with unique namesint current = 0;

int init(){ NDigits = Digits; if (false) ObjectsDeleteAll(); // clear the chart Comment(""); // clear the chart}

// Expert startint start(){ if (Bars < 10) { Comment("Not enough bars"); return (0); } if (Terminated == true) { Comment("EA Terminated."); return (0); } OnEveryTick1(); }

void OnEveryTick1(){ if (true == false && true) PipValue = 10; if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10; TechnicalAnalysis2x9(); TechnicalAnalysis2x12(); }

void TechnicalAnalysis2x9(){ if ((iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,1) < iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,1)) && (iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,0) > iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,0))) { IfOrderDoesNotExist10(); }}

void IfOrderDoesNotExist10()

{ bool exists = false; for (int i=OrdersTotal()-1; i >= 0; i--) if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderType() == OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == 1) { exists = true; } } else { Print("OrderSelect() error - ", ErrorDescription(GetLastError())); } if (exists == false) { BuyOrder11(); }}

void BuyOrder11(){ double SL = Ask - BuyStoploss11*PipValue*Point; if (BuyStoploss11 == 0) SL = 0; double TP = Ask + BuyTakeprofit11*PipValue*Point; if (BuyTakeprofit11 == 0) TP = 0; int ticket = -1; if (true) ticket = OrderSend(Symbol(), OP_BUY, BuyLots11, Ask, 4, 0, 0, "My Expert", 1, 0, Blue); else ticket = OrderSend(Symbol(), OP_BUY, BuyLots11, Ask, 4, SL, TP, "My Expert", 1, 0, Blue); if (ticket > -1) { if (true) { OrderSelect(ticket, SELECT_BY_TICKET); bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Blue); if (ret == false) Print("OrderModify() error - ", ErrorDescription(GetLastError())); } } else { Print("OrderSend() error - ", ErrorDescription(GetLastError())); }}

void TechnicalAnalysis2x12(){ if ((iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,1) > iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,1)) && (iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,0) < iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,0))) { IfOrderDoesNotExist8(); }}

void IfOrderDoesNotExist8(){ bool exists = false; for (int i=OrdersTotal()-1; i >= 0; i--) if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == 1) { exists = true; } } else { Print("OrderSelect() error - ", ErrorDescription(GetLastError())); } if (exists == false) { SellOrder15(); }}

void SellOrder15(){ double SL = Bid + SellStoploss15*PipValue*Point; if (SellStoploss15 == 0) SL = 0; double TP = Bid - SellTakeprofit15*PipValue*Point; if (SellTakeprofit15 == 0) TP = 0; int ticket = -1; if (true) ticket = OrderSend(Symbol(), OP_SELL, SellLots15, Bid, 4, 0, 0, "My Expert", 1, 0, Red); else ticket = OrderSend(Symbol(), OP_SELL, SellLots15, Bid, 4, SL, TP, "My Expert", 1, 0, Red); if (ticket > -1) { if (true) { OrderSelect(ticket, SELECT_BY_TICKET);

bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Red); if (ret == false) Print("OrderModify() error - ", ErrorDescription(GetLastError())); } } else { Print("OrderSend() error - ", ErrorDescription(GetLastError())); }}

int deinit(){ if (false) ObjectsDeleteAll(); }- Compra con cruce alcista del RSI sobre 30 y venta con cruce bajista del RSI sobre 70. No abre una operación (p.e. compra) si otra de la misma naturaleza (p.e. compra) está abierta y no se ha cerrado (IfOrderDoesNotExist).//-------------------------------------------------------------// Etasoft Inc. Forex EA and Script Generator version 4.4 EA//-------------------------------------------------------------// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "Copyright © 2011, Etasoft Inc. Forex EA Generator v4.4"#property link "http://www.forexgenerator.com/"

#include <stdlib.mqh>#include <WinUser32.mqh>

// exported variablesextern double BuyLots11 = 0.1;extern int BuyStoploss11 = 20;extern int BuyTakeprofit11 = 30;extern double SellLots15 = 0.1;extern int SellStoploss15 = 20;extern int SellTakeprofit15 = 30;

// local variablesdouble PipValue=1; // this variable is here to support 5-digit brokersbool Terminated = false;string LF = "\n"; // use this in custom or utility blocks where you need line feedsint NDigits = 4; // used mostly for NormalizeDouble in Flex type blocksint ObjCount = 0; // count of all objects created on the chart, allows creation of objects with unique names

int current = 0;

int init(){ NDigits = Digits; if (false) ObjectsDeleteAll(); // clear the chart Comment(""); // clear the chart}

// Expert startint start(){ if (Bars < 10) { Comment("Not enough bars"); return (0); } if (Terminated == true) { Comment("EA Terminated."); return (0); } OnEveryTick1(); }

void OnEveryTick1(){ if (true == false && true) PipValue = 10; if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10; TechnicalAnalysis2x2(); TechnicalAnalysis2x3(); }

void TechnicalAnalysis2x2(){ if ((iRSI(NULL, NULL,14,PRICE_CLOSE,1) < 30) && (iRSI(NULL, NULL,14,PRICE_CLOSE,0) > 30)) { IfOrderDoesNotExist10(); }}

void IfOrderDoesNotExist10(){

bool exists = false; for (int i=OrdersTotal()-1; i >= 0; i--) if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderType() == OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == 1) { exists = true; } } else { Print("OrderSelect() error - ", ErrorDescription(GetLastError())); } if (exists == false) { BuyOrder11(); }}

void BuyOrder11(){ double SL = Ask - BuyStoploss11*PipValue*Point; if (BuyStoploss11 == 0) SL = 0; double TP = Ask + BuyTakeprofit11*PipValue*Point; if (BuyTakeprofit11 == 0) TP = 0; int ticket = -1; if (true) ticket = OrderSend(Symbol(), OP_BUY, BuyLots11, Ask, 4, 0, 0, "My Expert", 1, 0, Blue); else ticket = OrderSend(Symbol(), OP_BUY, BuyLots11, Ask, 4, SL, TP, "My Expert", 1, 0, Blue); if (ticket > -1) { if (true) { OrderSelect(ticket, SELECT_BY_TICKET); bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Blue); if (ret == false) Print("OrderModify() error - ", ErrorDescription(GetLastError())); } } else { Print("OrderSend() error - ", ErrorDescription(GetLastError())); }}

void TechnicalAnalysis2x3()

{ if ((iRSI(NULL, NULL,14,PRICE_CLOSE,1) > 70) && (iRSI(NULL, NULL,14,PRICE_CLOSE,0) < 70)) { IfOrderDoesNotExist8(); }}

void IfOrderDoesNotExist8(){ bool exists = false; for (int i=OrdersTotal()-1; i >= 0; i--) if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == 1) { exists = true; } } else { Print("OrderSelect() error - ", ErrorDescription(GetLastError())); } if (exists == false) { SellOrder15(); }}

void SellOrder15(){ double SL = Bid + SellStoploss15*PipValue*Point; if (SellStoploss15 == 0) SL = 0; double TP = Bid - SellTakeprofit15*PipValue*Point; if (SellTakeprofit15 == 0) TP = 0; int ticket = -1; if (true) ticket = OrderSend(Symbol(), OP_SELL, SellLots15, Bid, 4, 0, 0, "My Expert", 1, 0, Red); else ticket = OrderSend(Symbol(), OP_SELL, SellLots15, Bid, 4, SL, TP, "My Expert", 1, 0, Red); if (ticket > -1) { if (true) { OrderSelect(ticket, SELECT_BY_TICKET); bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Red); if (ret == false)

Print("OrderModify() error - ", ErrorDescription(GetLastError())); } } else { Print("OrderSend() error - ", ErrorDescription(GetLastError())); }}

int deinit(){ if (false) ObjectsDeleteAll(); }

- CRUCE DE LINEAS

int Crossed (double line1 , double line2)

{

static int last_direction = 0;

static int current_dirction = 0;

if(line1>line2)current_dirction = 1; //up

if(line1<line2)current_dirction = 2; //down

if(current_dirction != last_direction) //changed

{

last_direction = current_dirction;

return (last_direction);

}

else

{

return (0);

}

}

Vigila el cruce de las lineas de de la EMA corta y la EMA larga.

Para este objetivo hemos creado la función Crossed.

La función Crossed toma dos valores double como parámetros y devuelve un integer.

El primer parámetro es el valor de la primera línea que queremos monitorizar (la EMA corta en

nuestro caso) y el segundo parámetro es el valor de la segunda (la EMA larga).

La función supervisará las dos líneas cada vez que la llamamos guardando la dirección de las

dos líneas en las variables static para recordar su estado entre las llamadas repetidas.

• Devolverá 0 si ningún cambio ha ocurrido en las últimas direcciones guardadas.

• Devolverá 1 si la dirección ha cambiado (las líneas se cruzaron) y la primera línea está por

encima de la segunda línea.

• Devolverá 2 si la dirección ha cambiado (las líneas se cruzaron) y la primera línea está por

debajo de la segunda línea.

Vamos a ver cómo lo escribimos

int Crossed (double line1 , double line2)

La línea anterior es la declaración de la función, esto significa que queremos crear la función

Crossed que tiene dos parámetros de tipo double y devuelve un integer.

Cuando llamas a esta función tienes que pasarle dos parámetros double y te devolverá un

integer.

Tienes que declarar la función antes de usarla (llamarla). El lugar de la función no importa, yo

lo coloqué encima de la función start (), pero puedes colocarla en cualquier otro sitio.

static int last_direction = 0;static int current_direction = 0;

Aquí hemos declarado dos integers estáticos para mantener la actual y la última dirección de

las dos líneas. Vamos a utilizar estas variables (que son variables estáticas lo que significa que

guardarán sus valores entre las repetidas llamadas) para comprobar si hay un cambio en la

dirección de las líneas o no.

Las hemos inicializado en 0, porque no queremos que trabajen en la primera llamada a la

función (si trabajaran en la primera llamada el asesor experto se abrirá una orden tan pronto

lo cargaramos en el terminal).

if(current_direction != last_direction) //changedEn esta línea se comparan las dos variables estáticas para comprobar los cambios entre la

última llamada de nuestra función y la actual llamada.

Si last_direction no es igual a current_direction eso significa que hay un cambio ha ocurrido en

la dirección.

last_direction = current_direction;return (last_direction);

En este caso (last_direction no igual que current_direction) que tenemos que restablecer

nuestra last_direction asignándole el valor de la current_direction.

Y devolveremos el valor de la last_direction. Este valor será 1 si la primera línea está por

encima de la segunda línea y 2 si la primera línea está por debajo de la segunda línea.

else{

return (0);}

Si no (last_direction es igual a current_directio) no hay ningún cambio en la dirección de las

líneas y tenemos que devolver 0.

Nuestro programa llamará a esta función en el cuerpo de su función start() y utiliza el valor

devuelto para determinar la acción apropiada.

SUBIDA O BAJADA DE X PIPSIfGap de FEAG://-------------------------------------------------------------// Etasoft Inc. Forex EA and Script Generator version 4.5 EA//-------------------------------------------------------------// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "Copyright © 2012, Etasoft Inc. Forex EA Generator v4.5"#property link "http://www.forexgenerator.com/"

#include <stdlib.mqh>#include <WinUser32.mqh>

// exported variablesextern int Gap1 = 40;

// local variablesdouble PipValue=1; // this variable is here to support 5-digit brokersbool Terminated = false;string LF = "\n"; // use this in custom or utility blocks where you need line feedsint NDigits = 4; // used mostly for NormalizeDouble in Flex type blocksint ObjCount = 0; // count of all objects created on the chart, allows creation of objects with unique namesint current = 0;

datetime BarTime2 = 0;

int init(){ NDigits = Digits; if (false) ObjectsDeleteAll(); // clear the chart Comment(""); // clear the chart}

// Expert startint start(){

if (Bars < 10) { Comment("Not enough bars"); return (0); } if (Terminated == true) { Comment("EA Terminated."); return (0); } OnEveryNewBar2(); }

void OnEveryNewBar2(){ if (true == false && false) PipValue = 10; if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10; if (BarTime2 < Time[0]) { // we have a new bar opened BarTime2 = Time[0]; // keep the new bar open time IfGap1(); }}

void IfGap1(){ for (int i=OrdersTotal()-1; i >= 0; i--) if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderSymbol() == Symbol() && OrderMagicNumber() == 1) { if ((Gap1 < 0 && ((OrderType() == OP_BUY && Ask - OrderOpenPrice() < Gap1*PipValue*Point) || (OrderType() == OP_SELL && OrderOpenPrice() - Bid < Gap1*PipValue*Point))) || ((Gap1 > 0 && ((OrderType() == OP_BUY && Ask - OrderOpenPrice() > Gap1*PipValue*Point) || (OrderType() == OP_SELL && OrderOpenPrice() - Bid > Gap1*PipValue*Point))))) { } } } else Print("OrderSelect() error - ", ErrorDescription(GetLastError())); }

int deinit(){ if (false) ObjectsDeleteAll(); }

TRADING ALCISTATradeUp en FEAG://-------------------------------------------------------------// Etasoft Inc. Forex EA and Script Generator version 4.5 EA//-------------------------------------------------------------// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "Copyright © 2012, Etasoft Inc. Forex EA Generator v4.5"#property link "http://www.forexgenerator.com/"

#include <stdlib.mqh>#include <WinUser32.mqh>

// exported variablesextern int NewStopLoss1 = 20;extern int NewTakeProfit1 = 30;extern int TradeUpPoint1 = 20;extern double Lots1 = 0.1;

// local variablesdouble PipValue=1; // this variable is here to support 5-digit brokersbool Terminated = false;string LF = "\n"; // use this in custom or utility blocks where you need line feedsint NDigits = 4; // used mostly for NormalizeDouble in Flex type blocksint ObjCount = 0; // count of all objects created on the chart, allows creation of objects with unique namesint current = 0;

datetime BarTime2 = 0;int LastTradeUpTicket1 = -1;

int init(){ NDigits = Digits; if (false) ObjectsDeleteAll(); // clear the chart Comment(""); // clear the chart}

// Expert startint start(){ if (Bars < 10) { Comment("Not enough bars"); return (0); } if (Terminated == true) { Comment("EA Terminated."); return (0); } OnEveryNewBar2(); }

void OnEveryNewBar2(){ if (true == false && false) PipValue = 10; if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10; if (BarTime2 < Time[0]) { // we have a new bar opened BarTime2 = Time[0]; // keep the new bar open time TradeUp1(); }}

void TradeUp1(){ bool exists = false; if (LastTradeUpTicket1 != -1) { for (int j=OrdersTotal()-1; j >= 0; j--) if (OrderSelect(j, SELECT_BY_POS, MODE_TRADES)) { if (OrderTicket() == LastTradeUpTicket1) { exists = true; } } else { Print("OrderSelect() error - ", ErrorDescription(GetLastError())); } } if (exists == false) LastTradeUpTicket1 = -1; // reset Ticket Id so trade-up would be possible double takeprofit = 0; double stoploss = 0;

for (int i=OrdersTotal()-1; i >= 0; i--) if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderSymbol() == Symbol() && OrderMagicNumber() == 1 && LastTradeUpTicket1 == -1) { if (OrderType() == OP_BUY && Ask - OrderOpenPrice() > TradeUpPoint1*PipValue*Point) { takeprofit = Ask+NewTakeProfit1*PipValue*Point; if (NewTakeProfit1 == 0) takeprofit = OrderTakeProfit(); stoploss = Ask-NewStopLoss1*PipValue*Point; if (NewStopLoss1 == 0) stoploss = OrderStopLoss(); LastTradeUpTicket1 = OrderTicket(); int ticket = -1; if (true) ticket = OrderSend(Symbol(), OP_BUY, Lots1, Ask, 4, 0, 0, "My Expert", 1, 0, White); else ticket = OrderSend(Symbol(), OP_BUY, Lots1, Ask, 4, stoploss, takeprofit, "My Expert", 1, 0, White); if (ticket > -1) { if (true) { OrderSelect(ticket, SELECT_BY_TICKET); bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), stoploss, takeprofit, 0, White); if (ret == false) Print("OrderModify() error - ", ErrorDescription(GetLastError())); } } } if (OrderType() == OP_SELL && OrderOpenPrice() - Bid > TradeUpPoint1*PipValue*Point) { takeprofit = Bid-NewTakeProfit1*PipValue*Point; if (NewTakeProfit1 == 0) takeprofit = OrderTakeProfit(); stoploss = Bid+NewStopLoss1*PipValue*Point; if (NewStopLoss1 == 0) stoploss = OrderStopLoss(); LastTradeUpTicket1 = OrderTicket(); int ticket2 = -1; if (true)

ticket2 = OrderSend(Symbol(), OP_SELL, Lots1, Bid, 4, 0, 0, "My Expert", 1, 0, White); else ticket2 = OrderSend(Symbol(), OP_SELL, Lots1, Bid, 4, stoploss, takeprofit, "My Expert", 1, 0, White); if (ticket2 > -1) { if (true) { OrderSelect(ticket2, SELECT_BY_TICKET); bool ret4 = OrderModify(OrderTicket(), OrderOpenPrice(), stoploss, takeprofit, 0, White); if (ret4 == false) Print("OrderModify() error - ", ErrorDescription(GetLastError())); } } } } } else Print("OrderSelect() error - ", ErrorDescription(GetLastError())); }

int deinit(){ if (false) ObjectsDeleteAll(); }

PASAR EA DE 4 A 5 DÍGITOSEn primer lugar en la parte superior de su EA, justo debajo de las declaraciones de variables externas, poner esta línea ...double dXPoint = 1;Luego, en la función init agrega lo siguiente ...if(Digits == 3 || Digits == 5) { dXPoint = 10; }Buscar todas las ocurrencias de la variable "Point" en el código (Ctrl-F, introduzca "point" - sin comillas - y luego F3 para avanzar). Normalmente estarán en las variables TakeProfit o StopLoss.Entonces, en lugar de, por ejemplo ...TakeProfit * Point;... cambialo a ...(TakeProfit * dXPoint) * Point;Los paréntesis/llaves son muy importantes, así que no los deje fuera.

Una vez que hayas hecho esto te irá bien para la mayor parte de los EAs, pero algunos utilizarán spreads variables de los brókers dentro del código. Puede aparecer así ...double dSpread = MarketInfo(Symbol(), MODE_SPREAD);... cámbialo a ...double dSpread = MarketInfo(Symbol(), MODE_SPREAD) / dXPoint;La otra cosa a tener en cuenta es la variable slipagge. Ahora usted puede cambiarla manualmente mediante, por ejemplo, el cambio de 3 a 300, o puede hacer que esto ocurra automáticamente. Si usted quiere que sea automático sólo cambie lo que ha añadido a la función init para algo parecido a esto ...if(Digits == 3 || Digits == 5) { dXPoint = 10; Slipagge = Slipagge * dXPoint; }¡Eso es!Su EA ahora debe ser compatible con los bróekers de ambos 4 y 5 decimales.PS: Recuerde hacer siempre una copia de seguridad de su EA antes de comenzar a editar el código.

CAMBIO DE LOTE A MICROLOTE

//-------------------------------------------------------------

// Etasoft Inc. Forex EA and Script Generator version 4.5 EA

//-------------------------------------------------------------

// Keywords: MT4, Forex EA builder, create EA, expert advisor developer

#property copyright "Copyright © 2012, Etasoft Inc. Forex EA Generator v4.5"

#property link "http://www.forexgenerator.com/"

#include <stdlib.mqh>

#include <WinUser32.mqh>

// exported variables

extern int BuyStoploss4 = 20;

extern int BuyTakeprofit4 = 30;

extern double BalanceRiskPercent4 = 2;

extern int SellStoploss6 = 20;

extern int SellTakeprofit6 = 30;

extern double BalanceRiskPercent6 = 2;

// local variables

double PipValue=1; // this variable is here to support 5-digit brokers

bool Terminated = false;

string LF = "\n"; // use this in custom or utility blocks where you need line feeds

int NDigits = 4; // used mostly for NormalizeDouble in Flex type blocks

int ObjCount = 0; // count of all objects created on the chart, allows creation of objects with unique names

int current = 0;

int init()

{

NDigits = Digits;

if (false) ObjectsDeleteAll(); // clear the chart

Comment(""); // clear the chart

}

// Expert start

int start()

{

if (Bars < 10)

{

Comment("Not enough bars");

return (0);

}

if (Terminated == true)

{

Comment("EA Terminated.");

return (0);

}

OnEveryTick1();

}

void OnEveryTick1()

{

if (true == false && true) PipValue = 10;

if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10;

TechnicalAnalysis2x9();

TechnicalAnalysis2x12();

}

void TechnicalAnalysis2x9()

{

if ((iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,1) < iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,1)) && (iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,0) > iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,0)))

{

IfOrderDoesNotExist10();

}

}

void IfOrderDoesNotExist10()

{

bool exists = false;

for (int i=OrdersTotal()-1; i >= 0; i--)

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderType() == OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)

{

exists = true;

}

}

else

{

Print("OrderSelect() error - ", ErrorDescription(GetLastError()));

}

if (exists == false)

{

BuyOrderRiskFixed4();

}

}

void BuyOrderRiskFixed4()

{

double lotsize = MarketInfo(Symbol(),MODE_LOTSIZE) / AccountLeverage();

double pipsize = 1100 * 10;

double maxlots = AccountBalance() / 100 * BalanceRiskPercent4 / lotsize * pipsize;

if (BuyStoploss4 == 0) Print("OrderSend() error - stoploss can not be zero");

double lots = maxlots / BuyStoploss4 * 10;

// calculate lot size based on current risk

double lotvalue = 0.001;

double minilot = MarketInfo(Symbol(), MODE_MINLOT);

int powerscount = 0;

while (minilot < 1)

{

minilot = minilot * MathPow(10, powerscount);

powerscount++;

}

lotvalue = NormalizeDouble(lots, powerscount - 1);

if (lotvalue < MarketInfo(Symbol(), MODE_MINLOT)) // make sure lot is not smaller than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MINLOT);

}

if (lotvalue > MarketInfo(Symbol(), MODE_MAXLOT)) // make sure lot is not greater than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MAXLOT);

}

double SL = Ask - BuyStoploss4*PipValue*Point;

if (BuyStoploss4 == 0) SL = 0;

double TP = Ask + BuyTakeprofit4*PipValue*Point;

if (BuyTakeprofit4 == 0) TP = 0;

int ticket = -1;

if (true)

ticket = OrderSend(Symbol(), OP_BUY, lotvalue, Ask, 4, 0, 0, "My Expert", 1, 0, Blue);

else

ticket = OrderSend(Symbol(), OP_BUY, lotvalue, Ask, 4, SL, TP, "My Expert", 1, 0, Blue);

if (ticket > -1)

{

if (true)

{

OrderSelect(ticket, SELECT_BY_TICKET);

bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Blue);

if (ret == false)

Print("OrderModify() error - ", ErrorDescription(GetLastError()));

}

}

else

{

Print("OrderSend() error - ", ErrorDescription(GetLastError()));

}

}

void TechnicalAnalysis2x12()

{

if ((iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,1) > iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,1)) && (iMA(NULL, NULL,10,0,MODE_SMA,PRICE_CLOSE,0) < iMA(NULL, NULL,20,0,MODE_SMA,PRICE_CLOSE,0)))

{

IfOrderDoesNotExist8();

}

}

void IfOrderDoesNotExist8()

{

bool exists = false;

for (int i=OrdersTotal()-1; i >= 0; i--)

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

{

if (OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == 1)

{

exists = true;

}

}

else

{

Print("OrderSelect() error - ", ErrorDescription(GetLastError()));

}

if (exists == false)

{

SellOrderRiskFixed6();

}

}

void SellOrderRiskFixed6()

{

double lotsize = MarketInfo(Symbol(),MODE_LOTSIZE) / AccountLeverage();

double pipsize = 1100 * 10;

double maxlots = AccountBalance() / 100 * BalanceRiskPercent6 / lotsize * pipsize;

if (SellStoploss6 == 0) Print("OrderSend() error - stoploss can not be zero");

double lots = maxlots / SellStoploss6 * 10;

// calculate lot size based on current risk

double lotvalue = 0.001;

double minilot = MarketInfo(Symbol(), MODE_MINLOT);

int powerscount = 0;

while (minilot < 1)

{

minilot = minilot * MathPow(10, powerscount);

powerscount++;

}

lotvalue = NormalizeDouble(lots, powerscount - 1);

if (lotvalue < MarketInfo(Symbol(), MODE_MINLOT)) // make sure lot is not smaller than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MINLOT);

}

if (lotvalue > MarketInfo(Symbol(), MODE_MAXLOT)) // make sure lot is not greater than allowed value

{

lotvalue = MarketInfo(Symbol(), MODE_MAXLOT);

}

double SL = Bid + SellStoploss6*PipValue*Point;

if (SellStoploss6 == 0) SL = 0;

double TP = Bid - SellTakeprofit6*PipValue*Point;

if (SellTakeprofit6 == 0) TP = 0;

int ticket = -1;

if (true)

ticket = OrderSend(Symbol(), OP_SELL, lotvalue, Bid, 4, 0, 0, "My Expert", 1, 0, Red);

else

ticket = OrderSend(Symbol(), OP_SELL, lotvalue, Bid, 4, SL, TP, "My Expert", 1, 0, Red);

if (ticket > -1)

{

if (true)

{

OrderSelect(ticket, SELECT_BY_TICKET);

bool ret = OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0, Red);

if (ret == false)

Print("OrderModify() error - ", ErrorDescription(GetLastError()));

}

}

else

{

Print("OrderSend() error - ", ErrorDescription(GetLastError()));

}

}

int deinit()

{

if (false) ObjectsDeleteAll();

}

ÓRDENES LIMITADAS- Insertar ordenes limitadas cada "x" pips. Se crean 5 ordenes limites...

double a;

int start()

{

for(int i=1;i<=5;i++)

{ OrderSend(Symbol(),OP_BUYSTOP,0.01,Ask + a+ 0.0020,3,0, Ask+ a +0.0030);

a = a + 0.0020;

}

}

EA que cada vez que se cierre alguna de las ordenes BUYSTOP me cree otra vez esa misma orden...

Es con la función OrderSelect(OrdersHistoryTotal()-1,SELECT_BY_POS,MODE_HISTORY)

EAS BASADOS EN INDICADORES

- Compra cuando el precio sale por encima de la 2a desviación estándar de las BB y se cierra la compra cuando el precio rompe por debajo la línea central de las BB. En FEAG se abre la compra así: iBands ( NULL, NULL, 20, 2, O, PRICE_CLOSE, MODE_UPPER, O) < High(O) El cierre de la compra es así: iMA (NULL, 2, O, MODE_SMA, PRICE_CLOSE,O) > Low(O) - Estoy tratando de tener un EA que compare la última barra cerrada contra muchos barras anteriores, por ejemplo, la última barra (1) tienen un bajo mas bajo que las últimas veinte barras (2-21). ¿Hay una manera de hacer esto con un solo bloque, o tengo que usar veinte diferentes bloques que comparen la última barra a cada una de los anteriores veinte barras? R: Te sugiero uses un solo bloque de Análisis Técnico y coloques lo siguiente en él: First Function - Low[1] Compare- < Second Function - Low[iLowest(NULL,0,MODE_HIGH,21 ,2)];

VARIOS

¿Cómo entrar en x pips por encima del último máximo o por debajo del último bajo? P: Los bloques de órdenes pendientes te permiten especificar un número fijo de pips más arriba (por ejemplo) del último alto para colocar una orden Buy Stop. Quiero precisar que el EA coloque una orden de compra a mercado x pips por encima del último alto o x pips por debajo del último bajo. He intentado usar el bloque técnico (High[1] + 0,0001), pero no puede conseguir que funcione. Cualquier ayuda sería muy apreciada. R: El problema con el uso de High[1] es que tal vez High[1] ya está por debajo del precio de mercado actual Así que hay situaciones posibles: 1. High[1]+0,0001 está por debajo del actual AsklBid. 2. High[1]+0.0001 está por encima del actual Ask I Bid. 3. High[1]+0.0001 está demasiado cerca de AsklBid. Por "demasiado cerca" me refiero a que los brókers no te permitirán tener órdenes pendientes demasiado cerca del actual Bid/Ask. Si está demasiado cerca (ejemplo: sólo 2-4 pips de distancia) obtendrás un error del bróker. Mi consejo en general es la siguiente: durante la configuración inicial evita situaciones que pueden causar errores. En lugar de High[1]+0.0001 usa High[1]+0.0095. En este caso es poco probable que tu High[1]+0.0095 está cerca del actual AsklBid. Una vez que consigues que funcione reduce High[1]+0.0095 más cerca de los valores que deseas. Dependiendo de la estrategia que uses puedes encontrar que brokers ponen más restricciones en la configuración comercial. Y cada bróker es diferente en las restricciones. En scalping es especialmente evidente. Verás todo tipo de errores que vienen de los brókers, ya que estarás negociando en rangos de pips muy estrechos.