Bancos centrales y grandes jugadores: leve cambio en el código requerido
Bancos centrales y grandes jugadores: leve cambio en el código requerido

 

Publi

Resultados 1 al 8 de 8

Tema: Bancos centrales y grandes jugadores: leve cambio en el código requerido

  1. #1
    Recientemente me ha intrigado el tema llamado Bancos centrales y Grandes jugadores. La compra básica es comprar o vender en la dirección del primer movimiento de 2 pips en el precio en la apertura de Londres y Nueva York. El autor del hilo usa un SL muy pequeño (2 pips), TP 140 y lo hace muy bien con el egy. El EA (ver código a continuación) desarrollado para este ejemplo funciona muy bien, excepto por una cosa. Como está, moverá su parada hacia BE pip por pip (hasta que se alcance BE) a medida que el precio se mueva a su favor. El problema que tengo es que, incluso cuando EA estableció mi parada en BE, todavía pierdo la comisión que tengo que pagar en el intercambio. ¿Podría alguien ajustar el código a continuación (en negrita) los cambios necesarios para que el EA detenga el número de pips BE (x) para cubrir el costo de la comisión? gracias/ --------------------------------------------- ---------------------
    //| CBBP_EA_v2-0.mq4 |
    //| Zen Leow |
    //| |
    // ----------------------------------------------- -------------------
    #propiedad de derechos de autor Zen Leow
    # enlace de propiedad

    #include lt; stdlib.mqhgt;
    #include lt; stderror.mqhgt;
    # define PRIMARY_ORDER 1
    #define SECONDARY_ORDER 2

    extern int EA_MAGIC_NUM = 3947947;
    extern bool IsECN = true;
    extern bool CheckHourOfAttach = true;
    cadena externa Session1 = London Session;
    extern int SessionOpenHour1 = 8;
    cadena externa Session2 = sesión de Nueva York;
    extern int SessionOpenHour2 = 13;
    extern int GraceMinutes = 5;
    extern bool Show_Comments = true;
    extern doble UserDefinedSpread = 0;

    extern int Slippage = 3;
    Pip_Distance doble externo = 2;
    extern int TakeProfit = 140;
    extern int StopLoss = 5;
    extern bool UseJumpingStop = falso;
    extern int TrailingStop = 0;
    extern bool Add_Spread_To_StopLoss = false;
    extern bool Use_Spread_Filtering = true;
    Spread_Filter doble externo = 1.0;

    extern bool MoneyManagement = true;
    extern Doble RiskPercent = 0.25;
    extern bool UseEquity = falso;
    extern bool Use_BE = true;
    externa doble BreakEven_Pips = 5.0;
    Lotes fijos dobles externos = 0.1;
    MaxLots dobles externos = 15.0;
    MinLots dobles externos = 0.01;
    extern int LotsDecimalAllowed = 2;

    string msg =;
    doble CustomSpread = 0;
    int PipFactor = 1;
    bool StartupStatusOK = true;
    int the_StopLoss = 0;
    bool TradeTheSession = true;
    bool ProblemLogged = falso;
    int todayOfYear = 0;
    bool SessionIsOn = false;
    doble theSessionOpenPrice;
    cadena latestSession;
    int currentSessionHour;
    bool SessionOpenPriceWritten = false;

    // ----------------------------------------------- -------------------
    //| función de inicialización experta |
    // ----------------------------------------------- -------------------
    int init ()
    {
    //----
    int currentHour = TimeHour (TimeCurrent ());
    if ((currentHour == SessionOpenHour1 || currentHour == SessionOpenHour2) CheckHourOfAttach)
    {
    Alerta (IMPT: No debes adjuntar este EA durante Session1 Open hour o la Session2 Open hour);
    StartupStatusOK = falso;
    }
    if (Period () gt; PERIOD_H1)
    {
    Alerta (Este EA solo se puede adjuntar a las Cartas con un período de tiempo MENOS DE 1 hora);
    StartupStatusOK = falso;
    }
    if (MinLots lt; MarketInfo (Symbol (), MODE_MINLOT))
    {
    Alerta (MinLots no válidos: MinLots | Probar: MarketInfo (Symbol (), MODE_MINLOT));
    StartupStatusOK = falso;
    }
    if (MaxLots gt; MarketInfo (Symbol (), MODE_MAXLOT))
    {
    Alerta (MaxLots no válidos: MaxLots | Probar: MarketInfo (Symbol (), MODE_MAXLOT));
    StartupStatusOK = falso;
    }
    if (SessionOpenHour1 lt; 0 || SessionOpenHour1 gt; 23)
    {
    Alerta (hora de apertura no válida dada para Session1 : SessionOpenHour1);
    StartupStatusOK = falso;
    }
    if (SessionOpenHour2 lt; 0 || SessionOpenHour2 gt; 23)
    {
    Alerta (hora de apertura no válida dada para Session2 : SessionOpenHour2);
    StartupStatusOK = falso;
    }
    if (MoneyManagement (RiskPercent lt; = 0 || RiskPercent gt; 100))
    {
    Alerta (Riesgo inválido Porcentaje dado: RiesgoPerciente %);
    StartupStatusOK = falso;
    }
    if (estado de inicio)
    {
    Alerta (CBBP EA cargado en Símbolo () con entradas válidas);
    }
    WriteToLogFile (inicio de CBBP EA);

    GetSpread ();

    todayOfYear = DayOfYear ();
    //Abastecer pips fraccionales
    si (Dígitos == 3 || Dígitos == 5)
    {
    PipFactor = 10;
    }
    Slippage = Slippage * PipFactor;
    if (Show_Comments)
    {
    WriteComment ();
    }
    //----
    retorno (0);
    }

    // ----------------------------------------------- -------------------
    //| función de desinicialización experta |
    // ----------------------------------------------- -------------------
    int deinit ()
    {
    //----

    //----
    retorno (0);
    }


    // ----------------------------------------------- -------------------
    //| Funciones de lógica de gestión comercial |
    // ----------------------------------------------- -------------------

    bool TradeNotPlacedYet ()
    {
    int total = OrdersTotal ();
    si (total gt; 0)
    {
    para (int cnt = 0; cntlt; total; cnt )
    {
    if (OrderSelect (cnt, SELECT_BY_POS))
    {
    if (OrderSymbol () == Symbol () OrderMagicNumber () == EA_MAGIC_NUM)
    {
    SessionIsOn = false;
    falso retorno);
    }
    }
    }
    }
    //en caso de que el comercio ya haya abierto y cerrado para esta sesión
    int histotal = OrdersHistoryTotal ();
    si (histotal gt; 0)
    {
    para (cnt = 0; cntlt; histotal; cnt )
    {
    if (OrderSelect (cnt, SELECT_BY_POS, MODE_HISTORY))
    {
    if (OrderSymbol () == Symbol () OrderMagicNumber () == EA_MAGIC_NUM)
    {
    datetime LatestSessionStart = iTime (NULL, PERIOD_H1,0);
    datetime LatestSessionGrace = LatestSessionStart (GraceMinutes * 60);
    datetime CurrentOrderOpenTime = OrderOpenTime ();
    if (CurrentOrderOpenTime gt; = LatestSessionStart CurrentOrderOpenTime lt; = LatestSessionGrace)
    {
    SessionIsOn = false;
    falso retorno);
    }
    }
    }
    }
    }
    retorno (verdadero);
    }

    bool Should_Buy (int SessionOpenIndex)
    {
    if (SessionOpenIndex == -1)
    {
    falso retorno);
    }
    theSessionOpenPrice = Abrir [SessionOpenIndex];
    doble theSessionCurrentPrice = Close [0];
    if (theSessionCurrentPrice gt; theSessionOpenPrice)
    {
    double lookoutPrice = theSessionOpenPrice (Pip_Distance * Point * PipFactor);
    if (theSessionCurrentPrice gt; = lookoutPrice)
    {
    if (Spread_Still_In_Range ())
    {
    retorno (verdadero);
    }
    más
    {
    si (! ProblemLogged)
    {
    string logmsg = El margen es DoubleToStr (CustomSpread, 1) cuando el precio se movió DoubleToStr (Pip_Distance, 1) de este Precio de apertura de sesión. No hay comercio para esta sesión;
    WriteToLogFile (logmsg);
    ProblemLogged = true;
    TradeTheSession = false;
    }
    }
    }
    }
    falso retorno);
    }

    bool Should_Sell (int SessionOpenIndex)
    {
    if (SessionOpenIndex == -1)
    {
    falso retorno);
    }
    theSessionOpenPrice = Abrir [SessionOpenIndex];
    doble theSessionCurrentPrice = Close [0];
    if (theSessionCurrentPrice lt; theSessionOpenPrice)
    {
    double lookoutPrice = theSessionOpenPrice - (Pip_Distance * Point * PipFactor);
    if (theSessionCurrentPrice lt; = lookoutPrice)
    {
    if (Spread_Still_In_Range ())
    {
    retorno (verdadero);
    }
    más
    {
    si (! ProblemLogged)
    {
    string logmsg = El margen es DoubleToStr (CustomSpread, 1) cuando el precio se movió DoubleToStr (Pip_Distance, 1) de este Precio de apertura de sesión. No hay comercio para esta sesión;
    WriteToLogFile (logmsg);
    ProblemLogged = true;
    TradeTheSession = false;
    }
    }
    }
    }
    falso retorno);
    }

    doble PositionSizeToOpen (int StopLossPips)
    {
    doble PositionSize;
    doble riesgoDolares;

    if (MoneyManagement StopLossPips gt; 0)
    {
    si (UseEquity)
    {
    riskDollars = (AccountEquity ()100) * RiskPercent;
    }
    más
    {
    riskDollars = (AccountBalance ()100) * RiskPercent;
    }
    PositionSize = (riskDollarsStopLossPips)(MarketInfo (Symbol (), MODE_TICKVALUE) * PipFactor);
    }

    if (MoneyManagement StopLossPips lt; = 0)
    {
    si (UseEquity)
    {
    PositionSize = ((AccountEquity ()100) * RiskPercent)(MarketInfo (Symbol (), MODE_LOTSIZE)AccountLeverage ());
    }
    más
    {
    PositionSize = ((AccountBalance ()100) * RiskPercent)(MarketInfo (Symbol (), MODE_LOTSIZE)AccountLeverage ());
    }
    }

    if (! MoneyManagement)
    {
    PositionSize = FixedLots;
    }

    if (PositionSize lt; MinLots)
    {
    PositionSize = MinLots;
    }
    if (PositionSize gt; MaxLots)
    {
    PositionSize = MaxLots;
    }
    PositionSize = NormalizeDouble (PositionSize, LotsDecimalAllowed);
    return (PositionSize);
    }

    bool SendOrders (int BuyOrSell, doble tamaño de lote, doble PriceToOpen, doble Slippage, doble SL_Price, doble TP_Price, cadenas de comentarios, fecha y hora de expiración)
    {
    int ticket, errorType;

    si (BuyOrSell == OP_BUY)
    {
    si (isecn)
    {
    Imprimir (Oferta: Oferta Preguntar: Preguntar | Orden de compra inicial: Símbolo () , ComprarSell , LotSize , PriceToOpen , Slippage , SL_Price , TP_Price , comments , EA_MAGIC_NUM , ExpirationTime , Green) ;
    ticket = OrderSend (Symbol (), BuyOrSell, LotSize, PriceToOpen, Slippage, 0,0, comments, EA_MAGIC_NUM, ExpirationTime, Green);
    si (ticketgt; 0)
    {
    if (OrderSelect (ticket, SELECT_BY_TICKET, MODE_TRADES))
    {
    Imprimir (COMPRAR orden abierto:, OrderOpenPrice ());
    msg = ticket : posición de compra abierta en DoubleToStr (OrderOpenPrice (), dígitos);
    WriteToLogFile (msg);
    if (OrderModify (ticket, OrderOpenPrice (), SL_Price, TP_Price, 0))
    {
    Imprimir (Stop Loss y Take Profit añadidos);
    msg = ticket : Stop Loss: DoubleToStr (SL_Price, Digits) y Take Profit DoubleToStr (TP_Price, Digits) agregado;
    WriteToLogFile (msg);
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (ERROR al agregar Stop Loss y Take Profit -, ErrorDescription (errorType));
    msg = ticket : ERROR agregando Stop Loss: DoubleToStr (SL_Price, Digits) y Take Profit DoubleToStr (TP_Price, Digits) - ErrorDescription (errorType);
    WriteToLogFile (msg);
    }
    retorno (verdadero);
    }
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (Error al abrir la orden de COMPRA:, ErrorDescription (errorType));
    msg = NO SE PUEDE abrir la posición de COMPRA. ErrorDescription (errorType);
    WriteToLogFile (msg);
    falso retorno);
    }
    }
    más
    {
    Imprimir (Oferta: Oferta Preguntar: Preguntar | Orden de compra inicial: Símbolo () , ComprarSell , LotSize , PriceToOpen , Slippage , SL_Price , TP_Price , comments , EA_MAGIC_NUM , ExpirationTime , Green) ;
    ticket = OrderSend (Symbol (), BuyOrSell, LotSize, PriceToOpen, Slippage, SL_Price, TP_Price, comentarios, EA_MAGIC_NUM, ExpirationTime, Green);
    si (ticketgt; 0)
    {
    if (OrderSelect (ticket, SELECT_BY_TICKET, MODE_TRADES))
    {
    Imprimir (COMPRAR orden abierto:, OrderOpenPrice ());
    msg = ticket : posición de compra abierta. ErrorDescription (errorType);
    WriteToLogFile (msg);
    retorno (verdadero);
    }
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (Error al abrir la orden de COMPRA:, ErrorDescription (errorType));
    msg = NO SE PUEDE abrir la posición de COMPRA. ErrorDescription (errorType);
    WriteToLogFile (msg);
    falso retorno);
    }
    }
    }
    si (BuyOrSell == OP_SELL)
    {
    si (isecn)
    {
    Imprimir (Oferta: Oferta Preguntar: Preguntar | Apertura Orden de venta: Símbolo () , ComprarSell , LotSize , PriceToOpen , Slippage , SL_Price , TP_Price , comments , EA_MAGIC_NUM , ExpirationTime , Red) ;
    ticket = OrderSend (Symbol (), BuyOrSell, LotSize, PriceToOpen, Slippage, 0,0, comments, EA_MAGIC_NUM, ExpirationTime, Red);
    si (ticketgt; 0)
    {
    if (OrderSelect (ticket, SELECT_BY_TICKET, MODE_TRADES))
    {
    Imprimir (Orden de VENTA abierta:, OrderOpenPrice ());
    msg = ticket : posición de venta abierta en DoubleToStr (OrderOpenPrice (), dígitos);
    WriteToLogFile (msg);
    if (OrderModify (ticket, OrderOpenPrice (), SL_Price, TP_Price, 0))
    {
    Imprimir (Stop Loss y Take Profit añadidos);
    msg = ticket : Stop Loss: DoubleToStr (SL_Price, Digits) y Take Profit DoubleToStr (TP_Price, Digits) agregado;
    WriteToLogFile (msg);
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (ERROR al agregar Stop Loss y Take Profit -, ErrorDescription (errorType));
    msg = ticket : ERROR agregando Stop Loss: DoubleToStr (SL_Price, Digits) y Take Profit DoubleToStr (TP_Price, Digits) - ErrorDescription (errorType);
    WriteToLogFile (msg);
    }
    retorno (verdadero);
    }
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (Error al abrir orden de VENTA:, ErrorDescription (errorType));
    msg = NO SE PUEDE abrir la posición de VENTA. ErrorDescription (errorType);
    WriteToLogFile (msg);
    falso retorno);
    }
    }
    más
    {
    Imprimir (Oferta: Oferta Preguntar: Preguntar | Apertura Orden de venta: Símbolo () , ComprarSell , LotSize , PriceToOpen , Slippage , SL_Price , TP_Price , comments , EA_MAGIC_NUM , ExpirationTime , Red) ;
    ticket = OrderSend (Symbol (), BuyOrSell, LotSize, PriceToOpen, Slippage, SL_Price, TP_Price, comentarios, EA_MAGIC_NUM, ExpirationTime, Red);
    si (ticketgt; 0)
    {
    if (OrderSelect (ticket, SELECT_BY_TICKET, MODE_TRADES))
    {
    Imprimir (Orden de venta abierta:, OrderOpenPrice ());
    msg = ticket : Posición de venta abierta. ErrorDescription (errorType);
    WriteToLogFile (msg);
    retorno (verdadero);
    }
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (Error al abrir orden de VENTA:, ErrorDescription (errorType));
    msg = NO SE PUEDE abrir la posición de VENTA. ErrorDescription (errorType);
    WriteToLogFile (msg);
    falso retorno);
    }
    }
    }
    }


    bool Spread_Still_In_Range ()
    {
    if (Use_Spread_Filtering CustomSpread gt; Spread_Filter)
    {
    falso retorno);
    }
    retorno (verdadero);
    }


    anular OpenBuyOrder ()
    {
    RefreshRates ();
    doble PriceToOpen, TakeProfitPrice, StopLossPrice, PositionSize;
    PriceToOpen = Ask;
    PriceToOpen = NormalizeDouble (PriceToOpen, Digits);
    PositionSize = PositionSizeToOpen (the_StopLoss);
    si (TakeProfit == 0)
    {
    TakeProfitPrice = 0;
    }
    más
    {
    TakeProfitPrice = PriceToOpen (TakeProfit * Point * PipFactor);
    TakeProfitPrice = NormalizeDouble (TakeProfitPrice, Digits);
    }
    if (the_StopLoss == 0)
    {
    StopLossPrice = 0;
    }
    más
    {
    StopLossPrice = PriceToOpen - (the_StopLoss * Point * PipFactor);
    StopLossPrice = NormalizeDouble (StopLossPrice, Digits);
    }
    if (PositionSize lt; MinLots)
    {
    PositionSize = MinLots;
    }
    if (PositionSize gt; MaxLots)
    {
    PositionSize = MaxLots;
    }
    PositionSize = NormalizeDouble (PositionSize, LotsDecimalAllowed);
    cadena DateNow = TimeDay (TimeCurrent ()) - TimeMonth (TimeCurrent ()) - TimeYear (TimeCurrent ());
    SendOrders (OP_BUY, PositionSize, PriceToOpen, Slippage, StopLossPrice, TakeProfitPrice, CBBP_ DateNow, 0);
    }

    anular OpenSellOrder ()
    {
    RefreshRates ();
    doble PriceToOpen, TakeProfitPrice, StopLossPrice, PositionSize;
    PriceToOpen = oferta;
    PriceToOpen = NormalizeDouble (PriceToOpen, Digits);
    PositionSize = PositionSizeToOpen (the_StopLoss);
    si (TakeProfit == 0)
    {
    TakeProfitPrice = 0;
    }
    más
    {
    TakeProfitPrice = PriceToOpen - (TakeProfit * Point * PipFactor);
    TakeProfitPrice = NormalizeDouble (TakeProfitPrice, Digits);
    }
    if (the_StopLoss == 0)
    {
    StopLossPrice = 0;
    }
    más
    {
    StopLossPrice = PriceToOpen (the_StopLoss * Point * PipFactor);
    StopLossPrice = NormalizeDouble (StopLossPrice, Digits);
    }

    if (PositionSize lt; MinLots)
    {
    PositionSize = MinLots;
    }
    if (PositionSize gt; MaxLots)
    {
    PositionSize = MaxLots;
    }
    PositionSize = NormalizeDouble (PositionSize, LotsDecimalAllowed);
    cadena DateNow = TimeDay (TimeCurrent ()) - TimeMonth (TimeCurrent ()) - TimeYear (TimeCurrent ());
    SendOrders (OP_SELL, PositionSize, PriceToOpen, Slippage, StopLossPrice, TakeProfitPrice, DateNow, 0);
    }

    void ManageTrades ()
    {
    doble TrailLevel = PipFactor * Point * TrailingStop;
    TrailLevel = NormalizeDouble (TrailLevel, Digits);
    doble BE_Level = PipFactor * Point * BreakEven_Pips;
    BE_Level = NormalizeDouble (BE_Level, Digits);
    TakeProfitPrice doble, StopLossPrice;
    cadena logmsg =;
    int ticket, errorType;
    doble cierreNOWprice = 0;

    int total = OrdersTotal ();
    si (total gt; 0)
    {
    //debe ir hacia atrás
    para (int cnt = total-1; cntgt; = 0; cnt--)
    {
    if (OrderSelect (cnt, SELECT_BY_POS))
    {
    if (OrderSymbol () == Symbol () OrderMagicNumber () == EA_MAGIC_NUM)
    {
    if (OrderType () == OP_BUY)
    {
    //En caso de que no se hayan agregado Stop Loss y TakeProfit. Vamos a hacer algo al respecto aquí ...
    if (OrderStopLoss () == 0 the_StopLoss! = 0)
    {
    ticket = OrderTicket ();
    //Cierre la operación inmediatamente si el precio ya se ha movido, rompiendo el nivel de stop loss
    if (OrderOpenPrice () - Bid gt; = PipFactor * Point * the_StopLoss)
    {
    closeNOWprice = NormalizeDouble (Bid, Digits);
    if (OrderClose (ticket, OrderLots (), closeNOWprice, Slippage, Red))
    {
    Imprimir (emergencia (Stop Loss) cierre de orden:, boleto, exitoso);
    logmsg = ticket : ¡Cierre de emergencia (Stop Loss) exitoso !;
    WriteToLogFile (logmsg);
    continuar;
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (¡ERROR! Cierre de orden de emergencia (Stop Loss):, ticket, failed! -, ErrorDescription (errorType));
    logmsg = ticket : Cierre de la orden de emergencia (Stop Loss): ticket failed! - ErrorDescription (errorType);
    WriteToLogFile (logmsg);
    }
    }
    más
    {
    //intenta colocar el nivel de Stop Loss y Take Profit ahora
    StopLossPrice = OrderOpenPrice () - (the_StopLoss * Point * PipFactor);
    StopLossPrice = NormalizeDouble (StopLossPrice, Digits);
    TakeProfitPrice = OrderOpenPrice () (TakeProfit * Point * PipFactor);
    TakeProfitPrice = NormalizeDouble (TakeProfitPrice, Digits);
    if (OrderModify (ticket, OrderOpenPrice (), StopLossPrice, TakeProfitPrice, 0))
    {
    Imprimir (Stop Loss y Take Profit of order:, ticket, agregado con éxito);
    logmsg = ticket : Stop Loss y Take Profit se agregaron correctamente;
    WriteToLogFile (logmsg);
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (¡ERROR! Adición de Stop Loss y Take Profit of order:, ticket, failed! -, ErrorDescription (errorType));
    logmsg = ticket : Agregar Stop Loss y Take Profit of order: ticket failed! - ErrorDescription (errorType);
    WriteToLogFile (logmsg);
    }
    }
    }
    //Similar a lo anterior, excepto que aborda el escenario de nalgas de nivel takeprofit
    if (OrderTakeProfit () == 0 TakeProfit! = 0)
    {
    //Cierre la operación inmediatamente si el precio ya se ha movido, rompiendo el nivel de stop loss
    if (Bid-OrderOpenPrice () gt; = PipFactor * Point * TakeProfit)
    {
    ticket = OrderTicket ();
    closeNOWprice = NormalizeDouble (Bid, Digits);
    if (OrderClose (ticket, OrderLots (), closeNOWprice, Slippage, Blue))
    {
    Impresión (emergencia (toma de ganancias) cierre de pedido:, boleto, exitoso);
    logmsg = ticket : ¡Cierre de emergencia (Take Profit) exitoso !;
    WriteToLogFile (logmsg);
    continuar;
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (¡ERROR! Emergencia (Take Profit) cierre de pedido:, ticket, failed! -, ErrorDescription (errorType));
    logmsg = ticket : Cierre de orden de emergencia (Take Profit): ¡ ticket fallido! - ErrorDescription (errorType);
    WriteToLogFile (logmsg);
    }
    }
    }

    //Compruebe si hay punto de equilibrio.
    si (Use_BE)
    {
    if (Bid-OrderStopLoss () gt; PipFactor * Point * BreakEven_Pips)
    {
    if (OrderStopLoss () lt; OrderOpenPrice ())
    {
    StopLossPrice = Bid ??????- BE_Level;
    StopLossPrice = NormalizeDouble (StopLossPrice, Digits);
    if (StopLossPrice gt; OrderOpenPrice ())
    {
    if (OrderModify (OrderTicket (), OrderOpenPrice (), OrderOpenPrice (), OrderTakeProfit (), 0, verde))
    {
    logmsg = Buy Order OrderTicket () SL alcanzó el nivel de equilibrio;
    WriteToLogFile (logmsg);
    }
    }
    más
    {
    if (OrderModify (OrderTicket (), OrderOpenPrice (), StopLossPrice, OrderTakeProfit (), 0, verde))
    {
    logmsg = Buy Order OrderTicket () SL se mueve hacia el nivel de equilibrio;
    WriteToLogFile (logmsg);
    }
    }
    }
    }
    }
    //Comprobar si hay una parada flotante
    if (! UseJumpingStop (TrailingStop! = 0))
    {
    if ((Bid-OrderOpenPrice ()) gt; TrailLevel ((Bid-OrderOpenPrice ()) gt; = BE_Level || OrderStopLoss () gt; = OrderOpenPrice ()))
    {
    if (OrderStopLoss () lt; Bid-TrailLevel)
    {
    StopLossPrice = NormalizeDouble (Bid-TrailLevel, Digits);
    OrderModify (OrderTicket (), OrderOpenPrice (), StopLossPrice, OrderTakeProfit (), 0, verde);
    }
    }
    }
    //Compruebe si hay una parada de salto
    if (UseJumpingStop (TrailingStop! = 0))
    {
    if ((Bid-OrderStopLoss () gt; (TrailLevel * 2)) ((Bid-OrderOpenPrice ()) gt; = BE_Level || OrderStopLoss () gt; = OrderOpenPrice ()))
    {
    if ((OrderStopLoss () TrailLevel) lt; OrderTakeProfit () || OrderTakeProfit () == 0)/El nivel de stop loss no puede ser mayor que el nivel de toma de ganancias
    {
    StopLossPrice = NormalizeDouble (OrderStopLoss () TrailLevel, Digits);
    OrderModify (OrderTicket (), OrderOpenPrice (), StopLossPrice, OrderTakeProfit (), 0, verde);
    }
    }
    }
    }

    if (OrderType () == OP_SELL)
    {
    //En caso de que no se hayan agregado Stop Loss y TakeProfit. Vamos a hacer algo al respecto aquí ...
    if (OrderStopLoss () == 0 the_StopLoss! = 0)
    {
    ticket = OrderTicket ();
    //Cierre la operación inmediatamente si el precio ya se ha movido, rompiendo el nivel de stop loss
    if (Ask - OrderOpenPrice () gt; = PipFactor * Point * the_StopLoss)
    {
    closeNOWprice = NormalizeDouble (Ask, Digits);
    if (OrderClose (ticket, OrderLots (), closeNOWprice, Slippage, Red))
    {
    Imprimir (emergencia (Stop Loss) cierre de orden:, boleto, exitoso);
    logmsg = ticket : ¡Cierre de emergencia (Stop Loss) exitoso !;
    WriteToLogFile (logmsg);
    continuar;
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (¡ERROR! Cierre de orden de emergencia (Stop Loss):, ticket, failed! -, ErrorDescription (errorType));
    logmsg = ticket : Cierre de la orden de emergencia (Stop Loss): ticket failed! - ErrorDescription (errorType);
    WriteToLogFile (logmsg);
    }
    }
    más
    {
    //intenta colocar el nivel de Stop Loss y Take Profit ahora
    StopLossPrice = OrderOpenPrice () (the_StopLoss * Point * PipFactor);
    StopLossPrice = NormalizeDouble (StopLossPrice, Digits);
    TakeProfitPrice = OrderOpenPrice () - (TakeProfit * Point * PipFactor);
    TakeProfitPrice = NormalizeDouble (TakeProfitPrice, Digits);
    if (OrderModify (ticket, OrderOpenPrice (), StopLossPrice, TakeProfitPrice, 0))
    {
    Imprimir (Stop Loss y Take Profit of order:, ticket, agregado con éxito);
    logmsg = ticket : Stop Loss y Take Profit se agregaron correctamente;
    WriteToLogFile (logmsg);
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (¡ERROR! Adición de Stop Loss y Take Profit of order:, ticket, failed! -, ErrorDescription (errorType));
    logmsg = ticket : Agregar Stop Loss y Take Profit of order: ticket failed! - ErrorDescription (errorType);
    WriteToLogFile (logmsg);
    }
    }
    }
    //Similar a lo anterior, excepto que aborda el escenario de nalgas de nivel takeprofit
    if (OrderTakeProfit () == 0 TakeProfit! = 0)
    {
    //Cierre la operación inmediatamente si el precio ya se ha movido, rompiendo el nivel de stop loss
    if (OrderOpenPrice () - Ask gt; = PipFactor * Point * TakeProfit)
    {
    ticket = OrderTicket ();
    closeNOWprice = NormalizeDouble (Ask, Digits);
    if (OrderClose (ticket, OrderLots (), closeNOWprice, Slippage, Blue))
    {
    Impresión (emergencia (toma de ganancias) cierre de pedido:, boleto, exitoso);
    logmsg = ticket : ¡Cierre de emergencia (Take Profit) exitoso !;
    WriteToLogFile (logmsg);
    continuar;
    }
    más
    {
    errorType = GetLastError ();
    Imprimir (¡ERROR! Emergencia (Take Profit) cierre de pedido:, ticket, failed! -, ErrorDescription (errorType));
    logmsg = ticket : Cierre de orden de emergencia (Take Profit): ¡ ticket fallido! - ErrorDescription (errorType);
    WriteToLogFile (logmsg);
    }
    }
    }

    //Compruebe si hay equilibrio
    si (Use_BE)
    {
    if (OrderStopLoss () - Ask gt; PipFactor * Point * BreakEven_Pips)
    {
    if (OrderStopLoss () gt; OrderOpenPrice ())
    {
    StopLossPrice = Ask BE_Level;
    StopLossPrice = NormalizeDouble (StopLossPrice, Digits);
    if (StopLossPrice lt; OrderOpenPrice ())
    {
    if (OrderModify (OrderTicket (), OrderOpenPrice (), OrderOpenPrice (), OrderTakeProfit (), 0, verde))
    {
    logmsg = Order Order OrderTicket () SL alcanzó el nivel de equilibrio;
    WriteToLogFile (logmsg);
    }
    }
    más
    {
    if (OrderModify (OrderTicket (), OrderOpenPrice (), StopLossPrice, OrderTakeProfit (), 0, verde))
    {
    logmsg = Order Order OrderTicket () SL avanzando hacia el nivel de equilibrio;
    WriteToLogFile (logmsg);
    }
    }
    }
    }
    }
    //Comprobar si hay una parada flotante
    if (! UseJumpingStop (TrailingStop! = 0))
    {
    if ((OrderOpenPrice () - Ask) gt; TrailLevel ((OrderOpenPrice () - Ask) gt; = BE_Level || OrderStopLoss () lt; = OrderOpenPrice ())))
    {
    if (OrderStopLoss () gt; Ask TrailLevel)
    {
    StopLossPrice = NormalizeDouble (Ask TrailLevel, Digits);
    OrderModify (OrderTicket (), OrderOpenPrice (), StopLossPrice, OrderTakeProfit (), 0, rojo);
    }
    }
    }
    //Compruebe si hay una parada de salto
    if (UseJumpingStop (TrailingStop! = 0))
    {
    //solo se activa cuando la posición está en beneficio por stoploss amt.
    if (((OrderStopLoss () - Ask) gt; (TrailLevel * 2)) ((OrderOpenPrice () - Ask) gt; = BE_Level || OrderStopLoss () lt; = OrderOpenPrice ()))
    {
    if ((OrderStopLoss () - TrailLevel) gt; OrderTakeProfit () || OrderTakeProfit () == 0)/El nivel de stop loss no puede ser menor que el nivel de toma de ganancias
    {
    StopLossPrice = NormalizeDouble (OrderStopLoss () - TrailLevel, Digits);
    OrderModify (OrderTicket (), OrderOpenPrice (), StopLossPrice, OrderTakeProfit (), 0, rojo);
    }
    }
    }
    }
    }
    }
    }
    }
    }

    // ----------------------------------------------- -------------------
    //| Funciones varias |
    // ----------------------------------------------- -------------------

    void GetSpread ()
    {
    if (UserDefinedSpread lt; = 0)
    {
    CustomSpread = (MarketInfo (Symbol (), MODE_SPREAD))PipFactor;
    }
    más
    {
    Extensión personalizada = Extensión definida por el usuario;
    }

    //¿Debemos agregar la propagación en StopLoss?
    el Stop Loss = Stop Loss;
    if (StopLoss gt; 0)
    {
    if (Add_Spread_To_StopLoss)
    {
    el Stop Loss = Stop Loss Custom Spread;
    }
    más
    {
    el Stop Loss = Stop Loss;
    }
    }
    }

    void WriteComment ()
    {
    msg =;
    int currentHour = TimeHour (Time [0]);
    if (SessionOpenHour1 lt; SessionOpenHour2)
    {
    if (currentHour lt; SessionOpenHour2)
    {
    msg = EA esperando Session2 Abrir;
    }
    if (currentHour lt; SessionOpenHour1 || currentHour gt; SessionOpenHour2)
    {
    msg = EA esperando Session1 Abrir;
    }
    }
    más
    {
    if (currentHour lt; SessionOpenHour1)
    {
    msg = EA esperando Session1 Abrir;
    }
    if (currentHour lt; SessionOpenHour2 || currentHour gt; SessionOpenHour1)
    {
    msg = EA esperando Session2 Abrir;
    }
    }
    msg = msg \ Hora actual: Hora actual : Minuto de tiempo (TimeCurrent ());

    si (PipFactor == 10)
    {
    msg = msg \ nTrabajando con pips fraccionales;
    }
    más
    {
    msg = msg \ nTrabajo con pips no fraccionales;
    }
    //double stoplevel = MarketInfo (Symbol (), MODE_STOPLEVEL)PipFactor;

    if (MoneyManagement the_StopLoss gt; 0)
    {
    msg = msg \ Uso de la función de administración de dinero de acuerdo con Stop loss;
    }
    msg = msg \ Spread actual: DoubleToStr (Custom Spread, 1) pips;
    if (Add_Spread_To_StopLoss the_StopLoss! = 0)
    {
    msg = msg \ nSe agregará una extensión a su Stop Loss;
    }
    más
    {
    msg = msg \ nLa extensión NO se agregará a Stop Loss;
    }
    si (SessionIsOn)
    {
    msg = msg \ on \ Time to trade latestSession . Buscando entrada ...;
    msg = msg \ nSession Precio de apertura: DoubleToStr (theSessionOpenPrice, Digits);
    msg = msg \ n Precio actual: DoubleToStr (Cerrar [0], Dígitos);
    }
    más
    {
    msg = msg \ n latestSession la ventana comercial está cerrada .;
    }
    Comentario (msg);
    }

    void WriteToLogFile (entrada de cadena)
    {
    cadena nombre de archivo = CBBP- Símbolo () - Día () - Mes () - Año () . log;
    int handle = FileOpen (nombre de archivo, FILE_READ | FILE_WRITE);
    if (handlegt; 1)
    {
    prefijo de cadena = Día () Mes () Año () - Hora () : Minuto () : Segundos () = gt; ;
    FileSeek (handle, 0, SEEK_END);/ir al final del archivo
    FileWrite (manejador, prefijo entrada);
    FileClose (manejar);
    }
    }
    //Este método se crea para generar un nuevo archivo para un nuevo día. La primera línea que se escribe a veces no se escribe.
    //El mensaje ficticio utilizado aquí puede actuar como un búfer para que la información útil no se pierda.
    void CreateNewLogFileIfNewDay ()
    {
    if (todayOfYear! = DayOfYear ())
    {
    todayOfYear = DayOfYear ();
    WriteToLogFile (mensaje ficticio);
    }
    }

    bool TimeToTrade ()
    {
    int currentHour = TimeHour (Time [0]);
    int currentMinute = TimeMinute (TimeCurrent ());
    if ((currentHour == SessionOpenHour1 || currentHour == SessionOpenHour2) currentMinute lt; GraceMinutes)
    {
    retorno (verdadero);
    }
    falso retorno);
    }

    int GetSessionOpenCandle ()
    {
    int SessionOpenCandleIndex = -1;
    para (int i = 0; ilt; = GraceMinutes 1; i )
    {
    if (TimeHour (Time [i]) == currentSessionHour TimeMinute (Time [i]) == 0)
    {
    SessionOpenCandleIndex = i;
    descanso;
    }
    }
    return (SessionOpenCandleIndex);
    }

    // ----------------------------------------------- -------------------
    //| función de inicio experto |
    // ----------------------------------------------- -------------------
    int start ()
    {
    //----
    if (! StartupStatusOK)
    {
    Comentario (hubo errores en sus entradas de EA. Vuelva a verificarlos nuevamente);
    retorno (0);
    }
    CreateNewLogFileIfNewDay ();
    Manage Trades ();
    GetSpread ();

    si (TimeToTrade ())
    {
    currentSessionHour = TimeHour (Time [0]);
    if (currentSessionHour == SessionOpenHour1)
    {
    latestSession = Session1;
    }
    if (currentSessionHour == SessionOpenHour2)
    {
    latestSession = Session2;
    }
    if (TradeNotPlacedYet () TradeTheSession)
    {
    int SessionOpenIndex = GetSessionOpenCandle ();
    SessionIsOn = true;
    si (! SessionOpenPriceWritten)
    {
    string logmsg = latestSession open en DoubleToStr (Open [SessionOpenIndex], Digits);
    Imprimir (logmsg);
    WriteToLogFile (logmsg);
    SessionOpenPriceWritten = true;
    }
    if (Should_Buy (SessionOpenIndex) TradeTheSession)
    {
    OpenBuyOrder ();
    TradeTheSession = false;
    }
    if (Should_Sell (SessionOpenIndex) TradeTheSession)
    {
    OpenSellOrder ();
    TradeTheSession = false;
    }
    }
    más
    {
    SessionIsOn = false;
    }
    }
    más
    {
    SessionIsOn = false;
    TradeTheSession = true;
    ProblemLogged = falso;
    SessionOpenPriceWritten = false;
    }
    if (Show_Comments)
    {
    WriteComment ();
    }

    //----
    retorno (0);

  2.                         
    Publicidad
  3. #2
    Hola, solo quería saber si este EA tiene un código que establece el límite para detenerse incluso después de la ganancia de 2 pips. Quería tener esta función para poder establecer y olvidar órdenes a un precio que quiero y después de que alcancen 2 pips de ganancias, permitir un comercio libre. No soy un programador, así que no tengo ni idea de lo que significa ese código arriba.

  4. #3
    ¿Tienes un enlace? O, quizás puedas publicar la versión más actual aquí? No importa, lo encontré en este post aquí.

  5. #4
    La versión 3 de la EA que se ofrece para este requisito se publica en el hilo de Bancos centrales y Grandes jugadores. Este hilo se puede cerrar. saludos, zen

  6. #5
    ¿Estás hablando de la propagación? ¿O la comisión encima de la propagación? Si fuera solo la propagación, eso sería bastante fácil, creo? ... BE ((Ask-Bid)Point) * Lotes (puede requerir paréntesis adicional). De lo contrario, tiene que averiguar cómo su agente calcula la comisión adicional y usted tendría que preguntarles.

  7. #6
    Cita Iniciado por ;
    adjunte el EA a la publicación - como es normal, la sintaxis de la escritura se complica un poco cuando se vuelve a cargar en MT4 para su edición.
    Aja, aquí tienes. Gracias
    https://www.forosforex.com/trading-d...statement.html
    https://www.forosforex.com/attachmen...1375101646.mq4

  8. #7
    adjunte el EA a la publicación - como es normal, la sintaxis de la escritura se complica un poco cuando se vuelve a cargar en MT4 para su edición.

  9. #8
    Estoy seguro de que hay alguien que puede ver el valor en este EA. ¿Cómo obtengo de BE (como está) a BE (x) el número de pips? gracias

Permisos de publicación

  • No puedes crear nuevos temas
  • No puedes responder temas
  • No puedes subir archivos adjuntos
  • No puedes editar tus mensajes
  •  
Uso de cookies
Utilizamos cookies propias y de terceros para elaborar información estadística y mostrarle publicidad personalizada a través del análisis de su navegación. Si continúa navegando acepta su uso. Más información y política de cookies.
     

Aviso legal: Ni forosforex.com ni ninguna persona involucrada en forosforex.com aceptarán ninguna responsabilidad por cualquier pérdida o daño en el trading como resultado de la confianza en la información contenida en este sitio web, incluidos datos, cotizaciones, gráficos y señales de compra/venta. Por favor, infórmese plenamente de los riesgos y costes asociados a las operaciones en los mercados financieros, una de las formas de inversión que más riesgos entrañan.
forosforex.com le quiere recordar que los datos contenidos en este sitio web no son necesariamente en tiempo real ni exactos. forosforex.com no asume responsabilidad alguna por las pérdidas en que usted podría incurrir como resultado de la utilización de estos datos. Este acuerdo se rige por su versión en inglés, que prevalecerá siempre que haya alguna discrepancia entre la versión en inglés y la versión en español. Los CFD son un producto difícil de entender, varios organismos reguladores consideran que no es adecuado para inversores minoristas debido a su complejidad y riesgo.
Advertencia de riesgo: Los CFDs son un producto difícil de entender, y puede no ser adecuado para inversores minoristas debido a su complejidad y riesgo. Existe la posibilidad de sufrir una pérdida igual o superior a la inversión. Por lo tanto, no debe invertir o arriesgar dinero que no pueda permitirse perder. Debe asegurarse de que comprende todos los riesgos. Antes de abrir una cuenta en un broker por favor sea consciente e infórmese de los riesgos asociados con el trading. El contenido de este sitio web no debe interpretarse como asesoramiento personal. ForosForex recomienda que busque el consejo de un asesor financiero independiente.