Beispiel #1
0
    def api_get(self, method, params={}):
        # 现货API
        if self.account:
            apikey, secretkey = get_account_key("okex", self.account)
        okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey)
        if method == "userinfo":
            api_do = "okcoinSpot.%s()" % (method)
            return eval(api_do)

        elif method in ["buy", "sell"]:
            return okcoinSpot.trade(params["symbol"],
                                    method,
                                    params["price"],
                                    params["amount"])
        elif method == "cancelOrder":
            return okcoinSpot.cancelOrder(params["symbol"],
                                          params["id"])

        elif method in ["order_info", "orders_info"]:
            return okcoinSpot.orderinfo(params["symbol"],
                                        params["id"])

        elif method == "ticker":
            return okcoinSpot.ticker(symbol=params["symbol"])

        elif method == "funds_transfer":
            return okcoinSpot.funds_transfer(params["amount"],params["From"],params["To"], params["symbol"])
        elif method == "withdraw":
            #tradepwd = get_tradepwd("okex", self.account)
            tradepwd="huangxinyu2"
            return okcoinSpot.withdraw(params["symbol"], params["address"],
            params["amount"], tradepwd,
            params["fee"],
            params["addr_tag"])
Beispiel #2
0
    def api_get(self, method, params={}):
        # 现货API
        if self.account:
            apikey, secretkey = get_account_key("okex", self.account)
        okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey)
        if method == "userinfo":
            api_do = "okcoinSpot.%s()" % (method)
            return eval(api_do)

        elif method in ["buy", "sell"]:
            return okcoinSpot.trade(params["symbol"], method, params["price"],
                                    params["amount"])
        elif method == "cancelOrder":
            return okcoinSpot.cancelOrder(params["symbol"], params["id"])

        elif method in ["order_info", "orders_info"]:
            return okcoinSpot.orderinfo(params["symbol"], params["id"])

        elif method == "ticker":
            return okcoinSpot.ticker(symbol=params["symbol"])
        elif method == "funds_transfer":
            return okcoinSpot.funds_transfer(params["amount"],
                                             params["from"],
                                             params["to"],
                                             symbol=params["symbol"])
Beispiel #3
0
	try:
		res = json.loads(okcoinSpot.userinfo())
	except:
		continue
	funds = res['info']['funds']
	#print (funds)
	for i in range(marketLength):
		Balances[i] = float(funds['free'][Names[i]])+float(funds['freezed'][Names[i]])

	#print (u' 现货订单信息查询 ')
	flagsuc = True
	for i in range(1,marketLength):
		buyOrders[i] = []
		sellOrders[i] = []
		try:
			res = json.loads(okcoinSpot.orderinfo(Names[i]+'_'+Names[0],'-1'))
		except:
			flagsuc = False
			break
		#print (res)
		orders = res['orders']
		for order in orders:
			#print (order)
			info = [order['order_id'], order['price'], order['amount']]
			if order['type'] == 'buy':
				buyOrders[i].append(info)
			elif order['type'] == 'sell':
				sellOrders[i].append(info)
	if not flagsuc:
		continue
	#print (Balances)
Beispiel #4
0
#!/usr/bin/python3.4
# -*- coding: utf-8 -*-
# encoding: utf-8
#客户端调用,用于查看API返回结果

from OkcoinSpotAPI import OKCoinSpot
from OkcoinFutureAPI import OKCoinFuture
import time

#初始化apikey,secretkey,url
apikey = 'db052c78-71e1-4db6-ae7f-f9c659568c30'
secretkey = '93CD90F4E914E8FD08A7DC5423F260C7'
okcoinRESTURL = 'www.okcoin.cn'   #请求注意:国内账号需要 修改为 www.okcoin.cn  
time_sleep = 5

#现货API
okcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey)

trade_record_file = open("./btcTradeRecord.txt", "a+")
print (u'Trade Info ')

#print (okcoinSpot.trade('btc_cny','buy_market',price=250))
#print (okcoinSpot.trade('btc_cny','sell_market',amount=0.1))

