Ejemplo n.º 1
0
def queryBalance_huobi(targetCoin,baseCoin):#Coin用大写

    myLogger.log("queryBalance_huobi")
    lowTargetCoin=targetCoin.lower()
    lowBaseCoin=baseCoin.lower()
    messageStr=""
    messageStr += "GET\n"
    messageStr += "api.huobi.pro\n"
    messageStr += myConfig.huobiRef['accountInfoUrl']
    messageStr += myConfig.huobiRef['account-id']+"/balance\n"
    messageStr += "AccessKeyId="+myConfig.huobiRef['apikey']
    messageStr += "&SignatureMethod=HmacSHA256&SignatureVersion=2"
    timeStr=datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
    timeStrEncodeUrl=urllib.quote(timeStr.encode('utf-8', 'replace'))
    messageStr += "&Timestamp="+timeStrEncodeUrl

    base64Str = base64Func(messageStr,myConfig.huobiRef['secretkey'])
    base64StrEncodeUrl=urllib.quote(base64Str.encode('utf-8', 'replace'))


    urlStr=""
    urlStr += myConfig.huobiRef['endpoint']+myConfig.huobiRef['accountInfoUrl']+myConfig.huobiRef['account-id']+"/balance?"
    urlStr += "AccessKeyId="+myConfig.huobiRef['apikey']
    urlStr += "&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp="+timeStrEncodeUrl
    urlStr += "&Signature="+base64StrEncodeUrl

    request = urllib2.Request(urlStr)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36')
    response = urllib2.urlopen(request,timeout = 15)
    data = json.load(response)
 

    try:

        balance_huobi={}
        for index, item in enumerate(data['data']['list']):

            #print item
            tmpItem={}

            if item['currency'] == lowTargetCoin and item['type'] == 'trade':

                balance_huobi[targetCoin] = float(item['balance'])

            elif item['currency'] == lowBaseCoin and item['type'] == 'trade':

                balance_huobi[baseCoin] = float(item['balance'])

        myLogger.log("balance_huobi:")
        myLogger.log(balance_huobi)
        return balance_huobi

    except Exception,e:

        #print '查询火币账户余额失败'
        print e
        myLogger.log('enquire huobi balance error')
        myLogger.log(e)
Ejemplo n.º 2
0
    def closed(self, code, reason=None):

        print("huobi websocket Closed down %s %s" % (code, reason))
        myLogger.log("huobi websocket Closed down %s %s" % (code, reason))
        global flag_isHuobiSocketWork
        flag_isHuobiSocketWork = False
        time.sleep(180)
        enquireHuobiPrice()
Ejemplo n.º 3
0
 def __init__(self):
     log("initializing Videostream...")
     self.videoStream = VideoStream(src=0).start()
     time.sleep(2.0)
     self.lowerColor = (0, 80, 138)
     self.upperColor = (38, 251, 255)
     self.position = (10, 10)
     log("Videostream initialized")
Ejemplo n.º 4
0
    def opened(self):

        print('huobi websocket opened')
        myLogger.log('huobi websocket opened')
        global flag_isHuobiSocketWork
        flag_isHuobiSocketWork=True
        tradeStr="""{"sub": "market.%s%s.depth.step0", "id": "id10"}""" % (targetCoin.lower(),baseCoin.lower())
        self.send(tradeStr)
Ejemplo n.º 5
0
    def closed(self, code, reason=None):

        print "bian websocket Closed down", code, reason
        myLogger.log("bian websocket Closed down %s %s" % (code, reason))
        global flag_isBianSocketWork
        flag_isBianSocketWork = False
        time.sleep(180)
        enquireBianPrice()
Ejemplo n.º 6
0
 def wafe(self):
     log('This is gonna take forever 😏')
     while True:
         for angle in range(-29, 30, 1):
             self.robo.setAngles(
                 [0, -angle, angle * 1.1, -angle * 1.4, angle * 2])
         for angle in range(29, -30, -1):
             self.robo.setAngles(
                 [0, -angle, angle * 1.1, -angle * 1.4, angle * 2])
