Você está na página 1de 19

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

// | MARTINGALE COMPRAR E VENDER |


// | Copyright 2018, MetaQuotes Software Corp. |
// | https://www.mql5.com |
// + ----------------------------------------------- ------------------- +
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property versão "1.01"
#property strict
/ * - Essas variáveis são mostradas no EA e podem ser alteradas - * /
extern bool UseTrailingStop = false;
externo duplo TrailStart = 10,0;
externo TrailStop duplo = 10,0;
extern bool Double_Lotsize = false;
extern double Lot_Size_Increment = 0.1;
extern int Take_Profit = 10;
extern int PipStep = 10;
extern double Lotsize = 0,1;
extern double Multiply = 2,0;
extern int MaxTrade = 4;
string de entrada str5 = "Média móvel rápida";
entrada int Período 1 = 1; // Média móvel rápida (em pips)
input string str6 = "Média móvel lenta";
entrada int Período2 = 50; // Média lenta (em pips)
extern bool CLOSEMAXORDERS = true; // Fechar pedidos máximos
extern int MagicNumber = 8095; // Número mágico
extern double TrailingStop = 40; // TrailingStop
extern bool UseEquityStop = FALSE; // Use Equity Stop
extern double TotalEquityRisk = 20.0; // Risco patrimonial total

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");

}
}

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


{
if (OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES))
if (OrderSymbol ()! = Symbol () || OrderMagicNumber ()! = MagicNumber)
continue;
if (OrderSymbol () == Symbol () && OrderMagicNumber () == MagicNumber)
{
if (OrderType () == OP_BUY || OrderType () == OP_SELL)
{
AveragePrice + = OrderOpenPrice () * OrderLots ();
Count + = OrderLots ();
}
}
}

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 - * /
{

if (iMA (Symbol (), 0, Period1, 0,0,0,1) <iMA (Symbol (), 0,


Period2,0,0,0,1)) // BUY
{return (1);}
else
if (iMA (Symbol (), 0, Period1 , 0,0,0,1)> iMA (Symbol (), 0,
Period2,0,0,0,1)) // SELL
{return (2);}
return (0);
}
// + ----------------------------------------------- ------------------- +
// + --------------------------- --------------------------------------- +
// | MARTINGALE_BUY |
// + ----------------------------------------------- ------------------- +
int MARTINGALE_BUY ()
{
/ * 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 (0);
}
}
} * /

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;

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


{
if (! OrderSelect (i, SELECT_BY_POS, MODE_TRADES))
Print ("eror"); // ‫בודקים אם ישנה עסקה פתוחה בצמד הנוכחי‬
if (OrderSymbol () == Symbol ())
total ++; // ‫סופרים סך הכל עסקאות‬
if (total> MaxTrade && CLOSEMAXORDERS == true)
{
exitbuys ();
return (0);
}
}
// if (! openorderthispair (Symbol ())> = 1)
// if (openorderthispair () == 0)
// if (OrdersTotal () == 0)
{
// + ------- -------------------------------------------------- ---------
+
// | / * - Ordem de compra - * / |
// + ----------------------------------------------- ------------------- +
if (((AccountStopoutMode () == 1) &&
(AccountFreeMarginCheck (Symbol (), OP_BUY, Lotsize)>
AccountStopoutLevel ()))
| | ((AccountStopoutMode () == 0) &&
((AccountEquity () / (AccountEquity () - AccountFreeMarginCheck
(Symbol (), OP_BUY, Lotsize)) * 100)> AccountStopoutLevel ())))
if (CheckMoneyForTrade (Symbol () , LotsOptimized (Lotsize), OP_BUY))
if (! OrderSend (Symbol (), OP_BUY, LotsOptimized (Lotsize), ND
(Ask), 3,0, NDTP (Ask + Take_Profit * pips), EAComment, MagicNumber))
Imprimir ( "eror", GetLastError ());

}
/ * - 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;

Spread = MarketInfo (Símbolo (), MODE_SPREAD);

para (iCount = 0; iCount <OrdersTotal (); iCount ++)


{

if (! OrderSelect (iCount, SELECT_BY_POS, MODE_TRADES))


Imprimir ("erro");

if (OrderType () == OP_BUY && OrderSymbol () == Symbol () && OrderComment ()


== EAComment && OrderMagicNumber () == MagicNumber)
{
if (LastOP == 0)
{
LastOP = OrderOpenPrice ();
}
if (LastOP> OrderOpenPrice ())
{
LastOP = OrderOpenPrice ();
}
if (LastLots <OrderLots ())
{
LastLots = OrderLots ();
}
LastIsBuy = TRUE;
iTotalBuy ++;

// Quando atinge o limite máximo de OP, OP não adiciona mais * /


if (iTotalBuy == MaxTrade)
{
if (CLOSEMAXORDERS == 1)
{
exitbuys ();
return (0);
}
}
}
}