print (u' 现货订单信息查询 ')
print (okcoinSpot.orderinfo('btc_cny', '185184673'))
print (okcoinSpot.get_fee('btc_cny', '185184673'))

trade_record_file.close()
Beispiel #5
0
error_flag = True
while True:
    if error_count >= 10:
        error_log = "%s    %s\n" % (time.strftime("%Y/%m/%d/%H:%M:%S"), "ERROR count exceed!")
        first_trade_error.write(error_log)
        break
    if symbol == 'btc_cny':
        if trade_type == 'buy_market':
            try:
                btc_trade_str = okcoinSpot.trade('btc_cny','buy_market',price)
                btc_trade = json.loads(btc_trade_str)
                if btc_trade['result'] == True:
                    order_id = btc_trade['order_id']
                    while True:
                        try:
                            orderinfo_str = okcoinSpot.orderinfo('btc_cny', str(order_id))
                            orderinfo = json.loads(orderinfo_str)
                            if orderinfo['orders'][0]['status'] == 2:
                                result = {'results': True, 'avg_price': orderinfo['orders'][0]['avg_price'],
                                          'deal_amount': orderinfo['orders'][0]['deal_amount']}
                                print (json.dumps(result))
                                error_flag = False
                                output_log = "%s    BUY_MARKET, price %s, avg_price:%f, deal_amount %f\n" % (time.strftime("%Y/%m/%d/%H:%M:%S"), price, orderinfo['orders'][0]['avg_price'], orderinfo['orders'][0]['deal_amount'])
                                first_trade_file.write(output_log)
                                first_trade_file.flush()
                                break
                        except Exception as e:
                            error_log = "%s    %s\n" % (time.strftime("%Y/%m/%d/%H:%M:%S"), e)
                            first_trade_error.write(error_log)
                            first_trade_error.flush()
                    break
Beispiel #6
0
print okcoinSpot.trades()

print u' 用户现货账户信息 '
print okcoinSpot.userinfo()

print u' 现货下单 '
print okcoinSpot.trade('ltc_usd','buy','0.1','0.2')

print u' 现货批量下单 '
print okcoinSpot.batchTrade('ltc_usd','buy','[{price:0.1,amount:0.2},{price:0.1,amount:0.2}]')

print u' 现货取消订单 '
print okcoinSpot.cancelOrder('ltc_usd','18243073')

print u' 现货订单信息查询 '
print okcoinSpot.orderinfo('ltc_usd','18243644')

print u' 现货批量订单信息查询 '
print okcoinSpot.ordersinfo('ltc_usd','18243800,18243801,18243644','0')

print u' 现货历史订单信息查询 '
print okcoinSpot.orderHistory('ltc_usd','0','1','2')

print u' 期货行情信息'
print okcoinFuture.future_ticker('ltc_usd','this_week')

print u' 期货市场深度信息'
print okcoinFuture.future_depth('ltc_usd','this_week','6')

