Exemple #1
0
 def __init__(self, account='*****@*****.**'):
     conf = VConf()
     url = conf.get_http('huobi')
     apikey = conf.get_apikey('huobi', account)
     apisecret = conf.get_secret('huobi', account)
     self.__uid = ''
     super(HuobiService, self).__init__(url, apikey, apisecret)
Exemple #2
0
 def _btc_usdt(self, account='13651401725'):
     '''获取btc的usdt价格,默认是okex的ticker数据
     '''
     conf = VConf()
     url = conf.get_http('okex')
     apikey = conf.get_apikey('okex', account)
     apisecret = conf.get_secret('okex', account)
     okexhttp = OkexHttp(url, apikey, apisecret)
     self.btc_usdt = float(okexhttp.ticker('btc_usdt')['ticker']['last'])
def getBtcUsdt():
    '''获取btc的usdt报价
    '''
    conf = VConf()
    account = '*****@*****.**'
    url = conf.get_http('okex')
    apikey = conf.get_apikey('okex', account)
    apisecret = conf.get_secret('okex', account)
    okexhttp = OkexHttp(url, apikey, apisecret)
    return float(okexhttp.ticker('btc_usdt')['ticker']['last'])
class ExchangeHuobi(HuobiHttp):
    def __init__(self, account='*****@*****.**'):
        self.conf = VConf()
        url = self.conf.get_http('huobi')
        apikey = self.conf.get_apikey('huobi', account)
        apisecret = self.conf.get_secret('huobi', account)
        self.__uid = ''
        super(ExchangeHuobi, self).__init__(url, apikey, apisecret)
        self.exch_account = account
        self.stat_huobi = {}

    def bb0(self):
        account = filter(lambda x: x['type'] == 'spot',
                         self.accounts()['data'])[0]
        balances = self.balance(account['id'])
        if not balances or balances.get('status') != 'ok':
            return
        balance = {}
        for item in balances['data']['list']:
            holding = 0.0
            price = 0.0
            try:
                if (float(item['balance']) < 0.00000001):
                    continue
                item['currency'] = item['currency'].upper()
                key = item['currency']
                if (not balance.get(key)):
                    balance[key.upper()] = {
                        'ts': ts,
                        'holding': 0.0,
                        'price': 0.0,
                        'account': self.exch_account,
                    }
                if (item['type'] == 'trade'):
                    holding = float(item['balance'])
                if (item['type'] == 'frozen'):
                    holding = float(item['balance'])
                if key.lower() == 'usdt':
                    price = 1.0
                else:
                    price = self.detail_merged(key.lower() +
                                               'usdt')['tick']['open']
                if holding * price < 1:
                    continue
                balance[key.upper()] = {
                    'ts': ts,
                    'holding': holding,
                    'price': price,
                    'account': self.exch_account,
                }
            except:
                continue
        self.stat_huobi['bb0'] = balance
        return balance
class ExchangeBina(BinaHttp):
    def __init__(self, account='*****@*****.**'):
        self.conf = VConf()
        url = self.conf.get_http('binance')
        apikey = self.conf.get_apikey('binance', account)
        apisecret = self.conf.get_secret('binance', account)
        super(ExchangeBina, self).__init__(url, apikey, apisecret)
        self.exch_account = account
        self.stat_bina = {}

    def bb0(self):
        acc = self.account()
        infos = acc.get('balances')
        if not infos:
            return
        currency = infos
        balances = {}
        for cur in currency:
            holding = 0.0
            price = 0.0
            if (float(cur['free']) + float(cur['locked']) < 0.000001):
                continue
            holding = float(cur['free']) + float(cur['locked'])
            try:
                if cur['asset'].upper() == 'USDT':
                    price = 1.0
                else:
                    price = float(
                        self.ticker(cur['asset'].upper() +
                                    'USDT')['lastPrice'])
                balances[cur['asset'].upper()] = {
                    'ts': ts,
                    'holding': holding,
                    'price': price,
                    'account': self.exch_account,
                }
            except:
                continue
        self.stat_bina['bb0'] = balances
        return balances
