Product URL : https://www.mql5.com/en/market/product/164533
Documentation of Bybit API URL: https://bybit-exchange.github.io/docs/v5/guide- Testnet:
https://api-testnet.bybit.com
- Mainnet:
https://api.bybit.com
Tutorial 1 : Trading Operations
Script Demo :
Note : Once you purchased the Library, It will be found under Scripts/Market Folder
///+--------------------------------------------------------------+ //| Library_Bybit.mq4 | //| 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" #property strict #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 category; bool debug; }; #import "..\Libraries\Library_Bybit.ex4" void Bybit_Init(BybitConfig &config); //+------------------------------------------------------------------+ //| Get Bybit Server Time | //+------------------------------------------------------------------+ string GetTime(); //+------------------------------------------------------------------+ //| Get Bybit Exchange Info | //+------------------------------------------------------------------+ 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); //+------------------------------------------------------------------+ //| Send SL / TP | //+------------------------------------------------------------------+ string setTradingStop(string symbol, string slTrigger, string tpTrigger); //+------------------------------------------------------------------+ //| Send Market Order Hedge Mode (for futures) | //+------------------------------------------------------------------+ string orderMarket_Hedge ( string symbol, string side, // Buy / Sell int positionIdx, // 1 = LONG hedge, 2 = SHORT hedge double qty ); //+------------------------------------------------------------------+ //| 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); //+------------------------------------------------------------------+ //| Set Leverage (Futures) | //+------------------------------------------------------------------+ string setLeverage(string symbol, string buyLeverage, string sellLeverage); //+------------------------------------------------------------------+ //| Position Info (Futures) | //+------------------------------------------------------------------+ string getPosition(string symbol, string cursor); //+------------------------------------------------------------------+ //| Get Ticker Price | //+------------------------------------------------------------------+ string Get_Symbol_Price_Ticker(string symbol); #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's API secret //string Bybit_URL = "https://api.bybit.com"; // API URL Mainnet string Bybit_URL = "https://api-testnet.bybit.com"; // API URL Testnet string Bybit_suffix = "/v5/"; // API Suffix (Do not edit) string category = "linear"; //Product type linear, inverse, spot, option //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.debug = Bybit_debug; config.category = category; Bybit_Init(config); //Add your codes here //+------------------------------------------------------------------+ //| Get_Symbol_Price_Ticker | //+------------------------------------------------------------------+ //string s = Get_Symbol_Price_Ticker("BTCUSDT"); //Print("ret : ",s); //+------------------------------------------------------------------+ //| Realtime Query Order | //+------------------------------------------------------------------+ ////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); // } // } //+------------------------------------------------------------------+ //| 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 | //+------------------------------------------------------------------+ //Symbol,Side,positionIdx (1=LONG,2=SHORT), qty) // To Open LONG // orderMarket_Hedge("BTCUSDT","Buy",1,0.001); //// To Open SHORT // orderMarket_Hedge("BTCUSDT","Sell",2,0.001); //// To Close LONG // orderMarket_Hedge("BTCUSDT","Sell",1,0.001); //// To Close SHORT // orderMarket_Hedge("BTCUSDT","Buy",2,0.001); //+------------------------------------------------------------------+ //| 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 = getPosition("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"); //+------------------------------------------------------------------+ //| 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("------------------------------------"); } //+------------------------------------------------------------------+
Files:
ByBit_Tester.mq4
20 kb


