浅谈比特币期货做市策略

论坛 期权论坛 期权     
zanks   2019-11-20 08:55   9632   0
一、什么是做市策略做市策略(market-maker strategy)是一种风险中立(risk-neutral)盘口价差套利策略。其基本原理是:在盘口的卖一和买一价之间,插入委买单和委卖单,如果插入的两个单子都成交的话,做市商就吃到了买卖单之间的价差,而整个过程结束后,做市商所持有的头寸并没有变化。如果买卖单之间的价差扣除各种交易手续费之后还有盈余,那么该做市商就获得了相应的盈利。
做市策略是一种增加交易所流动性的策略,一般来讲,成熟的交易市场为了提升自身的流动性,会用低佣金(甚至为做市商提供流动性奖励金)的办法,吸引做市商来该市场做市。
二、做市策略需要注意的事项
1 做市时机的选择。做市商本质上是整个市场的交易对手方。如果市场呈现急剧的单边行情,做市商下达的买卖委托单会大概率出现单边成交的情况,因此做市商手中就会积累大量的风险头寸,这是做市商不想承担的风险。因此,做市商在选择是否下达做市指令之前,都会预判一下市场的趋势明显程度,如果市场短期内呈现非常明显的趋势信号,做市商就会相应地减少自己的做市单数量(甚至停止做市)
2 净头寸的处理。做市商手中累计的净头寸,可以通过很多种办法来处理,下面列举其中两种:
(1)在下一次做市时,处理掉累积的净头寸。比如做市商目前净头寸有2BTC,下次做市时,他就可以下达一个卖3BTC的委卖单,一个买1BTC的委买单。这种做法好处是净头寸可以及时得到处理,坏处是净头寸处理的时机(价格)可能不是最优的。
(2)第二种方法是开立另外一个独立的程序,对累积的净头寸进行成本计算,然后按照成本价*(1+一定比例的手续费+一定比例的profit margin),将该头寸反向甩出市场,甩出方法又有两种:a. 按限价单从价优到价劣依次甩出市场,超时不成交的部分则撤单,等待下次机会;b. 先按限价单从价优到价劣依次甩出市场,超时不成交的部分,则按市价单甩货。第一种方法的好处是甩货成本可控,但是甩货周期可能会拖得比较长;第二种方法则能有效地控制甩货周期,但是成本不可控,孰优孰劣,需要做市商根据自己的风险偏好慎重考虑。
3 期货换合约(移仓)的处理
期货合约都有一个到期日,在到期日结束时刻的前几个小时,我们不建议做市商继续做市,而是利用这几个小时,将即将到期的期货合约进行移仓。移仓的意思就是平掉当前期货合约的仓位,然后再开同样仓位大小的下周合约。当然,移仓也是需要考虑成本的。如果当前持仓是多头,那么我们希望移仓的时间点是在下周期货贴水最厉害的时候;反之,我们则希望移仓的时间点是在下周期货升水最厉害的时候。等移仓做完以后,做市策略继续恢复执行。

三、一个典型的比特币期货做市策略源码分享