Ejemplo n.º 7
0
def sendTextInfo(title, content1, content2, remark):

    try:
        #print 'sendTextInfo'
        post_data = {
            "touser": '******',
            "template_id": "TAwWy-Am9SnHUAfKVhMnzTIUWMFPQyvwuDNbZx0plM4",
            "data": {
                "first": {
                    "value": title,
                    "color": "#173177"
                },
                "keyword1": {
                    "value": content1,
                    "color": "#173177"
                },
                "keyword2": {
                    "value": content2,
                    "color": "#173177"
                },
                "remark": {
                    "value": remark,
                    "color": "#173177"
                }
            }
        }
        #print post_data

        #xml解析在服务器的2.6环境下有问题!
        workPath = "/usr/local/bin/projects/fukuoka/"
        filePath = workPath + 'properties.xml'
        tree = ET.ElementTree(file=filePath)
        root = tree.getroot()
        for child_of_root in root:

            #print child_of_root
            if child_of_root.tag == "access_token":

                accessToken = child_of_root.text
                #print accessToken

        requrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
        headers = {'Content-Type': 'application/json'}
        request = urllib2.Request(url=requrl,
                                  headers=headers,
                                  data=json.dumps(post_data))
        response = urllib2.urlopen(request)
        jsonResult = json.load(response)
        #print jsonResult
        #return jsonResult['msgid']

    except Exception, e:

        print e
        myLogger.log("send notice error:")
        myLogger.log(e)
Ejemplo n.º 8
0
 def hasReachedAngle(self):
     # USING HASREACHEDANGLE FROM ARDUINO
     function = FUNC_HAS_REACHED_ANGLE
     message = f'{function}:{self.id}\n'.encode("utf-8")
     self.ser.write(message)
     answer = self.ser.read(1)
     # log(f'servo {self.id} answer: {answer}')
     hasReached = int.from_bytes(answer, byteorder='big', signed=False)
     # log(f'{hasReached}')
     if hasReached > 0:
         log(f'servo {self.id} has reached goal angle, is {self.getAngle()} should {self.goalAngle}')
     return hasReached > 0
Ejemplo n.º 9
0
def enquireBianPrice():

    while (1):
        try:
            URL_BIAN = myConfig.binanceRef[
                'websocket_endpoint'] + 'wx/%s%s@depth5' % (targetCoin.lower(),
                                                            baseCoin.lower())
            ws_bian = DummyClient_bian(URL_BIAN,
                                       protocols=['http-only', 'chat'])
            #ws = DummyClient('ws://10.222.138.163:1889/websocket', protocols=['chat'])
            ws_bian.connect()
            ws_bian.run_forever()
            break
            #except KeyboardInterrupt:
        except Exception, e:

            print "huobi websocket error"
            myLogger.log("bian websocket error")
            try:
                ws_bian.close()
            except Exception, e:

                print("ws_bian.close() error")
                myLogger.log("ws_bian.close() error")
                myLogger.log(e)
            time.sleep(10)
            print("will retry connect bian websocket")
            myLogger.log("will retry connect bian websocket")
Ejemplo n.º 10
0
def submitcancel_huobi(orderIdStr):

    #POST /v1/order/orders/{order-id}/submitcancel
    cancelResult={}
    params = {
              "order-id": orderIdStr,

             }

    timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
    params_to_sign = {
                      'AccessKeyId': myConfig.huobiRef['apikey'],
                      'SignatureMethod': 'HmacSHA256',
                      'SignatureVersion': '2',
                      'Timestamp': timestamp
                     }

    host_url = myConfig.huobiRef['endpoint']
    host_name = myConfig.huobiRef['host']
    submitcancekUrl="/v1/order/orders/"+params["order-id"]+"/submitcancel"
    params_to_sign['Signature'] = createSign(params_to_sign,'POST', host_name, submitcancekUrl, myConfig.huobiRef['secretkey'])
    url = host_url + submitcancekUrl + '?' + urllib.urlencode(params_to_sign)

    headers = {
        "Accept": "application/json",
        'Content-Type': 'application/json',
        "User-Agent": "Chrome/39.0.2171.71",
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0'
    }
    postdata = json.dumps(params)

    try:
        response = requests.post(url, postdata, headers=headers, timeout=15)


        if response.status_code == 200:


            cancelResult = response.json()
            myLogger.log(cancelResult)
            return cancelResult

        else:

            return response.json()

    except Exception as e:

        myLogger.log("httpPost failed, detail is:%s" % e)
        return cancelResult
