比特币 3角对冲python代码

3角对冲原理
基础货币 base, 兑换货币 quote, 中间货币 mid.

市场分为3个市场
p3: base_quote
p2: quote_mid
p1: quote_mid

代码逻辑
1, 首先获取3个市场的委托单
2, 开始计算: 情况一: 在p3市场买入 base币, 情况二: 在p3市场卖出base币
3, 上面两种情况, 考虑手续费, 和买卖价的情况下. 看付出的中间货币mid 是否比得到的中间货币 mid 少
4, 如果得到的mid比付出的多, 那么立刻下单

5, 下单逻辑没写, 不过大概率下单会成功, 如果不成功则等待, 等待时间太长可以止损, 直接卖出, 不能暂用资金, 下一轮套利开始

下面的代码, 只是寻找购买机会. 跑了几天, 发现机会渺茫. 所以放弃下订单的代码编写

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import threading

import http.client
import urllib
import json
import hashlib
import hmac
import numpy as np
np.set_printoptions(suppress=True)



#---------------------------------------数据库函数---------------------------------------
import pymysql
class MyDb:
    '''
    数据库类型
    '''
    def __init__(self, **kwargs):
        self.conn=pymysql.connect(host="127.0.0.1",user="root",password="root",database="btc",charset="utf8",cursorclass=pymysql.cursors.DictCursor)
        self.cur = self.conn.cursor()

    def create_args_string(self,num):
        '''
        创建参数占位符
        '''
        L = []
        for n in range(num):
            L.append('%s')
        return ', '.join(L)

    def query(self,sql,args=()):
        sql = sql.replace("?", "%s");
        self.cur.execute(sql,args)
        self.conn.commit()

    def select(self,sql,args=(),limit=None):
        sql = sql.replace("?", "%s");
        self.cur.execute(sql, args)
        if limit==1:
            result = self.cur.fetchone()
        else:
            result = self.cur.fetchall()
        return result

    def update(self,table,data,where="1"):
        fields =  ', '.join(map(lambda f: '`%s`=?' % (f), data.keys()))
        sql = "update `%s` set %s where %s" % (table, fields, where)
        sql = sql.replace("?", "%s");
        #print(sql)
        self.cur.execute(sql,tuple(data.values()))
        self.conn.commit()

    def insert(self,table, data):
        args        = list(data.values())
        args_string = self.create_args_string(len(args))
        fields      = ",".join(data.keys())
        sql = "insert into %s (%s) values (%s)" % (table, fields,args_string)
        self.cur.execute(sql,args)
        self.conn.commit()

    def close(self):
        self.cur.close()
        self.conn.close()
db = MyDb()
#---------------------------------------工具函数---------------------------------------
def getSign(params, secretKey):
    bSecretKey = bytes(secretKey, encoding='utf8')

    sign = ''
    for key in params.keys():
        value = str(params[key])
        sign += key + '=' + value + '&'
    bSign = bytes(sign[:-1], encoding='utf8')

    mySign = hmac.new(bSecretKey, bSign, hashlib.sha512).hexdigest()
    return mySign

def httpGet(url, resource, params=''):
    conn = http.client.HTTPSConnection(url, timeout=10)
    conn.request("GET", resource + '/' + params)
    response = conn.getresponse()
    data = response.read().decode('utf-8')
    return json.loads(data)

def httpPost(url, resource, params, apiKey, secretKey):
     headers = {
            "Content-type" : "application/x-www-form-urlencoded",
            "KEY":apiKey,
            "SIGN":getSign(params, secretKey)
     }

     conn = http.client.HTTPSConnection(url, timeout=10)

     tempParams = urllib.parse.urlencode(params) if params else ''
     print(tempParams)

     conn.request("POST", resource, tempParams, headers)
     response = conn.getresponse()
     data = response.read().decode('utf-8')
     params.clear()
     conn.close()
     return data


