BitMEX exchange API note

Author: The Little Dream, Created: 2017-05-08 18:39:32, Updated: 2023-07-27 20:40:27

BitMEX exchange API use case (BitMEX exchange API note)

The FMZ platform API Doc Join us on telegram group

www.fmz.com (used to be BotVs) is a quantitative strategy trading platform where you can easily learn, write, share, and trade quantitative strategies.

  • Our platform has many advantages:

    • 1、Cross-platform, support all major trading exchanges, strategy wrote on our platform is suitable for all major exchanges.
    • 2、Easy to get started, the specific API documentation and the classical template strategies helps users to get started really quick.
    • 3、It has an effective simulate backtesting system.
    • 4、Support sending e-mails, pushing messages to your phone.
    • 5、Web-based control mechanism, can be acessed through your phone.
    • 6、Support for complete Python\C++\JavaScript programming
    • 7、Support spots and futures trading, and will support more exchanges in the future.
    • 8、The cost is extremely low. 0.125 RMB per hour, based on current exchange rate: USDCNY 6.9303, which means 0.01804 dollar per hour.
    • 9、No API-KEY or passwords are saved in our website. FMZ has been running for more than four years without any security issues.

FMZ (BOTVS) now supports all contracts on BitMEX!

  • Trade on testnet:

function main() {
    exchange.IO("base", "https://testnet.bitmex.com")
}
  • The test code is:

var initAccount = null;
var nowAccount = null;
function main() {
    LogReset(1);
    Log("This is BitMEX test bot");
    Log("Fee:", exchange.GetFee());
    Log("Initial account:", initAccount = _C(exchange.GetAccount));    
    var info = exchange.SetContractType("XBTUSD");   // BitMEX : XBTUSD , OK : this_week
    Log("XBTUSD info:", info);   
    Log("Use GetTicker to get ticker information:", _C(exchange.GetTicker)) 
    Sleep(1000 * 10);   
    // make an order
    exchange.SetDirection("sell");                         // set order direction
    var orderId = exchange.Sell(-1, 1);                    // sell at market price。
    Sleep(6000);
    // log positions
    var positions = null;
    Log(positions = _C(exchange.GetPosition));
    Log("Account before changing leverage:", _C(exchange.GetAccount));
    // change leverage
    Log("Change leverage", _C(exchange.SetMarginLevel, positions[0].MarginLevel * 2));
    Log("Account after changing leverage:", _C(exchange.GetAccount));  
    // test GetOrder 
    if (orderId) {
        Log(_C(exchange.GetOrder, orderId));
    } 
    Sleep(1000 * 10);
    Log(_C(exchange.GetPosition));
    // set direction to close
    exchange.SetDirection("closesell");
    var go_buy = exchange.Go("Buy", -1, 1);
    var orderId2 = go_buy.wait();
    Log(_C(exchange.GetOrder, orderId2));
    Log("Current account:", nowAccount = _C(exchange.GetAccount));
    Log(_C(exchange.GetPosition));
    LogProfit(nowAccount.Stocks - initAccount.Stocks, " initAccount:", initAccount, " nowAccount:", nowAccount);
    Sleep(1000 * 10);
    var ticker = _C(exchange.GetTicker);
    exchange.SetDirection("buy");
    exchange.Buy(ticker.Last - 50, 1);
    exchange.SetDirection("sell");
    exchange.Sell(ticker.Last + 50, 1);
    // GetOrders
    Log("Test GetOrders:", _C(exchange.GetOrders));
    var e = exchange;
    while (true) {
        var orders = _C(e.GetOrders);
        if (orders.length === 0) {
            break;
        }
        Sleep(500);
        for (var j = 0; j < orders.length; j++) {
           e.CancelOrder(orders[j].Id);
            if (j < (orders.length - 1)) {
                Sleep(500);
            }
        }
    }
    Log("Cancel order, test GetOrders again:", _C(exchange.GetOrders));
}
  • Check your account information at BitMEX.

    img

    Log the information by bot, which is the same with that on BitMEX.

    img

  • Log positions after changing leverage, the leverage has been changed.

    img

  • Use the Go function to cover your positions at the same time.

      exchange.SetDirection("closesell");
      var go_buy = exchange.Go("Buy", -1, 1);
      var orderId2 = go_buy.wait();
      Log(_C(exchange.GetOrder, orderId2));
      Log("当前账户:", nowAccount = _C(exchange.GetAccount));
      Log(_C(exchange.GetPosition));
      LogProfit(nowAccount.Stocks - initAccount.Stocks, " initAccount:", initAccount, " nowAccount:", nowAccount);
    

    img

  • Let's try post orders and cancel it.

    var ticker = _C(exchange.GetTicker);
    exchange.SetDirection("buy");
    exchange.Buy(ticker.Last - 50, 1);
    exchange.SetDirection("sell");
    exchange.Sell(ticker.Last + 50, 1);  
    // GetOrders
    Log("Test GetOrders:", _C(exchange.GetOrders));
    var e = exchange;
    while (true) {
        var orders = _C(e.GetOrders);
        if (orders.length === 0) {
            break;
        }
        Sleep(500);
        for (var j = 0; j < orders.length; j++) {
            e.CancelOrder(orders[j].Id);
            if (j < (orders.length - 1)) {
                Sleep(500);
            }
        }
    }
    Log("orders have been canceled. Now check orders again, order array is empty. GetOrders:", _C(exchange.GetOrders));
    

    img

    The pending orders information.

 [{"Id":4,"Amount":1,"Price":1679.6,"DealAmount":0,"AvgPrice":0,"Status":0,"Type":1,"ContractType":"XBTUSD"},
 {"Id":3,"Amount":1,"Price":1579.6,"DealAmount":0,"AvgPrice":0,"Status":0,"Type":0,"ContractType":"XBTUSD"}]
  • Note (s):

    • BitMEX only supports K-line periods of 1m, 5m, 1h, 1d.

      Using the latest hosts, the sub-layer can automatically synthesize K-lines, and some K-line cycle data that BITMEX does not support can also be synthesized, so it is no longer limited to K-line cycles when setting them up.1分钟、5分钟、1小时、1天These cycles, all cycles can be set.

      img

    • Test holding long and short positions at the same time.

      LogReset(1);
      var info = exchange.SetContractType("XBTUSD");
      exchange.SetDirection("sell");
      var orderId = exchange.Sell(-1, 1);
      Log(_C(exchange.GetPosition));
      Sleep(1000*6);
      exchange.SetDirection("buy");
      var orderId2 = exchange.Buy(-1, 1);
      Log(_C(exchange.GetPosition));
      exchange.SetDirection("closesell");
      var orderId3 = exchange.Buy(-1, 1);
      Log(_C(exchange.GetPosition));
      

      img

    • The leverage can be changed while holding position.

    • 4、Support exchange.IOfunction for more API.

      img

      // exchange.IO example
      exchange.SetContractType("XBTUSD");
      Log(exchange.IO("api", "POST", "position/leverage", "symbol=XBTUSD&leverage=4"));
      Log(exchange.IO("api", "GET", "user"));
      

      The raw information of position/leverage API

      {"homeNotional":0,
      "sessionMargin":0,
      "bankruptPrice":null,
      "initMarginReq":0.25,
      "execBuyQty":2,
      "execComm":184,
      "unrealisedCost":0,
      "commission":0.00075,
      "leverage":4,
      "posLoss":0,
      "posMargin":0,
      "posMaint":0,
      "liquidationPrice":null,
      "maintMarginReq":0.005,
      "grossExecCost":0,
      "execCost":7,
      "currentTimestamp":"2017-05-08T10:51:20.576Z",
      "markValue":0,
      "unrealisedGrossPnl":0,
      "taxBase":7720,
      "unrealisedPnlPcnt":0,
      "prevUnrealisedPnl":0,
      "openOrderSellCost":0,
      "deleveragePercentile":null,
      "openingComm":31588,
      "openOrderBuyCost":0,
      "posCross":0,
      "taxableMargin":0,
      "simpleCost":0,
      "underlying":"XBT",
      "quoteCurrency":"USD",
      "execBuyCost":122613,
      "execSellCost":122620,
      "execQty":0,
      "realisedCost":-7720,
      "unrealisedPnl":0,
      "openingQty":0,
      "openOrderBuyQty":0,
      "initMargin":0,
      "unrealisedTax":0,
      "simpleQty":0,
      "avgCostPrice":null,
      "rebalancedPnl":24052,
      "openingTimestamp":"2017-05-08T10:00:00.000Z",
      "unrealisedRoePcnt":0,
      "posCost":0,
      "posInit":0,
      "posComm":0,
      "realisedTax":0,
      "indicativeTax":0,
      "breakEvenPrice":null,
      "isOpen":false,
      "riskValue":0,
      "posState":"",
      "varMargin":0,
      "realisedGrossPnl":7720,
      "timestamp":"2017-05-08T10:51:20.576Z",
      "account":25992,
      "foreignNotional":0,
      "openOrderSellPremium":0,
      "simpleValue":0,
      "lastValue":0,
      "riskLimit":20000000000,
      "openOrderSellQty":0,
      "grossOpenPremium":0,
      "marginCallPrice":null,
      "prevClosePrice":1562.74,
      "openOrderBuyPremium":0,
      "currentQty":0,
      "currentCost":-7720,
      "currentComm":31772,
      "markPrice":null,
      "posCost2":0,
      "realisedPnl":-24052,
      "prevRealisedPnl":-95,
      "execSellQty":2,
      "shortBankrupt":0,
      "simplePnl":0,
      "simplePnlPcnt":0,
      "lastPrice":null,
      "posAllowance":0,
      "targetExcessMargin":0,
      "indicativeTaxRate":0,
      "grossOpenCost":0,
      "maintMargin":0,
      "crossMargin":false,
      "openingCost":-7727,
      "longBankrupt":0,
      "avgEntryPrice":null,
      "symbol":"XBTUSD",
      "currency":"XBt"}
      

