Python http.client.RemoteDisconnected() Examples

The following are 29 code examples of http.client.RemoteDisconnected(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module http.client , or try the search function .
Example #1
Source File: mult_arbit.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
def get_ord_book(self, pair):
        error_count = 0
        book_returned = False
        ord_book = {}
        fail = False
        self.lg.log('Getting order book for pair ' + pair)

        while not book_returned and not fail:
            try:
                ord_book = client.depth(pair, limit=5)
            except (MalformedRequest, InternalError, StatusUnknown,
                    ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__) + ' ' + 'Order book retrieve for ' + pair +
                            ' failed, keep trying')
                error_count += 1
                time.sleep(1)
                client.set_offset()
            else:
                book_returned = True
            finally:
                if error_count >= 5:
                    self.lg.log("Tried to get order book 5 times and failed")
                    fail = True
        return {"ord_book": ord_book, "fail_flag": fail} 
Example #2
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
def route_check_alt_last_lastprice(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip):
        route_gain = -1
        calc_done = False
        t_1_price = -1
        t_2_price = -1
        t_3_price = -1
        while calc_done == False:
            try:
                prices = client.allPrices()
                for p in prices:
                    symbol = p['symbol']
                    if symbol == pair_1:
                        t_1_price =  float(p['price'])
                    if symbol == pair_2:
                        t_2_price =  float(p['price'])
                    if symbol == pair_3:
                        t_3_price =  float(p['price'])
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                route_gain = (t_1_price / (t_2_price) * t_3_price)
                calc_done = True

        return route_gain 
Example #3
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
def route_check_t3_ask_oth_lastprice(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip):
        route_gain = -1
        ask_p3 = -1
        calc_done = False
        t_1_price = -1
        t_2_price = -1
        while calc_done == False:
            try:
                prices = client.allPrices()
                for p in prices:
                    symbol = p['symbol']
                    if symbol == pair_1:
                        t_1_price = float(p['price']) - pair_1_pip
                    if symbol == pair_2:
                        t_2_price = float(p['price']) + pair_2_pip

                ask_p3 = float(client.depth(pair_3, limit=5)['asks'][0][0]) - pair_3_pip
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                route_gain = t_1_price / t_2_price * ask_p3
                calc_done = True

        return (route_gain, t_1_price, t_2_price, ask_p3) 
Example #4
Source File: api.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
def set_offset(self):
        got_time = False
        while not got_time:
            try:
                cur_time = int(time.time() * 1000)
                bintime = int(self.time()['serverTime'])
                time_diff = cur_time - bintime
                if time_diff > 0:
                    self.time_offset = time_diff
                else:
                    self.time_offset = 500
            except (InternalError, StatusUnknown,
                        ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                print(str(e) + ' ' + str(e.__traceback__) + 'Time check failed, retry')
                time.sleep(.5)
            else:
                got_time = True 
Example #5
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
def route_check_altlast(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip):
        calc_done = False
        route_gain = -1
        bid_p2 = -1
        ask_p3 = -1
        ask_p1 = -1
        while calc_done == False:
            try:
                ask_p1 = float(client.depth(pair_1, limit = 5)['asks'][0][0]) - float(pair_1_pip)
                bid_p2 = float(client.depth(pair_2, limit = 5)['bids'][0][0]) + float(pair_2_pip)
                ask_p3 = float(client.depth(pair_3, limit = 5)['asks'][0][0]) - float(pair_3_pip)
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                # route_gain = ((ask_p1 - pair_1_pip) / ((bid_p2 + pair_2_pip)) * (ask_p3 - pair_3_pip))
                route_gain = ask_p1  / bid_p2 * ask_p3
                calc_done = True
        return (route_gain, ask_p1, bid_p2, ask_p3) 
Example #6
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
def route_check_altfirst(self, pair_1, pair_2, pair_3, pair_1_pip, pair_2_pip, pair_3_pip):
        calc_done = False
        route_gain = -1
        bid_p1 = -1
        ask_p2 = -1
        bid_p3 = -1
        while calc_done == False:
            try:
                bid_p1 = float(client.depth(pair_1, limit = 5)['bids'][0][0])
                ask_p2 = float(client.depth(pair_2, limit = 5)['asks'][0][0])
                bid_p3 = float(client.depth(pair_3, limit = 5)['bids'][0][0])
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                route_gain = (1 / (bid_p1 + pair_1_pip)) * (ask_p2 - pair_2_pip)  / (bid_p3 + pair_3_pip)
                calc_done = True

        return (route_gain, bid_p1, ask_p2, bid_p3) 
Example #7
Source File: mult_arbit.py    From Binance-bot with GNU General Public License v3.0 6 votes vote down vote up
def get_open_ords(self, pair):
        error_count = 0
        got_ords = False
        open_ords = {}
        # self.lg.log('Getting open orders for pair ' + pair)
        while not got_ords and error_count < 10:
            try:
                open_ords = client.openOrders(pair)
            except (
            MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError,
            HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__) + ' ' + 'Open order request failed try again')
                error_count += 1
                time.sleep(1)
                client.set_offset()
            else:
                got_ords = True
            finally:
                if error_count >= 10:
                    self.lg.log('Open orders check failed 10 times')
        return open_ords 
