Obtén Partes de Código Para Crear Tus Robots
El sitio BotPulse Trading ofrece un directorio de códigos MQL5 (MetaQuotes Language 5), el lenguaje de programación utilizado para desarrollar Expert Advisors (EAs) en la plataforma MetaTrader 5 (MT5).

Categoría | Descripción | Contenido Destacado |
---|---|---|
Recursos principales | Directorio de códigos MQL5 para MetaTrader 5 | Códigos listos para usar Herramientas para automatización |
Tipos de contenido | Elementos programables para trading |
Expert Advisors (robots) Scripts operativos Bibliotecas de desarrollo |
Objetivo | Facilitar el trading automatizado | Repositorio comunitario Aprendizaje de MQL5 |
Contador de Posiciones (Compras & Ventas)
//+---Count Positions
int Position_buy_count;
int Position_sell_count;
input long MagicNumber = 47836; // ID of EA
void OnInit(){
// Codigo en OnInit
}
void OnTick(){
// Acceso a la variable
CountPositions();
//Uso de variable
Comment("Compras: "+(string)Position_buy_count+" || Ventas: "+Position_sell_count);
}
void CountPositions(){
//+-----------CONTAR POSICIONES ABIERTAS---------+//
Position_buy_count = 0; Position_sell_count = 0; //#1 initialize counts
for(int i = PositionsTotal() - 1 ; i >= 0 ; i--) //#2 not i <= 0
{
PositionGetTicket(i); //#3 Missing PositionGetTicket(i);
string PositionSimbol = PositionGetString(POSITION_SYMBOL);
long PositionMagicNumber=PositionGetInteger(POSITION_MAGIC);
string PositionComment =PositionGetString(POSITION_COMMENT);
double PositionOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double PositionLots = PositionGetDouble(POSITION_VOLUME);
//+-- CLOSE TRADES --+//
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && _Symbol==PositionSimbol && MagicNumber==PositionMagicNumber ) //#4 not PositionSelect(_Symbol)
{
Position_buy_count++;
}
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL && _Symbol==PositionSimbol && MagicNumber==PositionMagicNumber) //#4 not PositionSelect(_Symbol)
{
Position_sell_count++;
}
} // for loop end
}
Contar Ordenes Pendientes (LIMITS & STOPS)
int Order_buy_count = 0;
int Order_sell_count = 0;
input long MagicNumber = 47836; // ID of EA
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
ContarOrdenesAbiertas(); // Acceso a la función personalizada
Comment("Ordenes en Compr: "+(string)Order_buy_count+"Ordenes en Venta: "+(string)Order_sell_count);
}
//+------------------------------------------------------------------+
void ContarOrdenesAbiertas(){
// NOTA: PARA CONTAR ORDENES LIMIT USAR : ORDER_TYPE_BUY_LIMIT o ORDER_TYPE_SELL_LIMIT
//+-----------CONTAR ORDENES ABIERTAS---------+//
Order_buy_count = 0; Order_sell_count = 0; //#1 initialize counts
for(int i = OrdersTotal() - 1 ; i >= 0 ; i--) //#2 not i <= 0
{
OrderGetTicket(i); //#3 Missing PositionGetTicket(i);
string OrderSimbol = OrderGetString(ORDER_SYMBOL);
long OrderMagicNumber=OrderGetInteger(ORDER_MAGIC);
//+-- CLOSE TRADES --+//
if(OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY_STOP && _Symbol==OrderSimbol && MagicNumber==OrderMagicNumber ) //#4 not PositionSelect(_Symbol)
{
Order_buy_count++;
}
if(OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL_STOP && _Symbol==OrderSimbol && MagicNumber==OrderMagicNumber) //#4 not PositionSelect(_Symbol)
{
Order_sell_count++;
}
} // for loop end
//+-----------CONTAR ORDENES ABIERTAS---------+//
}
Acceder a Variable de Tiempo
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
MqlDateTime Time;
// Descomenta la zona horaria que deseas usar, quita las "//" del inicio
// TimeCurrent(Time); // Hora del Servidor(Broker)
// TimeGMT(Time); // Hora GMT + 0
// TimeLocal(Time); // Hora Local
Comment((string)Time.hour+" H"+(string)Time.min+" M"+(string)Time.min+" S");
}
//+------------------------------------------------------------------+
Cerrar Todas las Posiciones abiertas
#include <Trade/Trade.mqh>
CTrade trade;
//+---Count Positions
int Position_buy_count;
int Position_sell_count;
input long MagicNumber = 47836; // ID of EA
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
CloseAll(); // Cuando se llama a esta función se cierran todos los trades abiertos asignados a este robot
}
//+------------------------------------------------------------------+
void CloseAll()
{
while(Position_buy_count+Position_sell_count>0){
//+-----------CONTAR POSICIONES ABIERTAS---------+//
Position_buy_count = 0; Position_sell_count = 0; //#1 initialize counts
for(int i = PositionsTotal() - 1 ; i >= 0 ; i--) //#2 not i <= 0
{
PositionGetTicket(i); //#3 Missing PositionGetTicket(i);
string PositionSimbol = PositionGetString(POSITION_SYMBOL);
long PositionMagicNumber=PositionGetInteger(POSITION_MAGIC);
string PositionComment =PositionGetString(POSITION_COMMENT);
double PositionOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double PositionLots = PositionGetDouble(POSITION_VOLUME);
//+-- CLOSE TRADES --+//
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && _Symbol==PositionSimbol && MagicNumber==PositionMagicNumber ) //#4 not PositionSelect(_Symbol)
{
Position_buy_count++;
}
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL && _Symbol==PositionSimbol && MagicNumber==PositionMagicNumber) //#4 not PositionSelect(_Symbol)
{
Position_sell_count++;
}
} // for loop end
for (int i = PositionsTotal() - 1; i >= 0; i--) {
// Select the position by index
ulong positionTicket = PositionGetInteger(POSITION_TICKET);
string positionSymbol = PositionGetString(POSITION_SYMBOL);
long positionMagicNumber = PositionGetInteger(POSITION_MAGIC);
long positionType = PositionGetInteger(POSITION_TYPE); // Buy or Sell
// Check if the position matches the symbol and magic number
if (positionSymbol == _Symbol && positionMagicNumber == MagicNumber) {
if (positionType == POSITION_TYPE_BUY) {
trade.PositionClose(positionTicket); // Close Buy position
} else if (positionType == POSITION_TYPE_SELL) {
trade.PositionClose(positionTicket); // Close Sell position
}
}
}
}
return;
}
Acceder a datos de velas || High, Low, Open, Close, Highest, Lowest
input int NumeroVelasAtras = 1; // Velas hacia atrás
input int CantidadDeVelas =10; // Cantidad de velas para calcular HH, LL
input ENUM_TIMEFRAMES TF=PERIOD_H1;
void OnTick(){
double High = iHigh(_Symbol,TF,NumeroVelasAtras); // High de la vela elegida
double Low = iLow(_Symbol,TF,NumeroVelasAtras); // Low de la vela elegida
double Open = iOpen(_Symbol,TF,NumeroVelasAtras); // Open de la vela elegida
double Close = iClose(_Symbol,TF,NumeroVelasAtras); // Close de la vela elegida
double HH =iHigh(NULL,TF,iHighest(NULL,TF,MODE_HIGH,CantidadDeVelas,1)); // Higher High
double LL =iLow(NULL,TF,iLowest(NULL,TF,MODE_LOW,CantidadDeVelas,1)); // Lower Low
}
Calcular Lotes & SL/TP (Pips o Porcentaje)
#include <Trade/Trade.mqh>
CTrade trade;
enum Interes{
APY, //Interes Compuesto
APR //Interes Simple
};
enum TipoRiesgo{
Fijo, // Lotes fijos por trade
PorcentajeL // Riesgo en % del Balance
};
enum TypeSLTP{
Pips, //Calcular en Pips
Porcentaje //Calcular en Porcentaje
};
enum Tipo{
COMPRA, // Introducir Compra
VENTA // Introducir Venta
};
//+----Variables Globales del simbolo
double TickSize=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
double TickValue=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
double MinLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double MaxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double LotsLimit = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_LIMIT);
double LotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
int LotDigits;
//+---Fin varaibles globales del simbolo
//+---Variable de datos de cuenta
double BalanceInicial; // Balance inicial
input group "Parametros del Trade";
input long MagicNumber = 47836; // ID of EA
input Tipo TipoEntrada = COMPRA; // Compra o Venta
input TypeSLTP TypeStop = Pips; // Modo de Calcular TP / SL
input double TP=1.2548; // Take profit en Pips / %
input double SL= 50; // Stoploss en Pips / %
input group "Gestión de Riesgo";
input bool UnTrade=true; // (True) Solo 1 Trade Al dia, (false) 2 Trades Al día
input Interes Interes2 = APY; // Tipo de Interes
input TipoRiesgo Riesgo=PorcentajeL; // Tipo de Riesgo
input double Lotes=0.1; // Riesgo por trade (Fijo/%)
int OnInit(){
//+----Calcular digitos del simbolo y max y min volumen
if(MinLot == 0.001) LotDigits = 3;
if(MinLot == 0.01) LotDigits = 2;
if(MinLot == 0.1) LotDigits = 1;
if(LotsLimit==0) LotsLimit = MaxLot;
//+----Fin Calcular digitos del simbolo y max y min volumen
trade.SetExpertMagicNumber(MagicNumber);
BalanceInicial=AccountInfoDouble(ACCOUNT_BALANCE);
//+----Deteccion de errores en obtener datos de simbolo
if(TickSize==0 || TickValue==0 || LotStep==0){
Print(__FUNCTION__, "> Tamaño de Lotes no puede ser calculado...");
return(INIT_FAILED);
}
//+--Fin Deteccion de errores en obtener datos de simbolo
return(INIT_SUCCEEDED);
}
void OnTick(){
double BalanceActual = AccountInfoDouble(ACCOUNT_BALANCE);
double Ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
double Bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
double Balance=0;
if(Interes2==APR)Balance=BalanceInicial;
if(Interes2==APY)Balance=BalanceActual;
if(TipoEntrada==COMPRA){
double SLprice=0;
double SLbuy=0;
double TPprice=0;
double TPbuy=0;
double volume=0;
if(TypeStop==Pips){
SLprice = SL * _Point * ((_Digits == 5 || _Digits == 3) ? 10.0 : 1.0);
SLbuy = Ask - SLprice;
TPprice = TP * _Point * ((_Digits == 5 || _Digits == 3) ? 10.0 : 1.0);
TPbuy = Ask + TPprice;
}
if(TypeStop==Porcentaje){
SLbuy = Ask - (Ask*SL/100) ;
TPbuy = Ask + (Ask*TP/100) ;
}
if(Riesgo==PorcentajeL){
double MoneyLotStep = ((Ask - SLbuy)/TickSize) * TickValue * LotStep;
double MoneyRisk =NormalizeDouble(Lotes/100*Balance,2);
if(MoneyLotStep == 0)return;
volume=NormalizeDouble((MoneyRisk / MoneyLotStep * LotStep),LotDigits);
}
if(Riesgo==Fijo){
volume=NormalizeDouble(Lotes,LotDigits);
}
if(volume>MaxLot)volume=MaxLot;
if(volume<MinLot)volume=MinLot;
if(TP==0)TPbuy=0;
if(SL==0)SLbuy=0;
//trade.BuyStop(volume,HH,_Symbol,SLbuy,TPbuy,NULL,NULL,comentario);
}else{
double SLprice=0;
double SLsell=0;
double TPprice=0;
double TPsell=0;
double volume=0;
if(TypeStop==Pips){
SLprice = SL * _Point * ((_Digits == 5 || _Digits == 3) ? 10.0 : 1.0);
SLsell = Bid + SLprice;
TPprice = TP * _Point * ((_Digits == 5 || _Digits == 3) ? 10.0 : 1.0);
TPsell = Bid - TPprice;
}
if(TypeStop==Porcentaje){
SLsell = Bid + (Bid*SL/100) ;
TPsell = Bid - (Bid*TP/100) ;
}
if(Riesgo==PorcentajeL){
double MoneyLotStep = ( (SLsell-Bid)/TickSize) * TickValue * LotStep;
double MoneyRisk = Lotes/100*Balance;
if(MoneyLotStep == 0)return;
volume=NormalizeDouble((MoneyRisk / MoneyLotStep * LotStep),LotDigits);
}
if(Riesgo==Fijo){
volume=NormalizeDouble(Lotes,LotDigits);
}
if(volume>MaxLot)volume=MaxLot;
if(volume<MinLot)volume=MinLot;
if(TP==0)TPsell=0;
if(SL==0)SLsell=0;
//trade.SellStop(volume, Bid,_Symbol,SLsell,TPsell,NULL,NULL,comentario);
}
}
Obtener Flotante ($) del Robot
double totalProfit=0; // Variable para almacenar el flotante actual de Robot
input long MagicNumber=7483; // ID del Robot
int OnInit(){
Print("Robot Cargado Correctamente...");
return(INIT_SUCCEEDED);
}
void OnTick(){
GetCurrentProfit();
Comment("Flotante Actual = "+(string)totalProfit);
}
double GetCurrentProfit()
{
totalProfit = 0.0;
for(int i = PositionsTotal() - 1 ; i >= 0 ; i--) //#2 not i <= 0
{
PositionGetTicket(i); //#3 Missing PositionGetTicket(i);
string positionSymbol = PositionGetString(POSITION_SYMBOL);
long positionMagicNumber = PositionGetInteger(POSITION_MAGIC);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionSwap = PositionGetDouble(POSITION_SWAP);
double positionVolume = PositionGetDouble(POSITION_VOLUME);
double Comission = -(positionVolume*7); // El 7 hace referencia a la comsion por volumen de tu broker , es posible que tengas que cambiarlo para obtener el dato mas preciso.
// Filter by symbol and magic number
if (positionSymbol == _Symbol && positionMagicNumber == MagicNumber)
{
totalProfit += positionProfit+positionSwap+Comission;
}
}
return totalProfit;
}
Obtener Volumen (Lotes) del total de entradas que tiene el Robot
double Total_Volume=0; // Variable para almacenar el volumen actual de Robot
input long MagicNumber=7483; // ID del Robot
int OnInit(){
Print("Robot Cargado Correctamente...");
return(INIT_SUCCEEDED);
}
void OnTick(){
CheckTotalVolume();
Comment("Volumen Actual = "+(string)Total_Volume);
}
//+------check total volume--------+//
double CheckTotalVolume()
{
Total_Volume=0;
double deal_commission=0;
for(int i=0; i<PositionsTotal(); i++)
{
ulong position_ticket=PositionGetTicket(i); // ticket of the position
ulong magic=PositionGetInteger(POSITION_MAGIC);
long PositionType=PositionGetInteger(POSITION_TYPE);
double Volume=PositionGetDouble(POSITION_VOLUME);
// MAGICNUMBERI of the position
// position comment
long position_ID=PositionGetInteger(POSITION_IDENTIFIER); // Identifier of the position
if(magic==MagicNumber)
{
HistorySelect(POSITION_TIME,TimeCurrent());
for(int j=0; j<HistoryDealsTotal(); j++)
{
ulong deal_ticket=HistoryDealGetTicket(j);
if(HistoryDealGetInteger(deal_ticket,DEAL_POSITION_ID) == position_ID)
{
deal_commission=HistoryDealGetDouble(deal_ticket, DEAL_COMMISSION)*2;
break;
}
}
if(PositionType==POSITION_TYPE_BUY || PositionType==POSITION_TYPE_SELL ){
Total_Volume+=Volume;
}
}
}
return(Total_Volume);
}
Enviar Notificación Telegram
input group ">--- ✉️ TELEGRAM SETTINGS ---<";
input string apikey="6427004400:AAExeaPZ5NDFMwTeKTw-w9gugA967SeXXvA"; // API del Bot de Telegram
input string chatid="-4217238640"; // ID del Chat de Telegram / Añadir -100 delante si es un canal o el @xxxxxx
string base_url="https://api.telegram.org";
string cookie=NULL,headers;
char post[],resulttg[];
int restg;
string url=base_url+"/bot"+apikey+"/sendMessage?chat_id="+chatid+"&text=";
int OnInit(){
restg=WebRequest("GET",url+" Bot Pulse "+_Symbol+"%0A%0AEstado: Habilitado ✅",cookie,NULL,0,post,0,resulttg,headers);
return(INIT_SUCCEEDED);
}
Usar Indicador Bollinger Bands
#define NL "\n"
//+----Declaration of Bollinger Bands
int BollingerBands;
input group ">---⚙️ Setting Bollinger Bands";
input int Periods = 10; // Periods of Bollinger Bands
input ENUM_TIMEFRAMES TF=PERIOD_H1; // TimeFrame Bollinger Bands
int OnInit()
{
BollingerBands = iBands(_Symbol,TF,Periods,0,2,PRICE_CLOSE);
if(BollingerBands==INVALID_HANDLE){
Print("Bollinger Bands can't be Loaded...");
return(INIT_FAILED);
}
return(INIT_SUCCEEDED);
}
void OnTick(){
//create an array for several prices
double MiddleBandArray[];
double UpperBandArray[];
double LowerBandArray[];
//sort the price array from the cuurent candle downwards
ArraySetAsSeries(MiddleBandArray,true);
ArraySetAsSeries(UpperBandArray,true);
ArraySetAsSeries(LowerBandArray,true);
//copy price info into the array
CopyBuffer(BollingerBands,0,0,3,MiddleBandArray);
CopyBuffer(BollingerBands,1,0,3,UpperBandArray);
CopyBuffer(BollingerBands,2,0,3,LowerBandArray);
//calcualte EA for the cuurent candle
double MiddleBandValue=MiddleBandArray[0];
double UpperBandValue=UpperBandArray[0];
double LowerBandValue=LowerBandArray[0];
Comment("Banda Superior: "+(string)UpperBandValue+"\nBanda Media: "+(string)MiddleBandValue+"\nBanda Inferior: "+LowerBandValue);
}
Introducir Trade (Mercado, Limit o Stop)
#include <Trade\Trade.mqh> // Library to Management Orders
CTrade trade;
input double Lotes = 0.01; // Lotes del Trade
input double PrecioEntrada = 1.00; // Precio De Entrada(Ajustar a cada Tipo)
input double SL = 1.00; // Precio De StopLoss(Ajustar)
input double TP = 1.00; // Precio De TakeProfit(Ajustar)
input
int OnInit()
{
// Funciones On Init
return(INIT_SUCCEEDED);
}
void OnTick(){
double Ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
double Bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
//Ordenes Pendientes STOP, el precio CRUZA y Continua esa direccion
//trade.BuyStop(Lotes,PrecioEntrada,_Symbol,SL,TP,NULL,NULL,"Compra STOP");
//trade.SellStop(Lotes,PrecioEntrada,_Symbol,SL,TP,NULL,NULL,"Venta STOP");
//Ordenes Pendientes Limit, el precio TOCA y Se da Cambia la direccion
//trade.BuyLimit(Lotes,PrecioEntrada,_Symbol,SL,TP,NULL,NULL,"Compra Limite");
//trade.SellLimit(Lotes,PrecioEntrada,_Symbol,SL,TP,NULL,NULL,"Venta Limite");
//Posiciones Mercado, Se ejecuta de forma inmediata
//trade.Buy(Lotes,_Symbol,Ask,0,0,"Compra a Mercado");
//trade.Sell(Lotes,_Symbol,Bid,0,0,"Venta a Mercado");
}