print u'期货交易记录信息' 
print okcoinFuture.future_trades('ltc_usd','this_week')
Beispiel #7
0
class okex():
    def __init__(self):
        ##初始化apikey,secretkey,url
        apikey = config.apikey
        secretkey = config.secretkey
        okcoinRESTURL = 'www.okex.com'   #请求注意:国内账号需要 修改为 www.okcoin.cn

        #现货API
        self.okcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey)

        # 期货API
        self.okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey)

        self.depth = {}


    def getTicker(self, symbol):
        return self.okcoinSpot.ticker(symbol)['ticker']

    def getDepth(self, symbol):
        while(1):
            sleep(0.5)
            try:
                depth = self.okcoinSpot.depth(symbol)
            except Exception:
                pass
            DEPTH[symbol] = {'sell':{'price':depth['asks'][-1][0], 'amount':depth['asks'][-1][1]},
                    'buy':{'price':depth['bids'][0][0], 'amount':depth['bids'][0][1]}}
            print(symbol)
            print(DEPTH)
            # return {'sell':{'price':depth['asks'][-1][0], 'amount':depth['asks'][-1][1]},
            #         'buy':{'price':depth['bids'][0][0], 'amount':depth['bids'][0][1]}}

    def getBalance(self):
        '''

        :return:
        '''
        self.balance = {}
        info = json.loads(self.okcoinSpot.userinfo())
        for symbol in info['info']['funds']['free'].keys():
            self.balance[symbol] = float(info['info']['funds']['free'][symbol])

    def trade(self, symbol, type, price, amount):
        '''

        :param symbol:
        :param type:
        :param price:
        :param amount:
        :return: order_id
        '''
        if price != '':
            logging.info('[order]' + symbol + '|' + type+ '|' + str(price) + '|' + str(amount))
        rsp = json.loads(self.okcoinSpot.trade(symbol, type, price, amount))
        if 'error_code' in rsp:
            if str(rsp['error_code']) != '1003':
                logging.info('[trade error]' + str(rsp['error_code']))
            return False
        if rsp['result']:
            return rsp['order_id']

    def getOrderInfo(self, symbol, order_id):
        '''

        :param symbol:
        :param order_id:
        :return: order_status: -1:已撤销  0:未成交  1:部分成交  2:完全成交 3:撤单处理中
        '''
        rsp = json.loads(self.okcoinSpot.orderinfo(symbol, order_id))
        if 'error_code' in rsp:
            logging.info('[getOrderInfo error]' + str(rsp['error_code']))
            return False
        if rsp['result']:
            return int(rsp['orders'][0]['status'])
        else:
            return False

    def toBtc(self):
        self.getBalance()
        for symbol in self.balance.keys():
            if symbol != 'usdt' and symbol != 'btc' and symbol != 'mtl' and self.balance[symbol] != 0:
                # print(symbol)
                if self.balance[symbol] != 0:
                    tradeSymbol = symbol + '_btc'
                    self.trade(tradeSymbol, 'sell_market', '', self.balance[symbol])

    def cancelOrder(self, symbol, order_id):
        '''

        :param symbol:
        :param order_id:
        :return: True or False
        '''
        rsp = json.loads(self.okcoinSpot.cancelOrder(symbol, order_id))
        if 'error_code' in rsp:
            logging.info('[cancelOrder error]' + str(rsp['error_code']))
            return False
        return rsp['result']

    def good_trade(self, symbols, Threshold=1.02):
        '''

        :param symbols: such as [btc, eth, mco]
        :return:
        '''
        symbol_1 = symbols[1] + '_' + symbols[0]
        symbol_2 = symbols[2] + '_' + symbols[0]
        symbol_3 = symbols[2] + '_' + symbols[1]
        t1 = self.getTicker(symbol_1)
        t2 = self.getTicker(symbol_2)
        t3 = self.getTicker(symbol_3)
        # print ('=======================================')
        # temp = (float(t2['sell']) / float(t3['buy']))
        a1 = (float(t2['sell']) / float(t3['buy'])) / float(t1['buy'])
        a2 = (float(t1['sell']) * float(t3['sell'])) / float(t2['buy'])

        if a1 < Threshold:
            traderSymbol = [symbol_2, symbol_3, symbol_1]

            logging.debug('=======================================')
            logging.debug(a1)
            logging.debug('[trader] ' + symbols[0] + '--->' + symbols[2] + '--->' + symbols[1] + '--->' + symbols[0])
            logging.debug(t1)
            logging.debug(t2)
            logging.debug(t3)
        elif a2 < Threshold:
            traderSymbol = [symbol_1, symbol_3, symbol_2]

            logging.debug('=======================================')
            logging.debug(a2)
            logging.debug('[trader] ' + symbols[0] + '--->' + symbols[1] + '--->' + symbols[2] + '--->' + symbols[0])
            logging.debug(t1)
            logging.debug(t2)
            logging.debug(t3)
        else:
            pass

    def tradePolicy(self, symbols, initAmount=0.005, Threshold=1.02):
        '''

        :param symbols: such as [btc, eth, mco]
        :return:
        '''
        retry = 3
        symbol_1 = symbols[1] + '_' + symbols[0]
        symbol_2 = symbols[2] + '_' + symbols[0]
        symbol_3 = symbols[2] + '_' + symbols[1]
        t1 = self.getDepth(symbol_1)
        t2 = self.getDepth(symbol_2)
        t3 = self.getDepth(symbol_3)
        a1 = (float(t2['sell']['price']) / float(t3['buy']['price'])) / float(t1['buy']['price'])
        a2 = (float(t1['sell']['price']) * float(t3['sell']['price'])) / float(t2['buy']['price'])
        # logging.debug(t1)
        if a1 < Threshold:
            if float(t2['sell']['amount']) < amount[symbol_2] or float(t3['buy']['amount']) < amount[symbol_3] or\
                float(t1['buy']['amount']) < amount[symbol_1]:
                return
            logging.info('=========================================================')
            logging.debug(a1)
            traderSymbol = [symbol_2, symbol_3, symbol_1]
            logging.debug('[trader] ' + symbols[0] + '--->' + symbols[2] + '--->' + symbols[1] + '--->' + symbols[0])
            logging.debug(t1)
            logging.debug(t2)
            logging.debug(t3)
            #step1
            logging.info('[step1]')
            self.getBalance()
            self.toBtc()
            logging.info('[Balance]')
            logging.info(self.balance)
            amount1 = round((initAmount * 0.999) / float(t2['sell']['price']), 8)
            for i in range(retry):
                logging.info('[order]' + symbol_2 + '|buy|' + str(float(t2['sell']['price'])) + '|' + str(amount1))
                orderId = self.trade(symbol_2, 'buy', float(t2['sell']['price']), amount1)
                if orderId:
                    break
            if orderId:
                logging.info('[orderId]' + str(orderId))
                status = self.getOrderInfo(symbol_2, orderId)
                if status != 2:
                    print(status)
                    sleep(0.5)
                    status = self.getOrderInfo(symbol_2, orderId)
                    if status != 2:
                        print(status)
                        self.cancelOrder(symbol_2, orderId)
                        logging.info('[cancelOrder!]')
                        return
                    else:
                        logging.info('[order succssed!]')
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order failed!]')
                return

            #step2
            logging.info('[step2]')
            self.getBalance()
            logging.info('[Balance]')
            logging.info(self.balance)
            amount2 = self.balance[symbols[2]]
            for i in range(retry):
                logging.info('[order]' + symbol_3 + '|sell|' + str(float(t3['buy']['price'])) + '|' + str(amount2))
                orderId = self.trade(symbol_3, 'sell', float(t3['buy']['price']), amount2)
                if orderId:
                    break
            if orderId:
                logging.info('[orderId]' + str(orderId))
                status = self.getOrderInfo(symbol_3, orderId)
                if status != 2:
                    sleep(0.5)
                    status = self.getOrderInfo(symbol_3, orderId)
                    if status != 2:
                        self.cancelOrder(symbol_3, orderId)
                        logging.info('cancelOrder!')
                        return
                    else:
                        logging.info('[order succssed!]')
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order failed!]')
                return

            #step3
            logging.info('[step3]')
            self.getBalance()
            logging.info('[Balance]')
            logging.info(self.balance)
            amount3 = self.balance[symbols[1]]
            for i in range(retry):
                logging.info('[order]' + symbol_1 + '|sell|' + str(float(t1['buy']['price'])) + '|' + str(amount3))
                orderId = self.trade(symbol_1, 'sell', float(t1['buy']['price']), amount3)
                if orderId:
                    break
            if orderId:
                logging.info('[orderId]' + str(orderId))
                status = self.getOrderInfo(symbol_1, orderId)
                if status != 2:
                    sleep(0.5)
                    status = self.getOrderInfo(symbol_1, orderId)
                    if status != 2:
                        self.cancelOrder(symbol_1, orderId)
                        logging.info('cancelOrder!')
                        return
                    else:
                        logging.info('[order succssed!]')
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order failed!]')
                return

        elif a2 < Threshold:
            if float(t2['buy']['amount']) < amount[symbol_2] or float(t3['sell']['amount']) < amount[symbol_3] or\
                float(t1['sell']['amount']) < amount[symbol_1]:
                return
            logging.info('=========================================================')
            logging.debug(a2)
            traderSymbol = [symbol_1, symbol_3, symbol_2]
            logging.debug('[trader] ' + symbols[0] + '--->' + symbols[1] + '--->' + symbols[2] + '--->' + symbols[0])
            logging.debug(t1)
            logging.debug(t2)
            logging.debug(t3)

            # step1
            logging.info('[step1]')
            self.getBalance()
            self.toBtc()
            logging.info('[Balance]')
            logging.info(self.balance)
            amount1 = round((initAmount * 0.999) / float(t1['sell']['price']), 8)
            for i in range(retry):
                logging.info('[order]' + symbol_1 + '|buy|' + str(float(t1['sell']['price'])) + '|' + str(amount1))
                orderId = self.trade(symbol_1, 'buy', float(t1['sell']['price']), amount1)
                if orderId:
                    break
            if orderId:
                logging.info('[orderId]' + str(orderId))
                status = self.getOrderInfo(symbol_1, orderId)
                if status != 2:
                    sleep(0.5)
                    status = self.getOrderInfo(symbol_1, orderId)
                    if status != 2:
                        self.cancelOrder(symbol_1, orderId)
                        logging.info('cancelOrder!')
                        return
                    else:
                        logging.info('[order succssed!]')
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order failed!]')
                return

            # step2
            logging.info('[step2]')
            self.getBalance()
            logging.info('[Balance]')
            logging.info(self.balance)
            amount2 = round((self.balance[symbols[1]] * 0.999) / float(t3['sell']['price']), 8)
            for i in range(retry):
                logging.info('[order]' + symbol_3 + '|buy|' + str(float(t3['sell']['price'])) + '|' + str(amount2))
                orderId = self.trade(symbol_3, 'buy', float(t3['sell']['price']), amount2)
                if orderId:
                    break
            if orderId:
                logging.info('[orderId]' + str(orderId))
                status = self.getOrderInfo(symbol_3, orderId)
                if status != 2:
                    sleep(0.5)
                    status = self.getOrderInfo(symbol_3, orderId)
                    if status != 2:
                        self.cancelOrder(symbol_3, orderId)
                        logging.info('cancelOrder!')
                        return
                    else:
                        logging.info('[order succssed!]')
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order failed!]')
                return

            # step3
            logging.info('[step3]')
            self.getBalance()
            logging.info('[Balance]')
            logging.info(self.balance)
            amount3 = self.balance[symbols[2]]
            for i in range(retry):
                logging.info('[order]' + symbol_2 + '|sell|' + str(float(t2['buy']['price'])) + '|' + str(amount3))
                orderId = self.trade(symbol_2, 'sell', float(t2['buy']['price']), amount3)
                if orderId:
                    break
            if orderId:
                logging.info('[orderId]' + str(orderId))
                status = self.getOrderInfo(symbol_2, orderId)
                if status != 2:
                    sleep(0.5)
                    status = self.getOrderInfo(symbol_2, orderId)
                    if status != 2:
                        self.cancelOrder(symbol_2, orderId)
                        logging.info('cancelOrder!')
                        return
                    else:
                        logging.info('[order succssed!]')
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order failed!]')
                return
        else:
            pass

    def getCoinList(self, symbols):
        coinList = []
        for k in permutations(symbols, 2):
            tmp = ['btc', k[0], 'eth', k[1]]
            coinList.append(tmp)
        return coinList

    def getTradeSymbol(self, coinlist):
        ts =[]
        for c in coinlist:
            s = ['_'.join((c[1], c[0])),
                '_'.join((c[1], c[2])),
                '_'.join((c[3], c[2])),
                '_'.join((c[3], c[0]))]
            ts.append(s)
        return ts

    def getTradeAmount(self, symbols):
        print(self.depth)
        for s in symbols:
            if s not in self.depth:
                return 0
        print('getTrade:')
        print(symbols)
        ss = (self.depth[symbols[1]]['buy']['price'] * self.depth[symbols[3]]['buy']['price']) / (self.depth[symbols[0]]['sell']['price'] * self.depth[symbols[2]]['sell']['price'])
        if ss > 0.90:
            # logging.debug('profit: %f' % ss)
            # logging.debug(symbols)
            # logging.debug(self.depth[symbols[0]])
            # logging.debug(self.depth[symbols[1]])
            # logging.debug(self.depth[symbols[2]])
            # logging.debug(self.depth[symbols[3]])
            amount = []
            amount.append(self.depth[symbols[0]]['sell']['price'] * min(self.depth[symbols[0]]['sell']['amount'],self.depth[symbols[1]]['buy']['amount']))
            amount.append(self.depth[symbols[3]]['buy']['price'] * min(self.depth[symbols[3]]['buy']['amount'],self.depth[symbols[2]]['sell']['amount']))
            amount.sort()
            logging.debug('amount: %f' % amount[0])
            if amount[0] > 0.0001:
                logging.debug('profit: %f' % ss)
                logging.debug(symbols)
                logging.debug(self.depth[symbols[0]])
                logging.debug(self.depth[symbols[1]])
                logging.debug(self.depth[symbols[2]])
                logging.debug(self.depth[symbols[3]])
            return amount[0]
        else:
            return 0

    def doTrade(self, symbols, amount):
        if self.balance['btc'] < amount * 0.9:
            initamount = self.balance['btc'] * 0.99
        else:
            initamount = amount * 0.9

        logging.debug('step1')
        amount1 = round(initamount / self.depth[symbols[0]]['sell']['price'], 8)
        orderId = self.trade(symbols[0], 'buy', self.depth[symbols[0]]['sell']['price'], amount1)
        if orderId:
            logging.info('[orderId]' + str(orderId))
            status = self.getOrderInfo(symbols[0], orderId)
            if status != 2:
                sleep(0.5)
                status = self.getOrderInfo(symbols[0], orderId)
                if status != 2:
                    self.cancelOrder(symbols[0], orderId)
                    logging.info('cancelOrder!')
                    return
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order succssed!]')
        else:
            logging.info('[order failed!]')
            return

        logging.debug('step2')
        self.getBalance()
        logging.info('[Balance]')
        logging.info(self.balance)
        amount2 = self.balance[symbols[1].split('_')[0]]
        orderId = self.trade(symbols[1], 'sell', self.depth[symbols[1]]['buy']['price'], amount2)
        if orderId:
            logging.info('[orderId]' + str(orderId))
            status = self.getOrderInfo(symbols[1], orderId)
            if status != 2:
                sleep(0.5)
                status = self.getOrderInfo(symbols[1], orderId)
                if status != 2:
                    self.cancelOrder(symbols[1], orderId)
                    logging.info('cancelOrder!')
                    return
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order succssed!]')
        else:
            logging.info('[order failed!]')
            return

        logging.debug('step3')
        self.getBalance()
        logging.info('[Balance]')
        logging.info(self.balance)
        amount3 = round((self.balance[symbols[2].split('_')[1]] / self.depth[symbols[2]]['sell']['price']) * 0.998, 8)
        orderId = self.trade(symbols[2], 'buy', self.depth[symbols[2]]['sell']['price'], amount3)
        if orderId:
            logging.info('[orderId]' + str(orderId))
            status = self.getOrderInfo(symbols[2], orderId)
            if status != 2:
                sleep(0.5)
                status = self.getOrderInfo(symbols[2], orderId)
                if status != 2:
                    self.cancelOrder(symbols[2], orderId)
                    logging.info('cancelOrder!')
                    return
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order succssed!]')
        else:
            logging.info('[order failed!]')
            return

        logging.debug('step4')
        self.getBalance()
        logging.info('[Balance]')
        logging.info(self.balance)
        amount4 = self.balance[symbols[3].split('_')[0]]
        orderId = self.trade(symbols[3], 'sell', self.depth[symbols[3]]['buy']['price'], amount4)
        if orderId:
            logging.info('[orderId]' + str(orderId))
            status = self.getOrderInfo(symbols[3], orderId)
            if status != 2:
                sleep(0.5)
                status = self.getOrderInfo(symbols[3], orderId)
                if status != 2:
                    self.cancelOrder(symbols[3], orderId)
                    logging.info('cancelOrder!')
                    return
                else:
                    logging.info('[order succssed!]')
            else:
                logging.info('[order succssed!]')
        else:
            logging.info('[order failed!]')
            return

    def policy(self, allsymbol):
        coins = self.getCoinList(allsymbol)
        tradesymbol = self.getTradeSymbol(coins)
        while(1):
            for symbols in tradesymbol:
                # print(symbols)
                # self.toBtc()
                a = self.getTradeAmount(symbols)
                sleep(0.5)
