├── ios.wav ├── README.md ├── .gitignore ├── alert.py ├── coin_list.cfg ├── toolkit.py ├── auto_deal.py ├── store_amount.py ├── stare_change.py ├── jubi_wechat.py ├── jubi_access.py └── basic_usage.py /ios.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rockyzsu/jubi_api/master/ios.wav -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jubi_api 2 | 聚币网API调用教程 3 | jubi.com 4 | 可以获取实时行情,历史行情,历史k线和成交量。 5 | 6 | 文件说明 7 | 8 | jubi_wechat.py: 实时行情推送到微信 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .DS_Store 3 | data.cfg 4 | /.idea 5 | *.xml 6 | *.html 7 | /private 8 | *.log 9 | *.pkl 10 | *.csv 11 | *.xls 12 | *.json -------------------------------------------------------------------------------- /alert.py: -------------------------------------------------------------------------------- 1 | #-*-coding=utf-8-*- 2 | # play sound in python 3 | import os, subprocess 4 | def play(): 5 | media_path = "ios.wav" 6 | p = subprocess.Popen(['mplayer', media_path], stdout=subprocess.PIPE) 7 | p.communicate() 8 | p.wait() -------------------------------------------------------------------------------- /coin_list.cfg: -------------------------------------------------------------------------------- 1 | {"ppc": "\u70b9\u70b9\u5e01", "doge": "\u72d7\u72d7\u5e01", "pgc": "\u4e50\u901a\u5e01", "lsk": "LISK", "zet": "\u6cfd\u5854\u5e01", "ugt": "UG Token", "skt": "\u9ca8\u4e4b\u4fe1", "vtc": "\u7eff\u5e01", "xpm": "\u8d28\u6570\u5e01", "xas": "\u963f\u5e0c\u6bd4", "lkc": "\u5e78\u8fd0\u5e01", "gooc": "\u8c37\u58f3\u5e01", "eac": "\u5730\u7403\u5e01", "mcc": "\u884c\u4e91\u5e01", "tfc": "\u4f20\u9001\u5e01", "game": "\u6e38\u620f\u70b9", "mryc": "\u7f8e\u4eba\u9c7c\u5e01", "rss": "\u7ea2\u8d1d\u58f3", "ytc": "\u4e00\u53f7\u5e01", "ifc": "\u65e0\u9650\u5e01", "mtc": "\u7334\u5b9d\u5e01", "ktc": "\u80af\u7279\u5e01", "qec": "\u4f01\u9e45\u5e01", "bts": "\u6bd4\u7279\u80a1", "zcc": "\u62db\u8d22\u5e01", "rio": "\u91cc\u7ea6\u5e01", "xsgs": "\u96ea\u5c71\u53e4\u6811", "btc": "\u6bd4\u7279\u5e01", "ans": "\u5c0f\u8681\u80a1", "hlb": "\u6d3b\u529b\u5e01", "eos": "EOS", "ico": "ICO\u5e01", "blk": "\u9ed1\u5e01", "xrp": "\u745e\u6ce2\u5e01", "peb": "\u666e\u94f6\u5e01", "tic": "\u949b\u5e01", "max": "\u6700\u5927\u5e01", "fz": "\u51b0\u6cb3\u5e01", "vrc": "\u7ef4\u7406\u5e01", "met": "\u7f8e\u901a\u5e01", "plc": "\u4fdd\u7f57\u5e01", "nxt": "\u672a\u6765\u5e01", "wdc": "\u4e16\u754c\u5e01", "dnc": "\u6697\u7f51\u5e01", "ltc": "\u83b1\u7279\u5e01", "etc": "\u4ee5\u592a\u7ecf\u5178", "jbc": "\u805a\u5b9d\u5e01", "eth": "\u4ee5\u592a\u574a"} -------------------------------------------------------------------------------- /toolkit.py: -------------------------------------------------------------------------------- 1 | # -*-coding=utf-8-*- 2 | #常用的工具集合 3 | __author__ = 'Rocky' 4 | ''' 5 | http://30daydo.com 6 | Contact: weigesysu@qq.com 7 | ''' 8 | import codecs 9 | 10 | class Toolkit(): 11 | @staticmethod 12 | def save2file( filename, content): 13 | # 保存为文件 14 | filename = filename + ".txt" 15 | f = open(filename, 'a') 16 | f.write(content) 17 | f.close() 18 | 19 | @staticmethod 20 | def save2filecn( filename, content): 21 | # 保存为文件 22 | filename = filename + ".txt" 23 | f = codecs.open(filename, 'a',encoding='utf-8') 24 | f.write(content) 25 | f.close() 26 | 27 | @staticmethod 28 | def getUserData(cfg_file): 29 | f=open(cfg_file,'r') 30 | account={} 31 | for i in f.readlines(): 32 | ctype,passwd=i.split('=') 33 | #print ctype 34 | #print passwd 35 | account[ctype.strip()]=passwd.strip() 36 | 37 | return account 38 | 39 | @staticmethod 40 | def read_stock(cfg_file): 41 | result=[] 42 | try: 43 | 44 | f=open(cfg_file,'r').readlines() 45 | for i in f: 46 | i=i.strip() 47 | if len(i)!=6: 48 | continue 49 | result.append(i) 50 | #print i 51 | except Exception,e: 52 | print e 53 | return None 54 | return result -------------------------------------------------------------------------------- /auto_deal.py: -------------------------------------------------------------------------------- 1 | #-*-coding=utf-8-*- 2 | #聚币网自动下单 量化交易 3 | 4 | import random,json 5 | import hashlib 6 | import hmac,time 7 | from email import Utils 8 | import threading 9 | import requests,datetime,itchat 10 | import urllib,urllib2 11 | from toolkit import Toolkit 12 | import Queue 13 | from basic_usage import api_demo 14 | import pandas as pd 15 | import numpy as np 16 | 17 | obj=api_demo() 18 | q=Queue.Queue() 19 | data_dict={} 20 | def price_strategy(coin,price,amount): 21 | ''' 22 | 当价格满足要求的时候就下单 23 | :return: 24 | ''' 25 | 26 | ''' 27 | t_id=obj.Trade_add(coin,price,amount) 28 | print t_id 29 | data_dict={t_id:[coin,price,amount]} 30 | ''' 31 | 32 | s=obj.Trade_list('zet') 33 | ''' 34 | for i in s: 35 | #print k,v 36 | print i 37 | ''' 38 | 39 | 40 | #df=pd.DataFrame(s,index_col='datetime') 41 | #df=pd.DataFrame(s,index=[u'datetime']) 42 | df=pd.DataFrame(s) 43 | #print df 44 | 45 | #df['datetime']=df['datetime'].map(lambda x:datetime.datetime.strptime(x,'%Y-%m-%d %H:%M:%S')) 46 | #上面这两种方法都可以 47 | df['datetime'] = pd.to_datetime(df['datetime']) 48 | 49 | df.set_index('datetime',inplace=True,drop=True) 50 | 51 | #print df.dtypes 52 | #print df.info() 53 | #print df 54 | df['status']=df['id'].map(lambda x:obj.Trade_view('zet',x)['status']) 55 | 56 | print df 57 | new_df = df[df['status']=='open'] 58 | 59 | #df.to_csv('') 60 | print new_df 61 | 62 | 63 | 64 | 65 | def main(): 66 | 67 | price_strategy('zet',0.0112,1000) 68 | #price_strategy('zet',0.011,1000) 69 | 70 | while q.empty() is False: 71 | print q.get() 72 | 73 | 74 | 75 | if __name__=='__main__': 76 | main() 77 | 78 | -------------------------------------------------------------------------------- /store_amount.py: -------------------------------------------------------------------------------- 1 | # -*-coding=utf-8-*- 2 | import datetime 3 | import time 4 | import requests 5 | import pandas as pd 6 | import threading 7 | __author__ = 'Rocky' 8 | ''' 9 | http://30daydo.com 10 | Contact: weigesysu@qq.com 11 | 获取聚币网的成交量与成交价的数据,保存到本地,官方只为用户保存100条记录,没有提供完整的记录 12 | ''' 13 | 14 | 15 | class Storage(): 16 | 17 | def __init__(self): 18 | self.coin_list=['IFC','DOGE','EAC','DNC','MET','ZET','SKT','YTC','PLC','LKC', 19 | 'JBC','MRYC','GOOC','QEC','PEB','XRP','NXT','WDC','MAX','ZCC', 20 | 'HLB','RSS','PGC','RIO','XAS','TFC','BLK','FZ','ANS','XPM','VTC', 21 | 'KTC','VRC','XSGS','LSK','PPC','ETC','GAME','LTC','ETH','BTC'] 22 | self.url='http://www.jubi.com/api/v1/orders/' 23 | self.today=datetime.datetime.now().strftime('%Y-%m-%d') 24 | 25 | 26 | def getOrders(self,coin): 27 | try: 28 | js=requests.get(self.url,params={'coin':coin}).json() 29 | except Exception,e: 30 | print e 31 | print "can't get data, will retry" 32 | time.sleep(30) 33 | return 34 | #print js 35 | ''' 36 | u'date': u'1496936989', 37 | u'tid': u'121264', 38 | u'price': 0.1631, 39 | u'type': u'sell', 40 | u'amount': 8043.1328 41 | ''' 42 | ''' 43 | frame=[] 44 | for i in js: 45 | 46 | df=pd.DataFrame(i,index=[1]) 47 | df.set_index('date',inplace=True) 48 | #print df 49 | frame.append(df) 50 | #print i 51 | #print type(i) 52 | new_df=pd.concat(frame) 53 | print new_df.dtypes 54 | print new_df.info 55 | new_df.sort_values('date',inplace=True,ascending=True) 56 | #print new_df.groupby('date') 57 | print new_df 58 | ''' 59 | 60 | df=pd.DataFrame(js,columns=['date','tid','price','type','amount']) 61 | if len(df[df['amount']>50000]) > 0: 62 | print "Big deal buy or sell" 63 | #print df 64 | df.set_index('tid',inplace=True) 65 | print df 66 | #df.to_excel('test.xls') 67 | time1=df['date'].values[0] 68 | df['date']=df['date'].map(lambda x:datetime.datetime.fromtimestamp(long(x) )) 69 | print df 70 | 71 | filename=self.today+'_'+coin+'.csv' 72 | df.to_csv(filename,mode='a',header=False) 73 | 74 | def loops(self,coin): 75 | while 1: 76 | self.getOrders(coin) 77 | time.sleep(10) 78 | 79 | def multi_thread(self): 80 | t1=threading.Thread(target=self.loops,args=('zet',)) 81 | 82 | def testcase(self): 83 | #self.getOrders('zet') 84 | self.loops('zet') 85 | if __name__=='__main__': 86 | obj=Storage() 87 | obj.testcase() -------------------------------------------------------------------------------- /stare_change.py: -------------------------------------------------------------------------------- 1 | # -*-coding=utf-8-*- 2 | __author__ = 'Rocky' 3 | ''' 4 | http://30daydo.com 5 | Contact: weigesysu@qq.com 6 | ''' 7 | #关注成交量暴涨的coin 8 | import requests,time,datetime,threading 9 | import pandas as pd 10 | from jubi_wechat import Jubi_web 11 | from alert import play 12 | class CoinVol(): 13 | def __init__(self,wechat=False): 14 | 15 | 16 | self.wechat=wechat 17 | if self.wechat: 18 | self.obj_wc=Jubi_web() 19 | 20 | self.host='https://www.jubi.com' 21 | self.coin_list=['IFC','DOGE','EAC','DNC','MET','ZET','SKT','YTC','PLC','LKC', 22 | 'JBC','MRYC','GOOC','QEC','PEB','XRP','NXT','WDC','MAX','ZCC', 23 | 'HLB','RSS','PGC','RIO','XAS','TFC','BLK','FZ','ANS','XPM','VTC', 24 | 'KTC','VRC','XSGS','LSK','PPC','ETC','GAME','LTC','ETH','BTC'] 25 | self.coin_name={'zet':u'泽塔币', 26 | 'doge':u'狗狗币', 27 | 'eac':u'地球币', 28 | 'dnc':u'暗网币', 29 | 'rio':u'里约币', 30 | 'blk':u'黑币', 31 | 'ifc':u'无限币', 32 | 'met':u'美通币', 33 | 'gooc':u'谷壳币', 34 | 'jbc':u'聚宝币', 35 | 'pgc':u'乐通币', 36 | 'lsk':u'LISK', 37 | 'tfc':u'传送币', 38 | 'xpm':u'质数币', 39 | 'nxt':u'未来币', 40 | 'ppc':u'点点币', 41 | 'ktc':u'肯特币', 42 | 'mtc':u'猴宝币', 43 | 'skt':u'鲨之信', 44 | 'btc':u'比特币', 45 | 'peb':u'普银币', 46 | 'ltc':u'莱特币', 47 | 'xsgs':u'雪山古树', 48 | 'eth':u'以太坊', 49 | 'vtc':u'绿币', 50 | 'bts':u'比特股', 51 | 'hlb':u'活力币', 52 | 'zcc':u'招财币', 53 | 'etc':u'以太经典', 54 | 'qec':u'企鹅币', 55 | 'fz':u'冰河币', 56 | 'plc':u'保罗币', 57 | 'max':u'最大币', 58 | 'ytc':u'一号币', 59 | 'xrp':u'瑞波币', 60 | 'lkc':u'幸运币', 61 | 'wdc':u'世界币', 62 | 'vrc':u'维理币', 63 | 'rss':u'红贝壳', 64 | 'ans':u'小蚁股', 65 | 'xas':u'阿希比', 66 | 'game':u'游戏点', 67 | 'mryc':u'美人鱼币', 68 | } 69 | 70 | 71 | #出现买单占比65%以上和成交量放大的,就警报 72 | def vol_detect(self,coin,setup_timeout=60): 73 | 74 | url=self.host+'/api/v1/orders/' 75 | data={'coin':coin} 76 | print "in %s" %coin 77 | while 1: 78 | price_max=open('args.txt','r') 79 | price_min=open() 80 | try: 81 | js=requests.get(url,params=data).json() 82 | except Exception,e: 83 | time.sleep(10) 84 | continue 85 | #print js 86 | #rint type(js) 87 | #将字典列表转为Dataframe 88 | df=pd.DataFrame(js) 89 | df['date']=df['date'].map(lambda x:datetime.datetime.fromtimestamp(long(x) )) 90 | 91 | #print df 92 | price_min=df['price'].min() 93 | price_max=df['price'].max() 94 | print 'Coin : %s' %self.coin_name[coin] 95 | print 'recent max: ',price_max 96 | print 'recent min: ',price_min 97 | #print df.info() 98 | #print df.dtypes 99 | buy_df=df[df['type']=='buy'] 100 | #print buy_df 101 | buy_count= len(buy_df) 102 | total= len(df) 103 | buy_ratio=buy_count*1.00/total*100.00 104 | 105 | if price_max>p_max: 106 | print datetime.datetime.now().strftime('%H:%M:%S') 107 | print 'Coin : %s' %self.coin_name[coin], 108 | print "MAX than ",price_max 109 | #play() 110 | if price_min70.0: 118 | print datetime.datetime.now().strftime('%H:%M:%S') 119 | print "Coin : %s " %self.coin_name[coin], 120 | print "buy more than 60 percent in the pass 100 order: %s\n" %buy_ratio 121 | txt="buy more than 60 percent in the pass 100 order: %s\n" %buy_ratio 122 | if self.wechat: 123 | self.obj_wc.send_wechat(coin,txt) 124 | else: 125 | play() 126 | if float(df['amount'].values[0]) >1000000: 127 | print datetime.datetime.now().strftime('%H:%M:%S') 128 | print 'Coin : %s' %self.coin_name[coin], 129 | print " Big deal more than 10w" 130 | if self.wechat: 131 | 132 | self.obj_wc.send_wechat(coin," Big deal more than 10w") 133 | else: 134 | play() 135 | 136 | 137 | time.sleep(setup_timeout) 138 | 139 | 140 | def multi_thread(self,coin_list): 141 | thread_list=[] 142 | #print len(self.coin_name) 143 | ''' 144 | for i in coin_list: 145 | print i," ", 146 | print self.coin_name[i] 147 | #print i 148 | t=threading.Thread(target=self.vol_detect,args=(i,0.16,0.17)) 149 | thread_list.append(t) 150 | ''' 151 | 152 | 153 | t1=threading.Thread(target=self.vol_detect,args=(coin_list[0],0.19,0.22)) 154 | t1.start() 155 | t1.join() 156 | #t2=threading.Thread(target=self.vol_detect,args=(coin_list[1],0.009,0.012)) 157 | #thread_list.append(t1) 158 | #thread_list.append(t2) 159 | #for j in thread_list: 160 | #j.start() 161 | #j.join() 162 | #for k in thread_list: 163 | #k.join() 164 | 165 | 166 | 167 | def testcase(self): 168 | coin_list=['zet'] 169 | self.multi_thread(coin_list) 170 | #self.vol_detect('zet',0.15,0.195) 171 | if __name__=='__main__': 172 | obj=CoinVol() 173 | obj.testcase() 174 | 175 | -------------------------------------------------------------------------------- /jubi_wechat.py: -------------------------------------------------------------------------------- 1 | # -*-coding=utf-8-*- 2 | __author__ = 'Rocky' 3 | ''' 4 | http://30daydo.com 5 | Contact: weigesysu@qq.com 6 | ''' 7 | import random 8 | import hashlib 9 | import hmac,time 10 | import smtplib 11 | from email.mime.text import MIMEText 12 | from email import Utils 13 | import threading 14 | import requests,datetime,itchat 15 | 16 | from toolkit import Toolkit 17 | 18 | 19 | class Jubi_web(): 20 | def __init__(self, send='wechat'): 21 | cfg = Toolkit.getUserData('data.cfg') 22 | self.public_key = cfg['public_key'] 23 | self.private_key = cfg['private_key'] 24 | self.send=send 25 | from_mail = cfg['from_mail'] 26 | password = cfg['password'] 27 | to_mail = cfg['to_mail'] 28 | smtp_server = 'smtp.qq.com' 29 | 30 | self.server = smtp_server 31 | self.username = from_mail.split("@")[0] 32 | self.from_mail = from_mail 33 | self.password = password 34 | self.to_mail = to_mail 35 | self.coin_list=['IFC','DOGE','EAC','DNC','MET','ZET','SKT','YTC','PLC','LKC', 36 | 'JBC','MRYC','GOOC','QEC','PEB','XRP','NXT','WDC','MAX','ZCC', 37 | 'HLB','RSS','PGC','RIO','XAS','TFC','BLK','FZ','ANS','XPM','VTC', 38 | 'KTC','VRC','XSGS','LSK','PPC','ETC','GAME','LTC','ETH','BTC'] 39 | # 初始化邮箱设置读取需要股票信息 40 | # 这样子只登陆一次 41 | if self.send == 'msn': 42 | 43 | try: 44 | self.smtp = smtplib.SMTP_SSL(port=465) 45 | self.smtp.connect(self.server) 46 | self.smtp.login(self.username, self.password) 47 | except smtplib.SMTPException, e: 48 | print e 49 | return 0 50 | 51 | if send=='wechat': 52 | self.w_name=u'wwwei' 53 | #self.w_name1=u'wwwei' 54 | itchat.auto_login(hotReload=True) 55 | account=itchat.get_friends(self.w_name) 56 | for i in account: 57 | if i[u'PYQuanPin']==self.w_name: 58 | self.toName= i['UserName'] 59 | #print self.toName 60 | 61 | def send_wechat(self,name,content): 62 | w_content=name+' '+content 63 | itchat.send(w_content,toUserName=self.toName) 64 | time.sleep(1) 65 | itchat.send(w_content,toUserName='filehelper') 66 | 67 | 68 | def send_text(self, name, content): 69 | 70 | subject = '%s' % name 71 | self.msg = MIMEText(content, 'plain', 'utf-8') 72 | self.msg['to'] = self.to_mail 73 | self.msg['from'] = self.from_mail 74 | self.msg['Subject'] = subject 75 | self.msg['Date'] = Utils.formatdate(localtime=1) 76 | try: 77 | self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string()) 78 | self.smtp.quit() 79 | print "sent" 80 | except smtplib.SMTPException, e: 81 | print e 82 | return 0 83 | 84 | def warming(self, coin, up_price, down_price): 85 | url = 'https://www.jubi.com/api/v1/ticker/' 86 | while 1: 87 | time.sleep(5) 88 | try: 89 | data = requests.post(url, data={'coin': coin}).json() 90 | except Exception,e: 91 | print e 92 | print "time out. Retry" 93 | time.sleep(15) 94 | continue 95 | 96 | current = float(data['last']) 97 | if current >= up_price: 98 | print "Up to ", up_price 99 | print "current price ",current 100 | 101 | if self.send=='msn': 102 | self.send_text(coin,str(current)) 103 | if self.send=='wechat': 104 | self.send_wechat(coin,str(current)) 105 | 106 | time.sleep(1200) 107 | if current <= down_price: 108 | print "Down to ", down_price 109 | print "current price ",current 110 | if self.send=='msn': 111 | self.send_text(coin,str(current)) 112 | if self.send=='wechat': 113 | self.send_wechat(coin,str(current)) 114 | time.sleep(1200) 115 | #上面的内容尽量不用修改。 116 | 117 | 118 | def getContent(self): 119 | url = 'https://www.jubi.com/api/v1/trade_list' 120 | params_data = {'key': 'x', 'signature': 'x'} 121 | s = requests.get(url=url, params=params_data) 122 | 123 | def getHash(self, s): 124 | m = hashlib.md5() 125 | m.update(s) 126 | return m.hexdigest() 127 | 128 | def sha_convert(self, s): 129 | return hashlib.sha256(self.getHash(s)).hexdigest() 130 | 131 | def get_nonce(self): 132 | lens = 12 133 | return ''.join([str(random.randint(0, 9)) for i in range(lens)]) 134 | 135 | def get_signiture(self): 136 | url = 'https://www.jubi.com/api/v1/ticker/' 137 | coin = 'zet' 138 | nonce = self.get_nonce() 139 | 140 | # sha=self.sha_convert(private_key) 141 | md5 = self.getHash(self.private_key) 142 | message = 'nonce=' + nonce + '&' + 'key=' + self.public_key 143 | # print message 144 | signature = hmac.new(md5, message, digestmod=hashlib.sha256).digest() 145 | # print signature 146 | 147 | # req=requests.post(url,data={'signature':signature,'key':public_key,'nonce':nonce,'coin':'zet'}) 148 | req = requests.post(url, data={'coin': coin}) 149 | print req.status_code 150 | print req.text 151 | 152 | def real_time_ticker(self, coin): 153 | url = 'https://www.jubi.com/api/v1/ticker/' 154 | try: 155 | data = requests.post(url, data={'coin': coin}).json() 156 | #print data 157 | except Exception ,e: 158 | print e 159 | return data 160 | 161 | 162 | 163 | def real_time_depth(self, coin): 164 | url = 'https://www.jubi.com/api/v1/depth/' 165 | data = requests.post(url, data={'coin': coin}).json() 166 | print data 167 | data_bids = data['bids'] 168 | data_asks = data['asks'] 169 | print "bids" 170 | for i in data_bids: 171 | print i[0], 172 | print ' ', 173 | print i[1] 174 | print "asks" 175 | for j in data_asks: 176 | print j[0], 177 | print ' ', 178 | print j[1] 179 | 180 | def list_all_price(self): 181 | for i in self.coin_list: 182 | print i, 183 | print " price: ", 184 | p=self.real_time_ticker(i.lower()) 185 | if p is not None: 186 | print p[u'last'] 187 | 188 | def getOrder(self,coin): 189 | url='https://www.jubi.com/api/v1/orders/' 190 | try: 191 | req=requests.get(url,params={'coin':coin}) 192 | except Exception,e: 193 | print e 194 | 195 | data=req.json() 196 | return data 197 | # recent 100 trade turn over 198 | def turnover(self,coin): 199 | i=coin.lower() 200 | coins=Toolkit.getUserData('coins.csv') 201 | total=long(coins[i]) 202 | p=self.getOrder(i) 203 | print p 204 | amount=0.00 205 | for j in p: 206 | t= j[u'amount'] 207 | amount=float(t)+amount 208 | #current=float(self.real_time_ticker(i)[u'last']) 209 | turn_over=amount*1.00/total*100 210 | 211 | print turn_over 212 | 213 | def multi_thread(self,coin_list,price_list): 214 | thread_num=len(coin_list) 215 | thread_list=[] 216 | for i in range(thread_num): 217 | t=threading.Thread(target=self.warming, args=(coin_list[i],price_list[i][0],price_list[i][1]),) 218 | thread_list.append(t) 219 | for j in thread_list: 220 | j.start() 221 | for k in thread_list: 222 | k.join() 223 | 224 | if __name__ == '__main__': 225 | 226 | obj = Jubi_web(send='wechat') 227 | 228 | # print obj.get_signiture() 229 | #print obj.real_time_ticker('zet') 230 | # obj.real_time_depth('zet') 231 | #obj.warming('zet',0.23,0.17) 232 | #obj.list_all_price() 233 | #obj.turnover('doge') 234 | #print obj.getOrder('zet') 235 | 236 | coin_list=['zet','doge'] 237 | price_list=[[0.2,0.13],[0.03,0.021]] 238 | #obj.warming('zet',0.24,0.16) 239 | obj.multi_thread(coin_list,price_list) 240 | 241 | -------------------------------------------------------------------------------- /jubi_access.py: -------------------------------------------------------------------------------- 1 | # -*-coding=utf-8-*- 2 | import base64 3 | 4 | __author__ = 'Rocky' 5 | ''' 6 | http://30daydo.com 7 | Contact: weigesysu@qq.com 8 | ''' 9 | import random,json 10 | import hashlib 11 | import hmac,time 12 | import smtplib 13 | from email.mime.text import MIMEText 14 | from email import Utils 15 | import threading 16 | import requests,datetime,itchat 17 | import urllib,urllib2 18 | from toolkit import Toolkit 19 | #from Crypto import HMAC, SHA256 20 | from itertools import permutations 21 | class Jubi_access(): 22 | def __init__(self): 23 | cfg = Toolkit.getUserData('data.cfg') 24 | self.public_key = cfg['public_key'] 25 | self.private_key = cfg['private_key'] 26 | self.host='https://www.jubi.com' 27 | self.coin_list=['IFC','DOGE','EAC','DNC','MET','ZET','SKT','YTC','PLC','LKC', 28 | 'JBC','MRYC','GOOC','QEC','PEB','XRP','NXT','WDC','MAX','ZCC', 29 | 'HLB','RSS','PGC','RIO','XAS','TFC','BLK','FZ','ANS','XPM','VTC', 30 | 'KTC','VRC','XSGS','LSK','PPC','ETC','GAME','LTC','ETH','BTC'] 31 | 32 | 33 | 34 | def getContent(self): 35 | url = 'https://www.jubi.com/api/v1/trade_list' 36 | params_data = {'key': 'x', 'signature': 'x'} 37 | s = requests.get(url=url, params=params_data) 38 | 39 | def getHash(self, s): 40 | m = hashlib.md5() 41 | m.update(s) 42 | return m.hexdigest() 43 | 44 | def sha_convert(self, s): 45 | return hashlib.sha256(self.getHash(s)).hexdigest() 46 | 47 | def get_nonce(self): 48 | lens = 12 49 | return ''.join([str(random.randint(0, 9)) for i in range(lens)]) 50 | 51 | def get_nonce_time(self): 52 | lens = 12 53 | curr_stamp = time.time()*100 54 | nonece=long(curr_stamp) 55 | return nonece 56 | 57 | def get_signiture(self,): 58 | 59 | nonce_value=self.get_nonce_time() 60 | key_value=self.public_key 61 | private_key=self.private_key 62 | s='nonce='+str(nonce_value)+'&'+'key='+key_value 63 | print s 64 | #signature是签名,是将amount price type nonce key等参数通过'&'字符连接起来通过md5(私钥)为key进行sha256算法加密得到的值. 65 | md5=self.getHash(private_key) 66 | signature =hmac.new(md5,s,digestmod=hashlib.sha256).digest() 67 | sig=self.toHex(signature) 68 | 69 | md5 = self.getHash(self.private_key) 70 | message = 'nonce=' + nonce + '&' + 'key=' + self.public_key 71 | # print message 72 | signature = hmac.new(md5, message, digestmod=hashlib.sha256).digest() 73 | # print signature 74 | 75 | # req=requests.post(url,data={'signature':signature,'key':public_key,'nonce':nonce,'coin':'zet'}) 76 | req = requests.post(url, data={'coin': coin}) 77 | print req.status_code 78 | print req.text 79 | 80 | 81 | def getAccount(self): 82 | url='https://www.jubi.com/api/v1/balance/' 83 | nonce_value=self.get_nonce_time() 84 | print nonce_value 85 | key_value=self.public_key 86 | private_key=self.private_key 87 | s='nonce='+str(nonce_value)+'&'+'key='+key_value 88 | s='key='+key_value+'&'+'nonce='+str(nonce_value) 89 | print s 90 | #signature是签名,是将amount price type nonce key等参数通过'&'字符连接起来通过md5(私钥)为key进行sha256算法加密得到的值. 91 | md5=self.getHash(private_key) 92 | signature =hmac.new(md5,s,digestmod=hashlib.sha256).digest() 93 | sig=self.toHex(signature) 94 | data_wrap={'nonce':nonce_value,'key':key_value,'signature':sig} 95 | ''' 96 | data_en=urllib.urlencode(data_wrap) 97 | req=urllib2.Request(url,data=data_en) 98 | resp=urllib2.urlopen(req).read() 99 | print resp 100 | ''' 101 | 102 | js=requests.post(url,data=data_wrap).json() 103 | print js 104 | 105 | 106 | def toHex(self,str): 107 | lst = [] 108 | for ch in str: 109 | hv = hex(ord(ch)).replace('0x', '') 110 | if len(hv) == 1: 111 | hv = '0' + hv 112 | lst.append(hv) 113 | return reduce(lambda x, y: x + y, lst) 114 | 115 | def hmac_sha256(self,key, msg): 116 | hash_obj = HMAC.new(key=key, msg=msg, digestmod=SHA256) 117 | return hash_obj.hexdigest() 118 | 119 | def order_check(self): 120 | url=self.host+'/api/v1/trade_list/' 121 | print url 122 | coin='zet' 123 | types='all' 124 | #since='2017-5-10 13:29:39' 125 | since=0 126 | nonce=self.get_nonce_time() 127 | key_value=self.public_key 128 | private_key=self.private_key 129 | 130 | #s='nonce='+str(nonce)+'&'+'type='+types+'&'+'coin='+coin+'&'+'since='+since+'&'+'key='+key_value 131 | 132 | s='coin='+coin+'&'+'since'+str(since)+'&'+'type='+types+'&'+'nonce='+str(nonce)+'&'+'key='+key_value 133 | print s 134 | md5=self.getHash(private_key) 135 | 136 | msg=bytes(s).encode('utf-8') 137 | key=bytes(md5).encode('utf-8') 138 | sig=hmac.new(md5,s,digestmod=hashlib.sha256).digest() 139 | print sig 140 | sig_encode=self.toHex(sig) 141 | print sig_encode 142 | data_wrap1={'nonce':nonce,'type':types,'coin':coin,'signature':sig_encode,'key':key_value,'since':since} 143 | print data_wrap1 144 | js=requests.post(url,data=data_wrap1).json() 145 | print js 146 | 147 | def order_id(self): 148 | url=self.host+'/api/v1/trade_view/' 149 | print url 150 | coin='zet' 151 | types='open' 152 | since=0 153 | id=10 154 | nonce=self.get_nonce_time() 155 | print nonce 156 | key_value=self.public_key 157 | private_key=self.private_key 158 | s='nonce='+str(nonce)+'&'+'coin='+coin+'&'+'id='+str(id)+'&'+'key='+key_value 159 | print s 160 | md5=self.getHash(private_key) 161 | 162 | msg=bytes(s).encode('utf-8') 163 | key=bytes(md5).encode('utf-8') 164 | sig=hmac.new(md5,s,digestmod=hashlib.sha256).digest() 165 | print sig 166 | sig_encode=self.toHex(sig) 167 | print sig_encode 168 | data_wrap1={'nonce':nonce,'coin':coin,'signature':sig_encode,'key':key_value,'id':id} 169 | print data_wrap1 170 | js=requests.post(url,data=data_wrap1).json() 171 | print js 172 | 173 | def buy(self): 174 | url=self.host+'/api/v1/trade_add/' 175 | 176 | def get_access(self): 177 | url='https://www.jubi.com/api/v1/trade_list/' 178 | nonce_value=self.get_nonce_time() 179 | print nonce_value 180 | key_value=self.public_key 181 | private_key=self.private_key 182 | types='all' 183 | coin='zet' 184 | since_value=0 185 | s='type='+types+'&'+'since='+str(since_value)+'&'+'coin='+coin+'&'+'nonce='+str(nonce_value)+'&'+'key='+key_value 186 | print s 187 | #signature是签名,是将amount price type nonce key等参数通过'&'字符连接起来通过md5(私钥)为key进行sha256算法加密得到的值. 188 | md5=self.getHash(private_key) 189 | signature =hmac.new(md5,s,digestmod=hashlib.sha256).digest() 190 | sig=self.toHex(signature) 191 | data_wrap={'nonce':nonce_value,'key':key_value,'signature':sig,'type':types,'coin':coin,'since':since_value} 192 | 193 | js=requests.post(url,data=data_wrap).json() 194 | print js 195 | 196 | #下单 197 | def TradeOder(self,coin,types,amount,price): 198 | url='https://www.jubi.com/api/v1/trade_add/' 199 | nonce_value=self.get_nonce_time() 200 | #print nonce_value 201 | key_value=self.public_key 202 | private_key=self.private_key 203 | #types='buy' 204 | #coin='zet' 205 | #amount=500 206 | #price=0.1 207 | #s="amount="+str(amount)+"&price="+str(price)+"&type="+types+"&nonce="+str(nonce_value)+"&key="+key_value+"&coin="+coin 208 | #print s 209 | s="nonce="+str(nonce_value)+"&price="+str(price)+"&amount="+str(amount)+"&key="+key_value+"&coin="+coin+"&type="+types 210 | print s 211 | #signature是签名,是将amount price type nonce key等参数通过'&'字符连接起来通过md5(私钥)为key进行sha256算法加密得到的值. 212 | md5=self.getHash(private_key) 213 | signature =hmac.new(md5,s,digestmod=hashlib.sha256).digest() 214 | sig=self.toHex(signature) 215 | #print sig 216 | data_wrap={'signature':sig,'nonce':str(nonce_value),'coin':coin,'key':key_value,'amount':amount,'price':price,'type':types} 217 | print data_wrap 218 | js=requests.post(url,data=data_wrap).json() 219 | print js 220 | 221 | 222 | 223 | def testcase(self): 224 | #self.getAccount() 225 | #self.order_id() 226 | #self.order_check() 227 | #self.get_access() 228 | self.TradeOder('zet','buy','100',0.01) 229 | if __name__ == '__main__': 230 | 231 | obj = Jubi_access() 232 | obj.testcase() 233 | # print obj.get_signiture() 234 | #print obj.real_time_ticker('zet') 235 | # obj.real_time_depth('zet') 236 | #obj.warming('zet',0.23,0.17) 237 | #obj.list_all_price() 238 | #obj.turnover('doge') 239 | #print obj.getOrder('zet') 240 | 241 | 242 | -------------------------------------------------------------------------------- /basic_usage.py: -------------------------------------------------------------------------------- 1 | # -*-coding=utf-8-*- 2 | import multiprocessing 3 | import random 4 | 5 | __author__ = 'Rocky' 6 | ''' 7 | http://30daydo.com 8 | Contact: weigesysu@qq.com 9 | ''' 10 | 11 | import requests 12 | import json 13 | import time 14 | import hmac 15 | import base64 16 | import hashlib 17 | from toolkit import Toolkit 18 | import pandas as pd 19 | from multiprocessing import Pool,Manager 20 | from functools import partial 21 | import threading 22 | import Queue 23 | 24 | class api_demo(): 25 | def __init__(self): 26 | self.host = 'http://www.jubi.com' 27 | 28 | with open('coin_list.cfg') as f: 29 | c_content = f.read() 30 | 31 | self.d_content = json.loads(c_content) 32 | 33 | # x=zip(* d_content) 34 | # print x 35 | #为什么得不到想要的结果? 36 | 37 | self.coin_list = self.d_content.keys() 38 | self.coin_name = self.d_content.values() 39 | 40 | self.private_key = Toolkit.getUserData('data.cfg')['private_key'] 41 | self.public_key = Toolkit.getUserData('data.cfg')['public_key'] 42 | self.md5 = self.getHash(self.private_key) 43 | 44 | 45 | def getHash(self, s): 46 | m = hashlib.md5() 47 | m.update(s) 48 | return m.hexdigest() 49 | 50 | def get_nonce_time(self): 51 | lens = 12 52 | curr_stamp = time.time() * 100 53 | nonece = long(curr_stamp) 54 | return nonece 55 | 56 | def toHex(self, str): 57 | lst = [] 58 | for ch in str: 59 | hv = hex(ord(ch)).replace('0x', '') 60 | if len(hv) == 1: 61 | hv = '0' + hv 62 | lst.append(hv) 63 | return reduce(lambda x, y: x + y, lst) 64 | 65 | def account_balance(self): 66 | ''' 67 | 列举您的帐户信息 68 | Path:/api/v1/balance/ 69 | Request类型:POST 70 | 参数 71 | key - API key 72 | signature - signature 73 | nonce - nonce 74 | 返回JSON dictionary 75 | asset - 折合人民币总余额 76 | cny_balance - 人民币总余额 77 | ltc_balance - 比特币总余额 78 | cny_lock - 人民币冻结余额 79 | ltc_lock - 比特币冻结余额 80 | ............ 81 | nameauth - 实名认证状态 0 未实名 1 等待确认 2 已经认证成功 82 | moflag - 手机绑定状态 0 未绑定 1 绑定 83 | 返回结果示例: 84 | {"uid":8,"nameauth":0,"moflag":0,"doge_balance":4234234,"doge_lock":0,"ltc_balance":32429.6,"ltc_lock":2.4,"xpm_balance":0,"xpm_lock":0,"cny_balance":2344581.519,"cny_lock":868862.481} 85 | 86 | :return: 87 | ''' 88 | 89 | url = self.host + '/api/v1/balance/' 90 | nonce = self.get_nonce_time() 91 | parameters = {'key': self.public_key, 'nonce': str(nonce), 'signature': ''} 92 | post_data = '' 93 | for k, v in parameters.items(): 94 | post_data = post_data + k + '=' + v + '&' 95 | 96 | post_data = post_data.replace('&signature=&', '') 97 | # print post_data 98 | signature = signature = hmac.new(self.md5, post_data, digestmod=hashlib.sha256).digest() 99 | sig = self.toHex(signature) 100 | parameters['signature'] = sig 101 | r = requests.post(url, data=parameters) 102 | s = r.json() 103 | # print s 104 | for k, v in s.items(): 105 | 106 | #print k,v 107 | if v != 0: 108 | print k, v 109 | return s 110 | 111 | def Trade_list(self, coin): 112 | ''' 113 | Trade_list(挂单查询) 114 | 您指定时间后的挂单,可以根据类型查询,比如查看正在挂单和全部挂单 115 | Path:/api/v1/trade_list/ 116 | Request类型:POST 117 | 参数 118 | key - API key 119 | signature - signature 120 | nonce - nonce 121 | since - unix timestamp(utc timezone) default == 0, i.e. 返回所有 122 | coin - 币种简称,例如btc、ltc、xas 123 | type - 挂单类型[open:正在挂单, all:所有挂单] 124 | 125 | 返回JSON dictionary 126 | id - 挂单ID 127 | datetime - date and time 128 | type - "buy" or "sell" 129 | price - price 130 | amount_original - 下单时数量 131 | amount_outstanding - 当前剩余数量 132 | ''' 133 | url = self.host + '/api/v1/trade_list/' 134 | time.sleep(random.random()) 135 | nonce = self.get_nonce_time() 136 | types = 'all' 137 | since = 0 138 | parameters = {'key': self.public_key, 'nonce': str(nonce), 'type': types, 'coin': coin, 'signature': ''} 139 | # print parameters 140 | post_data = '' 141 | for k, v in parameters.items(): 142 | if not isinstance(v, str): 143 | #if type(v) is not types.StringType: 144 | v = str(v) 145 | post_data = post_data + k 146 | post_data = post_data + '=' + v + '&' 147 | 148 | #print 'post-data:\n',post_data 149 | post_data = post_data[:-1] 150 | post_data = post_data.replace('&signature=', '') 151 | #print post_data 152 | 153 | signature = hmac.new(self.md5, post_data, digestmod=hashlib.sha256).digest() 154 | sig = self.toHex(signature) 155 | parameters['signature'] = sig 156 | #print parameters 157 | r = requests.post(url=url, data=parameters) 158 | s = r.json() 159 | #print s 160 | return s 161 | 162 | def Trade_add(self, coin, price, amount): 163 | 164 | ''' 165 | Trade_add(下单) 166 | Path:/api/v1/trade_add/ 167 | Request类型:POST 168 | 参数 169 | key - API key 170 | signature - signature 171 | nonce - nonce 172 | amount - 购买数量 173 | price - 购买价格 174 | type - 买单或者卖单 175 | coin - 币种简称,例如btc、ltc、xas 176 | 返回JSON dictionary 177 | id - 挂单ID 178 | result - true(成功), false(失败) 179 | 返回结果示例: 180 | {"result":true, "id":"11"} 181 | ''' 182 | url = self.host + '/api/v1/trade_add/' 183 | nonce = self.get_nonce_time() 184 | types = 'buy' 185 | # amount=100 186 | # price=0.1 187 | parameters = {'key': self.public_key, 'nonce': str(nonce), 'type': types, 'coin': coin, 'signature': '', 188 | 'amount': amount, 'price': price} 189 | #print parameters 190 | post_data = '' 191 | for k, v in parameters.items(): 192 | if not isinstance(v, str): 193 | #if type(v) is not types.StringType: 194 | v = str(v) 195 | post_data = post_data + k 196 | post_data = post_data + '=' + v + '&' 197 | 198 | #print 'post-data:\n', post_data 199 | post_data = post_data[:-1] 200 | #print post_data 201 | post_data = post_data.replace('signature=&', '') 202 | #print post_data 203 | signature = hmac.new(self.md5, post_data, digestmod=hashlib.sha256).digest() 204 | sig = self.toHex(signature) 205 | parameters['signature'] = sig 206 | #print parameters 207 | r = requests.post(url=url, data=parameters) 208 | s = r.json() 209 | print s 210 | if s['result'] is True: 211 | return s['id'] 212 | #return s 213 | return False 214 | 215 | 216 | def Trade_cancel(self, coin, id_num): 217 | ''' 218 | Trade_cancel(取消订单) 219 | Path:/api/v1/trade_cancel/ 220 | Request类型:POST 221 | 参数 222 | key - API key 223 | signature - signature 224 | nonce - nonce 225 | id - 挂单ID 226 | coin - 币种简称,例如btc、ltc、xas 227 | 返回JSON dictionary 228 | result - true(成功), false(失败) 229 | id - 订单ID 230 | 返回结果示例: 231 | {"result":true, "id":"11"} 232 | ''' 233 | url = self.host + '/api/v1/trade_cancel/' 234 | nonce = self.get_nonce_time() 235 | 236 | parameters = {'nonce': str(nonce), 'coin': coin, 'id': id_num, 'key': self.public_key, 'signature': ''} 237 | post_data = '' 238 | for k, v in parameters.items(): 239 | post_data = post_data + k + '=' + v + '&' 240 | post_data = post_data[:-1] 241 | # print post_data 242 | post_data = post_data.replace('&signature=', '') 243 | signature = hmac.new(self.md5, post_data, digestmod=hashlib.sha256).digest() 244 | sig = self.toHex(signature) 245 | parameters['signature'] = sig 246 | r = requests.post(url=url, data=parameters) 247 | s = r.json() 248 | print s 249 | return s['result'] 250 | 251 | 252 | def Trade_view(self, coin, id_num): 253 | ''' 254 | Trade_view(查询订单信息) 255 | Path:/api/v1/trade_view/ 256 | Request类型:POST 257 | 参数 258 | key - API key 259 | signature - signature 260 | nonce - nonce 261 | id - 挂单ID 262 | coin - 币种简称,例如btc、ltc、xas 263 | 264 | 265 | 266 | 返回JSON dictionary 267 | id - 挂单ID 268 | datetime - 挂单时间(格式:YYYY-mm-dd HH:ii:ss) 269 | type - "buy" or "sell" 270 | price - 挂单价 271 | amount_original - 下单时数量 272 | amount_outstanding - 当前剩余数量 273 | status - 状态:new(新挂单), open(开放交易), cancelled(撤消), closed(完全成交) 274 | avg_price - 成交均价 275 | ''' 276 | url = self.host + '/api/v1/trade_view/' 277 | nonce = self.get_nonce_time() 278 | 279 | parameters = {'nonce': str(nonce), 'coin': coin, 'id': id_num, 'key': self.public_key, 'signature': ''} 280 | post_data = '' 281 | for k, v in parameters.items(): 282 | post_data = post_data + k + '=' + v + '&' 283 | post_data = post_data[:-1] 284 | # print post_data 285 | post_data = post_data.replace('&signature=', '') 286 | signature = hmac.new(self.md5, post_data, digestmod=hashlib.sha256).digest() 287 | sig = self.toHex(signature) 288 | parameters['signature'] = sig 289 | 290 | r = requests.post(url=url, data=parameters) 291 | s = r.json() 292 | 293 | #print s 294 | return s 295 | def Trade_view_m(self, id_num, coin): 296 | ''' 297 | Trade_view(查询订单信息) 298 | Path:/api/v1/trade_view/ 299 | Request类型:POST 300 | 参数 301 | key - API key 302 | signature - signature 303 | nonce - nonce 304 | id - 挂单ID 305 | coin - 币种简称,例如btc、ltc、xas 306 | 307 | 308 | 309 | 返回JSON dictionary 310 | id - 挂单ID 311 | datetime - 挂单时间(格式:YYYY-mm-dd HH:ii:ss) 312 | type - "buy" or "sell" 313 | price - 挂单价 314 | amount_original - 下单时数量 315 | amount_outstanding - 当前剩余数量 316 | status - 状态:new(新挂单), open(开放交易), cancelled(撤消), closed(完全成交) 317 | avg_price - 成交均价 318 | ''' 319 | url = self.host + '/api/v1/trade_view/' 320 | nonce = self.get_nonce_time() 321 | 322 | parameters = {'nonce': str(nonce), 'coin': coin, 'id': id_num, 'key': self.public_key, 'signature': ''} 323 | post_data = '' 324 | for k, v in parameters.items(): 325 | post_data = post_data + k + '=' + v + '&' 326 | post_data = post_data[:-1] 327 | # print post_data 328 | post_data = post_data.replace('&signature=', '') 329 | signature = hmac.new(self.md5, post_data, digestmod=hashlib.sha256).digest() 330 | sig = self.toHex(signature) 331 | parameters['signature'] = sig 332 | 333 | r = requests.post(url=url, data=parameters) 334 | s = r.json() 335 | #print s 336 | return s 337 | 338 | <<<<<<< HEAD 339 | <<<<<<< HEAD 340 | ======= 341 | ======= 342 | 343 | >>>>>>> origin/master 344 | def get_Completed_order(self,coin): 345 | js = self.Trade_list(coin) 346 | df=self.Data_DF(js) 347 | #速度太慢,使用多进程 348 | df['status'] = df['id'].map(lambda x: self.Trade_view(coin, x)['status']) 349 | df = df[df[u'status'] == u'closed'] 350 | self.current_order = df 351 | return self.current_order 352 | 353 | 354 | <<<<<<< HEAD 355 | >>>>>>> 93522ccc454b60ff763ef4866e4376d0a8ecffb9 356 | ======= 357 | 358 | >>>>>>> origin/master 359 | def matrix_trade_list(self, coin,l,q): 360 | result=[] 361 | for i in l: 362 | s=self.Trade_view(coin,i) 363 | if s.has_key('result'): 364 | print "trying again" 365 | time.sleep(5*random.random()) 366 | s=self.Trade_view(coin,i) 367 | if s.has_key('result'): 368 | print "trying again second time" 369 | time.sleep(10*random.random()) 370 | s=self.Trade_view(coin,i) 371 | if s.has_key('result'): 372 | print "trying again third time" 373 | time.sleep(10*random.random()) 374 | s=self.Trade_view(coin,i) 375 | result.append(s) 376 | q.put(result) 377 | 378 | def get_OpenOrder_Thread(self,coin): 379 | 380 | js = self.Trade_list(coin) 381 | df=self.Data_DF(js) 382 | #速度太慢,使用多进程 383 | id_list=df['id'].values 384 | l_id=len(id_list) 385 | thread_num=10 386 | thread_list=[] 387 | q=Queue.Queue() 388 | each_iteration=l_id/thread_num 389 | for i in range(thread_num-1): 390 | print id_list[i*each_iteration:(i+1)*each_iteration] 391 | t=threading.Thread(target=self.matrix_trade_list,args=(coin, id_list[i*each_iteration:(i+1)*each_iteration],q)) 392 | thread_list.append(t) 393 | 394 | if l_id%thread_num!=0: 395 | t=threading.Thread(target=self.matrix_trade_list,args=(coin,id_list[(i+1)*each_iteration:],q)) 396 | thread_list.append(t) 397 | 398 | for i in thread_list: 399 | i.start() 400 | time.sleep(0.5*random.random()) 401 | for i in thread_list: 402 | i.join() 403 | x_List=[] 404 | while not q.empty(): 405 | x= q.get() 406 | x_List.extend(x) 407 | #print result_list 408 | df=self.Data_DF(x_List) 409 | print df 410 | 411 | def get_Recent_Order(self, coin, date='2017-05-01'): 412 | df = self.Trade_list(coin) 413 | return df[df.index >= date] 414 | 415 | def AllTicker(self): 416 | url = self.host + '/api/v1/allticker/' 417 | r = requests.get(url) 418 | s = r.json() 419 | # print s 420 | ''' 421 | for k,v in s.items(): 422 | print self.d_content[k] 423 | for vk,vv in v.items(): 424 | print vk,vv 425 | print '*'*15 426 | ''' 427 | return s 428 | 429 | def Cancel_All(self, coin): 430 | df = self.Data_transform(coin) 431 | res = df['id'].map(lambda x: self.Trade_cancel(coin, x)) 432 | print res 433 | return res 434 | 435 | #获取所有开放的挂单 436 | def get_OpenOrder(self, coin): 437 | js = self.Trade_list(coin) 438 | df=self.Data_DF(js) 439 | #速度太慢,使用多进程 440 | df['status'] = df['id'].map(lambda x: self.Trade_view(coin, x)['status']) 441 | df = df[df[u'status'] == u'open'] 442 | self.current_order = df 443 | return self.current_order 444 | 445 | def Trade_View_Q(self,coin,x,q): 446 | s=self.Trade_view(coin,x) 447 | print s 448 | q.put(s) 449 | 450 | #多进程/线程 获取所有开放的挂单 451 | def get_OpenOrder_MultiCore(self, coin): 452 | js = self.Trade_list(coin) 453 | df=self.Data_DF(js) 454 | #速度太慢,使用多进程 455 | id_list=df['id'].values 456 | print id_list 457 | 458 | #df['status'] = df['id'].map(lambda x: self.Trade_view(coin, x)['status']) 459 | #df = df[df[u'status'] == u'open'] 460 | #self.current_order = df 461 | #return self.current_order 462 | part=partial(self.Trade_view_m,coin='zet') 463 | manager=Manager() 464 | q=manager.Queue() 465 | cpus = multiprocessing.cpu_count() 466 | p=Pool(len(id_list)) 467 | ''' 468 | for i in id_list: 469 | print i 470 | p.apply_async(self.Trade_View_Q,args=(coin,i,q,)) 471 | <<<<<<< HEAD 472 | <<<<<<< HEAD 473 | ======= 474 | 475 | >>>>>>> origin/master 476 | ''' 477 | resultqq=[] 478 | for i in range(len(id_list)): 479 | resultqq[i]=p.map(self.Trade_view_m,id_list[i]) 480 | 481 | p.close() 482 | p.join() 483 | print "Finish Multi-Process" 484 | print resultqq 485 | ''' 486 | result=[] 487 | while not q.empty(): 488 | t=q.get() 489 | print t 490 | result.append(t) 491 | 492 | print result 493 | #df=self.Data_DF(result) 494 | #print df 495 | ''' 496 | 497 | ''' 498 | resultqq=[] 499 | for i in range(len(id_list)): 500 | resultqq[i]=p.map(self.Trade_view_m,id_list[i]) 501 | 502 | p.close() 503 | p.join() 504 | print "Finish Multi-Process" 505 | print resultqq 506 | ''' 507 | result=[] 508 | while not q.empty(): 509 | t=q.get() 510 | print t 511 | result.append(t) 512 | 513 | print result 514 | #df=self.Data_DF(result) 515 | #print df 516 | <<<<<<< HEAD 517 | ''' 518 | >>>>>>> 93522ccc454b60ff763ef4866e4376d0a8ecffb9 519 | ======= 520 | 521 | 522 | >>>>>>> origin/master 523 | 524 | #格式转换 525 | def Data_DF(self, js): 526 | df = pd.DataFrame(js) 527 | df['datetime'] = pd.to_datetime(df['datetime']) 528 | df.set_index('datetime', inplace=True, drop=True) 529 | return df 530 | 531 | 532 | def main(): 533 | obj = api_demo() 534 | # obj.Trade_add('zet',0.01,2000) 535 | #obj.Trade_list('zet') 536 | #obj.Trade_cancel('zet','862979') 537 | #obj.Data_transform() 538 | #res=obj.Trade_view('zet','882354') 539 | #print res[u'status'] 540 | #obj.Data_transform() 541 | #obj.account_balance() 542 | #s=obj.AllTicker() 543 | #print s['zet']['last'] 544 | #obj.Cancel_All('zet') 545 | #print obj.get_Recent_Order('zet', '2017-07-28') 546 | #print obj.get_OpenOrder('zet') 547 | #obj.get_OpenOrder_MultiCore('zet') 548 | <<<<<<< HEAD 549 | <<<<<<< HEAD 550 | obj.get_OpenOrder_Thread('zet') 551 | ======= 552 | >>>>>>> origin/master 553 | 554 | #obj.get_OpenOrder_Thread('zet') 555 | <<<<<<< HEAD 556 | df= obj.get_Completed_order('zet') 557 | df.to_excel('closed.xls') 558 | >>>>>>> 93522ccc454b60ff763ef4866e4376d0a8ecffb9 559 | ======= 560 | #df= obj.get_Completed_order('zet') 561 | #df.to_excel('closed.xls') 562 | 563 | obj.get_OpenOrder_Thread('zet') 564 | 565 | >>>>>>> origin/master 566 | if __name__ == '__main__': 567 | main() --------------------------------------------------------------------------------