Exemplo n.º 1
0
 def _sell(self, qty, price):
     log.info("SELL %s qty:%s price:%s" % self._trading_pair, qty, price)
     res = BINANCE_INSTANCE.limit_maker(self._trading_pair, "SELL", qty, price)
     if not "orderId" in res:
         return False
     self._order_id = res["orderId"]
     self._order_status = "SELL"
     return True
Exemplo n.º 2
0
 def _buy(self, qty, price):
     log.info("BUY %s qty:%s price:%s" % (self._trading_pair, qty, price))
     res = BINANCE_INSTANCE.limit_maker(self._trading_pair, "BUY", qty, price)
     if not "orderId" in res:
         return False
     self._order_id = res["orderId"]
     self._order_status = "BUY"
     return True
Exemplo n.º 3
0
 def run(self):
     """Proxy Run"""
     log.info("ProxyProcess Start!")
     subprocess.run(["pkill", "-f", "trojan"])
     subprocess.run(["rm", "-rf", "trojan.log"])
     subprocess.run([
         "trojan", "-l",
         os.path.join(os.getcwd(), "trojan.log"), "-c", self.config_file
     ])
Exemplo n.º 4
0
 def get_sys_status(self) -> bool:
     """get binance system status
     
     @return bool: True: normal, False: system maintenance"""
     "https://api.binance.com/sapi/v1/system/status"
     url = "%s/sapi/v1/system/status" % self.binance_base_url
     res = eval(requests.get(url, proxies=PROXIES).text)
     if not isinstance(res, dict):
         log.error("error responce:%s" % res)
         return False
     return True if not res.get("status", 1) else False
Exemplo n.º 5
0
 def __init__(self, currency):
     super().__init__()
     self._currency = currency
     self._trading_pair = "%sUSDT" % self._currency
     self._hold_price = 0
     self._mark_price = 0
     self._decline_count = 0
     self._usdt_qty = 0
     self._currency_qty = 0
     self._side = ""
     self._order_id = ""
     self._order_status = ""
     self._order_start_time = 0
     log.info("%s class entry!", self.__class__.__name__)
     log.info(BINANCE_INSTANCE.get_exchange_info(self._trading_pair))
Exemplo n.º 6
0
 def cancel_order(self, symbol, order_id):
     url = "%s/api/v3/order" % self.binance_base_url
     params = {
         "timestamp": str(int(time.time() * 1000)),
         "symbol": symbol,
         "orderId": order_id
     }
     params = self._update_headers_with_signature(params)
     headers = {"X-MBX-APIKEY": self.api_key}
     res = requests.delete(url,
                           headers=headers,
                           params=params,
                           proxies=PROXIES).text
     res = eval(res)
     if res["status"] == "CANCELED":
         return True
     log.error("cancled failed!!")
     return False
Exemplo n.º 7
0
 def limit_maker(self, symbol, side, quantity, price):
     url = "%s/api/v3/order" % self.binance_base_url
     params = {
         "timestamp": str(int(time.time() * 1000)),
         "symbol": symbol,
         "side": side,
         "type": "LIMIT_MAKER",
         "quantity": quantity,
         "price": price,
         "newOrderRespType": "ACK"
     }
     params = self._update_headers_with_signature(params)
     headers = {"X-MBX-APIKEY": self.api_key}
     res = requests.post(url,
                         headers=headers,
                         params=params,
                         proxies=PROXIES).text
     log.info(res)
     return eval(res)
Exemplo n.º 8
0
 def get_user_data(self, currency):
     """get_user_data
     """
     url = "%s/api/v3/account" % self.binance_base_url
     params = {"timestamp": str(int(time.time() * 1000))}
     params = self._update_headers_with_signature(params)
     headers = {"X-MBX-APIKEY": self.api_key}
     res = requests.get(url,
                        headers=headers,
                        params=params,
                        proxies=PROXIES).text
     res = res.replace("false", "False").replace("true", "True")
     res = eval(res)
     if not "balances" in res:
         log.info(res)
         return None
     for item in res["balances"]:
         if item["asset"] == currency:
             return item
     return None
Exemplo n.º 9
0
    def get_recent_trades(self, symbol: str = None, limit: int = 1) -> List:
        """get_recent_trades

        @param symbol: trading pair
        @param limit: Trading volume 1 < limit < 1000

        @return list(if empty is not correct)
        """
        url = "%s/api/v3/trades" % self.binance_base_url

        if not symbol or limit > 1000 or limit < 1:
            err_info = \
                "symbol or limit is illegal." \
                "symbol must not None, 1 < limit < 1000!"
            log.error(err_info)
            return []

        params = {"symbol": symbol, "limit": limit}
        res = requests.get(url, params=params, proxies=PROXIES).text
        res = res.replace("false", "False").replace("true", "True")
        res = eval(res)
        return res