Related

More

q25459768Thank you.

CooongPlease open the VPN with a local host, use shadowsocks, global, bitmex web pages can be accessed, but the program does not run. Choose a US public server is no problem, you can place an order. Please help how to solve this, do you have to buy a US server to run?

Flowers are bloomingPlease botvs support bitmex's price limit mandate, which is equivalent to selecting a passive mandate when ordering in bitmex

bobo188With getrecords, bitmex only returns 100 bits of data, but bitmex supports a maximum of 500, how can you get more?

kissoulGetAccount (((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) This is a list of all the different ways Stocks: 0.00841059, FrozenStocks: 0.0092248, Balance: 0, FrozenBalance: 0 is credited in the database. FrozenStocks is down one zero, actually 0.092248.

beleevHow do you solve this problem when you call the rest interface of bitmex using exchange.IO (API, httpMethod, resource, params)? I want to get this bitmex url: https://www.bitmex.com/api/v1/orderBook/L2?symbol=XBT&depth=1, using the following code as documented def main (: depth = exchanges[0].IO (("api", "GET", "/api/v1/orderBook/L2","symbol=XBT&depth=1") Log ((depth)) The logs are running after an error: Futures_BitMEX error Futures_OP 4: 401: {"error":{"message":"Signature not valid.","name":"HTTPError"}} This is a list of all the different ways Futures_BitMEX is credited in the database. My aksk is fine, because other APIs can be called through, help me see why this is?

Victor997 Hello, i can't add droker, it says incorrect password. I need help with all steps if it is possible, i could only add the plateform. Thanks, Victor997

Eight oil tankersWhen will BitMEX be able to support websocekt mode, now the limit of 300 transactions per 5 minutes is too high

kezjohttps://dn-filebox.qbox.me/bf29e11e9f2d707808ccd006406bb3026a794876.png Why can't I see Bitmex in the add-in platform, including Kraken in the screenshot?

ytrezq Hello, I am new to botvs, how I can use this for bitmex?

LUISLUPlease ask if your platform has a feedback system for BitMex.

JBitMEX's GetRecords returned the last value of the K-line data that is not real-time, making it impossible to compute the metrics in real-time. This problem has been around for a long time and is a flaw in BitMEX's own API that has not been solved. If BotVS collects BitMEX data in real time, can it supplement BitMEX's real-time data with the data it collects?

JHow do you get the K-line data from BitMEX?

The NinjaDream sum, I found a problem, after bitMEX set the exchange rate to RMB, it could not be done ~ I don't know what the problem is, please dream sum please

JThis one is too big and can be leveraged.

The Little Dreamshadowsocks is not a truly global proxy, and does not have all proxy computers' network access. The simplest way to do this is to run a host on a server in another region.

bobo188Can you give me an example, please? Thank you!

The Little DreamYou can use HttpQuery to directly access the exchange interface, specify parameters, and access data.

The Little DreamYou can check my QQ: 359706687 and I'll help you.

The Little DreamYes, you are calling an interface that has access to depth, which should be unsigned encrypted. Use exchange.IO for encrypted interfaces, use HttpQuery for unencrypted ones (python uses urlib library), HttpQuery handles unencrypted interfaces for unencrypted requests.

The Little Dream Thanks for your supported! Could I get some answer about which kinds of your system that you want to run a docker. BotVS supported: - windows 64bit , 32bit (CLI , Interface) - MAC OSX (cmd line) - Linux 64bit , 32bit (cmd line) - ARM linux (cmd line) After this , I will make a process which step by step add a docker. Wait for you message! ^^

The Little DreamBITMEX's WS protocol is currently not supported.

kezjoI'm sorry. I'm sorry. I'm sorry. I'm sorry. I know, but I have to go.

The Little DreamThe outboard platform has no backtest data at the moment, and support is planned. You changed the browser trial, possibly the browser that caused the drop-down control not to show.

The Little Dream Using step: 1、Run the program named robot, where to download at this location: https://dn-filebox.qbox.me/cfe3c7fab12e72b6dae4ca238dde150e5d8bcd56.png 2、Add platform: configuration BitMEX `s API KEY: https://dn-filebox.qbox.me/5527bc725b11109774c5bdf152c80974542d59ed.png https://dn-filebox.qbox.me/c953a7570513cb6e5800a4775df67cbcbc9135b8.png https://dn-filebox.qbox.me/6a8077d08bae2ac3ba5c4f57eb88af5c0683e4f6.png 3、Add robot and Binding Strategy with robot : https://dn-filebox.qbox.me/290a20859a186b27af4058019259134b6b48bda5.png https://dn-filebox.qbox.me/5e797e71b6c7c0bfda4860f7b1073aa69b499f64.png https://dn-filebox.qbox.me/74307cc14fa0039695e4608c955c2b7d71789b10.png

ytrezq Yes, but what are the steps on the website to use BitMex on BotVS ?

The Little Dream Thanks for using BotVS ^^ , BotVS already support BitMEX .

The Little DreamHello, BitMEX is currently not supported by the verification system.

The Little DreamYou can deep copy a push in.

JThank you! Then I push to the other variable should be fine.

The Little DreamJ major ~ The array that GetRecords retrieves is referenced, and if you push in the next retrieval, the element of the push will appear.

The Little DreamI'll test it, wait a minute.

JI was going to add this last real-time data myself, but I ran into a problem. Exchange.SetContractType (('XBTUSD')) is the name of the // Get data from GetRecords records = exchange.GetRecords Log ((records)) // then add the last value yourself. records.push Time:records[records.length-1].Time + 3600000, which is a recording of a live performance. Close:records[records.length-1].Close + 1 It's not. Log ((records)) // Pause 10 seconds to recall GetRecords Sleep ((10000) records = exchange.GetRecords // Why is the last data added still there? Log ((records))

The Little DreamOkay, thanks for the suggestion, J. I'll test it.

The Little DreamYes, BITMEX, this is a contract.

JThe first thing to do is to set up the currency. Exchange.SetContractType (('XBTUSD')) is the name of the records = exchanges.GetRecords

The Little DreamWell, let's have a look.

The NinjaWell, that's also a possibility, I'll try it.

The Little DreamYou can try to limit the fractional value of the price using N. Many exchanges limit the fractional value of the quote, generally no more than 4 fractions.

The NinjaI'm always dreaming, Sell ((12319.94890, 100.00000): 400: {"error":{"message":"Invalid price tickSize","name":"HTTPError"}}, the feeling is, without converting the price to dollars, it is reported, so that the price deviates abnormally, not given a listing.

The Little DreamWell, I'll test it right away.