Ejemplo n.º 11
0
def enquireBianPrice():

    #while (1):
    try:
        print 'try connect bian websocket'
        print _targetCoin.lower()
        print _baseCoin.lower()
        URL_BIAN = myConfig.binanceRef[
            'websocket_endpoint'] + 'ws/%s%s@depth5' % (_targetCoin.lower(),
                                                        _baseCoin.lower())
        print URL_BIAN
        ws_bian = DummyClient_bian(URL_BIAN, protocols=['http-only', 'chat'])
        #ws = DummyClient('ws://10.222.138.163:1889/websocket', protocols=['chat'])
        ws_bian.connect()
        ws_bian.run_forever()
        #break

    except Exception, e:

        myLogger.log("bian websocket error")
        myLogger.log(e)
        print "bian websocket error"
        print e
        try:
            ws_bian.close()
        except Exception, e:

            myLogger.log("ws_bian.close() error")
            myLogger.log(e)
            print e
Ejemplo n.º 12
0
 def getCorrectedAngle(self, angle):
     if self.inverted:
         angle = -angle
     angle += self.offset
     if angle > self.bounds[1]:
         angle = self.bounds[1]
         log(
             "angle of servo {} out of bounds. angle is {}".format(
                 self.pin, angle), "ERR")
     if angle < self.bounds[0]:
         angle = self.bounds[0]
         log(
             "angle of servo {} out of bounds. angle is {}".format(
                 self.pin, angle), "ERR")
     newAngle = myutils.map(angle, self.bounds[0], self.bounds[1], 0, 180)
     return newAngle
Ejemplo n.º 13
0
    def received_message(self, m):

        try:
            msg = gzdecode(m).decode('utf-8')
            global highestBuyNum_huobi
            global highestBuyPrice_huobi
            global lowestSellPrice_huobi
            global lowestSellNum_huobi
            global flag_isHuobiSocketWork

            if msg[:7] == '{"ping"':
                ts = msg[8:21]
                pong = '{"pong":' + ts + '}'
                self.send(pong)
                tradeStr = """{"sub": "market.%s%s.depth.step0", "id": "id10"}""" % (
                    targetCoin.lower(), baseCoin.lower())
                self.send(tradeStr)

            else:

                if msg[:5] == '{"ch"':

                    priceData = json.loads(msg)
                    #bids 买
                    highestBuyPrice_huobi = float(
                        priceData['tick']['bids'][0][0])
                    highestBuyNum_huobi = float(
                        priceData['tick']['bids'][0][1])
                    #asks 卖
                    #print priceData
                    lowestSellPrice_huobi = float(
                        priceData['tick']['asks'][0][0])
                    lowestSellNum_huobi = float(
                        priceData['tick']['asks'][0][1])
                    #if not flag_isHuobiSocketWork:flag_isHuobiSocketWork=True
                    #价格显示出来核对下
                    #print "火币的最低卖价: "+"%f" % lowestSellPrice_huobi
                    #print "火币的最低卖价深度: "+"%f" % lowestSellNum_huobi

        except Exception, e:

            print("huobi on message error")
            myLogger.log("huobi on message error")
            print(e)
            flag_isHuobiSocketWork = False
