We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
BTG or other assets with no market in bittrex crash the app
## Problem Definition

If a user holds an asset in bittrex that does not have a market in the exchange, like say `BTG`, then during balances query rotkehlchen will crash with `ValueError: Bittrex: Could not find BTC market for "BTG"`

## Task

Fix the crash, and use other sources for market price data in the case this happens.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `rotkehlchen/bittrex.py`
Content:
```
1 import time
2 import hmac
3 import hashlib
4 from urllib.parse import urlencode
5 from json.decoder import JSONDecodeError
6 
7 from typing import Dict, Tuple, Optional, Union, List, cast
8 from rotkehlchen.utils import (
9     createTimeStamp,
10     get_pair_position,
11     rlk_jsonloads,
12     cache_response_timewise,
13 )
14 from rotkehlchen.exchange import Exchange
15 from rotkehlchen.order_formatting import Trade
16 from rotkehlchen.fval import FVal
17 from rotkehlchen.errors import RemoteError
18 from rotkehlchen.inquirer import Inquirer
19 from rotkehlchen import typing
20 
21 import logging
22 logger = logging.getLogger(__name__)
23 
24 BITTREX_MARKET_METHODS = {
25     'getopenorders',
26     'cancel',
27     'sellmarket',
28     'selllimit',
29     'buymarket',
30     'buylimit'
31 }
32 BITTREX_ACCOUNT_METHODS = {
33     'getbalances',
34     'getbalance',
35     'getdepositaddress',
36     'withdraw',
37     'getorderhistory'
38 }
39 
40 
41 def bittrex_pair_to_world(pair: str) -> str:
42     return pair.replace('-', '_')
43 
44 
45 def world_pair_to_bittrex(pair: str) -> str:
46     return pair.replace('_', '-')
47 
48 
49 def trade_from_bittrex(bittrex_trade: Dict) -> Trade:
50     """Turn a bittrex trade returned from bittrex trade history to our common trade
51     history format"""
52     amount = FVal(bittrex_trade['Quantity']) - FVal(bittrex_trade['QuantityRemaining'])
53     rate = FVal(bittrex_trade['PricePerUnit'])
54     order_type = bittrex_trade['OrderType']
55     bittrex_price = FVal(bittrex_trade['Price'])
56     bittrex_commission = FVal(bittrex_trade['Commission'])
57     pair = bittrex_pair_to_world(bittrex_trade['Exchange'])
58     base_currency = get_pair_position(pair, 'first')
59     if order_type == 'LIMIT_BUY':
60         order_type = 'buy'
61         cost = bittrex_price + bittrex_commission
62         fee = bittrex_commission
63     elif order_type == 'LIMIT_SEL':
64         order_type = 'sell'
65         cost = bittrex_price - bittrex_commission
66         fee = bittrex_commission
67     else:
68         raise ValueError('Got unexpected order type "{}" for bittrex trade'.format(order_type))
69 
70     return Trade(
71         timestamp=bittrex_trade['TimeStamp'],
72         pair=pair,
73         type=order_type,
74         rate=rate,
75         cost=cost,
76         cost_currency=base_currency,
77         fee=fee,
78         fee_currency=base_currency,
79         amount=amount,
80         location='bittrex'
81     )
82 
83 
84 class Bittrex(Exchange):
85     def __init__(
86             self,
87             api_key: typing.ApiKey,
88             secret: typing.ApiSecret,
89             inquirer: Inquirer,
90             data_dir: typing.FilePath
91     ):
92         super(Bittrex, self).__init__('bittrex', api_key, secret, data_dir)
93         self.apiversion = 'v1.1'
94         self.uri = 'https://bittrex.com/api/{}/'.format(self.apiversion)
95         self.inquirer = inquirer
96 
97     def first_connection(self):
98         self.first_connection_made = True
99 
100     def validate_api_key(self) -> Tuple[bool, str]:
101         try:
102             self.api_query('getbalance', {'currency': 'BTC'})
103         except ValueError as e:
104             error = str(e)
105             if error == 'APIKEY_INVALID':
106                 return False, 'Provided API Key is invalid'
107             elif error == 'INVALID_SIGNATURE':
108                 return False, 'Provided API Secret is invalid'
109             else:
110                 raise
111         return True, ''
112 
113     def api_query(
114             self,
115             method: str,
116             options: Optional[Dict] = None,
117     ) -> Union[List, Dict]:
118         """
119         Queries Bittrex with given method and options
120         """
121         if not options:
122             options = {}
123         nonce = str(int(time.time() * 1000))
124         method_type = 'public'
125 
126         if method in BITTREX_MARKET_METHODS:
127             method_type = 'market'
128         elif method in BITTREX_ACCOUNT_METHODS:
129             method_type = 'account'
130 
131         request_url = self.uri + method_type + '/' + method + '?'
132 
133         if method_type != 'public':
134             request_url += 'apikey=' + self.api_key.decode() + "&nonce=" + nonce + '&'
135 
136         request_url += urlencode(options)
137         signature = hmac.new(
138             self.secret,
139             request_url.encode(),
140             hashlib.sha512
141         ).hexdigest()
142         self.session.headers.update({'apisign': signature})
143         response = self.session.get(request_url)
144         try:
145             json_ret = rlk_jsonloads(response.text)
146         except JSONDecodeError:
147             raise RemoteError('Bittrex returned invalid JSON response')
148 
149         if json_ret['success'] is not True:
150             raise RemoteError(json_ret['message'])
151         return json_ret['result']
152 
153     def get_btc_price(self, asset: typing.BlockchainAsset) -> Optional[FVal]:
154         if asset == 'BTC':
155             return None
156         btc_price = None
157         btc_pair = 'BTC-' + asset
158         for market in self.markets:
159             if market['MarketName'] == btc_pair:
160                 btc_price = FVal(market['Last'])
161                 break
162 
163         if btc_price is None:
164             raise ValueError('Bittrex: Could not find BTC market for "{}"'.format(asset))
165 
166         return btc_price
167 
168     @cache_response_timewise()
169     def query_balances(self) -> Tuple[Optional[dict], str]:
170         try:
171             self.markets = self.api_query('getmarketsummaries')
172             resp = self.api_query('getbalances')
173         except RemoteError as e:
174             msg = (
175                 'Bittrex API request failed. Could not reach bittrex due '
176                 'to {}'.format(e)
177             )
178             logger.error(msg)
179             return None, msg
180 
181         returned_balances = dict()
182         for entry in resp:
183             currency = entry['Currency']
184             usd_price = self.inquirer.find_usd_price(
185                 asset=currency,
186                 asset_btc_price=self.get_btc_price(currency)
187             )
188 
189             balance = dict()
190             balance['amount'] = FVal(entry['Balance'])
191             balance['usd_value'] = FVal(balance['amount']) * usd_price
192             returned_balances[currency] = balance
193 
194         return returned_balances, ''
195 
196     def query_trade_history(
197             self,
198             start_ts: typing.Timestamp,
199             end_ts: typing.Timestamp,
200             end_at_least_ts: typing.Timestamp,
201             market: Optional[str] = None,
202             count: Optional[int] = None,
203     ) -> List:
204 
205         options: Dict[str, Union[str, int]] = dict()
206         cache = self.check_trades_cache(start_ts, end_at_least_ts)
207         cache = cast(List, cache)
208         if market is not None:
209             options['market'] = world_pair_to_bittrex(market)
210         elif cache is not None:
211             return cache
212 
213         if count is not None:
214             options['count'] = count
215         order_history = self.api_query('getorderhistory', options)
216 
217         returned_history = list()
218         for order in order_history:
219             order_timestamp = createTimeStamp(order['TimeStamp'], formatstr="%Y-%m-%dT%H:%M:%S.%f")
220             if start_ts is not None and order_timestamp < start_ts:
221                 continue
222             if end_ts is not None and order_timestamp > end_ts:
223                 break
224             order['TimeStamp'] = order_timestamp
225             returned_history.append(order)
226 
227         self.update_trades_cache(returned_history, start_ts, end_ts)
228         return returned_history
229
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/rotkehlchen/bittrex.py b/rotkehlchen/bittrex.py
--- a/rotkehlchen/bittrex.py
+++ b/rotkehlchen/bittrex.py
@@ -1,24 +1,24 @@
-import time
-import hmac
 import hashlib
-from urllib.parse import urlencode
+import hmac
+import logging
+import time
 from json.decoder import JSONDecodeError
+from typing import Dict, List, Optional, Tuple, Union, cast
+from urllib.parse import urlencode
 
-from typing import Dict, Tuple, Optional, Union, List, cast
+from rotkehlchen import typing
+from rotkehlchen.errors import RemoteError
+from rotkehlchen.exchange import Exchange
+from rotkehlchen.fval import FVal
+from rotkehlchen.inquirer import Inquirer
+from rotkehlchen.order_formatting import Trade
 from rotkehlchen.utils import (
+    cache_response_timewise,
     createTimeStamp,
     get_pair_position,
     rlk_jsonloads,
-    cache_response_timewise,
 )
-from rotkehlchen.exchange import Exchange
-from rotkehlchen.order_formatting import Trade
-from rotkehlchen.fval import FVal
-from rotkehlchen.errors import RemoteError
-from rotkehlchen.inquirer import Inquirer
-from rotkehlchen import typing
 
-import logging
 logger = logging.getLogger(__name__)
 
 BITTREX_MARKET_METHODS = {
@@ -160,9 +160,6 @@
                 btc_price = FVal(market['Last'])
                 break
 
-        if btc_price is None:
-            raise ValueError('Bittrex: Could not find BTC market for "{}"'.format(asset))
-
         return btc_price
 
     @cache_response_timewise()
@@ -181,9 +178,10 @@
         returned_balances = dict()
         for entry in resp:
             currency = entry['Currency']
+            asset_btc_price = self.get_btc_price(currency)
             usd_price = self.inquirer.find_usd_price(
                 asset=currency,
-                asset_btc_price=self.get_btc_price(currency)
+                asset_btc_price=asset_btc_price
             )
 
             balance = dict()

{"golden_diff": "diff --git a/rotkehlchen/bittrex.py b/rotkehlchen/bittrex.py\n--- a/rotkehlchen/bittrex.py\n+++ b/rotkehlchen/bittrex.py\n@@ -1,24 +1,24 @@\n-import time\n-import hmac\n import hashlib\n-from urllib.parse import urlencode\n+import hmac\n+import logging\n+import time\n from json.decoder import JSONDecodeError\n+from typing import Dict, List, Optional, Tuple, Union, cast\n+from urllib.parse import urlencode\n \n-from typing import Dict, Tuple, Optional, Union, List, cast\n+from rotkehlchen import typing\n+from rotkehlchen.errors import RemoteError\n+from rotkehlchen.exchange import Exchange\n+from rotkehlchen.fval import FVal\n+from rotkehlchen.inquirer import Inquirer\n+from rotkehlchen.order_formatting import Trade\n from rotkehlchen.utils import (\n+    cache_response_timewise,\n     createTimeStamp,\n     get_pair_position,\n     rlk_jsonloads,\n-    cache_response_timewise,\n )\n-from rotkehlchen.exchange import Exchange\n-from rotkehlchen.order_formatting import Trade\n-from rotkehlchen.fval import FVal\n-from rotkehlchen.errors import RemoteError\n-from rotkehlchen.inquirer import Inquirer\n-from rotkehlchen import typing\n \n-import logging\n logger = logging.getLogger(__name__)\n \n BITTREX_MARKET_METHODS = {\n@@ -160,9 +160,6 @@\n                 btc_price = FVal(market['Last'])\n                 break\n \n-        if btc_price is None:\n-            raise ValueError('Bittrex: Could not find BTC market for \"{}\"'.format(asset))\n-\n         return btc_price\n \n     @cache_response_timewise()\n@@ -181,9 +178,10 @@\n         returned_balances = dict()\n         for entry in resp:\n             currency = entry['Currency']\n+            asset_btc_price = self.get_btc_price(currency)\n             usd_price = self.inquirer.find_usd_price(\n                 asset=currency,\n-                asset_btc_price=self.get_btc_price(currency)\n+                asset_btc_price=asset_btc_price\n             )\n \n             balance = dict()\n", "issue": "BTG or other assets with no market in bittrex crash the app\n## Problem Definition\r\n\r\nIf a user holds an asset in bittrex that does not have a market in the exchange, like say `BTG`, then during balances query rotkehlchen will crash with `ValueError: Bittrex: Could not find BTC market for \"BTG\"`\r\n\r\n## Task\r\n\r\nFix the crash, and use other sources for market price data in the case this happens.\n", "before_files": [{"content": "import time\nimport hmac\nimport hashlib\nfrom urllib.parse import urlencode\nfrom json.decoder import JSONDecodeError\n\nfrom typing import Dict, Tuple, Optional, Union, List, cast\nfrom rotkehlchen.utils import (\n    createTimeStamp,\n    get_pair_position,\n    rlk_jsonloads,\n    cache_response_timewise,\n)\nfrom rotkehlchen.exchange import Exchange\nfrom rotkehlchen.order_formatting import Trade\nfrom rotkehlchen.fval import FVal\nfrom rotkehlchen.errors import RemoteError\nfrom rotkehlchen.inquirer import Inquirer\nfrom rotkehlchen import typing\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nBITTREX_MARKET_METHODS = {\n    'getopenorders',\n    'cancel',\n    'sellmarket',\n    'selllimit',\n    'buymarket',\n    'buylimit'\n}\nBITTREX_ACCOUNT_METHODS = {\n    'getbalances',\n    'getbalance',\n    'getdepositaddress',\n    'withdraw',\n    'getorderhistory'\n}\n\n\ndef bittrex_pair_to_world(pair: str) -> str:\n    return pair.replace('-', '_')\n\n\ndef world_pair_to_bittrex(pair: str) -> str:\n    return pair.replace('_', '-')\n\n\ndef trade_from_bittrex(bittrex_trade: Dict) -> Trade:\n    \"\"\"Turn a bittrex trade returned from bittrex trade history to our common trade\n    history format\"\"\"\n    amount = FVal(bittrex_trade['Quantity']) - FVal(bittrex_trade['QuantityRemaining'])\n    rate = FVal(bittrex_trade['PricePerUnit'])\n    order_type = bittrex_trade['OrderType']\n    bittrex_price = FVal(bittrex_trade['Price'])\n    bittrex_commission = FVal(bittrex_trade['Commission'])\n    pair = bittrex_pair_to_world(bittrex_trade['Exchange'])\n    base_currency = get_pair_position(pair, 'first')\n    if order_type == 'LIMIT_BUY':\n        order_type = 'buy'\n        cost = bittrex_price + bittrex_commission\n        fee = bittrex_commission\n    elif order_type == 'LIMIT_SEL':\n        order_type = 'sell'\n        cost = bittrex_price - bittrex_commission\n        fee = bittrex_commission\n    else:\n        raise ValueError('Got unexpected order type \"{}\" for bittrex trade'.format(order_type))\n\n    return Trade(\n        timestamp=bittrex_trade['TimeStamp'],\n        pair=pair,\n        type=order_type,\n        rate=rate,\n        cost=cost,\n        cost_currency=base_currency,\n        fee=fee,\n        fee_currency=base_currency,\n        amount=amount,\n        location='bittrex'\n    )\n\n\nclass Bittrex(Exchange):\n    def __init__(\n            self,\n            api_key: typing.ApiKey,\n            secret: typing.ApiSecret,\n            inquirer: Inquirer,\n            data_dir: typing.FilePath\n    ):\n        super(Bittrex, self).__init__('bittrex', api_key, secret, data_dir)\n        self.apiversion = 'v1.1'\n        self.uri = 'https://bittrex.com/api/{}/'.format(self.apiversion)\n        self.inquirer = inquirer\n\n    def first_connection(self):\n        self.first_connection_made = True\n\n    def validate_api_key(self) -> Tuple[bool, str]:\n        try:\n            self.api_query('getbalance', {'currency': 'BTC'})\n        except ValueError as e:\n            error = str(e)\n            if error == 'APIKEY_INVALID':\n                return False, 'Provided API Key is invalid'\n            elif error == 'INVALID_SIGNATURE':\n                return False, 'Provided API Secret is invalid'\n            else:\n                raise\n        return True, ''\n\n    def api_query(\n            self,\n            method: str,\n            options: Optional[Dict] = None,\n    ) -> Union[List, Dict]:\n        \"\"\"\n        Queries Bittrex with given method and options\n        \"\"\"\n        if not options:\n            options = {}\n        nonce = str(int(time.time() * 1000))\n        method_type = 'public'\n\n        if method in BITTREX_MARKET_METHODS:\n            method_type = 'market'\n        elif method in BITTREX_ACCOUNT_METHODS:\n            method_type = 'account'\n\n        request_url = self.uri + method_type + '/' + method + '?'\n\n        if method_type != 'public':\n            request_url += 'apikey=' + self.api_key.decode() + \"&nonce=\" + nonce + '&'\n\n        request_url += urlencode(options)\n        signature = hmac.new(\n            self.secret,\n            request_url.encode(),\n            hashlib.sha512\n        ).hexdigest()\n        self.session.headers.update({'apisign': signature})\n        response = self.session.get(request_url)\n        try:\n            json_ret = rlk_jsonloads(response.text)\n        except JSONDecodeError:\n            raise RemoteError('Bittrex returned invalid JSON response')\n\n        if json_ret['success'] is not True:\n            raise RemoteError(json_ret['message'])\n        return json_ret['result']\n\n    def get_btc_price(self, asset: typing.BlockchainAsset) -> Optional[FVal]:\n        if asset == 'BTC':\n            return None\n        btc_price = None\n        btc_pair = 'BTC-' + asset\n        for market in self.markets:\n            if market['MarketName'] == btc_pair:\n                btc_price = FVal(market['Last'])\n                break\n\n        if btc_price is None:\n            raise ValueError('Bittrex: Could not find BTC market for \"{}\"'.format(asset))\n\n        return btc_price\n\n    @cache_response_timewise()\n    def query_balances(self) -> Tuple[Optional[dict], str]:\n        try:\n            self.markets = self.api_query('getmarketsummaries')\n            resp = self.api_query('getbalances')\n        except RemoteError as e:\n            msg = (\n                'Bittrex API request failed. Could not reach bittrex due '\n                'to {}'.format(e)\n            )\n            logger.error(msg)\n            return None, msg\n\n        returned_balances = dict()\n        for entry in resp:\n            currency = entry['Currency']\n            usd_price = self.inquirer.find_usd_price(\n                asset=currency,\n                asset_btc_price=self.get_btc_price(currency)\n            )\n\n            balance = dict()\n            balance['amount'] = FVal(entry['Balance'])\n            balance['usd_value'] = FVal(balance['amount']) * usd_price\n            returned_balances[currency] = balance\n\n        return returned_balances, ''\n\n    def query_trade_history(\n            self,\n            start_ts: typing.Timestamp,\n            end_ts: typing.Timestamp,\n            end_at_least_ts: typing.Timestamp,\n            market: Optional[str] = None,\n            count: Optional[int] = None,\n    ) -> List:\n\n        options: Dict[str, Union[str, int]] = dict()\n        cache = self.check_trades_cache(start_ts, end_at_least_ts)\n        cache = cast(List, cache)\n        if market is not None:\n            options['market'] = world_pair_to_bittrex(market)\n        elif cache is not None:\n            return cache\n\n        if count is not None:\n            options['count'] = count\n        order_history = self.api_query('getorderhistory', options)\n\n        returned_history = list()\n        for order in order_history:\n            order_timestamp = createTimeStamp(order['TimeStamp'], formatstr=\"%Y-%m-%dT%H:%M:%S.%f\")\n            if start_ts is not None and order_timestamp < start_ts:\n                continue\n            if end_ts is not None and order_timestamp > end_ts:\n                break\n            order['TimeStamp'] = order_timestamp\n            returned_history.append(order)\n\n        self.update_trades_cache(returned_history, start_ts, end_ts)\n        return returned_history\n", "path": "rotkehlchen/bittrex.py"}], "after_files": [{"content": "import hashlib\nimport hmac\nimport logging\nimport time\nfrom json.decoder import JSONDecodeError\nfrom typing import Dict, List, Optional, Tuple, Union, cast\nfrom urllib.parse import urlencode\n\nfrom rotkehlchen import typing\nfrom rotkehlchen.errors import RemoteError\nfrom rotkehlchen.exchange import Exchange\nfrom rotkehlchen.fval import FVal\nfrom rotkehlchen.inquirer import Inquirer\nfrom rotkehlchen.order_formatting import Trade\nfrom rotkehlchen.utils import (\n    cache_response_timewise,\n    createTimeStamp,\n    get_pair_position,\n    rlk_jsonloads,\n)\n\nlogger = logging.getLogger(__name__)\n\nBITTREX_MARKET_METHODS = {\n    'getopenorders',\n    'cancel',\n    'sellmarket',\n    'selllimit',\n    'buymarket',\n    'buylimit'\n}\nBITTREX_ACCOUNT_METHODS = {\n    'getbalances',\n    'getbalance',\n    'getdepositaddress',\n    'withdraw',\n    'getorderhistory'\n}\n\n\ndef bittrex_pair_to_world(pair: str) -> str:\n    return pair.replace('-', '_')\n\n\ndef world_pair_to_bittrex(pair: str) -> str:\n    return pair.replace('_', '-')\n\n\ndef trade_from_bittrex(bittrex_trade: Dict) -> Trade:\n    \"\"\"Turn a bittrex trade returned from bittrex trade history to our common trade\n    history format\"\"\"\n    amount = FVal(bittrex_trade['Quantity']) - FVal(bittrex_trade['QuantityRemaining'])\n    rate = FVal(bittrex_trade['PricePerUnit'])\n    order_type = bittrex_trade['OrderType']\n    bittrex_price = FVal(bittrex_trade['Price'])\n    bittrex_commission = FVal(bittrex_trade['Commission'])\n    pair = bittrex_pair_to_world(bittrex_trade['Exchange'])\n    base_currency = get_pair_position(pair, 'first')\n    if order_type == 'LIMIT_BUY':\n        order_type = 'buy'\n        cost = bittrex_price + bittrex_commission\n        fee = bittrex_commission\n    elif order_type == 'LIMIT_SEL':\n        order_type = 'sell'\n        cost = bittrex_price - bittrex_commission\n        fee = bittrex_commission\n    else:\n        raise ValueError('Got unexpected order type \"{}\" for bittrex trade'.format(order_type))\n\n    return Trade(\n        timestamp=bittrex_trade['TimeStamp'],\n        pair=pair,\n        type=order_type,\n        rate=rate,\n        cost=cost,\n        cost_currency=base_currency,\n        fee=fee,\n        fee_currency=base_currency,\n        amount=amount,\n        location='bittrex'\n    )\n\n\nclass Bittrex(Exchange):\n    def __init__(\n            self,\n            api_key: typing.ApiKey,\n            secret: typing.ApiSecret,\n            inquirer: Inquirer,\n            data_dir: typing.FilePath\n    ):\n        super(Bittrex, self).__init__('bittrex', api_key, secret, data_dir)\n        self.apiversion = 'v1.1'\n        self.uri = 'https://bittrex.com/api/{}/'.format(self.apiversion)\n        self.inquirer = inquirer\n\n    def first_connection(self):\n        self.first_connection_made = True\n\n    def validate_api_key(self) -> Tuple[bool, str]:\n        try:\n            self.api_query('getbalance', {'currency': 'BTC'})\n        except ValueError as e:\n            error = str(e)\n            if error == 'APIKEY_INVALID':\n                return False, 'Provided API Key is invalid'\n            elif error == 'INVALID_SIGNATURE':\n                return False, 'Provided API Secret is invalid'\n            else:\n                raise\n        return True, ''\n\n    def api_query(\n            self,\n            method: str,\n            options: Optional[Dict] = None,\n    ) -> Union[List, Dict]:\n        \"\"\"\n        Queries Bittrex with given method and options\n        \"\"\"\n        if not options:\n            options = {}\n        nonce = str(int(time.time() * 1000))\n        method_type = 'public'\n\n        if method in BITTREX_MARKET_METHODS:\n            method_type = 'market'\n        elif method in BITTREX_ACCOUNT_METHODS:\n            method_type = 'account'\n\n        request_url = self.uri + method_type + '/' + method + '?'\n\n        if method_type != 'public':\n            request_url += 'apikey=' + self.api_key.decode() + \"&nonce=\" + nonce + '&'\n\n        request_url += urlencode(options)\n        signature = hmac.new(\n            self.secret,\n            request_url.encode(),\n            hashlib.sha512\n        ).hexdigest()\n        self.session.headers.update({'apisign': signature})\n        response = self.session.get(request_url)\n        try:\n            json_ret = rlk_jsonloads(response.text)\n        except JSONDecodeError:\n            raise RemoteError('Bittrex returned invalid JSON response')\n\n        if json_ret['success'] is not True:\n            raise RemoteError(json_ret['message'])\n        return json_ret['result']\n\n    def get_btc_price(self, asset: typing.BlockchainAsset) -> Optional[FVal]:\n        if asset == 'BTC':\n            return None\n        btc_price = None\n        btc_pair = 'BTC-' + asset\n        for market in self.markets:\n            if market['MarketName'] == btc_pair:\n                btc_price = FVal(market['Last'])\n                break\n\n        return btc_price\n\n    @cache_response_timewise()\n    def query_balances(self) -> Tuple[Optional[dict], str]:\n        try:\n            self.markets = self.api_query('getmarketsummaries')\n            resp = self.api_query('getbalances')\n        except RemoteError as e:\n            msg = (\n                'Bittrex API request failed. Could not reach bittrex due '\n                'to {}'.format(e)\n            )\n            logger.error(msg)\n            return None, msg\n\n        returned_balances = dict()\n        for entry in resp:\n            currency = entry['Currency']\n            asset_btc_price = self.get_btc_price(currency)\n            usd_price = self.inquirer.find_usd_price(\n                asset=currency,\n                asset_btc_price=asset_btc_price\n            )\n\n            balance = dict()\n            balance['amount'] = FVal(entry['Balance'])\n            balance['usd_value'] = FVal(balance['amount']) * usd_price\n            returned_balances[currency] = balance\n\n        return returned_balances, ''\n\n    def query_trade_history(\n            self,\n            start_ts: typing.Timestamp,\n            end_ts: typing.Timestamp,\n            end_at_least_ts: typing.Timestamp,\n            market: Optional[str] = None,\n            count: Optional[int] = None,\n    ) -> List:\n\n        options: Dict[str, Union[str, int]] = dict()\n        cache = self.check_trades_cache(start_ts, end_at_least_ts)\n        cache = cast(List, cache)\n        if market is not None:\n            options['market'] = world_pair_to_bittrex(market)\n        elif cache is not None:\n            return cache\n\n        if count is not None:\n            options['count'] = count\n        order_history = self.api_query('getorderhistory', options)\n\n        returned_history = list()\n        for order in order_history:\n            order_timestamp = createTimeStamp(order['TimeStamp'], formatstr=\"%Y-%m-%dT%H:%M:%S.%f\")\n            if start_ts is not None and order_timestamp < start_ts:\n                continue\n            if end_ts is not None and order_timestamp > end_ts:\n                break\n            order['TimeStamp'] = order_timestamp\n            returned_history.append(order)\n\n        self.update_trades_cache(returned_history, start_ts, end_ts)\n        return returned_history\n", "path": "rotkehlchen/bittrex.py"}]}