Example #8
Source File: autodefine.py    From AutoDefine with GNU General Public License v2.0 6 votes vote down vote up
def get_entries_from_api(word, url):
    if "YOUR_KEY_HERE" in url:
        return []
    try:
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0)'
                                                                 ' Gecko/20100101 Firefox/62.0'})
        returned = urllib.request.urlopen(req).read()
        if "Invalid API key" in returned.decode("UTF-8"):
            showInfo("API key '%s' is invalid. Please double-check you are using the key labeled \"Key (Dictionary)\". "
                     "A web browser with the web page that lists your keys will open." % url.split("?key=")[1])
            webbrowser.open("https://www.dictionaryapi.com/account/my-keys.htm")
            return []
        if "Results not found" in returned.decode("UTF-8"):
            return []
        etree = ET.fromstring(returned)
        return etree.findall("entry")
    except URLError:
        return []
    except (ET.ParseError, RemoteDisconnected):
        showInfo("Couldn't parse API response for word '%s'. "
                 "Please submit an issue to the AutoDefine GitHub (a web browser window will open)." % word)
        webbrowser.open("https://github.com/z1lc/AutoDefine/issues/new?title=Parse error for word '%s'"
                        "&body=Anki Version: %s%%0APlatform: %s %s%%0AURL: %s%%0AStack Trace: %s"
                        % (word, version, platform.system(), platform.release(), url, traceback.format_exc()), 0, False) 
Example #9
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_closes_connection_without_content_length(self):
        """
        The server doesn't support keep-alive because Python's http.server
        module that it uses hangs if a Content-Length header isn't set (for
        example, if CommonMiddleware isn't enabled or if the response is a
        StreamingHttpResponse) (#28440 / https://bugs.python.org/issue31076).
        """
        conn = HTTPConnection(LiveServerViews.server_thread.host, LiveServerViews.server_thread.port, timeout=1)
        try:
            conn.request('GET', '/example_view/', headers={'Connection': 'keep-alive'})
            response = conn.getresponse().read()
            conn.request('GET', '/example_view/', headers={'Connection': 'close'})
            # macOS may give ConnectionResetError.
            with self.assertRaises((RemoteDisconnected, ConnectionResetError)):
                try:
                    conn.getresponse()
                except ConnectionAbortedError:
                    if sys.platform == 'win32':
                        self.skipTest('Ignore nondeterministic failure on Windows.')
        finally:
            conn.close()
        self.assertEqual(response, b'example view') 