Ejemplo n.º 14
0
def getTradeDetail_bian(symbol,orderId):#symbol:"LTCBTC" orderId:1 #long

    tradeDetailResult={}
    timestamp = int(round(time.time() * 1000))
    #print timestamp
    queryString = "symbol="+symbol+"&"
    queryString += "orderId="+str(orderId)+"&"
    queryString += "recvWindow=5000&timestamp="+str(timestamp)
    #print queryString
    signature = sha256(queryString,myConfig.binanceRef['secretKey'])
    #print signature

    fullurl = ""
    fullurl += myConfig.binanceRef['endpoint']
    fullurl += "/api/v3/order?"
    fullurl += queryString+"&"
    fullurl += "signature="+signature

    try:

        request = urllib2.Request(fullurl)
        request.add_header('X-MBX-APIKEY', myConfig.binanceRef['apikey'])
        response = urllib2.urlopen(request,timeout = 15)
        tradeDetailResult = json.load(response)
        myLogger.log(tradeDetailResult)
        return tradeDetailResult

    except Exception,e:
        myLogger.log("get trade detail of bian wrong")
        myLogger.log(e)
        return tradeDetailResult
Ejemplo n.º 15
0
def getTradeDetail_huobi(orderIdStr):

    tradeResult={}
    messageStr=""
    messageStr += "GET\n"
    messageStr += "api.huobi.pro\n"
    messageStr += "/v1/order/orders/"
    messageStr += orderIdStr+"\n"
    messageStr += "AccessKeyId="+myConfig.huobiRef['apikey']
    messageStr += "&SignatureMethod=HmacSHA256&SignatureVersion=2"
    timeStr=datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
    timeStrEncodeUrl=urllib.quote(timeStr.encode('utf-8', 'replace'))
    messageStr += "&Timestamp="+timeStrEncodeUrl

    base64Str = base64Func(messageStr,myConfig.huobiRef['secretkey'])
    base64StrEncodeUrl=urllib.quote(base64Str.encode('utf-8', 'replace'))


    urlStr=""
    urlStr += myConfig.huobiRef['endpoint']+"/v1/order/orders/"+orderIdStr+"?"
    urlStr += "AccessKeyId="+myConfig.huobiRef['apikey']
    urlStr += "&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp="+timeStrEncodeUrl
    urlStr += "&Signature="+base64StrEncodeUrl

    request = urllib2.Request(urlStr)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36')

    try:
        response = urllib2.urlopen(request,timeout = 15)
        tradeResult = json.load(response)
        myLogger.log(tradeResult)
        return tradeResult


    except Exception,e:

        myLogger.log("get trade detail of huobi error")
        return tradeResult
Ejemplo n.º 16
0
 def getPositionFromFrame(self, frame):
     center = None
     if frame is None:
         log("no frame available", "WARN")
         return self.position
     # blur the frame, and convert it to the HSV color space
     # frame = imutils.resize(frame, width=600)
     blurred = cv2.GaussianBlur(frame, (11, 11), 0)
     hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
     # construct a mask for the color, then perform
     # a series of dilations and erosions to remove any small
     # blobs left in the mask
     mask = cv2.inRange(hsv, self.lowerColor, self.upperColor)
     mask = cv2.erode(mask, None, iterations=2)
     mask = cv2.dilate(mask, None, iterations=2)
     # find contours in the mask
     cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                             cv2.CHAIN_APPROX_SIMPLE)
     cnts = imutils.grab_contours(cnts)
     # only proceed if at least one contour was found
     if len(cnts) > 0:
         # log("found contour!", "OK")
         # find the largest contour in the mask
         c = max(cnts, key=cv2.contourArea)
         ((xc, yc), radius) = cv2.minEnclosingCircle(c)
         if radius > 10:
             M = cv2.moments(c)
             center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
             x = myutils.map(center[0], 0, 600, -100, 100)
             x *= -0.7
             y = myutils.map(center[1], 50, 300, 0, 80)
             y = 80 - y
             self.position = (x, y)
             self.contour = c
     else:
         log("no contour found", "WARN")
     # log("Position is {}".format(self.position))
     return self.position
