Example #1
0
    def _trade(self, coin):
        try:
            symbol = (coin + "_USDT").upper()

            future_first = self.pool.submit(self.first_api.fetch_depth, symbol)
            future_second = self.pool.submit(self.second_api.fetch_depth, symbol)

            first_depth = future_first.result()
            second_depth = future_second.result()

            first_bid, first_ask, second_bid, second_ask = self.analyze_price_from_depth(first_depth, second_depth,
                                                                                         coin)

            left_buy_price, left_sell_price, right_buy_price, right_sell_price = \
                self.price_chooser.choose(first_bid, first_ask, second_bid, second_ask)

            a = fix_float_radix(left_sell_price / right_buy_price)  # 左卖右买
            b = fix_float_radix(right_sell_price / left_buy_price)  # 左买右卖

            logging.info("策略结果 %s\t%s, 阈值: %s\t%s" % (a, b, self.cur_a, self.cur_b))
            if self.debug:
                return

            self.insert_diff_to_table(coin, a, b)
            if max(a, b) < 1.01 and self.has_unfinish_order():
                logging.info("利润太小且有未完成订单")
            else:
                if a >= self.cur_a:
                    self.miss_a = 0
                    if self.ts_got_a > 0 and cur_ms() - self.ts_got_a < 60000:
                        self.trade_from_left_to_right(coin, symbol, right_buy_price, left_sell_price, a)
                    self.ts_got_a = cur_ms()
                else:
                    self.miss_a += 1
                    if self.miss_a > 9:
                        self.cur_a = max(a - 0.0001, self.min_a)
                if b >= self.cur_b:
                    self.miss_b = 0
                    if self.ts_got_b > 0 and cur_ms() - self.ts_got_b < 60000:
                        self.trade_from_right_to_left(coin, symbol, left_buy_price, right_sell_price, b)
                    self.ts_got_b = cur_ms()
                else:
                    self.miss_b += 1
                    if self.miss_b > 9:
                        self.cur_b = max(b - 0.0001, self.min_b)
                self.refresh_strategy_min_v()
        except Exception, e:
            logging.exception("")
Example #2
0
 def back_test(self,
               base_exchange,
               trade_exchange,
               symbol,
               begin_time,
               end_time=None):
     self.backtest = True
     self.diff_tablename = "abs_diff_%s_%s" % (trade_exchange.id,
                                               base_exchange.id)
     sql = "select * from " + self.diff_tablename + " where symbol = ? and ts > ? and ts < ?"
     if not end_time:
         end_time = cur_ms()
     data = self.engine.fetch_row(sql, (symbol, begin_time, end_time))
     print begin_time, end_time
     for x in data:
         x.ar = ms_to_str(x.ts)
         self.bt_record = x
         bt = Ticker(x['base_bid'],
                     x['base_ask'],
                     x['base_price'],
                     ms=x['ts'])
         tt = Ticker(x['trade_bid'],
                     x['trade_ask'],
                     x['trade_price'],
                     ms=x['ts'])
         self.back_test_tick(bt, tt, symbol)
     print self.bt_benefit * 0.01
Example #3
0
    def sell(self, price=None, role=None):
        if self.bt_force_buy_first and self.prod_status == BtStatus.INIT:
            logging.info("没有买单, 不能卖")
            return
        if not (self.prod_status == BtStatus.INIT or self.prod_status == BtStatus.SUCCESS_BUY_ORDER):
            logging.info("没有买单, 不能卖")
            return

        amount = self.buy_amount
        if not price:
            if role == 'maker':
                price = self.okex_exchange.fetch_depth(self.symbol)['asks'][-1][0]
            else:
                price = self.okex_exchange.fetch_depth(self.symbol)['bids'][0][0]
        logging.info("try sell, price %s, amount: %s" % (price, amount))
        if not self._check_sell_price_is_ok(price):
            logging.warn("卖价太低了, 等吧, buy: %s, sell: %s" % (self.buy_price, price))
            return
        if self.debug:
            order_id = cur_ms()
            self.prod_status = BtStatus.SUCCESS_SELL_ORDER
        else:
            record_id = self.order_manager.init_order(self.okex_exchange.id, self.symbol, 'sell', amount, price)
            order_id = self.okex_exchange.sell_limit(self.symbol, price=price, amount=amount)
            self.order_manager.update_ex_id(record_id, order_id)
            self.prod_status = BtStatus.PLACE_SELL_ORDER

        logging.info("发送卖单成功 sell_order_id: %s" % order_id)
        slack("sell price %s" % price)
