BitMEX in BackTrader

Trading BitMEX via BackTrader

BitMEX is one of my favorite crypto exchange regardless the inconvenience of the lack of spot market. The most prominent trait of the exchange is the super trading liquidity especially for the BTC perpetual contract, and relatively low commission — maker -2.5bps, taker +7.5pbs, without considering the funding rates (in reality this should be taken into account because it’s a negligibly high cost & profit).

XBTUSD on BitMEX is an “inverse perpetual contract”. “Inverse” means the fund attained as margin is the underlying asset, i.e., BTC. This brings some trouble when using BackTrader (https://www.backtrader.com/) to do backtesting and live trading. However, the machinery provided by BackTrader is enough to solve this. Here is how:

BitMEX 是我个人比较喜欢的一个BTC衍生品交易所,虽然该交易所不提供现货交易有点不方便。吸引我的主要是永续合约的超强的流动性(基本是业内第一)以及比较低廉的commission — maker -2.5bps, taker +7.5bps,不考虑资金费率 (funding rate) 的话(实际交易时必须考虑)。

BitMEX 的 XBTUSD 永续合约是一种所谓”反向合约“ — 保证金是底层资产,即BTC而非美元。这在我使用BackTrader时遇到了问题。但是BackTrader提供的工具和框架是有办法解决的。代码snippet如下:

class BmexScheme(bt.CommInfoBase):
	params = (
      ('stocklike', False),  # Futures contract
      ('commtype', bt.CommInfoBase.COMM_PERC)
    )
    #@overload
    def profitandloss(self, size, price, newprice):
        if price == 0:
            return -size/newprice * self.p.mult
        return size * (1/price - 1/newprice ) * self.p.mult
    
    #@overload
    def cashadjust(self, size, price, newprice):
        '''Calculates cash adjustment for a given price difference'''
        if not self._stocklike:
            return size * (1/price-1/newprice) * self.p.mult
        return 0
    
    #@overload
    def get_margin(self, price):
        return 1/price * self.p.automargin  # int/float expected
    
    #@overload
    def _getcommission(self, size, price, pseudoexec):
        return abs(size/price*self.p.commission*self.p.mult) #FIXME refund is not counted

def get_comm_model_bmex(l=1):
    comminfo = BmexScheme(
        commission=0.02,  # 0.02%
        automargin=1,
        leverage=l
    )

...
comminfo = get_comm_model_bmex(l=args.leverage)
cerebro.broker.addcommissioninfo(comminfo)
...

猜你喜欢

转载自blog.csdn.net/weixin_47368014/article/details/108749624