Bybit EA Connection Library Documentation for MT5

6 February 2026, 12:20
Rajesh Kumar Nait
0
22

Product URL  : https://www.mql5.com/en/market/product/164455

Documentation of Bybit API URL: https://bybit-exchange.github.io/docs/v5/guide






Tutorial 1 : Trading Operations



Script Demo :

Note : Once you purchased the Library, It will be found under Scripts/Market Folder


///+-----------------------------------------------------------------+
//|                                                Library_Bybit.mq5 |
//|                                Copyright 2026, Rajesh Kumar Nait |
//|                  https://www.mql5.com/en/users/rajeshnait/seller |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Rajesh Kumar Nait"
#property link      "https://www.mql5.com/en/users/rajeshnait/seller"
#property version   "1.00"
#property description "Uncomment code which is required"

#include <Custom/Crypto_Charting/JAson.mqh>
CJAVal jv(NULL, jtUNDEF);
struct BybitConfig {
   string            api_url;
   string            api_key;
   string            api_secret;
   string            api_suffix;
   string            symbol_prefix;
   string            category;
   string            isLeverage;
   bool              debug;
};

#import "..\Libraries\Library_Bybit_new.ex5"
void Bybit_Init(BybitConfig &config);
string GetTime();
string Get_exchangeInfo();
//+------------------------------------------------------------------+
//| Limit Orders                                                     |
//+------------------------------------------------------------------+
string orderLimit(string symbol, string side, double quantity, double price);
string orderAmend(string symbol, string orderId, double qty, double price);

//+------------------------------------------------------------------+
//| Market Orders                                                    |
//+------------------------------------------------------------------+

string orderMarket(string symbol, string side, double quantity);

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string setTradingStop(string symbol, string slTrigger, string tpTrigger);
//+------------------------------------------------------------------+
//| Hedge Mode (for futures)                                         |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Cancel Order                                                     |
//+------------------------------------------------------------------+
string orderCancel(string symbol, string orderId);
string orderCancelAll(string symbol);
//+------------------------------------------------------------------+
//| Order queries                                                    |
//+------------------------------------------------------------------+
string orderRealtime(  string symbol, string orderId, string openOnly);
string orderHistory(   string symbol, string orderId, string execType, string startTime, string endTime, string cursor);
string tradeHistory(   string symbol, string orderId, string orderStatus, string startTime, string endTime, string cursor);
//+------------------------------------------------------------------+
//| Balance and Account Info                                         |
//+------------------------------------------------------------------+
string getWalletBalance(string accountType);
string setLeverage(string symbol, string buyLeverage, string sellLeverage);
//+------------------------------------------------------------------+
//| Change Leverage and Margin (Futures)                             |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Position Info (Futures)                                          |
//+------------------------------------------------------------------+
string getPositionMode(string symbol, string cursor);
//+------------------------------------------------------------------+
//| Create Symbols                                                   |
//+------------------------------------------------------------------+
void CreateSymbols_Bybit();

//+------------------------------------------------------------------+
//| Update Historical Data from API                                  |
//+------------------------------------------------------------------+
void RunUpdate(string symbol, datetime StartDateTime);
#import

bool Bybit_debug = true; // Debug will print messages in expert tab for troubleshooting
//+------------------------------------------------------------------+
//| Config                                                           |
//+------------------------------------------------------------------+

string Bybit_Key     = "L51zfkjJZOCdF3ufip"; //Bybit's API key
string Bybit_Secret  = "txnyks6V3dkyhUWWY64l5ay02B0V6V5MNNZa"; //Bybit Spot's API secret
//string Bybit_URL  = "https://api.bybit.com"; // API URL
string Bybit_URL  = "https://api-testnet.bybit.com"; // API URL
string Bybit_suffix = "/v5/"; // API Suffix (Do not edit)
string Bybit_SymbolPrefix = "bf_"; // Symbol Prefix
string category = "linear"; //Product type linear, inverse, spot, option
string isLeverage = "1"; // isLeverage: 0(default): false, spot trading 1: true, margin trading, make sure you turn on margin trading, and set the relevant currency as collateral
//+------------------------------------------------------------------+
//|  Other Config                                                    |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Symbols and Chart                                                |
//+------------------------------------------------------------------+