Ejemplo n.º 17
0
    def dance(self):
        log('This is gonna take forever 😏')
        velocity = 50
        while True:
            self.robo.setVelocity(velocity)

            self.robo.setVelocityForIndex(2, velocity * 2)
            angle = 60
            self.robo.setAnglesBlocking([0, angle, 2 * angle, angle, 0])
            angle = 0
            self.robo.setAnglesBlocking([0, angle, 2 * angle, angle, 0])

            self.robo.setVelocityForIndex(2, velocity)
            self.robo.setVelocityForIndex(3, velocity * 2)
            angle = 60
            self.robo.setAnglesBlocking([0, 0, angle, 2 * angle, angle])
            angle = 0
            self.robo.setAnglesBlocking([0, 0, angle, 2 * angle, angle])

            self.robo.setVelocityForIndex(3, velocity)
            self.robo.setVelocityForIndex(4, velocity * 2)
            angle = 60
            self.robo.setAnglesBlocking([0, 0, 0, angle, 2 * angle])
            angle = 0
            self.robo.setAnglesBlocking([0, 0, 0, angle, 2 * angle])

            self.robo.setVelocityForIndex(1, velocity)
            self.robo.setVelocityForIndex(2, velocity * 2)
            self.robo.setVelocityForIndex(3, velocity * 2)
            self.robo.setVelocityForIndex(4, velocity * 2)
            angle = 60
            self.robo.setAnglesBlocking(
                [0, angle, 2 * angle, 2 * angle, 2 * angle])
            angle = 0
            self.robo.setAnglesBlocking(
                [0, angle, 2 * angle, 2 * angle, 2 * angle])
Ejemplo n.º 18
0
def updateBalance():

    _balance_bian = myAccount.queryBalance_bian(_targetCoin, _baseCoin)
    _balance_huobi = myAccount.queryBalance_huobi(_targetCoin, _baseCoin)
    myLogger.log("update balance information:")
    myLogger.log("huobi: %s %s  %s %s" %
                 (_targetCoin, _balance_huobi[_targetCoin], _baseCoin,
                  _balance_huobi[_baseCoin]))
    myLogger.log("bian: %s %s  %s %s" %
                 (_targetCoin, _balance_bian[_targetCoin], _baseCoin,
                  _balance_bian[_baseCoin]))

    title = "update balance information:"
    content1 = "huobi: %s %s  %s %s" % (_targetCoin,
                                        _balance_huobi[_targetCoin], _baseCoin,
                                        _balance_huobi[_baseCoin])
    content2 = "bian: %s %s  %s %s" % (_targetCoin, _balance_bian[_targetCoin],
                                       _baseCoin, _balance_bian[_baseCoin])
    sendNotice(title, content1, content2)
Ejemplo n.º 19
0
def queryBalance_bian(targetCoin,baseCoin):

    myLogger.log("queryBalance_bian")
    balance_bian={}
    timestamp = int(round(time.time() * 1000))
    #print timestamp
    queryString = "recvWindow=5000&timestamp="+str(timestamp)
    #print queryString
    signature = sha256(queryString,myConfig.binanceRef['secretKey'])
    #print signature

    fullurl = ""
    fullurl += myConfig.binanceRef['endpoint']
    fullurl += myConfig.binanceRef['accountInfoUrl']+"?"
    fullurl += queryString+"&"
    fullurl += "signature="+signature
    try:

        request = urllib2.Request(fullurl)
        request.add_header('X-MBX-APIKEY', myConfig.binanceRef['apikey'])
        response = urllib2.urlopen(request,timeout = 15)
        data = json.load(response)

        for index, item in enumerate(data['balances']):

            tmpItem={}
            if item['asset'] == targetCoin:

                balance_bian[targetCoin] = float(item['free'].encode('utf-8'))

            elif item['asset'] == baseCoin:

                balance_bian[baseCoin] = float(item['free'].encode('utf-8'))

        myLogger.log("balance_bian:")
        myLogger.log(balance_bian)
        return balance_bian

    except Exception,e:
        print e