Example #10
Source File: bot.py    From bot with GNU General Public License v3.0 5 votes vote down vote up
def login(self, count=0):
        try:
            super().login()

            if self.aborting:
                self.aborting = False
                self.bypass_suspicious_attempt = True
                self.logger.warning("bypass_suspicious_attempt with Code: %s" % os.environ.get("SEC_CODE"))
                super().login()

            if self.aborting:
                self.send_mail_wrong_login_data()

        except (ConnectionRefusedError, RemoteDisconnected) as exc:
            return self.try_again(count, exc) 
Example #11
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def route_check_altlast_take_t2_t3(self, pair_1, pair_2, pair_3, pair_1_pip):
        calc_done = False
        route_gain = -1
        while calc_done == False:
            try:
                ask_p1 = float(client.depth(pair_1, limit = 5)['asks'][0][0])
                ask_p2 = float(client.depth(pair_2, limit = 5)['asks'][0][0])
                bid_p3 = float(client.depth(pair_3, limit = 5)['bids'][0][0])
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                route_gain = (ask_p1 - pair_1_pip) / ask_p2 * bid_p3
                calc_done = True
        return route_gain 
Example #12
Source File: bot.py    From bot with GNU General Public License v3.0 5 votes vote down vote up
def try_first_login(self, count=0):
        try:
            self.logger.warning("Try first login: \n%s\n%s" % (self.username, self.password))
            super().login()

            if self.aborting:
                self.aborting = False
                self.bypass_suspicious_attempt = True
                self.logger.warning("bypass_suspicious_attempt with Code: %s" % os.environ.get("SEC_CODE"))
                super().login()


            if self.aborting:
                email = os.environ.get("EMAIL", "")
                self.send_mail(mail_subject="Welcome to Pink Parrot!",
                               mail_body="Unfortunately Pink Parrot wasn\'t able to log-in to your account. Please "
                                         "help us to solve this problem. Go to this url: \n"
                                         "https://pinkparrot.co/insta_verify/?email=%s&username=%s"
                                         "\n\nThank you and enjoy our service!" % (email, self.username))
                self.send_stop_bot()

            else:
                self.send_mail(mail_subject="Welcome to Pink Parrot!",
                               mail_body="Congratulations and welcome to Pink Parrot! We successfully connected to "
                                         "your Instagram account and will now start interacting with your target "
                                         "groups! Now lean back and let us do the work! :)\n\nP.S.: Please make "
                                         "sure your Instagram 2-factor-authorization is switched off, as our service "
                                         "might have problems logging in to your account. ")
                self.send_start_bot()


        except (ConnectionRefusedError, RemoteDisconnected) as exc:
            return self.try_again(count, exc) 
Example #13
Source File: test_httplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_100_close(self):
        conn = FakeSocketHTTPConnection(
            b'HTTP/1.1 100 Continue\r\n'
            b'\r\n'
            # Missing final response
        )
        conn.request('GET', '/', headers={'Expect': '100-continue'})
        self.assertRaises(client.RemoteDisconnected, conn.getresponse)
        self.assertIsNone(conn.sock)
        conn.request('GET', '/reconnect')
        self.assertEqual(conn.connections, 2) 
Example #14
Source File: bot.py    From bot with GNU General Public License v3.0 5 votes vote down vote up
def act(self, count=0):
        if self.aborting:
            return

        actions = self.get_actions(self.settings or {})

        while datetime.datetime.now() < self.end_time:
            try:
                self.shuffle_actions(actions)
                self.logger.warning("shuffled actions: %s" % list(map(lambda a: a["name"], actions)))
                for f in actions:
                    if self.aborting:
                        self.logger.warning("ABORTING")
                        return

                    self.logger.warning("RUN: %s" % f["name"])
                    f["fun"]()
                    count = 0
                    sleep(1 * 60)

                sleep(2 * 60)

            except NoSuchElementException as exc:
                # if changes to IG layout, upload the file to help us locate the change
                file_path = os.path.join(gettempdir(), '{}.html'.format(time.strftime('%Y%m%d-%H%M%S')))
                with open(file_path, 'wb') as fp:
                    fp.write(self.browser.page_source.encode('utf8'))
                print('{0}\nIf raising an issue, please also upload the file located at:\n{1}\n{0}'.format(
                    '*' * 70, file_path))
                # full stacktrace when raising Github issue
                self.logger.exception(exc)
            except (ConnectionRefusedError, RemoteDisconnected, ProtocolError,
                    MaxRetryError, AttributeError) as exc:
                return self.try_again(count, exc)
            except Exception as exc:
                if 'RemoteDisconnected' in str(exc):
                    return self.try_again(count, exc)

                self.logger.error("Excepiton in act(): %s \n %s" % (exc, traceback.format_exc()))
                raise 