/ * Se o preço for de tendência de baixa .... direção, verifique o lance (* /


if (LastIsBuy)
{
if (Bid <= LastOP- (Spread * pips) - (PipStep * pips))
{
if (((AccountStopoutMode () == 1) &&
(AccountFreeMarginCheck (Symbol (), OP_BUY, Lotsize)>
AccountStopoutLevel ()))
| | ((AccountStopoutMode () == 0) &&
((AccountEquity () / (AccountEquity () - AccountFreeMarginCheck
(Symbol (), OP_BUY, Lotsize)) * 100)> AccountStopoutLevel ())))
if (Double_Lotsize == false)
{
if (CheckMoneyForTrade (Symbol (), LotsOptimized (LastLots +
Lot_Size_Increment), OP_BUY))
if (! OrderSend (Symbol (), OP_BUY, LotsOptimized (LastLots +
Lot_Size_Increment), ND (Ask), 3,0, NDTP (Ask + Take_Profit * pips), EAComment,
MagicNumber))
Print ("eror",GetLastError ());
}
if (Double_Lotsize == TRUE)
{
if (CheckMoneyForTrade (Symbol (), LotsOptimized (Multiply * LastLots),
OP_BUY))
if (! OrderSend (Symbol (), OP_BUY, LotsOptimized (Multiply *
LastLots), ND (Ask), 3,0, NDTP (Ask + Take_Profit * pips), EAComment, MagicNumber))
Print ("eror", GetLastError ());
}
ModifyTPbuy ();
LastIsBuy = FALSE;
return (0);

}
}
exit (); // CLOSE
return (0);
}
// =======================================================
==========================================================
=================================================
// + ----------------------------------------------- ------------------- +
// | MARTINGALE_SELL |
// + ----------------------------------------------- ------------------- +
int MARTINGALE_SELL ()
{

/ * 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 (0);
}
}
} * /

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;

Comentário (EAName); // Mostra o nome EA na tela


/ * --Se não houver OP, execute as seguintes funções - * /
/ * - É aqui que você insere os indicadores de codificação para acionar o OP
- * /
for (int i = OrdersTotal () - 1; i> = 0; i--)
{
if (! OrderSelect (i, SELECT_BY_POS, MODE_TRADES))
Print ("eror"); // ‫בודקים אם ישנה עסקה פתוחה בצמד הנוכחי‬
if (OrderSymbol () == Symbol ())
total ++; / / ‫סופרים סך הכל עסקאות‬
if (total> MaxTrade && CLOSEMAXORDERS == true)
{
exitsells ();
return (0);
}
}
// if (! openorderthispair (Symbol ())> = 1)
// if (openorderthispair () == 0)
// if (OrdersTotal () == 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;

Spread = MarketInfo (Símbolo (), MODE_SPREAD);

para (iCount = 0; iCount <OrdersTotal (); iCount ++)


