Skip to content

Commit

Permalink
Merge pull request hummingbot#3165 from TheHolyRoger/fix/hitbtc-balan…
Browse files Browse the repository at this point in the history
…ce-update

[v0.38] Fix / HitBTC Balance updates and tests for USD/USDT
  • Loading branch information
dennisocana authored Apr 6, 2021
2 parents dd9cc4a + d83cd37 commit abe7e3c
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 32 deletions.
3 changes: 2 additions & 1 deletion hummingbot/connector/exchange/hitbtc/hitbtc_exchange.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
from hummingbot.connector.exchange.hitbtc.hitbtc_utils import (
convert_from_exchange_trading_pair,
convert_to_exchange_trading_pair,
translate_asset,
get_new_client_order_id,
aiohttp_response_with_errors,
retry_sleep_time,
Expand Down Expand Up @@ -740,7 +741,7 @@ def _process_balance_message(self, balance_update):
local_asset_names = set(self._account_balances.keys())
remote_asset_names = set()
for account in balance_update:
asset_name = account["currency"]
asset_name = translate_asset(account["currency"])
self._account_available_balances[asset_name] = Decimal(str(account["available"]))
self._account_balances[asset_name] = Decimal(str(account["reserved"])) + Decimal(str(account["available"]))
remote_asset_names.add(asset_name)
Expand Down
28 changes: 16 additions & 12 deletions hummingbot/connector/exchange/hitbtc/hitbtc_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,22 @@ def split_trading_pair(trading_pair: str) -> Optional[Tuple[str, str]]:
return None


def translate_tokens(hb_trading_pair: str) -> str:
token_replacements = [
def translate_asset(asset_name: str) -> str:
asset_replacements = [
("USD", "USDT"),
]
tokens = hb_trading_pair.split('-')
for token_replacement in token_replacements:
for x in range(len(tokens)):
for inv in [0, 1]:
if tokens[x] == token_replacement[inv]:
tokens[x] = token_replacement[(0 if inv else 1)]
break
return '-'.join(tokens)
for asset_replacement in asset_replacements:
for inv in [0, 1]:
if asset_name == asset_replacement[inv]:
return asset_replacement[(0 if inv else 1)]
return asset_name


def translate_assets(hb_trading_pair: str) -> str:
assets = hb_trading_pair.split('-')
for x in range(len(assets)):
assets[x] = translate_asset(assets[x])
return '-'.join(assets)


def convert_from_exchange_trading_pair(ex_trading_pair: str) -> Optional[str]:
Expand All @@ -77,12 +81,12 @@ def convert_from_exchange_trading_pair(ex_trading_pair: str) -> Optional[str]:
return None
# HitBTC uses uppercase (BTCUSDT)
base_asset, quote_asset = split_trading_pair(ex_trading_pair)
return translate_tokens(f"{base_asset.upper()}-{quote_asset.upper()}")
return translate_assets(f"{base_asset.upper()}-{quote_asset.upper()}")


def convert_to_exchange_trading_pair(hb_trading_pair: str) -> str:
# HitBTC uses uppercase (BTCUSDT)
return translate_tokens(hb_trading_pair).replace("-", "").upper()
return translate_assets(hb_trading_pair).replace("-", "").upper()


def get_new_client_order_id(is_buy: bool, trading_pair: str) -> str:
Expand Down
26 changes: 13 additions & 13 deletions test/connector/exchange/hitbtc/test_hitbtc_exchange.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class HitbtcExchangeUnitTest(unittest.TestCase):
]
connector: HitbtcExchange
event_logger: EventLogger
trading_pair = "BTC-USD"
trading_pair = "BTC-USDT"
base_token, quote_token = trading_pair.split("-")
stack: contextlib.ExitStack

Expand Down Expand Up @@ -144,7 +144,7 @@ def test_estimate_fee(self):
def test_buy_and_sell(self):
price = self.connector.get_price(self.trading_pair, True) * Decimal("1.02")
price = self.connector.quantize_order_price(self.trading_pair, price)
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0001"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0002"))
quote_bal = self.connector.get_available_balance(self.quote_token)
base_bal = self.connector.get_available_balance(self.base_token)