Example #15
Source File: test_httplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_disconnected(self):

        def make_reset_reader(text):
            """Return BufferedReader that raises ECONNRESET at EOF"""
            stream = io.BytesIO(text)
            def readinto(buffer):
                size = io.BytesIO.readinto(stream, buffer)
                if size == 0:
                    raise ConnectionResetError()
                return size
            stream.readinto = readinto
            return io.BufferedReader(stream)

        tests = (
            (io.BytesIO, client.RemoteDisconnected),
            (make_reset_reader, ConnectionResetError),
        )
        for stream_factory, exception in tests:
            with self.subTest(exception=exception):
                conn = FakeSocketHTTPConnection(b'', stream_factory)
                conn.request('GET', '/eof-response')
                self.assertRaises(exception, conn.getresponse)
                self.assertIsNone(conn.sock)
                # HTTPConnection.connect() should be automatically invoked
                conn.request('GET', '/reconnect')
                self.assertEqual(conn.connections, 2) 
Example #16
Source File: test_httplib.py    From android_universal with MIT License 5 votes vote down vote up
def test_disconnected(self):

        def make_reset_reader(text):
            """Return BufferedReader that raises ECONNRESET at EOF"""
            stream = io.BytesIO(text)
            def readinto(buffer):
                size = io.BytesIO.readinto(stream, buffer)
                if size == 0:
                    raise ConnectionResetError()
                return size
            stream.readinto = readinto
            return io.BufferedReader(stream)

        tests = (
            (io.BytesIO, client.RemoteDisconnected),
            (make_reset_reader, ConnectionResetError),
        )
        for stream_factory, exception in tests:
            with self.subTest(exception=exception):
                conn = FakeSocketHTTPConnection(b'', stream_factory)
                conn.request('GET', '/eof-response')
                self.assertRaises(exception, conn.getresponse)
                self.assertIsNone(conn.sock)
                # HTTPConnection.connect() should be automatically invoked
                conn.request('GET', '/reconnect')
                self.assertEqual(conn.connections, 2) 
Example #17
Source File: test_httplib.py    From android_universal with MIT License 5 votes vote down vote up
def test_100_close(self):
        conn = FakeSocketHTTPConnection(
            b'HTTP/1.1 100 Continue\r\n'
            b'\r\n'
            # Missing final response
        )
        conn.request('GET', '/', headers={'Expect': '100-continue'})
        self.assertRaises(client.RemoteDisconnected, conn.getresponse)
        self.assertIsNone(conn.sock)
        conn.request('GET', '/reconnect')
        self.assertEqual(conn.connections, 2) 
Example #18
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def get_high_bid(self, pair):
        bid = -1
        got_bid = False
        while got_bid == False:
            try:
                bid = client.depth(pair, limit = 5)['bids'][0][0]
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                got_bid = True
        return bid 
Example #19
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def get_low_ask(self, pair):
        ask = -1
        got_ask = False
        while got_ask == False:
            try:
                ask = client.depth(pair, limit = 5)['asks'][0][0]
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                got_ask = True
        return ask 
