def initialize(self):
     """
     初始化或者出异常之后重新初始化
     :return:
     """
     self.first_market_trade_api = OKExTradeApi(
         api_key=self.combination.first_market_api_key,
         api_secret=self.combination.first_market_api_secret)
     self.second_market_trade_api = BinanceTradeApi(
         api_key=self.combination.second_market_api_key,
         api_secret=self.combination.second_market_api_secret)
     self.first_market_account = dict()
     self.second_market_account = dict()
     self.trader = self.get_trader()(self.combination.combination,
                                     self.first_market_trade_api,
                                     self.second_market_trade_api)
# -*- coding=utf-8 -*-
from coin.lib.api.binance import BinanceTradeApi


trade_api = BinanceTradeApi()


def test_ping():
    print trade_api.ping()


def test_server_time():
    return trade_api.get_server_time()


def test_get_order_book():
    print trade_api.get_order_book(symbol='ETHBTC', limit=20)


if __name__ == '__main__':
    # test_ping()
    # test_server_time()
    test_get_order_book()
    # 测试时间
    # import time
    # start = time.time()
    # res = test_server_time()['serverTime']
    # end = time.time()
    # print int(start*1000), res, int(end*1000)
    # print res-int(start*1000), int(end*1000)-res
    # start = time.time()
Example #3
0
class HuobiBinanceCombinationTask(CombinationTaskBase):
    def __init__(self, rds, id=None, combination=None):
        """
        用id或者组合来初始化,优先id
        :param id:
        :param combination:
        """
        super(HuobiBinanceCombinationTask,
              self).__init__(rds=rds, id=id, combination=combination)
        self.huobi_trade_api = self.first_market_trade_api
        self.binance_trade_api = self.second_market_trade_api

    def get_trader(self):
        """
        获取trader
        :return:
        """
        trade_pair = '{}_{}'.format(self.combination.small_coin,
                                    self.combination.big_coin)
        trader_class = None
        trader_class_list = HuobiBinanceTrader.__subclasses__()
        for item in trader_class_list:
            if item.__trade_pair__ == trade_pair:
                trader_class = item
        if trader_class is None:
            raise InitialError(
                u'can not find trader class for trade_pair {}'.format(
                    trade_pair))
        return trader_class

    def initialize(self):
        """
        初始化或者出异常之后重新初始化
        :return:
        """
        self.first_market_trade_api = HuoBiTradeApi(
            api_key=self.combination.first_market_api_key,
            api_secret=self.combination.first_market_api_secret,
            account_id=self.combination.huobi_account,
            huobipoint_account_id=self.combination.huobipoint_account)
        self.second_market_trade_api = BinanceTradeApi(
            api_key=self.combination.second_market_api_key,
            api_secret=self.combination.second_market_api_secret)
        self.first_market_account = dict()
        self.second_market_account = dict()
        self.trader = self.get_trader()(self.combination.combination,
                                        self.first_market_trade_api,
                                        self.second_market_trade_api)

    def get_first_market_account(self):
        """
        火币account,注意get account不要和trade并发
        :return: account数据
        """
        res = self.first_market_trade_api.get_balance()['list']
        tmp_account_data = defaultdict(Decimal)
        for item in res:
            balance = Decimal(item['balance'])
            if balance > 0:
                if item['type'] == 'trade':  # 非冻结
                    tmp_account_data[item['currency']] = balance
                if item['type'] == 'frozen':  # 冻结
                    tmp_account_data['{}_frozen'.format(
                        item['currency'])] = balance
        self.first_market_account = tmp_account_data
        del tmp_account_data
        if not self.first_market_account.get(self.combination.small_coin):
            self.first_market_account[self.combination.small_coin] = Decimal(
                '0')
        if not self.first_market_account.get(self.combination.big_coin):
            self.first_market_account[self.combination.big_coin] = Decimal('0')
        print("{}|GetHuobiAccount|{}".format(
            datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f'),
            self.first_market_account))

    def get_second_market_account(self):
        """
        币安account
        :return:
        """
        res = self.second_market_trade_api.get_account()
        tmp_account_data = dict()
        if not res['canTrade']:  # 无法交易
            return
        for item in res['balances']:
            balance = Decimal(item['free'])
            frozen = Decimal(item['locked'])
            if balance > 0:  # 有币
                # 统一使用小写
                tmp_account_data[item['asset'].lower()] = balance
            if frozen > 0:
                tmp_account_data['{}_frozen'.format(
                    item['asset'].lower())] = frozen
        self.second_market_account = tmp_account_data
        del tmp_account_data
        if not self.second_market_account.get(self.combination.small_coin):
            self.second_market_account[self.combination.small_coin] = Decimal(
                '0')
        if not self.second_market_account.get(self.combination.big_coin):
            self.second_market_account[self.combination.big_coin] = Decimal(
                '0')
        print("{}|GetBinanceAccount|{}".format(
            datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f'),
            self.second_market_account))

    def coin_supplement(self):
        """
        补充bnb
        :return:
        """
        if self.second_market_account.get(
                'bnb', Decimal('0')) < BNB_SUPPLEMENT_THRESHOLD:
            self.trader.bnb_supplement(BNB_SUPPLEMENT)