#---------------------------------------多线程函数---------------------------------------
class MyThread(object):
    '''
    多线程
    '''
    def __init__(self, func_list=None,timeout=5):
        self.threads = []
        self.rs = {}
        self.timeout = timeout
        self.func_list = func_list
        self.start()

    #封装的线程函数
    def trace_func(self, func, name , *args, **kwargs):
        ret = func(*args, **kwargs)
        self.rs[name] = ret

    #执行多线程
    def start(self):
        for v in self.func_list:
            if v["args"]:
                lists = []
                lists.append(v["func"])
                lists.append(v["name"])
                for arg in v["args"]:
                    lists.append(arg)
                    tuples = tuple(lists)
                    t = threading.Thread(target=self.trace_func, args=tuples)
            else:
                t = threading.Thread(target=self.trace_func, args=(v["func"],v["name"],))
            self.threads.append(t)
        for t in self.threads:
            t.start()
        for t in self.threads:
            t.join()
            #t.join(self.timeout)


#########################################套利#####################################################
class Taoli:
    def __init__(self, base='eos', quote='ht', mid='usdt'):
        self.base = base
        self.quote = quote
        self.mid = mid
        self.start()
    '''
    开始套利
    '''
    def start(self):
        #获取委托单
        func_list = []
        func_list.append({"func":self.depth, "args":("%s_%s"%(self.base, self.mid),), "name":"p1"})
        func_list.append({"func":self.depth, "args":("%s_%s"%(self.quote, self.mid),), "name":"p2"})
        func_list.append({"func":self.depth, "args":("%s_%s"%(self.base, self.quote),), "name":"p3"})
        mt = MyThread(func_list)
        d = mt.rs
        #print(d)
        #计算是否满足条件套利
        try:
            p1s = d['p1']['asks'][-1]
            p1s[0] = float(p1s[0])
            p1s[1] = float(p1s[1])
            p1b = d['p1']['bids'][0]
            p1b[0] = float(p1b[0])
            p1b[1] = float(p1b[1])

            p2s = d['p2']['asks'][-1]
            p2s[0] = float(p2s[0])
            p2s[1] = float(p2s[1])
            p2b = d['p2']['bids'][0]
            p2b[0] = float(p2b[0])
            p2b[1] = float(p2b[1])

            p3s = d['p3']['asks'][-1]
            p3s[0] = float(p3s[0])
            p3s[1] = float(p3s[1])
            p3b = d['p3']['bids'][0]
            p3b[0] = float(p3b[0])
            p3b[1] = float(p3b[1])
        except:
            print('线程错误,重新开始')
            return False
        self.buy(p1s, p1b, p2s,p2b,p3s,p3b)
        self.sell(p1s, p1b, p2s,p2b,p3s,p3b)

    '''
    买入 base货币
    '''
    def buy(self,p1s, p1b, p2s,p2b,p3s,p3b):
        num1 = p3s[1]
        num2 = p1b[1]
        min1  = min(num1,num2) #最小base币

        num3 = min1*p3s[0]
        num4 = p2s[1]
        min2 = min(num3, num4) #最小quote币

        #最小base币
        num = min(min1,min2/p3s[0])
        num_usdt = 1/p1b[1]
        num = min(num,num_usdt)
        num = "%.4f"%(num)
        num = float(num)

        #开始计算
        orders = {}
        #p3 市场
        orders['p3'] = {
            'type':'buy',
            'base_num':num,
            'quote_num':num*p3s[0],
            'price':p3s[0]
        }

        #p2 市场
        orders['p2'] = {
            'type':'buy',
            'quote_num':orders['p3']['quote_num']*1000/998,
            'mid_num' :orders['p3']['quote_num']*1000/998*p2s[0],
            'price':p2s[0]
        }

        #p1 市场
        orders['p1'] = {
            'type':'sell',
            'base_num':num*998/1000,
            'mid_num':num*998/1000*p1b[0],
            'price':p1b[0]
        }

        own_usdt = orders['p1']['mid_num']*0.998 - orders['p2']['mid_num']
        if own_usdt>0:
            with open('t.txt','a+') as f:
                own_usdt = "%.7f"%own_usdt
                orders['p2']['mid_num'] = "%.7f"%orders['p2']['mid_num']
                f.write("%s_%s: 交易:%s USDT 盈利: %s\n" % (self.base,self.quote,orders['p2']['mid_num'], own_usdt))
        print('买入base币开始下单')
        print('买入base币:数量%s'%(num))
        print('盈利mid币:%s'%(own_usdt))

    '''
    卖 base货币
    '''
    def sell(self,p1s, p1b, p2s,p2b,p3s,p3b):
        num1 = p3b[1]
        num2 = p1s[1]
        min1  = min(num1,num2) #最小base币

        num3 = min1*p3b[0]
        num4 = p2b[1]
        min2 = min(num3, num4) #最小quote币

        #最小base币
        num = min(min1,min2/p3b[0])
        num_usdt = 1/p1s[1]
        num = min(num,num_usdt)
        num = "%.4f"%(num)
        num = float(num)

        #开始计算
        orders = {}
        #p3 市场
        orders['p3'] = {
            'type':'sell',
            'base_num':num,
            'quote_num':num*p3b[0],
            'price':p3b[0]
        }

        #p2 市场
        orders['p2'] = {
            'type':'sell',
            'quote_num':orders['p3']['quote_num']*998/1000,
            'mid_num' :orders['p3']['quote_num']*998/1000*p2b[0],
            'price':p2b[0]
        }

        #p1 市场
        orders['p1'] = {
            'type':'buy',
            'base_num':num*1000/998,
            'mid_num':num*1000/998*p1s[0],
            'price':p1s[0]
        }

        own_usdt = orders['p2']['mid_num']*0.998 - orders['p1']['mid_num']
        if own_usdt>0:
            with open('t.txt','a+') as f:
                own_usdt = "%.7f"%own_usdt
                orders['p1']['mid_num'] = "%.7f"%orders['p1']['mid_num']
                f.write("%s_%s: 交易:%s USDT 盈利: %s\n" % (self.base,self.quote,orders['p1']['mid_num'], own_usdt))
        # print([p1s, p1b, p2s,p2b,p3s,p3b])
        print(orders)
        print('卖出base币开始下单')
        print('卖出base币:数量%s'%(num))
        print('盈利mid币:%s'%(own_usdt))



    '''
    获取现货市场深度信息
    '''
    def depth(self,symbol = ''):
        URL = "/api2/1/orderBook"
        url = "data.gateio.io"
        return httpGet(url, URL, symbol)