class ExchangeOkex(OkexHttp, OkexftHttp):
    '''获取OKEX账户的持仓和价格
    bb0: 币币权益部分
    ft1: 合约权益部分
    ft2: 合约持仓部分
    '''
    def __init__(self, account='*****@*****.**'):
        '''只接受单账户的传入,多账户下需外部进行遍历
        '''
        self.conf = VConf()
        url = self.conf.get_http('okex')
        apikey = self.conf.get_apikey('okex', account)
        apisecret = self.conf.get_secret('okex', account)
        super(ExchangeOkex, self).__init__(url, apikey, apisecret)
        self.exch_account = account
        self.contract_types = ['this_week', 'next_week', 'quarter']
        self.stat_okex = {}

    def bb0(self):
        '''获取OKEX的币币权益
        没有币种不做
        持仓量低不做
        权益数低不做
        '''
        userinfo = self.userinfo()['info']['funds']
        if not userinfo:
            return
        free = userinfo['free']
        freezed = userinfo['freezed']
        currency = set(free.keys() + freezed.keys())
        balances = {}
        for cur in currency:
            holding = 0.0
            price = 0.0
            try:
                if (free.get(cur) == None):
                    free[cur] = 0.0
                if (freezed.get(cur) == None):
                    freezed[cur] = 0.0
                if (float(free[cur]) < 0.000001
                        and float(freezed[cur]) < 0.000001):
                    continue
                holding = float(free[cur]) + float(freezed[cur])
                if cur == 'usdt':
                    price = 1.0
                elif self.ticker(cur.lower() + '_usdt'):
                    price = float(
                        self.ticker(cur.lower() + '_usdt')['ticker']['last'])
                if holding * price < 1:
                    continue
                balances[cur.upper()] = {
                    'ts': ts,
                    'holding': holding,
                    'price': price,
                    'account': self.exch_account,
                }
            except:
                continue
        self.stat_okex['bb0'] = balances
        return balances

    def ft1(self):
        '''获取OKEX的合约权益
        '''
        userinfo = self.future_userinfo()['info']
        if not userinfo:
            return
        currency = userinfo.keys()
        balances = {}
        for cur in currency:
            holding = 0.0
            price = 0.0
            if userinfo[cur]['account_rights'] > 0.0001:
                try:
                    holding = userinfo[cur]['account_rights']
                    if cur == 'usdt':
                        price = 1.0
                    elif self.ticker(cur.lower() + '_usdt'):
                        price = float(
                            self.ticker(cur.lower() +
                                        '_usdt')['ticker']['last'])
                    if holding * price < 1:
                        continue
                    balances[cur.upper()] = {
                        'ts': ts,
                        'holding': holding,
                        'price': price,
                        'account': self.exch_account,
                    }
                except:
                    continue
        self.stat_okex['ft1'] = balances
        return balances

    def ft2(self):
        '''获取OKEX的合约持仓
        '''
        userinfo = self.future_userinfo()['info']
        if not userinfo:
            return
        currency = userinfo.keys()
        balances = {}
        for cur in currency:
            cur = cur.lower() + '_usd'
            for con in self.contract_types:
                holding = 0.0
                price = 0.0
                try:
                    if len(self.future_position(cur, con)['holding']) > 0:
                        holding = float(
                            self.future_position(
                                cur, con)['holding'][0]['buy_amount']) - float(
                                    self.future_position(
                                        cur, con)['holding'][0]['sell_amount'])
                        if self.future_ticker(cur, con):
                            price = float(
                                self.future_ticker(cur, con)['ticker']['last'])
                        if cur == 'btc_usd':
                            holding = holding * 100 / price
                        else:
                            holding = holding * 10 / price
                        if abs(holding * price) < 1:
                            continue
                        balances[cur[:-3].upper() + con] = {
                            'ts': ts,
                            'holding': holding,
                            'price': price,
                            'account': self.exch_account,
                        }
                except:
                    continue
        self.stat_okex['ft2'] = balances
        return balances