Exemplo n.º 10
0
    def initialize(self):
        if not BINANCE_INSTANCE.get_sys_status():
            log.error("remote binance system is maintenance!")
            return False
        log.info("binance system is normal")

        status, self._usdt_qty = self._update_currency("USDT")
        if not status:
            return
        log.info("the account has %f usdt free!" % self._usdt_qty)

        status, self._currency_qty = self._update_currency(self._currency)
        if not status:
            return
        log.info("the account has %f %s free!" % (self._currency_qty, self._currency))

        return True
Exemplo n.º 11
0
 def _query_order(self):
     if not self._order_status:
         log.warning("there is no order found!")
         return False
     query = BINANCE_INSTANCE.query_order(self._trading_pair, self._order_id)
     return query.get("status", "NEW")
Exemplo n.º 12
0
 def _cancel(self):
     if not self._order_status:
         log.warning("there is no order found!")
         return False
     return BINANCE_INSTANCE.cancel_order(self._trading_pair, self._order_id)
Exemplo n.º 13
0
 def _update_currency(self, currency):
     currency_data = BINANCE_INSTANCE.get_user_data(currency)
     if not currency_data:
         log.error("can not fetch account %s" % currency)
         return False, 0
     return True, float(currency_data["free"])
Exemplo n.º 14
0
            return False
        self._order_id = res["orderId"]
        self._order_status = "BUY"
        return True

    def _cancel(self):
        if not self._order_status:
            log.warning("there is no order found!")
            return False
        return BINANCE_INSTANCE.cancel_order(self._trading_pair, self._order_id)

    def _query_order(self):
        if not self._order_status:
            log.warning("there is no order found!")
            return False
        query = BINANCE_INSTANCE.query_order(self._trading_pair, self._order_id)
        return query.get("status", "NEW")

    def _query_trading_pair(self):
        return BINANCE_INSTANCE.get_best_trading_pair(self._trading_pair)


if __name__ == "__main__":
    log.info("auto trade entry")
    proxy = proxy_func()
    auto_trade = SingleTransaction("DOGE")
    auto_trade.start()
    auto_trade.join()
    proxy.kill()

Exemplo n.º 15
0
    def run(self):
        if not self.initialize():
            return
        # 买入
        # 涨 1% 卖出盈利, 跌0.5% 卖出止损
        while True:
            if not self._order_status and self._usdt_qty > 10:  # 买入
                log.info("query trading pair")
                now_trading = self._query_trading_pair()
                log.info("ready to buy")
                if not self._buy(
                        float("%.1f" %
                              (self._usdt_qty / float(now_trading["seller"]))),
                        float("%.5f" %
                              (float(now_trading["seller"]) * 0.9999))):
                    log.info("buy error")
                    return
                self._order_start_time = time.time()
                flag = False
                while time.time() - self._order_start_time < 10:
                    query_order = self._query_order()
                    log.info(query_order)
                    if not query_order == "NEW":
                        flag = True
                        break

                if not flag:
                    self._cancel()
                    self._order_status = ""
                    log.info("buy doge failed! try to rebuy")
                    continue
                status, self._currency_qty = self._update_currency(
                    self._currency)
                status, self._usdt_qty = self._update_currency("USDT")
                self._hold_price = float(now_trading["seller"])

            elif self._order_status == "BUY":
                now_trading = self._query_trading_pair()
                log.info("i have usdt %s doge %s" %
                         (self._usdt_qty, self._currency_qty))
                log.info("now buyer:%s profit:%s loss:%s" %
                         (self._hold_price, 1.01 * self._hold_price,
                          0.995 * self._hold_price))
                if float(now_trading["buyer"]) > 1.01 * self._hold_price:
                    if not self._sell(
                            float("%.1f" % self._currency_qty),
                            float("%.5f" %
                                  (float(now_trading["buyer"] * 1.0002)))):
                        log.error("sell doge error")
                        return
                elif float(now_trading["buyer"]) < 0.995 * self._hold_price:
                    if not self._sell(
                            float("%.1f" % self._currency_qty),
                            float("%.5f" %
                                  (float(now_trading["buyer"] * 1.0002)))):
                        log.error("sell doge error")
                        return
            elif self._order_status == "SELL":
                if not self._query_order() == "NEW":
                    self._order_status = ""
Exemplo n.º 16
0
 def __init__(self, config_file="/home/han/.proxy/config.json"):
     """ProxyProcess"""
     super(ProxyProcess, self).__init__()
     self.config_file = config_file
     log.info("ProxyProcess init!")