while True:
    #btc
    # coins = ['bch','eth','etc','ltc','eos','xrp','omg','dash','zec','ada','steem','iota','ocn','soc','ctxc','act','btm','bts','ont','iost','ht','trx','dta','neo','qtum','smt','ela','ven','theta','snt','zil','xem','nas','ruff','hsr','let','mds','storj','elf','itc','cvc','gnt','wicc','cmt','bix']
    # for v in coins:
    #     print("%s_%s"%(v,'btc'))
    #     Taoli(base=v, quote='btc', mid='usdt')

    #eth
    coins = ['etc','qtum','btm','eos','req','snt','omg','pay','cvc','zrx','tnt','bat','pst','dpy','lrc','storj','rdn','stx','knc','link','cdt','ae','rlc','rcn','trx','kick','vet','mco','fun','data','zsc','mda','xtz','gnt','gem','rfr','dadi','abt','ost','xlm','mobi','ocn','zpt','cofi','jnt','blz','mtn','ruff','tnc','zil','tio','bto','theta','ddd','mkr','smt','mdt','mana','lun','salt','fuel','elf','drgn','gtc','qlc','dbc','bnty','lend','icx','mds','dgd','qash','powr','hsr','qsp','ink','med','bot','qbt','gnx','nas','bcdn','snet','bu','boe','medx','cs','man','rem','lym','ont','bft','iht','senc','tomo','elec','hav','swth','nkn','soul','lrn','eosdac','dock','gse','rating','hsc','gard','fti','sop','lemo','qkc','iotx','red','lba','open','mith','skm','met','tct']
    for v in coins:
        print("%s_%s"%(v,'eth'))
        Taoli(base=v, quote='eth', mid='usdt')

    #qtum
    coins = ['ink','med','bot','qbt','tsl']
    for v in coins:
        print("%s_%s"%(v,'qtum'))
        Taoli(base=v, quote='qtum', mid='usdt')

posted @ 2018-08-03 07:54  geek程序员  阅读(750)  评论(0编辑  收藏  举报