Beispiel #8
0
class Ok_api:
	
    def __init__(self, mykey=None, mysecret=None):
        if mykey and mysecret:
            self.mykey,self.mysecret = mykey,mysecret
        else:
            filename = CURRENTURL+r'\key'
            with open(filename,'r',encoding='utf-8') as f:
                data = f.read()
            self.mykey,self.mysecret = data.split('\n')
            self.mykey = self.mykey.strip()
            self.mysecret = self.mysecret.strip()

        okcoinRESTURL = 'www.okb.com'
        # print(self.mykey,self.mysecret)
        self.okcoinSpot = OKCoinSpot(okcoinRESTURL,self.mykey,self.mysecret)

    def __api_public_call(self,path,params=''):
        headers = {
        'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36 Maxthon/5.1.3.2000',
        }

        url = 'https://www.okb.com/api/v1/' + path + params
        req = urllib.request.Request(url,headers=headers)
        res = urllib.request.urlopen(req, timeout=10)
        doc = json.loads(res.read().decode('utf-8')) # .decode('gbk', 'ignore')
        return doc


        # try:

        # except Exception as ex:
        #     print(sys.stderr, 'ok request public_ex: ', ex)
        #     return None

            



    def trades(self,symbol='btc_usdt',since=0):
        '''
            return (tid,symbol,date,price,amount,type)
            max_len 60
        '''
        data = self.okcoinSpot.trades(symbol,since)
        lst = [da['tid'] for da in data]
        return [(da['tid'],symbol,da['date'],da['price'],da['amount'],da['type']) for da in data[::-1]]

        # try:
            
        # except Exception as e:
        #     # raise e
        #     print('ok_api_ trades' ,e)
        #     return []

    def kline(self,symbol,type,size=500):
        '''
            symbol
            type
            size
            since

            https://www.okb.com/api/v1/kline.do
        '''
        path = 'kline.do?'
        params = "symbol=%s&type=%s&size=%s" %(symbol,type,size)
        obj = self.__api_public_call(path, params)

        return obj

        # try:

        # except Exception as ex:
        #     print(sys.stderr, 'ok %s exception ,'%path,ex)
        #     return None

    def depth(self,symbol = ''):
        data = self.okcoinSpot.depth(symbol)
        data =[data['asks'][::-1],data['bids']]
        return data


    def balance(self):
        data = self.okcoinSpot.userinfo()



        data_free = data['info']['funds']['free']
        data_freezed = data['info']['funds']['freezed']
        data = filter( lambda x:data_free[x] != '0',data_free)
        data_free = { da:data_free[da]     for da in data_free if data_free[da] != '0'}
        data_freezed = { da:data_freezed[da] for da in data_freezed if data_freezed[da] != '0'}
        return data_free,data_freezed

        
    def order(self,symbol,price,amount,type):
        data = self.okcoinSpot.trade(symbol,price,amount,type)
        return data

    def deal_order_data(self,data,lst):
        resl = []
        for da in data:
            d = {}
            for l in lst:
                if l == 'order_id':
                    d['id'] = da[l]
                else:
                    d[l] = da[l]
            resl.append(d)
        return resl

    def getOrder(self,id,symbol=None):
        '''
            {'orders': [{'amount': 1,
                         'avg_price': 0,
                         'create_date': 1536112711000,
                         'deal_amount': 0,
                         'order_id': 864345207,
                         'orders_id': 864345207,
                         'price': 10.0,
                         'status': 0,
                         'symbol': 'eos_usdt',
                         'type': 'sell'}],
             'result': True}
        '''
        data = self.okcoinSpot.orderinfo(symbol,id)



        data = data['orders']
        data = self.deal_order_data(data,['amount','price','deal_amount','avg_price','create_date','order_id','type'])
        [da.update({'deal_money':da['deal_amount']*da['avg_price']}) for da in data]
        if len(data) > 1:
            raise ValueError(data)
        return data[0]






    def unfinished_orders_list(self,symbol):
        '''{'currency_page': 1,
             'orders': [{'amount': 1,
                         'avg_price': 0,
                         'create_date': 1536112711000,
                         'deal_amount': 0,
                         'order_id': 864345207,
                         'orders_id': 864345207,
                         'price': 10.0,
                         'status': 0,
                         'symbol': 'eos_usdt',
                         'type': 'sell'}],
             'page_length': 200,
             'result': True,
             'total': 1}



             [{'amount': 1,
               'avg_price': 0,
               'create_date': 1536112711000,
               'deal_amount': 0,
               'deal_money': 0,
               'order_id': 864345207,
               'price': 10.0,
               'type': 'sell'}]
        '''


        data = self.okcoinSpot.orderHistory(symbol)
        if not data.get('orders'):
            return data
        data = data['orders']
        data = self.deal_order_data(data,['amount','price','deal_amount','avg_price','create_date','order_id','type'])
        [da.update({'deal_money':da['deal_amount']*da['avg_price']}) for da in data]
        return data


    def cancelOrder(self,id,symbol):
        '''
            {'orders': [{'amount': 1,
                         'avg_price': 0,
                         'create_date': 1536112711000,
                         'deal_amount': 0,
                         'order_id': 864345207,
                         'orders_id': 864345207,
                         'price': 10.0,
                         'status': 0,
                         'symbol': 'eos_usdt',
                         'type': 'sell'}],
             'result': True}
        '''
        data = self.okcoinSpot.ordersinfo(symbol,id)
        if data.get('result') == True:
            return True
        print(data)
        return False
Beispiel #9
0
# print (okcoinSpot.trades(coin))

#print (u' Spot user info ')
#print (okcoinSpot.userinfo())

#print (u' Spot trade ')
#print (okcoinSpot.trade(coin,'buy','0.1','0.2'))

#print (u' 现货批量下单 ')
#print (okcoinSpot.batchTrade(coin,'buy','[{price:0.1,amount:0.2},{price:0.1,amount:0.2}]'))

#print (u' 现货取消订单 ')
#print (okcoinSpot.cancelOrder(coin,'18243073'))

#print (u' 现货订单信息查询 ')
print(okcoinSpot.orderinfo(coin, '-1'))

# print (u' 现货批量订单信息查询 ')
# print (okcoinSpot.ordersinfo(coin,'18243800,18243801,18243644','0'))

print(u' 现货历史订单信息查询 ')
print(okcoinSpot.orderHistory(coin, '1', '1', '20'))

#print (u' 期货行情信息')
#print (okcoinFuture.future_ticker(coin,'this_week'))

#print (u' 期货市场深度信息')
#print (okcoinFuture.future_depth('btc_usd','this_week','6'))

#print (u'期货交易记录信息')
#print (okcoinFuture.future_trades(coin,'this_week'))