注意,以下的策略需要其他WeQuant基础类库的支持才能运行,这里仅给出策略核心源码,是为了让读者对做市策略本身有一个具体的认识,而不用去太纠结底层下单、统计收益、收发邮件、进程监控等技术细节。关于代码的详细解释,欢迎入QQ群讨论:519538535。
期货做市策略源码:


  1. #!/usr/bin/env python  # -*- coding: utf-8 -*-
  2.   from signalGenerator.futureSpotArb import *
  3.   from signalGenerator.strategyConfig import changeFutureContractConfig as rollCfg
  4.   import time, threading
  5.   class FutureMarketMaker(FutureSpotArb):
  6.   def __init__(self, startRunningTime, orderRatio, timeInterval, orderWaitingTime,
  7.   coinMarketType, open_diff, close_diff, heart_beat_time, depth_data, account_info, transaction_info, maximum_qty_multiplier=None,
  8.   dailyExitTime=None):
  9.   super(FutureMarketMaker, self).__init__(startRunningTime, orderRatio, timeInterval, orderWaitingTime,
  10.   coinMarketType, open_diff, close_diff, heart_beat_time, depth_data, account_info, transaction_info, maximum_qty_multiplier=maximum_qty_multiplier,
  11.   dailyExitTime=dailyExitTime)
  12.   # 显示在邮件中的策略名字
  13.   self.strat_name = "期货做市-%s" % startRunningTime.strftime("%Y%m%d_%H%M%S")
  14.   self.trade_threshold = 0.0003 * 1.01
  15.   self.sell_cut = 0.6
  16.   self.buy_cut = 0.6
  17.   self.leverage = 5
  18.   self.remaining_delta_cash = 0
  19.   # 策略下单参数
  20.   self.coin_type = helper.HUOBI_COIN_TYPE_BTC
  21.   self.contract_type = helper.CONTRACT_TYPE_WEEK
  22.   self.initial_acct_info = None
  23.   # cancel all pending orders
  24.   def cancel_pending_orders(self):
  25.   orders = self.BitVCService.order_list(self.coin_type,self.contract_type)
  26.   while orders is not None and len(componentExtract(orders, "week", [])) > 0:
  27.   orders = componentExtract(orders, "week", [])
  28.   for order in orders:
  29.   if componentExtract(order, u"id", "") != "":
  30.   order_id = order[u"id"]
  31.   self.BitVCService.order_cancel(self.coin_type,self.contract_type, order_id)
  32.   orders = self.BitVCService.order_list(self.coin_type,self.contract_type)
  33.   def go(self):
  34.   self.timeLog("日志启动于 %s" % self.getStartRunningTime().strftime(self.TimeFormatForLog))
  35.   self.timeLog("开始cancel pending orders")
  36.   self.cancel_pending_orders()
  37.   self.timeLog("完成cancel pending orders")
  38.   while True:
  39.   # 期货移仓期间,程序一直sleep
  40.   if self.in_time_period(datetime.datetime.now(), rollCfg.CHANGE_CONTRACT_START_WEEK_DAY_FOR_NORMAL,
  41.   rollCfg.CHANGE_CONTRACT_END_WEEK_DAY_FOR_NORMAL, rollCfg.CHANGE_CONTRACT_START_TIME_FOR_NORMAL,
  42.   rollCfg.CHANGE_CONTRACT_END_TIME_FOR_NORMAL):
  43.   self.timeLog("当前处于移仓时间,程序进入睡眠状态……")
  44.   time.sleep(60)
  45.   continue
  46.   if self.timeInterval > 0:
  47.   self.timeLog("等待 %d 秒进入下一个循环..." % self.timeInterval)
  48.   time.sleep(self.timeInterval)
  49.   self.order_info_list = []
  50.   # 获取账户持仓信息
  51.   try:
  52.   account = copy.deepcopy(self.account_info)
  53.   acct_info = account["account_info"]
  54.   account_update_time = account["time"]
  55.   except Exception:
  56.   self.timeLog("尚未取得账户信息")
  57.   continue
  58.   # 检查账户获取时间
  59.   if account_update_time < self.latest_trade_time:
  60.   self.timeLog("当前账户信息时间晚于最近交易时间,需要重新获取")
  61.   continue
  62.   # setup initial account info
  63.   if self.initial_acct_info is None:
  64.   self.initial_acct_info = acct_info
  65.   short_pos_money_delta = acct_info["bitvc_btc_hold_money_week_short"] - self.initial_acct_info["bitvc_btc_hold_money_week_short"]
  66.   long_pos_money_delta = acct_info["bitvc_btc_hold_money_week_long"] - self.initial_acct_info["bitvc_btc_hold_money_week_long"]
  67.   self.remaining_delta_cash = long_pos_money_delta - short_pos_money_delta  # 代表着增加了多少开多的money,需要减去(sell)
  68.   if self.remaining_delta_cash != 0:
  69.   self.timeLog("剩余 %.4f 数量还没有平" % self.remaining_delta_cash)
  70.   # 查询bitvc深度数据
  71.   try:
  72.   bitvcDepth = copy.deepcopy(self.depth_data)["bitvc"]
  73.   except Exception:
  74.   self.timeLog("尚未取得bitvc深度数据")
  75.   continue
  76.   # 查看行情信息时间戳是否合理
  77.   timestamp_list = [bitvcDepth["time"]]
  78.   if not self.check_time(timestamp_list):
  79.   self.timeLog("获取的行情信息时间延迟过大,被舍弃,进入下一循环")
  80.   continue
  81.   self.timeLog("记录心跳信息...")
  82.   self.heart_beat_time.value = time.time()
  83.   asks = bitvcDepth["asks"]
  84.   bids = bitvcDepth["bids"]
  85.   bitvc_sell_1_price = float(asks[len(asks) - 1][0])
  86.   bitvc_buy_1_price = float(bids[0][0])
  87.   margin = bitvc_sell_1_price - bitvc_buy_1_price
  88.   future_order_sell_price = bitvc_sell_1_price - 0.5*margin*self.sell_cut
  89.   future_order_buy_price = bitvc_buy_1_price + 0.5*margin*self.buy_cut
  90.   future_order_sell_money = 100
  91.   future_order_buy_money = 100
  92.   if self.remaining_delta_cash > 0: #bought too much
  93.   future_order_sell_money += self.remaining_delta_cash
  94.   future_order_sell_price -= 0.2*margin*self.sell_cut
  95.   future_order_buy_price -= 0.1*margin*self.buy_cut
  96.   else:
  97.   future_order_buy_money += abs(self.remaining_delta_cash)
  98.   future_order_buy_price += 0.2*margin*self.buy_cut
  99.   future_order_sell_price += 0.1*margin*self.sell_cut
  100.   diff_percentage = (future_order_sell_price - future_order_buy_price)/future_order_sell_price
  101.   if diff_percentage < self.trade_threshold:
  102.   self.timeLog("future_order_sell_price: %.2f, future_order_buy_price: %.2f, diff percentage: %.6f%% smaller than trade threshold: %.6f%%, so ignore and continue" % ( future_order_sell_price, future_order_buy_price, diff_percentage*100, self.trade_threshold*100))
  103.   continue
  104.   bitvc_btc_hold_money_week_long = acct_info["bitvc_btc_hold_money_week_long"]
  105.   bitvc_btc_hold_money_week_short = acct_info["bitvc_btc_hold_money_week_short"]
  106.   global sold_money
  107.   sold_money = 0
  108.   global bought_money
  109.   bought_money = 0
  110.   # 策略下单参数
  111.   coin_type = self.coin_type
  112.   contract_type = self.contract_type
  113.   def loop1():
  114.   # place sell order
  115.   order_id_list_sell = []
  116.   if bitvc_btc_hold_money_week_long > future_order_sell_money:
  117.   order_id_list_sell.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_CLOSE, helper.CONTRACT_TRADE_TYPE_SELL, future_order_sell_price, future_order_sell_money, leverage=self.leverage))
  118.   else:
  119.   if bitvc_btc_hold_money_week_long > 0:
  120.   order_id_list_sell.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_CLOSE, helper.CONTRACT_TRADE_TYPE_SELL, future_order_sell_price, bitvc_btc_hold_money_week_long, leverage=self.leverage))
  121.   if future_order_sell_money-bitvc_btc_hold_money_week_long > 0:
  122.   order_id_list_sell.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_OPEN, helper.CONTRACT_TRADE_TYPE_SELL, future_order_sell_price, future_order_sell_money-bitvc_btc_hold_money_week_long, leverage=self.leverage))
  123.   if self.remaining_delta_cash > 0:
  124.   bitvc_order_query_retry_maximum_times = 100
  125.   bitvc_order_cancel_query_retry_maximum_times = 10
  126.   else:
  127.   bitvc_order_query_retry_maximum_times = 100
  128.   bitvc_order_cancel_query_retry_maximum_times = 10
  129.   global sold_money
  130.   for order_id in order_id_list_sell:
  131.   if order_id is not None:
  132.   tmp = self.bitvc_order_wait_and_cancel(coin_type, contract_type, order_id, returnProcessedMoney=True, bitvc_order_query_retry_maximum_times=bitvc_order_query_retry_maximum_times, bitvc_order_cancel_query_retry_maximum_times=bitvc_order_cancel_query_retry_maximum_times)
  133.   if tmp is not None:
  134.   sold_money += tmp
  135.   order_id_list_sell = []
  136.   if sold_money < future_order_sell_money and bought_money > 0: # buy side is partially filled or filled
  137.   adjusted_future_order_sell_price = future_order_buy_price * (1 + 0.0003)
  138.   adjusted_future_order_sell_money = future_order_sell_money - sold_money
  139.   if bitvc_btc_hold_money_week_long - sold_money > adjusted_future_order_sell_money:
  140.   order_id_list_sell.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_CLOSE, helper.CONTRACT_TRADE_TYPE_SELL, adjusted_future_order_sell_price, adjusted_future_order_sell_money, leverage=self.leverage))
  141.   else:
  142.   if bitvc_btc_hold_money_week_long - sold_money > 0:
  143.   order_id_list_sell.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_CLOSE, helper.CONTRACT_TRADE_TYPE_SELL, adjusted_future_order_sell_price, bitvc_btc_hold_money_week_long - sold_money, leverage=self.leverage))
  144.   if bitvc_btc_hold_money_week_long - sold_money < 0:
  145.   #already opened short
  146.   remaining_short = adjusted_future_order_sell_money
  147.   else:
  148.   remaining_short = adjusted_future_order_sell_money - (bitvc_btc_hold_money_week_long - sold_money)
  149.   if remaining_short > 0:
  150.   order_id_list_sell.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_OPEN, helper.CONTRACT_TRADE_TYPE_SELL, adjusted_future_order_sell_price, remaining_short, leverage=self.leverage))
  151.   for order_id in order_id_list_sell:
  152.   if order_id is not None:
  153.   tmp = self.bitvc_order_wait_and_cancel(coin_type, contract_type, order_id, returnProcessedMoney=True, bitvc_order_query_retry_maximum_times=bitvc_order_query_retry_maximum_times, bitvc_order_cancel_query_retry_maximum_times=bitvc_order_cancel_query_retry_maximum_times)
  154.   if tmp is not None:
  155.   sold_money += tmp
  156.   def loop2():
  157.   # place buy order
  158.   order_id_list_buy = []
  159.   if bitvc_btc_hold_money_week_short > future_order_buy_money:
  160.   order_id_list_buy.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_CLOSE, helper.CONTRACT_TRADE_TYPE_BUY, future_order_buy_price, future_order_buy_money, leverage=self.leverage))
  161.   else:
  162.   if bitvc_btc_hold_money_week_short > 0:
  163.   order_id_list_buy.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_CLOSE, helper.CONTRACT_TRADE_TYPE_BUY, future_order_buy_price, bitvc_btc_hold_money_week_short, leverage=self.leverage))
  164.   if future_order_buy_money-bitvc_btc_hold_money_week_short > 0:
  165.   order_id_list_buy.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_OPEN, helper.CONTRACT_TRADE_TYPE_BUY, future_order_buy_price, future_order_buy_money-bitvc_btc_hold_money_week_short, leverage=self.leverage))
  166.   if self.remaining_delta_cash < 0:
  167.   bitvc_order_query_retry_maximum_times = 100
  168.   bitvc_order_cancel_query_retry_maximum_times = 10
  169.   else:
  170.   bitvc_order_query_retry_maximum_times = 100
  171.   bitvc_order_cancel_query_retry_maximum_times = 10
  172.   global bought_money
  173.   for order_id in order_id_list_buy:
  174.   if order_id is not None:
  175.   tmp = self.bitvc_order_wait_and_cancel(coin_type, contract_type, order_id, returnProcessedMoney=True, bitvc_order_query_retry_maximum_times=bitvc_order_query_retry_maximum_times, bitvc_order_cancel_query_retry_maximum_times=bitvc_order_cancel_query_retry_maximum_times)
  176.   if tmp is not None:
  177.   bought_money += tmp
  178.   order_id_list_buy = []
  179.   if bought_money < future_order_buy_money and sold_money > 0: # sell side is partially filled or filled
  180.   adjusted_future_order_buy_price = future_order_sell_price * (1 - 0.0003)
  181.   adjusted_future_order_buy_money = future_order_buy_money - bought_money
  182.   if bitvc_btc_hold_money_week_short - bought_money > adjusted_future_order_buy_money:
  183.   order_id_list_buy.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_CLOSE, helper.CONTRACT_TRADE_TYPE_BUY, adjusted_future_order_buy_price, adjusted_future_order_buy_money, leverage=self.leverage))
  184.   else:
  185.   if bitvc_btc_hold_money_week_short - bought_money > 0:
  186.   order_id_list_buy.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_CLOSE, helper.CONTRACT_TRADE_TYPE_BUY, adjusted_future_order_buy_price, bitvc_btc_hold_money_week_short - bought_money, leverage=self.leverage))
  187.   if bitvc_btc_hold_money_week_short - bought_money < 0:
  188.   # already opened long
  189.   remaining_long = adjusted_future_order_buy_money
  190.   else:
  191.   remaining_long = adjusted_future_order_buy_money - (bitvc_btc_hold_money_week_short - bought_money)
  192.   if remaining_long > 0:
  193.   order_id_list_buy.append(self.bitvc_order(coin_type, contract_type, helper.CONTRACT_ORDER_TYPE_OPEN, helper.CONTRACT_TRADE_TYPE_BUY, adjusted_future_order_buy_price, remaining_long, leverage=self.leverage))
  194.   for order_id in order_id_list_buy:
  195.   if order_id is not None:
  196.   tmp = self.bitvc_order_wait_and_cancel(coin_type, contract_type, order_id, returnProcessedMoney=True, bitvc_order_query_retry_maximum_times=bitvc_order_query_retry_maximum_times, bitvc_order_cancel_query_retry_maximum_times=bitvc_order_cancel_query_retry_maximum_times)
  197.   if tmp is not None:
  198.   bought_money += tmp
  199.   t1 = threading.Thread(target=loop1, name='LoopThread1')
  200.   t2 = threading.Thread(target=loop2, name='LoopThread2')
  201.   t1.start()
  202.   t2.start()
  203.   t1.join()
  204.   t2.join()
  205.   if len(self.order_info_list) > 0:
  206.   transaction_id = helper.getUUID()
  207.   for order_info in self.order_info_list:
  208.   coinType = self.coinMarketType
  209.   marketType = order_info["marketType"]
  210.   order_id = order_info["order_id"]
  211.   self.put_order_info_in_queue(coinType, marketType, order_id, transaction_id)
  212.   self.cancel_pending_orders()
  213.   self.latest_trade_time = time.time()
复制代码
四、策略实盘运行结果展示策略在运行了半个小时之后,成功地抓住了两次做市机会,胜率100%!在比特币基准收益为-0.03%的情况下,本策略30分钟收益达到0.12%。



分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1008
帖子:253
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP