All successful trading involves 3 key elements:
- Edge
- Size
- Variance
Trading edge relies on either trader’s talent or instinct; size is the amount you wish to invest in a trade; and variance is the market volatility measure. Simplest way (not ideal) of way of taking all three into one bucket is the “bucket order”.
“Bucket order” involves three simultaneous trades: center order, stop-loss (SL), and take-profit (TP), all in one shot. Here is how to realize this on BitMEX XBTUSD via ccxt:
成功的交易通常是有3个要素:
- 机会发现
- 交易规模
- 市场波动
发现交易机会依赖交易员的使用的技术和个人直觉;交易规模是我们可以用来交易的资金;波动则是市场行为。一个最简单的方法,能同时把三个要素都照顾到,就是使用带止盈止损的下单策略。
这个下单策略包含3个订单,同时发出去:中央订单,止损单,和止盈单。有些交易所包括传统金融和数字资产交易所,是提供了这个订单类型。在BitMEX这家交易所没有提供Bucket Order,但是可以自己组合出这个订单类型。代码如下:
...
def _get_prices(p0,islong):
sl_r = 0.01 # 1% SL
tp_r = 0.05 # 5% TP
side = 1 if islong else -1
sl = p0 * (1 - side * sl_r)
tp = p0 * (1 + side * tp_r)
sl = _b(sl)
tp = _b(tp)
return p0, sl, tp
...
def _bracket(exchange,limitprice, price, stopprice, amount=1, direction='long'):
"""
@param exchange (object): ccxt stub of bitmex api
@param limitprice (float): price of the limit order for TP leg
@param price (float): price of the center order (limit order)
@param stopprice (float): price of the market order for SL leg
@param amount (int): quantitiy of contracts in $
"""
sym = 'BTC/USD' # don't change this for bitmex perp contract XBTUSD
kwargs = dict(symbol=sym,type='Limit',side='buy' if direction == 'long' else 'sell',amount=amount,price=price)
od = exchange.create_order(**kwargs)
kwargs = dict(symbol=sym,type='Stop',side='sell' if direction == 'long' else 'buy',amount=amount,params=dict(stopPx=stopprice))
sl = exchange.create_order(**kwargs)
kwargs = dict(symbol=sym,type='Limit',side='sell' if direction == 'long' else 'buy',amount=amount,price=limitprice)
tp = exchange.create_order(**kwargs)
logging.info(f'order: {od}\nSL: {sl}\nTP: {tp}')
return (od, sl, tp)
def _buy_bracket(exchange,limitprice, price, stopprice,amount=1):
logging.info(' -- creating buy bracket')
if stopprice > limitprice:
raise ValueError('SL price should not be greater than TP.')
_bracket(exchange,limitprice, price, stopprice,amount,'long')
def _sell_bracket(exchange,limitprice, price, stopprice,amount=1):
logging.info(' -- creating sell bracket')
if stopprice < limitprice:
raise ValueError('SL price should not be less than TP.')
_bracket(exchange,limitprice, price, stopprice,amount,'short')