Example #4
0
 def insert_diff_to_table(self, symbol, trade_ticker, base_ticker):
     sql = "insert into " + self.diff_tablename + \
           " (symbol, base_bid, base_ask, base_price, trade_bid, trade_ask, trade_price, ts) values (?, ?, ?, ?, ?, ?, ?, ?)"
     self.engine.execute(
         sql,
         (symbol, base_ticker.bid, base_ticker.ask, base_ticker.price,
          trade_ticker.bid, trade_ticker.ask, trade_ticker.price, cur_ms()))
Example #5
0
    def record_account(self):
        sql = "insert into `account` values (null, ?, ?)"
        acc = {}
        for k, v in self.exchanges.iteritems():
            acc[k] = str(v.account())

        self.engine.execute(sql, (json.dumps(acc), cur_ms()))
Example #6
0
    def insert(self, name, first_order_id, second_order_id, benefit, amount):
        sql = "insert into `strategy` (name, first_order_id, second_order_id, benefit, amount, ts) values \
              (?, ?, ?, ?, ?, ?)"

        a = self.engine.execute(
            sql,
            (name, first_order_id, second_order_id, benefit, amount, cur_ms()))
        return a.lastrowid
Example #7
0
    def init_order(self, exchange, coin, side, amount, price, type="limit"):
        coin = coin.lower()
        sql = "insert into `order` (exchange, coin, type, side, amount, price, status, ts) values \
			(?, ?, ?, ?, ?, ?, ?, ?)"

        a = self.engine.execute(sql, (exchange, coin, type, side, amount,
                                      price, ORDER_STATUS.INIT, cur_ms()))
        return a.lastrowid
Example #8
0
 def refresh_back_context(self):
     now = cur_ms()
     if now - self.last_fetch_ts < 3 * 60 * 1000: # 3min one time
         return False, None 
     now = arrow.now().to('local')
     res = []
     for strategy in ('ab', 'ba'):
         big_window = self._get_base_thres_by_window(strategy, now.shift(hours=-2).timestamp * 1000, 40)
         mid_window = self._get_base_thres_by_window(strategy, now.shift(hours=-1).timestamp * 1000, 25)
         small_window = self._get_base_thres_by_window(strategy, now.shift(minutes=-5).timestamp * 1000, 5)
         estimate_thres = (big_window * 2 + mid_window * 3 + small_window * 5) / 10
         if estimate_thres < 0.8:
             return False, None
         res.append(estimate_thres)
     logging.info("back see threshold %s" % res)
     self.last_fetch_ts = cur_ms()
     return True, res 
Example #9
0
 def refresh_back_context(self):
     now = cur_ms()
     if now - self.last_fetch_ts < 3 * 60 * 1000:  # 3min one time
         return False, None
     now = arrow.now().to('local')
     res = []
     for strategy in ('ab', 'ba'):
         big_window = self._get_base_thres_by_window(
             strategy,
             now.shift(hours=-2).timestamp * 1000, 40)
         mid_window = self._get_base_thres_by_window(
             strategy,
             now.shift(hours=-1).timestamp * 1000, 25)
         small_window = self._get_base_thres_by_window(
             strategy,
             now.shift(minutes=-5).timestamp * 1000, 5)
         estimate_thres = (big_window * 2 + mid_window * 3 +
                           small_window * 5) / 10
         if estimate_thres < 0.8:
             return False, None
         res.append(estimate_thres)
     logging.info("back see threshold %s" % res)
     self.last_fetch_ts = cur_ms()
     return True, res
Example #10
0
 def buy(self, amount, role):
     if not (self.prod_status == BtStatus.INIT or self.prod_status == BtStatus.SUCCESS_SELL_ORDER):
         logging.info("不是初始状态或者卖单未完成, 不能买")
         return
     if role == 'maker':
         price = self.okex_exchange.fetch_depth(self.symbol)['bids'][0][0]
     else:
         price = self.okex_exchange.fetch_depth(self.symbol)['asks'][-1][0]
     logging.info("try buy, price %s, amount: %s" % (price, self.amount))
     if self.debug:
         order_id = cur_ms()
         self.prod_status = BtStatus.SUCCESS_BUY_ORDER
     else:
         buy_record_id = self.order_manager.init_order(self.okex_exchange.id, self.symbol, 'buy', self.amount, price)
         order_id = self.okex_exchange.buy_limit(self.symbol, price=price, amount=self.amount)
         self.order_manager.update_ex_id(buy_record_id, order_id)
         self.buy_price = price
         self.prod_status = BtStatus.PLACE_BUY_ORDER
     logging.info("发送买单成功 buy_order_id: %s" % order_id)
     slack("buy price %s" % price)
