Escolar Documentos
Profissional Documentos
Cultura Documentos
double StopLevel = 0;
double SetPoint = 0; // SetPoint variável para codificar corretores de 4 ou 5
dígitos
double pips;
int T = 0;
int Count_one_message = 0;
int Tp, err, ntp, total = 0, resultado;
double priceopen, stoploss, takeprofit;
double AccountEquityHighAmt, PrevEquity;
/ * - Esses parâmetros devem ser exibidos na tela - * /
string EAName = "Martingale ver 1.0"; // nome do EA, a ser exibido na tela
string EAComment = "Martingale"; // Esta variável colocaremos em cada negociação
como um comentário
// + ----------------------------------------------- ------------------- +
// | Função de inicialização de especialista |
// + ----------------------------------------------- ------------------- +
int OnInit ()
{
double ticksize = MarketInfo (Symbol (), MODE_TICKSIZE);
if (ticksize == 0,00001 || ticksize == 0,001)
pips = ticksize * 10;
else
pips = ticksize;
ntp = Take_Profit;
// ---
// ---
return (INIT_SUCCEEDED);
}
// + ---------------------------------------------- -------------------- +
// | Função de desinicialização especializada |
// + ----------------------------------------------- ------------------- +
void OnDeinit (const int reason)
{
// ---
}
// + ------------- -------------------------------------------------- --- +
// | Função de marcação de especialista |
// + ----------------------------------------------- ------------------- +
void OnTick ()
{
double AveragePrice = 0;
contagem dupla = 0;
double CurrentPairProfit = CalculateProfit ();
if (UseEquityStop)
{
if (CurrentPairProfit <0.0 && MathAbs (CurrentPairProfit)> TotalEquityRisk /
100.0 * AccountEquityHigh ())
{
CloseThisSymbolAll ();
Imprimir ("Tudo fechado devido a interrupção");
}
}
if (UseTrailingStop)
Trail (TrailStart, TrailStop, AveragePrice);
// Verifique se há Nova Barra (compatível com MQL4 e MQL5)
static datetime dtBarCurrent = WRONG_VALUE;
datetime dtBarPrevious = dtBarCurrent;
dtBarCurrent = (data / hora) SeriesInfoInteger (_Symbol, _Period,
SERIES_LASTBAR_DATE);
bool NewBarFlag = (dtBarCurrent! = dtBarPrevious);
if (NewBarFlag)
{
if (IfOrderDoesNotExistBuy () == 0)
{
if ((trade () == 2))
MARTINGALE_BUY ();
if ((comércio () == 1))
MARTINGALE_SELL ();
}
if ((IfOrderopenBuy () == 1) && (IfOrderopenSell () == 0))
MARTINGALE_SELL ();
if ((IfOrderopenSell () == 1) && (IfOrderopenBuy () == 0))
MARTINGALE_BUY ();
if (IfOrderopenBuy () == 1)
GoMartingalebuy ();
if (IfOrderopenSell () == 1)
GoMartingalesell ();
}
}
// ----------------------------------------------
-------------------------------------------------- -----------
int trade ()
// condições de negociação
// - Aqui é onde você insere indicadores de codificação para acionar OP - * /
{
bilhete interno = 0;
// Verifique se há Nova Barra (compatível com MQL4 e MQL5)
static datetime dtBarCurrent = WRONG_VALUE;
datetime dtBarPrevious = dtBarCurrent;
dtBarCurrent = (data / hora) SeriesInfoInteger (_Symbol, _Period,
SERIES_LASTBAR_DATE);
bool NewBarFlag = (dtBarCurrent! = dtBarPrevious);
total = 0;
if (Barras <100)
{
Imprimir ("barras menores que 100");
return (0);
}
if (IsTradeAllowed () == false)
{
Print ("Negociação NÃO É Permitida");
return (0);
}
{
// ----
int stops_level = (int) SymbolInfoInteger (_Symbol,
SYMBOL_TRADE_STOPS_LEVEL);
int iTrade = 0;
}
/ * - Esta é a função de Martingale. Se o OP estiver errado, faça martingale
- * /
if (OrdersTotal ()> = 1)
{
if (NewBarFlag)
GoMartingalebuy ();
}
exit (); // CLOSE
// ----
return (0);
}
}
// + --------------------------------------------- --------------------- +
// + ------------------------- ----------------------------------------- +
// | MARTINGALE |
// + ----------------------------------------------- ------------------- +
int GoMartingalebuy ()
{
int iCount = 0;
LastOP duplo = 0;
LastLots duplo = 0;
bool LastIsBuy = FALSE;
int iTotalBuy = 0;
int iTotalSell = 0;
Spread duplo = 0;
}
}
exit (); // CLOSE
return (0);
}
// =======================================================
==========================================================
=================================================
// + ----------------------------------------------- ------------------- +
// | MARTINGALE_SELL |
// + ----------------------------------------------- ------------------- +
int MARTINGALE_SELL ()
{
bilhete interno = 0;
// Verifique se há nova barra (compatível com MQL4 e MQL5)
data e hora estática dtBarCurrent = WRONG_VALUE;
datetime dtBarPrevious = dtBarCurrent;
dtBarCurrent = (data / hora) SeriesInfoInteger (_Symbol, _Period,
SERIES_LASTBAR_DATE);
bool NewBarFlag = (dtBarCurrent! = dtBarPrevious);
total = 0;
if (Barras <100)
{
Imprimir ("barras menores que 100");
return (0);
}
if (IsTradeAllowed () == false)
{
Print ("Negociação NÃO É Permitida");
return (0);
}
{
// ----
int stops_level = (int) SymbolInfoInteger (_Symbol,
SYMBOL_TRADE_STOPS_LEVEL);
int iTrade = 0;
//
+ ---------------------------------------------- -------------------- +
//
| / * - Ordem de Venda - * / |
//
+ ----------------------------------------------- ------------------- +
if
(((AccountStopoutMode () == 1) &&
(AccountFreeMarginCheck (Symbol (), OP_SELL, Lotsize)>
AccountStopoutLevel ()))
| | ((AccountStopoutMode () == 0) &&
((AccountEquity () / (AccountEquity () - AccountFreeMarginCheck
(Symbol (), OP_SELL, Lotsize)) * 100)> AccountStopoutLevel ())))
if (CheckMoneyForTrade (Symbol () , LotsOptimized (Lotsize), OP_SELL))
if (! OrderSend (Symbol (), OP_SELL, LotsOptimized (Lotsize), ND
(Bid), 3,0, NDTP (Bid-Take_Profit * pips), EAComment, MagicNumber))
Print ("eror", GetLastError ());
}
/ * - Esta é a função da Gamarra. Se houver OP errado, faça martingale - * /
if (OrdersTotal ()> = 1)
{
if (NewBarFlag)
GoMartingalesell ();
}
// ----
exit (); // CLOSE
return (0);
}
}
// + --------------------------------------------- --------------------- +
// | MARTINGALE |
// + ----------------------------------------------- ------------------- +
int GoMartingalesell ()
{
int iCount = 0;
LastOP duplo = 0;
LastLots duplo = 0;
bool LastIsBuy = FALSE;
int iTotalBuy = 0;
int iTotalSell = 0;
Spread duplo = 0;
{
LastOP = OrderOpenPrice ();
}
if (LastOP <OrderOpenPrice ())
{
LastOP = OrderOpenPrice ();
}
if (LastLots <OrderLots ())
{
LastLots = OrderLots ();
}
LastIsBuy = FALSE;
iTotalSell ++;
{
if ( ((AccountStopoutMode () == 1) &&
(AccountFreeMarginCheck (Symbol (), OP_SELL, Lotsize)>
AccountStopoutLevel ()))
|| ((AccountStopoutMode () == 0) &&
((AccountEquity () / (AccountEquity () - AccountFreeMarginCheck
(Symbol (), OP_SELL, Lotsize)) * 100)> AccountStopoutLevel ())))
if (Double_Lotsize == false)
{
if (CheckMoneyForTrade (Symbol (), LotsOptimized (LastLots +
Lot_Size_Increment), OP_SELL))
if (! OrderSend (Symbol (), OP_SELL, LotsOptimized (LastLots +
Lot_Size_Increment), ND (Bid), 3,0, NDTP (Bid-Take_Profit * pips), EAComment,
MagicNumber))
Print ("eror", GetLastError () );
}
if (Double_Lotsize == TRUE)
{
if (CheckMoneyForTrade (Symbol (), LotsOptimized (Multiply * LastLots),
OP_SELL))
if (! OrderSend (Symbol (), OP_SELL, LotsOptimized (Multiply *
LastLots), ND (Bid), 3,0, NDTP (Bid-Take_Profit * pips), EAComment, MagicNumber))
Print ("eror", GetLastError ());
}
ModifyTPsell ();
return (0);
}
}
exit (); // CLOSE
return (0);
}
// ======================================================
==========================================================
================================================
// + ----- -------------------------------------------------- ----------- +
// + ----------------------------------- ------------------------------- +
// | MODIFICAR TOME LUCRO COMPRAR |
// + ----------------------------------------------- ------------------- +
/ * - A função ModifyTP é mudar todo aquele OP TP no mesmo ponto - * /
void ModifyTPbuy ()
{
int iCount = 0 ;
NewTP duplo = 0;
RefreshRates ();
// stoploss = Ask + (pips * TrailingStop);
StopLevel = MarketInfo (Symbol (), MODE_STOPLEVEL) + MarketInfo (Symbol
(), MODE_SPREAD);
if (NewTP <StopLevel * pips)
stoploss = StopLevel * pips;
símbolo de string = OrderSymbol ();
ponto duplo = SymbolInfoDouble (símbolo, SYMBOL_POINT);
if (MathAbs (OrderTakeProfit () - NewTP)> point)
if ((Bid-NewTP)> (int) SymbolInfoInteger (_Symbol,
SYMBOL_TRADE_FREEZE_LEVEL) * pips)
if (OrderModifyCheck (OrderTicket (), OrderOpenPrice (), 0, NewTP))
if (! OrderModify (OrderTicket (), OrderLots (), 0, NewTP, 0))
Print ("erro");
}
}
exit (); // CLOSE
}
// ======================================================
==========================================================
======================================
// + ------------- -------------------------------------------------- --- +
// + ------------------------------------------- ----------------------- +
// | Trailing stop loss |
// + ----------------------------------------------- ------------------- +
// + --------------------------- --------------------------------------- +
Trilha dupla (partida dupla, parada dupla, dupla Preço Médio)
{
lucro duplo;
stoptrade duplo;
stopcal duplo = 0;
// ponto duplo = 0;
// double StopLevel = 0;
if (pare! = 0)
{
for (int trade = OrdersTotal () - 1; trade> = 0; trade--)
{
if (OrderSelect (trade, SELECT_BY_POS, MODE_TRADES))
{
if (OrderSymbol ()! = Symbol () || OrderMagicNumber ()! = MagicNumber)
continue;
if (OrderSymbol () == Symbol () || OrderMagicNumber () == MagicNumber)
{
if (OrderType () == OP_BUY)
{
profit = NormalizeDouble ((Bid-AvgPrice) / pips, 0);
se (lucro <Início)
continuar;
stoptrade = OrderStopLoss ();
stopcal = NDTP (parada de lance * pips);
if (stoptrade == 0.0 || (stoptrade! = 0.0 && stopcal> stoptrade))
// --- modificar o pedido e sair do
if (CheckStopLoss_Takeprofit (OP_BUY, stopcal, OrderTakeProfit
()))
if (OrderModifyCheck (OrderTicket (), AvgPrice , NDTP
(stopcal), OrderTakeProfit ()))
if (! OrderModify (OrderTicket (), AvgPrice, NDTP
(stopcal), OrderTakeProfit (), OrderExpiration (), Aqua))
Print ("Erro OrderModify", GetLastError ());
}
if (OrderType () == OP_SELL)
{
profit = NormalizeDouble ((AvgPrice + Ask) / pips, 0);
if (lucro <início)
continuar;
stoptrade = OrderStopLoss ();
stopcal = NDTP (Ask + stop * pips);
if (stoptrade == 0.0 || (stoptrade! = 0.0 && stopcal <stoptrade))
// --- modificar o pedido e sair
if (CheckStopLoss_Takeprofit (OP_SELL, stopcal,
OrderTakeProfit ()))
if (OrderModifyCheck (OrderTicket (), AvgPrice , NDTP
(stopcal), OrderTakeProfit ()))
if (! OrderModify (OrderTicket (), AvgPrice, NDTP
(stopcal), OrderTakeProfit (), OrderExpiration (), Vermelho))
Print ("Erro OrderModify", GetLastError ());
}
}
Sono (1000);
}
}
}
return (0);
}
// + ---------------------------------------------- -------------------- +
// + -------------------------- ---------------------------------------- +
// | Calcular compra de tamanho de lote ideal |
// + ----------------------------------------------- ------------------- +
double LotsOptimized (double lot)
{
int orders = OrdersHistoryTotal (); // histórico de pedidos totais
// --- volume mínimo permitido para operações de negociação
double minlot = SymbolInfoDouble (Symbol (), SYMBOL_VOLUME_MIN);
if (lote <minlot)
{
lote = minlot;
Print ("O volume é menor que o mínimo permitido, nós usamos", minlot);
}
// --- volume máximo permitido de operações de negociação
double maxlot = SymbolInfoDouble (Symbol (), SYMBOL_VOLUME_MAX);
if (lote> maxlot)
{
lote = maxlot;
Print ("O volume é maior que o máximo permitido, usamos", maxlot);
}
// --- obter passo mínimo de alteração de volume
double volume_step = SymbolInfoDouble (Symbol (), SYMBOL_VOLUME_STEP);
proporção interna = (int) MathRound (lote / passo_do_volume);
if (MathAbs (proporção * volume_etapa-lote)> 0,0000001)
{
lote = proporção * volume_etapa;
}
}
}
}
// + --------------------- --------------------------------------------- +
// + - -------------------------------------------------- --------------- +
// | exitsells () |
// + ----------------------------------------------- ------------------- +
void exitsells ()
{
for (int i = OrdersTotal () - 1; i> = 0; i--)
{
if (OrderSelect ( i, SELECT_BY_POS, MODE_TRADES))
{
}
}
// + --------------------------------------------- --------------------- +
// + ------------------------- -------------------------------------------------- +
// בדיקה אם יש עסקאות פתוחות בצמד הנוכחי
// + ------------------------------------- -------------------------------------- +
int openorderthispair (par de strings) // בוחרים עסקה בצמד המטבעות הנוכחי
{
total = 0;
for (int i = OrdersTotal () - 1; i> = 0; i--)
{
if (! OrderSelect (i, SELECT_BY_POS, MODE_TRADES))
Print ("eror"); // בודקים אם ישנה עסקה פתוחה בצמד הנוכחי
if (OrderSymbol () == pair)
total ++; // סופרים סך הכל עסקאות
}
return (total);
}
// ------------------------------------------------
-------------------------------------------------- ---------
// IfOrderDoesNotExistBuy
// + ----------------------------------- ---------------------------------------- +
int IfOrderDoesNotExistBuy ()
{
bool existe = false ;
for (int i = OrdersTotal (); i> = 0; i--)
{
return (0);
}
// ------------------------------------------------
-------------------------------------------------- ---------
// + -------------------------------------- ------------------------------------- +
// VERIFICAR Compra aberta
// + ---- -------------------------------------------------- ---------------------
+
int IfOrderopenBuy ()
{
for (int i = OrdersTotal () - 1; i> = 0; i--)
{
if ( OrderSelect (i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderType () == OP_BUY && OrderSymbol () == Symbol () && OrderComment
() == EAComment && OrderMagicNumber () == MagicNumber)
{
return (1);
}
}
}
return (0);
}
// ------------------------------------------------
-------------------------------------------------- ---------
// + -------------------------------------- ------------------------------------- +
// VERIFICAR Venda aberta
// + ---- -------------------------------------------------- ---------------------
+
int IfOrderopenSell ()
{
for (int i = OrdersTotal () - 1; i> = 0; i--)
{
if ( OrderSelect (i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderType () == OP_SELL && OrderSymbol () == Symbol () && OrderComment
() == EAComment && OrderMagicNumber () == MagicNumber)
{
return (1);
}
}
}
return (0);
}
// -----------------------------------------------
-------------------------------------------------- ---------
// + -------------------------------------- ---------------------------- +
// + ------------------ ------------------------------------------------ +
/ / | |
// + ----------------------------------------------- ------------------- +
int CountTrades ()
{
int count = 0;
for (int trade = OrdersTotal () - 1; trade> = 0; trade--)
{
if (! OrderSelect (trade, SELECT_BY_POS, MODE_TRADES))
Print ("Error");
if (OrderSymbol ()! = Symbol () || OrderMagicNumber ()! = MagicNumber)
continue;
if (OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber)
if (OrderType () == OP_SELL || OrderType () == OP_BUY)
count ++;
}
retorno (contagem);
}
// + ---------------------------------------------- -------------------- +
double AccountEquityHigh ()
{
if (CountTrades () == 0)
AccountEquityHighAmt = AccountEquity ();
if (AccountEquityHighAmt <PrevEquity)
AccountEquityHighAmt = PrevEquity;
else
AccountEquityHighAmt = AccountEquity ();
PrevEquity = AccountEquity ();
return (AccountEquityHighAmt);
}
// + ---------------------------------------------- -------------------- +
double CalculateProfit ()
{
double Profit = 0;
for (int cnt = OrdersTotal () - 1; cnt> = 0; cnt--)
{
if (! OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES))
Print ("Erro");
if (OrderSymbol ()! = Symbol () || OrderMagicNumber ()! = MagicNumber)
continue;
if (OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber)
if (OrderType () == OP_BUY || OrderType () == OP_SELL)
Profit + = OrderProfit ();
}
retorno (lucro);
}
// + ---------------------------------------------- -------------------- +
// + -------------------------- ---------------------------------------- +
// | |
// + ----------------------------------------------- ------------------- +
void CloseThisSymbolAll ()
{
for (int trade = OrdersTotal () - 1; trade> = 0; trade--)
{
if (! OrderSelect (comércio, SELECT_BY_POS, MODE_TRADES))
Imprimir ("Erro");
if (OrderSymbol () == Symbol ())
{
if (OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber)
{
if (OrderType () == OP_BUY)
if (! OrderClose (OrderTicket (), OrderLots (), Lance, 3, Azul))
Imprimir ("Erro");
if (OrderType () == OP_SELL)
if (! OrderClose (OrderTicket (), OrderLots (), Ask, 3, Red))
Print ("Erro");
}
Sono (1000);
}
}
}
// + -------------------------------------------- ---------------------- +
// + ------------------------ ------------------------------------------ +
// | saída () |
// + ----------------------------------------------- ------------------- +
void exit ()
{
for (int i = OrdersTotal () - 1; i> = 0; i--)
{
if (OrderSelect ( i, SELECT_BY_POS, MODE_TRADES))
{
// if (OrderType () == OP_SELL)
{
if ((Ask == OrderStopLoss ()) || Bid == OrderStopLoss ()) // Se um
pedido for fechado, feche todos
if (OrderType () == OP_SELL)
{
result = OrderClose (OrderTicket (), OrderLots (),
OrderClosePrice (), 3, Red); // fechamento do pedido real
if (result! = True) // se não foi fechado
{
err = GetLastError ();
Print ("LastError =", err); // descubra o motivo pelo qual não
fechou
}
}
else
if (OrderType () == OP_BUY)
{
result = OrderClose (OrderTicket (), OrderLots (),
OrderClosePrice (), 3, Red); // fechamento do pedido real
if (result! = true) // se não foi fechado
{
err = GetLastError ();
Print ("LastError =", err); // obter o motivo pelo qual não
fechou
}
}
}
}
}
}
// + -------------------- ---------------------------------------------- +
// + -------------------------------------------------- ---------------- +
// | Verificar os novos valores dos níveis antes da modificação da ordem |
// + ----------------------------------------------- ------------------- +
bool OrderModifyCheck (int ticket, double price, double sl, double tp)
{
// --- selecionar pedido por ticket
if (OrderSelect (ticket , SELECT_BY_TICKET))
{
// --- tamanho do ponto e nome do símbolo, para o qual um pedido pendente foi
colocado
string symbol = OrderSymbol ();
ponto duplo = SymbolInfoDouble (símbolo, SYMBOL_POINT);
// --- verificar se há mudanças no preço de abertura
bool PriceOpenChanged = true;
tipo int = OrderType ();
if (! (tipo == OP_BUY || tipo == OP_SELL))
{
PriceOpenChanged = (MathAbs (OrderOpenPrice () - preço)> ponto);
}
// --- verificar se há mudanças no nível de StopLoss
bool StopLossChanged = (MathAbs (OrderStopLoss () - sl)> point);
// --- verificar se há mudanças no nível de Takeprofit
bool TakeProfitChanged = (MathAbs (OrderTakeProfit () - tp)> point);
// --- se houver alguma mudança nos níveis
if (PriceOpenChanged || StopLossChanged || TakeProfitChanged)
return (true); // o pedido pode ser modificado
// --- não há mudanças nos níveis de Open, StopLoss e Takeprofit
mais
// --- notificar sobre o erro
PrintFormat ("Pedido #% d já tem níveis de Open =%. 5f SL =%. 5f TP =%. 5f
",
bilhete, OrderOpenPrice (), OrderStopLoss (), OrderTakeProfit
());
}
// --- chegou ao fim, sem alterações para a ordem
exit (); // CLOSE
return (false); // nenhum ponto em modificar
}
// + ---------------------------------------- -------------------------- +
// + -------------------- ---------------------------------------------- +
bool CheckStopLoss_Takeprofit ( ENUM_ORDER_TYPE type, double SL, double TP)
{
// --- obter o nível
SYMBOL_TRADE_STOPS_LEVEL int stops_level = (int) SymbolInfoInteger (_Symbol,
SYMBOL_TRADE_STOPS_LEVEL);
if (stops_level! = 0)
{
PrintFormat ("SYMBOL_TRADE_STOPS_LEVEL =% d: StopLoss e TakeProfit devem" +
"não estar mais próximos do que% d pontos do preço de
fechamento", stops_level, stops_level);
}
// ---
bool SL_check = false, TP_check = false;
// --- verificar apenas dois tipos de pedido
switch (tipo)
{
// ---
Caso de operação de compra ORDER_TYPE_BUY:
{
// --- verifique o StopLoss
SL_check = (Bid-SL> stops_level * _Point);
if (! SL_check)
PrintFormat ("Para pedido% s StopLoss =%. 5f deve ser menor que% .5f" +
"(Bid =%. 5f - SYMBOL_TRADE_STOPS_LEVEL =% d pontos)",
EnumToString (tipo), SL, Lance -stops_level * _Point, Bid,
stops_level);
// --- verificar o TakeProfit
TP_check = (TP-Bid> stops_level * _Point);
if (! TP_check)
PrintFormat ("Para o pedido% s TakeProfit =%. 5f deve ser maior que% .
5f" +
"(Lance =%. 5f + SYMBOL_TRADE_STOPS_LEVEL =% d pontos)",
EnumToString (tipo), TP, Lance + stops_level * _Point, Bid,
stops_level);
// --- retornar o resultado da verificação
return (SL_check && TP_check);
}
// ---
Caso de operação de venda ORDER_TYPE_SELL:
{
// --- verifique o StopLoss
SL_check = (SL-Ask> stops_level * _Point);
if (! SL_check)
PrintFormat ("Para pedido% s StopLoss =%. 5f deve ser maior que% .5f" +
"(Ask =%. 5f + SYMBOL_TRADE_STOPS_LEVEL =% d pontos)",
EnumToString (tipo), SL, Ask + stops_level * _Point, Ask,
stops_level);
// --- verificar o TakeProfit
TP_check = (Ask-TP> stops_level * _Point);
if (! TP_check)
PrintFormat ("Para pedido% s TakeProfit =%. 5f deve ser menor que% .5f"
+
"(Ask =%. 5f - SYMBOL_TRADE_STOPS_LEVEL =% d pontos)",
EnumToString (type), TP, Ask -stops_level * _Point, Ask,
stops_level);
// --- retornar o resultado da verificação
return (TP_check && SL_check);
}
pausa;
}
// --- uma função ligeiramente diferente é necessária para pedidos pendentes
return false;
}
// + ----------------------------------------------- ------------------- +
// + --------------------------- --------------------------------------- +