Ejemplo n.º 20
0
 def getPosition(self):
     center = None
     frame = self.videoStream.read()
     # log("Frame read")
     if frame is None:
         log("no frame available", "WARN")
         return self.position
     # resize the frame, blur it, and convert it to the HSV
     # color space
     frame = imutils.resize(frame, width=600)
     blurred = cv2.GaussianBlur(frame, (11, 11), 0)
     hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
     # construct a mask for the color, then perform
     # a series of dilations and erosions to remove any small
     # blobs left in the mask
     mask = cv2.inRange(hsv, self.lowerColor, self.upperColor)
     mask = cv2.erode(mask, None, iterations=2)
     mask = cv2.dilate(mask, None, iterations=2)
     # find contours in the mask
     cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                             cv2.CHAIN_APPROX_SIMPLE)
     cnts = imutils.grab_contours(cnts)
     # only proceed if at least one contour was found
     if len(cnts) > 0:
         # log("found contour!", "OK")
         # find the largest contour in the mask
         c = max(cnts, key=cv2.contourArea)
         M = cv2.moments(c)
         center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
         x = myutils.map(center[0], 0, 600, 0, 100)
         y = myutils.map(center[1], 0, 600, 0, 100)
         self.position = (x, y)
         cv2.drawContours(frame, [c], 0, (0, 255, 0), 3)
     else:
         log("no contour found", "WARN")
     cv2.imshow("Frame", frame)
     log("Position is {}".format(self.position))
     return self.position
Ejemplo n.º 21
0
def order_bian_GTC(buyOrSell,targetCoin,baseCoin,quantity,price):

    orderResult={}
    symbol = targetCoin+baseCoin
    side = buyOrSell
    type = "LIMIT"
    quantity = quantity
    price = price
    timestamp = int(round(time.time() * 1000))


    requestBody = ""
    requestBody += "symbol="+targetCoin+baseCoin
    requestBody += "&side="+buyOrSell
    requestBody += "&type="+type
    requestBody += "&timeInForce=GTC" #GTC
    requestBody += "&quantity="+str(quantity)
    requestBody += "&price="+str(price)
    #requestBody += "&recvWindow=5000"
    requestBody += "&timestamp="+str(timestamp)
    #print requestBody

    #sha256
    signature = sha256(requestBody,myConfig.binanceRef['secretKey'])
    #print signature
    requestBody += "&signature="+signature
    #post

    try:

        headers = {

            'X-MBX-APIKEY': myConfig.binanceRef['apikey'],
            'Content-Type':'application/x-www-form-urlencoded'
        }

        url = myConfig.binanceRef['endpoint']+myConfig.binanceRef['tradeUrl']+'?'+requestBody
        myLogger.log(url)
        r = requests.post(url,headers=headers)
        print r.json()
        if r.status_code == 200:

            orderResult = r.json()
            myLogger.log(orderResult)
            return orderResult

        else:
            myLogger.log("trade error in bian")
            myLogger.log(r.json())
            return orderResult


    except Exception,e:

        myLogger.log('币安交易失败')
        myLogger.log(e)
        return orderResult
Ejemplo n.º 22
0
    for key in myConfig.minNumOfLimitTrade:

        targetCoin = key.split('/')[0]
        baseCoin = key.split('/')[1]

        minTradeNumOfTargetCoin = myConfig.minNumOfLimitTrade[key]
    symbol = targetCoin + baseCoin
    balance_bian = {}
    balance_huobi = {}

    balance_bian = myAccount.queryBalance_bian(targetCoin, baseCoin)
    balance_huobi = myAccount.queryBalance_huobi(targetCoin, baseCoin)

    if balance_bian and balance_huobi:

        myLogger.log("now balance information:")
        myLogger.log("huobi: %s %s  %s %s" %
                     (targetCoin, balance_huobi[targetCoin], baseCoin,
                      balance_huobi[baseCoin]))
        myLogger.log("bian: %s %s  %s %s" %
                     (targetCoin, balance_bian[targetCoin], baseCoin,
                      balance_bian[baseCoin]))

        title = "now balance information:"
        content1 = "huobi: %s %s  %s %s" % (targetCoin,
                                            balance_huobi[targetCoin],
                                            baseCoin, balance_huobi[baseCoin])
        content2 = "bian: %s %s  %s %s" % (targetCoin,
                                           balance_bian[targetCoin], baseCoin,
                                           balance_bian[baseCoin])
        remark = "fukuoka"
