聚币 现货 API [Python2版]

一、utils.py,基础类,包括HTTP 请求、签名等

# -*- coding: utf-8 -*-
import hashlib
import hmac
import time
import urllib
import urllib2
import json
from datetime import datetime
from uuid import UUID
from objutil import dict_obj
# import requests

def http_get(url, data_wrap, encode=False):
    if encode is True:
        data_wrap = urllib.urlencode(data_wrap)
    req = urllib2.Request(url, data=data_wrap)
    resp = urllib2.urlopen(req).read()
    dic = json.loads(resp)
    return dict_obj(dic)

def get_signature(private_key, data):
    data_en = urllib.urlencode(data)
    md5_hash = getHash(private_key)
    msg = bytes(data_en).encode('utf-8')
    key = bytes(md5_hash).encode('utf-8')
    signature = hmac.new(key, msg, digestmod=hashlib.sha256).digest()
    last_warp = "%s&signature=%s" % (data_en, toHex(signature))
    return last_warp

def get_nonce_time():
    curr_stamp = time.time() * 100
    return str(long(curr_stamp))

def getHash(s):
    m = hashlib.md5()
    m.update(s)
    return m.hexdigest()

def toHex(str):
    lst = []
    for ch in str:
        hv = hex(ord(ch)).replace('0x', '')
        if len(hv) == 1:
            hv = ' + hv
        lst.append(hv)
    return reduce(lambda x, y: x + y, lst)

def getUserData(cfg_file):
    f = open(cfg_file, 'r')
    account = {}
    for i in f.readlines():
        ctype, passwd = i.split('=')
        account[ctype.strip()] = passwd.strip()

    return account

class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, UUID):
            return str(obj)
        else:
            return json.JSONEncoder.default(self, obj)

def json_dumps(result):
    return json.dumps(result, cls=CJsonEncoder)

二、jubi.py,聚币网API

# -*- coding: utf-8 -*-
# @Author: wujiyu
# @Date:   2017-07-09 10:44:41
# @Last Modified by:   far
# @Last Modified time: 2017-07-25 09:28:12

from utils import *

BASE_API = "https://www.jubi.com/api/v1"

TICKER_API = "%s/ticker" % BASE_API
DEPTH_API = "%s/depth" % BASE_API
ORDERS_API = "%s/orders" % BASE_API
BALANCE_API = "%s/balance" % BASE_API
TRADLIST_API = "%s/trade_list" % BASE_API
TRADEVIEW_API = "%s/trade_view" % BASE_API
TRADECANCEL_API = "%s/trade_cancel" % BASE_API
TRADEADD_API = "%s/trade_add" % BASE_API

class JuBi(object):
    """docstring for JuBi"""

    def __init__(self):
        super(JuBi, self).__init__()
        cfg = getUserData('data.cfg')
        self.public_key = cfg['public_key']
        self.private_key = cfg['private_key']

    def get_ticker(self, coin):
        data_wrap = {'coin': coin}
        return http_get(TICKER_API, data_wrap, True)

    def get_depth(self, coin):
        data_wrap = {'coin': coin}
        return http_get(DEPTH_API, data_wrap, True)

    def get_orders(self, coin):
        data_wrap = {'coin': coin}
        return http_get(ORDERS_API, data_wrap, True)

    def get_balance(self):
        nonce = get_nonce_time()
        data_wrap = {'nonce': nonce,
                     'key': self.public_key}
        all_data = get_signature(self.private_key, data_wrap)
        return http_get(BALANCE_API, all_data)

    def get_trade_list(self, coin):
        #  open:正在挂单, all:所有挂单
        trade_type = "open"
        since = "
        nonce = get_nonce_time()
        data_wrap = {'nonce': nonce, 'type': trade_type, 'coin': coin, 'since': since,
                     'key': self.public_key}
        all_data = get_signature(self.private_key, data_wrap)
        return http_get(TRADLIST_API, all_data)

    def get_trade_view_list(self, coin, id):
        nonce = get_nonce_time()
        data_wrap = {'nonce': nonce, 'coin': coin,
                     'key': self.public_key, 'id': id}
        all_data = get_signature(self.private_key, data_wrap)
        return http_get(TRADEVIEW_API, all_data)

    def cancel(self, coin, id):
        nonce = get_nonce_time()
        data_wrap = {'nonce': nonce, 'coin': coin,
                     'key': self.public_key, 'id': id}
        all_data = get_signature(self.private_key, data_wrap)
        return http_get(TRADECANCEL_API, all_data)

    def trade_add(self, coin, amount, price, sell_type):
        nonce = get_nonce_time()
        data_wrap = {'nonce': nonce, 'coin': coin,
                     'key': self.public_key, 'amount': amount, "price": price, "type": sell_type}
        all_data = get_signature(self.private_key, data_wrap)
        return http_get(TRADEADD_API, all_data)

    def sell(self, coin, amount, price):
        return self.trade_add(coin, amount, price, "sell")

    def buy(self, coin, amount, price):
        return self.trade_add(coin, amount, price, "buy")

    def cancel_all(self, coin, sell_type="all"):
        lst = self.get_trade_list(coin)
        print("当前挂单!!!!!!!!!!:%s" % (lst))
        for item in lst:
            if sell_type == "all" or sell_type == item["type"]:
                self.cancel(coin, item["id"])
        print("取消挂单成功!!!!!!!!!")
        print("当前挂单!!!!!!!!!!:%s" % (self.get_trade_list(coin)))
        return True

    def cancel_all_sell(self, coin):
        return self.cancel_all(coin, "sell")

    def cancel_all_buy(self, coin):
        return self.cancel_all(coin, "buy")