datetime MaxDate= D'2026-2-1 00:00:00'; //Max Datetime for History

string sym;
//Init API
BybitConfig config;


//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnStart() {
//---

   config.api_url = Bybit_URL;
   config.api_key = Bybit_Key;
   config.api_secret = Bybit_Secret;
   config.api_suffix = Bybit_suffix;
   config.symbol_prefix = Bybit_SymbolPrefix;
   config.debug = Bybit_debug;
   config.category = category;
   config.isLeverage = isLeverage;

   Bybit_Init(config);


//Add your codes here

////5. Realtime Query Order showing Example of orderCancel and orderAmemd
//   string s = orderRealtime("BTCUSDT", "", "0");
//   jv.Deserialize(s);
//
//// --- category
//   string cat = jv["result"]["category"].ToStr();
//   Print("Cat is : ", cat);
//
//// --- list size safety check
//   int total = jv["result"]["list"].Size();
//   Print("Total Orders : ", total);
//
//   if(total == 0) {
//      Print("No active orders");
//      return;
//   }
//
//// --- loop through orders
//   for(int i = 0; i < total; i++) {
//      string symbol       = jv["result"]["list"][i]["symbol"].ToStr();
//      string orderType    = jv["result"]["list"][i]["orderType"].ToStr();
//      string orderId      = jv["result"]["list"][i]["orderId"].ToStr();
//      string price        = jv["result"]["list"][i]["price"].ToStr();
//      string qty          = jv["result"]["list"][i]["qty"].ToStr();
//      string side         = jv["result"]["list"][i]["side"].ToStr();
//      string orderStatus  = jv["result"]["list"][i]["orderStatus"].ToStr();
//      string triggerPrice = jv["result"]["list"][i]["triggerPrice"].ToStr();
//      string takeProfit   = jv["result"]["list"][i]["takeProfit"].ToStr();
//      string stopLoss     = jv["result"]["list"][i]["stopLoss"].ToStr();
//
//
//      Print("------------ ORDER ", i, " ------------");
//      Print("Symbol       : ", symbol);
//      Print("OrderType    : ", orderType);
//      Print("OrderId      : ", orderId);
//      Print("Price        : ", price);
//      Print("Qty          : ", qty);
//      Print("Side         : ", side);
//      Print("Status       : ", orderStatus);
//      Print("TP           : ", takeProfit);
//      Print("SL           : ", stopLoss);
//orderCancel("BTCUSDT",  orderId);
//      // --- any condition
//      if(cat == category && orderType == "Limit" && orderStatus=="NEW") {
//         Print("MATCHED LIMIT ORDER: ", orderId);
//         
//         // orderAmend(symbol, orderId, 0.005, 71642.00);
//      }
//   }

//+------------------------------------------------------------------+
//| Get info of MODES                                                |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| ORDER PLACEMENT                                                  |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| LIMIT ORDERS                                                     |
//+------------------------------------------------------------------+

// Send Limit Order : Symbol,Side,Size,Price
//orderLimit("BTCUSDT","Buy",0.001,65500.50);

//+------------------------------------------------------------------+
//| AMEND LIMIT ORDERS                                               |
//+------------------------------------------------------------------+

// Amend Order
// orderAmend(symbol, orderId, qty, price);

//+------------------------------------------------------------------+
//| MARKET ORDERS                                                    |
//+------------------------------------------------------------------+

// Send Market Order : Symbol,Side,Size,Receive Window,Reduce Only
 //orderMarket("BTCUSDT","Sell",0.001);


//+------------------------------------------------------------------+
//| Hedge mode : LIMIT ORDERS  LONG or SHORT                        |
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//| Hedge mode : MARKET ORDERS  LONG or SHORT                        |
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//| CANCEL ORDERS                                                    |
//+------------------------------------------------------------------+

// Cancel Order
//orderCancel("BTCUSDT", "c277611d");
// Cancel All Orders
//orderCancelAll(string symbol)

