coinall挖矿(下)

2018-09-01  本文已影响17人  提莫队长1234
from Exchanges import Exchange_Coinall  #import交易所类。注:需要将公众号文章上篇所写的交易所类,保存为文件名Exchanges.py
import json
import time
import sys
import datetime
import decimal
import threading



###########################################################################
######################   用户设置区  #######################################

#以下设置交易所api key, secret key和PASSPHRASE
API_KEY = ""
SECRET_KEY = ""
PASSPHRASE = ""    #Coinall交易所多一个PASSPHRASE设置

#以下设置机器人运行参数
SYMBOL_FOR_EXCHANGE  = "eth-usdt"   #交易对,将传递给Exchange交易所对象
SLEEP_TIME_AFTER_TRADE = 5  #下单后暂停时间,用于适应交易API访问频率限制
TRADE_AMOUNT = 0.1  #单笔下单数量
PRICE_GAP  = 0  #价差。为0时以相同的价格买进和卖出,为负时低买高卖,为正时高买低卖。
CAC_ONHOLD_AMOUNT = 1000  #CAC锁仓数量,默认1000个(最低锁仓量)
MINING_DIFFICULTY_LIMIT_RATE = 95   #每小时挖矿数量占限额比例,防止挖矿超限

######################   用户设置区结束  ####################################
###########################################################################

#下单数量计数器 
SUM_TRADE_AMOUNT = 0
#下单数量计数器清零标志
SUM_TRADE_AMOUNT_CLEARED_FLAG = True   

#初始化交易所对象
exchange = Exchange_Coinall()   #交易所对象
exchange.auth(API_KEY, SECRET_KEY, PASSPHRASE)  

# 取浮点数的指定小数点位数。不四舍五入
def get_float(value, length):
    value = str(value)
    flag = '.'
    point = value.find(flag)
    length = int(length) + point
    value = value[0:point] + value[point:length + 1]
    return float(value)

#定义交易所返回错误码对应的提示信息
def tx_result_msg_display(tx_result):
    if  tx_result['code'] == 1003:
        print("\n参数设置的每笔交易数量过小,请适当增大\n")
    elif tx_result['code'] == 1002:
        print("\n可用余额不足\n")
    else:
        print("\n其它错误代码,需要查询API文档。\n")
        pass
    #请根据交易所API文档调整错误代码对应的提示信息
    
        
#限价买入线程
def limit_buy_thread_func(symbol_pair, price, amount):
    print("\n发送限价买入指令:价格" + price + " 数量" + amount)
    try:
        buy_result = exchange.limit_buy_order(symbol_pair, price, amount)
    except Exception as e:
        print("发送买入指令时,出现错误\n" + repr(e) + "\n")
        return
        
    if ('result' in buy_result):
        if buy_result['result'] == True:  
            print("\n买入指令,服务器返回: OK" )        
    else:
        print("\n买入指令,服务器返回: "  + str(buy_result))
        tx_result_msg_display(buy_result )

        
#限价卖出线程  
def limit_sell_thread_func(symbol_pair, price, amount):
    #time.sleep(0.1)
    print("\n发送限价卖出指令:价格" + price + " 数量" + amount)
    try:
        sell_result = exchange.limit_sell_order(symbol_pair, price, amount)
    except Exception as e:
        print("发送卖出指令时,出现错误\n" + repr(e) + "\n")
        return
        
    if ('result' in sell_result):
        if sell_result['result'] == True:     
            print("\n卖出指令,服务器返回: OK" )
    else:
        print("\n卖出指令,服务器返回: "  + str(sell_result))
        tx_result_msg_display(sell_result)