Expand All @@ -159,7 +159,7 @@ def test_buy_and_sell(self):
self.assertEqual(order_id, order_completed_event.order_id)
self.assertEqual(amount, order_completed_event.base_asset_amount)
self.assertEqual("BTC", order_completed_event.base_asset)
self.assertEqual("USD", order_completed_event.quote_asset)
self.assertEqual("USDT", order_completed_event.quote_asset)
self.assertAlmostEqual(base_amount_traded, order_completed_event.base_asset_amount)
self.assertAlmostEqual(quote_amount_traded, order_completed_event.quote_asset_amount)
self.assertGreater(order_completed_event.fee_amount, Decimal(0))
Expand All @@ -178,7 +178,7 @@ def test_buy_and_sell(self):
# Try to sell back the same amount to the exchange, and watch for completion event.
price = self.connector.get_price(self.trading_pair, True) * Decimal("0.98")
price = self.connector.quantize_order_price(self.trading_pair, price)
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0001"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0002"))
order_id = self._place_order(False, amount, OrderType.LIMIT, price, 2)
order_completed_event = self.ev_loop.run_until_complete(self.event_logger.wait_for(SellOrderCompletedEvent))
trade_events = [t for t in self.event_logger.event_log if isinstance(t, OrderFilledEvent)]
Expand All @@ -189,7 +189,7 @@ def test_buy_and_sell(self):
self.assertEqual(order_id, order_completed_event.order_id)
self.assertEqual(amount, order_completed_event.base_asset_amount)
self.assertEqual("BTC", order_completed_event.base_asset)
self.assertEqual("USD", order_completed_event.quote_asset)
self.assertEqual("USDT", order_completed_event.quote_asset)
self.assertAlmostEqual(base_amount_traded, order_completed_event.base_asset_amount)
self.assertAlmostEqual(quote_amount_traded, order_completed_event.quote_asset_amount)
self.assertGreater(order_completed_event.fee_amount, Decimal(0))
Expand All @@ -206,7 +206,7 @@ def test_buy_and_sell(self):
def test_limit_makers_unfilled(self):
price = self.connector.get_price(self.trading_pair, True) * Decimal("0.8")
price = self.connector.quantize_order_price(self.trading_pair, price)
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0001"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0002"))
self.ev_loop.run_until_complete(asyncio.sleep(1))
self.ev_loop.run_until_complete(self.connector._update_balances())
self.ev_loop.run_until_complete(asyncio.sleep(2))
Expand All @@ -231,7 +231,7 @@ def test_limit_makers_unfilled(self):

price = self.connector.get_price(self.trading_pair, True) * Decimal("1.2")
price = self.connector.quantize_order_price(self.trading_pair, price)
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0001"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0002"))

cl_order_id = self._place_order(False, amount, OrderType.LIMIT_MAKER, price, 2)
order_created_event = self.ev_loop.run_until_complete(self.event_logger.wait_for(SellOrderCreatedEvent))
Expand Down Expand Up @@ -261,7 +261,7 @@ def test_cancel_all(self):
ask_price = self.connector.get_price(self.trading_pair, False)
bid_price = self.connector.quantize_order_price(self.trading_pair, bid_price * Decimal("0.9"))
ask_price = self.connector.quantize_order_price(self.trading_pair, ask_price * Decimal("1.1"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0001"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0002"))

buy_id = self._place_order(True, amount, OrderType.LIMIT, bid_price, 1)
sell_id = self._place_order(False, amount, OrderType.LIMIT, ask_price, 2)
Expand All @@ -280,14 +280,14 @@ def test_order_quantized_values(self):

# Make sure there's enough balance to make the limit orders.
self.assertGreater(self.connector.get_balance("BTC"), Decimal("0.0005"))
self.assertGreater(self.connector.get_balance("USD"), Decimal("10"))
self.assertGreater(self.connector.get_balance("USDT"), Decimal("10"))

# Intentionally set some prices with too many decimal places s.t. they
# need to be quantized. Also, place them far away from the mid-price s.t. they won't
# get filled during the test.
bid_price = self.connector.quantize_order_price(self.trading_pair, mid_price * Decimal("0.9333192292111341"))
ask_price = self.connector.quantize_order_price(self.trading_pair, mid_price * Decimal("1.1492431474884933"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.000123456"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.000223456"))