//+------------------------------------------------------------------+
//|  ACCOUNT INFO                                                    |
//+------------------------------------------------------------------+
//getWalletBalance("UNIFIED");

//Example
//string s = getWalletBalance("UNIFIED");
//jv.Deserialize(s);
//
//for(int i=0; i<jv["result"]["list"].Size(); i++)
//{
//   Print("Balance : ", jv["result"]["list"][i]["totalWalletBalance"].ToStr());
//}
//
//

//+------------------------------------------------------------------+
//| QUERY ORDERS HISTORY                                             |
//+------------------------------------------------------------------+

// orderRealtime("BTCUSDT", "", "0");


//+------------------------------------------------------------------+
//| POSITION INFO                                                    |
//+------------------------------------------------------------------+
//string s = getPositionMode("BTCUSDT","");
//jv.Deserialize(s);
//
//for(int i=0; i<jv["result"]["list"].Size(); i++)
//{
//   Print("Symbol      : ", jv["result"]["list"][i]["symbol"].ToStr());
//   Print("Leverage      : ", jv["result"]["list"][i]["leverage"].ToStr());
//   Print("BreakEvenPrice      : ", jv["result"]["list"][i]["breakEvenPrice"].ToStr());
//   Print("AveragePrice      : ", jv["result"]["list"][i]["avgPrice"].ToStr());
//   Print("Liquidation Price      : ", jv["result"]["list"][i]["liqPrice"].ToStr());
//   Print("Take Profit      : ", jv["result"]["list"][i]["takeProfit"].ToStr());
//   Print("Position Value      : ", jv["result"]["list"][i]["positionValue"].ToStr());
//   Print("Unrealised PnL      : ", jv["result"]["list"][i]["unrealisedPnl"].ToStr());
//   Print("Mark Price     : ", jv["result"]["list"][i]["markPrice"].ToStr());
//
//   Print("Side      : ", jv["result"]["list"][i]["side"].ToStr());
//   Print("Size      : ", jv["result"]["list"][i]["size"].ToStr());
//   Print("positionStatus: ", jv["result"]["list"][i]["positionStatus"].ToStr());
//}

//+------------------------------------------------------------------+
//| SET LEVERAGE                                                     |
//+------------------------------------------------------------------+
//string s = setLeverage("BTCUSDT",20,20);
//jv.Deserialize(s);
//Print(s);

//+------------------------------------------------------------------+
//| SEND SL TP                                                       |
//+------------------------------------------------------------------+
orderMarket("BTCUSDT","Buy",0.002);
Sleep(10000);
setTradingStop("BTCUSDT","60000.00","70000.00");

//+------------------------------------------------------------------+
//| CHARTS                                                           |
//+------------------------------------------------------------------+

//1. Create Symbols (MUST RUN ONLY ONCE) :

//CreateSymbols_Bybit(); // It will create symbols as per category selected e.g. linear, inverse etc


//2. Run History Updater
//string syms = RemovePrefixFromSymbol();
// RunUpdate(syms, MaxDate);


}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string RemovePrefixFromSymbol() { // example of removal 2 digit symbol prefix, adjust as needed
//---
   sym = _Symbol;
   string prefix = "bf_"; //  (Change as required)
   int length = 2; // length of prefix is 2 in case of Futures and 3 in case of Spot (Change as required)
   string resultString;

   if(StringSubstr(sym, 0, length) == prefix) {
      resultString = StringSubstr(sym, length);
      return resultString;
   } else {
      resultString = sym;
      return NULL;
   }

// Output the result for testing
//Print("Result String: ", resultString);

   return NULL;

}

//+------------------------------------------------------------------+
//| EXAMPLES OF CANCEL AND AMEND ORDERS                              |
//+------------------------------------------------------------------+



//+------------------------------------------------------------------+
//|  QUERY ORDERS HISTORY EXAMPLE                                    |
//+------------------------------------------------------------------+

//orderHistory(  string symbol, string orderId, string orderStatus, string startTime, string endTime, string cursor);