Exemple #7
0
class OkexService(OkexHttp, OkexftHttp):
    ''' OkexService 
        1. 法币账户
        2. 币币账户
        3. 合约账户
        4. margin账户
        只支持币币账户和合约账户
    '''
    def __init__(self, account='*****@*****.**'):
        ''' okex okexft的http地址一致 '''
        self.conf = VConf()
        url = self.conf.get_http('okex')
        apikey = self.conf.get_apikey('okex', account)
        apisecret = self.conf.get_secret('okex', account)
        self.contract_types = ['this_week', 'next_week', 'quarter']
        super(OkexService, self).__init__(url, apikey, apisecret)

    def ft_balances_list(self):
        ''' 期货权益 '''
        userinfo = self.future_userinfo()['info']
        balances = {}
        for k in userinfo:
            if userinfo[k]['account_rights'] > 0.0001:
                balances[k.upper()] = userinfo[k]
        return balances

    def bb_balances_list(self):
        ''' 币币权益 '''
        userinfo = self.userinfo()['info']['funds']
        free = userinfo['free']
        freezed = userinfo['freezed']
        keys = set(free.keys() + freezed.keys())
        balances = {}
        for key in keys:
            if (free.get(key) == None): free[key] = 0.0
            if (freezed.get(key) == None): freezed[key] = 0.0
            if (float(free[key]) < 0.000001
                    and float(freezed[key]) < 0.000001):
                continue
            balances[key.upper()] = {
                'currency': key.upper(),
                'free': float(free[key]),
                'freezed': float(freezed[key])
            }
        return balances

    def balances_list(self):
        balances = self.bb_balances_list()
        for b in balances:
            balances[b]['future'] = 0
        ft = self.ft_balances_list()
        for c in ft:
            if not balances.get(c):
                balances[c] = {}
                balances[c]['free'] = 0
                balances[c]['freezed'] = 0
            balances[c]['future'] = ft[c]['account_rights']
        return balances

    def c1toc2(self, c1, c2):
        c1 = c1.lower()
        c2 = c2.lower()
        if c1 == c2: return 1
        ticker = self.ticker(c1 + '_' + c2)
        if ticker.get('ticker'):
            return float(ticker['ticker']['last'])
        return None

    def tousdt(self, currency):
        usdt = self.c1toc2(currency, 'usdt')
        if usdt: return usdt
        btc = self.c1toc2(currency, 'btc')
        usdt = self.c1toc2('btc', 'usdt')
        if btc and usdt:
            return btc * usdt
        return 0

    def sum_usdt(self):
        _sum = 0.0
        balances = self.balances_list()
        for currency in balances:
            balance = balances[currency]
            bvol = float(balance['free']) + float(balance['freezed']) + float(
                balance['future'])
            _sum += bvol * self.tousdt(currency)
        return _sum

    ################################加减仓相关######################################################
    def okex_cancel_order(self, symbols=''):
        ''' okex币币 撤掉挂单'''
        channels = self.conf.get_channels('OKEX')
        channels = [
            i.replace('OKEX--', '').reaplce('--', '_').lower()
            for i in channels
        ]
        for cc in channels:
            if symbols and symbols == cc:
                continue
            orders = self.orderinfo(cc)
            for order in orders:
                self.cancelorder(order['symbol'], order['order_id'])
            time.sleep(0.5)
        return True

    def okex_future_cancel(self, symbol='', contract_type=''):
        ''' okex合约 撤单 '''
        #查询持仓权益  根据持仓权益符号查询订单id 然后撤单
        channels = self.conf.get_channels('OKEXFT')
        channels = [
            i.replace('OKEXFT--', '').reaplce('--', '_').lower()
            for i in channels
        ]
        #查询orderid
        for cc in channels:
            for contract_type in contract_types:
                orders = self.future_order_info(cc, contract_type, -1)
                for order in orders:
                    self.future_cancel(order['symbol'], contract_type,
                                       order['order_id'])
                    time.sleep(0.1)
        return True

    def okex_future_closeposition(self):
        ''' 期货平仓 '''
        channels = self.conf.get_channels('OKEXFT')
        channels = [
            i.replace('OKEXFT--', '').reaplce('--', '_').lower()
            for i in channels
        ]
        for cc in channels:
            for contract_type in contract_types:
                positions = self.future_position(cc, contract_type)
                for position in positions:
                    if position['buy_available'] > 0:
                        self.future_trade(cc, contract_type, 3, 0,
                                          position['buy_available'], 1)
                    if position['sell_available'] > 0:
                        self.future_trade(cc, contract_type, 4, 0,
                                          position['buy_available'], 1)
                    time.sleep(0.2)
        return True

    def ft_account_2bb(self, currency='', amount=0):
        ''' currency转换到bb账户 或者 所有资金转换到币币账户'''
        if not amount:
            balances = self.ft_balances_list()
            balances = [(b, b['account_rights']) for b in balances]
            if currency:
                balances = filter(lambda x: x[0] == currency, balances)
        else:
            balances = [(currency, amount)]

        for b in balances:
            self.funds_transfer(b[0], b[1], 3, 1)

    def balance_btc(self, currency, quantity, side='sell-market', price=0):
        ''' 货币转化为btc '''
        if currency == 'BTC': return
        symbol = currency.upper() + 'BTC'
        self.addorder(symbol, side, price, quantity)

    def balance_usdt(self, currency, quantity, side='sell-market', price=0):
        ''' 货币转化为usdt '''
        if currency == 'USDT': return
        symbol = currency.upper() + 'USDT'
        self.addorder(symbol, side, price, quantity)

    def balance_all_tousdt(self):
        ''' 
            所有的货币不能转化为usdt的线转化为btc  转化为usdt
            1. 期货撤单
            2. 期货平仓
            3. 期货账户转到币币账户
            4. 币币取消订单
            5. 将比比所有的资金转化为usdt
        '''
        #self.okex_future_cancel()
        #
        #self.okex_future_closeposition()

        #self.ft_account_2bb()

        #self.okex_cancel_order()

        #self.okex_balance_usdt()

        channels = self.conf.get_channels('OKEX')
        channels = [
            i.replace('OKEX--', '').reaplce('--', '') for i in channels
        ]

        def tousdt():
            balances_list = self.balances_list()
            for b in balances_list:
                currency = b['asset'].upper()
                if (currency and currency != currency) or currency == 'USDT':
                    continue
                free = float(b['free'])
                if free < 0.0001: continue

                if currency + 'USDT' not in symbols:
                    self.balance_btc(currency, free)
                else:
                    self.balance_usdt(currency, free)

        tousdt()
        tousdt()