Ejemplo n.º 23
0
def order_huobi_IOC(buyOrSell,targetCoin,baseCoin,quantity,price):#limit 限价单

    orderResult={}
    params = {
              "account-id": myConfig.huobiRef['account-id'],
              "amount": quantity,
              "symbol": targetCoin+baseCoin,
              "type": buyOrSell.lower()+"-ioc",
              "source": "api",
              "price":price,
             }
    print params
    timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
    params_to_sign = {
                      'AccessKeyId': myConfig.huobiRef['apikey'],
                      'SignatureMethod': 'HmacSHA256',
                      'SignatureVersion': '2',
                      'Timestamp': timestamp
                     }

    host_url = myConfig.huobiRef['endpoint']
    host_name = myConfig.huobiRef['host']
    params_to_sign['Signature'] = createSign(params_to_sign,'POST', host_name, myConfig.huobiRef['tradeUrl'], myConfig.huobiRef['secretkey'])
    url = host_url + myConfig.huobiRef['tradeUrl'] + '?' + urllib.urlencode(params_to_sign)
    myLogger.log(url)
    headers = {
        "Accept": "application/json",
        'Content-Type': 'application/json',
        "User-Agent": "Chrome/39.0.2171.71",
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0'
    }
    postdata = json.dumps(params)

    try:
        response = requests.post(url, postdata, headers=headers, timeout=15)

        if response.status_code == 200:

            #status error "ok"
            orderResult = response.json()
            myLogger.log(orderResult)
            print orderResult
            return orderResult


        else:
            myLogger.log("trade error in huobi")
            myLogger.log(response.json())
            return orderResult

    except Exception as e:

        myLogger.log("trade error in huobi")
        myLogger.log(e)
        return orderResult
Ejemplo n.º 24
0
def saveActualPriceData(direction, rate, sellMarketNumber, buyMarketNumber):

    myLogger.log("saveActualPriceData")
    timeStr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    dao.insertActualPriceData(timeStr, _symbol, direction, rate,
                              sellMarketNumber, buyMarketNumber)
Ejemplo n.º 25
0
def order_bian(buyOrSell,targetCoin,baseCoin,quantity,price):

    symbol = targetCoin+baseCoin
    side = buyOrSell
    type = "LIMIT"
    quantity = quantity
    price = price
    timestamp = int(round(time.time() * 1000))


    requestBody = ""
    requestBody += "symbol="+targetCoin+baseCoin
    requestBody += "&side="+buyOrSell
    requestBody += "&type="+type
    requestBody += "&timeInForce=FOK" #GTC
    requestBody += "&quantity="+str(quantity)
    requestBody += "&price="+str(price)
    #requestBody += "&recvWindow=5000"
    requestBody += "&timestamp="+str(timestamp)
    #print requestBody

    #sha256
    signature = sha256(requestBody,myConfig.binanceRef['secretKey'])
    #print signature
    requestBody += "&signature="+signature
    #post

    try:

        headers = {

            'X-MBX-APIKEY': myConfig.binanceRef['apikey'],
            'Content-Type':'application/x-www-form-urlencoded'
        }

        url = myConfig.binanceRef['endpoint']+myConfig.binanceRef['tradeUrl']+'?'+requestBody
        myLogger.log(url)
        r = requests.post(url,headers=headers)
        myLogger.log(r.json())
        if r.status_code == 200:

            result = r.json()	
            status = result['status']
            if status == "FILLED":#完全成交
                return "SUCCESS"
            else:
                myLogger.log("trade failed in bian")
                myLogger.log(r.json())
                return "FAILED"

        else:
            myLogger.log("networkError in bian")
            myLogger.log(r.json())
            return "networkError"
        #status":"FILLED
        #返回的结果 status 有 NEW FILLED

    except Exception,e:

        print '币安交易失败'
        print e
        return "networkError"
        myLogger.log('币安交易失败')
        myLogger.log(e)
Ejemplo n.º 26
0
    def opened(self):

        print 'bian websocket opened'
        myLogger.log('bian websocket opened')
        global flag_isBianSocketWork
        flag_isBianSocketWork = True