{

if (! OrderSelect (iCount, SELECT_BY_POS, MODE_TRADES))


Imprimir ("erro");

if (OrderType () == OP_SELL && OrderSymbol () == Symbol () && OrderComment ()


== EAComment &&

{
LastOP = OrderOpenPrice ();
}
if (LastOP <OrderOpenPrice ())
{
LastOP = OrderOpenPrice ();
}
if (LastLots <OrderLots ())
{
LastLots = OrderLots ();
}
LastIsBuy = FALSE;
iTotalSell ++;

// Quando atinge o limite máximo de OP, OP não adiciona mais * /


if (iTotalSell == MaxTrade) // {return (0);}
{
if (CLOSEMAXORDERS == 1)
{
exitsells ();
return (0);
}
}

/ * Se a direção for Preço de venda ...., verifique o valor de Ask (* /


if (! LastIsBuy)
{

if (Ask> = LastOP + (Spread * pips) + (PipStep * pips))

{
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;

/ * - Take Profit of the last Order - * /


for (iCount = 0; iCount <OrdersTotal (); iCount ++)
{
if (! OrderSelect (iCount, SELECT_BY_POS, MODE_TRADES))
Imprimir ("erro");

/ * - Se for OP - BUY, TP assume o menor valor. Faça TP juntos - * /


if (OrderType () == OP_BUY && OrderSymbol () == Symbol () && OrderComment ()
== EAComment && OrderMagicNumber () == MagicNumber)
{
if (NewTP == 0)
{
NewTP = OrderTakeProfit ();
}
if (NewTP> OrderTakeProfit ())
{
NewTP = OrderTakeProfit ();
}
}
}

/ * - Alterar todos os valores TakeProfit com o novo OP (2X) - * /


para (iCount = 0; iCount <OrdersTotal (); iCount ++)
{
if (! OrderSelect (iCount, SELECT_BY_POS, MODE_TRADES))
Imprimir ("erro");

/ * - Se todos os OP forem BUY, altere o TP - * /


if (OrderType () == OP_BUY && OrderSymbol () == Symbol () && OrderComment ()
== EAComment && OrderMagicNumber () == MagicNumber)
{
RefreshRates ( );
// stoploss = Bid- (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)> ponto)
if ((NewTP-Ask)> (int) SymbolInfoInteger (_Symbol,
SYMBOL_TRADE_FREEZE_LEVEL) * pips)
if (OrderModifyCheck (OrderTicket (), OrderOpenPrice (), 0, NewTP))
if (! OrderModify (OrderTicket (), OrderLots (), 0, NewTP, 0))
Imprimir ("erro");
}
}
exit (); // CLOSE
}
// ========================================
==========================================================
==================================================
// + --- -------------------------------------------------- ------------- +
// | MODIFICAR TOME LUCRO VENDA |
// + ----------------------------------------------- ------------------- +
/ * - A função ModifyTP é mudar todos os OP TP no mesmo ponto - * /
void ModifyTPsell ()
{
int iCount = 0;
NewTP duplo = 0;

/ * - Take Profit of the last Order - * /


for (iCount = 0; iCount <OrdersTotal (); iCount ++)
{
if (! OrderSelect (iCount, SELECT_BY_POS, MODE_TRADES))
Print ("eror");

/ * - Se for OP - SELL, TP obtém o maior valor. Faça TP juntos - * /


if (OrderType () == OP_SELL && OrderSymbol () == Symbol () && OrderComment ()
== EAComment && OrderMagicNumber () == MagicNumber)
{
if (NewTP == 0)
{
NewTP = OrderTakeProfit ();
}
if (NewTP <OrderTakeProfit ())
{
NewTP = OrderTakeProfit ();
}
}
}

/ * - Alterar todos os valores TakeProfit com o novo OP (2X) - * /


for (iCount = 0; iCount <OrdersTotal (); iCount ++)
{
if (! OrderSelect (iCount, SELECT_BY_POS, MODE_TRADES))
Imprimir ("eror");

/ * - Se todos os OP forem SELL, altere seu TP - * /


if (OrderType () == OP_SELL && OrderSymbol () == Symbol () && OrderComment ()
== EAComment && OrderMagicNumber () == MagicNumber)
{

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;

Imprimir ("O volume não é um múltiplo do passo mínimo, usamos o volume


correto mais próximo", proporção * volume_step);
}
exit (); // CLOSE
return (ND (lote));
}
// + ---------------------------------------------- -------------------- +
// | |
// + ----------------------------------------------- ------------------- +
NDTP duplo (val duplo)
{
RefreshRates ();
double FREEZELEVEL = MarketInfo (Symbol (), MODE_FREEZELEVEL);
SPREAD duplo = MarketInfo (Símbolo (), MODE_SPREAD);
StopLevel = MarketInfo (Symbol (), MODE_STOPLEVEL);
if (val <StopLevel * SetPoint + SPREAD * SetPoint + FREEZELEVEL * SetPoint)
val = StopLevel * SetPoint + SPREAD * SetPoint + FREEZELEVEL * SetPoint;
return (NormalizeDouble (val, Digits));
}
// + ---------------------------------------------- -------------------- +
bool CheckMoneyForTrade (string símbolo, lotes duplos, tipo int)
{
double free_margin = AccountFreeMarginCheck (símbolo, tipo, lotes);
if (free_margin <0)
{
string oper = (type == OP_BUY)? "Compra venda";
Print ("Dinheiro insuficiente para", oper, "", lotes, "", símbolo, "Código de
erro =", GetLastError ());
retorna falso);
}
// --- verificação bem-sucedida
return (true);
}
// + ---------------------------------------------- -------------------- +
// + ----------------------------------------------- ------------------- +
// | |
// + ----------------------------------------------- ------------------- +
double ND (double val)
{
return (NormalizeDouble (val, Digits));
}
// + ---------------------------------------------- -------------------- +
// | exitbuys () |
// + ----------------------------------------------- ------------------- +
void exitbuys ()
{
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)
{
result = OrderClose (OrderTicket (), OrderLots (), OrderClosePrice (),
3 , clrNONE);
if (result! = true) // se não fechou
{
err = GetLastError ();
Print ("LastError =", err); // obter o motivo pelo qual não fechou
}

}
}

}
}
// + --------------------- --------------------------------------------- +
// + - -------------------------------------------------- --------------- +
// | exitsells () |
// + ----------------------------------------------- ------------------- +
void exitsells ()
{
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)
{
result = OrderClose (OrderTicket (), OrderLots (), OrderClosePrice (),
3, clrNONE);
if (result! = true) // se não fechou
{
err = GetLastError ();
Print ("LastError =", err); // descubra o motivo pelo qual não

}
}
// + --------------------------------------------- --------------------- +
// + ------------------------- -------------------------------------------------- +
// ‫בדיקה אם יש עסקאות פתוחות בצמד הנוכחי‬
// + ------------------------------------- -------------------------------------- +
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--)
{

if (OrderSelect (i, SELECT_BY_POS) == true && OrderSymbol () == Symbol ())


{
exists = true;
return (existe);
}
else
{
Print ("OrderSelect () error -", (GetLastError ()));
}
}

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;
}
// + ----------------------------------------------- ------------------- +
// + --------------------------- --------------------------------------- +

Você também pode gostar