//   string s = orderHistory("BTCUSDT", "", "", "", "", "");
//   jv.Deserialize(s);
//// --- Basic checks
//   if(jv["retCode"].ToInt() != 0) {
//      Print("OrderHistory error: ", jv["retMsg"].ToStr());
//      return;
//   }
//
//// --- Top-level info
//   string category = jv["result"]["category"].ToStr();
//   string cursor   = jv["result"]["nextPageCursor"].ToStr();
//
//   Print("Category         : ", category);
//   Print("NextPageCursor   : ", cursor);
//
//// --- Orders list
//   CJAVal orders = jv["result"]["list"];
//   int total = orders.Size();
//
//   Print("Total Orders     : ", total);
//   Print("------------------------------------");
//
//   for(int i = 0; i < total; i++) {
//      CJAVal o = orders[i];
//
//      string symbol        = o["symbol"].ToStr();
//      string orderId       = o["orderId"].ToStr();
//      string orderType     = o["orderType"].ToStr();
//      string side          = o["side"].ToStr();
//      string orderStatus   = o["orderStatus"].ToStr();
//      string cancelType    = o["cancelType"].ToStr();
//      string price         = o["price"].ToStr();
//      string qty           = o["qty"].ToStr();
//      string avgPrice      = o["avgPrice"].ToStr();
//      string cumExecQty    = o["cumExecQty"].ToStr();
//      string cumExecValue  = o["cumExecValue"].ToStr();
//      string cumExecFee    = o["cumExecFee"].ToStr();
//      string reduceOnly    = o["reduceOnly"].ToStr();
//      string timeInForce   = o["timeInForce"].ToStr();
//      string createType    = o["createType"].ToStr();
//      string createdTime   = o["createdTime"].ToStr();
//      string updatedTime   = o["updatedTime"].ToStr();
//
//      // --- Pretty print
//      Print("Order #", i);
//      Print(" Symbol        : ", symbol);
//      Print(" OrderId       : ", orderId);
//      Print(" Type / Side   : ", orderType, " / ", side);
//      Print(" Status        : ", orderStatus);
//      Print(" CancelType    : ", cancelType);
//      Print(" Price         : ", price);
//      Print(" Qty           : ", qty);
//      Print(" AvgPrice      : ", avgPrice);
//      Print(" ExecQty       : ", cumExecQty);
//      Print(" ExecValue     : ", cumExecValue);
//      Print(" ExecFee       : ", cumExecFee);
//      Print(" ReduceOnly    : ", reduceOnly);
//      Print(" TIF           : ", timeInForce);
//      Print(" CreateType    : ", createType);
//      Print(" CreatedTime   : ", createdTime);
//      Print(" UpdatedTime   : ", updatedTime);
//      Print("------------------------------------");
//   }

//+------------------------------------------------------------------+
//| QUERY TRADE HISTORY EXAMPLE                                      |
//+------------------------------------------------------------------+

