Exemple #1
0
    def test_entrusts_post(self, market_id, price, entrust_type, trade_type,
                           volume, trigger_price, auto_cancel_at):
        """Test case for entrusts_post

        创建委托单  # noqa: E501
        """
        payload = PostEntrustsRequest()
        payload.market_id = market_id
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.trigger_price = trigger_price
        payload.volume = volume
        payload.auto_cancel_at = auto_cancel_at
        try:
            api.entrusts_post(body=payload, async_req=True)
        except ApiException as e:
            if price == '' or market_id == '':
                assert e.status == 400
    def test_high_buy_deal_success(self, market_id, price, entrust_type,
                                   trade_type, volume, trigger_price,
                                   auto_cancel_at, volume_flag, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 1000_00
        # payload.auto_cancel_at = auto_cancel_at
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空

        before_market_buy = api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        before_makret_sell = api.entrusts_post(body=payload)
        # 恢复限价

        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        # 符合精度的价格和数目
        price, volume = get_random_price_and_volume(special_info['precision'])
        payload.price = price
        payload.volume = volume
        price_range = (1 / (10**(int(special_info['precision']) - 1)))
        sub_range = (1 / (10**(int(special_info['precision']) - 1)))
        inc_range = (1 / (10**(int(special_info['precision']) - 1)))
        sell_id = ''
        buy_id = ''
        try:
            # 不管是sell还是buy,只有less或者more两种情况,所以忽略sell或者buy
            if volume_flag in ('sell_less', 'buy_less'):
                payload.volume = round(payload.volume - sub_range,
                                       int(special_info['precision']))
            if volume_flag in ('buy_more', 'sell_more'):
                payload.volume = round(payload.volume + inc_range,
                                       int(special_info['precision']))
            print(f"{volume_flag}payload{payload}")
            first_result = api.entrusts_post(body=payload)
            if trade_type == 'buy':
                buy_id = first_result.order_id
                payload.trade_type = 'sell'
                payload.volume = volume
                payload.price = round(payload.price - price_range,
                                      int(special_info['precision']))
                print(f"{trade_type}payload{payload}")
                result = api.entrusts_post(body=payload)
                sell_id = result.order_id
            else:
                payload.trade_type = 'buy'
                sell_id = first_result.order_id
                payload.price = round(payload.price + price_range,
                                      int(special_info['precision']))
                payload.volume = volume
                print(f"{trade_type}payload{payload}")
                result = api.entrusts_post(body=payload)
                buy_id = result.order_id

        except ApiException as e:
            assert e.status == 400

        time.sleep(5)
        # 最新的default 的pagesize估计能够把刚下的单捞出来
        result = api.entrusts_get(status=['done'])
        print(result)
        ids = [i.order_id for i in result.items]

        # 买单多或着卖单少,所以买单剩
        if volume_flag in ('buy_more', 'sell_less'):
            assert sell_id in ids  # 买单多卖完全部成交
            # 测试撤回多余单
            api.entrusts_id_cancel_post(buy_id)
        # 卖单多或者买单少所以卖单剩
        if volume_flag in ('sell_more', 'buy_less'):
            assert buy_id in ids  # 卖单多买单全部成交
            # 测试撤回多余单
            api.entrusts_id_cancel_post(sell_id)
Exemple #3
0
    def test_timelimit_create_et_cancel_buy_sell(self, market_id, price,
                                                 entrust_type, trade_type,
                                                 volume, trigger_price,
                                                 auto_cancel_at,
                                                 special_login):
        payload = PostEntrustsRequest()
        payload.market_id = market_id
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.trigger_price = trigger_price
        payload.volume = volume
        payload.auto_cancel_at = auto_cancel_at
        # login
        special_login([main_entrust_api, main_ac_api])

        # 清空
        main_entrust_api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        main_entrust_api.entrusts_post(body=payload)

        try:
            first_result = main_entrust_api.entrusts_post(body=payload)
            logger.info(f"{trade_type} id: {first_result.order_id}")
        except ApiException as e:
            if e.status == 400:
                logger.error('下单失败,没钱')
            raise e

        # 如果first_result的post参数trade_type是'buy'那么就要创建'sell'单
        if trade_type == 'buy':
            buy_id = first_result.order_id
            payload.trade_type = 'sell'
            result = main_entrust_api.entrusts_post(body=payload)
            sell_id = result.order_id
            logger.info(f"sell id :{sell_id}")
        # 如果first_result的post参数trade_type是'sell'那么就要创建'sell'单
        else:
            payload.trade_type = 'buy'
            sell_id = first_result.order_id
            result = main_entrust_api.entrusts_post(body=payload)
            buy_id = result.order_id
            logger.info(f"buy id :{buy_id}")

        time.sleep(5)
        result = main_entrust_api.entrusts_get(status=['done'])
        ids = [i.order_id for i in result.items]
        assert sell_id in ids
        assert buy_id in ids

        result_sell = main_entrust_api.trades_get(order_id=sell_id)
        logger.info(f"get result sell trades: {result}")
        result_buy = main_entrust_api.trades_get(order_id=buy_id)
        logger.info(f"get result buy trades:  {result}")
        assert hasattr(result_sell.items[0], 'price')
        assert hasattr(result_buy.items[0], 'price')
        assert float(result_buy.items[0].price) == price
        assert float(result_sell.items[0].price) == price
        logger.info('ending order')
        # 获取本地下单时间
        local_tm = datetime.fromtimestamp(0)
        # 本地时间转换为utc时间
        local_to_utc_time = datetime.utcfromtimestamp(local_tm.timestamp())
    def igtest_same_price_volume_multi_sell_first(self, market_id, price,
                                                  entrust_type, trade_type,
                                                  volume, trigger_price,
                                                  auto_cancel_at, volume_flag,
                                                  special_login, with_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_0
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 1000_0
        # payload.auto_cancel_at = auto_cancel_at
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']

        # 清空
        before_market_buy = api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        before_makret_sell = api.entrusts_post(body=payload)

        # 恢复限价

        price, _ = get_random_price_and_volume(special_info['precision'])  # 精度
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.volume = volume

        sell_ids = []
        sell_volume = []
        buy_id = ''
        try:
            assert volume_flag == 'multi_sell'
            # 多个卖单与单个买单
            for i in range(5):
                _, volume = get_random_price_and_volume(
                    special_info['precision'])  # 精度
                sell_volume.append(volume)
                payload.volume = volume
                result = api.entrusts_post(body=payload)
                sell_ids.append(result.order_id)

            # 单买
            payload.trade_type = 'buy'
            # sell_id = first_result['id']
            payload.volume = sum(sell_volume)
            result = api.entrusts_post(body=payload)
            buy_id = result.order_id
        except ApiException as e:
            if e.status == 400:
                raise e

        # 获取已成交委托单
        time.sleep(5)
        logger.info(f"sell_ids: {sell_ids}, buy_id: {buy_id}")
        result = api.entrusts_get(status=['done'])
        ids = [i.order_id for i in result.items]
        assert buy_id in ids

        result_sell = api.trades_get(order_id=buy_id)
        assert hasattr(result_sell.items[0], "price")
        assert float(result_sell.items[0].price) == price

        with_login('tenant', [tenant_api], account=TENANT, password=TENANTPWD)
        tenant_entrusts = tenant_api.exchange_entrusts_get(
            status=['done'], uid=special_info['account_id'])
        ids = [i.order_id for i in tenant_entrusts.items]
        assert buy_id in ids

        tenant_trades = tenant_api.exchange_trade_history_get(order_id=buy_id)
        assert hasattr(tenant_trades.items[0], "price")
        assert float(tenant_trades.items[0].price) == price
    def igtest_multi_sell_volume_lt_buy(
            self, market_id, price, entrust_type, trade_type, volume,
            trigger_price, auto_cancel_at, volume_flag, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_000
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.volume = 1000_000
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空
        sell_clear_order = api.entrusts_post(body=payload)
        print(f"sell clear: {sell_clear_order}")
        payload.trade_type = 'buy'
        buy_clear_order = api.entrusts_post(body=payload)
        print(f"buy clear: {buy_clear_order}")

        # 恢复限价
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.volume = volume
        # 添加多笔卖单和一笔买单
        sell_trades = []
        inc_range = 20
        payload.trade_type = 'sell'
        for i in range(5):
            payload.price, payload.volume = get_random_price_and_volume(special_info['precision'])
            r = api.entrusts_post(body=payload)
            sell_trades.append({
                'order_id': r.order_id,
                'price': payload.price,
                'volume': payload.volume
            })

        payload.trade_type = 'buy'
        if volume_flag == 'eq_sell_price':
            # 买单价格高于卖单最低价格,且低于卖单最高价格,且等于某一中间卖单价格,
            sorted_sell_entrusts = sorted(sell_trades, key=lambda x: x['price'])
            payload.price = sorted_sell_entrusts[2]['price']
        else:
            # 买单价格高于卖单最低价格,且低于卖单最高价格,且不等于任何卖单价格
            sorted_sell_entrusts = sorted(sell_trades, key=lambda x: x['price'])
            sell_price = (sorted_sell_entrusts[2]['price'] +
                          sorted_sell_entrusts[3]['price']) / 2
            payload.price = round(sell_price, int(special_info['precision']))

        # 买单购买数量大于,低于买单价格的卖单总数量,均应以卖单价格成交,
        payload.volume = round(
            sum([i['volume'] for i in sorted_sell_entrusts[:3]]) + inc_range,
            8 - int(special_info['precision']))
        r = api.entrusts_post(body=payload)
        buy_trade_id = r.order_id
        time.sleep(5)

        entrust_res = api.entrusts_get(status=['done'])
        # 买单没有完全成交
        assert buy_trade_id not in [i.order_id for i in entrust_res.items]

        trades = api.trades_get(order_id=buy_trade_id)
        assert buy_trade_id in [i.order_id for i in trades.items]

        # 买卖单剩余,测试剩余单撤销
        for i in [i['order_id']
                  for i in sorted_sell_entrusts[3:]] + [buy_trade_id]:
            api.entrusts_id_cancel_post(i)
    def test_multi_sell_volume_gt_buy(
            self, market_id, price, entrust_type, trade_type, volume,
            trigger_price, auto_cancel_at, volume_flag, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000000
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.volume = 1000000
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空
        api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        api.entrusts_post(body=payload)

        # 恢复限价
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.volume = volume
        # 添加多笔卖单和一笔买单
        buy_trades = []
        sub_range = 0.001
        payload.trade_type = 'sell'
        for i in range(5):
            payload.price, payload.volume = get_random_price_and_volume(special_info['precision'])
            r = api.entrusts_post(body=payload)
            buy_trades.append({
                'order_id': r.order_id,
                'price': payload.price,
                'volume': payload.volume
            })

        payload.trade_type = 'buy'
        if volume_flag == 'eq_sell_price':
            # 限价买单价格低于卖单最高价格,且高于卖单最低价格,且等于某一中间卖单价格
            sorted_buy_trades = sorted(buy_trades, key=lambda x: x['price'])
            payload.price = sorted_buy_trades[2]['price']
        else:
            # 限价卖单价格低于买单最高价格,且高于买单最低价格,且等且不等于任何买单价格
            sorted_buy_trades = sorted(buy_trades, key=lambda x: x['price'])
            sell_price = (sorted_buy_trades[2]['price'] +
                          sorted_buy_trades[3]['price']) / 2
            payload.price = round(sell_price, int(special_info['precision']))
        # 买单购买数量小于,低于买单价格的卖单总数量,均应以卖单价格成交[0~2]
        payload.volume = round(
            sum([i['volume'] for i in sorted_buy_trades[:3]]) - sub_range,
            8 - int(special_info['precision']))
        r = api.entrusts_post(body=payload)
        buy_trade_id = r.order_id

        time.sleep(3)
        # 买单应成交
        r = api.trades_get(order_id=buy_trade_id)
        assert hasattr(r.items[0], "volume")
        assert hasattr(r.items[0], "fee")
        assert round(sum([float(i.volume) for i in r.items]), 8-int(special_info['precision'])) == float(
            payload.volume)
        # 卖单剩余,测试剩余单撤销 index为2的卖单会剩余,所以从2开始算
        ids = [i['order_id'] for i in sorted_buy_trades[2:]]
        for i in ids:
            api.entrusts_id_cancel_post(i)
Exemple #7
0
    def test_multi_buy_volume_eq_one_sell(self, market_id, price, entrust_type,
                                          trade_type, volume, trigger_price,
                                          auto_cancel_at, volume_flag,
                                          special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.volume = 1000_00

        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']

        # 清空
        api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        api.entrusts_post(body=payload)

        # 恢复限价
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.volume = volume

        # 添加多笔买单和一笔卖单
        buy_trades = []
        payload.trade_type = 'buy'
        for i in range(5):
            payload.price, payload.volume = get_random_price_and_volume(
                special_info['precision'])
            r = api.entrusts_post(body=payload)
            buy_trades.append({
                'order_id': r.order_id,
                'price': payload.price,
                'volume': payload.volume
            })

        payload.trade_type = 'sell'
        if volume_flag == 'eq_buy_price':
            # 限价卖单价格低于买单最高价格,且高于买单最低价格,且等于某一中间买单价格
            sorted_buy_trades = sorted(buy_trades, key=lambda x: x['price'])
            payload.price = sorted_buy_trades[2]['price']
            # 卖单出售数量等于,高于卖单价格的所有买单总数量
            payload.volume = round(
                sum([i['volume'] for i in sorted_buy_trades[3:]]),
                8 - int(special_info['precision']))
        else:
            # 限价卖单价格低于买单最高价格,且高于买单最低价格,且等且不等于任何买单价格
            sorted_buy_trades = sorted(buy_trades, key=lambda x: x['price'])
            sell_price = (sorted_buy_trades[2]['price'] +
                          sorted_buy_trades[3]['price']) / 2
            payload.price = round(sell_price, int(special_info['precision']))
            # 卖单出售数量等于,高于卖单价格的所有买单总数量
            payload.volume = round(
                sum([i['volume'] for i in sorted_buy_trades[3:]]),
                8 - int(special_info['precision']))

        r = api.entrusts_post(body=payload)
        p_res = r.to_dict()
        sell_trade_id = p_res['order_id']

        time.sleep(6)
        sell_entrust_result = api.entrusts_get(status=['done'])
        sell_entrusts = sell_entrust_result.to_dict()
        done_ids = [i['order_id'] for i in sell_entrusts['items']]
        assert sell_trade_id in done_ids
        # 卖单应都成交了
        sell_result = api.trades_get(order_id=sell_trade_id)
        assert hasattr(sell_result.items[0], 'volume')
        assert hasattr(sell_result.items[0], 'fee')
        for i in sell_result.items:
            print(i.volume)
        assert round(sum([float(i.volume) for i in sell_result.items]), 8 -
                     int(special_info['precision'])) == float(payload.volume)

        # 买单剩余,测试剩余单撤销
        # 这里碰巧都是到index等于2
        ids = [i['order_id'] for i in sorted_buy_trades[:3]]

        for i in ids:
            api.entrusts_id_cancel_post(i)
Exemple #8
0
    def test_multi_sell_volume_eq(self, market_id, price, entrust_type,
                                  trade_type, volume, trigger_price,
                                  auto_cancel_at, volume_flag, special_login):

        payload = PostEntrustsRequest()
        payload.price = 1000_0
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 1000_0
        # payload.auto_cancel_at = auto_cancel_at
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空

        before_market_buy = api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        before_makret_sell = api.entrusts_post(body=payload)
        # 恢复限价

        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.volume = volume

        # 添加多笔买单和一笔卖单
        buy_trades = []
        inc_range = 1
        for i in range(5):
            payload.trade_type = 'buy'
            payload.price, payload.volume = get_random_price_and_volume(
                special_info['precision'])
            r = api.entrusts_post(body=payload)
            buy_trades.append({
                'order_id': r.order_id,
                'price': payload.price,
                'volume': payload.volume
            })

        payload.trade_type = 'sell'
        if volume_flag == 'sell_price_eq_min_buy':
            # 卖单与买单最低价格一致
            sorted_buy_trades = sorted(buy_trades, key=lambda x: x['price'])
            payload.price = sorted_buy_trades[0]['price']
            # 卖单出售数量等于所有买单总数量
        else:
            # 限价卖单价格高于买单最高价格
            sorted_buy_trades = sorted(buy_trades, key=lambda x: x['price'])
            payload.price = sorted_buy_trades[-1]['price'] + inc_range
        # 卖单出售数量等于所有买单总数量
        payload.volume = round(sum([i['volume'] for i in sorted_buy_trades]),
                               8 - int(special_info['precision']))

        r = api.entrusts_post(body=payload)
        sell_trade_id = r.order_id

        ids = [i['order_id'] for i in sorted_buy_trades]
        time.sleep(5)
        if volume_flag == 'sell_price_eq_min_buy':
            # 卖单应都成交了
            for i in sorted_buy_trades:
                result = api.trades_get(order_id=i['order_id'])
                assert result.items
                assert hasattr(result.items[0], 'volume')
                assert float(result.items[0].volume) <= float(i['volume'])
        else:
            # 买卖单剩余,测试剩余单撤销
            for i in ids + [sell_trade_id]:
                api.entrusts_id_cancel_post(i)
Exemple #9
0
    def test_same_price_volume_success(self, market_id, price, entrust_type,
                                       trade_type, volume, trigger_price,
                                       auto_cancel_at, exchange_ids, coin_id,
                                       sell_coin_id, trading_area_id, symbol,
                                       quotation_special_login):

        # login
        special_info = quotation_special_login([
            main_entrust_api, main_ac_api, main_quota_api, tenant_quota_api,
            venture_quota_api
        ])
        for i in range(20):
            price, volume = get_random_price_and_volume(
                special_info['precision'])
            coin_id = coin_id
            payload = PostEntrustsRequest()
            # payload.market_id = market_id
            payload.market_id = special_info['market_id']
            logger.info(f'下单价格:{price}')
            payload.price = price
            payload.entrust_type = entrust_type
            payload.trade_type = trade_type
            payload.trigger_price = trigger_price
            payload.volume = volume
            payload.auto_cancel_at = auto_cancel_at
            try:
                first_result = main_entrust_api.entrusts_post(body=payload)
                logger.info(f"{trade_type} id: {first_result.order_id}")
            except Exception as e:
                if e.status == 400:
                    logger.error('下单失败,没钱')
                raise e
            logger.info(f'第一次下单result:{first_result}')
            # 如果first_result的post参数trade_type是'buy'那么就要创建'sell'单
            if trade_type == 'buy':
                buy_id = first_result.order_id
                payload.trade_type = 'sell'
                result = main_entrust_api.entrusts_post(body=payload)
                sell_id = result.order_id
                logger.info(f"sell id :{sell_id}")
            # 如果first_result的post参数trade_type是'sell'那么就要创建'sell'单
            else:
                payload.trade_type = 'buy'
                sell_id = first_result.order_id
                logger.info('*' * 20)
                result = main_entrust_api.entrusts_post(body=payload)
                # logger.info('第二次下买单:', result)
                buy_id = result.order_id
                logger.info(f"buy id :{buy_id}")
            # result = api.entrusts_get(status=['done'])
            time.sleep(5)
            result = main_entrust_api.entrusts_get()
            logger.info(f'委托记录列表:{result}')
            ids = [i.order_id for i in result.items]
            result_sell = main_entrust_api.trades_get(order_id=sell_id)
            logger.info(f"get result sell trades: {result_sell}")
            result_buy = main_entrust_api.trades_get(order_id=buy_id)
            logger.info(f"get result buy trades:  {result_buy}")

        for i in range(5):
            price, volume = get_random_price_and_volume(
                special_info['precision'])
            payload = PostEntrustsRequest()
            payload.market_id = special_info['market_id']
            logger.info(f'下单价格:{price}')
            payload.price = price
            payload.entrust_type = entrust_type
            payload.trade_type = trade_type
            payload.trigger_price = trigger_price
            payload.volume = volume
            payload.auto_cancel_at = auto_cancel_at
            try:
                first_result = main_entrust_api.entrusts_post(body=payload)
                logger.info(f"{trade_type} id: {first_result.order_id}")
            except Exception as e:
                if e.status == 400:
                    logger.error('下单失败,没钱')
                raise e
            logger.info(f'第一次下单result:{first_result}')
            # 如果first_result的post参数trade_type是'buy'那么就要创建'sell'单
            if trade_type == 'buy':
                buy_id = first_result.order_id
                payload.trade_type = 'sell'
                result = main_entrust_api.entrusts_post(body=payload)
                sell_id = result.order_id
                logger.info(f"sell id :{sell_id}")
            # 如果first_result的post参数trade_type是'sell'那么就要创建'sell'单
            else:
                payload.trade_type = 'buy'
                payload.price = price - 0.55
                sell_id = first_result.order_id
                logger.info('*' * 20)
                result = main_entrust_api.entrusts_post(body=payload)
                buy_id = result.order_id
                logger.info(f"buy id :{buy_id}")
Exemple #10
0
    def test_same_price(self, market_id, price, entrust_type, trade_type,
                        volume, trigger_price, auto_cancel_at, volume_flag,
                        special_login):

        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 1000_00
        # payload.auto_cancel_at = auto_cancel_at
        # login
        special_info = special_login(
            [api, tenant_market_api, tenant_exchange_api])
        payload.market_id = special_info['market_id']
        # 清空

        before_market_buy = api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        before_makret_sell = api.entrusts_post(body=payload)
        # 恢复限价

        payload.entrust_type = entrust_type
        payload.trade_type = trade_type

        precision = special_info['precision']

        # 添加多笔买单和一笔卖单
        trades = []
        inc_range = 1 / 10**(int(precision) - 1)
        sub_range = 1 / 10**(int(precision) - 1)
        if 'buy' in volume_flag:
            payload.trade_type = 'buy'
        else:
            payload.trade_type = 'sell'
        payload.price, _ = get_random_price_and_volume(precision)
        for i in range(5):
            _, payload.volume = get_random_price_and_volume(precision)
            r = api.entrusts_post(body=payload)
            trades.append({
                'order_id': r['orderId'],
                'price': payload.price,
                'volume': payload.volume
            })

        if 'buy' in volume_flag:
            payload.trade_type = 'sell'
            payload.entrust_type = EntrustTypeMarket
        else:
            payload.trade_type = 'buy'
            payload.trade_type = EntrustTypeMarket

        # 获取服务费率
        market_rate = tenant_market_api.markets_id_get(payload.market_id)
        if 'eq' in volume_flag:
            if 'buy' in volume_flag:
                volume = sum([i['volume'] for i in trades])
            else:
                # 市价买,提供的是资金不是数量,所以需要算汇率
                volume = sum([i['volume'] * i['price'] for i in trades])
            market_volume = round(volume, int(precision))
            fee_volume = round(market_volume * float(market_rate.totalRate),
                               int(precision))
        elif 'gt' in volume_flag:
            # 42 先挂多笔价格相同限价买单,提交一笔市价卖出单,买方多余卖方   same_price_buy_gt
            # 52 先挂多笔价格相同限价卖单,提交一笔市价买单,卖方多余买方     same_price_sell_gt
            if 'buy' in volume_flag:
                volume = sum([i['volume'] for i in trades])
            else:
                # 市价买,提供的是资金不是数量,所以需要算汇率
                volume = sum([i['volume'] * i['price'] for i in trades])
            market_volume = round(volume - sub_range, int(precision))
            fee_volume = round(market_volume * float(market_rate.totalRate),
                               int(precision))
        else:
            # 43 先挂多笔价格相同限价买单,提交一笔市价卖出单,卖方多余买方   same_price_buy_lt
            # 51 先挂多笔价格相同限价卖单,提交一笔市价买单,买方多余卖方     same_price_sell_lt
            if 'buy' in volume_flag:
                volume = sum([i['volume'] for i in trades])
            else:
                # 市价买,提供的是资金不是数量,所以需要算汇率
                volume = sum([i['volume'] * i['price'] for i in trades])
            market_volume = round(volume + inc_range, int(precision))
            fee_volume = round(market_volume * float(market_rate.totalRate),
                               int(precision))

        payload.volume = round(market_volume)
        r = api.entrusts_post(body=payload)
        single_trade_id = r.order_id

        # 计算逻辑
        # 限价卖单,市价买单,买单能买多少买多少, mark_volume是买方币资金
        result = api.entrusts_get(trade_type='sell', status=['done'])
        trade_ids = [i.id for i in result.items]
        if 'sell' in volume_flag:
            tmp = market_volume  # 提供的资金
            for i in trades:
                # 市价买,提供的是资金不是数量,所以需要乘以汇率
                tmp -= (i["volume"] * i['price'])
                if tmp >= 0:
                    assert i['order_id'] in trade_ids

        # 限价买单,市价卖单,卖单能卖多少卖多少,提供的mark_volume是卖方币种
        elif 'buy' in volume_flag:
            tmp = market_volume  # 提供的货物
            for i in trades[::-1]:  # 先买再卖,从买价最高交易起
                # 市价卖,提供的是数量不是资金,所以不需要算汇率
                tmp -= i["volume"]
                if tmp >= 0:
                    assert i['order_id'] in trade_ids
        trade_info = api.trades_get(order_id=single_trade_id)
Exemple #11
0
    def test_one_buy_one_sell(self, market_id, price, entrust_type, trade_type,
                              volume, trigger_price, auto_cancel_at,
                              volume_flag, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 1000_00
        # payload.auto_cancel_at = auto_cancel_at
        # login
        special_info = special_login(
            [api, tenant_market_api, tenant_exchange_api])
        payload.market_id = special_info['market_id']
        # 清空

        before_market_buy = api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        before_makret_sell = api.entrusts_post(body=payload)
        # 恢复限价

        payload.entrust_type = entrust_type
        payload.trade_type = trade_type

        precision = special_info['precision']
        inc_range = 1 / (10**(int(precision) - 1))
        sub_range = 1 / (10**(int(precision) - 1))

        if 'buy' in volume_flag:
            payload.trade_type = 'buy'

        else:
            payload.trade_type = 'sell'

        payload.price, payload.volume = get_random_price_and_volume(precision)
        first = api.entrusts_post(body=payload)  # 限价单
        first_id = first.order_id

        if 'buy' in volume_flag:
            payload.trade_type = 'sell'
            payload.entrust_type = EntrustTypeMarket
        else:
            payload.trade_type = 'buy'
            payload.trade_type = EntrustTypeMarket

        # 获取服务费率
        market_rate = tenant_market_api.markets_id_get(payload.market_id)
        if 'eq' in volume_flag:
            market_volume = round(payload.volume * payload.price,
                                  int(precision))
            fee_volume = round(market_volume * float(market_rate.totalRate),
                               int(precision))
        elif 'gt' in volume_flag:
            # 买方大于卖方
            payload.volume = round(sub_range, int(precision))
            market_volume = round(payload.volume * payload.price,
                                  int(precision))
            fee_volume = round(market_volume * float(market_rate.totalRate),
                               int(precision))
        else:
            # 买方小于卖方
            payload.volume = round(payload.volume + inc_range, int(precision))
            market_volume = round(payload.volume * payload.price,
                                  int(precision))
            fee_volume = round(market_volume * float(market_rate.totalRate),
                               int(precision))

        payload.volume = round(market_volume, int(precision))
        r = api.entrusts_post(body=payload)
        second_trade_id = r.order_id

        first_order_info = tenant_exchange_api.exchange_entrusts_get(
            id=first_id)

        assert first_order_info.status == 'done'
        # 获取委托单详情
        second_order_info = tenant_exchange_api.exchange_entrusts_get(
            id=second_trade_id)
        # 市价单
        assert second_order_info.volume == first_order_info.volume
        trade_info = api.trades_get(order_id=first_id)
        # 手续费验证
        assert fee_volume == trade_info.items.fee
Exemple #12
0
    def test_different_price(self, market_id, price, entrust_type, trade_type,
                             volume, trigger_price, auto_cancel_at,
                             volume_flag, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 1000_00
        # payload.auto_cancel_at = auto_cancel_at
        # login
        special_info = special_login(
            [api, tenant_market_api, tenant_exchange_api])
        payload.market_id = special_info['market_id']
        # 清空

        before_market_buy = api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        before_makret_sell = api.entrusts_post(body=payload)
        # 恢复限价

        payload.entrust_type = entrust_type
        payload.trade_type = trade_type

        precision = special_info['precision']
        inc_range = 1 / (10**(int(precision) - 1))
        sub_range = 1 / (10**(int(precision) - 1))

        # buy first
        if 'buy' in volume_flag:
            payload.trade_type = 'buy'
        # sell first
        else:
            payload.trade_type = 'sell'
        trades = []
        for i in range(5):
            payload.price, payload.volume = get_random_price_and_volume(
                precision)
            r = api.entrusts_post(body=payload)
            trades.append({
                'order_id': r['orderId'],
                'price': payload.price,
                'volume': payload.volume
            })

        # 多限价的单子,要依据市价的买卖不同,从卖一往上或者买一往下去验证
        sorted_trades = sorted(trades, key=lambda x: x['price'])

        if 'buy' in volume_flag:
            payload.trade_type = 'sell'
            payload.entrust_type = EntrustTypeMarket
        else:
            payload.trade_type = 'buy'
            payload.trade_type = EntrustTypeMarket

        # 获取服务费率
        market_rate = tenant_market_api.markets_id_get(payload.market_id)
        if 'eq' in volume_flag:
            if 'buy' in volume_flag:
                volume = sum([i['volume'] for i in trades])
            else:
                # 市价买,提供的是资金不是数量,所以需要算汇率
                volume = sum([i['volume'] * i['price'] for i in trades])
            market_volume = round(volume, int(precision))
            fee_volume = round(market_volume * float(market_rate.totalRate),
                               int(precision))
        elif 'gt' in volume_flag:
            # 45 先挂多笔价格不同限价买单,提交一笔市价卖出单,买方多余卖方     different_price_buy_gt
            # 55 先挂多笔价格不同限价卖单,提交一笔市价买单,卖方多余买方      different_price_sell_gt
            if 'buy' in volume_flag:
                volume = sum([i['volume'] for i in trades])
            else:
                # 市价买,提供的是资金不是数量,所以需要算汇率
                volume = sum([i['volume'] * i['price'] for i in trades])
            market_volume = round(volume - sub_range, int(precision))
            fee_volume = market_volume * float(market_rate.totalRate)
        else:
            # 46 先挂多笔价格不同限价买单,提交一笔市价卖出单,卖方多余买方     different_price_buy_lt
            # 54 先挂多笔价格不同限价卖单,提交一笔市价买单,买方多余卖方      different_price_sell_lt
            if 'buy' in volume_flag:
                volume = sum([i['volume'] for i in trades])
            else:
                # 市价买,提供的是资金不是数量,所以需要算汇率
                volume = sum([i['volume'] * i['price'] for i in trades])
            market_volume = round(volume + inc_range, int(precision))
            fee_volume = round(market_volume * float(market_rate.totalRate),
                               int(precision))

        payload.volume = round(market_volume, int(precision))
        r = api.entrusts_post(body=payload)
        single_trade_id = r.order_id

        # 计算逻辑
        # 限价卖单,市价买单,从最低价卖单开始买起, mark_volume是买方币资金
        result = api.entrusts_get(status=['done'])
        trade_ids = [i.id for i in result]
        if 'sell' in volume_flag:
            tmp = market_volume
            for i in sorted_trades:
                # 市价买,提供的是资金不是数量,所以需要算汇率
                tmp = round(tmp - (i["volume"] * i['price']), int(precision))
                if tmp >= 0:
                    assert i['order_id'] in trade_ids

        # 限价买单,市价卖单,从最高价买单开始卖起,提供的mark_volume是卖方币种
        elif 'buy' in volume_flag:
            tmp = market_volume
            for i in sorted_trades[::-1]:
                # 市价卖,提供的是数量不是资金,所以不需要算汇率
                tmp = round(tmp - i["volume"], int(precision))
                if tmp >= 0:
                    assert i['order_id'] in trade_ids
        trade_info = api.trades_get(order_id=single_trade_id)
        # 手续费验证
        assert fee_volume == trade_info.items.fee
    def test_high_buy_multi_deal_success(self, entrust_type, trade_type,
                                         volume_flag, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 1000_00
        # payload.auto_cancel_at = auto_cancel_at
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空

        before_market_buy = api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        before_makret_sell = api.entrusts_post(body=payload)
        # 恢复限价

        payload.entrust_type = entrust_type
        payload.trade_type = trade_type

        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        precision = special_info['precision']
        inc_range = 1 / (10**(int(precision) - 1))
        sub_range = 1 / (10**(8 - int(precision) - 1))

        sell_ids = []
        sell_volume = []
        buy_ids = []
        buy_volume = []
        buy_id = ''
        sell_id = ''
        try:
            if trade_type == 'sell':
                # 多个卖单与单个买单
                sell_price, _ = get_random_price_and_volume()
                payload.price = sell_price
                for i in range(5):
                    _, volume = get_random_price_and_volume()
                    sell_volume.append(volume)
                    payload.volume = volume
                    result = api.entrusts_post(body=payload)
                    sell_ids.append(result.order_id)
            else:
                # 多个买单与单个卖单
                buy_price, _ = get_random_price_and_volume(precision)
                payload.price = round(buy_price + inc_range,
                                      int(precision))  # 买高
                for i in range(5):
                    _, volume = get_random_price_and_volume()
                    buy_volume.append(volume)
                    payload.volume = volume
                    result = api.entrusts_post(body=payload)
                    buy_ids.append(result.order_id)

            if trade_type == 'buy':
                # 单卖
                payload.trade_type = 'sell'  # 卖低
                payload.volume = sum(buy_volume)
                result = api.entrusts_post(body=payload)
                sell_id = result.order_id  # NOQA: F841
            else:
                # 单买
                payload.trade_type = 'buy'
                # sell_id = first_result['id']
                payload.price += inc_range  # 买高
                payload.volume = sum(sell_volume)  # sell_multi_eq_buy
                # 买量大于卖单多笔相加总量
                if volume_flag in ('sell_multi_lt_buy', ):
                    payload.volume = round(
                        sum(sell_volume) + (1 / (8 - int(precision))),
                        8 - int(precision))

                # 买量小于卖单多笔相加总量
                if volume_flag in ('sell_multi_gt_buy', ):
                    payload.volume = round(
                        sum(sell_volume) - sub_range, 8 - int(precision))
                result = api.entrusts_post(body=payload)
                buy_id = result.order_id

        except ApiException as e:
            return

        # 获取已成交委托单
        time.sleep(3)
        result = api.entrusts_get(status=['done'])
        ids = [i.order_id for i in result.items]

        # 买单多,所以买单剩
        if volume_flag in ('sell_multi_lt_buy', ):
            assert buy_id not in ids
            # 测试撤回多余单
            api.entrusts_id_cancel_post(buy_id)

        # 卖单多所以卖单剩
        if volume_flag in ('sell_multi_gt_buy', ):
            need_cancel_sell_ids = [i for i in sell_ids if i not in ids]
            assert buy_id in ids
            # 测试撤回多余单
            for i in need_cancel_sell_ids:
                api.entrusts_id_cancel_post(i)
Exemple #14
0
    def test_takeprofit_sell(self, market_id, price, entrust_type, trade_type,
                             volume, trigger_price, auto_cancel_at,
                             special_login, with_login):
        # 构造entrust_post请求对象
        payload = PostEntrustsRequest()
        payload.market_id = market_id
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.trigger_price = trigger_price
        payload.volume = volume
        payload.auto_cancel_at = auto_cancel_at
        # special_login
        special_login([api])
        # login
        with_login('staff', [staff_api], 'account',
                   'password')  # TODO add account
        # 1.先下一买一卖,构造最新成交价
        try:
            first_result = api.entrusts_post(body=payload, async_req=True)
            buy1_id = first_result.get('orderid', '')
            payload.trade_type = 'sell'
            result = api.entrusts_post(body=payload, async_req=True)
            sell1_id = result.get('orderid', '')
            # 1.1 检查成交记录列表,委托交易列表
            entrust_res = api.entrusts_get(status=['done'], async_req=True)
            assert entrust_res['items']
            entrust_list = [res["orderid"] for res in entrust_res['items']]
            assert buy1_id in entrust_list
            assert sell1_id in entrust_list
            # 1.2 检查委托交易列表
            trade_res = api.trades_get(order_id=buy1_id, async_req=True)
            assert trade_res['items']
            # 获取最新成交价
            new_price = trade_res['items'][0]['price']
        except ApiException as e:
            if market_id == "" or price == "":
                assert e.status == 500
            return
        # 2.下委托单(类型:止损 如果当前价小于触发价)
        try:
            payload.trigger_price = new_price + 0.001
            payload.price = payload.trigger_price
            payload.trade_type = 'buy'
            payload.entrust_type = 'profitLoss'
            tri_price = new_price + 0.001
            commi_price = tri_price
            buy_res = api.entrusts_post(body=payload, async_req=True)
            commission_order_id = buy_res.get('orderid', '')
        except ApiException as e:
            if market_id == "" or price == "":
                assert e.status == 500
            return
        # 3.再下一买一卖,达到触发价
        try:
            payload.trade_type = 'buy'
            payload.trigger_price = ''
            payload.price = new_price + 0.004
            buy2_price = payload.price
            payload.entrust_type = 'limit'
            # 3.1先下一笔买单
            buy2_res = api.entrusts_post(body=payload, async_req=True)
            buy2_id = buy2_res.get('orderid', '')
            # 3.2再下一笔卖单
            payload.trade_type = 'sell'
            payload.price = buy2_price
            sell2_res = api.entrusts_post(body=payload, async_req=True)
            sell2_id = sell2_res.get('orderid', '')
            # 3.3检查委托交易列表
            check_res = api.entrusts_get(status=['done'], async_req=True)
            assert check_res['items']
            check_list = [res.id for res in entrust_res['items']]
            assert buy2_id in check_list
            assert sell2_id in check_list
            # 3.4获取成交记录列表
            ch_trade_res = api.trades_get(order_id=buy2_id, async_req=True)
            assert ch_trade_res['items'][0]
            latest_price = ch_trade_res['items'][0]['price']
        except ApiException as e:
            if market_id == "" or price == "":
                assert e.status == 500
            return
        # 4.当前成交价价变动时,当前价小于等于触发价,开始委托,检查委托列表是否有委托订单记录
        if latest_price >= tri_price:
            order_lists = api.entrusts_get(status=["entrusting"],
                                           tradeType='buy',
                                           async_req=True)
            assert order_lists['items']
            order_list = [order_res.id for order_res in order_lists['items']]
            assert commission_order_id in order_list
        # 5.下一个与第2步方向相反的单,促成第二步的单成交
        try:
            payload.trade_type = 'sell'
            # 委托价>=卖一时,撮合成功
            payload.price = commi_price
            result = api.entrusts_post(body=payload, async_req=True)
            sell_id = result.get('orderid', '')
        except ApiException as e:
            if price == '' or market_id == '':
                assert e.status == 500
            return
        result = api.trades_get(async_req=True)
        ids = [i.id for i in result['items']]
        assert sell_id in ids
        assert commission_order_id in ids

        user_info = account_api.accounts_account_info_get()
        assert user_info['account_info'].get('account_id')
        result = staff_api.entrusts_get(
            uid=user_info['account_info'].get('account_id'),
            status="done",
            async_req=True)
        ids = [i.id for i in result['items']]
        assert sell_id in ids

        # 测试交易所获取委托列表
        result = staff_api.entrusts_get(entrust_id=sell_id,
                                        status="done",
                                        async_req=True)
        assert result.items.id == sell_id

        fee_result = staff_api.fee_history_get(
            uid=user_info['account_info'].get('account_id'), status="done")
        fee_ids_map = {
            i.trade_history_id: i.fee_yield_amount
            for i in fee_result['items']
        }
        for k, v in fee_ids_map.items():
            r = staff_api.trade_history_get(trade_history_id=k, async_req=True)
            assert r.items.buyer_fee == v
            r2 = tenant_api.exchanges_trade_history_get(trade_id=k,
                                                        async_req=True)
            assert r2.items.buyerFee == v
            tenant_fee_r = tenant_api.exchanges_fee_history_get(trade_id=k,
                                                                async_req=True)
            assert tenant_fee_r.items.fee_yield_amount == v

        payload.price = 10**8
        payload.trade_type = 'sell'
        result = api.entrusts_post(body=payload, async_req=True)
        buy_id = result.order_id
        staff_api.entrusts_id_cancel_post(buy_id, async_req=True)
    def test_high_buy_same_volume_deal_success(self, market_id, price,
                                               entrust_type, trade_type,
                                               volume, trigger_price,
                                               auto_cancel_at, volume_flag,
                                               special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.volume = 1000_00
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空

        before_market_buy = api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        before_makret_sell = api.entrusts_post(body=payload)
        # 恢复限价

        payload.entrust_type = entrust_type
        payload.trade_type = trade_type

        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        price, volume = get_random_price_and_volume(special_info['precision'])
        payload.volume = volume
        payload.price = price
        price_range = (1 / (10**int(special_info["precision"])))

        try:
            assert 'same' in volume_flag
            first_result = api.entrusts_post(body=payload)
            if trade_type == 'buy':
                buy_id = first_result.order_id
                payload.trade_type = 'sell'
                payload.price -= price_range
                result = api.entrusts_post(body=payload)
                sell_id = result.order_id
            else:
                payload.trade_type = 'buy'
                sell_id = first_result.order_id
                payload.price += price_range
                result = api.entrusts_post(body=payload)
                buy_id = result.order_id

        except ApiException as e:
            assert e.status == 400
            raise e

        time.sleep(5)
        result = api.trades_get()
        ids = [i.order_id for i in result.items]
        assert sell_id in ids
        assert buy_id in ids
    def test_same_price_volume_success(self, market_id, price, entrust_type,
                                       trade_type, volume, trigger_price,
                                       auto_cancel_at, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 1000_00
        # payload.auto_cancel_at = auto_cancel_at
        # login
        special_info = special_login([
            api, main_ac_api, main_quota_api, tenant_quota_api,
            venture_quota_api
        ])
        payload.market_id = special_info['market_id']

        # 清空
        api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        api.entrusts_post(body=payload)

        # 恢复限价
        price, volume = get_random_price_and_volume(special_info['precision'])

        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.volume = volume

        try:
            first_result = api.entrusts_post(body=payload)
            logger.info(f"{trade_type} id: {first_result.order_id}")
        except Exception as e:
            if e.status == 400:
                logger.error('下单失败,没钱')
            raise e

        # 如果first_result的post参数trade_type是'buy'那么就要创建'sell'单
        if trade_type == 'buy':
            buy_id = first_result.order_id
            payload.trade_type = 'sell'
            result = api.entrusts_post(body=payload)
            sell_id = result.order_id
            logger.info(f"sell id :{sell_id}")
        # 如果first_result的post参数trade_type是'sell'那么就要创建'sell'单
        else:
            payload.trade_type = 'buy'
            sell_id = first_result.order_id
            result = api.entrusts_post(body=payload)
            buy_id = result.order_id
            logger.info(f"buy id :{buy_id}")

        time.sleep(5)
        result = api.entrusts_get(status=['done'])
        ids = [i.order_id for i in result.items]
        assert sell_id in ids
        assert buy_id in ids

        result_sell = api.trades_get(order_id=sell_id)
        logger.info(f"get result sell trades: {result}")
        result_buy = api.trades_get(order_id=buy_id)
        logger.info(f"get result buy trades:  {result}")
        assert hasattr(result_sell.items[0], 'price')
        assert hasattr(result_buy.items[0], 'price')
        assert float(result_buy.items[0].price) == price
        assert float(result_sell.items[0].price) == price

        my_exchange = api.entrusts_list_exchange_get()
        assert special_info['exchange_id'] in [i.id for i in my_exchange.items]
        logger.info('ending order')
    def test_multi_sell_volume_eq(self, market_id, price, entrust_type,
                                  trade_type, volume, trigger_price,
                                  auto_cancel_at, entrust_special_login):
        # login
        special_info = entrust_special_login([main_entrust_api, main_ac_api])
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.trigger_price = trigger_price
        payload.volume = 100000_00
        payload.auto_cancel_at = auto_cancel_at
        # login
        payload.market_id = market_id

        # 清空
        main_entrust_api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        main_entrust_api.entrusts_post(body=payload)

        # 恢复限价
        price, volume = get_random_price_and_volume(special_info['precision'])

        payload = PostEntrustsRequest()
        payload.market_id = market_id
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.trigger_price = trigger_price
        payload.volume = volume
        payload.auto_cancel_at = auto_cancel_at
        deviation = 0.005
        devia_pri = 0.01

        # 添加多笔买单和一笔卖单
        buy_trades = []
        for i in range(5):
            payload.trade_type = 'sell'
            price, volume = get_random_price_and_volume(
                special_info['precision'])
            payload.price = price
            payload.volume = volume
            r = main_entrust_api.entrusts_post(body=payload)
            buy_trades.append({
                'order_id': r.order_id,
                'price': payload.price,
                'volume': payload.volume
            })

        # 卖单升序排序
        sorted_buy_trades = sorted(buy_trades, key=lambda x: x['price'])
        payload.price = sorted_buy_trades[0]['price']
        # 下一笔买单将卖一撮合
        payload.trade_type = 'buy'
        payload.price = sorted_buy_trades[0]['price']
        payload.volume = sorted_buy_trades[0]['volume']
        r = main_entrust_api.entrusts_post(body=payload)
        sell_trade_id = r.order_id
        time.sleep(5)
        sell_res = main_entrust_api.entrusts_get(status='entrusting')
        sell_list = [i.order_id for i in sell_res.items]
        assert sell_trade_id in sell_list
        trade_res = main_entrust_api.trades_get(
            order_id=sorted_buy_trades[0]['order_id'])
        assert trade_res.items
        # 获取最新成交价
        new_price = [i.price for i in trade_res.items][0]
        # 下一笔止盈买单,当前成交价大于等于触发价,开始委托
        # 2.下委托单(类型:止盈 如果当前成交价大于触发价)
        payload.trigger_price = sorted_buy_trades[1]['price']
        payload.price = sorted_buy_trades[2]['price'] + devia_pri
        payload.trade_type = 'buy'
        payload.entrust_type = 'profit_loss'
        tri_price = sorted_buy_trades[1]['price']
        payload.volume = sorted_buy_trades[2]['volume'] + deviation
        commi_price = sorted_buy_trades[2]['price'] + devia_pri
        buy_res = main_entrust_api.entrusts_post(body=payload)
        commission_order_id = buy_res.order_id
        # 3.再下一买一卖,达到触发价
        payload.trade_type = 'buy'
        payload.trigger_price = None
        payload.price = sorted_buy_trades[1]['price']
        payload.volume = sorted_buy_trades[1]['volume']
        payload.entrust_type = 'limit'
        # 3.1先下一笔买单
        buy2_res = main_entrust_api.entrusts_post(body=payload)
        buy2_id = buy2_res.order_id
        # 3.3检查委托交易列表
        time.sleep(5)
        check_res = main_entrust_api.entrusts_get(status=['done'])
        print('已完成交易委托列表:', check_res)
        assert check_res.items
        check_list = [res.order_id for res in check_res.items]
        assert buy2_id in check_list
        # 3.4获取成交记录列表
        ch_trade_res = main_entrust_api.trades_get(order_id=buy2_id)
        assert ch_trade_res.items
        latest_price = ch_trade_res.items[0].price
        # 4.当前成交价价变动时,当前价大于等于触发价,开始委托,委托价大于卖一时候,,检查委托列表是否有委托订单记录
        if round(
                float(latest_price), 8
        ) <= tri_price and commi_price > sorted_buy_trades[2]['price']:
            order_lists = main_entrust_api.entrusts_get(status=["entrusting"],
                                                        trade_type='buy')
            assert order_lists.items
            order_list = [
                order_res.order_id for order_res in order_lists.items
            ]
            assert commission_order_id in order_list
        result = main_entrust_api.trades_get(
            order_id=sorted_buy_trades[2]['order_id'])
        result_list = [i.order_id for i in result.items]
        assert commission_order_id not in result_list
        # 5.撤销未成交的止损委托单
        main_entrust_api.entrusts_id_cancel_post(commission_order_id)
        time.sleep(5)
        cancel_res = main_entrust_api.entrusts_get(status=['cancelled'])
        assert cancel_res.items
        cancel_list = [i.order_id for i in cancel_res.items]
        assert commission_order_id in cancel_list
    def test_stoploss_sell(self, market_id, price, entrust_type, trade_type,
                           volume, trigger_price, auto_cancel_at,
                           entrust_special_login):
        # login
        special_info = entrust_special_login([main_entrust_api, main_ac_api])
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 100000_00
        # payload.auto_cancel_at = auto_cancel_at
        # login
        payload.market_id = market_id

        # 清空
        main_entrust_api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        main_entrust_api.entrusts_post(body=payload)

        # 恢复限价
        price, volume = get_random_price_and_volume(special_info['precision'])

        # 构造entrust_post请求对象
        payload = PostEntrustsRequest()
        payload.market_id = market_id
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.trigger_price = trigger_price
        payload.volume = volume
        payload.auto_cancel_at = auto_cancel_at
        # 1.先下一买一卖,构造最新成交价
        first_result = main_entrust_api.entrusts_post(body=payload)
        buy1_id = first_result.order_id
        payload.trade_type = 'buy'
        result = main_entrust_api.entrusts_post(body=payload)
        sell1_id = result.order_id
        # 1.1 检查成交记录列表,委托交易列表
        # entrust_res = main_entrust_api.entrusts_get(status=['done'])
        time.sleep(5)
        entrust_res = main_entrust_api.entrusts_get()
        print('交易委托列表:', entrust_res)
        assert entrust_res.items
        entrust_list = [res.order_id for res in entrust_res.items]
        assert buy1_id in entrust_list
        assert sell1_id in entrust_list
        # 1.2 检查委托交易列表
        trade_res = main_entrust_api.trades_get(order_id=buy1_id)
        assert trade_res.items
        # 获取最新成交价
        new_price = trade_res.items[0].price
        # 2.下委托单(类型:止损 如果当前成交价大于触发价)
        payload.trigger_price = str(float(new_price) - 0.01)
        payload.price = str(float(new_price) - 0.01)
        payload.trade_type = 'sell'
        payload.entrust_type = 'profit_loss'
        tri_price = float(new_price) - 0.01
        commi_price = tri_price
        buy_res = main_entrust_api.entrusts_post(body=payload)
        commission_order_id = buy_res.order_id
        # 3.再下一买一卖,达到触发价
        payload.trade_type = 'buy'
        payload.trigger_price = None
        payload.price = str(float(new_price) - 0.04)
        buy2_price = payload.price
        payload.entrust_type = 'limit'
        # 3.1先下一笔买单
        buy2_res = main_entrust_api.entrusts_post(body=payload)
        buy2_id = buy2_res.order_id
        # 3.2再下一笔卖单
        payload.trade_type = 'sell'
        payload.price = buy2_price
        sell2_res = main_entrust_api.entrusts_post(body=payload)
        sell2_id = sell2_res.order_id
        # 3.3检查委托交易列表
        time.sleep(5)
        check_res = main_entrust_api.entrusts_get(status=['done'])
        print('已完成交易委托列表:', check_res)
        assert check_res.items
        check_list = [res.order_id for res in check_res.items]
        print('chck_list:', check_list)
        assert buy2_id in check_list
        assert sell2_id in check_list
        # 3.4获取成交记录列表
        ch_trade_res = main_entrust_api.trades_get(order_id=buy2_id)
        assert ch_trade_res.items[0]
        latest_price = ch_trade_res.items[0].price
        # 4.当前成交价价变动时,当前价小于等于触发价,开始委托,检查委托列表是否有委托订单记录
        if round(float(latest_price), 8) <= tri_price:
            order_lists = main_entrust_api.entrusts_get(status=["entrusting"],
                                                        trade_type='sell')
            assert order_lists.items
            order_list = [
                order_res.order_id for order_res in order_lists.items
            ]
            assert commission_order_id in order_list
        # 5.下一个与第2步方向相反的单,促成第二步的单成交
        payload.trade_type = 'buy'
        # 委托价<=买一时,撮合成功
        payload.price = commi_price + 0.01
        result = main_entrust_api.entrusts_post(body=payload)
        sell_id = result.order_id
        time.sleep(5)
        result = main_entrust_api.trades_get()
        ids = [i.order_id for i in result.items]
        assert sell_id in ids
        assert commission_order_id in ids
Exemple #19
0
    def test_multi_sell_volume_gt_buy(self, market_id, price, entrust_type,
                                      trade_type, volume, trigger_price,
                                      auto_cancel_at, volume_flag,
                                      special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.volume = 1000
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空
        api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        api.entrusts_post(body=payload)

        # 恢复限价
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.volume = volume
        # 添加多笔买单和一笔卖单
        # 精度
        buy_trades = []
        inc_range = 1
        payload.trade_type = 'buy'
        for i in range(5):
            payload.price, payload.volume = get_random_price_and_volume(
                special_info['precision'])
            r = api.entrusts_post(body=payload)
            buy_trades.append({
                'order_id': r.order_id,
                'price': payload.price,
                'volume': payload.volume
            })

        payload.trade_type = 'sell'
        if volume_flag == 'eq_buy_price':
            # 限价卖单价格低于买单最高价格,且高于买单最低价格,且等于某一中间买单价格
            sorted_buy_trades = sorted(buy_trades, key=lambda x: x['price'])
            payload.price = sorted_buy_trades[2]['price']
            # 卖单出售数量大于,高于卖单价格的所有买单总数量,等于的也要算上,不然没法剩
            payload.volume = round(
                sum([i['volume'] for i in sorted_buy_trades[2:]]) + inc_range,
                8 - int(special_info['precision']))
        else:
            # 限价卖单价格低于买单最高价格,且高于买单最低价格,且等且不等于任何买单价格
            sorted_buy_trades = sorted(buy_trades, key=lambda x: x['price'])
            payload.price = round(
                (sorted_buy_trades[2]['price'] + sorted_buy_trades[3]['price'])
                / 2, int(special_info['precision']))
            # 卖单出售数量大于,高于卖单价格的所有买单总数量
            payload.volume = round(
                sum([i['volume'] for i in sorted_buy_trades[3:]]) + inc_range,
                8 - int(special_info['precision']))
        r = api.entrusts_post(body=payload)
        sell_trade_id = r.order_id

        time.sleep(5)

        done_res = api.entrusts_get(status=['done'])
        done_ids = [i.order_id for i in done_res.items]
        # 卖单量大于买单价格区间的数目,不完全成交
        assert sell_trade_id not in done_ids
        # 买单剩
        sell_result = api.trades_get(order_id=sell_trade_id)
        trade_ids = [i.order_id for i in sell_result.items]
        assert sell_trade_id in trade_ids
        assert hasattr(sell_result.items[0], 'volume')
        assert hasattr(sell_result.items[0], 'fee')

        # 买单剩余,测试剩余单撤销
        if volume_flag == 'eq_buy_price':
            ids = [i['order_id'] for i in sorted_buy_trades[:2]]
        else:
            ids = [i['order_id'] for i in sorted_buy_trades[:3]]

        for i in ids:
            api.entrusts_id_cancel_post(i)
Exemple #20
0
    def test_stopprofit_buy_fail(self, market_id, price, entrust_type, trade_type,
                                 volume, trigger_price, auto_cancel_at, entrust_special_login):
        # login
        special_info = entrust_special_login([main_entrust_api, main_ac_api])
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.trigger_price = trigger_price
        payload.volume = 100000_00
        payload.auto_cancel_at = auto_cancel_at
        # login
        payload.market_id = market_id

        # 清空
        main_entrust_api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        main_entrust_api.entrusts_post(body=payload)

        # 恢复限价
        price, volume = get_random_price_and_volume(special_info['precision'])

        # 构造entrust_post请求对象
        payload = PostEntrustsRequest()
        payload.market_id = market_id
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.trigger_price = trigger_price
        payload.volume = volume
        payload.auto_cancel_at = auto_cancel_at
        # login
        entrust_special_login([main_entrust_api])
        # 1.先下一买一卖,构造最新成交价
        try:
            first_result = main_entrust_api.entrusts_post(body=payload)
            buy1_id = first_result.order_id
            payload.trade_type = 'buy'
            result = main_entrust_api.entrusts_post(body=payload)
            sell1_id = result.order_id
            # 1.1 检查成交记录列表,委托交易列表
            time.sleep(5)
            # entrust_res = main_entrust_api.entrusts_get(status=['done'])
            entrust_res = main_entrust_api.entrusts_get()
            print('交易委托列列表:', entrust_res)
            assert entrust_res.items
            entrust_list = [res.order_id for res in entrust_res.items]
            assert buy1_id in entrust_list
            assert sell1_id in entrust_list
            # 1.2 检查委托交易列表
            trade_res = main_entrust_api.trades_get(order_id=buy1_id)
            assert trade_res.items
            # 获取最新成交价
            new_price = trade_res.items[0].price
        except ApiException as e:
            if market_id == "" or price == "":
                assert e.status == 400
            return
        # 2.下委托单(类型:止盈 如果当前成交价大于触发价)
        try:
            payload.trigger_price = str(float(new_price) + 0.01)
            payload.price = str(float(new_price) + 0.01)
            payload.trade_type = 'buy'
            payload.entrust_type = 'profit_loss'
            tri_price = float(new_price) + 0.01
            commi_price = tri_price
            buy_res = main_entrust_api.entrusts_post(body=payload)
            commission_order_id = buy_res.order_id
        except ApiException as e:
            if market_id == "" or price == "":
                assert e.status == 400
            return
        # 3.再下一买一卖,达到触发价
        try:
            payload.trade_type = 'buy'
            payload.trigger_price = None
            payload.price = str(float(new_price) + 0.04)
            buy2_price = str(float(new_price) + 0.04)
            payload.entrust_type = 'limit'
            # 3.1先下一笔买单
            buy2_res = main_entrust_api.entrusts_post(body=payload)
            buy2_id = buy2_res.order_id
            # 3.2再下一笔卖单
            payload.trade_type = 'sell'
            payload.price = buy2_price
            sell2_res = main_entrust_api.entrusts_post(body=payload)
            sell2_id = sell2_res.order_id
            # 3.3检查委托交易列表
            time.sleep(5)
            check_res = main_entrust_api.entrusts_get(status=['done'])
            print('已完成交易委托列表:', check_res)
            assert check_res.items
            check_list = [res.order_id for res in check_res.items]
            assert buy2_id in check_list
            assert sell2_id in check_list
            # 3.4获取成交记录列表
            ch_trade_res = main_entrust_api.trades_get(order_id=buy2_id)
            assert ch_trade_res.items
            latest_price = ch_trade_res.items[0].price
        except ApiException as e:
            if market_id == "" or price == "":
                assert e.status == 400
            return
        # 4.当前成交价价变动时,当前价大于等于触发价,开始委托,检查委托列表是否有委托订单记录
        if round(float(latest_price), 8) >= tri_price:
            order_lists = main_entrust_api.entrusts_get(status=["entrusting"], trade_type='buy')
            assert order_lists.items
            order_list = [order_res.order_id for order_res in order_lists.items]
            assert commission_order_id in order_list
        # 5.下一个与第2步方向相反的单,促成第二步的单成交
        try:
            payload.trade_type = 'sell'
            # 委托价<卖一时,撮合不成功,2步下的止损buy单在委托列表
            payload.price = commi_price + 0.01
            result = main_entrust_api.entrusts_post(body=payload)
            sell_id = result.order_id
        except ApiException as e:
            if price == '' or market_id == '':
                assert e.status == 400
            return
        time.sleep(5)
        result = main_entrust_api.trades_get()
        ids = [i.order_id for i in result.items]
        assert sell_id not in ids
        assert commission_order_id not in ids
        result = main_entrust_api.entrusts_get(status=["entrusting"])
        result_list = [i.order_id for i in result.items]
        assert commission_order_id in result_list
    def test_multi_sell_volume_eq_buy(
            self, market_id, price, entrust_type, trade_type, volume,
            trigger_price, auto_cancel_at, volume_flag, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000000
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.volume = 1000000
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空
        api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        api.entrusts_post(body=payload)

        # 恢复限价
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.volume = volume
        # 添加多笔卖单和一笔买单
        sell_trades = []
        payload.trade_type = 'sell'
        for i in range(5):
            payload.price, payload.volume = get_random_price_and_volume(special_info["precision"])
            r = api.entrusts_post(body=payload)
            sell_trades.append({
                'order_id': r.order_id,
                'price': payload.price,
                'volume': payload.volume
            })

        payload.trade_type = 'buy'
        if volume_flag == 'eq_buy_price':
            # 限价买单价格高于卖单最低价格,且低于卖单最高价格,且等于某一中间卖单价格
            sorted_sell_trades = sorted(sell_trades, key=lambda x: x['price'])
            payload.price = sorted_sell_trades[2]['price']
        else:
            # 限价买单价格高于卖单最低价格,且低于卖单最高价格,且不等于某一中间卖单价格
            sorted_sell_trades = sorted(sell_trades, key=lambda x: x['price'])
            payload.price = round((sorted_sell_trades[2]['price'] +
                                   sorted_sell_trades[3]['price']) / 2,
                                  int(special_info['precision']))

        # 买单购买数量等于,低于买单价格的所有卖单总数量
        payload.volume = round(
            sum([i['volume'] for i in sorted_sell_trades[:3]]), 8 - int(special_info['precision']))

        r = api.entrusts_post(body=payload)
        buy_trade_id = r.order_id
        time.sleep(10)

        # 买单应都成交了
        r = api.trades_get(order_id=buy_trade_id)
        assert r.items
        assert hasattr(r.items[0], 'volume')
        assert hasattr(r.items[0], 'fee')
        assert round(sum([float(i.volume) for i in r.items]), 8-int(special_info['precision'])) == float(
            payload.volume)
        # 卖单剩余,测试剩余单撤销
        ids = [i['order_id'] for i in sorted_sell_trades[3:]]
        for i in ids:
            api.entrusts_id_cancel_post(i)
    def test_same_price_volume_success(self, market_id, price, entrust_type, trade_type,
                                       volume, trigger_price, auto_cancel_at, exchange_ids, coin_id, sell_coin_id,
                                       trading_area_id, symbol, less_entrust_special_login):

        # login
        less_entrust_special_login([api, main_ac_api, main_quota_api, tenant_quota_api, venture_quota_api])
        for i in range(5):
            # price_range = (0.1, 18)
            # volume_range = (1, 10)
            # price = round(random.uniform(*price_range), 2)
            # volume = round(random.uniform(*volume_range), 2)
            coin_id = coin_id
            payload = PostEntrustsRequest()
            payload.market_id = market_id
            payload.price = price
            payload.entrust_type = entrust_type
            payload.trade_type = trade_type
            payload.trigger_price = trigger_price
            payload.volume = volume
            payload.auto_cancel_at = auto_cancel_at
            try:
                first_result = api.entrusts_post(body=payload)
                logger.info(f"{trade_type} id: {first_result.order_id}")
            except Exception as e:
                if e.status == 400:
                    logger.error('下单失败,没钱')
                raise e
            print('第一次下单result:', first_result)
            # 如果first_result的post参数trade_type是'buy'那么就要创建'sell'单
            if trade_type == 'buy':
                buy_id = first_result.order_id
                payload.trade_type = 'sell'
                result = api.entrusts_post(body=payload)
                sell_id = result.order_id
                logger.info(f"sell id :{sell_id}")
            # 如果first_result的post参数trade_type是'sell'那么就要创建'sell'单
            else:
                payload.trade_type = 'buy'
                sell_id = first_result.order_id
                print('*' * 20)
                result = api.entrusts_post(body=payload)
                print('第二次下买单:', result)
                buy_id = result.order_id
                logger.info(f"buy id :{buy_id}")
            result = api.entrusts_get(status=['done'])
            ids = [i.order_id for i in result.items]
            result_sell = api.trades_get(order_id=sell_id)
            logger.info(f"get result sell trades: {result}")
            result_buy = api.trades_get(order_id=buy_id)
            logger.info(f"get result buy trades:  {result}")
            time.sleep(5)
    def test_multi_sell_volume_eq(
            self, market_id, price, entrust_type, trade_type, volume,
            trigger_price, auto_cancel_at, volume_flag, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000000
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.volume = 1000000
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空
        api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        api.entrusts_post(body=payload)

        # 恢复限价
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.volume = volume
        # 添加多笔买单和一笔卖单
        sell_trades = []
        sub_range = 1 / (10**int(special_info['precision']))
        payload.trade_type = 'sell'

        for i in range(5):
            payload.price, payload.volume = get_random_price_and_volume(special_info['precision'])
            r = api.entrusts_post(body=payload)
            sell_trades.append({
                'order_id': r.order_id,
                'price': payload.price,
                'volume': payload.volume
            })

        payload.trade_type = 'buy'
        if volume_flag == 'buy_price_eq_max_sell':
            # 买单与卖单最高价格一致
            sorted_sell_trades = sorted(sell_trades, key=lambda x: x['price'])
            payload.price = sorted_sell_trades[-1]['price']
        else:
            # 限价买单价格低于于卖单最低价格
            sorted_sell_trades = sorted(sell_trades, key=lambda x: x['price'])
            payload.price = round(sorted_sell_trades[0]['price'] - sub_range,
                                  int(special_info['precision']))
        # 卖单出售数量等于所有买单总数量
        payload.volume = round(
            sum([i['volume'] for i in sorted_sell_trades]), 8 - int(special_info['precision']))

        r = api.entrusts_post(body=payload)
        buy_entrust_id = r.order_id

        # print(f"{volume_flag}: {sorted_sell_trades}")
        time.sleep(5)

        total = []
        all_buy_id = [i['order_id'] for i in sell_trades]
        if volume_flag == 'buy_price_eq_max_sell':
            entrust_res = api.entrusts_get(trade_type="done")
            done_entrust_ids = [i.order_id for i in entrust_res.items]
            total = [float(i.volume) for i in entrust_res.items if i.order_id in all_buy_id]
            assert buy_entrust_id in done_entrust_ids

        result = api.trades_get()
        logger.info(sum([float(i.volume) for i in result.items]))
        done_trade_ids = [i.order_id for i in result.items]

        if volume_flag == 'buy_price_eq_max_sell':
            #  买卖单应都成交了
            assert buy_entrust_id in done_trade_ids
            assert payload.volume == round(sum(total), 8 - int(special_info['precision']))
            assert len(
                set(done_trade_ids) -
                set([i['order_id'] for i in sorted_sell_trades])) >= 0
        else:
            # 买卖单都剩余,测试剩余单撤销
            # print(f"payload: {payload}")
            # print(f"done_trade_ids: {done_trade_ids}")
            # print(f"buy_entrust_id: {buy_entrust_id}")
            # print(f"{sorted_sell_trades}")
            ids = [i['order_id'] for i in sorted_sell_trades]
            for i in ids + [buy_entrust_id]:
                print(f"canceling {i}")
                api.entrusts_id_cancel_post(i)
Exemple #24
0
    def test_takeprofit_sell(self, market_id, price, entrust_type, trade_type,
                             volume, trigger_price, auto_cancel_at,
                             entrust_special_login):
        # login
        special_info = entrust_special_login([main_entrust_api, main_ac_api])
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        payload.trigger_price = trigger_price
        payload.volume = 100000_00
        payload.auto_cancel_at = auto_cancel_at
        # login
        payload.market_id = market_id

        # 清空
        main_entrust_api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        main_entrust_api.entrusts_post(body=payload)

        # 恢复限价
        price, volume = get_random_price_and_volume(special_info['precision'])

        # 构造entrust_post请求对象
        payload = PostEntrustsRequest()
        payload.market_id = market_id
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.trigger_price = trigger_price
        payload.volume = volume
        payload.auto_cancel_at = auto_cancel_at

        # 1.先下一买一卖,构造最新成交价
        first_result = main_entrust_api.entrusts_post(body=payload)
        buy1_id = first_result.order_id
        payload.trade_type = 'buy'
        result = main_entrust_api.entrusts_post(body=payload)
        sell1_id = result.order_id
        # 1.1 检查成交记录列表,委托交易列表
        time.sleep(5)
        # entrust_res = main_entrust_api.entrusts_get(status=['done'])
        entrust_res = main_entrust_api.entrusts_get()
        print('交易委托列表拍:', entrust_res)
        assert entrust_res.items
        entrust_list = [res.order_id for res in entrust_res.items]
        assert buy1_id in entrust_list
        assert sell1_id in entrust_list
        # 1.2 检查委托交易列表
        trade_res = main_entrust_api.trades_get(order_id=buy1_id)
        assert trade_res.items
        # 获取最新成交价
        new_price = trade_res.items[0].price
        # 2.下委托单(类型:止损 如果当前价小于触发价)
        payload.trigger_price = float(new_price) + 0.01
        payload.price = float(new_price) + 0.01
        payload.trade_type = 'buy'
        payload.entrust_type = 'profit_loss'
        tri_price = float(new_price) + 0.01
        buy_res = main_entrust_api.entrusts_post(body=payload)
        commission_order_id = buy_res.order_id
        # 3.再下一买一卖,达到触发价
        payload.trade_type = 'buy'
        payload.trigger_price = None
        payload.price = str(float(new_price) + 0.04)
        buy2_price = str(float(new_price) + 0.04)
        payload.entrust_type = 'limit'
        # 3.1先下一笔买单
        buy2_res = main_entrust_api.entrusts_post(body=payload)
        buy2_id = buy2_res.order_id
        # 3.2再下一笔卖单
        payload.trade_type = 'sell'
        payload.price = buy2_price
        sell2_res = main_entrust_api.entrusts_post(body=payload)
        sell2_id = sell2_res.order_id
        # 3.3检查委托交易列表
        time.sleep(5)
        check_res = main_entrust_api.entrusts_get(status=['done'])
        print('已完成委托交易列表:', check_res)
        assert check_res.items
        check_list = [res.order_id for res in check_res.items]
        assert buy2_id in check_list
        assert sell2_id in check_list
        # 3.4获取成交记录列表
        ch_trade_res = main_entrust_api.trades_get(order_id=buy2_id)
        assert ch_trade_res.items[0]
        latest_price = ch_trade_res.items[0].price
        # 4.当前成交价价变动时,当前价小于等于触发价,开始委托,检查委托列表是否有委托订单记录
        if round(float(latest_price), 8) >= tri_price:
            order_lists = main_entrust_api.entrusts_get(status=["entrusting"],
                                                        trade_type='buy')
            assert order_lists.items
            order_list = [
                order_res.order_id for order_res in order_lists.items
            ]
            assert commission_order_id in order_list
        # 5.在委托记录中选择需要撤单的订单,点击撤销按钮撤单成功,生成一笔历史委托订单,订单状态为撤销
        main_entrust_api.entrusts_id_cancel_post(order_list[0])
        time.sleep(5)
        cancel_res = main_entrust_api.entrusts_get(status=['cancelled'])
        cancel_list = [i.order_id for i in cancel_res.items]
        assert commission_order_id in cancel_list
    def test_high_sell_multi_buy_first(self, entrust_type, trade_type,
                                       volume_flag, special_login):
        payload = PostEntrustsRequest()
        payload.price = 1000_00
        payload.entrust_type = 'market'
        payload.trade_type = 'sell'
        # payload.trigger_price = trigger_price
        payload.volume = 1000_00
        # payload.auto_cancel_at = auto_cancel_at
        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        # 清空

        before_market_buy = api.entrusts_post(body=payload)
        payload.trade_type = 'buy'
        before_makret_sell = api.entrusts_post(body=payload)
        # 恢复限价

        payload.entrust_type = entrust_type
        payload.trade_type = trade_type

        # login
        special_info = special_login([api])
        payload.market_id = special_info['market_id']
        precision = special_info['precision']
        inc_range = round(1 / (10**(int(precision) - 1)), int(precision))

        buy_ids = []
        buy_volume = []
        try:
            assert volume_flag == 'multi_buy'
            # 多个买单与单个卖单
            buy_price, _ = get_random_price_and_volume(precision)
            payload.price = buy_price
            for i in range(5):
                _, volume = get_random_price_and_volume(precision)
                buy_volume.append(volume)
                payload.volume = volume
                result = api.entrusts_post(body=payload)
                buy_ids.append(result.order_id)

            # 单卖
            payload.trade_type = 'sell'
            payload.volume = round(sum(buy_volume), int(precision))
            payload.price = round(payload.price + inc_range,
                                  int(precision))  # 卖高
            result = api.entrusts_post(body=payload)
            sell_id = result.order_id

        except ApiException as e:
            return

        # 获取已成交委托单
        result = api.entrusts_get(status=['done'])
        ids = [i.id for i in result.items]

        # 交易不成功
        assert sell_id not in ids

        # 撤回
        for i in buy_ids + [sell_id]:
            api.entrusts_id_cancel_post(i)
Exemple #26
0
    def test_entrust(self, market_id, price, entrust_type, trade_type, volume,
                     trigger_price, auto_cancel_at, special_login, with_login):
        payload = PostEntrustsRequest()
        payload.market_id = market_id
        payload.price = price
        payload.entrust_type = entrust_type
        payload.trade_type = trade_type
        payload.trigger_price = trigger_price
        payload.volume = volume
        payload.auto_cancel_at = auto_cancel_at
        # login
        special_login([api, tenant_api])
        # login
        with_login('staff', [staff_api], 'account',
                   'password')  # TODO add account

        try:
            first_result = api.entrusts_post(body=payload, async_req=True)
            # 如果first_result的post参数trade_type是'buy'那么就要创建'sell'单
            if trade_type == 'buy':
                buy_id = first_result['id']
                payload.trade_type = 'sell'
                result = api.entrusts_post(body=payload, async_req=True)
                sell_id = result['id']
            # 如果first_result的post参数trade_type是'sell'那么就要创建'sell'单
            else:
                payload.trade_type = 'buy'
                sell_id = first_result['id']
                result = api.entrusts_post(body=payload, async_req=True)
                buy_id = result.order_id

        except ApiException as e:
            if price == '' or market_id == '':
                assert e.status == 400
            return

        user_info = account_api.accounts_account_info_get()
        assert user_info['account_info'].get('account_id')
        result = staff_api.entrusts_get(
            uid=user_info['account_info'].get('account_id'),
            status="done",
            async_req=True)
        ids = [i.id for i in result['items']]
        assert sell_id in ids
        assert buy_id in ids

        # 测试交易所获取委托列表
        result = staff_api.entrusts_get(entrust_id=buy_id,
                                        status="done",
                                        async_req=True)
        assert result.items.id == buy_id

        fee_result = staff_api.fee_history_get(
            uid=user_info['account_info'].get('account_id'), status="done")
        fee_ids_map = {
            i.trade_history_id: i.fee_yield_amount
            for i in fee_result['items']
        }
        for k, v in fee_ids_map.items():
            r = staff_api.trade_history_get(trade_history_id=k, async_req=True)
            assert r.items.buyer_fee == v
            r2 = tenant_api.exchanges_trade_history_get(trade_id=k,
                                                        async_req=True)
            assert r2.items.buyerFee == v
            tenant_fee_r = tenant_api.exchanges_fee_history_get(trade_id=k,
                                                                async_req=True)
            assert tenant_fee_r.items.fee_yield_amount == v

        payload.price = 10**8
        payload.trade_type = 'sell'
        result = api.entrusts_post(body=payload, async_req=True)
        buy_id = result.order_id
        staff_api.entrusts_id_cancel_post(buy_id, async_req=True)