Example #4
0
def fetch_combination_account(combination, status):
    """
    获取组合的账号信息
    :param combination:
    :type combination: Combination
    :param status:
    :return:
    """
    task_obj = get_task_object(None, combination.combination)
    task_obj.get_account()
    first_market_big_coin = task_obj.first_market_account[combination.big_coin]
    first_market_small_coin = task_obj.first_market_account[
        combination.small_coin]
    second_market_big_coin = task_obj.second_market_account[
        combination.big_coin]
    second_market_small_coin = task_obj.second_market_account[
        combination.small_coin]
    time.sleep(1)
    btc_price = Decimal('0')
    bnb_price = Decimal('0')
    symbol_price = Decimal('0')
    big_coin_btc_price = Decimal('0')
    # 使用币安的价格
    price_list = BinanceTradeApi('', '').get_orderbook_tickers()
    binance_symbol = '{}{}'.format(combination.small_coin,
                                   combination.big_coin).upper()
    big_coin_btc_symbol = '{}{}'.format(combination.big_coin, 'btc').upper()
    for item in price_list:
        if item['symbol'] == 'BTCUSDT':
            btc_price = (Decimal(item['bidPrice']) +
                         Decimal(item['askPrice'])) / 2
        elif item['symbol'] == 'BNBBTC':
            bnb_price = (Decimal(item['bidPrice']) +
                         Decimal(item['askPrice'])) / 2
        elif item['symbol'] == binance_symbol:
            symbol_price = (Decimal(item['bidPrice']) +
                            Decimal(item['askPrice'])) / 2
        elif combination.big_coin.lower(
        ) != 'btc' and item['symbol'] == big_coin_btc_symbol:
            big_coin_btc_price = (Decimal(item['bidPrice']) +
                                  Decimal(item['askPrice'])) / 2
        elif combination.big_coin.lower() == 'btc':
            big_coin_btc_price = Decimal('1')
    # Account中间都是小写
    if combination.first_market == Market.BINANCE:
        bnb = task_obj.first_market_account.get('bnb', Decimal(0))
    elif combination.second_market == Market.BINANCE:
        bnb = task_obj.second_market_account.get('bnb', Decimal(0))
    else:
        bnb = Decimal('0')
    if combination.first_market == Market.HUOBI:
        huobi_point = task_obj.first_market_trade_api.get_huobi_point()
    elif combination.second_market == Market.HUOBI:
        huobi_point = task_obj.second_market_trade_api.get_huobi_point()
    else:
        huobi_point = Decimal('0')

    AccountCoinInfoModel(
        combination=combination.combination,
        first_market_big_coin=first_market_big_coin,
        first_market_small_coin=first_market_small_coin,
        second_market_big_coin=second_market_big_coin,
        second_market_small_coin=second_market_small_coin,
        big_coin_total=first_market_big_coin + second_market_big_coin,
        small_coin_total=first_market_small_coin + second_market_small_coin,
        bnb=bnb,
        huobi_point=huobi_point,
        symbol_price=symbol_price,
        bnb_price=bnb_price,
        btc_price=btc_price,
        status=status,
        big_coin_btc_price=big_coin_btc_price,
        log_time=datetime.utcnow()).add()
    print("{}|GetAccount|{}".format(
        datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f'),
        combination.combination))