Binance Futures Library
- Bibliotecas
- Hadil Mutaqin SE
- Versión: 1.53
- Actualizado: 16 enero 2025
- Activaciones: 5
La librería se utiliza para desarrollar trading automático en el Mercado de Futuros Binance desde la plataforma MT5.
- Soporta Binance Futuros USD-M y COIN-M
- Soporta el modo Testnet
- Soporta todos los tipos de órdenes: Límite, Mercado, StopLimit, StopMarket, StopLoss y TakeProfit
- Muestra automáticamente el gráfico en la pantalla
Uso:
1. Abrir una cuenta demo MQL5
2. Descargue el archivo Header y el ejemplo de EA https://drive.google.com/uc?export=download&id=17fWrZFeMZoSvH9-2iv4WDJhcyxG2eW17
- Copie BinanceFutures.mqh a la carpeta \MQL5\Include
- Copie BinanceFuturesEA-Sample.mq5 a la carpeta \MQL5\Experts
3. Permitir WebRequest desde MT5 Herramientas menú >> Opciones >> Asesores Expertos y añadir URL:
https://testnet.binancefuture.com
4. Abra cualquier gráfico y adjunte BinanceFuturesEA-Sample al gráfico
Funciones de la Biblioteca de Futuros Binance:
Esta función debe ser llamada desde la función OnInit()
void init ( string symbol, // nombre del símbolo string historicalData, // historicalData: 1W = 1 semana, 1M = 1 mes, 3M = 3 meses, 6M = 6 meses, 1Y = 1 año string apiKey, // clave api binance string secretKey, // clave secreta de binance bool testnet = false // modo testnet );
Esta función debe ser llamada desde la función OnTimer()
void getTickData(); Esta función debe ser llamada desde la función OnDeinit()
void deinit(); La función utilizada para colocar la orden, devuelve orderId si tiene éxito, de lo contrario -1
long order ( ORDERTYPE orderType, // enum ORDERTYPE: COMPRA_MERCADO, VENTA_MERCADO, COMPRA_LIMITE, VENTA_LIMITE, COMPRA_STOP, VENTA_STOP, COMPRA_STOPLIMIT, VENTA_STOPLIMIT double quantity, // cantidad del pedido double limitPrice = 0, // precio límite de la orden double stopPrice = 0, // orden stopPrecio double stopLossPrice = 0, // precio stopLoss double takeProfitPrice = 0, // precio takeProfit string timeInForce = "GTC", // timeInForce: GTC, IOC, FOK, por defecto GTC string comment = "" // comentario de pedido );
Establecer stoploss y takeprofit, devuelve true si se ha realizado correctamente, false en caso contrario
bool setSLTP ( SIDE side, // enum SIDE: COMPRA, VENTA double stopLossPrice, // precio stopLoss double takeProfitPrice // precio de adquisición );
Cancelar órdenes abiertas, devuelve true si se ha ejecutado correctamente, false en caso contrario
bool cancelOrder ( long orderId = -1 // Id de orden, por defecto -1 cancelar todas las órdenes abiertas );
Cerrar posiciones abiertas, devuelve true si se ha realizado correctamente, false en caso contrario
bool closePosition ( SIDE side = -1 // enum SIDE: COMPRA, VENTA, por defecto -1 cerrar todas las posiciones abiertas );
Obtener información de la bolsa, devuelve la estructura ExchangeInfo si se ha realizado correctamente
void getExchangeInfo ( ExchangeInfo &exchangeInfo // [out] Estructura ExchangeInfo );
Obtener libro de órdenes, devuelve la estructura OrderBook si se ha ejecutado correctamente
void getOrderBook ( OrderBook &orderBook[], // [out] Matriz de la estructura OrderBook int limit = 5 // límite: 5, 10, 20, 50, 100, por defecto 5 );
Obtener órdenes abiertas, devuelve la estructura OpenOrders si se ha realizado correctamente
void getOpenOrders ( OpenOrders &openOrders[] // [out] matriz de la estructura OpenOrders );
Obtener posiciones abiertas, devuelve la estructura OpenPositions si se ha realizado correctamente
void getOpenPositions ( OpenPositions &openPositions[] // [out] matriz de la estructura OpenPositions );
Obtener el número de órdenes abiertas
int ordersTotal ( ORDERTYPE orderType = -1 // enum ORDERTYPE: BUY_LIMIT, SELL_LIMIT, BUY_STOP, SELL_STOP, BUY_STOPLIMIT, SELL_STOPLIMIT, por defecto -1 el número de todas las órdenes abiertas );
Obtener el número de posiciones abiertas
int positionsTotal ( SIDE side = -1 // enum SIDE: COMPRA, VENTA, por defecto -1 el número de todas las posiciones abiertas );
Establecer apalancamiento, devuelve true si tiene éxito, en caso contrario false
bool setLeverage ( int leverage // valor de apalancamiento );
Obtener el saldo disponible
double getBalance(); Establecer modo de posición de cobertura, devuelve true si se ha realizado correctamente, false en caso contrario
bool setHedgeMode();
Establecer modo de posición unidireccional, devuelve true si se ha realizado correctamente, false en caso contrario
bool setOneWayMode();
Establecer tipo de margen aislado, devuelve true si se ha realizado correctamente, en caso contrario false
bool setIsolatedMargin();
Establecer tipo de margen cruzado, devuelve true si se ha realizado correctamente, en caso contrario false
bool setCrossedMargin();
Ejemplo de cómo llamar a la Biblioteca de Futuros de Binance desde el EA
#include <BinanceFutures.mqh>
input string Symbol = "BTCUSDC";
input string HistoricalData = "1W";
input string ApiKey = "";
input string SecretKey = "";
BinanceFutures b;
int OnInit()
{
b.init(Symbol,HistoricalData,ApiKey,SecretKey);
return 0;
}
void OnTimer()
{
b.getTickData();
}
void OnDeinit(const int reason)
{
b.deinit();
}
void OnTick()
{
// Place buy market order
// b.order(BUY_MARKET,0.001);
// Place buy limit order
// b.order(BUY_LIMIT,0.001,75000);
// Place buy stop order
// b.order(BUY_STOP,0.001,0,115000);
// Place buy stoplimit order
// b.order(BUY_STOPLIMIT,0.001,110000,115000);
// Place sell market order
// b.order(SELL_MARKET,0.001);
// Place sell limit order
// b.order(SELL_LIMIT,0.001,115000);
// Place sell stop order
// b.order(SELL_STOP,0.001,0,75000);
// Place sell stoplimit order
// b.order(SELL_STOPLIMIT,0.001,80000,75000);
// Cancel all open orders
// b.cancelOrder();
// Close all open positions
// b.closePosition();
// Set leverage to 10x
// b.setLeverage(10);
// Set crossed margin type
// b.setCrossedMargin();
// Set isolated margin type
// b.setIsolatedMargin();
// Set hedge position Mode
// b.setHedgeMode();
// Set oneWay position Mode
// b.setOneWayMode();
// Get the number of all open orders
// int ordTotal = b.ordersTotal();
// Get the number of all open positions
// int posTotal = b.positionsTotal();
// Get available balance
// double balance = b.getBalance();
/* // Get exchangeInfo data
ExchangeInfo exchangeInfo;
b.getExchangeInfo(exchangeInfo);
double minQty = exchangeInfo.minQty;
double maxQty = exchangeInfo.maxQty;
double minNotional = exchangeInfo.minNotional;
int qtyDigit = exchangeInfo.qtyDigit;
int priceDigit = exchangeInfo.priceDigit;
int contractSize = exchangeInfo.contractSize;
*/
/* // Get orderBook data
OrderBook orderBook[];
b.getOrderBook(orderBook);
for(int i = 0; i < ArraySize(orderBook); i++)
{
double askPrice = orderBook[i].askPrice;
double askQty = orderBook[i].askQty;
double bidPrice = orderBook[i].bidPrice;
double bidQty = orderBook[i].bidQty;
}
*/
/* // Get open orders
OpenOrders openOrders[];
b.getOpenOrders(openOrders);
for(int i = 0; i < ArraySize(openOrders); i++)
{
bool closePosition = openOrders[i].closePosition;
if(closePosition == false)
{
long orderId = openOrders[i].orderId;
string symbol = openOrders[i].symbol;
string side = openOrders[i].side;
string positionSide = openOrders[i].positionSide;
string type = openOrders[i].type;
string status = openOrders[i].status;
string timeInForce = openOrders[i].timeInForce;
double price = openOrders[i].price;
double stopPrice = openOrders[i].stopPrice;
double avgPrice = openOrders[i].avgPrice;
double origQty = openOrders[i].origQty;
double executedQty = openOrders[i].executedQty;
ulong time = openOrders[i].time;
}
}
*/
/* // Get open positions
OpenPositions openPositions[];
b.getOpenPositions(openPositions);
for(int i = 0; i < ArraySize(openPositions); i++)
{
string symbol = openPositions[i].symbol;
string side = openPositions[i].side;
string positionSide = openPositions[i].positionSide;
double positionAmt = openPositions[i].positionAmt;
double entryPrice = openPositions[i].entryPrice;
double markPrice = openPositions[i].markPrice;
double unRealizedProfit = openPositions[i].unRealizedProfit;
double liquidationPrice = openPositions[i].liquidationPrice;
}
*/
}

