Loading ...

BitMEX exchange API note

Author: 小小梦, Created: 2017-05-08 18:39:32, Updated: 2019-06-03 12:10:57

BitMEX 交易所API使用事项 (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) 现已支持 BitMEX 的所有合约!(FMZ(BOTVS) supports all contracts on BitMEX)

  • 模拟交易所 (trade on testnet) :

function main() {
    exchange.IO("base", "https://testnet.bitmex.com")
}
  • 测试代码 (Test code) :

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 Go function to cover your positions at the same time. (调用 Go 函数异步多线程平仓)

      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 (注意):

    • 1、BitMEX only supoort K-line periods of 1m,5m,1h,1d.(BitMEX的K线周期只支持1分钟、5分钟、1小时、1天这些周期。)

      使用最新的托管者,底层可以自动合成K线,一些BITMEX 不支持的K线周期数据也可以合成出来,所以在设置K线周期的时候不再局限于1分钟、5分钟、1小时、1天这些周期,所有周期都可以设置。

      img

    • 2、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

    • 3、The leverage can be changed while holding position.(持仓后杠杆可调。)

    • 4、Support exchange.IO function for more API. (支持exchange.IO函数)

      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 (直接调用交易所API–position/leverage返回的数据:)

      {"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

q25459768 多谢

mtf bitmex The raw information of position/leverage API (直接调用交易所API--position/leverage返回的数据:)接口 返回的数据都是什么意思啊,能给解释下嘛

timedgqb 活动订单中的gross value字段是如何获得值的?

Cooong 请问用本地托管者开了vpn,用的shadowsocks,全局,bitmex网页可以上的去,但是程序跑不动。选美国公用服务器就没问题,可以下单平仓。求救这该怎么解决,一定要自己买一个美国服务器才可以跑吗?

小花开开 请问botvs 支持 bitmex的限价委托么,相当于在bitmex里下单的时候,勾选“被动委托”

bobo188 用getrecords, bitmex只是返回100根数据,但是bitmex是支持最大500,怎么才能获得更多?谢谢

elgordo11 can anyone send me all of the informations how to configure the bot in english? davepoldi@gmail.com how to configure and what strategy i can make would be very nice

elgordo11 can anyone send me all of the informations how to configure the bot in english? davepoldi@gmail.com how to configure and what strategy i can make would be very nice

kissoul GetAccount()获取的数据不对啊 {"Stocks":0.00841059,"FrozenStocks":0.0092248,"Balance":0,"FrozenBalance":0} FrozenStocks少了一个0, 实际是0.00092248

beleev 使用exchange.IO("api", httpMethod, resource, params) 调用bitmex的rest接口报错,请问这个怎么解决? 我想GET bitmex的这个url:https://www.bitmex.com/api/v1/orderBook/L2?symbol=XBT&depth=1,按照文档使用了如下代码 def main(): depth = exchanges[0].IO("api", "GET", "/api/v1/orderBook/L2","symbol=XBT&depth=1") Log(depth) 运行后日志报错: Futures_BitMEX 错误 Futures_OP 4: 401: {"error":{"message":"Signature not valid.","name":"HTTPError"}} 我的aksk是没问题的,因为其他的api可以调用通过,帮忙看看这个是什么原因?

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

八位酱油 BitMEX 什么时候能支持websocekt模式,现在5分钟300次交易频率限制太大了

vincentmayx 梦神,现在bitmex还是只能跑实盘么?有没有计划何时支持模拟盘?

kezjo https://dn-filebox.qbox.me/bf29e11e9f2d707808ccd006406bb3026a794876.png 为什么我在添加平台里看不到Bitmex,包括截图里的Kraken也没有?另外,国外的平台都有哪几个可以回测呢?谢谢!

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

LUISLU 请问贵平台针对BitMex有没有回测系统

J BitMEX 的GetRecords 返回的K线数据最后一个值不是实时的,造成无法实时计算各项指标。 这个问题已经很久了,是BitMEX本身API 的缺陷,一直没有解决的方法。 BotVS 有实时收集BitMEX 的数据,能否通过收集到的数据来补足BitMEX的这个实时数据呢?

J BitMEX 的K线数据怎么获得? GetRecords 好像不能用

宁公子 梦总,我发现一个问题,bitMEX 设置汇率成人民币之后,无法成交了~不知道什么问题,请梦总请教~

J 这个太牛了,又可以杠杆操作了

小小梦 如果调用的 代码 可以发下 看下。

小小梦 上面范例上是 调用的以下代码获取。 ``` Log(exchange.IO("api", "POST", "position/leverage", "symbol=XBTUSD&leverage=4")); Log(exchange.IO("api", "GET", "user")); ``` 您可以查询下 BITMEX 文档 ,看下是哪个接口返回 您需要的数据(gross value)然后直接用 exchange.IO 调用就可以了。

小小梦 shadowsocks 不是真正的 全局代理 , 并没有全部代理 电脑的 网络访问, 目前最简单的就是 用一个 其他地区的服务器 跑托管者就可以了。

bobo188 请问,能不能给我一个例子,谢谢!我是小白

小小梦 可以使用 HttpQuery 直接访问 交易所 接口 指定参数 获取 数据。

小小梦 Thanks for supported BotVS , But now , there only has some page, Please wait some time , we will edit a simple diagram。 https://www.botvs.com/bbs-topic/1083

小小梦 您 加下我 QQ : 359706687 , 我帮您 看下。

小小梦 是这样的, 您调用的是 获取深度 的接口, 这个 接口应该是 不用签名 加密的。 对于加密请求的接口 要使用 exchange.IO 调用, 对于 不加密的 使用 HttpQuery (python 使用 urlib 库) , HttpQuery 处理 不加密的 接口 请求。

小小梦 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! ^^

小小梦 BITMEX 的 WS 协议 还暂时 没支持。

小小梦 暂时还没有 做 支持 BitMEX 的回测。 期货回测支持 OKEX 合约。

kezjo 我晕。。还真是,ie可以

小小梦 外盘的平台 暂时没有回测数据,正在计划支持。您换个 游览器试试,可能是游览器 导致 下滑控件没显示出来。

小小梦 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 ?

小小梦 Thanks for using BotVS ^^ , BotVS already support BitMEX .

小小梦 您好,暂时 回测系统还没有支持 BitMEX 交易所, ^^ 。

小小梦 可以深拷贝一个 push进去。 ^^

J 谢谢!那我push到另外一个变量应该就可以了

小小梦 J大~ 这个 GetRecords 获取的 数组 是引用传递的 ,如果 push 进去 下次获取 就会出现push 的元素。

小小梦 我测试一下,稍等。

J 我想自己加上最后这个实时数据,但是遇到一个问题,帮我看看 exchange.SetContractType('XBTUSD') // 通过 GetRecords() 获取数据 records = exchange.GetRecords() Log(records) // 然后自己添加最后一个值。这里随便加个数据,仅供测试 records.push({ Time:records[records.length-1].Time + 3600000, Close:records[records.length-1].Close + 1 }) Log(records) // 休息10秒重新调用 GetRecords() Sleep(10000) records = exchange.GetRecords() // 为什么上次添加的数据还在? Log(records)

小小梦 好的,感谢J 大 提出,我测试一下 记录 报告!

小小梦 是的 BITMEX这个是 合约。

J 明白了,要先设置下币种 exchanges.SetContractType('XBTUSD') records = exchanges.GetRecords()

小小梦 好的 ,我们检查一下。

宁公子 噢,也有这个可能,我试试~

小小梦 可以使用_N 限制一下 价格的小数位试试,很多交易所 限制报价的小数位,一般别超过4位小数。

宁公子 梦总早呀,Sell(12319.94890, 100.00000): 400: {"error":{"message":"Invalid price tickSize","name":"HTTPError"}},感觉是,没把价格转成美元就报上去了,以至于价格异常偏离,不给挂单。

小小梦 好的 ,我这马上测试 。