# Test bid order
cl_order_id_1 = self._place_order(True, amount, OrderType.LIMIT, bid_price, 1)
Expand Down Expand Up @@ -321,7 +321,7 @@ def test_orders_saving_and_restoration(self):
price: Decimal = current_bid_price * Decimal("0.8")
price = self.connector.quantize_order_price(self.trading_pair, price)

amount: Decimal = Decimal("0.0001")
amount: Decimal = Decimal("0.0002")
amount = self.connector.quantize_order_amount(self.trading_pair, amount)

cl_order_id = self._place_order(True, amount, OrderType.LIMIT_MAKER, price, 1)
Expand Down Expand Up @@ -402,7 +402,7 @@ def test_filled_orders_recorded(self):
# Try to buy some token from the exchange, and watch for completion event.
price = self.connector.get_price(self.trading_pair, True) * Decimal("1.05")
price = self.connector.quantize_order_price(self.trading_pair, price)
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0001"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0002"))

order_id = self._place_order(True, amount, OrderType.LIMIT, price, 1)
self.ev_loop.run_until_complete(self.event_logger.wait_for(BuyOrderCompletedEvent))
Expand All @@ -414,7 +414,7 @@ def test_filled_orders_recorded(self):
# Try to sell back the same amount to the exchange, and watch for completion event.
price = self.connector.get_price(self.trading_pair, True) * Decimal("0.95")
price = self.connector.quantize_order_price(self.trading_pair, price)
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0001"))
amount = self.connector.quantize_order_amount(self.trading_pair, Decimal("0.0002"))
order_id = self._place_order(False, amount, OrderType.LIMIT, price, 2)
self.ev_loop.run_until_complete(self.event_logger.wait_for(SellOrderCompletedEvent))
self.ev_loop.run_until_complete(asyncio.sleep(1))
Expand Down
10 changes: 5 additions & 5 deletions test/connector/exchange/hitbtc/test_hitbtc_order_book_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ class HitbtcOrderBookTrackerUnitTest(unittest.TestCase):
OrderBookEvent.TradeEvent
]
trading_pairs: List[str] = [
"BTC-USD",
"ETH-USD",
"BTC-USDT",
"ETH-USDT",
]

@classmethod
Expand Down Expand Up @@ -87,7 +87,7 @@ def test_tracker_integrity(self):
# Wait 5 seconds to process some diffs.
self.ev_loop.run_until_complete(asyncio.sleep(5.0))
order_books: Dict[str, OrderBook] = self.order_book_tracker.order_books
eth_usd: OrderBook = order_books["ETH-USD"]
eth_usd: OrderBook = order_books["ETH-USDT"]
self.assertIsNot(eth_usd.last_diff_uid, 0)
self.assertGreaterEqual(eth_usd.get_price_for_volume(True, 10).result_price,
eth_usd.get_price(True))
Expand All @@ -96,8 +96,8 @@ def test_tracker_integrity(self):

def test_api_get_last_traded_prices(self):
prices = self.ev_loop.run_until_complete(
HitbtcAPIOrderBookDataSource.get_last_traded_prices(["BTC-USD", "LTC-BTC"]))
HitbtcAPIOrderBookDataSource.get_last_traded_prices(["BTC-USDT", "LTC-BTC"]))
for key, value in prices.items():
print(f"{key} last_trade_price: {value}")
self.assertGreater(prices["BTC-USD"], 1000)
self.assertGreater(prices["BTC-USDT"], 1000)
self.assertLess(prices["LTC-BTC"], 1)
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class HitbtcUserStreamTrackerUnitTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
cls.trading_pairs = ["BTC-USD"]
cls.trading_pairs = ["BTC-USDT"]
cls.user_stream_tracker: HitbtcUserStreamTracker = HitbtcUserStreamTracker(
hitbtc_auth=HitbtcAuth(cls.api_key, cls.api_secret),
trading_pairs=cls.trading_pairs)
Expand Down

0 comments on commit abe7e3c

Please sign in to comment.