三、调用方法

coin = "btc"
jubi = JuBi()
print(jubi.get_ticker(coin))
# print(jubi.get_depth(coin))
# print(jubi.get_orders(coin))
# print(jubi.get_balance())
# print(jubi.get_trade_list(coin))
# print(jubi.get_trade_view_list(coin, "1"))
# print(jubi.get_trade_cancel_list(coin, "1"))
# print(jubi.sell(coin, 10000, 0.001))
# print(jubi.buy(coin, 100, 0.2))
# print(jubi.get_trade_cancel_list(coin, "1"))
# print(jubi.cancel(coin, 940591))

四、下载地址

http://www.cnblogs.com/fangbei/p/jubi-api-python.html

http://files.cnblogs.com/files/fangbei/jubi-api-python2.zip

聚币网API[Python2版]的更多相关文章

  1. 聚币网API[Python3版]

    代码 #!/usr/bin/env python # -*- coding:utf-8 -*- import hashlib import requests import time import ur ...

  2. 聚币网API使用教程 demo

    原文 http://30daydo.com/article/181 目前还在完善,等功能完善了,就更新到csdn. 更新 2017-05-27 官方有API的文档,可是这个文档就像一个草稿一样,两个基 ...

  3. 火币网现货API[Python3版]

    火币 期货 现货 API [Python3版] 一.Util.py,基础类,包括参数配置.签名,HTTP 请求方法,发送信息到API #coding=utf-8 import hashlib impo ...

  4. 淘宝网触屏版 - 学习笔记(1 - 关于meta)

    注:本文是学习笔记,并不是教程,所以会有很多我不理解或猜测的问题,也会有不尽详实之处,望见谅. <meta charset="utf-8"> <meta cont ...

  5. 淘宝网触屏版 - 学习笔记(0 - 关于dpr)

    注:本文是学习笔记,并不是教程,所以会有很多我不理解或猜测的问题,也会有不尽详实之处,望见谅. 对于pc端网页设计师来说,移动端的网页制作,我之前只是简单的加了一个 <meta name=&qu ...

  6. [转载]中国天气网API

    最近在做个网站要用到天气网的api,在网上找了些参考资料,这篇文章对天气网api的介绍比较详细,所以转载之,谢谢原作者的辛勤劳动和奉献精神. 原文地址:http://g.kehou.com/t1033 ...

  7. OKCoin期货现货API[Python3版]

    OKCoin 期货 现货 API [Python版] 一.HttpMD5Util.py,基础类,包括MD5签名,HTTP Post及HTTP Get方法 #!/usr/bin/python # -*- ...

  8. 火币Huobi API Websocket

    本文介绍火币Huobi API Websocket WebSocket API简介 WebSocket协议是基于TCP的一种新的网络协议.它实现了客户端与服务器之间在单个 tcp 连接上的全双工通信, ...

  9. 火币Huobi API

    本文介绍火币Huobi API REST API 简介 火币为用户提供了一套全新的API,可以帮用户快速接入火币PRO站及HADAX站的交易系统,实现程序化交易. 访问地址 适用站点 适用功能 适用交 ...

随机推荐

  1. C#常用8种排序算法实现以及原理简介

    public static class SortExtention { #region 冒泡排序 /* * 已知一组无序数据a[1].a[2].--a[n],需将其按升序排列.首先比较a[1]与a[2 ...

  2. 一个简单的java贷款程序

    代码如下: //计算贷款package ClassDemo;import javax.swing.JOptionPane; public class ComputeLoan { public stat ...

  3. JDK+Tomcat+Zookeeper+DubboAdmin安装教程

    JDK+Tomcat+Zookeeper+DubboAdmin安装教程 1. 安装内容: JDK 1.8.131 Tomcat 7.0.77 Zookeeper 3.4.9 Dubbo admin 2 ...

  4. javac.exe、 java.exe、 java虚拟机三者之间的区别与联系

    JDK中 javac:Java编译器,将Java源代码换成字节代: java:Java解释器,直接从类文件执行Java应用程序代码: 先编译  *.java文件――――>*.class文件 运行 ...

  5. 【chrome】 chrome 开发者工具

    1. 常用控制台工具 console.log  console.info  console.error  console.warn console.assert console.count conso ...

  6. LeetCode题解 343.Integer Break

    题目:Given a positive integer n, break it into the sum of at least two positive integers and maximize ...

  7. Grass Cownoisseur[Usaco2015 Jan]

    题目描述 In an effort to better manage the grazing patterns of his cows, Farmer John has installed one-w ...

  8. Hibernate与 MyBatis的比较(转)

    第一章     Hibernate与MyBatis Hibernate 是当前最流行的O/R mapping框架,它出身于sf.NET,现在已经成为Jboss的一部分. Mybatis 是另外一种优秀 ...

  9. 在drawRect:方法中绘制图片,文字以及Core Graphics 框架的了解

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #000000 } p.p2 { margin: 0.0px 0. ...

  10. NOIP 2014 提高组 题解

    NOIP 2014 提高组 题解 No 1. 生活大爆炸版石头剪刀布 http://www.luogu.org/problem/show?pid=1328 这是道大水题,我都在想怎么会有人错了,没算法 ...