Example #20
Source File: integration_tools.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _submit_request(self, url, params=None, data=None,
                        headers=None, method="GET"):
        """Submits the given request, and handles the errors appropriately.

        Args:
            url (str): the request to send.
            params (dict): params to be passed along to get/post
            data (bytes): the data to include in the request.
            headers (dict): the headers to include in the request.
            method (str): the method to use for the request, "POST" or "GET".

        Returns:
            tuple of (int, str): The response status code and the json parsed
                body, or the error message.

        Raises:
            `Exception`: If any issues occur with the URL.
        """
        try:
            if method == 'POST':
                result = requests.post(
                    url, params=params, data=data, headers=headers)
            elif method == 'GET':
                result = requests.get(
                    url, params=params, data=data, headers=headers)
            result.raise_for_status()
            return (result.status_code, result.json())
        except requests.exceptions.HTTPError as excp:
            return (excp.response.status_code, excp.response.reason)
        except RemoteDisconnected as excp:
            raise Exception(excp)
        except requests.exceptions.ConnectionError as excp:
            raise Exception(
                ('Unable to connect to "{}": '
                 'make sure URL is correct').format(self.url)) 
Example #21
Source File: data_checks.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def route_check_altlast_take_t2(self, pair_1, pair_2, pair_3, pair_1_pip, pair_3_pip):
        calc_done = False
        route_gain = -1
        while calc_done == False:
            try:
                ask_p1 = float(client.depth(pair_1, limit = 5)['asks'][0][0])
                ask_p2 = float(client.depth(pair_2, limit = 5)['asks'][0][0])
                ask_p3 = float(client.depth(pair_3, limit = 5)['asks'][0][0])
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
            else:
                route_gain = ((ask_p1 - pair_1_pip) / ((ask_p2)) * (ask_p3 - pair_3_pip))
                calc_done = True
        return route_gain 
Example #22
Source File: turtle_trade.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def get_klines(self, pair, interval, limit):
        klines = []
        got_klines = False

        while not got_klines:
            try:
                klines = client.klines(pair, interval=interval, limit=limit)
            except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError,
                    HTTPException) as e:
                print(str(e) + ' ' + str(e.__traceback__))
                client.set_offset()
            else:
                got_klines = True

        return klines 
Example #23
Source File: mult_arbit.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def ord_cancel(self, pair, Order_id):
        ord_cancelled = False
        error_count = 0
        self.lg.log('Cancelling order ' + str(Order_id))
        while not ord_cancelled and error_count < 10:
            try:
                client.deleteOrder(pair, orderId=Order_id)
            except MalformedRequest as e:
                self.lg.log(str(e) + ' ' + str(
                    e.__traceback__) + ' ' + 'Order ID not found on cancel, try cancelling all open orders for the pair')
                client.set_offset()
                cur_open = self.get_open_ords(pair)
                if cur_open == []:
                    self.lg.log('Could not find the order, but no order open for the pair so must be cancelled')
                    ord_cancelled = True
                else:
                    for o in cur_open:
                        try:
                            client.deleteOrder(pair, orderId=o['orderId'])
                        except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected,
                                ProtocolError, HTTPException) as e:
                            self.lg.log(str(e) + ' ' + str(
                                e.__traceback__) + ' ' + 'Trying to cancel open orders after single cancel fails, wtf')
                            client.set_offset()
                    ord_cancelled = True
                error_count += 1
                time.sleep(1)
            except (
            InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(
                    e.__traceback__) + 'Internal or Unknown error while cancelling order, keep trying')
                error_count += 1
                time.sleep(1)
            else:
                ord_cancelled = True
            finally:
                if error_count >= 10:
                    self.lg.log('Order cancel failed 10 times, Order ID was: ' + str(Order_id)) 