#主循环
#获取行情 -> 下单 -> 获取行情 -> 下单
def main_loop():
    global SUM_TRADE_AMOUNT
    global SUM_TRADE_AMOUNT_CLEARED_FLAG
    global SLEEP_TIME_AFTER_TRADE
 
    
    while True:

        #每个整点开始时,清零交易量计数器
        current_minute = int(datetime.datetime.now().strftime("%M"))   #取当前分钟数        
        #判断是否已清零交易计数器   
        if current_minute >= 0 and current_minute < 5:
            if SUM_TRADE_AMOUNT_CLEARED_FLAG == False:
                SUM_TRADE_AMOUNT = 0
                SUM_TRADE_AMOUNT_CLEARED_FLAG = True
        elif current_minute > 50:
            SUM_TRADE_AMOUNT_CLEARED_FLAG = False
            

        nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S  %f')
        print("\n\n---------------------------------")
        print(nowTime)
        print("---------------------------------")
          
        
        #获取基准挖矿难度,及CET-ETH(或CET-BTC)价格
        #global CAC_ONHOLD_AMOUNT
        try:
            basic_mining_speed = exchange.get_basic_mining_speed()   #返回难度的浮点数
        except Exception as e:
            print("\n\n从交易所服务器获取基准挖矿速度出错。错误信息:\n" + repr(e))
            time.sleep(1)
            continue
            
        time.sleep(0.3)
        
        
        for i in range(0, len(SYMBOL_FOR_EXCHANGE)):
            if SYMBOL_FOR_EXCHANGE[i] == "-":    # cac/h
                front_half = SYMBOL_FOR_EXCHANGE[0:i]
        front_currency = front_half


       #如果使用cac-usdt以外的交易对  
        if front_currency != "cac":             
            try:
                cac_depth = exchange.get_market_depth('cac-' + front_currency)
            except Exception as e:
                print("\n\n获取CET发前价格出错。错误信息:\n" + repr(e))
                continue
            cac_price = (float(cac_depth['asks'][0][0]) + float(cac_depth['bids'][0][0])) / 2
            
        #如果使用cac-usdt交易对            
        else:    
            cac_price = 1
       
        print("每小时基准挖矿速度: " + str(basic_mining_speed) + " CAC/小时\n")
        print("你的每小时挖矿限额: " + str(basic_mining_speed * CAC_ONHOLD_AMOUNT / 10000) + " CAC/小时\n")
        print("按当前价格估算的已挖数量(CAC数量): " + str(SUM_TRADE_AMOUNT) + "\n")  
        
        if SUM_TRADE_AMOUNT >= (basic_mining_speed * CAC_ONHOLD_AMOUNT / 10000) * MINING_DIFFICULTY_LIMIT_RATE /100:
            print("\n已接近每小时限额,暂停交易挖矿。\n\n")
            time.sleep(5)
            continue


    #####获取行情#####

        start = time.time()
       
        try:
            current_depth = exchange.get_market_depth(SYMBOL_FOR_EXCHANGE)            
        except Exception as e:
            print("\n获取行情时,服务器或网络错误。稍后重新获取 \n")
            print(repr(e))
            time.sleep(1)
            continue
        
        getting_depth_period = time.time() - start
        print("正在获取行情...  获取行情网络延时:%s秒" % get_float(getting_depth_period, 3)) 



        middle_price = get_float((float(current_depth['asks'][0][0]) + float(current_depth['bids'][0][0])) / 2, 5)   #取depth的买1卖1

        if SYMBOL_FOR_EXCHANGE  != "cac-usdt":
            sell_price = str(get_float((middle_price - PRICE_GAP/2), 2))      
            buy_price = str(get_float((middle_price + PRICE_GAP/2), 2))
        else:
            sell_price = str(get_float((middle_price - PRICE_GAP/2), 5))      
            buy_price = str(get_float((middle_price + PRICE_GAP/2), 5))
            

    #####下单#####
            
        #开始计时,用于计算下单指令所消耗的时间。
        tx_start = time.time()
       
        #交易总量计数
        SUM_TRADE_AMOUNT += (float(TRADE_AMOUNT) * 2) * 0.002 /cac_price

        #限价下单
        buy_thread = threading.Thread(target = limit_buy_thread_func, args=(SYMBOL_FOR_EXCHANGE, buy_price, str(TRADE_AMOUNT)))
        sell_thread = threading.Thread(target = limit_sell_thread_func, args=(SYMBOL_FOR_EXCHANGE, sell_price, str(TRADE_AMOUNT)))      
        buy_thread.start()
        sell_thread.start()
        buy_thread.join()
        sell_thread.join()

        #结束计时,并显示发出下单指令所消耗的时间。
        tx_period = time.time() - tx_start
        print("\n发送交易指令耗时(网络延时):%s秒" % get_float(tx_period, 3)) 


        #下单后暂停一定时间
        if SLEEP_TIME_AFTER_TRADE > 0:
            time.sleep(SLEEP_TIME_AFTER_TRADE)
            
        time.sleep(1)   #需至少加暂停1秒


def main():
    #启动循环
    main_loop()
        

if __name__=='__main__':
        main()

上一篇下一篇

猜你喜欢

热点阅读