Ejemplo n.º 27
0
def queryOrderDetail_huobi(orderIdStr):

    while (1):

        tradeDetail = myAccount.getTradeDetail_huobi(orderIdStr)
        if tradeDetail:

            if tradeDetail['data']['state'] != "filled":  #没有完成交易
                myLogger.log("order of huobi is not finished")
                myLogger.log(tradeDetail)

            else:  #交易全部完成 state = filled

                myLogger.log("buy order of huobi is finished")
                title = "huobiBuy order success:"
                content1 = "BuyNum:%s" % tradeDetail['data']['field-amount']
                content2 = "BuyPrice:%s" % tradeDetail['data']['price']
                remark = "fukuoka"
                notice.sendTextInfo(title, content1, content2, remark)

                #更新balance
                global _balance_bian
                global _balance_huobi
                _balance_bian = myAccount.queryBalance_bian(
                    _targetCoin, _baseCoin)
                _balance_huobi = myAccount.queryBalance_huobi(
                    _targetCoin, _baseCoin)
                myLogger.log("update balance information:")
                myLogger.log("huobi: %s %s  %s %s" %
                             (_targetCoin, _balance_huobi[_targetCoin],
                              _baseCoin, _balance_huobi[_baseCoin]))
                myLogger.log("bian: %s %s  %s %s" %
                             (_targetCoin, _balance_bian[_targetCoin],
                              _baseCoin, _balance_bian[_baseCoin]))

                title = "update balance information:"
                content1 = "huobi: %s %s  %s %s" % (
                    _targetCoin, _balance_huobi[_targetCoin], _baseCoin,
                    _balance_huobi[_baseCoin])
                content2 = "bian: %s %s  %s %s" % (
                    _targetCoin, _balance_bian[_targetCoin], _baseCoin,
                    _balance_bian[_baseCoin])
                sendNotice(title, content1, content2)

                break  #不再继续查询交易结果

        else:

            myLogger.log("query order detail error in huobi")
            break

        time.sleep(300)
Ejemplo n.º 28
0
def enquireHuobiPrice():

    while (1):
        try:
            #print 'enquireHuobi'
            myLogger.log('websocket_endpoint_huobi start to connect')
            ws_huobi = DummyClient_huobi(
                myConfig.huobiRef['websocket_endpoint'],
                protocols=['http-only', 'chat'])
            ws_huobi.connect()
            ws_huobi.run_forever()
            break

        except Exception, e:

            print "huobi websocket error"
            myLogger.log("huobi websocket error")
            myLogger.log(e)
            try:
                ws_huobi.close()
            except Exception, e:

                print("ws_huobi.close() error")
                myLogger.log("ws_huobi.close() error")
                myLogger.log(e)
            time.sleep(10)
            print("will retry connect huobi websocket")
            myLogger.log("will retry connect huobi websocket")
Ejemplo n.º 29
0
def moveLine():
    angles, fname = moves.getLine()
    moveAngles(angles)


def moveAngles(angles):
    for angle in angles:
        robo.setAngles(angle)


def teachPositions():
    cli.startTeachingCli()


try:
    log("starting actual programm")
    robo.chill()
    time.sleep(2.0)

    # moves.auroraMoves()
    # moves.dance()
    # moves.hello()
    # moves.wafe()
    # moves.simpleMovementExample()
    # moves.myMove()
    # moves.createCircle()
    # moves.moveCircle()

    teachPositions()

    # time.sleep(2.0)
Ejemplo n.º 30
0
def insertActualPriceData(queryTime, symbol, direction, rate, sellMarketNumber,
                          buyMarketNumber):

    myLogger.log('def insertActualPriceData')
    pwd = 'MyNewPass4!'
    db = mysql.connector.connect(user='******',
                                 password=pwd,
                                 database='coin',
                                 use_unicode=True)
    cursor = db.cursor()

    sql = "insert into actualPriceRecord (queryTime,symbol,tradeDirection,tradeRate,sellMarketNumber," \
          "buyMarketNumber) values ('%s','%s','%s','%f','%f','%f')"\
          % (queryTime,symbol,direction,rate,sellMarketNumber,buyMarketNumber)

    myLogger.log(sql)
    try:
        # 执行SQL语句
        myLogger.log("try insert")
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
        myLogger.log("finish insert")

    except Exception, e:
        print e
        myLogger.log("insert actual price error")
        myLogger.log(e)
        db.rollback()