Example #24
Source File: mult_arbit.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def get_order_stat_remaining(self, pair, Order_id):
        error_count = 0
        info_returned = False
        status = 'not_found'
        remaining = -1
        executed = -1
        fail = False

        if Order_id == 0:
            self.lg.log("Tried to check an unplaced order")
            fail = True

        while info_returned == False and not fail:
            try:
                stat_get = client.queryOrder(pair, orderId=Order_id)
            except MalformedRequest as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__) +
                            ' Order ID not found on status + remain check, keep trying')
                error_count += 1
                time.sleep(5)
                client.set_offset()
            except (
            InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(str(e) + ' ' + str(e.__traceback__))
                error_count += 1
                time.sleep(1)
            else:
                status = stat_get['status']
                remaining = float(stat_get['origQty']) - float(stat_get['executedQty'])
                executed = float(stat_get['executedQty'])
                info_returned = True
            finally:
                if error_count >= 5:
                    self.lg.log("Tried to get status/remaining 5 times and failed")
                    fail = True

        # self.lg.log('Returning: status = ' + status + ' remaining = ' + str(remaining))
        return {"status": status, "remaining": remaining, "executed": executed, "fail_flag": fail} 
Example #25
Source File: mult_arbit.py    From Binance-bot with GNU General Public License v3.0 5 votes vote down vote up
def place_order_onetry(self, pair, quant, price, side, test=False):
        status = 'not_placed'
        orderID = '0'
        trade = {}

        if test:
            self.lg.log('Would have placed order as: pair = ' + pair + ', quant = ' + str(quant) + ', price = '
                        + str(price) + ', side = ' + side)
            status = 'was_tested'
        elif not test:
            self.lg.log('Placing order as pair = ' + pair + ', quant = ' + str(quant) + ', price = '
                        + str(price) + ', side = ' + side)
            try:
                if side == 'sell':
                    trade = client.newLimitSellOrder(pair, quant, price)
                elif side == 'buy':
                    trade = client.newLimitBuyOrder(pair, quant, price)
            except MalformedRequest as e:
                self.lg.log(
                    str(e) + ' ' + str(e.__traceback__) + ' Tried to place order as pair = ' + pair + ', quant = '
                    + str(quant) + ', price = ' + str(price) + ', side = ' + side)
                client.set_offset()
            except StatusUnknown as e:
                self.lg.log(
                    str(e) + ' ' + str(e.__traceback__) + 'API returned StatusUnknown, checking for placed order')
                order = self.check_for_open(pair)
                fail = order["fail_flag"]
                if not fail:
                    orderID = order["order_ID"]
                    status = order["status"]
            except (InternalError, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(
                    str(e) + ' ' + str(e.__traceback__) + " Some sort of connection or internal error occured")
            else:
                status = trade["status"]
                orderID = trade["orderId"]
        self.lg.log('Returning: orderID = ' + str(orderID) + ', status = ' + status)
        return {"orderID": orderID, "status": status} 
Example #26
Source File: test_httplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_100_close(self):
        conn = FakeSocketHTTPConnection(
            b'HTTP/1.1 100 Continue\r\n'
            b'\r\n'
            # Missing final response
        )
        conn.request('GET', '/', headers={'Expect': '100-continue'})
        self.assertRaises(client.RemoteDisconnected, conn.getresponse)
        self.assertIsNone(conn.sock)
        conn.request('GET', '/reconnect')
        self.assertEqual(conn.connections, 2) 
Example #27
Source File: test_httplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_disconnected(self):

        def make_reset_reader(text):
            """Return BufferedReader that raises ECONNRESET at EOF"""
            stream = io.BytesIO(text)
            def readinto(buffer):
                size = io.BytesIO.readinto(stream, buffer)
                if size == 0:
                    raise ConnectionResetError()
                return size
            stream.readinto = readinto
            return io.BufferedReader(stream)

        tests = (
            (io.BytesIO, client.RemoteDisconnected),
            (make_reset_reader, ConnectionResetError),
        )
        for stream_factory, exception in tests:
            with self.subTest(exception=exception):
                conn = FakeSocketHTTPConnection(b'', stream_factory)
                conn.request('GET', '/eof-response')
                self.assertRaises(exception, conn.getresponse)
                self.assertIsNone(conn.sock)
                # HTTPConnection.connect() should be automatically invoked
                conn.request('GET', '/reconnect')
                self.assertEqual(conn.connections, 2) 
Example #28
Source File: mult_arbit.py    From Binance-bot with GNU General Public License v3.0 4 votes vote down vote up
def place_order_retry(self, pair, quant, price, side, test=False):
        status = 'not_placed'
        orderID = '0'
        trade = {}
        fail_count = 0

        if test:
            self.lg.log('Would have placed order as: pair = ' + pair + ', quant = ' + str(quant) + ', price = '
                        + str(price) + ', side = ' + side)
            status = 'was_tested'
        elif not test:
            self.lg.log('Placing order as pair = ' + pair + ', quant = ' + str(quant) + ', price = '
                        + str(price) + ', side = ' + side)
            try:
                while status == 'not_placed' and fail_count < 5:
                    if side == 'sell':
                        trade = client.newLimitSellOrder(pair, quant, price)
                    elif side == 'buy':
                        trade = client.newLimitBuyOrder(pair, quant, price)
                    status = trade["status"]
                    orderID = trade["orderId"]
            except MalformedRequest as e:
                self.lg.log(
                    str(e) + ' ' + str(e.__traceback__) + ' Tried to place order as pair = ' + pair + ', quant = '
                    + str(quant) + ', price = ' + str(price) + ', side = ' + side)
                fail_count += 1
                time.sleep(1)
                client.set_offset()
            except StatusUnknown as e:
                self.lg.log(
                    str(e) + ' ' + str(e.__traceback__) + ' API returned StatusUnknown, checking for placed order')
                order = self.check_for_open(pair)
                fail = order["fail_flag"]
                if not fail:
                    orderID = order["order_ID"]
                    status = order["status"]
                elif fail:
                    fail_count += 1
                    time.sleep(1)
            except (InternalError, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e:
                self.lg.log(
                    str(e) + ' ' + str(e.__traceback__) + " Some sort of connection or internal error occured")
                fail_count += 1
                time.sleep(1)
            # else:
            #     status = trade["status"]
            #     orderID = trade["orderId"]
            finally:
                if fail_count >= 5:
                    self.lg.log("Retried order 5 times, still didn't take")
        self.lg.log('Returning: orderID = ' + str(orderID) + ', status = ' + status)
        return {"orderID": orderID, "status": status} 
Example #29
Source File: rest_client.py    From sawtooth-core with Apache License 2.0 4 votes vote down vote up
def _submit_request(self, url, params=None, data=None, headers=None,
                        method="GET"):
        """Submits the given request, and handles the errors appropriately.

        Args:
            url (str): the request to send.
            params (dict): params to be passed along to get/post
            data (bytes): the data to include in the request.
            headers (dict): the headers to include in the request.
            method (str): the method to use for the request, "POST" or "GET".

        Returns:
            tuple of (int, str): The response status code and the json parsed
                body, or the error message.

        Raises:
            `CliException`: If any issues occur with the URL.
        """
        if headers is None:
            headers = {}

        if self._auth_header is not None:
            headers['Authorization'] = self._auth_header

        try:
            if method == 'POST':
                result = requests.post(
                    url, params=params, data=data, headers=headers)
            elif method == 'GET':
                result = requests.get(
                    url, params=params, data=data, headers=headers)
            result.raise_for_status()
            return (result.status_code, result.json())
        except requests.exceptions.HTTPError as e:
            return (e.response.status_code, e.response.reason)
        except RemoteDisconnected as e:
            raise CliException(e)
        except (requests.exceptions.MissingSchema,
                requests.exceptions.InvalidURL) as e:
            raise CliException(e)
        except requests.exceptions.InvalidSchema as e:
            raise CliException(
                ('Schema not valid in "{}": '
                 'make sure URL has valid schema').format(self._base_url))
        except requests.exceptions.ConnectionError as e:
            raise CliException(
                ('Unable to connect to "{}": '
                 'make sure URL is correct').format(self._base_url))