Example #11
0
    def sell(self, price=None, role=None):
        if self.bt_force_buy_first and self.prod_status == BtStatus.INIT:
            logging.info("没有买单, 不能卖")
            return
        if not (self.prod_status == BtStatus.INIT
                or self.prod_status == BtStatus.SUCCESS_BUY_ORDER):
            logging.info("没有买单, 不能卖")
            return

        amount = self.buy_amount
        if not price:
            if role == 'maker':
                price = self.okex_exchange.fetch_depth(
                    self.symbol)['asks'][-1][0]
            else:
                price = self.okex_exchange.fetch_depth(
                    self.symbol)['bids'][0][0]
        logging.info("try sell, price %s, amount: %s" % (price, amount))
        if not self._check_sell_price_is_ok(price):
            logging.warn("卖价太低了, 等吧, buy: %s, sell: %s" %
                         (self.buy_price, price))
            return
        if self.debug:
            order_id = cur_ms()
            self.prod_status = BtStatus.SUCCESS_SELL_ORDER
        else:
            record_id = self.order_manager.init_order(self.okex_exchange.id,
                                                      self.symbol, 'sell',
                                                      amount, price)
            order_id = self.okex_exchange.sell_limit(self.symbol,
                                                     price=price,
                                                     amount=amount)
            self.order_manager.update_ex_id(record_id, order_id)
            self.prod_status = BtStatus.PLACE_SELL_ORDER

        logging.info("发送卖单成功 sell_order_id: %s" % order_id)
        slack("sell price %s" % price)
Example #12
0
 def buy(self, amount, role):
     if not (self.prod_status == BtStatus.INIT
             or self.prod_status == BtStatus.SUCCESS_SELL_ORDER):
         logging.info("不是初始状态或者卖单未完成, 不能买")
         return
     if role == 'maker':
         price = self.okex_exchange.fetch_depth(self.symbol)['bids'][0][0]
     else:
         price = self.okex_exchange.fetch_depth(self.symbol)['asks'][-1][0]
     logging.info("try buy, price %s, amount: %s" % (price, self.amount))
     if self.debug:
         order_id = cur_ms()
         self.prod_status = BtStatus.SUCCESS_BUY_ORDER
     else:
         buy_record_id = self.order_manager.init_order(
             self.okex_exchange.id, self.symbol, 'buy', self.amount, price)
         order_id = self.okex_exchange.buy_limit(self.symbol,
                                                 price=price,
                                                 amount=self.amount)
         self.order_manager.update_ex_id(buy_record_id, order_id)
         self.buy_price = price
         self.prod_status = BtStatus.PLACE_BUY_ORDER
     logging.info("发送买单成功 buy_order_id: %s" % order_id)
     slack("buy price %s" % price)
Example #13
0
 def insert_st_pair(self, ab, ba):
     if self.debug:
         return
     sql = "insert into st_pair (`name`, ab, ba, fee, ts) values (?, ? ,? ,? ,?)"
     res = self.engine.execute(sql, (self.st_pair_name, ab, ba, self.fee, cur_ms()))
     return res.lastrowid
Example #14
0
 def insert_diff_to_table(self, coin, a, b):
     sql = "insert into " + self.diff_tablename + " (coin, ab, ba, ts) values (?, ?, ?, ?)"
     self.engine.execute(sql, (coin, a, b, cur_ms()))
Example #15
0
 def success(self, id):
     sql = "update `order` set status = ?, success_ts = ? where id = ?"
     self.engine.execute(sql, (ORDER_STATUS.SUCCESS, cur_ms(), id))
Example #16
0
 def insert(self, name, first_order_id, second_order_id, benefit, amount):
     sql = "insert into `strategy` (name, first_order_id, second_order_id, benefit, amount, ts) values \
           (?, ?, ?, ?, ?, ?)"
     a = self.engine.execute(sql, (name, first_order_id, second_order_id, benefit, amount, cur_ms()))
     return a.lastrowid
Example #17
0
 def success(self, id):
     sql = "update `order` set status = ?, success_ts = ? where id = ?"
     self.engine.execute(sql, (ORDER_STATUS.SUCCESS, cur_ms(), id))
Example #18
0
    def init_order(self, exchange, coin, side, amount, price, type="limit"):
        coin = coin.lower()
        sql = "insert into `order` (exchange, coin, type, side, amount, price, status, ts) values \
			(?, ?, ?, ?, ?, ?, ?, ?)"
        a = self.engine.execute(sql, (exchange, coin, type, side, amount, price, ORDER_STATUS.INIT, cur_ms()))
        return a.lastrowid