//tradeHistory( string symbol, string orderId, string execType, string startTime, string endTime, string cursor);
//
//   string s = tradeHistory("BTCUSDT", "", "Trade", "", "", "");
//   jv.Deserialize(s);
//
//   Print(s);
//
//// --- Basic validation
//   if(jv["retCode"].ToInt() != 0) {
//      Print("TradeHistory error: ", jv["retMsg"].ToStr());
//      return;
//   }
//
//// --- Top-level info
//   string category = jv["result"]["category"].ToStr();
//   string cursor   = jv["result"]["nextPageCursor"].ToStr();
//
//   Print("Category         : ", category);
//   Print("NextPageCursor   : ", cursor);
//
//// --- Execution list
//   CJAVal execs = jv["result"]["list"];
//   int total = execs.Size();
//
//   Print("Total Executions : ", total);
//   Print("====================================");
//
//   for(int i = 0; i < total; i++) {
//      CJAVal e = execs[i];
//
//      string symbol       = e["symbol"].ToStr();
//      string orderId      = e["orderId"].ToStr();
//      string execId       = e["execId"].ToStr();
//      string orderType    = e["orderType"].ToStr();
//      string side         = e["side"].ToStr();
//      string execType     = e["execType"].ToStr();
//      string execPrice    = e["execPrice"].ToStr();
//      string execQty      = e["execQty"].ToStr();
//      string execValue    = e["execValue"].ToStr();
//      string execFee      = e["execFee"].ToStr();
//      string feeCurrency  = e["feeCurrency"].ToStr();
//      string feeRate      = e["feeRate"].ToStr();
//      string isMaker      = e["isMaker"].ToStr();
//      string markPrice    = e["markPrice"].ToStr();
//      string orderPrice   = e["orderPrice"].ToStr();
//      string orderQty     = e["orderQty"].ToStr();
//      string leavesQty    = e["leavesQty"].ToStr();
//      string closedSize   = e["closedSize"].ToStr();
//      string createType   = e["createType"].ToStr();
//      string execTime     = e["execTime"].ToStr();
//      string seq          = e["seq"].ToStr();
//
//      // --- Convert time if needed
//      datetime exec_dt = (datetime)(StringToInteger(execTime) / 1000);
//
//      // --- Pretty print
//      Print("Execution #", i);
//      Print(" Symbol        : ", symbol);
//      Print(" OrderId       : ", orderId);
//      Print(" ExecId        : ", execId);
//      Print(" Type / Side   : ", orderType, " / ", side);
//      Print(" ExecType      : ", execType);
//      Print(" ExecPrice     : ", execPrice);
//      Print(" ExecQty       : ", execQty);
//      Print(" ExecValue     : ", execValue);
//      Print(" ExecFee       : ", execFee, " ", feeCurrency);
//      Print(" FeeRate       : ", feeRate);
//      Print(" Maker         : ", isMaker);
//      Print(" OrderPrice    : ", orderPrice);
//      Print(" OrderQty      : ", orderQty);
//      Print(" LeavesQty     : ", leavesQty);
//      Print(" ClosedSize    : ", closedSize);
//      Print(" MarkPrice     : ", markPrice);
//      Print(" CreateType    : ", createType);
//      Print(" ExecTime      : ", TimeToString(exec_dt, TIME_DATE|TIME_SECONDS));
//      Print(" Seq           : ", seq);
//      Print("------------------------------------");
//   }
//+------------------------------------------------------------------+


FAQ

1. How to remove symbol prefix from my symbol when sending order to binance? if symbol prefix is a_BTCUSDT, when sending order via API you should send "BTCUSDT" only

here is the script tutorial to remove prefix from your symbol

void OnStart() {
//---
   string sym = _Symbol;
   string prefix = "bf_"; // change as required
   int length = 3; // length of prefix is 3 character
   string resultString;

// Check if the original string starts with "a_"
   if (StringSubstr(sym, 0, length) == prefix) {
      // Remove the "a_" prefix
      resultString = StringSubstr(sym, length);
   } else {
      // If the string doesn't start with "a_", keep the original string
      resultString = sym;
   }

// Output the result
   Print("Original Symbol: ", sym);
   Print("Result String: ", resultString);
}

2. How do i run chart to be updated every few seconds via API?

Binance recommends to update chart via Websocket which is available on product Crypto Charting because API is not for real time chart and running it too frequently may result in temporary IP ban by Binance, but if you wish not to use it and update history via API

here is how you can do it by adding this on your EA.

#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

int updatetime = 60;// Chart Update time in seconds
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit() {
//--- create timer
   EventSetTimer(1);
//---
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
//--- destroy timer
   EventKillTimer();

}

//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer() {
//---
   while(!IsStopped()) {
      datetime now = TimeGMT();
      static datetime UpdateTime = now;
      if(UpdateTime==now) {
         datetime mydate = iTime("bf_ETHUSDT",PERIOD_M1,2);

         //3. Run History Updater FUTURES : Symbol, Symbol Prefix, API URL, API Suffix, Max Date for History
         RunUpdate("ETHUSDT",  mydate);

         Print("Update Done");
         UpdateTime=now + updatetime; // wait for next 60 seconds before next update of 1 minute bar
      }
   }
}
//+------------------------------------------------------------------+