#include <Trade\Trade.mqh>
input double lotSize = 0.1;
// Variáveis globais para controle de ordens
bool orderOpened = false;
ulong orderTicket = 0;
// Variáveis para armazenar rompimento anterior
bool lastBreakoutAlta = false;
bool lastBreakoutBaixa = false;
double breakoutHigh = 0.0;
double breakoutLow = 0.0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configurações do EA
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Função de finalização
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Variáveis para bandas de Bollinger
double bollingerUpper[], bollingerLower[], bollingerMiddle[];
// Configurações das Bandas de Bollinger (período 20, desvio 2)
int bbPeriod = 20;
double bbDeviation = 2.0;
double slippage = 3 * _Point;
// Obtenção das Bandas de Bollinger
int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
// Verifique se o handle é válido
if (bbHandle == INVALID_HANDLE) {
Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
return;
}
// Inicializar os buffers das bandas de Bollinger
ArraySetAsSeries(bollingerUpper, true);
ArraySetAsSeries(bollingerMiddle, true);
ArraySetAsSeries(bollingerLower, true);
// Preencher os buffers
if (CopyBuffer(bbHandle, 0, 0, 1, bollingerUpper) <= 0 ||
CopyBuffer(bbHandle, 1, 0, 1, bollingerMiddle) <= 0 ||
CopyBuffer(bbHandle, 2, 0, 1, bollingerLower) <= 0) {
Print("Erro ao copiar buffer das Bandas de Bollinger: ", GetLastError());
return;
}
// Preço atual e range da vela
double priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
double priceLow = iLow(_Symbol, PERIOD_M2, 0);
double priceClose = iClose(_Symbol, PERIOD_M2, 0);
double range = priceHigh - priceLow;
// Objeto para enviar ordens
CTrade trade;
// Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionGetTicket(i) > 0)
{
ulong positionTicket = PositionGetTicket(i);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
// Verifica se a posição está no lucro e se o preço está perto da linha do meio
if (positionProfit > 0 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + slippage)
{
if (trade.PositionClose(positionTicket))
{
Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
}
else
{
Print("Erro ao fechar a posição: ", GetLastError());
}
}
}
}
// Atualizar informações de rompimento e confirmação
if (lastBreakoutAlta && priceClose > breakoutHigh)
{
double slBuy = priceClose - 10 * _Point;
if (trade.Buy(lotSize, _Symbol, slBuy))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de compra aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutAlta = false;
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
if (lastBreakoutBaixa && priceClose < breakoutLow)
{
double slSell = priceClose + 10 * _Point;
if (trade.Sell(lotSize, _Symbol, slSell))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de venda aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutBaixa = false;
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Verificar rompimento de alta
if (range >= 30 * _Point && priceClose > bollingerUpper[0]) {
lastBreakoutAlta = true;
breakoutHigh = priceHigh;
Print("Possível rompimento de alta detectado.");
}
// Verificar rompimento de baixa
if (range >= 30 * _Point && priceClose < bollingerLower[0]) {
lastBreakoutBaixa = true;
breakoutLow = priceLow;
Print("Possível rompimento de baixa detectado.");
}
// Gerenciamento de trailing stop
ManageTrailingStop();
}
//+------------------------------------------------------------------+
//| Gerenciamento de trailing stop |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
CTrade trade;
// Itera sobre todas as posições abertas
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionGetTicket(i) > 0)
{
ulong ticket = PositionGetTicket(i);
double currentSL = PositionGetDouble(POSITION_SL);
double currentTP = PositionGetDouble(POSITION_TP);
// Determina o low e high da última vela (PERIOD_M2)
double lastLow = iLow(_Symbol, PERIOD_M2, 1);
double lastHigh = iHigh(_Symbol, PERIOD_M2, 1);
// Verificar se é uma posição de compra aberta e atualizar Stop Loss
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
double newSL = lastLow - 2 * _Point;
if (newSL > currentSL || currentSL == 0.0)
{
trade.PositionModify(ticket, newSL, currentTP);
Print("Stop Loss atualizado para posição de compra.");
}
}
// Verificar se é uma posição de venda aberta e atualizar Stop Loss
else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
double newSL = lastHigh + 2 * _Point;
if (newSL < currentSL || currentSL == 0.0)
{
trade.PositionModify(ticket, newSL, currentTP);
Print("Stop Loss atualizado para posição de venda.");
}
}
}
}
}
faça meu codigo acima usar a mesmaa configuração de trilingstop do codigo abaixo onde o preço segue o fluxo e vai fechando quando vai pegar os lucros:
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#include <Trade/Trade.mqh>
CTrade trade;
CPositionInfo pos;
COrderInfo ord;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
input group "*** Trading Inputs ***"
input double RiskPercent = 3; // Risk as % of Trading capital)
input int Tppoints = 200; // Take Profit (10 points = 1 pip)
input int Slpoints = 200; // Stoploss Points (10 points = 1 pip)
input int TslTriggerPoints = 15; // Points in profit before Trailing SL is activated (10 points = 1 pip)
input int TslPoints = 10; // Trailing Stoploss (10 points = 1 pip)
input ENUM_TIMEFRAMES Timeframe = PERIOD_CURRENT; //Time frame to run
input int InpMagic = 298347; //EA indentification no
input string TradeComment = "Scalpin Robot";
enum StarHour { Inactive=0, _0100=1, _0200=2, _0300=3, _0400=4, _0500=5, _0600=6, _0700=7, _0800=8, _0900=9, _1000=10, _1100=11, _1200=12, _1300=13, _1400=14, _1500=15, _1600=16, _1700=17, _1800=18, _1900=19, _2000=20, _2100=21, _2200=22, _2300=23};
input StarHour SHInput=0; // Star Hour
enum EndHour { Inactive=0, _0100=1, _0200=2, _0300=3, _0400=4, _0500=5, _0600=6, _0700=7, _0800=8, _0900=9, _1000=10, _1100=11, _1200=12, _1300=13, _1400=14, _1500=15, _1600=16, _1700=17, _1800=18, _1900=19, _2000=20, _2100=21, _2200=22, _2300=23};
input EndHour EHInput=0; // End Hour
int SHChoice;
int EHChoice;
int BarsN = 5;
int ExpirationBars = 100;
int OrderDistPoints = 100;
int OnInit()
{
//---
//---
trade.SetExpertMagicNumber(InpMagic);
ChartSetInteger(0,CHART_SHOW_GRID,false);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
TrailStop();
if(!IsNewBar())return;
MqlDateTime time;
TimeToStruct(TimeCurrent(),time);
int Hournow = time.hour;
SHChoice = SHInput;
EHChoice = EHInput;
if(Hournow<SHChoice){CloseAllOrders(); return;}
if(Hournow>=EHChoice && EHChoice!=0){CloseAllOrders(); return;}
int BuyTotal=0;
int SellTotal=0;
for (int i=PositionsTotal()-1; i>=0; i--){
pos.SelectByIndex(i);
if(pos.PositionType()==POSITION_TYPE_BUY && pos.Symbol()==_Symbol && pos.Magic()==InpMagic) BuyTotal++;
if(pos.PositionType()==POSITION_TYPE_SELL && pos.Symbol()==_Symbol && pos.Magic()==InpMagic) SellTotal++;
}
for (int i=PositionsTotal()-1; i>=0; i--){
ord.SelectByIndex(i);
if(ord.OrderType()==ORDER_TYPE_BUY_STOP && ord.Symbol()==_Symbol && ord.Magic()==InpMagic) BuyTotal++;
if(ord.OrderType()==ORDER_TYPE_SELL_STOP && ord.Symbol()==_Symbol && ord.Magic()==InpMagic) SellTotal++;
}
if(BuyTotal <=0){
double high = findHigh();
if(high > 0){
SendBuyOrder(high);
}
}
if(SellTotal <=0){
double low = findLow();
if(low > 0){
SendSellOrder(low);
}
}
}
//+------------------------------------------------------------------+
double findHigh(){
double highestHigh = 0;
for(int i = 0; i < 200; i++){
double high = iHigh(_Symbol,Timeframe,i);
if(i > BarsN && iHighest(_Symbol,Timeframe,MODE_HIGH,BarsN*2+1,i-BarsN) == i){
if(high > highestHigh){
return high;
}
}
highestHigh = MathMax(high, highestHigh);
}
return -1;
}
double findLow(){
double LowestLow = DBL_MAX;
for(int i = 0; i <200; i++){
double Low = iLow(_Symbol,Timeframe,i);
if(i > BarsN && iLowest(_Symbol,Timeframe,MODE_LOW,BarsN*2+1,i-BarsN) == i){
if(Low > LowestLow){
return Low;
}
}
LowestLow = MathMin(Low, LowestLow);
}
return -1;
}
bool IsNewBar(){
static datetime previousTime = 0;
datetime currentTime = iTime(_Symbol,Timeframe,0);
if(previousTime!=currentTime){
previousTime=currentTime;
return true;
}
return false;
}
void SendBuyOrder(double entry){
double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
if(ask > entry - OrderDistPoints * _Point) return;
double tp = entry + Tppoints * _Point;
double sl = entry - Slpoints * _Point;
double lots = 0.01;
if(RiskPercent > 0) lots = calcLots(entry-sl);
datetime expiration = iTime(_Symbol,Timeframe,0) + ExpirationBars * PeriodSeconds(Timeframe);
trade.BuyStop(lots,entry,_Symbol,sl,tp,ORDER_TIME_SPECIFIED,expiration);
}
void SendSellOrder(double entry){
double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
if(bid < entry + OrderDistPoints *_Point) return;
double tp = entry - Tppoints*_Point;
double sl = entry + Slpoints*_Point;
double lots = 0.01;
if(RiskPercent > 0) lots = calcLots(sl-entry);
datetime expiration = iTime(_Symbol,Timeframe,0) + ExpirationBars * PeriodSeconds(Timeframe);
trade.SellStop(lots,entry,_Symbol,sl,tp,ORDER_TIME_SPECIFIED,expiration);
}
double calcLots(double slPoints){
double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
double ticksize =SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
double tickvalue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
double lotstep = SymbolInfoDouble( _Symbol,SYMBOL_VOLUME_STEP);
double minvolume=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
double maxvolume=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
double volumelimit = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_LIMIT);
double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
if(volumelimit!=0) lots = MathMin(lots,volumelimit);
if(maxvolume!=0) lots = MathMin(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX));
if(minvolume!=0) lots = MathMax(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN));
lots = NormalizeDouble(lots,2);
return lots;
}
void CloseAllOrders(){
for(int i=OrdersTotal()-1;i>=0;i--){
ord.SelectByIndex(i);
ulong ticket = ord.Ticket();
if(ord.Symbol()==_Symbol && ord.Magic()==InpMagic){
trade.OrderDelete(ticket);
}
}
}
void TrailStop() {
double sl = 0;
double tp = 0;
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--) {
if (pos.SelectByIndex(i)) {
ulong ticket = pos.Ticket();
if (pos.Magic() == InpMagic && pos.Symbol() == _Symbol) {
if (pos.PositionType() == POSITION_TYPE_BUY) {
if (bid - pos.PriceOpen() > TslTriggerPoints * _Point) {
tp = pos.TakeProfit();
sl = bid - (TslPoints * _Point);
if (sl > pos.StopLoss() && sl != 0) {
trade.PositionModify(ticket, sl, tp);
}
}
}
else if (pos.PositionType() == POSITION_TYPE_SELL) {
if (ask +(TslTriggerPoints* _Point)<pos.PriceOpen()){
tp = pos.TakeProfit();
sl = ask + (TslPoints * _Point);
if (sl > pos.StopLoss() && sl != 0) {
trade.PositionModify(ticket, sl, tp);
}
}
}
}
}
}
}