code
stringlengths
541
76.7k
apis
list
extract_api
stringlengths
178
38.5k
#!/usr/bin/env python import unittest from hummingbot.client.config.security import Security from hummingbot.client import settings from hummingbot.client.config.global_config_map import global_config_map from hummingbot.client.config.config_crypt import encrypt_n_save_config_value import os import shutil import asyncio temp_folder = "conf_testing_temp/" class ConfigSecurityNewPasswordUnitTest(unittest.TestCase): def setUp(self): settings.CONF_FILE_PATH = temp_folder global_config_map["key_file_path"].value = temp_folder os.makedirs(settings.CONF_FILE_PATH, exist_ok=False) def tearDown(self): shutil.rmtree(temp_folder) def test_new_password_process(self): # empty folder, new password is required self.assertFalse(Security.any_encryped_files()) self.assertTrue(Security.new_password_required()) # login will pass with any password result = Security.login("a") self.assertTrue(result) Security.update_secure_config("new_key", "new_value") self.assertTrue(os.path.exists(f"{temp_folder}encrypted_new_key.json")) self.assertTrue(Security.encrypted_file_exists("new_key")) class ConfigSecurityExistingPasswordUnitTest(unittest.TestCase): def setUp(self): settings.CONF_FILE_PATH = temp_folder global_config_map["key_file_path"].value = temp_folder os.makedirs(settings.CONF_FILE_PATH, exist_ok=False) encrypt_n_save_config_value("test_key_1", "test_value_1", "a") encrypt_n_save_config_value("test_key_2", "test_value_2", "a") def tearDown(self): shutil.rmtree(temp_folder) async def _test_existing_password(self): # check the 2 encrypted files exist self.assertTrue(os.path.exists(f"{temp_folder}encrypted_test_key_1.json")) self.assertTrue(os.path.exists(f"{temp_folder}encrypted_test_key_2.json")) self.assertTrue(Security.any_encryped_files()) self.assertFalse(Security.new_password_required()) # login fails with incorrect password result = Security.login("b") self.assertFalse(result) # login passes with correct password result = Security.login("a") self.assertTrue(result) # right after logging in, the decryption shouldn't finished yet self.assertFalse(Security.is_decryption_done()) await Security.wait_til_decryption_done() self.assertEqual(len(Security.all_decrypted_values()), 2) config_value = Security.decrypted_value("test_key_1") self.assertEqual("test_value_1", config_value) Security.update_secure_config("test_key_1", "new_value") self.assertEqual("new_value", Security.decrypted_value("test_key_1")) def test_existing_password(self): loop = asyncio.get_event_loop() loop.run_until_complete(self._test_existing_password())
[ "hummingbot.client.config.security.Security.any_encryped_files", "hummingbot.client.config.security.Security.wait_til_decryption_done", "hummingbot.client.config.security.Security.all_decrypted_values", "hummingbot.client.config.security.Security.update_secure_config", "hummingbot.client.config.security.Sec...
[((559, 611), 'os.makedirs', 'os.makedirs', (['settings.CONF_FILE_PATH'], {'exist_ok': '(False)'}), '(settings.CONF_FILE_PATH, exist_ok=False)\n', (570, 611), False, 'import os\n'), ((645, 671), 'shutil.rmtree', 'shutil.rmtree', (['temp_folder'], {}), '(temp_folder)\n', (658, 671), False, 'import shutil\n'), ((938, 957), 'hummingbot.client.config.security.Security.login', 'Security.login', (['"""a"""'], {}), "('a')\n", (952, 957), False, 'from hummingbot.client.config.security import Security\n'), ((998, 1051), 'hummingbot.client.config.security.Security.update_secure_config', 'Security.update_secure_config', (['"""new_key"""', '"""new_value"""'], {}), "('new_key', 'new_value')\n", (1027, 1051), False, 'from hummingbot.client.config.security import Security\n'), ((1404, 1456), 'os.makedirs', 'os.makedirs', (['settings.CONF_FILE_PATH'], {'exist_ok': '(False)'}), '(settings.CONF_FILE_PATH, exist_ok=False)\n', (1415, 1456), False, 'import os\n'), ((1465, 1527), 'hummingbot.client.config.config_crypt.encrypt_n_save_config_value', 'encrypt_n_save_config_value', (['"""test_key_1"""', '"""test_value_1"""', '"""a"""'], {}), "('test_key_1', 'test_value_1', 'a')\n", (1492, 1527), False, 'from hummingbot.client.config.config_crypt import encrypt_n_save_config_value\n'), ((1536, 1598), 'hummingbot.client.config.config_crypt.encrypt_n_save_config_value', 'encrypt_n_save_config_value', (['"""test_key_2"""', '"""test_value_2"""', '"""a"""'], {}), "('test_key_2', 'test_value_2', 'a')\n", (1563, 1598), False, 'from hummingbot.client.config.config_crypt import encrypt_n_save_config_value\n'), ((1632, 1658), 'shutil.rmtree', 'shutil.rmtree', (['temp_folder'], {}), '(temp_folder)\n', (1645, 1658), False, 'import shutil\n'), ((2092, 2111), 'hummingbot.client.config.security.Security.login', 'Security.login', (['"""b"""'], {}), "('b')\n", (2106, 2111), False, 'from hummingbot.client.config.security import Security\n'), ((2207, 2226), 'hummingbot.client.config.security.Security.login', 'Security.login', (['"""a"""'], {}), "('a')\n", (2221, 2226), False, 'from hummingbot.client.config.security import Security\n'), ((2526, 2564), 'hummingbot.client.config.security.Security.decrypted_value', 'Security.decrypted_value', (['"""test_key_1"""'], {}), "('test_key_1')\n", (2550, 2564), False, 'from hummingbot.client.config.security import Security\n'), ((2628, 2684), 'hummingbot.client.config.security.Security.update_secure_config', 'Security.update_secure_config', (['"""test_key_1"""', '"""new_value"""'], {}), "('test_key_1', 'new_value')\n", (2657, 2684), False, 'from hummingbot.client.config.security import Security\n'), ((2817, 2841), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2839, 2841), False, 'import asyncio\n'), ((788, 817), 'hummingbot.client.config.security.Security.any_encryped_files', 'Security.any_encryped_files', ([], {}), '()\n', (815, 817), False, 'from hummingbot.client.config.security import Security\n'), ((843, 875), 'hummingbot.client.config.security.Security.new_password_required', 'Security.new_password_required', ([], {}), '()\n', (873, 875), False, 'from hummingbot.client.config.security import Security\n'), ((1076, 1130), 'os.path.exists', 'os.path.exists', (['f"""{temp_folder}encrypted_new_key.json"""'], {}), "(f'{temp_folder}encrypted_new_key.json')\n", (1090, 1130), False, 'import os\n'), ((1156, 1197), 'hummingbot.client.config.security.Security.encrypted_file_exists', 'Security.encrypted_file_exists', (['"""new_key"""'], {}), "('new_key')\n", (1186, 1197), False, 'from hummingbot.client.config.security import Security\n'), ((1773, 1830), 'os.path.exists', 'os.path.exists', (['f"""{temp_folder}encrypted_test_key_1.json"""'], {}), "(f'{temp_folder}encrypted_test_key_1.json')\n", (1787, 1830), False, 'import os\n'), ((1856, 1913), 'os.path.exists', 'os.path.exists', (['f"""{temp_folder}encrypted_test_key_2.json"""'], {}), "(f'{temp_folder}encrypted_test_key_2.json')\n", (1870, 1913), False, 'import os\n'), ((1939, 1968), 'hummingbot.client.config.security.Security.any_encryped_files', 'Security.any_encryped_files', ([], {}), '()\n', (1966, 1968), False, 'from hummingbot.client.config.security import Security\n'), ((1995, 2027), 'hummingbot.client.config.security.Security.new_password_required', 'Security.new_password_required', ([], {}), '()\n', (2025, 2027), False, 'from hummingbot.client.config.security import Security\n'), ((2356, 2385), 'hummingbot.client.config.security.Security.is_decryption_done', 'Security.is_decryption_done', ([], {}), '()\n', (2383, 2385), False, 'from hummingbot.client.config.security import Security\n'), ((2401, 2436), 'hummingbot.client.config.security.Security.wait_til_decryption_done', 'Security.wait_til_decryption_done', ([], {}), '()\n', (2434, 2436), False, 'from hummingbot.client.config.security import Security\n'), ((2723, 2761), 'hummingbot.client.config.security.Security.decrypted_value', 'Security.decrypted_value', (['"""test_key_1"""'], {}), "('test_key_1')\n", (2747, 2761), False, 'from hummingbot.client.config.security import Security\n'), ((2466, 2497), 'hummingbot.client.config.security.Security.all_decrypted_values', 'Security.all_decrypted_values', ([], {}), '()\n', (2495, 2497), False, 'from hummingbot.client.config.security import Security\n')]
#!/usr/bin/env python import asyncio import cytoolz from hexbytes import HexBytes import logging import math from typing import ( List, Dict, Iterable, Set, Optional ) from web3 import Web3 from web3.contract import Contract from web3.datastructures import AttributeDict from hummingbot.logger import HummingbotLogger from hummingbot.core.event.events import ( NewBlocksWatcherEvent, WalletReceivedAssetEvent, TokenApprovedEvent, ERC20WatcherEvent ) from hummingbot.wallet.ethereum.erc20_token import ERC20Token from hummingbot.core.event.event_forwarder import EventForwarder from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from .base_watcher import BaseWatcher from .new_blocks_watcher import NewBlocksWatcher from .contract_event_logs import ContractEventLogger weth_sai_symbols: Set[str] = {"WETH", "SAI"} TRANSFER_EVENT_NAME = "Transfer" APPROVAL_EVENT_NAME = "Approval" class ERC20EventsWatcher(BaseWatcher): _w2ew_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._w2ew_logger is None: cls._w2ew_logger = logging.getLogger(__name__) return cls._w2ew_logger @staticmethod def is_weth_sai(symbol: str) -> bool: global weth_sai_symbols return symbol in weth_sai_symbols def __init__(self, w3: Web3, blocks_watcher: NewBlocksWatcher, contract_addresses: List[str], contract_abi: List[any], watch_addresses: Iterable[str]): if len(contract_addresses) != len(contract_abi): raise ValueError("Each entry in contract_addresses must have a corresponding entry in contract_abi.") super().__init__(w3) self._blocks_watcher: NewBlocksWatcher = blocks_watcher self._addresses_to_contracts: Dict[str, Contract] = { address: w3.eth.contract(address=address, abi=abi) for address, abi in zip(contract_addresses, contract_abi) } self._watch_addresses: Set[str] = set(watch_addresses) self._address_to_asset_name_map: Dict[str, str] = {} self._asset_decimals: Dict[str, int] = {} self._contract_event_loggers: Dict[str, ContractEventLogger] = {} self._new_blocks_queue: asyncio.Queue = asyncio.Queue() self._event_forwarder: EventForwarder = EventForwarder(self.did_receive_new_blocks) self._poll_erc20_logs_task: Optional[asyncio.Task] = None async def start_network(self): if len(self._address_to_asset_name_map) < len(self._addresses_to_contracts): for address, contract in self._addresses_to_contracts.items(): contract: Contract = contract try: asset_name: str = await self.call_async(ERC20Token.get_symbol_from_contract, contract) decimals: int = await self.call_async(contract.functions.decimals().call) except asyncio.CancelledError: raise except Exception: self.logger().network("Error fetching ERC20 token information.", app_warning_msg="Could not fetch ERC20 token information. Check Ethereum " "node connection.", exc_info=True) self._address_to_asset_name_map[address] = asset_name self._asset_decimals[asset_name] = decimals self._contract_event_loggers[address] = ContractEventLogger(self._w3, address, contract.abi) if self._poll_erc20_logs_task is not None: await self.stop_network() self._blocks_watcher.add_listener(NewBlocksWatcherEvent.NewBlocks, self._event_forwarder) self._poll_erc20_logs_task = safe_ensure_future(self.poll_erc20_logs_loop()) async def stop_network(self): if self._poll_erc20_logs_task is not None: self._poll_erc20_logs_task.cancel() self._poll_erc20_logs_task = None self._blocks_watcher.remove_listener(NewBlocksWatcherEvent.NewBlocks, self._event_forwarder) def did_receive_new_blocks(self, new_blocks: List[AttributeDict]): self._new_blocks_queue.put_nowait(new_blocks) async def poll_erc20_logs_loop(self): while True: try: new_blocks: List[AttributeDict] = await self._new_blocks_queue.get() block_hashes: List[HexBytes] = [block["hash"] for block in new_blocks] transfer_tasks = [] approval_tasks = [] for address in self._addresses_to_contracts.keys(): contract_event_logger: ContractEventLogger = self._contract_event_loggers[address] transfer_tasks.append( contract_event_logger.get_new_entries_from_logs(TRANSFER_EVENT_NAME, block_hashes) ) approval_tasks.append( contract_event_logger.get_new_entries_from_logs(APPROVAL_EVENT_NAME, block_hashes) ) raw_transfer_entries = await safe_gather(*transfer_tasks) raw_approval_entries = await safe_gather(*approval_tasks) transfer_entries = list(cytoolz.concat(raw_transfer_entries)) approval_entries = list(cytoolz.concat(raw_approval_entries)) for transfer_entry in transfer_entries: await self._handle_event_data(transfer_entry) for approval_entry in approval_entries: await self._handle_event_data(approval_entry) except asyncio.CancelledError: raise except asyncio.TimeoutError: continue except Exception: self.logger().network(f"Error fetching new events from ERC20 contracts.", exc_info=True, app_warning_msg=f"Error fetching new events from ERC20 contracts. " f"Check wallet network connection") async def _handle_event_data(self, event_data: AttributeDict): event_type: str = event_data["event"] timestamp: float = float(await self._blocks_watcher.get_timestamp_for_block(event_data["blockHash"])) tx_hash: str = event_data["transactionHash"].hex() contract_address: str = event_data["address"] token_asset_name: str = self._address_to_asset_name_map.get(contract_address) if event_type == TRANSFER_EVENT_NAME: self.handle_incoming_tokens_event(timestamp, tx_hash, token_asset_name, event_data) elif event_type == APPROVAL_EVENT_NAME: self.handle_approve_tokens_event(timestamp, tx_hash, token_asset_name, event_data) else: self.logger().warning(f"Received log with unrecognized event type - '{event_type}'.") def handle_incoming_tokens_event(self, timestamp: float, tx_hash: str, asset_name: str, event_data: AttributeDict): event_args: AttributeDict = event_data["args"] is_weth_sai: bool = self.is_weth_sai(asset_name) decimals: int = self._asset_decimals[asset_name] if is_weth_sai and hasattr(event_args, "wad"): raw_amount: int = event_args.wad normalized_amount: float = raw_amount * math.pow(10, -decimals) from_address: str = event_args.src to_address: str = event_args.dst else: raw_amount: int = event_args["value"] normalized_amount: float = raw_amount * math.pow(10, -decimals) from_address: str = event_args["from"] to_address: str = event_args["to"] if to_address not in self._watch_addresses: return self.trigger_event(ERC20WatcherEvent.ReceivedToken, WalletReceivedAssetEvent(timestamp, tx_hash, from_address, to_address, asset_name, normalized_amount, raw_amount)) def handle_approve_tokens_event(self, timestamp: float, tx_hash: str, asset_name: str, event_data: AttributeDict): event_args: AttributeDict = event_data["args"] is_weth_sai: bool = self.is_weth_sai(asset_name) decimals: int = self._asset_decimals[asset_name] if is_weth_sai and hasattr(event_args, "wad"): raw_amount: int = event_args.wad owner_address: str = event_args.src spender_address: str = event_args.guy else: raw_amount: int = event_args["value"] owner_address: str = event_args["owner"] spender_address: str = event_args["spender"] if owner_address not in self._watch_addresses: return normalized_amount: float = raw_amount * math.pow(10, -decimals) self.trigger_event(ERC20WatcherEvent.ApprovedToken, TokenApprovedEvent(timestamp, tx_hash, owner_address, spender_address, asset_name, normalized_amount, raw_amount))
[ "hummingbot.core.event.events.TokenApprovedEvent", "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.core.event.event_forwarder.EventForwarder", "hummingbot.core.event.events.WalletReceivedAssetEvent" ]
[((2381, 2396), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (2394, 2396), False, 'import asyncio\n'), ((2445, 2488), 'hummingbot.core.event.event_forwarder.EventForwarder', 'EventForwarder', (['self.did_receive_new_blocks'], {}), '(self.did_receive_new_blocks)\n', (2459, 2488), False, 'from hummingbot.core.event.event_forwarder import EventForwarder\n'), ((1178, 1205), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1195, 1205), False, 'import logging\n'), ((8194, 8311), 'hummingbot.core.event.events.WalletReceivedAssetEvent', 'WalletReceivedAssetEvent', (['timestamp', 'tx_hash', 'from_address', 'to_address', 'asset_name', 'normalized_amount', 'raw_amount'], {}), '(timestamp, tx_hash, from_address, to_address,\n asset_name, normalized_amount, raw_amount)\n', (8218, 8311), False, 'from hummingbot.core.event.events import NewBlocksWatcherEvent, WalletReceivedAssetEvent, TokenApprovedEvent, ERC20WatcherEvent\n'), ((9199, 9222), 'math.pow', 'math.pow', (['(10)', '(-decimals)'], {}), '(10, -decimals)\n', (9207, 9222), False, 'import math\n'), ((9310, 9427), 'hummingbot.core.event.events.TokenApprovedEvent', 'TokenApprovedEvent', (['timestamp', 'tx_hash', 'owner_address', 'spender_address', 'asset_name', 'normalized_amount', 'raw_amount'], {}), '(timestamp, tx_hash, owner_address, spender_address,\n asset_name, normalized_amount, raw_amount)\n', (9328, 9427), False, 'from hummingbot.core.event.events import NewBlocksWatcherEvent, WalletReceivedAssetEvent, TokenApprovedEvent, ERC20WatcherEvent\n'), ((7680, 7703), 'math.pow', 'math.pow', (['(10)', '(-decimals)'], {}), '(10, -decimals)\n', (7688, 7703), False, 'import math\n'), ((7912, 7935), 'math.pow', 'math.pow', (['(10)', '(-decimals)'], {}), '(10, -decimals)\n', (7920, 7935), False, 'import math\n'), ((5414, 5442), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*transfer_tasks'], {}), '(*transfer_tasks)\n', (5425, 5442), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((5488, 5516), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*approval_tasks'], {}), '(*approval_tasks)\n', (5499, 5516), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((5557, 5593), 'cytoolz.concat', 'cytoolz.concat', (['raw_transfer_entries'], {}), '(raw_transfer_entries)\n', (5571, 5593), False, 'import cytoolz\n'), ((5635, 5671), 'cytoolz.concat', 'cytoolz.concat', (['raw_approval_entries'], {}), '(raw_approval_entries)\n', (5649, 5671), False, 'import cytoolz\n')]
from hummingbot.cli.config.config_var import ConfigVar from hummingbot.cli.config.config_validators import ( is_exchange, is_valid_market_symbol, ) from hummingbot.cli.settings import ( required_exchanges, EXAMPLE_PAIRS, ) def maker_symbol_prompt(): maker_market = cross_exchange_market_making_config_map.get("maker_market").value example = EXAMPLE_PAIRS.get(maker_market) return "Enter the token symbol you would like to trade on %s%s >>> " \ % (maker_market, f" (e.g. {example})" if example else "") def taker_symbol_prompt(): taker_market = cross_exchange_market_making_config_map.get("taker_market").value example = EXAMPLE_PAIRS.get(taker_market) return "Enter the token symbol you would like to trade on %s%s >>> " \ % (taker_market, f" (e.g. {example})" if example else "") # strategy specific validators def is_valid_maker_market_symbol(value: str) -> bool: maker_market = cross_exchange_market_making_config_map.get("maker_market").value return is_valid_market_symbol(maker_market, value) def is_valid_taker_market_symbol(value: str) -> bool: taker_market = cross_exchange_market_making_config_map.get("taker_market").value return is_valid_market_symbol(taker_market, value) cross_exchange_market_making_config_map = { "maker_market": ConfigVar(key="maker_market", prompt="Enter your maker exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value)), "taker_market": ConfigVar(key="taker_market", prompt="Enter your taker exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value)), "maker_market_symbol": ConfigVar(key="maker_market_symbol", prompt=maker_symbol_prompt, validator=is_valid_maker_market_symbol), "taker_market_symbol": ConfigVar(key="taker_market_symbol", prompt=taker_symbol_prompt, validator=is_valid_taker_market_symbol), "min_profitability": ConfigVar(key="min_profitability", prompt="What is the minimum profitability for you to make a trade? "\ "(Enter 0.01 to indicate 1%) >>> ", default=0.003, type_str="float"), "trade_size_override": ConfigVar(key="trade_size_override", prompt="What is your preferred trade size? (denominated in " "the quote asset) >>> ", required_if=lambda: False, default=0.0, type_str="float"), "top_depth_tolerance": ConfigVar(key="top_depth_tolerance", prompt="What is the maximum depth you would go into th" "e order book to make a trade? >>> ", type_str="list", required_if=lambda: False, default=[ ["^.+(USDT|USDC|USDS|DAI|PAX|TUSD)$", 1000], ["^.+ETH$", 10], ["^.+BTC$", 0.5], ]), "active_order_canceling": ConfigVar(key="active_order_canceling", prompt="Do you want to actively adjust/cancel orders? (Default "\ "True, only set to False if maker market is Radar Relay) >>> ", type_str="bool", default=True), # Setting the default threshold to -1.0 when to active_order_canceling is disabled # prevent canceling orders after it has expired "cancel_order_threshold": ConfigVar(key="cancel_order_threshold", prompt="What is the minimum profitability to actively cancel orders? " "(Default to -1.0, only specify when active_order_canceling " "is disabled, value can be negative) >>> ", default=-1.0, type_str="float"), "limit_order_min_expiration": ConfigVar(key="limit_order_min_expiration", prompt="What is the minimum limit order expiration in seconds? " "(Default to 130 seconds) >>> ", default=130.0, type_str="float") }
[ "hummingbot.cli.settings.EXAMPLE_PAIRS.get", "hummingbot.cli.config.config_validators.is_valid_market_symbol", "hummingbot.cli.settings.required_exchanges.append", "hummingbot.cli.config.config_var.ConfigVar" ]
[((367, 398), 'hummingbot.cli.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['maker_market'], {}), '(maker_market)\n', (384, 398), False, 'from hummingbot.cli.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((671, 702), 'hummingbot.cli.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['taker_market'], {}), '(taker_market)\n', (688, 702), False, 'from hummingbot.cli.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1030, 1073), 'hummingbot.cli.config.config_validators.is_valid_market_symbol', 'is_valid_market_symbol', (['maker_market', 'value'], {}), '(maker_market, value)\n', (1052, 1073), False, 'from hummingbot.cli.config.config_validators import is_exchange, is_valid_market_symbol\n'), ((1226, 1269), 'hummingbot.cli.config.config_validators.is_valid_market_symbol', 'is_valid_market_symbol', (['taker_market', 'value'], {}), '(taker_market, value)\n', (1248, 1269), False, 'from hummingbot.cli.config.config_validators import is_exchange, is_valid_market_symbol\n'), ((2058, 2167), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""maker_market_symbol"""', 'prompt': 'maker_symbol_prompt', 'validator': 'is_valid_maker_market_symbol'}), "(key='maker_market_symbol', prompt=maker_symbol_prompt, validator=\n is_valid_maker_market_symbol)\n", (2067, 2167), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((2304, 2413), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""taker_market_symbol"""', 'prompt': 'taker_symbol_prompt', 'validator': 'is_valid_taker_market_symbol'}), "(key='taker_market_symbol', prompt=taker_symbol_prompt, validator=\n is_valid_taker_market_symbol)\n", (2313, 2413), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((2550, 2729), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""min_profitability"""', 'prompt': '"""What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> """', 'default': '(0.003)', 'type_str': '"""float"""'}), "(key='min_profitability', prompt=\n 'What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> '\n , default=0.003, type_str='float')\n", (2559, 2729), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((2972, 3159), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""trade_size_override"""', 'prompt': '"""What is your preferred trade size? (denominated in the quote asset) >>> """', 'required_if': '(lambda : False)', 'default': '(0.0)', 'type_str': '"""float"""'}), "(key='trade_size_override', prompt=\n 'What is your preferred trade size? (denominated in the quote asset) >>> ',\n required_if=lambda : False, default=0.0, type_str='float')\n", (2981, 3159), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((3451, 3732), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""top_depth_tolerance"""', 'prompt': '"""What is the maximum depth you would go into the order book to make a trade? >>> """', 'type_str': '"""list"""', 'required_if': '(lambda : False)', 'default': "[['^.+(USDT|USDC|USDS|DAI|PAX|TUSD)$', 1000], ['^.+ETH$', 10], ['^.+BTC$', 0.5]\n ]"}), "(key='top_depth_tolerance', prompt=\n 'What is the maximum depth you would go into the order book to make a trade? >>> '\n , type_str='list', required_if=lambda : False, default=[[\n '^.+(USDT|USDC|USDS|DAI|PAX|TUSD)$', 1000], ['^.+ETH$', 10], ['^.+BTC$',\n 0.5]])\n", (3460, 3732), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((4229, 4435), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""active_order_canceling"""', 'prompt': '"""Do you want to actively adjust/cancel orders? (Default True, only set to False if maker market is Radar Relay) >>> """', 'type_str': '"""bool"""', 'default': '(True)'}), "(key='active_order_canceling', prompt=\n 'Do you want to actively adjust/cancel orders? (Default True, only set to False if maker market is Radar Relay) >>> '\n , type_str='bool', default=True)\n", (4238, 4435), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((4817, 5069), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""cancel_order_threshold"""', 'prompt': '"""What is the minimum profitability to actively cancel orders? (Default to -1.0, only specify when active_order_canceling is disabled, value can be negative) >>> """', 'default': '(-1.0)', 'type_str': '"""float"""'}), "(key='cancel_order_threshold', prompt=\n 'What is the minimum profitability to actively cancel orders? (Default to -1.0, only specify when active_order_canceling is disabled, value can be negative) >>> '\n , default=-1.0, type_str='float')\n", (4826, 5069), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((5371, 5552), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""limit_order_min_expiration"""', 'prompt': '"""What is the minimum limit order expiration in seconds? (Default to 130 seconds) >>> """', 'default': '(130.0)', 'type_str': '"""float"""'}), "(key='limit_order_min_expiration', prompt=\n 'What is the minimum limit order expiration in seconds? (Default to 130 seconds) >>> '\n , default=130.0, type_str='float')\n", (5380, 5552), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((1632, 1664), 'hummingbot.cli.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (1657, 1664), False, 'from hummingbot.cli.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1983, 2015), 'hummingbot.cli.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (2008, 2015), False, 'from hummingbot.cli.settings import required_exchanges, EXAMPLE_PAIRS\n')]
from decimal import Decimal import unittest.mock import hummingbot.strategy.celo_arb.start as strategy_start from hummingbot.connector.exchange_base import ExchangeBase from hummingbot.strategy.celo_arb.celo_arb_config_map import celo_arb_config_map as strategy_cmap from test.hummingbot.strategy import assign_config_default class CeloArbStartTest(unittest.TestCase): def setUp(self) -> None: super().setUp() self.strategy = None self.markets = {"binance": ExchangeBase()} self.assets = set() self.notifications = [] self.log_errors = [] assign_config_default(strategy_cmap) strategy_cmap.get("secondary_exchange").value = "binance" strategy_cmap.get("secondary_market").value = "CELO-USDT" strategy_cmap.get("order_amount").value = Decimal("1") strategy_cmap.get("min_profitability").value = Decimal("2") strategy_cmap.get("celo_slippage_buffer").value = Decimal("3") def _initialize_market_assets(self, market, trading_pairs): return [("ETH", "USDT")] def _initialize_wallet(self, token_trading_pairs): pass def _initialize_markets(self, market_names): pass def _notify(self, message): self.notifications.append(message) def logger(self): return self def error(self, message, exc_info): self.log_errors.append(message) def test_strategy_creation(self): strategy_start.start(self) self.assertEqual(self.strategy.order_amount, Decimal("1")) self.assertEqual(self.strategy.min_profitability, Decimal("0.02")) self.assertEqual(self.strategy.celo_slippage_buffer, Decimal("0.03"))
[ "hummingbot.strategy.celo_arb.start.start", "hummingbot.strategy.celo_arb.celo_arb_config_map.celo_arb_config_map.get", "hummingbot.connector.exchange_base.ExchangeBase" ]
[((602, 638), 'test.hummingbot.strategy.assign_config_default', 'assign_config_default', (['strategy_cmap'], {}), '(strategy_cmap)\n', (623, 638), False, 'from test.hummingbot.strategy import assign_config_default\n'), ((821, 833), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (828, 833), False, 'from decimal import Decimal\n'), ((889, 901), 'decimal.Decimal', 'Decimal', (['"""2"""'], {}), "('2')\n", (896, 901), False, 'from decimal import Decimal\n'), ((960, 972), 'decimal.Decimal', 'Decimal', (['"""3"""'], {}), "('3')\n", (967, 972), False, 'from decimal import Decimal\n'), ((1450, 1476), 'hummingbot.strategy.celo_arb.start.start', 'strategy_start.start', (['self'], {}), '(self)\n', (1470, 1476), True, 'import hummingbot.strategy.celo_arb.start as strategy_start\n'), ((489, 503), 'hummingbot.connector.exchange_base.ExchangeBase', 'ExchangeBase', ([], {}), '()\n', (501, 503), False, 'from hummingbot.connector.exchange_base import ExchangeBase\n'), ((647, 686), 'hummingbot.strategy.celo_arb.celo_arb_config_map.celo_arb_config_map.get', 'strategy_cmap.get', (['"""secondary_exchange"""'], {}), "('secondary_exchange')\n", (664, 686), True, 'from hummingbot.strategy.celo_arb.celo_arb_config_map import celo_arb_config_map as strategy_cmap\n'), ((713, 750), 'hummingbot.strategy.celo_arb.celo_arb_config_map.celo_arb_config_map.get', 'strategy_cmap.get', (['"""secondary_market"""'], {}), "('secondary_market')\n", (730, 750), True, 'from hummingbot.strategy.celo_arb.celo_arb_config_map import celo_arb_config_map as strategy_cmap\n'), ((779, 812), 'hummingbot.strategy.celo_arb.celo_arb_config_map.celo_arb_config_map.get', 'strategy_cmap.get', (['"""order_amount"""'], {}), "('order_amount')\n", (796, 812), True, 'from hummingbot.strategy.celo_arb.celo_arb_config_map import celo_arb_config_map as strategy_cmap\n'), ((842, 880), 'hummingbot.strategy.celo_arb.celo_arb_config_map.celo_arb_config_map.get', 'strategy_cmap.get', (['"""min_profitability"""'], {}), "('min_profitability')\n", (859, 880), True, 'from hummingbot.strategy.celo_arb.celo_arb_config_map import celo_arb_config_map as strategy_cmap\n'), ((910, 951), 'hummingbot.strategy.celo_arb.celo_arb_config_map.celo_arb_config_map.get', 'strategy_cmap.get', (['"""celo_slippage_buffer"""'], {}), "('celo_slippage_buffer')\n", (927, 951), True, 'from hummingbot.strategy.celo_arb.celo_arb_config_map import celo_arb_config_map as strategy_cmap\n'), ((1530, 1542), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (1537, 1542), False, 'from decimal import Decimal\n'), ((1602, 1617), 'decimal.Decimal', 'Decimal', (['"""0.02"""'], {}), "('0.02')\n", (1609, 1617), False, 'from decimal import Decimal\n'), ((1680, 1695), 'decimal.Decimal', 'Decimal', (['"""0.03"""'], {}), "('0.03')\n", (1687, 1695), False, 'from decimal import Decimal\n')]
from hummingbot.cli.config.config_var import ConfigVar from hummingbot.cli.config.config_validators import ( is_exchange, is_valid_market_symbol, ) from hummingbot.cli.settings import ( required_exchanges, EXAMPLE_PAIRS, ) def is_valid_primary_market_symbol(value: str) -> bool: primary_market = arbitrage_config_map.get("primary_market").value return is_valid_market_symbol(primary_market, value) def is_valid_secondary_market_symbol(value: str) -> bool: secondary_market = arbitrage_config_map.get("secondary_market").value return is_valid_market_symbol(secondary_market, value) def primary_symbol_prompt(): primary_market = arbitrage_config_map.get("primary_market").value example = EXAMPLE_PAIRS.get(primary_market) return "Enter the token symbol you would like to trade on %s%s >>> " \ % (primary_market, f" (e.g. {example})" if example else "") def secondary_symbol_prompt(): secondary_market = arbitrage_config_map.get("secondary_market").value example = EXAMPLE_PAIRS.get(secondary_market) return "Enter the token symbol you would like to trade on %s%s >>> " \ % (secondary_market, f" (e.g. {example})" if example else "") arbitrage_config_map = { "primary_market": ConfigVar(key="primary_market", prompt="Enter your primary exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value)), "secondary_market": ConfigVar(key="secondary_market", prompt="Enter your secondary exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value)), "primary_market_symbol": ConfigVar(key="primary_market_symbol", prompt=primary_symbol_prompt), "secondary_market_symbol": ConfigVar(key="secondary_market_symbol", prompt=secondary_symbol_prompt), "min_profitability": ConfigVar(key="min_profitability", prompt="What is the minimum profitability for you to make a trade? "\ "(Enter 0.01 to indicate 1%) >>> ", default=0.003, type_str="float"), "trade_size_override": ConfigVar(key="trade_size_override", prompt="What is your preferred trade size? (denominated in " "the quote asset) >>> ", required_if=lambda: False, default=0.0, type_str="float"), "top_depth_tolerance": ConfigVar(key="top_depth_tolerance", prompt="What is the maximum depth you would go into th" "e order book to make a trade? >>>", type_str="list", required_if=lambda: False, default=[ ["^.+(USDT|USDC|USDS|DAI|PAX|TUSD)$", 1000], ["^.+ETH$", 10], ["^.+BTC$", 0.5], ]), }
[ "hummingbot.cli.settings.EXAMPLE_PAIRS.get", "hummingbot.cli.config.config_validators.is_valid_market_symbol", "hummingbot.cli.settings.required_exchanges.append", "hummingbot.cli.config.config_var.ConfigVar" ]
[((378, 423), 'hummingbot.cli.config.config_validators.is_valid_market_symbol', 'is_valid_market_symbol', (['primary_market', 'value'], {}), '(primary_market, value)\n', (400, 423), False, 'from hummingbot.cli.config.config_validators import is_exchange, is_valid_market_symbol\n'), ((569, 616), 'hummingbot.cli.config.config_validators.is_valid_market_symbol', 'is_valid_market_symbol', (['secondary_market', 'value'], {}), '(secondary_market, value)\n', (591, 616), False, 'from hummingbot.cli.config.config_validators import is_exchange, is_valid_market_symbol\n'), ((732, 765), 'hummingbot.cli.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['primary_market'], {}), '(primary_market)\n', (749, 765), False, 'from hummingbot.cli.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1033, 1068), 'hummingbot.cli.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['secondary_market'], {}), '(secondary_market)\n', (1050, 1068), False, 'from hummingbot.cli.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1998, 2066), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""primary_market_symbol"""', 'prompt': 'primary_symbol_prompt'}), "(key='primary_market_symbol', prompt=primary_symbol_prompt)\n", (2007, 2066), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((2158, 2230), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""secondary_market_symbol"""', 'prompt': 'secondary_symbol_prompt'}), "(key='secondary_market_symbol', prompt=secondary_symbol_prompt)\n", (2167, 2230), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((2322, 2501), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""min_profitability"""', 'prompt': '"""What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> """', 'default': '(0.003)', 'type_str': '"""float"""'}), "(key='min_profitability', prompt=\n 'What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> '\n , default=0.003, type_str='float')\n", (2331, 2501), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((2744, 2931), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""trade_size_override"""', 'prompt': '"""What is your preferred trade size? (denominated in the quote asset) >>> """', 'required_if': '(lambda : False)', 'default': '(0.0)', 'type_str': '"""float"""'}), "(key='trade_size_override', prompt=\n 'What is your preferred trade size? (denominated in the quote asset) >>> ',\n required_if=lambda : False, default=0.0, type_str='float')\n", (2753, 2931), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((3223, 3503), 'hummingbot.cli.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""top_depth_tolerance"""', 'prompt': '"""What is the maximum depth you would go into the order book to make a trade? >>>"""', 'type_str': '"""list"""', 'required_if': '(lambda : False)', 'default': "[['^.+(USDT|USDC|USDS|DAI|PAX|TUSD)$', 1000], ['^.+ETH$', 10], ['^.+BTC$', 0.5]\n ]"}), "(key='top_depth_tolerance', prompt=\n 'What is the maximum depth you would go into the order book to make a trade? >>>'\n , type_str='list', required_if=lambda : False, default=[[\n '^.+(USDT|USDC|USDS|DAI|PAX|TUSD)$', 1000], ['^.+ETH$', 10], ['^.+BTC$',\n 0.5]])\n", (3232, 3503), False, 'from hummingbot.cli.config.config_var import ConfigVar\n'), ((1564, 1596), 'hummingbot.cli.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (1589, 1596), False, 'from hummingbot.cli.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1923, 1955), 'hummingbot.cli.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (1948, 1955), False, 'from hummingbot.cli.settings import required_exchanges, EXAMPLE_PAIRS\n')]
from os.path import join, realpath import sys; sys.path.insert(0, realpath(join(__file__, "../../../../../"))) import asyncio import unittest from typing import List import conf from hummingbot.connector.exchange.probit.probit_auth import ProbitAuth from hummingbot.connector.exchange.probit.probit_websocket import ProbitWebsocket class TestAuth(unittest.TestCase): @classmethod def setUpClass(cls): cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() api_key = conf.probit_api_key secret_key = conf.probit_secret_key cls.auth = ProbitAuth(api_key, secret_key) cls.ws = ProbitWebsocket(cls.auth) async def con_auth(self): await self.ws.connect() await self.ws.subscribe(channel="balance") async for response in self.ws.on_message(): if (response.get("channel") == "balance"): return response def test_auth(self): result: List[str] = self.ev_loop.run_until_complete(self.con_auth()) assert result["data"] != None print(result["data"]) if __name__ == '__main__': unittest.main()
[ "hummingbot.connector.exchange.probit.probit_auth.ProbitAuth", "hummingbot.connector.exchange.probit.probit_websocket.ProbitWebsocket" ]
[((1117, 1132), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1130, 1132), False, 'import unittest\n'), ((75, 108), 'os.path.join', 'join', (['__file__', '"""../../../../../"""'], {}), "(__file__, '../../../../../')\n", (79, 108), False, 'from os.path import join, realpath\n'), ((458, 482), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (480, 482), False, 'import asyncio\n'), ((584, 615), 'hummingbot.connector.exchange.probit.probit_auth.ProbitAuth', 'ProbitAuth', (['api_key', 'secret_key'], {}), '(api_key, secret_key)\n', (594, 615), False, 'from hummingbot.connector.exchange.probit.probit_auth import ProbitAuth\n'), ((633, 658), 'hummingbot.connector.exchange.probit.probit_websocket.ProbitWebsocket', 'ProbitWebsocket', (['cls.auth'], {}), '(cls.auth)\n', (648, 658), False, 'from hummingbot.connector.exchange.probit.probit_websocket import ProbitWebsocket\n')]
import logging from typing import List, Optional from hummingbot.connector.exchange.k2.k2_api_user_stream_data_source import \ K2APIUserStreamDataSource from hummingbot.connector.exchange.k2.k2_auth import K2Auth from hummingbot.connector.exchange.k2.k2_constants import EXCHANGE_NAME from hummingbot.core.data_type.user_stream_tracker import UserStreamTracker from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from hummingbot.logger import HummingbotLogger class K2UserStreamTracker(UserStreamTracker): _logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._logger is None: cls._logger = logging.getLogger(__name__) return cls._logger def __init__(self, k2_auth: Optional[K2Auth] = None, trading_pairs: Optional[List[str]] = None): self._k2_auth: K2Auth = k2_auth self._trading_pairs: List[str] = trading_pairs or [] super().__init__(data_source=K2APIUserStreamDataSource( auth=self._k2_auth, trading_pairs=self._trading_pairs )) @property def data_source(self) -> UserStreamTrackerDataSource: """ *required Initializes a user stream data source (user specific order diffs from live socket stream) :return: OrderBookTrackerDataSource """ if not self._data_source: self._data_source = K2APIUserStreamDataSource( auth=self._k2_auth, trading_pairs=self._trading_pairs ) return self._data_source @property def exchange_name(self) -> str: """ *required Name of the current exchange """ return EXCHANGE_NAME async def start(self): """ *required Start all listeners and tasks """ self._user_stream_tracking_task = safe_ensure_future( self.data_source.listen_for_user_stream(self._user_stream) ) await safe_gather(self._user_stream_tracking_task)
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.connector.exchange.k2.k2_api_user_stream_data_source.K2APIUserStreamDataSource" ]
[((814, 841), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (831, 841), False, 'import logging\n'), ((1582, 1667), 'hummingbot.connector.exchange.k2.k2_api_user_stream_data_source.K2APIUserStreamDataSource', 'K2APIUserStreamDataSource', ([], {'auth': 'self._k2_auth', 'trading_pairs': 'self._trading_pairs'}), '(auth=self._k2_auth, trading_pairs=self._trading_pairs\n )\n', (1607, 1667), False, 'from hummingbot.connector.exchange.k2.k2_api_user_stream_data_source import K2APIUserStreamDataSource\n'), ((2166, 2210), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['self._user_stream_tracking_task'], {}), '(self._user_stream_tracking_task)\n', (2177, 2210), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((1143, 1228), 'hummingbot.connector.exchange.k2.k2_api_user_stream_data_source.K2APIUserStreamDataSource', 'K2APIUserStreamDataSource', ([], {'auth': 'self._k2_auth', 'trading_pairs': 'self._trading_pairs'}), '(auth=self._k2_auth, trading_pairs=self._trading_pairs\n )\n', (1168, 1228), False, 'from hummingbot.connector.exchange.k2.k2_api_user_stream_data_source import K2APIUserStreamDataSource\n')]
from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_validators import ( is_exchange, is_valid_market_symbol, ) from hummingbot.client.settings import ( required_exchanges, EXAMPLE_PAIRS, ) def is_valid_primary_market_symbol(value: str) -> bool: primary_market = arbitrage_config_map.get("primary_market").value return is_valid_market_symbol(primary_market, value) def is_valid_secondary_market_symbol(value: str) -> bool: secondary_market = arbitrage_config_map.get("secondary_market").value return is_valid_market_symbol(secondary_market, value) def primary_symbol_prompt(): primary_market = arbitrage_config_map.get("primary_market").value example = EXAMPLE_PAIRS.get(primary_market) return "Enter the token symbol you would like to trade on %s%s >>> " \ % (primary_market, f" (e.g. {example})" if example else "") def secondary_symbol_prompt(): secondary_market = arbitrage_config_map.get("secondary_market").value example = EXAMPLE_PAIRS.get(secondary_market) return "Enter the token symbol you would like to trade on %s%s >>> " \ % (secondary_market, f" (e.g. {example})" if example else "") arbitrage_config_map = { "primary_market": ConfigVar( key="primary_market", prompt="Enter your primary exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value)), "secondary_market": ConfigVar( key="secondary_market", prompt="Enter your secondary exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value)), "primary_market_symbol": ConfigVar( key="primary_market_symbol", prompt=primary_symbol_prompt, validator=is_valid_primary_market_symbol), "secondary_market_symbol": ConfigVar( key="secondary_market_symbol", prompt=secondary_symbol_prompt, validator=is_valid_secondary_market_symbol), "min_profitability": ConfigVar( key="min_profitability", prompt="What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> ", default=0.003, type_str="decimal"), }
[ "hummingbot.client.settings.EXAMPLE_PAIRS.get", "hummingbot.client.settings.required_exchanges.append", "hummingbot.client.config.config_var.ConfigVar", "hummingbot.client.config.config_validators.is_valid_market_symbol" ]
[((387, 432), 'hummingbot.client.config.config_validators.is_valid_market_symbol', 'is_valid_market_symbol', (['primary_market', 'value'], {}), '(primary_market, value)\n', (409, 432), False, 'from hummingbot.client.config.config_validators import is_exchange, is_valid_market_symbol\n'), ((578, 625), 'hummingbot.client.config.config_validators.is_valid_market_symbol', 'is_valid_market_symbol', (['secondary_market', 'value'], {}), '(secondary_market, value)\n', (600, 625), False, 'from hummingbot.client.config.config_validators import is_exchange, is_valid_market_symbol\n'), ((741, 774), 'hummingbot.client.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['primary_market'], {}), '(primary_market)\n', (758, 774), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1042, 1077), 'hummingbot.client.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['secondary_market'], {}), '(secondary_market)\n', (1059, 1077), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1728, 1842), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""primary_market_symbol"""', 'prompt': 'primary_symbol_prompt', 'validator': 'is_valid_primary_market_symbol'}), "(key='primary_market_symbol', prompt=primary_symbol_prompt,\n validator=is_valid_primary_market_symbol)\n", (1737, 1842), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((1896, 2016), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""secondary_market_symbol"""', 'prompt': 'secondary_symbol_prompt', 'validator': 'is_valid_secondary_market_symbol'}), "(key='secondary_market_symbol', prompt=secondary_symbol_prompt,\n validator=is_valid_secondary_market_symbol)\n", (1905, 2016), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((2064, 2245), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""min_profitability"""', 'prompt': '"""What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> """', 'default': '(0.003)', 'type_str': '"""decimal"""'}), "(key='min_profitability', prompt=\n 'What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> '\n , default=0.003, type_str='decimal')\n", (2073, 2245), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((1438, 1470), 'hummingbot.client.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (1463, 1470), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1664, 1696), 'hummingbot.client.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (1689, 1696), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n')]
import typing from abc import ABC, abstractmethod from dataclasses import dataclass, field from decimal import Decimal from typing import Dict, List, Optional from hummingbot.connector.utils import combine_to_hb_trading_pair, split_hb_trading_pair from hummingbot.core.event.utils import interchangeable if typing.TYPE_CHECKING: # avoid circular import problems from hummingbot.connector.exchange_base import ExchangeBase from hummingbot.core.data_type.order_candidate import OrderCandidate @dataclass class TokenAmount: token: str amount: Decimal def __iter__(self): return iter((self.token, self.amount)) @dataclass class TradeFeeBase(ABC): """ Contains the necessary information to apply the trade fee to a particular order. """ percent: Decimal = Decimal("0") percent_token: Optional[str] = None # only set when fee charged in third token (the Binance BNB case) flat_fees: List[TokenAmount] = field(default_factory=list) # list of (asset, amount) tuples def to_json(self) -> Dict[str, any]: return { "percent": float(self.percent), "percent_token": self.percent_token, "flat_fees": [{"asset": asset, "amount": float(amount)} for asset, amount in self.flat_fees] } def fee_amount_in_quote( self, trading_pair: str, price: Decimal, order_amount: Decimal, exchange: Optional['ExchangeBase'] = None ) -> Decimal: fee_amount = Decimal("0") if self.percent > 0: fee_amount = (price * order_amount) * self.percent base, quote = split_hb_trading_pair(trading_pair) for flat_fee in self.flat_fees: if interchangeable(flat_fee.token, base): fee_amount += (flat_fee.amount * price) elif interchangeable(flat_fee.token, quote): fee_amount += flat_fee.amount else: conversion_pair = combine_to_hb_trading_pair(base=flat_fee.token, quote=quote) conversion_rate = self._get_exchange_rate(conversion_pair, exchange) fee_amount = (flat_fee.amount * conversion_rate) return fee_amount @abstractmethod def get_fee_impact_on_order_cost( self, order_candidate: 'OrderCandidate', exchange: 'ExchangeBase' ) -> Optional[TokenAmount]: """ WARNING: Do not use this method for sizing. Instead, use the `BudgetChecker`. Returns the impact of the fee on the cost requirements for the candidate order. """ ... @abstractmethod def get_fee_impact_on_order_returns( self, order_candidate: 'OrderCandidate', exchange: 'ExchangeBase' ) -> Optional[Decimal]: """ WARNING: Do not use this method for sizing. Instead, use the `BudgetChecker`. Returns the impact of the fee on the expected returns from the candidate order. """ ... @staticmethod def _get_exchange_rate(trading_pair: str, exchange: Optional["ExchangeBase"] = None) -> Decimal: from hummingbot.core.rate_oracle.rate_oracle import RateOracle if exchange is not None: rate = exchange.get_price(trading_pair, is_buy=True) else: rate = RateOracle.get_instance().rate(trading_pair) return rate class AddedToCostTradeFee(TradeFeeBase): def get_fee_impact_on_order_cost( self, order_candidate: 'OrderCandidate', exchange: 'ExchangeBase' ) -> Optional[TokenAmount]: """ WARNING: Do not use this method for sizing. Instead, use the `BudgetChecker`. Returns the impact of the fee on the cost requirements for the candidate order. """ ret = None if self.percent != Decimal("0"): fee_token = self.percent_token or order_candidate.order_collateral.token if order_candidate.order_collateral is None or fee_token != order_candidate.order_collateral.token: token, size = order_candidate.get_size_token_and_order_size() if fee_token == token: exchange_rate = Decimal("1") else: exchange_pair = combine_to_hb_trading_pair(token, fee_token) # buy order token w/ pf token exchange_rate = exchange.get_price(exchange_pair, is_buy=True) fee_amount = size * exchange_rate * self.percent else: # self.percent_token == order_candidate.order_collateral.token fee_amount = order_candidate.order_collateral.amount * self.percent ret = TokenAmount(fee_token, fee_amount) return ret def get_fee_impact_on_order_returns( self, order_candidate: 'OrderCandidate', exchange: 'ExchangeBase' ) -> Optional[Decimal]: """ WARNING: Do not use this method for sizing. Instead, use the `BudgetChecker`. Returns the impact of the fee on the expected returns from the candidate order. """ return None class DeductedFromReturnsTradeFee(TradeFeeBase): def get_fee_impact_on_order_cost( self, order_candidate: 'OrderCandidate', exchange: 'ExchangeBase' ) -> Optional[TokenAmount]: """ WARNING: Do not use this method for sizing. Instead, use the `BudgetChecker`. Returns the impact of the fee on the cost requirements for the candidate order. """ return None def get_fee_impact_on_order_returns( self, order_candidate: 'OrderCandidate', exchange: 'ExchangeBase' ) -> Optional[Decimal]: """ WARNING: Do not use this method for sizing. Instead, use the `BudgetChecker`. Returns the impact of the fee on the expected returns from the candidate order. """ impact = order_candidate.potential_returns.amount * self.percent return impact @dataclass class TradeFeeSchema: """ Contains the necessary information to build a `TradeFee` object. NOTE: Currently, `percent_fee_token` is only specified if the percent fee is always charged in a particular token (e.g. the Binance BNB case). To always populate the `percent_fee_token`, this class will require access to the `exchange` class at runtime to determine the collateral token for the trade (e.g. for derivatives). This means that, if the `percent_fee_token` is specified, then the fee is always added to the trade costs, and `buy_percent_fee_deducted_from_returns` cannot be set to `True`. """ percent_fee_token: Optional[str] = None maker_percent_fee_decimal: Decimal = Decimal("0") taker_percent_fee_decimal: Decimal = Decimal("0") buy_percent_fee_deducted_from_returns: bool = False maker_fixed_fees: List[TokenAmount] = field(default_factory=list) taker_fixed_fees: List[TokenAmount] = field(default_factory=list) def __post_init__(self): self.validate_schema() def validate_schema(self): if self.percent_fee_token is not None: assert not self.buy_percent_fee_deducted_from_returns self.maker_percent_fee_decimal = Decimal(self.maker_percent_fee_decimal) self.taker_percent_fee_decimal = Decimal(self.taker_percent_fee_decimal) for i in range(len(self.taker_fixed_fees)): self.taker_fixed_fees[i] = TokenAmount( self.taker_fixed_fees[i].token, Decimal(self.taker_fixed_fees[i].amount) ) for i in range(len(self.maker_fixed_fees)): self.maker_fixed_fees[i] = TokenAmount( self.maker_fixed_fees[i].token, Decimal(self.maker_fixed_fees[i].amount) )
[ "hummingbot.connector.utils.combine_to_hb_trading_pair", "hummingbot.core.rate_oracle.rate_oracle.RateOracle.get_instance", "hummingbot.core.event.utils.interchangeable", "hummingbot.connector.utils.split_hb_trading_pair" ]
[((803, 815), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (810, 815), False, 'from decimal import Decimal\n'), ((958, 985), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (963, 985), False, 'from dataclasses import dataclass, field\n'), ((6611, 6623), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (6618, 6623), False, 'from decimal import Decimal\n'), ((6665, 6677), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (6672, 6677), False, 'from decimal import Decimal\n'), ((6776, 6803), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (6781, 6803), False, 'from dataclasses import dataclass, field\n'), ((6846, 6873), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (6851, 6873), False, 'from dataclasses import dataclass, field\n'), ((1496, 1508), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (1503, 1508), False, 'from decimal import Decimal\n'), ((1623, 1658), 'hummingbot.connector.utils.split_hb_trading_pair', 'split_hb_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (1644, 1658), False, 'from hummingbot.connector.utils import combine_to_hb_trading_pair, split_hb_trading_pair\n'), ((7121, 7160), 'decimal.Decimal', 'Decimal', (['self.maker_percent_fee_decimal'], {}), '(self.maker_percent_fee_decimal)\n', (7128, 7160), False, 'from decimal import Decimal\n'), ((7202, 7241), 'decimal.Decimal', 'Decimal', (['self.taker_percent_fee_decimal'], {}), '(self.taker_percent_fee_decimal)\n', (7209, 7241), False, 'from decimal import Decimal\n'), ((1714, 1751), 'hummingbot.core.event.utils.interchangeable', 'interchangeable', (['flat_fee.token', 'base'], {}), '(flat_fee.token, base)\n', (1729, 1751), False, 'from hummingbot.core.event.utils import interchangeable\n'), ((3772, 3784), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (3779, 3784), False, 'from decimal import Decimal\n'), ((1826, 1864), 'hummingbot.core.event.utils.interchangeable', 'interchangeable', (['flat_fee.token', 'quote'], {}), '(flat_fee.token, quote)\n', (1841, 1864), False, 'from hummingbot.core.event.utils import interchangeable\n'), ((7394, 7434), 'decimal.Decimal', 'Decimal', (['self.taker_fixed_fees[i].amount'], {}), '(self.taker_fixed_fees[i].amount)\n', (7401, 7434), False, 'from decimal import Decimal\n'), ((7601, 7641), 'decimal.Decimal', 'Decimal', (['self.maker_fixed_fees[i].amount'], {}), '(self.maker_fixed_fees[i].amount)\n', (7608, 7641), False, 'from decimal import Decimal\n'), ((1964, 2024), 'hummingbot.connector.utils.combine_to_hb_trading_pair', 'combine_to_hb_trading_pair', ([], {'base': 'flat_fee.token', 'quote': 'quote'}), '(base=flat_fee.token, quote=quote)\n', (1990, 2024), False, 'from hummingbot.connector.utils import combine_to_hb_trading_pair, split_hb_trading_pair\n'), ((3275, 3300), 'hummingbot.core.rate_oracle.rate_oracle.RateOracle.get_instance', 'RateOracle.get_instance', ([], {}), '()\n', (3298, 3300), False, 'from hummingbot.core.rate_oracle.rate_oracle import RateOracle\n'), ((4136, 4148), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (4143, 4148), False, 'from decimal import Decimal\n'), ((4207, 4251), 'hummingbot.connector.utils.combine_to_hb_trading_pair', 'combine_to_hb_trading_pair', (['token', 'fee_token'], {}), '(token, fee_token)\n', (4233, 4251), False, 'from hummingbot.connector.utils import combine_to_hb_trading_pair, split_hb_trading_pair\n')]
from os.path import join, realpath import sys; sys.path.insert(0, realpath(join(__file__, "../../"))) import logging; logging.basicConfig(level=logging.ERROR) import unittest from unittest.mock import MagicMock from decimal import Decimal from hummingbot.strategy.spot_perpetual_arbitrage.arb_proposal import ArbProposalSide, ArbProposal from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple class TestSpotPerpetualArbitrage(unittest.TestCase): trading_pair = "BTC-USDT" base_token, quote_token = trading_pair.split("-") def test_arb_proposal(self): spot_connector = MagicMock() spot_connector.display_name = "Binance" spot_market_info = MarketTradingPairTuple(spot_connector, self.trading_pair, self.base_token, self.quote_token) perp_connector = MagicMock() perp_connector.display_name = "Binance Perpetual" perp_market_info = MarketTradingPairTuple(perp_connector, self.trading_pair, self.base_token, self.quote_token) spot_side = ArbProposalSide( spot_market_info, True, Decimal(100) ) perp_side = ArbProposalSide( perp_market_info, False, Decimal(110) ) proposal = ArbProposal(spot_side, perp_side, Decimal("1")) self.assertEqual(Decimal("0.1"), proposal.profit_pct()) expected_str = "Spot: Binance: Buy BTC at 100 USDT.\n" \ "Perpetual: Binance perpetual: Sell BTC at 110 USDT.\n" \ "Order amount: 1\n" \ "Profit: 10.00%" self.assertEqual(expected_str, str(proposal)) perp_side = ArbProposalSide( perp_market_info, True, Decimal(110) ) with self.assertRaises(Exception) as context: proposal = ArbProposal(spot_side, perp_side, Decimal("1")) self.assertEqual('Spot and perpetual arb proposal cannot be on the same side.', str(context.exception))
[ "hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple" ]
[((119, 159), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.ERROR'}), '(level=logging.ERROR)\n', (138, 159), False, 'import logging\n'), ((75, 99), 'os.path.join', 'join', (['__file__', '"""../../"""'], {}), "(__file__, '../../')\n", (79, 99), False, 'from os.path import join, realpath\n'), ((618, 629), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (627, 629), False, 'from unittest.mock import MagicMock\n'), ((705, 801), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['spot_connector', 'self.trading_pair', 'self.base_token', 'self.quote_token'], {}), '(spot_connector, self.trading_pair, self.base_token,\n self.quote_token)\n', (727, 801), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((823, 834), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (832, 834), False, 'from unittest.mock import MagicMock\n'), ((920, 1016), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['perp_connector', 'self.trading_pair', 'self.base_token', 'self.quote_token'], {}), '(perp_connector, self.trading_pair, self.base_token,\n self.quote_token)\n', (942, 1016), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((1110, 1122), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (1117, 1122), False, 'from decimal import Decimal\n'), ((1231, 1243), 'decimal.Decimal', 'Decimal', (['(110)'], {}), '(110)\n', (1238, 1243), False, 'from decimal import Decimal\n'), ((1307, 1319), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (1314, 1319), False, 'from decimal import Decimal\n'), ((1346, 1360), 'decimal.Decimal', 'Decimal', (['"""0.1"""'], {}), "('0.1')\n", (1353, 1360), False, 'from decimal import Decimal\n'), ((1767, 1779), 'decimal.Decimal', 'Decimal', (['(110)'], {}), '(110)\n', (1774, 1779), False, 'from decimal import Decimal\n'), ((1901, 1913), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (1908, 1913), False, 'from decimal import Decimal\n')]
import hashlib import hmac import mock from unittest import TestCase from hummingbot.connector.exchange.ascend_ex.ascend_ex_auth import AscendExAuth class AscendExAuthTests(TestCase): @property def api_key(self): return 'test_api_key' @property def secret_key(self): return 'test_secret_key' def _get_ms_timestamp(self): return str(1633084102569) def test_authentication_headers(self): with mock.patch('hummingbot.connector.exchange.ascend_ex.ascend_ex_auth.get_ms_timestamp') as get_ms_timestamp_mock: timestamp = self._get_ms_timestamp() get_ms_timestamp_mock.return_value = timestamp path_url = "test.com" auth = AscendExAuth(api_key=self.api_key, secret_key=self.secret_key) headers = auth.get_auth_headers(path_url=path_url) message = timestamp + path_url expected_signature = hmac.new(self.secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest() self.assertEqual(3, len(headers)) self.assertEqual(timestamp, headers.get('x-auth-timestamp')) self.assertEqual(self.api_key, headers.get('x-auth-key')) self.assertEqual(expected_signature, headers.get('x-auth-signature'))
[ "hummingbot.connector.exchange.ascend_ex.ascend_ex_auth.AscendExAuth" ]
[((456, 546), 'mock.patch', 'mock.patch', (['"""hummingbot.connector.exchange.ascend_ex.ascend_ex_auth.get_ms_timestamp"""'], {}), "(\n 'hummingbot.connector.exchange.ascend_ex.ascend_ex_auth.get_ms_timestamp')\n", (466, 546), False, 'import mock\n'), ((730, 792), 'hummingbot.connector.exchange.ascend_ex.ascend_ex_auth.AscendExAuth', 'AscendExAuth', ([], {'api_key': 'self.api_key', 'secret_key': 'self.secret_key'}), '(api_key=self.api_key, secret_key=self.secret_key)\n', (742, 792), False, 'from hummingbot.connector.exchange.ascend_ex.ascend_ex_auth import AscendExAuth\n')]
import asyncio import os.path import threading import time from decimal import Decimal from shutil import move from typing import ( Dict, List, Optional, Tuple, Union, ) import pandas as pd from sqlalchemy.orm import Query, Session from hummingbot import data_path from hummingbot.connector.connector_base import ConnectorBase from hummingbot.connector.utils import TradeFillOrderDetails from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder from hummingbot.core.event.events import ( BuyOrderCompletedEvent, BuyOrderCreatedEvent, FundingPaymentCompletedEvent, MarketEvent, MarketOrderFailureEvent, OrderCancelledEvent, OrderExpiredEvent, OrderFilledEvent, RangePositionInitiatedEvent, RangePositionUpdatedEvent, SellOrderCompletedEvent, SellOrderCreatedEvent, ) from hummingbot.model.funding_payment import FundingPayment from hummingbot.model.market_state import MarketState from hummingbot.model.order import Order from hummingbot.model.order_status import OrderStatus from hummingbot.model.range_position import RangePosition from hummingbot.model.range_position_update import RangePositionUpdate from hummingbot.model.sql_connection_manager import SQLConnectionManager from hummingbot.model.trade_fill import TradeFill class MarketsRecorder: market_event_tag_map: Dict[int, MarketEvent] = { event_obj.value: event_obj for event_obj in MarketEvent.__members__.values() } def __init__(self, sql: SQLConnectionManager, markets: List[ConnectorBase], config_file_path: str, strategy_name: str): if threading.current_thread() != threading.main_thread(): raise EnvironmentError("MarketsRecorded can only be initialized from the main thread.") self._ev_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() self._sql_manager: SQLConnectionManager = sql self._markets: List[ConnectorBase] = markets self._config_file_path: str = config_file_path self._strategy_name: str = strategy_name # Internal collection of trade fills in connector will be used for remote/local history reconciliation for market in self._markets: trade_fills = self.get_trades_for_config(self._config_file_path, 2000) market.add_trade_fills_from_market_recorder({TradeFillOrderDetails(tf.market, tf.exchange_trade_id, tf.symbol) for tf in trade_fills}) exchange_order_ids = self.get_orders_for_config_and_market(self._config_file_path, market, True, 2000) market.add_exchange_order_ids_from_market_recorder({o.exchange_order_id: o.id for o in exchange_order_ids}) self._create_order_forwarder: SourceInfoEventForwarder = SourceInfoEventForwarder(self._did_create_order) self._fill_order_forwarder: SourceInfoEventForwarder = SourceInfoEventForwarder(self._did_fill_order) self._cancel_order_forwarder: SourceInfoEventForwarder = SourceInfoEventForwarder(self._did_cancel_order) self._fail_order_forwarder: SourceInfoEventForwarder = SourceInfoEventForwarder(self._did_fail_order) self._complete_order_forwarder: SourceInfoEventForwarder = SourceInfoEventForwarder(self._did_complete_order) self._expire_order_forwarder: SourceInfoEventForwarder = SourceInfoEventForwarder(self._did_expire_order) self._funding_payment_forwarder: SourceInfoEventForwarder = SourceInfoEventForwarder( self._did_complete_funding_payment) self._intiate_range_position_forwarder: SourceInfoEventForwarder = SourceInfoEventForwarder( self._did_initiate_range_position) self._update_range_position_forwarder: SourceInfoEventForwarder = SourceInfoEventForwarder( self._did_update_range_position) self._event_pairs: List[Tuple[MarketEvent, SourceInfoEventForwarder]] = [ (MarketEvent.BuyOrderCreated, self._create_order_forwarder), (MarketEvent.SellOrderCreated, self._create_order_forwarder), (MarketEvent.OrderFilled, self._fill_order_forwarder), (MarketEvent.OrderCancelled, self._cancel_order_forwarder), (MarketEvent.OrderFailure, self._fail_order_forwarder), (MarketEvent.BuyOrderCompleted, self._complete_order_forwarder), (MarketEvent.SellOrderCompleted, self._complete_order_forwarder), (MarketEvent.OrderExpired, self._expire_order_forwarder), (MarketEvent.FundingPaymentCompleted, self._funding_payment_forwarder), (MarketEvent.RangePositionInitiated, self._intiate_range_position_forwarder), (MarketEvent.RangePositionUpdated, self._update_range_position_forwarder), ] @property def sql_manager(self) -> SQLConnectionManager: return self._sql_manager @property def config_file_path(self) -> str: return self._config_file_path @property def strategy_name(self) -> str: return self._strategy_name @property def db_timestamp(self) -> int: return int(time.time() * 1e3) def start(self): for market in self._markets: for event_pair in self._event_pairs: market.add_listener(event_pair[0], event_pair[1]) def stop(self): for market in self._markets: for event_pair in self._event_pairs: market.remove_listener(event_pair[0], event_pair[1]) def get_orders_for_config_and_market(self, config_file_path: str, market: ConnectorBase, with_exchange_order_id_present: Optional[bool] = False, number_of_rows: Optional[int] = None) -> List[Order]: with self._sql_manager.get_new_session() as session: filters = [Order.config_file_path == config_file_path, Order.market == market.display_name] if with_exchange_order_id_present: filters.append(Order.exchange_order_id.isnot(None)) query: Query = (session .query(Order) .filter(*filters) .order_by(Order.creation_timestamp)) if number_of_rows is None: return query.all() else: return query.limit(number_of_rows).all() def get_trades_for_config(self, config_file_path: str, number_of_rows: Optional[int] = None) -> List[TradeFill]: with self._sql_manager.get_new_session() as session: query: Query = (session .query(TradeFill) .filter(TradeFill.config_file_path == config_file_path) .order_by(TradeFill.timestamp.desc())) if number_of_rows is None: return query.all() else: return query.limit(number_of_rows).all() def save_market_states(self, config_file_path: str, market: ConnectorBase, session: Session): market_states: Optional[MarketState] = self.get_market_states(config_file_path, market, session=session) timestamp: int = self.db_timestamp if market_states is not None: market_states.saved_state = market.tracking_states market_states.timestamp = timestamp else: market_states = MarketState(config_file_path=config_file_path, market=market.display_name, timestamp=timestamp, saved_state=market.tracking_states) session.add(market_states) def restore_market_states(self, config_file_path: str, market: ConnectorBase): with self._sql_manager.get_new_session() as session: market_states: Optional[MarketState] = self.get_market_states(config_file_path, market, session=session) if market_states is not None: market.restore_tracking_states(market_states.saved_state) def get_market_states(self, config_file_path: str, market: ConnectorBase, session: Session) -> Optional[MarketState]: query: Query = (session .query(MarketState) .filter(MarketState.config_file_path == config_file_path, MarketState.market == market.display_name)) market_states: Optional[MarketState] = query.one_or_none() return market_states def _did_create_order(self, event_tag: int, market: ConnectorBase, evt: Union[BuyOrderCreatedEvent, SellOrderCreatedEvent]): if threading.current_thread() != threading.main_thread(): self._ev_loop.call_soon_threadsafe(self._did_create_order, event_tag, market, evt) return base_asset, quote_asset = evt.trading_pair.split("-") timestamp: int = self.db_timestamp event_type: MarketEvent = self.market_event_tag_map[event_tag] with self._sql_manager.get_new_session() as session: with session.begin(): order_record: Order = Order(id=evt.order_id, config_file_path=self._config_file_path, strategy=self._strategy_name, market=market.display_name, symbol=evt.trading_pair, base_asset=base_asset, quote_asset=quote_asset, creation_timestamp=timestamp, order_type=evt.type.name, amount=Decimal(evt.amount), leverage=evt.leverage if evt.leverage else 1, price=Decimal(evt.price) if evt.price == evt.price else Decimal(0), position=evt.position if evt.position else "NILL", last_status=event_type.name, last_update_timestamp=timestamp, exchange_order_id=evt.exchange_order_id) order_status: OrderStatus = OrderStatus(order=order_record, timestamp=timestamp, status=event_type.name) session.add(order_record) session.add(order_status) market.add_exchange_order_ids_from_market_recorder({evt.exchange_order_id: evt.order_id}) self.save_market_states(self._config_file_path, market, session=session) def _did_fill_order(self, event_tag: int, market: ConnectorBase, evt: OrderFilledEvent): if threading.current_thread() != threading.main_thread(): self._ev_loop.call_soon_threadsafe(self._did_fill_order, event_tag, market, evt) return base_asset, quote_asset = evt.trading_pair.split("-") timestamp: int = self.db_timestamp event_type: MarketEvent = self.market_event_tag_map[event_tag] order_id: str = evt.order_id with self._sql_manager.get_new_session() as session: with session.begin(): # Try to find the order record, and update it if necessary. order_record: Optional[Order] = session.query(Order).filter(Order.id == order_id).one_or_none() if order_record is not None: order_record.last_status = event_type.name order_record.last_update_timestamp = timestamp # Order status and trade fill record should be added even if the order record is not found, because it's # possible for fill event to come in before the order created event for market orders. order_status: OrderStatus = OrderStatus(order_id=order_id, timestamp=timestamp, status=event_type.name) trade_fill_record: TradeFill = TradeFill(config_file_path=self.config_file_path, strategy=self.strategy_name, market=market.display_name, symbol=evt.trading_pair, base_asset=base_asset, quote_asset=quote_asset, timestamp=timestamp, order_id=order_id, trade_type=evt.trade_type.name, order_type=evt.order_type.name, price=Decimal(evt.price) if evt.price == evt.price else Decimal(0), amount=Decimal(evt.amount), leverage=evt.leverage if evt.leverage else 1, trade_fee=evt.trade_fee.to_json(), exchange_trade_id=evt.exchange_trade_id, position=evt.position if evt.position else "NILL", ) session.add(order_status) session.add(trade_fill_record) self.save_market_states(self._config_file_path, market, session=session) market.add_trade_fills_from_market_recorder({TradeFillOrderDetails(trade_fill_record.market, trade_fill_record.exchange_trade_id, trade_fill_record.symbol)}) self.append_to_csv(trade_fill_record) def _did_complete_funding_payment(self, event_tag: int, market: ConnectorBase, evt: FundingPaymentCompletedEvent): if threading.current_thread() != threading.main_thread(): self._ev_loop.call_soon_threadsafe(self._did_complete_funding_payment, event_tag, market, evt) return session: Session = self.session timestamp: float = evt.timestamp with self._sql_manager.get_new_session() as session: with session.begin(): # Try to find the funding payment has been recorded already. payment_record: Optional[FundingPayment] = session.query(FundingPayment).filter( FundingPayment.timestamp == timestamp).one_or_none() if payment_record is None: funding_payment_record: FundingPayment = FundingPayment(timestamp=timestamp, config_file_path=self.config_file_path, market=market.display_name, rate=evt.funding_rate, symbol=evt.trading_pair, amount=float(evt.amount)) session.add(funding_payment_record) @staticmethod def _is_primitive_type(obj: object) -> bool: return not hasattr(obj, '__dict__') @staticmethod def _is_protected_method(method_name: str) -> bool: return method_name.startswith('_') @staticmethod def _csv_matches_header(file_path: str, header: tuple) -> bool: df = pd.read_csv(file_path, header=None) return tuple(df.iloc[0].values) == header def append_to_csv(self, trade: TradeFill): csv_filename = "trades_" + trade.config_file_path[:-4] + ".csv" csv_path = os.path.join(data_path(), csv_filename) field_names = ("exchange_trade_id",) # id field should be first field_names += tuple(attr for attr in dir(trade) if (not self._is_protected_method(attr) and self._is_primitive_type(getattr(trade, attr)) and (attr not in field_names))) field_data = tuple(getattr(trade, attr) for attr in field_names) # adding extra field "age" # // indicates order is a paper order so 'n/a'. For real orders, calculate age. age = pd.Timestamp(int(trade.timestamp / 1e3 - int(trade.order_id[-16:]) / 1e6), unit='s').strftime( '%H:%M:%S') if "//" not in trade.order_id else "n/a" field_names += ("age",) field_data += (age,) if (os.path.exists(csv_path) and (not self._csv_matches_header(csv_path, field_names))): move(csv_path, csv_path[:-4] + '_old_' + pd.Timestamp.utcnow().strftime("%Y%m%d-%H%M%S") + ".csv") if not os.path.exists(csv_path): df_header = pd.DataFrame([field_names]) df_header.to_csv(csv_path, mode='a', header=False, index=False) df = pd.DataFrame([field_data]) df.to_csv(csv_path, mode='a', header=False, index=False) def _update_order_status(self, event_tag: int, market: ConnectorBase, evt: Union[OrderCancelledEvent, MarketOrderFailureEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent, OrderExpiredEvent]): if threading.current_thread() != threading.main_thread(): self._ev_loop.call_soon_threadsafe(self._update_order_status, event_tag, market, evt) return timestamp: int = self.db_timestamp event_type: MarketEvent = self.market_event_tag_map[event_tag] order_id: str = evt.order_id with self._sql_manager.get_new_session() as session: with session.begin(): order_record: Optional[Order] = session.query(Order).filter(Order.id == order_id).one_or_none() if order_record is not None: order_record.last_status = event_type.name order_record.last_update_timestamp = timestamp order_status: OrderStatus = OrderStatus(order_id=order_id, timestamp=timestamp, status=event_type.name) session.add(order_status) self.save_market_states(self._config_file_path, market, session=session) def _did_cancel_order(self, event_tag: int, market: ConnectorBase, evt: OrderCancelledEvent): self._update_order_status(event_tag, market, evt) def _did_fail_order(self, event_tag: int, market: ConnectorBase, evt: MarketOrderFailureEvent): self._update_order_status(event_tag, market, evt) def _did_complete_order(self, event_tag: int, market: ConnectorBase, evt: Union[BuyOrderCompletedEvent, SellOrderCompletedEvent]): self._update_order_status(event_tag, market, evt) def _did_expire_order(self, event_tag: int, market: ConnectorBase, evt: OrderExpiredEvent): self._update_order_status(event_tag, market, evt) def _did_initiate_range_position(self, event_tag: int, connector: ConnectorBase, evt: RangePositionInitiatedEvent): if threading.current_thread() != threading.main_thread(): self._ev_loop.call_soon_threadsafe(self._did_initiate_range_position, event_tag, connector, evt) return timestamp: int = self.db_timestamp with self._sql_manager.get_new_session() as session: with session.begin(): r_pos: RangePosition = RangePosition(hb_id=evt.hb_id, config_file_path=self._config_file_path, strategy=self._strategy_name, tx_hash=evt.tx_hash, connector=connector.display_name, trading_pair=evt.trading_pair, fee_tier=str(evt.fee_tier), lower_price=float(evt.lower_price), upper_price=float(evt.upper_price), base_amount=float(evt.base_amount), quote_amount=float(evt.quote_amount), status=evt.status, creation_timestamp=timestamp, last_update_timestamp=timestamp) session.add(r_pos) self.save_market_states(self._config_file_path, connector, session=session) def _did_update_range_position(self, event_tag: int, connector: ConnectorBase, evt: RangePositionUpdatedEvent): if threading.current_thread() != threading.main_thread(): self._ev_loop.call_soon_threadsafe(self._did_update_range_position, event_tag, connector, evt) return timestamp: int = self.db_timestamp with self._sql_manager.get_new_session() as session: with session.begin(): rp_record: Optional[RangePosition] = session.query(RangePosition).filter( RangePosition.hb_id == evt.hb_id).one_or_none() if rp_record is not None: rp_update: RangePositionUpdate = RangePositionUpdate(hb_id=evt.hb_id, timestamp=timestamp, tx_hash=evt.tx_hash, token_id=evt.token_id, base_amount=float(evt.base_amount), quote_amount=float(evt.quote_amount), status=evt.status, ) session.add(rp_update) self.save_market_states(self._config_file_path, connector, session=session)
[ "hummingbot.model.trade_fill.TradeFill.timestamp.desc", "hummingbot.connector.utils.TradeFillOrderDetails", "hummingbot.core.event.events.MarketEvent.__members__.values", "hummingbot.data_path", "hummingbot.model.order_status.OrderStatus", "hummingbot.model.order.Order.exchange_order_id.isnot", "humming...
[((1903, 1927), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1925, 1927), False, 'import asyncio\n'), ((2977, 3025), 'hummingbot.core.event.event_forwarder.SourceInfoEventForwarder', 'SourceInfoEventForwarder', (['self._did_create_order'], {}), '(self._did_create_order)\n', (3001, 3025), False, 'from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder\n'), ((3089, 3135), 'hummingbot.core.event.event_forwarder.SourceInfoEventForwarder', 'SourceInfoEventForwarder', (['self._did_fill_order'], {}), '(self._did_fill_order)\n', (3113, 3135), False, 'from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder\n'), ((3201, 3249), 'hummingbot.core.event.event_forwarder.SourceInfoEventForwarder', 'SourceInfoEventForwarder', (['self._did_cancel_order'], {}), '(self._did_cancel_order)\n', (3225, 3249), False, 'from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder\n'), ((3313, 3359), 'hummingbot.core.event.event_forwarder.SourceInfoEventForwarder', 'SourceInfoEventForwarder', (['self._did_fail_order'], {}), '(self._did_fail_order)\n', (3337, 3359), False, 'from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder\n'), ((3427, 3477), 'hummingbot.core.event.event_forwarder.SourceInfoEventForwarder', 'SourceInfoEventForwarder', (['self._did_complete_order'], {}), '(self._did_complete_order)\n', (3451, 3477), False, 'from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder\n'), ((3543, 3591), 'hummingbot.core.event.event_forwarder.SourceInfoEventForwarder', 'SourceInfoEventForwarder', (['self._did_expire_order'], {}), '(self._did_expire_order)\n', (3567, 3591), False, 'from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder\n'), ((3660, 3720), 'hummingbot.core.event.event_forwarder.SourceInfoEventForwarder', 'SourceInfoEventForwarder', (['self._did_complete_funding_payment'], {}), '(self._did_complete_funding_payment)\n', (3684, 3720), False, 'from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder\n'), ((3809, 3868), 'hummingbot.core.event.event_forwarder.SourceInfoEventForwarder', 'SourceInfoEventForwarder', (['self._did_initiate_range_position'], {}), '(self._did_initiate_range_position)\n', (3833, 3868), False, 'from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder\n'), ((3956, 4013), 'hummingbot.core.event.event_forwarder.SourceInfoEventForwarder', 'SourceInfoEventForwarder', (['self._did_update_range_position'], {}), '(self._did_update_range_position)\n', (3980, 4013), False, 'from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder\n'), ((16633, 16668), 'pandas.read_csv', 'pd.read_csv', (['file_path'], {'header': 'None'}), '(file_path, header=None)\n', (16644, 16668), True, 'import pandas as pd\n'), ((18097, 18123), 'pandas.DataFrame', 'pd.DataFrame', (['[field_data]'], {}), '([field_data])\n', (18109, 18123), True, 'import pandas as pd\n'), ((1453, 1485), 'hummingbot.core.event.events.MarketEvent.__members__.values', 'MarketEvent.__members__.values', ([], {}), '()\n', (1483, 1485), False, 'from hummingbot.core.event.events import BuyOrderCompletedEvent, BuyOrderCreatedEvent, FundingPaymentCompletedEvent, MarketEvent, MarketOrderFailureEvent, OrderCancelledEvent, OrderExpiredEvent, OrderFilledEvent, RangePositionInitiatedEvent, RangePositionUpdatedEvent, SellOrderCompletedEvent, SellOrderCreatedEvent\n'), ((1696, 1722), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (1720, 1722), False, 'import threading\n'), ((1726, 1749), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (1747, 1749), False, 'import threading\n'), ((7610, 7745), 'hummingbot.model.market_state.MarketState', 'MarketState', ([], {'config_file_path': 'config_file_path', 'market': 'market.display_name', 'timestamp': 'timestamp', 'saved_state': 'market.tracking_states'}), '(config_file_path=config_file_path, market=market.display_name,\n timestamp=timestamp, saved_state=market.tracking_states)\n', (7621, 7745), False, 'from hummingbot.model.market_state import MarketState\n'), ((9030, 9056), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (9054, 9056), False, 'import threading\n'), ((9060, 9083), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (9081, 9083), False, 'import threading\n'), ((11406, 11432), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (11430, 11432), False, 'import threading\n'), ((11436, 11459), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (11457, 11459), False, 'import threading\n'), ((14979, 15005), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (15003, 15005), False, 'import threading\n'), ((15009, 15032), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (15030, 15032), False, 'import threading\n'), ((16871, 16882), 'hummingbot.data_path', 'data_path', ([], {}), '()\n', (16880, 16882), False, 'from hummingbot import data_path\n'), ((17980, 18007), 'pandas.DataFrame', 'pd.DataFrame', (['[field_names]'], {}), '([field_names])\n', (17992, 18007), True, 'import pandas as pd\n'), ((18649, 18675), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (18673, 18675), False, 'import threading\n'), ((18679, 18702), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (18700, 18702), False, 'import threading\n'), ((20960, 20986), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (20984, 20986), False, 'import threading\n'), ((20990, 21013), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (21011, 21013), False, 'import threading\n'), ((22815, 22841), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (22839, 22841), False, 'import threading\n'), ((22845, 22868), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (22866, 22868), False, 'import threading\n'), ((5306, 5317), 'time.time', 'time.time', ([], {}), '()\n', (5315, 5317), False, 'import time\n'), ((6985, 7011), 'hummingbot.model.trade_fill.TradeFill.timestamp.desc', 'TradeFill.timestamp.desc', ([], {}), '()\n', (7009, 7011), False, 'from hummingbot.model.trade_fill import TradeFill\n'), ((10761, 10837), 'hummingbot.model.order_status.OrderStatus', 'OrderStatus', ([], {'order': 'order_record', 'timestamp': 'timestamp', 'status': 'event_type.name'}), '(order=order_record, timestamp=timestamp, status=event_type.name)\n', (10772, 10837), False, 'from hummingbot.model.order_status import OrderStatus\n'), ((12515, 12590), 'hummingbot.model.order_status.OrderStatus', 'OrderStatus', ([], {'order_id': 'order_id', 'timestamp': 'timestamp', 'status': 'event_type.name'}), '(order_id=order_id, timestamp=timestamp, status=event_type.name)\n', (12526, 12590), False, 'from hummingbot.model.order_status import OrderStatus\n'), ((2427, 2492), 'hummingbot.connector.utils.TradeFillOrderDetails', 'TradeFillOrderDetails', (['tf.market', 'tf.exchange_trade_id', 'tf.symbol'], {}), '(tf.market, tf.exchange_trade_id, tf.symbol)\n', (2448, 2492), False, 'from hummingbot.connector.utils import TradeFillOrderDetails\n'), ((6227, 6262), 'hummingbot.model.order.Order.exchange_order_id.isnot', 'Order.exchange_order_id.isnot', (['None'], {}), '(None)\n', (6256, 6262), False, 'from hummingbot.model.order import Order\n'), ((19405, 19480), 'hummingbot.model.order_status.OrderStatus', 'OrderStatus', ([], {'order_id': 'order_id', 'timestamp': 'timestamp', 'status': 'event_type.name'}), '(order_id=order_id, timestamp=timestamp, status=event_type.name)\n', (19416, 19480), False, 'from hummingbot.model.order_status import OrderStatus\n'), ((10164, 10183), 'decimal.Decimal', 'Decimal', (['evt.amount'], {}), '(evt.amount)\n', (10171, 10183), False, 'from decimal import Decimal\n'), ((13737, 13756), 'decimal.Decimal', 'Decimal', (['evt.amount'], {}), '(evt.amount)\n', (13744, 13756), False, 'from decimal import Decimal\n'), ((14401, 14516), 'hummingbot.connector.utils.TradeFillOrderDetails', 'TradeFillOrderDetails', (['trade_fill_record.market', 'trade_fill_record.exchange_trade_id', 'trade_fill_record.symbol'], {}), '(trade_fill_record.market, trade_fill_record.\n exchange_trade_id, trade_fill_record.symbol)\n', (14422, 14516), False, 'from hummingbot.connector.utils import TradeFillOrderDetails\n'), ((10325, 10343), 'decimal.Decimal', 'Decimal', (['evt.price'], {}), '(evt.price)\n', (10332, 10343), False, 'from decimal import Decimal\n'), ((10375, 10385), 'decimal.Decimal', 'Decimal', (['(0)'], {}), '(0)\n', (10382, 10385), False, 'from decimal import Decimal\n'), ((13611, 13629), 'decimal.Decimal', 'Decimal', (['evt.price'], {}), '(evt.price)\n', (13618, 13629), False, 'from decimal import Decimal\n'), ((13661, 13671), 'decimal.Decimal', 'Decimal', (['(0)'], {}), '(0)\n', (13668, 13671), False, 'from decimal import Decimal\n'), ((17856, 17877), 'pandas.Timestamp.utcnow', 'pd.Timestamp.utcnow', ([], {}), '()\n', (17875, 17877), True, 'import pandas as pd\n')]
import logging from typing import List, Optional from hummingbot.connector.exchange.bitfinex.bitfinex_api_user_stream_data_source import BitfinexAPIUserStreamDataSource from hummingbot.connector.exchange.bitfinex.bitfinex_auth import BitfinexAuth from hummingbot.core.data_type.user_stream_tracker import UserStreamTracker from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather from hummingbot.logger import HummingbotLogger class BitfinexUserStreamTracker(UserStreamTracker): _cbpust_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._bust_logger is None: cls._bust_logger = logging.getLogger(__name__) return cls._bust_logger def __init__( self, bitfinex_auth: Optional[BitfinexAuth] = None, trading_pairs=None, ): self._bitfinex_auth: BitfinexAuth = bitfinex_auth self._trading_pairs: List[str] = trading_pairs or [] super().__init__(data_source=BitfinexAPIUserStreamDataSource( bitfinex_auth=self._bitfinex_auth, trading_pairs=self._trading_pairs )) @property def data_source(self) -> UserStreamTrackerDataSource: """ """ if not self._data_source: self._data_source = BitfinexAPIUserStreamDataSource( bitfinex_auth=self._bitfinex_auth, trading_pairs=self._trading_pairs ) return self._data_source @property def exchange_name(self) -> str: """ *required Name of the current exchange """ return "bitfinex" async def start(self): """ *required Start all listeners and tasks """ self._user_stream_tracking_task = safe_ensure_future( self.data_source.listen_for_user_stream(self._user_stream) ) await safe_gather(self._user_stream_tracking_task)
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.connector.exchange.bitfinex.bitfinex_api_user_stream_data_source.BitfinexAPIUserStreamDataSource" ]
[((782, 809), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (799, 809), False, 'import logging\n'), ((1421, 1526), 'hummingbot.connector.exchange.bitfinex.bitfinex_api_user_stream_data_source.BitfinexAPIUserStreamDataSource', 'BitfinexAPIUserStreamDataSource', ([], {'bitfinex_auth': 'self._bitfinex_auth', 'trading_pairs': 'self._trading_pairs'}), '(bitfinex_auth=self._bitfinex_auth,\n trading_pairs=self._trading_pairs)\n', (1452, 1526), False, 'from hummingbot.connector.exchange.bitfinex.bitfinex_api_user_stream_data_source import BitfinexAPIUserStreamDataSource\n'), ((2007, 2051), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['self._user_stream_tracking_task'], {}), '(self._user_stream_tracking_task)\n', (2018, 2051), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((1120, 1225), 'hummingbot.connector.exchange.bitfinex.bitfinex_api_user_stream_data_source.BitfinexAPIUserStreamDataSource', 'BitfinexAPIUserStreamDataSource', ([], {'bitfinex_auth': 'self._bitfinex_auth', 'trading_pairs': 'self._trading_pairs'}), '(bitfinex_auth=self._bitfinex_auth,\n trading_pairs=self._trading_pairs)\n', (1151, 1225), False, 'from hummingbot.connector.exchange.bitfinex.bitfinex_api_user_stream_data_source import BitfinexAPIUserStreamDataSource\n')]
#!/usr/bin/env python import asyncio import ujson import aiohttp import logging import pandas as pd from typing import ( Any, AsyncIterable, Dict, List, Optional ) from decimal import Decimal import requests import cachetools.func import time import websockets from websockets.exceptions import ConnectionClosed from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource from hummingbot.core.data_type.order_book_message import OrderBookMessage from hummingbot.core.data_type.order_book import OrderBook from hummingbot.logger import HummingbotLogger from hummingbot.connector.exchange.dexfin.dexfin_order_book import DexfinOrderBook from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_to_exchange_trading_pair SNAPSHOT_REST_URL = "https://test.dexfin.dev/api/v2/peatio/public/markets/{0}/depth" DIFF_STREAM_URL = "wss://test.dexfin.dev/api/v2/ranger/public/" TICKER_PRICE_CHANGE_URL = "https://test.dexfin.dev/api/v2/peatio/public/markets" EXCHANGE_INFO_URL = "https://test.dexfin.dev/api/v2/peatio/public/markets" class DexfinAPIOrderBookDataSource(OrderBookTrackerDataSource): MESSAGE_TIMEOUT = 30.0 PING_TIMEOUT = 10.0 _kaobds_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._kaobds_logger is None: cls._kaobds_logger = logging.getLogger(__name__) return cls._kaobds_logger def __init__(self, trading_pairs: List[str]): super().__init__(trading_pairs) self._order_book_create_function = lambda: OrderBook() @classmethod async def get_last_traded_prices(cls, trading_pairs: List[str]) -> Dict[str, float]: results = dict() async with aiohttp.ClientSession() as client: resp = await client.get(f"{TICKER_PRICE_CHANGE_URL}/tickers") resp_json = await resp.json() for trading_pair in trading_pairs: if trading_pair not in resp_json: continue market = convert_to_exchange_trading_pair(trading_pair) resp_record = resp_json[market]["tikcer"] results[trading_pair] = float(resp_record["last"]) return results @staticmethod @cachetools.func.ttl_cache(ttl=10) def get_mid_price(trading_pair: str) -> Optional[Decimal]: from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_to_exchange_trading_pair market = convert_to_exchange_trading_pair(trading_pair) resp = requests.get(url=f"{TICKER_PRICE_CHANGE_URL}/{market}/tickers") record = resp.json() result = Decimal(record["ticker"]["avg_price"]) return result if result else None @staticmethod async def fetch_trading_pairs() -> List[str]: try: from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_from_exchange_trading_pair async with aiohttp.ClientSession() as client: async with client.get(EXCHANGE_INFO_URL, timeout=10) as response: if response.status == 200: data = await response.json() raw_trading_pairs = [d["id"] for d in data if d["state"] == "enabled"] trading_pair_list: List[str] = [] for raw_trading_pair in raw_trading_pairs: converted_trading_pair: Optional[str] = \ convert_from_exchange_trading_pair(raw_trading_pair) if converted_trading_pair is not None: trading_pair_list.append(converted_trading_pair) return trading_pair_list except Exception: # Do nothing if the request fails -- there will be no autocomplete for dexfin trading pairs pass return [] @staticmethod async def get_snapshot(client: aiohttp.ClientSession, trading_pair: str, limit: int = 1000) -> Dict[str, Any]: params: Dict = {"limit": str(limit)} if limit != 0 else {} market = convert_to_exchange_trading_pair(trading_pair) async with client.get(SNAPSHOT_REST_URL.format(market), params=params) as response: response: aiohttp.ClientResponse = response if response.status != 200: raise IOError(f"Error fetching Dexfin market snapshot for {trading_pair}. " f"HTTP status is {response.status}.") data: Dict[str, Any] = await response.json() # Need to add the symbol into the snapshot message for the Kafka message queue. # Because otherwise, there'd be no way for the receiver to know which market the # snapshot belongs to. return data async def get_new_order_book(self, trading_pair: str) -> OrderBook: market = convert_to_exchange_trading_pair(trading_pair) async with aiohttp.ClientSession() as client: snapshot: Dict[str, Any] = await self.get_snapshot(client, market, 1000) snapshot_timestamp: float = time.time() snapshot_msg: OrderBookMessage = DexfinOrderBook.snapshot_message_from_exchange( snapshot, snapshot_timestamp, metadata={"trading_pair": trading_pair} ) order_book = self.order_book_create_function() order_book.apply_snapshot(snapshot_msg.bids, snapshot_msg.asks, snapshot_msg.update_id) return order_book async def _inner_messages(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]: # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect. try: while True: try: msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT) yield msg except asyncio.TimeoutError: try: pong_waiter = await ws.ping() await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT) except asyncio.TimeoutError: raise except asyncio.TimeoutError: self.logger().warning("WebSocket ping timed out. Going to reconnect...") return except ConnectionClosed: return finally: await ws.close() async def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): while True: try: converted_pairs = [] for trading_pair in self._trading_pairs: converted_pairs.append(convert_to_exchange_trading_pair(trading_pair).lower()) ws_path: str = "&".join([f"stream={trading_pair}.trades" for trading_pair in converted_pairs]) stream_url: str = f"{DIFF_STREAM_URL}?{ws_path}" logging.info(f"Connecting to {stream_url}") async with websockets.connect(stream_url) as ws: ws: websockets.WebSocketClientProtocol = ws async for raw_msg in self._inner_messages(ws): msg = ujson.loads(raw_msg) market, topic = None, None for item in msg.items(): if "trades" in item[0]: market, topic = item[0].split('.') break for trade in msg[f"{market}.{topic}"][topic]: trade_msg: OrderBookMessage = DexfinOrderBook.trade_message_from_exchange( trade, metadata={"trading_pair": market}) output.put_nowait(trade_msg) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...", exc_info=True) await asyncio.sleep(30.0) async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): while True: try: converted_pairs = [] for trading_pair in self._trading_pairs: converted_pairs.append(convert_to_exchange_trading_pair(trading_pair).lower()) ws_path: str = "&".join([f"stream={trading_pair}.ob-inc" for trading_pair in converted_pairs]) stream_url: str = f"{DIFF_STREAM_URL}?{ws_path}" async with websockets.connect(stream_url) as ws: ws: websockets.WebSocketClientProtocol = ws async for raw_msg in self._inner_messages(ws): msg = ujson.loads(raw_msg) market, topic = None, None for item in msg.items(): if "ob-inc" in item[0]: market, topic = item[0].split('.') break if market is None or topic is None: continue if topic and 'ob-snap' not in topic: continue obook = msg[f"{market}.{topic}"] order_book_message: OrderBookMessage = DexfinOrderBook.diff_message_from_exchange( obook, time.time(), metadata={"trading_pair": market}) output.put_nowait(order_book_message) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...", exc_info=True) await asyncio.sleep(30.0) async def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): while True: try: async with aiohttp.ClientSession() as client: for trading_pair in self._trading_pairs: try: snapshot: Dict[str, Any] = await self.get_snapshot(client, trading_pair) snapshot_timestamp: float = time.time() snapshot_msg: OrderBookMessage = DexfinOrderBook.snapshot_message_from_exchange( snapshot, snapshot_timestamp, metadata={"trading_pair": trading_pair} ) output.put_nowait(snapshot_msg) self.logger().debug(f"Saved order book snapshot for {trading_pair}") await asyncio.sleep(5.0) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error.", exc_info=True) await asyncio.sleep(5.0) this_hour: pd.Timestamp = pd.Timestamp.utcnow().replace(minute=0, second=0, microsecond=0) next_hour: pd.Timestamp = this_hour + pd.Timedelta(hours=1) delta: float = next_hour.timestamp() - time.time() await asyncio.sleep(delta) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error.", exc_info=True) await asyncio.sleep(5.0)
[ "hummingbot.connector.exchange.dexfin.dexfin_order_book.DexfinOrderBook.trade_message_from_exchange", "hummingbot.core.data_type.order_book.OrderBook", "hummingbot.connector.exchange.dexfin.dexfin_order_book.DexfinOrderBook.snapshot_message_from_exchange", "hummingbot.connector.exchange.dexfin.dexfin_utils.co...
[((2503, 2549), 'hummingbot.connector.exchange.dexfin.dexfin_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (2535, 2549), False, 'from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_to_exchange_trading_pair\n'), ((2565, 2628), 'requests.get', 'requests.get', ([], {'url': 'f"""{TICKER_PRICE_CHANGE_URL}/{market}/tickers"""'}), "(url=f'{TICKER_PRICE_CHANGE_URL}/{market}/tickers')\n", (2577, 2628), False, 'import requests\n'), ((2675, 2713), 'decimal.Decimal', 'Decimal', (["record['ticker']['avg_price']"], {}), "(record['ticker']['avg_price'])\n", (2682, 2713), False, 'from decimal import Decimal\n'), ((4143, 4189), 'hummingbot.connector.exchange.dexfin.dexfin_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (4175, 4189), False, 'from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_to_exchange_trading_pair\n'), ((4930, 4976), 'hummingbot.connector.exchange.dexfin.dexfin_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (4962, 4976), False, 'from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_to_exchange_trading_pair\n'), ((1397, 1424), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1414, 1424), False, 'import logging\n'), ((1601, 1612), 'hummingbot.core.data_type.order_book.OrderBook', 'OrderBook', ([], {}), '()\n', (1610, 1612), False, 'from hummingbot.core.data_type.order_book import OrderBook\n'), ((1764, 1787), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (1785, 1787), False, 'import aiohttp\n'), ((4996, 5019), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (5017, 5019), False, 'import aiohttp\n'), ((5156, 5167), 'time.time', 'time.time', ([], {}), '()\n', (5165, 5167), False, 'import time\n'), ((5213, 5334), 'hummingbot.connector.exchange.dexfin.dexfin_order_book.DexfinOrderBook.snapshot_message_from_exchange', 'DexfinOrderBook.snapshot_message_from_exchange', (['snapshot', 'snapshot_timestamp'], {'metadata': "{'trading_pair': trading_pair}"}), "(snapshot, snapshot_timestamp,\n metadata={'trading_pair': trading_pair})\n", (5259, 5334), False, 'from hummingbot.connector.exchange.dexfin.dexfin_order_book import DexfinOrderBook\n'), ((2066, 2112), 'hummingbot.connector.exchange.dexfin.dexfin_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (2098, 2112), False, 'from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_to_exchange_trading_pair\n'), ((2970, 2993), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (2991, 2993), False, 'import aiohttp\n'), ((7050, 7093), 'logging.info', 'logging.info', (['f"""Connecting to {stream_url}"""'], {}), "(f'Connecting to {stream_url}')\n", (7062, 7093), False, 'import logging\n'), ((7122, 7152), 'websockets.connect', 'websockets.connect', (['stream_url'], {}), '(stream_url)\n', (7140, 7152), False, 'import websockets\n'), ((8742, 8772), 'websockets.connect', 'websockets.connect', (['stream_url'], {}), '(stream_url)\n', (8760, 8772), False, 'import websockets\n'), ((10196, 10219), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (10217, 10219), False, 'import aiohttp\n'), ((7321, 7341), 'ujson.loads', 'ujson.loads', (['raw_msg'], {}), '(raw_msg)\n', (7332, 7341), False, 'import ujson\n'), ((8183, 8202), 'asyncio.sleep', 'asyncio.sleep', (['(30.0)'], {}), '(30.0)\n', (8196, 8202), False, 'import asyncio\n'), ((8941, 8961), 'ujson.loads', 'ujson.loads', (['raw_msg'], {}), '(raw_msg)\n', (8952, 8961), False, 'import ujson\n'), ((10003, 10022), 'asyncio.sleep', 'asyncio.sleep', (['(30.0)'], {}), '(30.0)\n', (10016, 10022), False, 'import asyncio\n'), ((11442, 11463), 'pandas.Timedelta', 'pd.Timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (11454, 11463), True, 'import pandas as pd\n'), ((11523, 11534), 'time.time', 'time.time', ([], {}), '()\n', (11532, 11534), False, 'import time\n'), ((11561, 11581), 'asyncio.sleep', 'asyncio.sleep', (['delta'], {}), '(delta)\n', (11574, 11581), False, 'import asyncio\n'), ((11771, 11789), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (11784, 11789), False, 'import asyncio\n'), ((3509, 3561), 'hummingbot.connector.exchange.dexfin.dexfin_utils.convert_from_exchange_trading_pair', 'convert_from_exchange_trading_pair', (['raw_trading_pair'], {}), '(raw_trading_pair)\n', (3543, 3561), False, 'from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_from_exchange_trading_pair\n'), ((7727, 7816), 'hummingbot.connector.exchange.dexfin.dexfin_order_book.DexfinOrderBook.trade_message_from_exchange', 'DexfinOrderBook.trade_message_from_exchange', (['trade'], {'metadata': "{'trading_pair': market}"}), "(trade, metadata={'trading_pair':\n market})\n", (7770, 7816), False, 'from hummingbot.connector.exchange.dexfin.dexfin_order_book import DexfinOrderBook\n'), ((9613, 9624), 'time.time', 'time.time', ([], {}), '()\n', (9622, 9624), False, 'import time\n'), ((10478, 10489), 'time.time', 'time.time', ([], {}), '()\n', (10487, 10489), False, 'import time\n'), ((10551, 10672), 'hummingbot.connector.exchange.dexfin.dexfin_order_book.DexfinOrderBook.snapshot_message_from_exchange', 'DexfinOrderBook.snapshot_message_from_exchange', (['snapshot', 'snapshot_timestamp'], {'metadata': "{'trading_pair': trading_pair}"}), "(snapshot, snapshot_timestamp,\n metadata={'trading_pair': trading_pair})\n", (10597, 10672), False, 'from hummingbot.connector.exchange.dexfin.dexfin_order_book import DexfinOrderBook\n'), ((11319, 11340), 'pandas.Timestamp.utcnow', 'pd.Timestamp.utcnow', ([], {}), '()\n', (11338, 11340), True, 'import pandas as pd\n'), ((6157, 6213), 'asyncio.wait_for', 'asyncio.wait_for', (['pong_waiter'], {'timeout': 'self.PING_TIMEOUT'}), '(pong_waiter, timeout=self.PING_TIMEOUT)\n', (6173, 6213), False, 'import asyncio\n'), ((6801, 6847), 'hummingbot.connector.exchange.dexfin.dexfin_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (6833, 6847), False, 'from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_to_exchange_trading_pair\n'), ((8482, 8528), 'hummingbot.connector.exchange.dexfin.dexfin_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (8514, 8528), False, 'from hummingbot.connector.exchange.dexfin.dexfin_utils import convert_to_exchange_trading_pair\n'), ((10986, 11004), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (10999, 11004), False, 'import asyncio\n'), ((11254, 11272), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (11267, 11272), False, 'import asyncio\n')]
import aiohttp import asyncio import random from typing import ( Any, Dict, Optional, ) import ujson from hummingbot.connector.exchange.coinzoom.coinzoom_constants import Constants from hummingbot.connector.exchange.coinzoom.coinzoom_utils import CoinzoomAPIError from hummingbot.core.api_throttler.async_throttler import AsyncThrottler def retry_sleep_time(try_count: int) -> float: random.seed() randSleep = 1 + float(random.randint(1, 10) / 100) return float(2 + float(randSleep * (1 + (try_count ** try_count)))) async def aiohttp_response_with_errors(request_coroutine): http_status, parsed_response, request_errors = None, None, False try: async with request_coroutine as response: http_status = response.status try: parsed_response = await response.json() except Exception: if response.status not in [204]: request_errors = True try: parsed_response = str(await response.read()) if len(parsed_response) > 100: parsed_response = f"{parsed_response[:100]} ... (truncated)" except Exception: pass temp_failure = (parsed_response is None or (response.status not in [200, 201, 204] and "error" not in parsed_response)) if temp_failure: parsed_response = response.reason if parsed_response is None else parsed_response request_errors = True except Exception: request_errors = True return http_status, parsed_response, request_errors async def api_call_with_retries(method, endpoint, extra_headers: Optional[Dict[str, str]] = None, params: Optional[Dict[str, Any]] = None, shared_client=None, try_count: int = 0, throttler: Optional[AsyncThrottler] = None, limit_id: Optional[str] = None) -> Dict[str, Any]: url = f"{Constants.REST_URL}/{endpoint}" headers = {"Content-Type": "application/json", "User-Agent": "hummingbot"} if extra_headers: headers.update(extra_headers) http_client = shared_client or aiohttp.ClientSession() http_throttler = throttler or AsyncThrottler(Constants.RATE_LIMITS) limit_id = limit_id or endpoint # Turn `params` into either GET params or POST body data qs_params: dict = params if method.upper() == "GET" else None req_params = ujson.dumps(params) if method.upper() == "POST" and params is not None else None async with http_throttler.execute_task(limit_id): # Build request coro response_coro = http_client.request(method=method.upper(), url=url, headers=headers, params=qs_params, data=req_params, timeout=Constants.API_CALL_TIMEOUT) http_status, parsed_response, request_errors = await aiohttp_response_with_errors(response_coro) if shared_client is None: await http_client.close() if request_errors or parsed_response is None: if try_count < Constants.API_MAX_RETRIES: try_count += 1 time_sleep = retry_sleep_time(try_count) print(f"Error fetching data from {url}. HTTP status is {http_status}. " f"Retrying in {time_sleep:.0f}s.") await asyncio.sleep(time_sleep) return await api_call_with_retries(method=method, endpoint=endpoint, params=params, shared_client=shared_client, try_count=try_count) else: raise CoinzoomAPIError({"error": parsed_response, "status": http_status}) return parsed_response
[ "hummingbot.connector.exchange.coinzoom.coinzoom_utils.CoinzoomAPIError", "hummingbot.core.api_throttler.async_throttler.AsyncThrottler" ]
[((405, 418), 'random.seed', 'random.seed', ([], {}), '()\n', (416, 418), False, 'import random\n'), ((2405, 2428), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (2426, 2428), False, 'import aiohttp\n'), ((2463, 2500), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['Constants.RATE_LIMITS'], {}), '(Constants.RATE_LIMITS)\n', (2477, 2500), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((2682, 2701), 'ujson.dumps', 'ujson.dumps', (['params'], {}), '(params)\n', (2693, 2701), False, 'import ujson\n'), ((3811, 3878), 'hummingbot.connector.exchange.coinzoom.coinzoom_utils.CoinzoomAPIError', 'CoinzoomAPIError', (["{'error': parsed_response, 'status': http_status}"], {}), "({'error': parsed_response, 'status': http_status})\n", (3827, 3878), False, 'from hummingbot.connector.exchange.coinzoom.coinzoom_utils import CoinzoomAPIError\n'), ((445, 466), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (459, 466), False, 'import random\n'), ((3560, 3585), 'asyncio.sleep', 'asyncio.sleep', (['time_sleep'], {}), '(time_sleep)\n', (3573, 3585), False, 'import asyncio\n')]
import unittest from copy import deepcopy from hummingbot.client.settings import AllConnectorSettings from hummingbot.strategy.arbitrage.arbitrage_config_map import ( arbitrage_config_map, primary_trading_pair_prompt, secondary_trading_pair_prompt ) class ArbitrageConfigMapTest(unittest.TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.primary_exchange = "binance" cls.secondary_exchange = "kucoin" def setUp(self) -> None: super().setUp() self.config_backup = deepcopy(arbitrage_config_map) def tearDown(self) -> None: self.reset_config_map() super().tearDown() def reset_config_map(self): for key, value in self.config_backup.items(): arbitrage_config_map[key] = value def test_primary_trading_pair_prompt(self): arbitrage_config_map["primary_market"].value = self.primary_exchange example = AllConnectorSettings.get_example_pairs().get(self.primary_exchange) prompt = primary_trading_pair_prompt() expected = f"Enter the token trading pair you would like to trade on {self.primary_exchange} (e.g. {example}) >>> " self.assertEqual(expected, prompt) def test_secondary_trading_pair_prompt(self): arbitrage_config_map["secondary_market"].value = self.secondary_exchange example = AllConnectorSettings.get_example_pairs().get(self.secondary_exchange) prompt = secondary_trading_pair_prompt() expected = f"Enter the token trading pair you would like to trade on {self.secondary_exchange} (e.g. {example}) >>> " self.assertEqual(expected, prompt)
[ "hummingbot.strategy.arbitrage.arbitrage_config_map.primary_trading_pair_prompt", "hummingbot.strategy.arbitrage.arbitrage_config_map.secondary_trading_pair_prompt", "hummingbot.client.settings.AllConnectorSettings.get_example_pairs" ]
[((561, 591), 'copy.deepcopy', 'deepcopy', (['arbitrage_config_map'], {}), '(arbitrage_config_map)\n', (569, 591), False, 'from copy import deepcopy\n'), ((1047, 1076), 'hummingbot.strategy.arbitrage.arbitrage_config_map.primary_trading_pair_prompt', 'primary_trading_pair_prompt', ([], {}), '()\n', (1074, 1076), False, 'from hummingbot.strategy.arbitrage.arbitrage_config_map import arbitrage_config_map, primary_trading_pair_prompt, secondary_trading_pair_prompt\n'), ((1483, 1514), 'hummingbot.strategy.arbitrage.arbitrage_config_map.secondary_trading_pair_prompt', 'secondary_trading_pair_prompt', ([], {}), '()\n', (1512, 1514), False, 'from hummingbot.strategy.arbitrage.arbitrage_config_map import arbitrage_config_map, primary_trading_pair_prompt, secondary_trading_pair_prompt\n'), ((961, 1001), 'hummingbot.client.settings.AllConnectorSettings.get_example_pairs', 'AllConnectorSettings.get_example_pairs', ([], {}), '()\n', (999, 1001), False, 'from hummingbot.client.settings import AllConnectorSettings\n'), ((1395, 1435), 'hummingbot.client.settings.AllConnectorSettings.get_example_pairs', 'AllConnectorSettings.get_example_pairs', ([], {}), '()\n', (1433, 1435), False, 'from hummingbot.client.settings import AllConnectorSettings\n')]
#!/usr/bin/env python import asyncio import logging from typing import ( Optional ) from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.logger import HummingbotLogger from hummingbot.core.data_type.user_stream_tracker import ( UserStreamTrackerDataSourceType, UserStreamTracker ) from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from hummingbot.market.loopring.loopring_api_order_book_data_source import LoopringAPIOrderBookDataSource from hummingbot.market.loopring.loopring_api_user_stream_data_source import LoopringAPIUserStreamDataSource from hummingbot.market.loopring.loopring_auth import LoopringAuth class LoopringUserStreamTracker(UserStreamTracker): _krust_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._krust_logger is None: cls._krust_logger = logging.getLogger(__name__) return cls._krust_logger def __init__(self, orderbook_tracker_data_source: LoopringAPIOrderBookDataSource, loopring_auth: LoopringAuth, data_source_type: UserStreamTrackerDataSourceType = UserStreamTrackerDataSourceType.EXCHANGE_API): super().__init__(data_source_type=data_source_type) self._ev_loop: asyncio.events.AbstractEventLoop = asyncio.get_event_loop() self._data_source: Optional[UserStreamTrackerDataSource] = None self._user_stream_tracking_task: Optional[asyncio.Task] = None self._orderbook_tracker_data_source = orderbook_tracker_data_source self._loopring_auth: LoopringAuth = loopring_auth @property def data_source(self) -> UserStreamTrackerDataSource: if not self._data_source: if self._data_source_type is UserStreamTrackerDataSourceType.EXCHANGE_API: self._data_source = LoopringAPIUserStreamDataSource(orderbook_tracker_data_source=self._orderbook_tracker_data_source, loopring_auth=self._loopring_auth) else: raise ValueError(f"data_source_type {self._data_source_type} is not supported.") return self._data_source @property def exchange_name(self) -> str: return "loopring" async def start(self): self._user_stream_tracking_task = safe_ensure_future( self.data_source.listen_for_user_stream(self._ev_loop, self._user_stream) ) await safe_gather(self._user_stream_tracking_task)
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.market.loopring.loopring_api_user_stream_data_source.LoopringAPIUserStreamDataSource" ]
[((1407, 1431), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1429, 1431), False, 'import asyncio\n'), ((962, 989), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (979, 989), False, 'import logging\n'), ((2567, 2611), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['self._user_stream_tracking_task'], {}), '(self._user_stream_tracking_task)\n', (2578, 2611), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((1939, 2077), 'hummingbot.market.loopring.loopring_api_user_stream_data_source.LoopringAPIUserStreamDataSource', 'LoopringAPIUserStreamDataSource', ([], {'orderbook_tracker_data_source': 'self._orderbook_tracker_data_source', 'loopring_auth': 'self._loopring_auth'}), '(orderbook_tracker_data_source=self.\n _orderbook_tracker_data_source, loopring_auth=self._loopring_auth)\n', (1970, 2077), False, 'from hummingbot.market.loopring.loopring_api_user_stream_data_source import LoopringAPIUserStreamDataSource\n')]
from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_validators import ( validate_exchange, validate_market_trading_pair, validate_decimal, validate_bool ) from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS from decimal import Decimal from hummingbot.client.config.config_helpers import ( minimum_order_amount ) from typing import Optional def first_trading_pair_prompt(): maker_market = triangular_arbitrage_config_map.get("market").value example = EXAMPLE_PAIRS.get(maker_market) return "Enter first token trading pair: %s%s >>> " % ( maker_market, f" (e.g. {example})" if example else "", ) def second_trading_pair_prompt(): maker_market = triangular_arbitrage_config_map.get("market").value example = EXAMPLE_PAIRS.get(maker_market) return "Enter second token trading pair: %s%s >>> " % ( maker_market, f" (e.g. {example})" if example else "", ) def third_trading_pair_prompt(): maker_market = triangular_arbitrage_config_map.get("market").value example = EXAMPLE_PAIRS.get(maker_market) return "Enter third token trading pair: %s%s >>> " % ( maker_market, f" (e.g. {example})" if example else "", ) # strategy specific validators def validate_target_asset(value: str) -> Optional[str]: try: """ first = triangular_arbitrage_config_map.get("first_market_trading_pair").value third = triangular_arbitrage_config_map.get("third_market_trading_pair").value if value not in first: return f"The first pair {first.} should contain the target asset {value}." elif value not in third: return f"The first pair {first.} should contain the target asset {value}" """ except Exception: return "Invalid target asset" def validate_trading_pair(value: str) -> Optional[str]: market = triangular_arbitrage_config_map.get("market").value return validate_market_trading_pair(market, value) def order_amount_prompt() -> str: maker_exchange = triangular_arbitrage_config_map["market"].value trading_pair = triangular_arbitrage_config_map.get("first_market_trading_pair").value base_asset, quote_asset = trading_pair.split("-") min_amount = minimum_order_amount(maker_exchange, trading_pair) return f"What is the amount of {base_asset} per order? (minimum {min_amount}) >>>: " def validate_order_amount(value: str) -> Optional[str]: try: maker_exchange = triangular_arbitrage_config_map.get("market").value trading_pair = triangular_arbitrage_config_map.get("first_market_trading_pair").value min_amount = minimum_order_amount(maker_exchange, trading_pair) if Decimal(value) < min_amount: return f"Order amount must be at least {min_amount}." except Exception: return "Invalid order amount." triangular_arbitrage_config_map = { "strategy": ConfigVar( key="strategy", prompt="", default="triangular_arbitrage" ), "market": ConfigVar( key="market", prompt="Enter your exchange name >>> ", prompt_on_new=True, validator=validate_exchange, on_validated=lambda value: required_exchanges.append(value), ), "first_market_trading_pair": ConfigVar( key="first_market_trading_pair", prompt=first_trading_pair_prompt, prompt_on_new=True, validator=validate_trading_pair ), "second_market_trading_pair": ConfigVar( key="second_market_trading_pair", prompt=second_trading_pair_prompt, prompt_on_new=True, validator=validate_trading_pair ), "third_market_trading_pair": ConfigVar( key="third_market_trading_pair", prompt=third_trading_pair_prompt, prompt_on_new=True, validator=validate_trading_pair ), "target_asset": ConfigVar( key="target_asset", prompt="Target asset - must be included in the first and third pair", prompt_on_new=True, validator=validate_target_asset ), "min_profitability": ConfigVar( key="min_profitability", prompt="What is the minimum profitability for you to make a trade? (Enter 1 to indicate 1%) >>> ", prompt_on_new=True, validator=lambda v: validate_decimal(v, Decimal(-100), Decimal("100"), inclusive=True), type_str="decimal", ), "order_amount": ConfigVar( key="order_amount", prompt=order_amount_prompt, prompt_on_new=True, type_str="decimal", validator=validate_order_amount, ), "iteration_time": ConfigVar( key="iteration_time", prompt="Time to wait for a new iteration after order execution(in seconds)? >>> ", default=60.0, type_str="float", required_if=lambda: False, validator=lambda v: validate_decimal(v, min_value=0, inclusive=False) ) }
[ "hummingbot.client.config.config_validators.validate_market_trading_pair", "hummingbot.client.config.config_var.ConfigVar", "hummingbot.client.config.config_helpers.minimum_order_amount", "hummingbot.client.config.config_validators.validate_decimal", "hummingbot.client.settings.EXAMPLE_PAIRS.get", "hummin...
[((544, 575), 'hummingbot.client.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['maker_market'], {}), '(maker_market)\n', (561, 575), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((832, 863), 'hummingbot.client.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['maker_market'], {}), '(maker_market)\n', (849, 863), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1120, 1151), 'hummingbot.client.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['maker_market'], {}), '(maker_market)\n', (1137, 1151), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((2013, 2056), 'hummingbot.client.config.config_validators.validate_market_trading_pair', 'validate_market_trading_pair', (['market', 'value'], {}), '(market, value)\n', (2041, 2056), False, 'from hummingbot.client.config.config_validators import validate_exchange, validate_market_trading_pair, validate_decimal, validate_bool\n'), ((2322, 2372), 'hummingbot.client.config.config_helpers.minimum_order_amount', 'minimum_order_amount', (['maker_exchange', 'trading_pair'], {}), '(maker_exchange, trading_pair)\n', (2342, 2372), False, 'from hummingbot.client.config.config_helpers import minimum_order_amount\n'), ((2991, 3059), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""strategy"""', 'prompt': '""""""', 'default': '"""triangular_arbitrage"""'}), "(key='strategy', prompt='', default='triangular_arbitrage')\n", (3000, 3059), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3364, 3497), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""first_market_trading_pair"""', 'prompt': 'first_trading_pair_prompt', 'prompt_on_new': '(True)', 'validator': 'validate_trading_pair'}), "(key='first_market_trading_pair', prompt=first_trading_pair_prompt,\n prompt_on_new=True, validator=validate_trading_pair)\n", (3373, 3497), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3567, 3708), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""second_market_trading_pair"""', 'prompt': 'second_trading_pair_prompt', 'prompt_on_new': '(True)', 'validator': 'validate_trading_pair'}), "(key='second_market_trading_pair', prompt=\n second_trading_pair_prompt, prompt_on_new=True, validator=\n validate_trading_pair)\n", (3576, 3708), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3771, 3904), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""third_market_trading_pair"""', 'prompt': 'third_trading_pair_prompt', 'prompt_on_new': '(True)', 'validator': 'validate_trading_pair'}), "(key='third_market_trading_pair', prompt=third_trading_pair_prompt,\n prompt_on_new=True, validator=validate_trading_pair)\n", (3780, 3904), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3960, 4121), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""target_asset"""', 'prompt': '"""Target asset - must be included in the first and third pair"""', 'prompt_on_new': '(True)', 'validator': 'validate_target_asset'}), "(key='target_asset', prompt=\n 'Target asset - must be included in the first and third pair',\n prompt_on_new=True, validator=validate_target_asset)\n", (3969, 4121), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((4507, 4642), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""order_amount"""', 'prompt': 'order_amount_prompt', 'prompt_on_new': '(True)', 'type_str': '"""decimal"""', 'validator': 'validate_order_amount'}), "(key='order_amount', prompt=order_amount_prompt, prompt_on_new=\n True, type_str='decimal', validator=validate_order_amount)\n", (4516, 4642), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((2720, 2770), 'hummingbot.client.config.config_helpers.minimum_order_amount', 'minimum_order_amount', (['maker_exchange', 'trading_pair'], {}), '(maker_exchange, trading_pair)\n', (2740, 2770), False, 'from hummingbot.client.config.config_helpers import minimum_order_amount\n'), ((2782, 2796), 'decimal.Decimal', 'Decimal', (['value'], {}), '(value)\n', (2789, 2796), False, 'from decimal import Decimal\n'), ((3286, 3318), 'hummingbot.client.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (3311, 3318), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((4951, 5000), 'hummingbot.client.config.config_validators.validate_decimal', 'validate_decimal', (['v'], {'min_value': '(0)', 'inclusive': '(False)'}), '(v, min_value=0, inclusive=False)\n', (4967, 5000), False, 'from hummingbot.client.config.config_validators import validate_exchange, validate_market_trading_pair, validate_decimal, validate_bool\n'), ((4404, 4417), 'decimal.Decimal', 'Decimal', (['(-100)'], {}), '(-100)\n', (4411, 4417), False, 'from decimal import Decimal\n'), ((4419, 4433), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (4426, 4433), False, 'from decimal import Decimal\n')]
#!/usr/bin/env python from os.path import join, realpath import sys; sys.path.insert(0, realpath(join(__file__, "../../"))) from decimal import Decimal import logging; logging.basicConfig(level=logging.ERROR) import pandas as pd from typing import List import unittest from hummingbot.cli.utils.exchange_rate_conversion import ExchangeRateConversion from hummingsim.backtest.backtest_market import BacktestMarket from hummingsim.backtest.market import ( AssetType, Market, MarketConfig, QuantizationParams ) from hummingsim.backtest.mock_order_book_loader import MockOrderBookLoader from wings.clock import ( Clock, ClockMode ) from wings.event_logger import EventLogger from wings.events import ( MarketEvent, OrderBookTradeEvent, TradeType, OrderType, OrderFilledEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent ) from wings.order_book import OrderBook from wings.order_book_row import OrderBookRow from wings.limit_order import LimitOrder from hummingbot.strategy.arbitrage.arbitrage import ArbitrageStrategy from hummingbot.strategy.arbitrage.arbitrage_market_pair import ArbitrageMarketPair class ArbitrageUnitTest(unittest.TestCase): start: pd.Timestamp = pd.Timestamp("2019-01-01", tz="UTC") end: pd.Timestamp = pd.Timestamp("2019-01-01 01:00:00", tz="UTC") start_timestamp: float = start.timestamp() end_timestamp: float = end.timestamp() market_1_symbols: List[str] = ["COINALPHA-WETH", "COINALPHA", "WETH"] market_2_symbols: List[str] = ["coinalpha/eth", "COINALPHA", "ETH"] @classmethod def setUpClass(cls): ExchangeRateConversion.set_global_exchange_rate_config([ ("WETH", 1.0, "None"), ("QETH", 0.95, "None"), ]) def setUp(self): self.clock: Clock = Clock(ClockMode.BACKTEST, 1.0, self.start_timestamp, self.end_timestamp) self.market_1: BacktestMarket = BacktestMarket() self.market_2: BacktestMarket = BacktestMarket() self.market_1_data: MockOrderBookLoader = MockOrderBookLoader(*self.market_1_symbols) self.market_2_data: MockOrderBookLoader = MockOrderBookLoader(*self.market_2_symbols) self.market_1_data.set_balanced_order_book(1.0, 0.5, 1.5, 0.01, 10) self.market_2_data.set_balanced_order_book(1.3, 0.5, 1.5, 0.001, 4) self.market_1.add_data(self.market_1_data) self.market_2.add_data(self.market_2_data) self.market_1.set_balance("COINALPHA", 5) self.market_1.set_balance("ETH", 5) self.market_2.set_balance("COINALPHA", 5) self.market_2.set_balance("WETH", 5) self.market_1.set_quantization_param( QuantizationParams( self.market_1_symbols[0], 5, 5, 5, 5 ) ) self.market_2.set_quantization_param( QuantizationParams( self.market_2_symbols[0], 5, 5, 5, 5 ) ) self.market_pair: ArbitrageMarketPair = ArbitrageMarketPair( *( [self.market_1] + self.market_1_symbols + [self.market_2] + self.market_2_symbols ) ) logging_options: int = ArbitrageStrategy.OPTION_LOG_ALL self.strategy: ArbitrageStrategy = ArbitrageStrategy( [self.market_pair], min_profitability=0.01 ) self.logging_options = logging_options self.clock.add_iterator(self.market_1) self.clock.add_iterator(self.market_2) self.clock.add_iterator(self.strategy) self.market_1_order_fill_logger: EventLogger = EventLogger() self.market_2_order_fill_logger: EventLogger = EventLogger() self.market_1.add_listener(MarketEvent.OrderFilled, self.market_1_order_fill_logger) self.market_2.add_listener(MarketEvent.OrderFilled, self.market_2_order_fill_logger) def test_find_profitable_arbitrage_orders(self): pass def test_find_best_profitable_amount(self): pass def test_process_market_pair(self): pass def test_process_market_pair_inner(self): pass def test_ready_for_new_orders(self): pass def main(): unittest.main() if __name__ == "__main__": main()
[ "hummingbot.cli.utils.exchange_rate_conversion.ExchangeRateConversion.set_global_exchange_rate_config", "hummingbot.strategy.arbitrage.arbitrage_market_pair.ArbitrageMarketPair", "hummingbot.strategy.arbitrage.arbitrage.ArbitrageStrategy" ]
[((170, 210), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.ERROR'}), '(level=logging.ERROR)\n', (189, 210), False, 'import logging\n'), ((1229, 1265), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01"""'], {'tz': '"""UTC"""'}), "('2019-01-01', tz='UTC')\n", (1241, 1265), True, 'import pandas as pd\n'), ((1290, 1335), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01 01:00:00"""'], {'tz': '"""UTC"""'}), "('2019-01-01 01:00:00', tz='UTC')\n", (1302, 1335), True, 'import pandas as pd\n'), ((4183, 4198), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4196, 4198), False, 'import unittest\n'), ((98, 122), 'os.path.join', 'join', (['__file__', '"""../../"""'], {}), "(__file__, '../../')\n", (102, 122), False, 'from os.path import join, realpath\n'), ((1623, 1730), 'hummingbot.cli.utils.exchange_rate_conversion.ExchangeRateConversion.set_global_exchange_rate_config', 'ExchangeRateConversion.set_global_exchange_rate_config', (["[('WETH', 1.0, 'None'), ('QETH', 0.95, 'None')]"], {}), "([('WETH', 1.0,\n 'None'), ('QETH', 0.95, 'None')])\n", (1677, 1730), False, 'from hummingbot.cli.utils.exchange_rate_conversion import ExchangeRateConversion\n'), ((1812, 1884), 'wings.clock.Clock', 'Clock', (['ClockMode.BACKTEST', '(1.0)', 'self.start_timestamp', 'self.end_timestamp'], {}), '(ClockMode.BACKTEST, 1.0, self.start_timestamp, self.end_timestamp)\n', (1817, 1884), False, 'from wings.clock import Clock, ClockMode\n'), ((1925, 1941), 'hummingsim.backtest.backtest_market.BacktestMarket', 'BacktestMarket', ([], {}), '()\n', (1939, 1941), False, 'from hummingsim.backtest.backtest_market import BacktestMarket\n'), ((1982, 1998), 'hummingsim.backtest.backtest_market.BacktestMarket', 'BacktestMarket', ([], {}), '()\n', (1996, 1998), False, 'from hummingsim.backtest.backtest_market import BacktestMarket\n'), ((2049, 2092), 'hummingsim.backtest.mock_order_book_loader.MockOrderBookLoader', 'MockOrderBookLoader', (['*self.market_1_symbols'], {}), '(*self.market_1_symbols)\n', (2068, 2092), False, 'from hummingsim.backtest.mock_order_book_loader import MockOrderBookLoader\n'), ((2143, 2186), 'hummingsim.backtest.mock_order_book_loader.MockOrderBookLoader', 'MockOrderBookLoader', (['*self.market_2_symbols'], {}), '(*self.market_2_symbols)\n', (2162, 2186), False, 'from hummingsim.backtest.mock_order_book_loader import MockOrderBookLoader\n'), ((2992, 3102), 'hummingbot.strategy.arbitrage.arbitrage_market_pair.ArbitrageMarketPair', 'ArbitrageMarketPair', (['*([self.market_1] + self.market_1_symbols + [self.market_2] + self.\n market_2_symbols)'], {}), '(*([self.market_1] + self.market_1_symbols + [self.\n market_2] + self.market_2_symbols))\n', (3011, 3102), False, 'from hummingbot.strategy.arbitrage.arbitrage_market_pair import ArbitrageMarketPair\n'), ((3258, 3319), 'hummingbot.strategy.arbitrage.arbitrage.ArbitrageStrategy', 'ArbitrageStrategy', (['[self.market_pair]'], {'min_profitability': '(0.01)'}), '([self.market_pair], min_profitability=0.01)\n', (3275, 3319), False, 'from hummingbot.strategy.arbitrage.arbitrage import ArbitrageStrategy\n'), ((3598, 3611), 'wings.event_logger.EventLogger', 'EventLogger', ([], {}), '()\n', (3609, 3611), False, 'from wings.event_logger import EventLogger\n'), ((3667, 3680), 'wings.event_logger.EventLogger', 'EventLogger', ([], {}), '()\n', (3678, 3680), False, 'from wings.event_logger import EventLogger\n'), ((2692, 2748), 'hummingsim.backtest.market.QuantizationParams', 'QuantizationParams', (['self.market_1_symbols[0]', '(5)', '(5)', '(5)', '(5)'], {}), '(self.market_1_symbols[0], 5, 5, 5, 5)\n', (2710, 2748), False, 'from hummingsim.backtest.market import AssetType, Market, MarketConfig, QuantizationParams\n'), ((2847, 2903), 'hummingsim.backtest.market.QuantizationParams', 'QuantizationParams', (['self.market_2_symbols[0]', '(5)', '(5)', '(5)', '(5)'], {}), '(self.market_2_symbols[0], 5, 5, 5, 5)\n', (2865, 2903), False, 'from hummingsim.backtest.market import AssetType, Market, MarketConfig, QuantizationParams\n')]
import asyncio import contextlib import logging import os import time import unittest from decimal import Decimal from os.path import join, realpath from typing import ( List, ) from unittest import mock import conf from hummingbot.client.config.global_config_map import global_config_map from hummingbot.connector.connector.uniswap_v3.uniswap_v3_connector import UniswapV3Connector from hummingbot.connector.markets_recorder import MarketsRecorder from hummingbot.core.clock import ( Clock, ClockMode ) from hummingbot.core.event.event_logger import EventLogger from hummingbot.core.event.events import ( BuyOrderCreatedEvent, MarketEvent, OrderType, RangePositionCreatedEvent, RangePositionRemovedEvent, ) from hummingbot.core.mock_api.mock_web_server import MockWebServer from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from hummingbot.logger.struct_logger import METRICS_LOG_LEVEL from hummingbot.model.sql_connection_manager import ( SQLConnectionManager, SQLConnectionType ) from test.connector.connector.uniswap_v3.fixture import Fixture logging.basicConfig(level=METRICS_LOG_LEVEL) global_config_map['gateway_api_host'].value = "localhost" global_config_map['gateway_api_port'].value = "5000" logging.basicConfig(level=METRICS_LOG_LEVEL) API_MOCK_ENABLED = True # conf.mock_api_enabled is not None and conf.mock_api_enabled.lower() in ['true', 'yes', '1'] WALLET_KEY = "XXX" if API_MOCK_ENABLED else conf.wallet_private_key base_api_url = "localhost" rpc_url = global_config_map["ethereum_rpc_url"].value class UniswapV3ConnectorUnitTest(unittest.TestCase): events: List[MarketEvent] = [e for e in MarketEvent] connector: UniswapV3Connector event_logger: EventLogger stack: contextlib.ExitStack @classmethod def setUpClass(cls): global MAINNET_RPC_URL cls.ev_loop = asyncio.get_event_loop() if API_MOCK_ENABLED: cls.web_app = MockWebServer.get_instance() cls.web_app.add_host_to_mock(base_api_url) cls.web_app.start() cls.ev_loop.run_until_complete(cls.web_app.wait_til_started()) cls._patcher = mock.patch("aiohttp.client.URL") cls._url_mock = cls._patcher.start() cls._url_mock.side_effect = cls.web_app.reroute_local cls.web_app.update_response("get", base_api_url, "/api", {"status": "ok"}) cls.web_app.update_response("get", base_api_url, "/eth/uniswap/start", {"success": True}) cls.web_app.update_response("post", base_api_url, "/eth/balances", Fixture.BALANCES) cls.web_app.update_response("post", base_api_url, "/eth/allowances", Fixture.APPROVALS) cls._t_nonce_patcher = unittest.mock.patch( "hummingbot.connector.connector.uniswap.uniswap_connector.get_tracking_nonce") cls._t_nonce_mock = cls._t_nonce_patcher.start() cls.current_nonce = 1000000000000000 cls.clock: Clock = Clock(ClockMode.REALTIME) cls.connector = UniswapV3Connector(["ZRX-ETH"], WALLET_KEY, rpc_url, True) print("Initializing Uniswap v3 connector... this will take a few seconds.") # cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() cls.clock.add_iterator(cls.connector) cls.stack: contextlib.ExitStack = contextlib.ExitStack() cls._clock = cls.stack.enter_context(cls.clock) cls.ev_loop.run_until_complete(cls.wait_til_ready()) print("Ready.") @classmethod def tearDownClass(cls) -> None: cls.stack.close() if API_MOCK_ENABLED: cls.web_app.stop() cls._patcher.stop() cls._t_nonce_patcher.stop() @classmethod async def wait_til_ready(cls): while True: now = time.time() next_iteration = now // 1.0 + 1 if cls.connector.ready: break else: await cls._clock.run_til(next_iteration) await asyncio.sleep(1.0) def setUp(self): self.db_path: str = realpath(join(__file__, "../connector_test.sqlite")) try: os.unlink(self.db_path) except Exception: pass self.event_logger = EventLogger() for event_tag in self.events: self.connector.add_listener(event_tag, self.event_logger) def tearDown(self): for event_tag in self.events: self.connector.remove_listener(event_tag, self.event_logger) self.event_logger = None @classmethod async def run_parallel_async(cls, *tasks): future: asyncio.Future = safe_ensure_future(safe_gather(*tasks)) while not future.done(): now = time.time() next_iteration = now // 1.0 + 1 await cls._clock.run_til(next_iteration) await asyncio.sleep(1.0) return future.result() def run_parallel(self, task): return self.ev_loop.run_until_complete(self.run_parallel_async(task)) def test_add_position(self): sql = SQLConnectionManager(SQLConnectionType.TRADE_FILLS, db_path=self.db_path) config_path = "test_config" strategy_name = "test_strategy" recorder = MarketsRecorder(sql, [self.connector], config_path, strategy_name) recorder.start() try: if API_MOCK_ENABLED: self.web_app.update_response("post", base_api_url, "/eth/uniswap/v3/add-position", Fixture.ADD_POSITION) self.web_app.update_response("post", base_api_url, "/eth/poll", Fixture.ETH_POLL_LP_ORDER) self.web_app.update_response("post", base_api_url, "/eth/uniswap/v3/result", Fixture.ETH_RESULT_LP_ORDER) hb_id = self.connector.add_position("HBOT-ETH", Decimal("0.1"), Decimal("100"), Decimal("200"), Decimal("50"), Decimal("60")) pos_cre_evt = self.run_parallel(self.event_logger.wait_for(RangePositionCreatedEvent)) self.run_parallel(asyncio.sleep(0.1)) print(pos_cre_evt[0]) self.assertEqual(pos_cre_evt[0].hb_id, hb_id) self.assertEqual(Fixture.ADD_POSITION["txHash"], pos_cre_evt[0].tx_hash) # Testing tracking market state and restoration tracking_state = self.connector.tracking_states self.assertTrue("orders" in tracking_state) self.assertTrue("positions" in tracking_state) self.connector._in_flight_positions.clear() self.connector.restore_tracking_states(tracking_state) self.assertGreater(len(self.connector._in_flight_positions), 0) self.assertEqual(list(self.connector._in_flight_positions.values())[0].hb_id, hb_id) finally: pass recorder.stop() os.unlink(self.db_path) def test_remove_position(self): if API_MOCK_ENABLED: self.web_app.update_response("post", base_api_url, "/eth/uniswap/v3/add-position", Fixture.ADD_POSITION) self.web_app.update_response("post", base_api_url, "/eth/poll", Fixture.ETH_POLL_LP_ORDER) self.web_app.update_response("post", base_api_url, "/eth/uniswap/v3/result", Fixture.ETH_RESULT_LP_ORDER) hb_id = self.connector.add_position("HBOT-ETH", Decimal("0.1"), Decimal("100"), Decimal("200"), Decimal("50"), Decimal("60")) pos_cre_evt = self.run_parallel(self.event_logger.wait_for(RangePositionCreatedEvent)) self.assertEqual(pos_cre_evt[0].hb_id, hb_id) self.assertEqual(Fixture.ADD_POSITION["txHash"], pos_cre_evt[0].tx_hash) if API_MOCK_ENABLED: self.web_app.update_response("post", base_api_url, "/eth/uniswap/v3/remove-position", Fixture.REMOVE_POSITION) self.web_app.update_response("post", base_api_url, "/eth/uniswap/v3/result", Fixture.ETH_RESULT_LP_ORDER_REMOVE) self.connector.remove_position(hb_id, "123") evt = self.run_parallel(self.event_logger.wait_for(RangePositionRemovedEvent)) print(evt) def test_buy(self): if API_MOCK_ENABLED: self.web_app.update_response("post", base_api_url, "/eth/uniswap/trade", Fixture.BUY_ORDER) uniswap = self.connector amount = Decimal("0.1") price = Decimal("20") order_id = uniswap.buy("HBOT-USDT", amount, OrderType.LIMIT, price) event = self.ev_loop.run_until_complete(self.event_logger.wait_for(BuyOrderCreatedEvent)) self.assertTrue(event.order_id is not None) self.assertEqual(order_id, event.order_id) # self.assertEqual(event.base_asset_amount, amount) print(event.order_id) def test_get_position(self): if API_MOCK_ENABLED: self.web_app.update_response("post", base_api_url, "/uniswap/v3/position", Fixture.POSITION) pos = self.ev_loop.run_until_complete(self.connector.get_position("dummy_token_id")) print(pos) def test_collect_fees(self): if API_MOCK_ENABLED: self.web_app.update_response("post", base_api_url, "/uniswap/v3/collect-fees", Fixture.COLLECT_FEES) pos = self.ev_loop.run_until_complete(self.connector.collect_fees("dummy_token_id")) print(pos)
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.connector.markets_recorder.MarketsRecorder", "hummingbot.core.mock_api.mock_web_server.MockWebServer.get_instance", "hummingbot.core.event.event_logger.EventLogger", "hummingbot.core.clock.Clock", "hummingbot.model.sql_connection_manager.SQLConn...
[((1131, 1175), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'METRICS_LOG_LEVEL'}), '(level=METRICS_LOG_LEVEL)\n', (1150, 1175), False, 'import logging\n'), ((1287, 1331), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'METRICS_LOG_LEVEL'}), '(level=METRICS_LOG_LEVEL)\n', (1306, 1331), False, 'import logging\n'), ((1905, 1929), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1927, 1929), False, 'import asyncio\n'), ((3023, 3048), 'hummingbot.core.clock.Clock', 'Clock', (['ClockMode.REALTIME'], {}), '(ClockMode.REALTIME)\n', (3028, 3048), False, 'from hummingbot.core.clock import Clock, ClockMode\n'), ((3073, 3131), 'hummingbot.connector.connector.uniswap_v3.uniswap_v3_connector.UniswapV3Connector', 'UniswapV3Connector', (["['ZRX-ETH']", 'WALLET_KEY', 'rpc_url', '(True)'], {}), "(['ZRX-ETH'], WALLET_KEY, rpc_url, True)\n", (3091, 3131), False, 'from hummingbot.connector.connector.uniswap_v3.uniswap_v3_connector import UniswapV3Connector\n'), ((3376, 3398), 'contextlib.ExitStack', 'contextlib.ExitStack', ([], {}), '()\n', (3396, 3398), False, 'import contextlib\n'), ((4292, 4305), 'hummingbot.core.event.event_logger.EventLogger', 'EventLogger', ([], {}), '()\n', (4303, 4305), False, 'from hummingbot.core.event.event_logger import EventLogger\n'), ((5110, 5183), 'hummingbot.model.sql_connection_manager.SQLConnectionManager', 'SQLConnectionManager', (['SQLConnectionType.TRADE_FILLS'], {'db_path': 'self.db_path'}), '(SQLConnectionType.TRADE_FILLS, db_path=self.db_path)\n', (5130, 5183), False, 'from hummingbot.model.sql_connection_manager import SQLConnectionManager, SQLConnectionType\n'), ((5279, 5345), 'hummingbot.connector.markets_recorder.MarketsRecorder', 'MarketsRecorder', (['sql', '[self.connector]', 'config_path', 'strategy_name'], {}), '(sql, [self.connector], config_path, strategy_name)\n', (5294, 5345), False, 'from hummingbot.connector.markets_recorder import MarketsRecorder\n'), ((8450, 8464), 'decimal.Decimal', 'Decimal', (['"""0.1"""'], {}), "('0.1')\n", (8457, 8464), False, 'from decimal import Decimal\n'), ((8481, 8494), 'decimal.Decimal', 'Decimal', (['"""20"""'], {}), "('20')\n", (8488, 8494), False, 'from decimal import Decimal\n'), ((1986, 2014), 'hummingbot.core.mock_api.mock_web_server.MockWebServer.get_instance', 'MockWebServer.get_instance', ([], {}), '()\n', (2012, 2014), False, 'from hummingbot.core.mock_api.mock_web_server import MockWebServer\n'), ((2204, 2236), 'unittest.mock.patch', 'mock.patch', (['"""aiohttp.client.URL"""'], {}), "('aiohttp.client.URL')\n", (2214, 2236), False, 'from unittest import mock\n'), ((2774, 2882), 'unittest.mock.patch', 'unittest.mock.patch', (['"""hummingbot.connector.connector.uniswap.uniswap_connector.get_tracking_nonce"""'], {}), "(\n 'hummingbot.connector.connector.uniswap.uniswap_connector.get_tracking_nonce'\n )\n", (2793, 2882), False, 'import unittest\n'), ((3843, 3854), 'time.time', 'time.time', ([], {}), '()\n', (3852, 3854), False, 'import time\n'), ((4128, 4170), 'os.path.join', 'join', (['__file__', '"""../connector_test.sqlite"""'], {}), "(__file__, '../connector_test.sqlite')\n", (4132, 4170), False, 'from os.path import join, realpath\n'), ((4197, 4220), 'os.unlink', 'os.unlink', (['self.db_path'], {}), '(self.db_path)\n', (4206, 4220), False, 'import os\n'), ((4700, 4719), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*tasks'], {}), '(*tasks)\n', (4711, 4719), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((4772, 4783), 'time.time', 'time.time', ([], {}), '()\n', (4781, 4783), False, 'import time\n'), ((6929, 6952), 'os.unlink', 'os.unlink', (['self.db_path'], {}), '(self.db_path)\n', (6938, 6952), False, 'import os\n'), ((7413, 7427), 'decimal.Decimal', 'Decimal', (['"""0.1"""'], {}), "('0.1')\n", (7420, 7427), False, 'from decimal import Decimal\n'), ((7429, 7443), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (7436, 7443), False, 'from decimal import Decimal\n'), ((7445, 7459), 'decimal.Decimal', 'Decimal', (['"""200"""'], {}), "('200')\n", (7452, 7459), False, 'from decimal import Decimal\n'), ((7505, 7518), 'decimal.Decimal', 'Decimal', (['"""50"""'], {}), "('50')\n", (7512, 7518), False, 'from decimal import Decimal\n'), ((7520, 7533), 'decimal.Decimal', 'Decimal', (['"""60"""'], {}), "('60')\n", (7527, 7533), False, 'from decimal import Decimal\n'), ((4050, 4068), 'asyncio.sleep', 'asyncio.sleep', (['(1.0)'], {}), '(1.0)\n', (4063, 4068), False, 'import asyncio\n'), ((4899, 4917), 'asyncio.sleep', 'asyncio.sleep', (['(1.0)'], {}), '(1.0)\n', (4912, 4917), False, 'import asyncio\n'), ((5872, 5886), 'decimal.Decimal', 'Decimal', (['"""0.1"""'], {}), "('0.1')\n", (5879, 5886), False, 'from decimal import Decimal\n'), ((5888, 5902), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (5895, 5902), False, 'from decimal import Decimal\n'), ((5904, 5918), 'decimal.Decimal', 'Decimal', (['"""200"""'], {}), "('200')\n", (5911, 5918), False, 'from decimal import Decimal\n'), ((5968, 5981), 'decimal.Decimal', 'Decimal', (['"""50"""'], {}), "('50')\n", (5975, 5981), False, 'from decimal import Decimal\n'), ((5983, 5996), 'decimal.Decimal', 'Decimal', (['"""60"""'], {}), "('60')\n", (5990, 5996), False, 'from decimal import Decimal\n'), ((6127, 6145), 'asyncio.sleep', 'asyncio.sleep', (['(0.1)'], {}), '(0.1)\n', (6140, 6145), False, 'import asyncio\n')]
from decimal import Decimal from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from hummingbot.strategy.hedged_lm.hedged_lm import HedgedLMStrategy from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map from hummingbot.core.event.events import ( PositionMode ) def start(self): exchange = c_map.get("exchange").value.lower() el_markets = list(c_map.get("markets").value.split(",")) token = c_map.get("token").value.upper() el_markets = [m.upper() for m in el_markets] quote_markets = [m for m in el_markets if m.split("-")[1] == token] base_markets = [m for m in el_markets if m.split("-")[0] == token] markets = quote_markets if quote_markets else base_markets order_amount = c_map.get("order_amount").value spread = c_map.get("spread").value / Decimal("100") inventory_skew_enabled = c_map.get("inventory_skew_enabled").value target_base_pct = c_map.get("target_base_pct").value / Decimal("100") order_refresh_time = c_map.get("order_refresh_time").value order_refresh_tolerance_pct = c_map.get("order_refresh_tolerance_pct").value / Decimal("100") inventory_range_multiplier = c_map.get("inventory_range_multiplier").value volatility_interval = c_map.get("volatility_interval").value avg_volatility_period = c_map.get("avg_volatility_period").value volatility_to_spread_multiplier = c_map.get("volatility_to_spread_multiplier").value max_spread = c_map.get("max_spread").value / Decimal("100") max_order_age = c_map.get("max_order_age").value derivative_connector = c_map.get("derivative_connector").value.lower() #derivative_market = c_map.get("derivative_market").value derivative_leverage = c_map.get("derivative_leverage").value self._initialize_markets([(exchange, markets), (derivative_connector, markets)]) exchange = self.markets[exchange] deriv_exchange = self.markets[derivative_connector] market_infos = {} derivative_market_infos = {} for trading_pair in markets: base, quote = trading_pair.split("-") market_infos[trading_pair] = MarketTradingPairTuple(exchange, trading_pair, base, quote) derivative_market_infos[trading_pair] = MarketTradingPairTuple(self.markets[derivative_connector], trading_pair, base, quote) deriv_market = derivative_market_infos[trading_pair].market deriv_market.set_leverage(trading_pair, derivative_leverage) deriv_market.set_position_mode(PositionMode.ONEWAY) self.strategy = HedgedLMStrategy( exchange=exchange, deriv_exchange=deriv_exchange, market_infos=market_infos, derivative_market_infos=derivative_market_infos, token=token, order_amount=order_amount, spread=spread, inventory_skew_enabled=inventory_skew_enabled, target_base_pct=target_base_pct, order_refresh_time=order_refresh_time, order_refresh_tolerance_pct=order_refresh_tolerance_pct, inventory_range_multiplier=inventory_range_multiplier, volatility_interval=volatility_interval, avg_volatility_period=avg_volatility_period, volatility_to_spread_multiplier=volatility_to_spread_multiplier, max_spread=max_spread, max_order_age=max_order_age, hb_app_notification=True )
[ "hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple", "hummingbot.strategy.hedged_lm.hedged_lm.HedgedLMStrategy", "hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get" ]
[((2564, 3267), 'hummingbot.strategy.hedged_lm.hedged_lm.HedgedLMStrategy', 'HedgedLMStrategy', ([], {'exchange': 'exchange', 'deriv_exchange': 'deriv_exchange', 'market_infos': 'market_infos', 'derivative_market_infos': 'derivative_market_infos', 'token': 'token', 'order_amount': 'order_amount', 'spread': 'spread', 'inventory_skew_enabled': 'inventory_skew_enabled', 'target_base_pct': 'target_base_pct', 'order_refresh_time': 'order_refresh_time', 'order_refresh_tolerance_pct': 'order_refresh_tolerance_pct', 'inventory_range_multiplier': 'inventory_range_multiplier', 'volatility_interval': 'volatility_interval', 'avg_volatility_period': 'avg_volatility_period', 'volatility_to_spread_multiplier': 'volatility_to_spread_multiplier', 'max_spread': 'max_spread', 'max_order_age': 'max_order_age', 'hb_app_notification': '(True)'}), '(exchange=exchange, deriv_exchange=deriv_exchange,\n market_infos=market_infos, derivative_market_infos=\n derivative_market_infos, token=token, order_amount=order_amount, spread\n =spread, inventory_skew_enabled=inventory_skew_enabled, target_base_pct\n =target_base_pct, order_refresh_time=order_refresh_time,\n order_refresh_tolerance_pct=order_refresh_tolerance_pct,\n inventory_range_multiplier=inventory_range_multiplier,\n volatility_interval=volatility_interval, avg_volatility_period=\n avg_volatility_period, volatility_to_spread_multiplier=\n volatility_to_spread_multiplier, max_spread=max_spread, max_order_age=\n max_order_age, hb_app_notification=True)\n', (2580, 3267), False, 'from hummingbot.strategy.hedged_lm.hedged_lm import HedgedLMStrategy\n'), ((782, 807), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""order_amount"""'], {}), "('order_amount')\n", (791, 807), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((855, 869), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (862, 869), False, 'from decimal import Decimal\n'), ((899, 934), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""inventory_skew_enabled"""'], {}), "('inventory_skew_enabled')\n", (908, 934), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1000, 1014), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (1007, 1014), False, 'from decimal import Decimal\n'), ((1040, 1071), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""order_refresh_time"""'], {}), "('order_refresh_time')\n", (1049, 1071), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1161, 1175), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (1168, 1175), False, 'from decimal import Decimal\n'), ((1209, 1248), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""inventory_range_multiplier"""'], {}), "('inventory_range_multiplier')\n", (1218, 1248), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1281, 1313), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""volatility_interval"""'], {}), "('volatility_interval')\n", (1290, 1313), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1348, 1382), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""avg_volatility_period"""'], {}), "('avg_volatility_period')\n", (1357, 1382), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1427, 1471), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""volatility_to_spread_multiplier"""'], {}), "('volatility_to_spread_multiplier')\n", (1436, 1471), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1527, 1541), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (1534, 1541), False, 'from decimal import Decimal\n'), ((1562, 1588), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""max_order_age"""'], {}), "('max_order_age')\n", (1571, 1588), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1758, 1790), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""derivative_leverage"""'], {}), "('derivative_leverage')\n", (1767, 1790), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((2153, 2212), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['exchange', 'trading_pair', 'base', 'quote'], {}), '(exchange, trading_pair, base, quote)\n', (2175, 2212), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((2261, 2350), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['self.markets[derivative_connector]', 'trading_pair', 'base', 'quote'], {}), '(self.markets[derivative_connector], trading_pair,\n base, quote)\n', (2283, 2350), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((827, 846), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""spread"""'], {}), "('spread')\n", (836, 846), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((963, 991), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""target_base_pct"""'], {}), "('target_base_pct')\n", (972, 991), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1112, 1152), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""order_refresh_tolerance_pct"""'], {}), "('order_refresh_tolerance_pct')\n", (1121, 1152), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1495, 1518), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""max_spread"""'], {}), "('max_spread')\n", (1504, 1518), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((366, 387), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""exchange"""'], {}), "('exchange')\n", (375, 387), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((475, 493), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""token"""'], {}), "('token')\n", (484, 493), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((1622, 1655), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""derivative_connector"""'], {}), "('derivative_connector')\n", (1631, 1655), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n'), ((424, 444), 'hummingbot.strategy.hedged_lm.hedged_lm_config_map.hedged_lm_config_map.get', 'c_map.get', (['"""markets"""'], {}), "('markets')\n", (433, 444), True, 'from hummingbot.strategy.hedged_lm.hedged_lm_config_map import hedged_lm_config_map as c_map\n')]
import asyncio import logging import math import time import unittest from decimal import Decimal from typing import ( Dict, List, ) from hummingbot.client.config.global_config_map import global_config_map from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler from hummingbot.core.api_throttler.data_types import LinkedLimitWeightPair, RateLimit, TaskLog from hummingbot.logger.struct_logger import METRICS_LOG_LEVEL TEST_PATH_URL = "/hummingbot" TEST_POOL_ID = "TEST" TEST_WEIGHTED_POOL_ID = "TEST_WEIGHTED" TEST_WEIGHTED_TASK_1_ID = "/weighted_task_1" TEST_WEIGHTED_TASK_2_ID = "/weighted_task_2" logging.basicConfig(level=METRICS_LOG_LEVEL) class AsyncThrottlerUnitTests(unittest.TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.ev_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() cls.rate_limits: List[RateLimit] = [ RateLimit(limit_id=TEST_POOL_ID, limit=1, time_interval=5.0), RateLimit(limit_id=TEST_PATH_URL, limit=1, time_interval=5.0, linked_limits=[LinkedLimitWeightPair(TEST_POOL_ID)]), RateLimit(limit_id=TEST_WEIGHTED_POOL_ID, limit=10, time_interval=5.0), RateLimit(limit_id=TEST_WEIGHTED_TASK_1_ID, limit=1000, time_interval=5.0, linked_limits=[LinkedLimitWeightPair(TEST_WEIGHTED_POOL_ID, 5)]), RateLimit(limit_id=TEST_WEIGHTED_TASK_2_ID, limit=1000, time_interval=5.0, linked_limits=[LinkedLimitWeightPair(TEST_WEIGHTED_POOL_ID, 1)]), ] def setUp(self) -> None: super().setUp() self.throttler = AsyncThrottler(rate_limits=self.rate_limits) self._req_counters: Dict[str, int] = {limit.limit_id: 0 for limit in self.rate_limits} def tearDown(self) -> None: global_config_map["rate_limits_share_pct"].value = None super().tearDown() async def execute_requests(self, no_request: int, limit_id: str, throttler: AsyncThrottler): for _ in range(no_request): async with throttler.execute_task(limit_id=limit_id): self._req_counters[limit_id] += 1 def test_init_without_rate_limits_share_pct(self): self.assertEqual(0.1, self.throttler._retry_interval) self.assertEqual(5, len(self.throttler._rate_limits)) self.assertEqual(1, self.throttler._id_to_limit_map[TEST_POOL_ID].limit) self.assertEqual(1, self.throttler._id_to_limit_map[TEST_PATH_URL].limit) def test_init_with_rate_limits_share_pct(self): rate_share_pct: Decimal = Decimal("55") global_config_map["rate_limits_share_pct"].value = rate_share_pct rate_limits = self.rate_limits.copy() rate_limits.append(RateLimit(limit_id="ANOTHER_TEST", limit=10, time_interval=5)) expected_limit = math.floor(Decimal("10") * rate_share_pct / Decimal("100")) throttler = AsyncThrottler(rate_limits=rate_limits) self.assertEqual(0.1, throttler._retry_interval) self.assertEqual(6, len(throttler._rate_limits)) self.assertEqual(Decimal("1"), throttler._id_to_limit_map[TEST_POOL_ID].limit) self.assertEqual(Decimal("1"), throttler._id_to_limit_map[TEST_PATH_URL].limit) self.assertEqual(expected_limit, throttler._id_to_limit_map["ANOTHER_TEST"].limit) def test_get_related_limits(self): self.assertEqual(5, len(self.throttler._rate_limits)) _, related_limits = self.throttler.get_related_limits(TEST_POOL_ID) self.assertEqual(1, len(related_limits)) _, related_limits = self.throttler.get_related_limits(TEST_PATH_URL) self.assertEqual(2, len(related_limits)) def test_flush_empty_task_logs(self): # Test: No entries in task_logs to flush lock = asyncio.Lock() rate_limit = self.rate_limits[0] self.assertEqual(0, len(self.throttler._task_logs)) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=lock, safety_margin_pct=self.throttler._safety_margin_pct) context.flush() self.assertEqual(0, len(self.throttler._task_logs)) def test_flush_only_elapsed_tasks_are_flushed(self): lock = asyncio.Lock() rate_limit = self.rate_limits[0] self.throttler._task_logs = [ TaskLog(timestamp=1.0, rate_limit=rate_limit, weight=rate_limit.weight), TaskLog(timestamp=time.time(), rate_limit=rate_limit, weight=rate_limit.weight) ] self.assertEqual(2, len(self.throttler._task_logs)) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=lock, safety_margin_pct=self.throttler._safety_margin_pct) context.flush() self.assertEqual(1, len(self.throttler._task_logs)) def test_within_capacity_singular_non_weighted_task_returns_false(self): rate_limit, _ = self.throttler.get_related_limits(limit_id=TEST_POOL_ID) self.throttler._task_logs.append(TaskLog(timestamp=time.time(), rate_limit=rate_limit, weight=rate_limit.weight)) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) self.assertFalse(context.within_capacity()) def test_within_capacity_singular_non_weighted_task_returns_true(self): rate_limit, _ = self.throttler.get_related_limits(limit_id=TEST_POOL_ID) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) self.assertTrue(context.within_capacity()) def test_within_capacity_pool_non_weighted_task_returns_false(self): rate_limit, related_limits = self.throttler.get_related_limits(limit_id=TEST_PATH_URL) for linked_limit, weight in related_limits: self.throttler._task_logs.append(TaskLog(timestamp=time.time(), rate_limit=linked_limit, weight=weight)) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=rate_limit, related_limits=related_limits, lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) self.assertFalse(context.within_capacity()) def test_within_capacity_pool_non_weighted_task_returns_true(self): rate_limit, related_limits = self.throttler.get_related_limits(limit_id=TEST_PATH_URL) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=rate_limit, related_limits=related_limits, lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) self.assertTrue(context.within_capacity()) def test_within_capacity_pool_weighted_tasks(self): task_1, task_1_related_limits = self.throttler.get_related_limits(limit_id=TEST_WEIGHTED_TASK_1_ID) # Simulate Weighted Task 1 and Task 2 already in task logs, resulting in a used capacity of 6/10 for linked_limit, weight in task_1_related_limits: self.throttler._task_logs.append(TaskLog(timestamp=time.time(), rate_limit=linked_limit, weight=weight)) task_2, task_2_related_limits = self.throttler.get_related_limits(limit_id=TEST_WEIGHTED_TASK_2_ID) for linked_limit, weight in task_2_related_limits: self.throttler._task_logs.append(TaskLog(timestamp=time.time(), rate_limit=linked_limit, weight=weight)) # Another Task 1(weight=5) will exceed the capacity(11/10) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=task_1, related_limits=task_1_related_limits, lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) self.assertFalse(context.within_capacity()) # However Task 2(weight=1) will not exceed the capacity(7/10) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=task_2, related_limits=task_2_related_limits, lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) self.assertTrue(context.within_capacity()) def test_within_capacity_returns_true(self): lock = asyncio.Lock() rate_limit = self.rate_limits[0] context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=lock, safety_margin_pct=self.throttler._safety_margin_pct) self.assertTrue(context.within_capacity()) def test_acquire_appends_to_task_logs(self): rate_limit = self.rate_limits[0] context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) self.ev_loop.run_until_complete(context.acquire()) self.assertEqual(2, len(self.throttler._task_logs)) def test_acquire_awaits_when_exceed_capacity(self): rate_limit = self.rate_limits[0] self.throttler._task_logs.append(TaskLog(timestamp=time.time(), rate_limit=rate_limit, weight=rate_limit.weight)) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limit=rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) with self.assertRaises(asyncio.exceptions.TimeoutError): self.ev_loop.run_until_complete( asyncio.wait_for(context.acquire(), 1.0) )
[ "hummingbot.core.api_throttler.async_throttler.AsyncRequestContext", "hummingbot.core.api_throttler.data_types.LinkedLimitWeightPair", "hummingbot.core.api_throttler.data_types.TaskLog", "hummingbot.core.api_throttler.data_types.RateLimit", "hummingbot.core.api_throttler.async_throttler.AsyncThrottler" ]
[((654, 698), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'METRICS_LOG_LEVEL'}), '(level=METRICS_LOG_LEVEL)\n', (673, 698), False, 'import logging\n'), ((879, 903), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (901, 903), False, 'import asyncio\n'), ((1763, 1807), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', ([], {'rate_limits': 'self.rate_limits'}), '(rate_limits=self.rate_limits)\n', (1777, 1807), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((2708, 2721), 'decimal.Decimal', 'Decimal', (['"""55"""'], {}), "('55')\n", (2715, 2721), False, 'from decimal import Decimal\n'), ((3039, 3078), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', ([], {'rate_limits': 'rate_limits'}), '(rate_limits=rate_limits)\n', (3053, 3078), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((3921, 3935), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (3933, 3935), False, 'import asyncio\n'), ((4056, 4258), 'hummingbot.core.api_throttler.async_throttler.AsyncRequestContext', 'AsyncRequestContext', ([], {'task_logs': 'self.throttler._task_logs', 'rate_limit': 'rate_limit', 'related_limits': '[(rate_limit, rate_limit.weight)]', 'lock': 'lock', 'safety_margin_pct': 'self.throttler._safety_margin_pct'}), '(task_logs=self.throttler._task_logs, rate_limit=\n rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=lock,\n safety_margin_pct=self.throttler._safety_margin_pct)\n', (4075, 4258), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((4559, 4573), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (4571, 4573), False, 'import asyncio\n'), ((4919, 5121), 'hummingbot.core.api_throttler.async_throttler.AsyncRequestContext', 'AsyncRequestContext', ([], {'task_logs': 'self.throttler._task_logs', 'rate_limit': 'rate_limit', 'related_limits': '[(rate_limit, rate_limit.weight)]', 'lock': 'lock', 'safety_margin_pct': 'self.throttler._safety_margin_pct'}), '(task_logs=self.throttler._task_logs, rate_limit=\n rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=lock,\n safety_margin_pct=self.throttler._safety_margin_pct)\n', (4938, 5121), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((9716, 9730), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (9728, 9730), False, 'import asyncio\n'), ((9790, 9992), 'hummingbot.core.api_throttler.async_throttler.AsyncRequestContext', 'AsyncRequestContext', ([], {'task_logs': 'self.throttler._task_logs', 'rate_limit': 'rate_limit', 'related_limits': '[(rate_limit, rate_limit.weight)]', 'lock': 'lock', 'safety_margin_pct': 'self.throttler._safety_margin_pct'}), '(task_logs=self.throttler._task_logs, rate_limit=\n rate_limit, related_limits=[(rate_limit, rate_limit.weight)], lock=lock,\n safety_margin_pct=self.throttler._safety_margin_pct)\n', (9809, 9992), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((962, 1022), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'TEST_POOL_ID', 'limit': '(1)', 'time_interval': '(5.0)'}), '(limit_id=TEST_POOL_ID, limit=1, time_interval=5.0)\n', (971, 1022), False, 'from hummingbot.core.api_throttler.data_types import LinkedLimitWeightPair, RateLimit, TaskLog\n'), ((1164, 1234), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'TEST_WEIGHTED_POOL_ID', 'limit': '(10)', 'time_interval': '(5.0)'}), '(limit_id=TEST_WEIGHTED_POOL_ID, limit=10, time_interval=5.0)\n', (1173, 1234), False, 'from hummingbot.core.api_throttler.data_types import LinkedLimitWeightPair, RateLimit, TaskLog\n'), ((2870, 2931), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': '"""ANOTHER_TEST"""', 'limit': '(10)', 'time_interval': '(5)'}), "(limit_id='ANOTHER_TEST', limit=10, time_interval=5)\n", (2879, 2931), False, 'from hummingbot.core.api_throttler.data_types import LinkedLimitWeightPair, RateLimit, TaskLog\n'), ((3218, 3230), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (3225, 3230), False, 'from decimal import Decimal\n'), ((3305, 3317), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (3312, 3317), False, 'from decimal import Decimal\n'), ((4665, 4736), 'hummingbot.core.api_throttler.data_types.TaskLog', 'TaskLog', ([], {'timestamp': '(1.0)', 'rate_limit': 'rate_limit', 'weight': 'rate_limit.weight'}), '(timestamp=1.0, rate_limit=rate_limit, weight=rate_limit.weight)\n', (4672, 4736), False, 'from hummingbot.core.api_throttler.data_types import LinkedLimitWeightPair, RateLimit, TaskLog\n'), ((3002, 3016), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (3009, 3016), False, 'from decimal import Decimal\n'), ((5898, 5912), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (5910, 5912), False, 'import asyncio\n'), ((6482, 6496), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (6494, 6496), False, 'import asyncio\n'), ((7228, 7242), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (7240, 7242), False, 'import asyncio\n'), ((7804, 7818), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (7816, 7818), False, 'import asyncio\n'), ((9012, 9026), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (9024, 9026), False, 'import asyncio\n'), ((9493, 9507), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (9505, 9507), False, 'import asyncio\n'), ((10545, 10559), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (10557, 10559), False, 'import asyncio\n'), ((11258, 11272), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (11270, 11272), False, 'import asyncio\n'), ((2969, 2982), 'decimal.Decimal', 'Decimal', (['"""10"""'], {}), "('10')\n", (2976, 2982), False, 'from decimal import Decimal\n'), ((4768, 4779), 'time.time', 'time.time', ([], {}), '()\n', (4777, 4779), False, 'import time\n'), ((5567, 5578), 'time.time', 'time.time', ([], {}), '()\n', (5576, 5578), False, 'import time\n'), ((10928, 10939), 'time.time', 'time.time', ([], {}), '()\n', (10937, 10939), False, 'import time\n'), ((1113, 1148), 'hummingbot.core.api_throttler.data_types.LinkedLimitWeightPair', 'LinkedLimitWeightPair', (['TEST_POOL_ID'], {}), '(TEST_POOL_ID)\n', (1134, 1148), False, 'from hummingbot.core.api_throttler.data_types import LinkedLimitWeightPair, RateLimit, TaskLog\n'), ((1404, 1451), 'hummingbot.core.api_throttler.data_types.LinkedLimitWeightPair', 'LinkedLimitWeightPair', (['TEST_WEIGHTED_POOL_ID', '(5)'], {}), '(TEST_WEIGHTED_POOL_ID, 5)\n', (1425, 1451), False, 'from hummingbot.core.api_throttler.data_types import LinkedLimitWeightPair, RateLimit, TaskLog\n'), ((1623, 1670), 'hummingbot.core.api_throttler.data_types.LinkedLimitWeightPair', 'LinkedLimitWeightPair', (['TEST_WEIGHTED_POOL_ID', '(1)'], {}), '(TEST_WEIGHTED_POOL_ID, 1)\n', (1644, 1670), False, 'from hummingbot.core.api_throttler.data_types import LinkedLimitWeightPair, RateLimit, TaskLog\n'), ((6925, 6936), 'time.time', 'time.time', ([], {}), '()\n', (6934, 6936), False, 'import time\n'), ((8355, 8366), 'time.time', 'time.time', ([], {}), '()\n', (8364, 8366), False, 'import time\n'), ((8639, 8650), 'time.time', 'time.time', ([], {}), '()\n', (8648, 8650), False, 'import time\n')]
""" Unit tests for hummingbot.core.utils.ethereum """ import asyncio from hummingbot.core.utils.ethereum import check_web3, check_transaction_exceptions, fetch_trading_pairs import unittest.mock class EthereumTest(unittest.TestCase): @unittest.mock.patch('hummingbot.core.utils.ethereum.is_connected_to_web3') def test_check_web3(self, is_connected_to_web3_mock): """ Unit tests for hummingbot.core.utils.ethereum.check_web3 """ # unable to connect to web3 is_connected_to_web3_mock.return_value = False self.assertEqual(check_web3('doesnt-exist'), False) # connect to web3 is_connected_to_web3_mock.return_value = True self.assertEqual(check_web3('ethereum.node'), True) def test_check_transaction_exceptions(self): """ Unit tests for hummingbot.core.utils.ethereum.transaction_exceptions """ # create transactions data that should result in no warnings transaction = { "allowances": {"WBTC": 1000}, "balances": {"ETH": 1000}, "base": "ETH", "quote": "WBTC", "amount": 1000, "side": 100, "gas_limit": 22000, "gas_price": 90, "gas_cost": 90, "price": 100 } self.assertEqual(check_transaction_exceptions(transaction), []) # ETH balance less than gas_cost invalid_transaction_1 = transaction.copy() invalid_transaction_1["balances"] = {"ETH": 10} self.assertRegexpMatches(check_transaction_exceptions(invalid_transaction_1)[0], r"^Insufficient ETH balance to cover gas") # Gas limit set too low, gas_limit is less than 21000 invalid_transaction_2 = transaction.copy() invalid_transaction_2["gas_limit"] = 10000 self.assertRegexpMatches(check_transaction_exceptions(invalid_transaction_2)[0], r"^Gas limit") # Insufficient token allowance, allowance of quote less than amount invalid_transaction_3 = transaction.copy() invalid_transaction_3["allowances"] = {"WBTC": 500} self.assertRegexpMatches(check_transaction_exceptions(invalid_transaction_3)[0], r"^Insufficient") @unittest.mock.patch('hummingbot.core.utils.ethereum.get_token_list') def test_fetch_trading_pairs(self, get_token_list_mock): """ Unit tests for hummingbot.core.utils.ethereum.fetch_trading_pairs """ # patch get_token_list to avoid a server call get_token_list_mock.return_value = {'tokens': [{"symbol": "ETH"}, {"symbol": "DAI"}, {"symbol": "BTC"}]} trading_pairs = asyncio.get_event_loop().run_until_complete(fetch_trading_pairs()) # the order of the elements isn't guaranteed so compare both to sets to compare self.assertEqual(set(trading_pairs), set(['DAI-BTC', 'DAI-ETH', 'BTC-DAI', 'BTC-ETH', 'ETH-DAI', 'ETH-BTC']))
[ "hummingbot.core.utils.ethereum.check_transaction_exceptions", "hummingbot.core.utils.ethereum.fetch_trading_pairs", "hummingbot.core.utils.ethereum.check_web3" ]
[((581, 607), 'hummingbot.core.utils.ethereum.check_web3', 'check_web3', (['"""doesnt-exist"""'], {}), "('doesnt-exist')\n", (591, 607), False, 'from hummingbot.core.utils.ethereum import check_web3, check_transaction_exceptions, fetch_trading_pairs\n'), ((722, 749), 'hummingbot.core.utils.ethereum.check_web3', 'check_web3', (['"""ethereum.node"""'], {}), "('ethereum.node')\n", (732, 749), False, 'from hummingbot.core.utils.ethereum import check_web3, check_transaction_exceptions, fetch_trading_pairs\n'), ((1341, 1382), 'hummingbot.core.utils.ethereum.check_transaction_exceptions', 'check_transaction_exceptions', (['transaction'], {}), '(transaction)\n', (1369, 1382), False, 'from hummingbot.core.utils.ethereum import check_web3, check_transaction_exceptions, fetch_trading_pairs\n'), ((2703, 2724), 'hummingbot.core.utils.ethereum.fetch_trading_pairs', 'fetch_trading_pairs', ([], {}), '()\n', (2722, 2724), False, 'from hummingbot.core.utils.ethereum import check_web3, check_transaction_exceptions, fetch_trading_pairs\n'), ((1570, 1621), 'hummingbot.core.utils.ethereum.check_transaction_exceptions', 'check_transaction_exceptions', (['invalid_transaction_1'], {}), '(invalid_transaction_1)\n', (1598, 1621), False, 'from hummingbot.core.utils.ethereum import check_web3, check_transaction_exceptions, fetch_trading_pairs\n'), ((1867, 1918), 'hummingbot.core.utils.ethereum.check_transaction_exceptions', 'check_transaction_exceptions', (['invalid_transaction_2'], {}), '(invalid_transaction_2)\n', (1895, 1918), False, 'from hummingbot.core.utils.ethereum import check_web3, check_transaction_exceptions, fetch_trading_pairs\n'), ((2159, 2210), 'hummingbot.core.utils.ethereum.check_transaction_exceptions', 'check_transaction_exceptions', (['invalid_transaction_3'], {}), '(invalid_transaction_3)\n', (2187, 2210), False, 'from hummingbot.core.utils.ethereum import check_web3, check_transaction_exceptions, fetch_trading_pairs\n'), ((2659, 2683), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2681, 2683), False, 'import asyncio\n')]
from hummingbot.core.utils.market_price import get_mid_price from hummingbot.client.settings import CONNECTOR_SETTINGS from hummingbot.client.config.security import Security from hummingbot.client.config.config_helpers import get_connector_class, get_eth_wallet_private_key from hummingbot.core.utils.async_utils import safe_gather from hummingbot.client.config.global_config_map import global_config_map from hummingbot.connector.connector.balancer.balancer_connector import BalancerConnector from hummingbot.connector.derivative.perpetual_finance.perpetual_finance_derivative import PerpetualFinanceDerivative from hummingbot.client.settings import ethereum_required_trading_pairs from typing import Optional, Dict, List from decimal import Decimal from web3 import Web3 class UserBalances: __instance = None @staticmethod def connect_market(exchange, **api_details): connector = None conn_setting = CONNECTOR_SETTINGS[exchange] if not conn_setting.use_ethereum_wallet: connector_class = get_connector_class(exchange) init_params = conn_setting.conn_init_parameters(api_details) connector = connector_class(**init_params) return connector # return error message if the _update_balances fails @staticmethod async def _update_balances(market) -> Optional[str]: try: await market._update_balances() except Exception as e: return str(e) return None @staticmethod def instance(): if UserBalances.__instance is None: UserBalances() return UserBalances.__instance def __init__(self): if UserBalances.__instance is not None: raise Exception("This class is a singleton!") else: UserBalances.__instance = self self._markets = {} async def add_exchange(self, exchange, **api_details) -> Optional[str]: self._markets.pop(exchange, None) market = UserBalances.connect_market(exchange, **api_details) err_msg = await UserBalances._update_balances(market) if err_msg is None: self._markets[exchange] = market return err_msg def all_balances(self, exchange) -> Dict[str, Decimal]: if exchange not in self._markets: return None return self._markets[exchange].get_all_balances() async def update_exchange_balance(self, exchange) -> Optional[str]: if exchange in self._markets: return await self._update_balances(self._markets[exchange]) else: api_keys = await Security.api_keys(exchange) if api_keys: return await self.add_exchange(exchange, **api_keys) else: return "API keys have not been added." # returns error message for each exchange async def update_exchanges(self, reconnect: bool = False, exchanges: List[str] = []) -> Dict[str, Optional[str]]: tasks = [] # Update user balances, except connectors that use Ethereum wallet. if len(exchanges) == 0: exchanges = [cs.name for cs in CONNECTOR_SETTINGS.values()] exchanges = [cs.name for cs in CONNECTOR_SETTINGS.values() if not cs.use_ethereum_wallet and cs.name in exchanges] if reconnect: self._markets.clear() for exchange in exchanges: tasks.append(self.update_exchange_balance(exchange)) results = await safe_gather(*tasks) return {ex: err_msg for ex, err_msg in zip(exchanges, results)} async def all_balances_all_exchanges(self) -> Dict[str, Dict[str, Decimal]]: await self.update_exchanges() return {k: v.get_all_balances() for k, v in sorted(self._markets.items(), key=lambda x: x[0])} def all_avai_balances_all_exchanges(self) -> Dict[str, Dict[str, Decimal]]: return {k: v.available_balances for k, v in sorted(self._markets.items(), key=lambda x: x[0])} async def balances(self, exchange, *symbols) -> Dict[str, Decimal]: if await self.update_exchange_balance(exchange) is None: results = {} for token, bal in self.all_balances(exchange).items(): matches = [s for s in symbols if s.lower() == token.lower()] if matches: results[matches[0]] = bal return results @staticmethod def ethereum_balance() -> Decimal: ethereum_wallet = global_config_map.get("ethereum_wallet").value ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value web3 = Web3(Web3.HTTPProvider(ethereum_rpc_url)) balance = web3.eth.getBalance(ethereum_wallet) balance = web3.fromWei(balance, "ether") return balance @staticmethod async def eth_n_erc20_balances() -> Dict[str, Decimal]: ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value # Todo: Use generic ERC20 balance update connector = BalancerConnector(ethereum_required_trading_pairs(), get_eth_wallet_private_key(), ethereum_rpc_url, True) await connector._update_balances() return connector.get_all_balances() @staticmethod async def xdai_balances() -> Dict[str, Decimal]: connector = PerpetualFinanceDerivative("", get_eth_wallet_private_key(), "", True) await connector._update_balances() return connector.get_all_balances() @staticmethod def validate_ethereum_wallet() -> Optional[str]: if global_config_map.get("ethereum_wallet").value is None: return "Ethereum wallet is required." if global_config_map.get("ethereum_rpc_url").value is None: return "ethereum_rpc_url is required." if global_config_map.get("ethereum_rpc_ws_url").value is None: return "ethereum_rpc_ws_url is required." if global_config_map.get("ethereum_wallet").value not in Security.private_keys(): return "Ethereum private key file does not exist or corrupts." try: UserBalances.ethereum_balance() except Exception as e: return str(e) return None @staticmethod def base_amount_ratio(exchange, trading_pair, balances) -> Optional[Decimal]: try: base, quote = trading_pair.split("-") base_amount = balances.get(base, 0) quote_amount = balances.get(quote, 0) price = get_mid_price(exchange, trading_pair) total_value = base_amount + (quote_amount / price) return None if total_value <= 0 else base_amount / total_value except Exception: return None
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.client.settings.ethereum_required_trading_pairs", "hummingbot.client.config.config_helpers.get_connector_class", "hummingbot.client.config.security.Security.private_keys", "hummingbot.client.config.config_helpers.get_eth_wallet_private_key", "hu...
[((1042, 1071), 'hummingbot.client.config.config_helpers.get_connector_class', 'get_connector_class', (['exchange'], {}), '(exchange)\n', (1061, 1071), False, 'from hummingbot.client.config.config_helpers import get_connector_class, get_eth_wallet_private_key\n'), ((3528, 3547), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*tasks'], {}), '(*tasks)\n', (3539, 3547), False, 'from hummingbot.core.utils.async_utils import safe_gather\n'), ((4519, 4559), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_wallet"""'], {}), "('ethereum_wallet')\n", (4540, 4559), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((4593, 4634), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_rpc_url"""'], {}), "('ethereum_rpc_url')\n", (4614, 4634), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((4661, 4696), 'web3.Web3.HTTPProvider', 'Web3.HTTPProvider', (['ethereum_rpc_url'], {}), '(ethereum_rpc_url)\n', (4678, 4696), False, 'from web3 import Web3\n'), ((4931, 4972), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_rpc_url"""'], {}), "('ethereum_rpc_url')\n", (4952, 4972), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((5066, 5099), 'hummingbot.client.settings.ethereum_required_trading_pairs', 'ethereum_required_trading_pairs', ([], {}), '()\n', (5097, 5099), False, 'from hummingbot.client.settings import ethereum_required_trading_pairs\n'), ((5139, 5167), 'hummingbot.client.config.config_helpers.get_eth_wallet_private_key', 'get_eth_wallet_private_key', ([], {}), '()\n', (5165, 5167), False, 'from hummingbot.client.config.config_helpers import get_connector_class, get_eth_wallet_private_key\n'), ((5526, 5554), 'hummingbot.client.config.config_helpers.get_eth_wallet_private_key', 'get_eth_wallet_private_key', ([], {}), '()\n', (5552, 5554), False, 'from hummingbot.client.config.config_helpers import get_connector_class, get_eth_wallet_private_key\n'), ((6245, 6268), 'hummingbot.client.config.security.Security.private_keys', 'Security.private_keys', ([], {}), '()\n', (6266, 6268), False, 'from hummingbot.client.config.security import Security\n'), ((6761, 6798), 'hummingbot.core.utils.market_price.get_mid_price', 'get_mid_price', (['exchange', 'trading_pair'], {}), '(exchange, trading_pair)\n', (6774, 6798), False, 'from hummingbot.core.utils.market_price import get_mid_price\n'), ((2614, 2641), 'hummingbot.client.config.security.Security.api_keys', 'Security.api_keys', (['exchange'], {}), '(exchange)\n', (2631, 2641), False, 'from hummingbot.client.config.security import Security\n'), ((3243, 3270), 'hummingbot.client.settings.CONNECTOR_SETTINGS.values', 'CONNECTOR_SETTINGS.values', ([], {}), '()\n', (3268, 3270), False, 'from hummingbot.client.settings import CONNECTOR_SETTINGS\n'), ((5830, 5870), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_wallet"""'], {}), "('ethereum_wallet')\n", (5851, 5870), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((5947, 5988), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_rpc_url"""'], {}), "('ethereum_rpc_url')\n", (5968, 5988), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((6066, 6110), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_rpc_ws_url"""'], {}), "('ethereum_rpc_ws_url')\n", (6087, 6110), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((6191, 6231), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_wallet"""'], {}), "('ethereum_wallet')\n", (6212, 6231), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((3175, 3202), 'hummingbot.client.settings.CONNECTOR_SETTINGS.values', 'CONNECTOR_SETTINGS.values', ([], {}), '()\n', (3200, 3202), False, 'from hummingbot.client.settings import CONNECTOR_SETTINGS\n')]
""" Unit tests for hummingbot.strategy.uniswap_v3_lp.uniswap_v3_lp """ from decimal import Decimal import pandas as pd import numpy as np from typing import Dict, List import unittest.mock import asyncio from hummingbot.core.clock import Clock, ClockMode from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from hummingbot.strategy.uniswap_v3_lp.uniswap_v3_lp import UniswapV3LpStrategy from hummingbot.connector.connector.uniswap_v3.uniswap_v3_in_flight_position import UniswapV3InFlightPosition from hummingsim.backtest.backtest_market import BacktestMarket from hummingsim.backtest.market import QuantizationParams from hummingsim.backtest.mock_order_book_loader import MockOrderBookLoader class ExtendedBacktestMarket(BacktestMarket): def __init__(self): super().__init__() self._trading_pairs = ["ETH-USDT"] np.random.seed(123456789) self._in_flight_positions = {} self._in_flight_orders = {} async def get_price_by_fee_tier(self, trading_pair: str, tier: str, seconds: int = 1, twap: bool = False): if twap: original_price = 100 volatility = 0.1 return np.random.normal(original_price, volatility, 3599) else: return Decimal("100") def add_position(self, trading_pair: str, fee_tier: str, base_amount: Decimal, quote_amount: Decimal, lower_price: Decimal, upper_price: Decimal, token_id: int = 0): self._in_flight_positions["pos1"] = UniswapV3InFlightPosition(hb_id="pos1", token_id=token_id, trading_pair=trading_pair, fee_tier=fee_tier, base_amount=base_amount, quote_amount=quote_amount, lower_price=lower_price, upper_price=upper_price) async def _remove_position(self, hb_id: str, token_id: str = "1", reducePercent: Decimal = Decimal("100.0"), fee_estimate: bool = False): return self.remove_position(hb_id, token_id, reducePercent, fee_estimate) def remove_position(self, hb_id: str, token_id: str = "1", reducePercent: Decimal = Decimal("100.0"), fee_estimate: bool = False): if fee_estimate: return Decimal("0") else: self._in_flight_positions.pop(hb_id) class UniswapV3LpStrategyTest(unittest.TestCase): start: pd.Timestamp = pd.Timestamp("2019-01-01", tz="UTC") end: pd.Timestamp = pd.Timestamp("2019-01-01 01:00:00", tz="UTC") start_timestamp: float = start.timestamp() end_timestamp: float = end.timestamp() market_infos: Dict[str, MarketTradingPairTuple] = {} @staticmethod def create_market(trading_pairs: List[str], mid_price, balances: Dict[str, int]) -> (BacktestMarket, Dict[str, MarketTradingPairTuple]): """ Create a BacktestMarket and marketinfo dictionary to be used by the liquidity mining strategy """ market: ExtendedBacktestMarket = ExtendedBacktestMarket() market_infos: Dict[str, MarketTradingPairTuple] = {} for trading_pair in trading_pairs: base_asset = trading_pair.split("-")[0] quote_asset = trading_pair.split("-")[1] book_data: MockOrderBookLoader = MockOrderBookLoader(trading_pair, base_asset, quote_asset) book_data.set_balanced_order_book(mid_price=mid_price, min_price=1, max_price=200, price_step_size=1, volume_step_size=10) market.add_data(book_data) market.set_quantization_param(QuantizationParams(trading_pair, 6, 6, 6, 6)) market_infos[trading_pair] = MarketTradingPairTuple(market, trading_pair, base_asset, quote_asset) for asset, value in balances.items(): market.set_balance(asset, value) return market, market_infos def setUp(self) -> None: self.loop = asyncio.get_event_loop() self.clock_tick_size = 1 self.clock: Clock = Clock(ClockMode.BACKTEST, self.clock_tick_size, self.start_timestamp, self.end_timestamp) self.mid_price = 100 self.bid_spread = 0.01 self.ask_spread = 0.01 self.order_refresh_time = 1 trading_pairs = list(map(lambda quote_asset: "ETH-" + quote_asset, ["USDT", "BTC"])) market, market_infos = self.create_market(trading_pairs, self.mid_price, {"USDT": 5000, "ETH": 500, "BTC": 100}) self.market = market self.market_infos = market_infos self.default_strategy = UniswapV3LpStrategy( self.market_infos[trading_pairs[0]], "MEDIUM", True, Decimal('144'), Decimal('2'), Decimal('0.01'), Decimal('0.01'), Decimal('1'), Decimal('1'), Decimal('0.05') ) def test_generate_proposal_with_volatility_above_zero(self): """ Test generate proposal function works correctly when volatility is above zero """ orders = self.loop.run_until_complete(self.default_strategy.propose_position_creation()) self.assertEqual(orders[0][0], Decimal("0")) self.assertEqual(orders[0][1], Decimal("100")) self.assertEqual(orders[1][0], Decimal("100")) self.assertAlmostEqual(orders[1][1], Decimal("305.35"), 1) def test_generate_proposal_with_volatility_equal_zero(self): """ Test generate proposal function works correctly when volatility is zero """ for x in range(3600): self.default_strategy._volatility.add_sample(100) orders = self.loop.run_until_complete(self.default_strategy.propose_position_creation()) self.assertEqual(orders[0][0], Decimal("99")) self.assertEqual(orders[0][1], Decimal("100")) self.assertEqual(orders[1][0], Decimal("100")) self.assertEqual(orders[1][1], Decimal("101")) def test_generate_proposal_without_volatility(self): """ Test generate proposal function works correctly using user set spreads """ self.default_strategy._use_volatility = False orders = self.loop.run_until_complete(self.default_strategy.propose_position_creation()) self.assertEqual(orders[0][0], Decimal("99")) self.assertEqual(orders[0][1], Decimal("100")) self.assertEqual(orders[1][0], Decimal("100")) self.assertEqual(orders[1][1], Decimal("101")) def test_profitability_calculation(self): """ Test profitability calculation function works correctly """ pos = UniswapV3InFlightPosition(hb_id="pos1", token_id=1, trading_pair="HBOT-USDT", fee_tier="MEDIUM", base_amount=Decimal("0"), quote_amount=Decimal("100"), lower_price=Decimal("100"), upper_price=Decimal("101")) pos.current_base_amount = Decimal("1") pos.current_quote_amount = Decimal("0") pos.unclaimed_base_amount = Decimal("1") pos.unclaimed_quote_amount = Decimal("10") pos.gas_price = Decimal("5") self.default_strategy._last_price = Decimal("100") result = self.loop.run_until_complete(self.default_strategy.calculate_profitability(pos)) self.assertEqual(result["profitability"], (Decimal("110") - result["tx_fee"]) / Decimal("100")) def test_position_creation(self): """ Test that positions are created properly. """ self.assertEqual(len(self.default_strategy._market_info.market._in_flight_positions), 0) self.default_strategy.execute_proposal([[95, 100], []]) self.assertEqual(len(self.default_strategy._market_info.market._in_flight_positions), 1) def test_range_calculation(self): """ Test that the overall range of all positions cover are calculated correctly. """ self.default_strategy._market_info.market._in_flight_positions["pos1"] = UniswapV3InFlightPosition(hb_id="pos1", token_id=1, trading_pair="ETH-USDT", fee_tier="MEDIUM", base_amount=Decimal("0"), quote_amount=Decimal("100"), lower_price=Decimal("90"), upper_price=Decimal("95")) self.default_strategy._market_info.market._in_flight_positions["pos2"] = UniswapV3InFlightPosition(hb_id="pos2", token_id=2, trading_pair="ETH-USDT", fee_tier="MEDIUM", base_amount=Decimal("0"), quote_amount=Decimal("100"), lower_price=Decimal("95"), upper_price=Decimal("100")) self.default_strategy._market_info.market._in_flight_positions["pos3"] = UniswapV3InFlightPosition(hb_id="pos3", token_id=3, trading_pair="ETH-USDT", fee_tier="MEDIUM", base_amount=Decimal("0"), quote_amount=Decimal("100"), lower_price=Decimal("100"), upper_price=Decimal("105")) self.default_strategy._market_info.market._in_flight_positions["pos4"] = UniswapV3InFlightPosition(hb_id="pos4", token_id=4, trading_pair="ETH-USDT", fee_tier="MEDIUM", base_amount=Decimal("0"), quote_amount=Decimal("100"), lower_price=Decimal("105"), upper_price=Decimal("110")) self.assertEqual(len(self.default_strategy._market_info.market._in_flight_positions), 4) lower_bound, upper_bound = self.default_strategy.total_position_range() self.assertEqual(lower_bound, Decimal("90")) self.assertEqual(upper_bound, Decimal("110"))
[ "hummingbot.connector.connector.uniswap_v3.uniswap_v3_in_flight_position.UniswapV3InFlightPosition", "hummingbot.core.clock.Clock", "hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple" ]
[((2903, 2939), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01"""'], {'tz': '"""UTC"""'}), "('2019-01-01', tz='UTC')\n", (2915, 2939), True, 'import pandas as pd\n'), ((2964, 3009), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01 01:00:00"""'], {'tz': '"""UTC"""'}), "('2019-01-01 01:00:00', tz='UTC')\n", (2976, 3009), True, 'import pandas as pd\n'), ((875, 900), 'numpy.random.seed', 'np.random.seed', (['(123456789)'], {}), '(123456789)\n', (889, 900), True, 'import numpy as np\n'), ((1647, 1863), 'hummingbot.connector.connector.uniswap_v3.uniswap_v3_in_flight_position.UniswapV3InFlightPosition', 'UniswapV3InFlightPosition', ([], {'hb_id': '"""pos1"""', 'token_id': 'token_id', 'trading_pair': 'trading_pair', 'fee_tier': 'fee_tier', 'base_amount': 'base_amount', 'quote_amount': 'quote_amount', 'lower_price': 'lower_price', 'upper_price': 'upper_price'}), "(hb_id='pos1', token_id=token_id, trading_pair=\n trading_pair, fee_tier=fee_tier, base_amount=base_amount, quote_amount=\n quote_amount, lower_price=lower_price, upper_price=upper_price)\n", (1672, 1863), False, 'from hummingbot.connector.connector.uniswap_v3.uniswap_v3_in_flight_position import UniswapV3InFlightPosition\n'), ((2440, 2456), 'decimal.Decimal', 'Decimal', (['"""100.0"""'], {}), "('100.0')\n", (2447, 2456), False, 'from decimal import Decimal\n'), ((2658, 2674), 'decimal.Decimal', 'Decimal', (['"""100.0"""'], {}), "('100.0')\n", (2665, 2674), False, 'from decimal import Decimal\n'), ((4560, 4584), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (4582, 4584), False, 'import asyncio\n'), ((4646, 4740), 'hummingbot.core.clock.Clock', 'Clock', (['ClockMode.BACKTEST', 'self.clock_tick_size', 'self.start_timestamp', 'self.end_timestamp'], {}), '(ClockMode.BACKTEST, self.clock_tick_size, self.start_timestamp, self.\n end_timestamp)\n', (4651, 4740), False, 'from hummingbot.core.clock import Clock, ClockMode\n'), ((7781, 7793), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (7788, 7793), False, 'from decimal import Decimal\n'), ((7829, 7841), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (7836, 7841), False, 'from decimal import Decimal\n'), ((7878, 7890), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (7885, 7890), False, 'from decimal import Decimal\n'), ((7928, 7941), 'decimal.Decimal', 'Decimal', (['"""10"""'], {}), "('10')\n", (7935, 7941), False, 'from decimal import Decimal\n'), ((7966, 7978), 'decimal.Decimal', 'Decimal', (['"""5"""'], {}), "('5')\n", (7973, 7978), False, 'from decimal import Decimal\n'), ((8023, 8037), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (8030, 8037), False, 'from decimal import Decimal\n'), ((1186, 1236), 'numpy.random.normal', 'np.random.normal', (['original_price', 'volatility', '(3599)'], {}), '(original_price, volatility, 3599)\n', (1202, 1236), True, 'import numpy as np\n'), ((1270, 1284), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (1277, 1284), False, 'from decimal import Decimal\n'), ((2749, 2761), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (2756, 2761), False, 'from decimal import Decimal\n'), ((3765, 3823), 'hummingsim.backtest.mock_order_book_loader.MockOrderBookLoader', 'MockOrderBookLoader', (['trading_pair', 'base_asset', 'quote_asset'], {}), '(trading_pair, base_asset, quote_asset)\n', (3784, 3823), False, 'from hummingsim.backtest.mock_order_book_loader import MockOrderBookLoader\n'), ((4311, 4380), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['market', 'trading_pair', 'base_asset', 'quote_asset'], {}), '(market, trading_pair, base_asset, quote_asset)\n', (4333, 4380), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((5304, 5318), 'decimal.Decimal', 'Decimal', (['"""144"""'], {}), "('144')\n", (5311, 5318), False, 'from decimal import Decimal\n'), ((5332, 5344), 'decimal.Decimal', 'Decimal', (['"""2"""'], {}), "('2')\n", (5339, 5344), False, 'from decimal import Decimal\n'), ((5358, 5373), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (5365, 5373), False, 'from decimal import Decimal\n'), ((5387, 5402), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (5394, 5402), False, 'from decimal import Decimal\n'), ((5416, 5428), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (5423, 5428), False, 'from decimal import Decimal\n'), ((5442, 5454), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (5449, 5454), False, 'from decimal import Decimal\n'), ((5468, 5483), 'decimal.Decimal', 'Decimal', (['"""0.05"""'], {}), "('0.05')\n", (5475, 5483), False, 'from decimal import Decimal\n'), ((5807, 5819), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (5814, 5819), False, 'from decimal import Decimal\n'), ((5860, 5874), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (5867, 5874), False, 'from decimal import Decimal\n'), ((5915, 5929), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (5922, 5929), False, 'from decimal import Decimal\n'), ((5976, 5993), 'decimal.Decimal', 'Decimal', (['"""305.35"""'], {}), "('305.35')\n", (5983, 5993), False, 'from decimal import Decimal\n'), ((6397, 6410), 'decimal.Decimal', 'Decimal', (['"""99"""'], {}), "('99')\n", (6404, 6410), False, 'from decimal import Decimal\n'), ((6451, 6465), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (6458, 6465), False, 'from decimal import Decimal\n'), ((6506, 6520), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (6513, 6520), False, 'from decimal import Decimal\n'), ((6561, 6575), 'decimal.Decimal', 'Decimal', (['"""101"""'], {}), "('101')\n", (6568, 6575), False, 'from decimal import Decimal\n'), ((6929, 6942), 'decimal.Decimal', 'Decimal', (['"""99"""'], {}), "('99')\n", (6936, 6942), False, 'from decimal import Decimal\n'), ((6983, 6997), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (6990, 6997), False, 'from decimal import Decimal\n'), ((7038, 7052), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (7045, 7052), False, 'from decimal import Decimal\n'), ((7093, 7107), 'decimal.Decimal', 'Decimal', (['"""101"""'], {}), "('101')\n", (7100, 7107), False, 'from decimal import Decimal\n'), ((13119, 13132), 'decimal.Decimal', 'Decimal', (['"""90"""'], {}), "('90')\n", (13126, 13132), False, 'from decimal import Decimal\n'), ((13172, 13186), 'decimal.Decimal', 'Decimal', (['"""110"""'], {}), "('110')\n", (13179, 13186), False, 'from decimal import Decimal\n'), ((4224, 4268), 'hummingsim.backtest.market.QuantizationParams', 'QuantizationParams', (['trading_pair', '(6)', '(6)', '(6)', '(6)'], {}), '(trading_pair, 6, 6, 6, 6)\n', (4242, 4268), False, 'from hummingsim.backtest.market import QuantizationParams\n'), ((7528, 7540), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (7535, 7540), False, 'from decimal import Decimal\n'), ((7595, 7609), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (7602, 7609), False, 'from decimal import Decimal\n'), ((7663, 7677), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (7670, 7677), False, 'from decimal import Decimal\n'), ((7731, 7745), 'decimal.Decimal', 'Decimal', (['"""101"""'], {}), "('101')\n", (7738, 7745), False, 'from decimal import Decimal\n'), ((8224, 8238), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (8231, 8238), False, 'from decimal import Decimal\n'), ((9376, 9388), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (9383, 9388), False, 'from decimal import Decimal\n'), ((9510, 9524), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (9517, 9524), False, 'from decimal import Decimal\n'), ((9645, 9658), 'decimal.Decimal', 'Decimal', (['"""90"""'], {}), "('90')\n", (9652, 9658), False, 'from decimal import Decimal\n'), ((9779, 9792), 'decimal.Decimal', 'Decimal', (['"""95"""'], {}), "('95')\n", (9786, 9792), False, 'from decimal import Decimal\n'), ((10411, 10423), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (10418, 10423), False, 'from decimal import Decimal\n'), ((10545, 10559), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (10552, 10559), False, 'from decimal import Decimal\n'), ((10680, 10693), 'decimal.Decimal', 'Decimal', (['"""95"""'], {}), "('95')\n", (10687, 10693), False, 'from decimal import Decimal\n'), ((10814, 10828), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (10821, 10828), False, 'from decimal import Decimal\n'), ((11447, 11459), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (11454, 11459), False, 'from decimal import Decimal\n'), ((11581, 11595), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (11588, 11595), False, 'from decimal import Decimal\n'), ((11716, 11730), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (11723, 11730), False, 'from decimal import Decimal\n'), ((11851, 11865), 'decimal.Decimal', 'Decimal', (['"""105"""'], {}), "('105')\n", (11858, 11865), False, 'from decimal import Decimal\n'), ((12484, 12496), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (12491, 12496), False, 'from decimal import Decimal\n'), ((12618, 12632), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (12625, 12632), False, 'from decimal import Decimal\n'), ((12753, 12767), 'decimal.Decimal', 'Decimal', (['"""105"""'], {}), "('105')\n", (12760, 12767), False, 'from decimal import Decimal\n'), ((12888, 12902), 'decimal.Decimal', 'Decimal', (['"""110"""'], {}), "('110')\n", (12895, 12902), False, 'from decimal import Decimal\n'), ((8187, 8201), 'decimal.Decimal', 'Decimal', (['"""110"""'], {}), "('110')\n", (8194, 8201), False, 'from decimal import Decimal\n')]
#!/usr/bin/env python import asyncio import logging import time import aiohttp import pandas as pd import hummingbot.market.bitcoin_com.bitcoin_com_constants as constants from typing import Optional, List, Dict, Any from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.data_type.order_book_message import OrderBookMessage from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource from hummingbot.core.utils import async_ttl_cache from hummingbot.core.utils.async_utils import safe_gather from hummingbot.logger import HummingbotLogger from hummingbot.market.bitcoin_com.bitcoin_com_active_order_tracker import BitcoinComActiveOrderTracker from hummingbot.market.bitcoin_com.bitcoin_com_order_book import BitcoinComOrderBook from hummingbot.market.bitcoin_com.bitcoin_com_websocket import BitcoinComWebsocket from hummingbot.market.bitcoin_com.bitcoin_com_utils import merge_dicts, add_event_type, EventTypes from hummingbot.market.bitcoin_com.bitcoin_com_order_book_tracker_entry import BitcoinComOrderBookTrackerEntry class BitcoinComAPIOrderBookDataSource(OrderBookTrackerDataSource): MAX_RETRIES = 20 MESSAGE_TIMEOUT = 30.0 SNAPSHOT_TIMEOUT = 10.0 _logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._logger is None: cls._logger = logging.getLogger(__name__) return cls._logger def __init__(self, trading_pairs: Optional[List[str]] = None): super().__init__() self._trading_pairs: Optional[List[str]] = trading_pairs self._snapshot_msg: Dict[str, any] = {} @classmethod @async_ttl_cache(ttl=60 * 30, maxsize=1) async def get_active_exchange_markets(cls) -> pd.DataFrame: """ Returned data frame should have symbol as index and include USDVolume, baseAsset and quoteAsset """ async with aiohttp.ClientSession() as client: markets_response, tickers_response = await safe_gather( client.get(constants.REST_MARKETS_URL), client.get(constants.REST_TICKERS_URL) ) markets_response: aiohttp.ClientResponse = markets_response tickers_response: aiohttp.ClientResponse = tickers_response if markets_response.status != 200: raise IOError( f"Error fetching active {constants.EXCHANGE_NAME} markets information. " f"HTTP status is {markets_response.status}." ) if tickers_response.status != 200: raise IOError( f"Error fetching active {constants.EXCHANGE_NAME} tickers information. " f"HTTP status is {tickers_response.status}." ) markets_data, tickers_data = await safe_gather( markets_response.json(), tickers_response.json() ) markets_data: Dict[str, Any] = {item["id"]: item for item in markets_data} tickers_data: Dict[str, Any] = {item["symbol"]: item for item in tickers_data} data_union = merge_dicts(tickers_data, markets_data) all_markets: pd.DataFrame = pd.DataFrame.from_records(data=list(data_union.values()), index="symbol") all_markets.rename( {"baseCurrency": "baseAsset", "quoteCurrency": "quoteAsset"}, axis="columns", inplace=True ) btc_usd_price: float = float(all_markets.loc["BTCUSD"]["last"]) eth_usd_price: float = float(all_markets.loc["ETHUSD"]["last"]) usd_volume: List[float] = [ ( volume * last if symbol.endswith(("USD", "USDT")) else volume * last * btc_usd_price if symbol.endswith("BTC") else volume * last * eth_usd_price if symbol.endswith("ETH") else volume ) for symbol, volume, last in zip(all_markets.index, all_markets.volume.astype("float"), all_markets["last"].astype("float") ) ] all_markets.loc[:, "USDVolume"] = usd_volume await client.close() return all_markets.sort_values("USDVolume", ascending=False) async def get_trading_pairs(self) -> List[str]: """ Return list of trading pairs """ if not self._trading_pairs: try: active_markets: pd.DataFrame = await self.get_active_exchange_markets() self._trading_pairs = active_markets.index.tolist() except Exception: self._trading_pairs = [] self.logger().network( f"Error getting active exchange information.", exc_info=True, app_warning_msg=f"Error getting active exchange information. Check network connection.", ) return self._trading_pairs @staticmethod async def get_orderbook(trading_pair: str) -> Dict[str, any]: """ Get whole orderbook """ client = aiohttp.ClientSession() orderbook_response = await client.get(f"{constants.REST_ORDERBOOK_URL}/{trading_pair}", params={"limit": 0}) if orderbook_response.status != 200: raise IOError( f"Error fetching OrderBook for {trading_pair} at {constants.EXCHANGE_NAME}. " f"HTTP status is {orderbook_response.status}." ) orderbook_data: List[Dict[str, Any]] = await safe_gather(orderbook_response.json()) await client.close() if len(orderbook_data) > 0: return orderbook_data[0] return {} async def get_tracking_pairs(self) -> Dict[str, BitcoinComOrderBookTrackerEntry]: trading_pairs: List[str] = await self.get_trading_pairs() tracking_pairs: Dict[str, BitcoinComOrderBookTrackerEntry] = {} number_of_pairs: int = len(trading_pairs) for index, trading_pair in enumerate(trading_pairs): try: snapshot: Dict[str, any] = await self.get_orderbook(trading_pair) snapshot_timestamp: float = pd.Timestamp(snapshot["timestamp"]).timestamp() snapshot_msg: OrderBookMessage = BitcoinComOrderBook.snapshot_message_from_exchange( add_event_type(EventTypes.OrderbookSnapshot, snapshot), snapshot_timestamp, metadata={"trading_pair": trading_pair} ) order_book: OrderBook = self.order_book_create_function() active_order_tracker: BitcoinComActiveOrderTracker = BitcoinComActiveOrderTracker() bids, asks = active_order_tracker.convert_snapshot_message_to_order_book_row(snapshot_msg) order_book.apply_snapshot(bids, asks, snapshot_msg.update_id) tracking_pairs[trading_pair] = BitcoinComOrderBookTrackerEntry( trading_pair, snapshot_timestamp, order_book, active_order_tracker ) self.logger().info(f"Initialized order book for {trading_pair}. " f"{index+1}/{number_of_pairs} completed.") await asyncio.sleep(0.6) except IOError: self.logger().network( f"Error getting snapshot for {trading_pair}.", exc_info=True, app_warning_msg=f"Error getting snapshot for {trading_pair}. Check network connection." ) except Exception: self.logger().error(f"Error initializing order book for {trading_pair}. ", exc_info=True) return tracking_pairs async def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Listen for trades using websocket "updateTrades" method """ while True: try: ws = BitcoinComWebsocket() await ws.connect() trading_pairs: List[str] = await self.get_trading_pairs() for trading_pair in trading_pairs: await ws.subscribe("subscribeTrades", { "symbol": trading_pair, "limit": 1 # we only care about updates, this sets the initial snapshot limit }) async for response in ws.on("updateTrades"): if (response["error"] is not None): self.logger().error(response["error"]) continue trades = response["data"]["data"] for trade in trades: trade_timestamp: float = pd.Timestamp(trade["timestamp"]).timestamp() trade_msg: OrderBookMessage = BitcoinComOrderBook.trade_message_from_exchange( add_event_type(EventTypes.TradesUpdate, trade), trade_timestamp, metadata={"trading_pair": trading_pair} ) output.put_nowait(trade_msg) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error.", exc_info=True) await asyncio.sleep(5.0) finally: await ws.disconnect() async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Listen for orderbook diffs using websocket "updateOrderbook" method """ while True: try: ws = BitcoinComWebsocket() await ws.connect() trading_pairs: List[str] = await self.get_trading_pairs() for trading_pair in trading_pairs: await ws.subscribe("subscribeOrderbook", { "symbol": trading_pair }) async for response in ws.on("updateOrderbook"): if (response["error"] is not None): self.logger().error(response["error"]) continue diff = response["data"] diff_timestamp: float = pd.Timestamp(diff["timestamp"]).timestamp() orderbook_msg: OrderBookMessage = BitcoinComOrderBook.diff_message_from_exchange( add_event_type(EventTypes.OrderbookUpdate, diff), diff_timestamp, metadata={"trading_pair": trading_pair} ) output.put_nowait(orderbook_msg) except asyncio.CancelledError: raise except Exception: self.logger().network( f"Unexpected error with WebSocket connection.", exc_info=True, app_warning_msg=f"Unexpected error with WebSocket connection. Retrying in 30 seconds. " f"Check network connection." ) await asyncio.sleep(30.0) finally: await ws.disconnect() async def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Listen for orderbook snapshots by fetching orderbook """ while True: try: trading_pairs: List[str] = await self.get_trading_pairs() for trading_pair in trading_pairs: try: snapshot: Dict[str, any] = await self.get_orderbook(trading_pair) snapshot_timestamp: float = pd.Timestamp(snapshot["timestamp"]).timestamp() snapshot_msg: OrderBookMessage = BitcoinComOrderBook.snapshot_message_from_exchange( add_event_type(EventTypes.OrderbookSnapshot, snapshot), snapshot_timestamp, metadata={"trading_pair": trading_pair} ) output.put_nowait(snapshot_msg) self.logger().debug(f"Saved order book snapshot for {trading_pair}") # Be careful not to go above API rate limits. await asyncio.sleep(5.0) except asyncio.CancelledError: raise except Exception: self.logger().network( f"Unexpected error with WebSocket connection.", exc_info=True, app_warning_msg=f"Unexpected error with WebSocket connection. Retrying in 5 seconds. " f"Check network connection." ) await asyncio.sleep(5.0) this_hour: pd.Timestamp = pd.Timestamp.utcnow().replace(minute=0, second=0, microsecond=0) next_hour: pd.Timestamp = this_hour + pd.Timedelta(hours=1) delta: float = next_hour.timestamp() - time.time() await asyncio.sleep(delta) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error.", exc_info=True) await asyncio.sleep(5.0)
[ "hummingbot.core.utils.async_ttl_cache", "hummingbot.market.bitcoin_com.bitcoin_com_utils.add_event_type", "hummingbot.market.bitcoin_com.bitcoin_com_websocket.BitcoinComWebsocket", "hummingbot.market.bitcoin_com.bitcoin_com_order_book_tracker_entry.BitcoinComOrderBookTrackerEntry", "hummingbot.market.bitco...
[((1682, 1721), 'hummingbot.core.utils.async_ttl_cache', 'async_ttl_cache', ([], {'ttl': '(60 * 30)', 'maxsize': '(1)'}), '(ttl=60 * 30, maxsize=1)\n', (1697, 1721), False, 'from hummingbot.core.utils import async_ttl_cache\n'), ((5239, 5262), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (5260, 5262), False, 'import aiohttp\n'), ((1396, 1423), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1413, 1423), False, 'import logging\n'), ((1933, 1956), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (1954, 1956), False, 'import aiohttp\n'), ((3121, 3160), 'hummingbot.market.bitcoin_com.bitcoin_com_utils.merge_dicts', 'merge_dicts', (['tickers_data', 'markets_data'], {}), '(tickers_data, markets_data)\n', (3132, 3160), False, 'from hummingbot.market.bitcoin_com.bitcoin_com_utils import merge_dicts, add_event_type, EventTypes\n'), ((6790, 6820), 'hummingbot.market.bitcoin_com.bitcoin_com_active_order_tracker.BitcoinComActiveOrderTracker', 'BitcoinComActiveOrderTracker', ([], {}), '()\n', (6818, 6820), False, 'from hummingbot.market.bitcoin_com.bitcoin_com_active_order_tracker import BitcoinComActiveOrderTracker\n'), ((7054, 7157), 'hummingbot.market.bitcoin_com.bitcoin_com_order_book_tracker_entry.BitcoinComOrderBookTrackerEntry', 'BitcoinComOrderBookTrackerEntry', (['trading_pair', 'snapshot_timestamp', 'order_book', 'active_order_tracker'], {}), '(trading_pair, snapshot_timestamp,\n order_book, active_order_tracker)\n', (7085, 7157), False, 'from hummingbot.market.bitcoin_com.bitcoin_com_order_book_tracker_entry import BitcoinComOrderBookTrackerEntry\n'), ((8156, 8177), 'hummingbot.market.bitcoin_com.bitcoin_com_websocket.BitcoinComWebsocket', 'BitcoinComWebsocket', ([], {}), '()\n', (8175, 8177), False, 'from hummingbot.market.bitcoin_com.bitcoin_com_websocket import BitcoinComWebsocket\n'), ((9932, 9953), 'hummingbot.market.bitcoin_com.bitcoin_com_websocket.BitcoinComWebsocket', 'BitcoinComWebsocket', ([], {}), '()\n', (9951, 9953), False, 'from hummingbot.market.bitcoin_com.bitcoin_com_websocket import BitcoinComWebsocket\n'), ((6473, 6527), 'hummingbot.market.bitcoin_com.bitcoin_com_utils.add_event_type', 'add_event_type', (['EventTypes.OrderbookSnapshot', 'snapshot'], {}), '(EventTypes.OrderbookSnapshot, snapshot)\n', (6487, 6527), False, 'from hummingbot.market.bitcoin_com.bitcoin_com_utils import merge_dicts, add_event_type, EventTypes\n'), ((7434, 7452), 'asyncio.sleep', 'asyncio.sleep', (['(0.6)'], {}), '(0.6)\n', (7447, 7452), False, 'import asyncio\n'), ((13416, 13437), 'pandas.Timedelta', 'pd.Timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (13428, 13437), True, 'import pandas as pd\n'), ((13493, 13504), 'time.time', 'time.time', ([], {}), '()\n', (13502, 13504), False, 'import time\n'), ((13527, 13547), 'asyncio.sleep', 'asyncio.sleep', (['delta'], {}), '(delta)\n', (13540, 13547), False, 'import asyncio\n'), ((6304, 6339), 'pandas.Timestamp', 'pd.Timestamp', (["snapshot['timestamp']"], {}), "(snapshot['timestamp'])\n", (6316, 6339), True, 'import pandas as pd\n'), ((9591, 9609), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (9604, 9609), False, 'import asyncio\n'), ((11453, 11472), 'asyncio.sleep', 'asyncio.sleep', (['(30.0)'], {}), '(30.0)\n', (11466, 11472), False, 'import asyncio\n'), ((13297, 13318), 'pandas.Timestamp.utcnow', 'pd.Timestamp.utcnow', ([], {}), '()\n', (13316, 13318), True, 'import pandas as pd\n'), ((13737, 13755), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (13750, 13755), False, 'import asyncio\n'), ((10757, 10805), 'hummingbot.market.bitcoin_com.bitcoin_com_utils.add_event_type', 'add_event_type', (['EventTypes.OrderbookUpdate', 'diff'], {}), '(EventTypes.OrderbookUpdate, diff)\n', (10771, 10805), False, 'from hummingbot.market.bitcoin_com.bitcoin_com_utils import merge_dicts, add_event_type, EventTypes\n'), ((12241, 12295), 'hummingbot.market.bitcoin_com.bitcoin_com_utils.add_event_type', 'add_event_type', (['EventTypes.OrderbookSnapshot', 'snapshot'], {}), '(EventTypes.OrderbookSnapshot, snapshot)\n', (12255, 12295), False, 'from hummingbot.market.bitcoin_com.bitcoin_com_utils import merge_dicts, add_event_type, EventTypes\n'), ((12688, 12706), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (12701, 12706), False, 'import asyncio\n'), ((9146, 9192), 'hummingbot.market.bitcoin_com.bitcoin_com_utils.add_event_type', 'add_event_type', (['EventTypes.TradesUpdate', 'trade'], {}), '(EventTypes.TradesUpdate, trade)\n', (9160, 9192), False, 'from hummingbot.market.bitcoin_com.bitcoin_com_utils import merge_dicts, add_event_type, EventTypes\n'), ((10579, 10610), 'pandas.Timestamp', 'pd.Timestamp', (["diff['timestamp']"], {}), "(diff['timestamp'])\n", (10591, 10610), True, 'import pandas as pd\n'), ((12056, 12091), 'pandas.Timestamp', 'pd.Timestamp', (["snapshot['timestamp']"], {}), "(snapshot['timestamp'])\n", (12068, 12091), True, 'import pandas as pd\n'), ((13236, 13254), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (13249, 13254), False, 'import asyncio\n'), ((8962, 8994), 'pandas.Timestamp', 'pd.Timestamp', (["trade['timestamp']"], {}), "(trade['timestamp'])\n", (8974, 8994), True, 'import pandas as pd\n')]
from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from hummingbot.strategy.limit_order import LimitOrder from hummingbot.strategy.limit_order.limit_order_config_map import limit_order_config_map as c_map def start(self): connector = c_map.get("connector").value.lower() market = c_map.get("market").value self._initialize_markets([(connector, [market])]) base, quote = market.split("-") market_info = MarketTradingPairTuple(self.markets[connector], market, base, quote) self.market_trading_pair_tuples = [market_info] self.strategy = LimitOrder(market_info)
[ "hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple", "hummingbot.strategy.limit_order.LimitOrder", "hummingbot.strategy.limit_order.limit_order_config_map.limit_order_config_map.get" ]
[((455, 523), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['self.markets[connector]', 'market', 'base', 'quote'], {}), '(self.markets[connector], market, base, quote)\n', (477, 523), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((597, 620), 'hummingbot.strategy.limit_order.LimitOrder', 'LimitOrder', (['market_info'], {}), '(market_info)\n', (607, 620), False, 'from hummingbot.strategy.limit_order import LimitOrder\n'), ((320, 339), 'hummingbot.strategy.limit_order.limit_order_config_map.limit_order_config_map.get', 'c_map.get', (['"""market"""'], {}), "('market')\n", (329, 339), True, 'from hummingbot.strategy.limit_order.limit_order_config_map import limit_order_config_map as c_map\n'), ((270, 292), 'hummingbot.strategy.limit_order.limit_order_config_map.limit_order_config_map.get', 'c_map.get', (['"""connector"""'], {}), "('connector')\n", (279, 292), True, 'from hummingbot.strategy.limit_order.limit_order_config_map import limit_order_config_map as c_map\n')]
import asyncio from os.path import ( join, dirname ) from typing import ( List, Dict, Any, ) from hummingbot.client.liquidity_bounty.liquidity_bounty_config_map import liquidity_bounty_config_map from hummingbot.client.config.config_helpers import ( parse_cvar_value, save_to_yml, ) from hummingbot.client.liquidity_bounty.bounty_utils import LiquidityBounty from hummingbot.client.settings import LIQUIDITY_BOUNTY_CONFIG_PATH from typing import TYPE_CHECKING if TYPE_CHECKING: from hummingbot.client.hummingbot_application import HummingbotApplication class BountyCommand: def bounty(self, # type: HummingbotApplication register: bool = False, status: bool = False, terms: bool = False, restore_id: bool = False, list: bool = False): """ Router function for `bounty` command """ if terms: asyncio.ensure_future(self.bounty_print_terms(), loop=self.ev_loop) elif register: asyncio.ensure_future(self.bounty_registration(), loop=self.ev_loop) elif list: asyncio.ensure_future(self.bounty_list(), loop=self.ev_loop) elif restore_id: asyncio.ensure_future(self.bounty_restore_id(), loop=self.ev_loop) else: asyncio.ensure_future(self.bounty_show_status(), loop=self.ev_loop) async def print_doc(self, # type: HummingbotApplication doc_path: str): with open(doc_path) as doc: data = doc.read() self._notify(str(data)) async def bounty_show_status(self, # type: HummingbotApplication ): """ Show bounty status """ if self.liquidity_bounty is None: self._notify("Liquidity bounty not active. Please register for the bounty by entering `bounty --register`.") return else: status_table: str = self.liquidity_bounty.formatted_status() self._notify(status_table) volume_metrics: List[Dict[str, Any]] = \ await self.liquidity_bounty.fetch_filled_volume_metrics(start_time=self.start_time or -1) self._notify(self.liquidity_bounty.format_volume_metrics(volume_metrics)) async def bounty_print_terms(self, # type: HummingbotApplication ): """ Print bounty Terms and Conditions to output pane """ await self.print_doc(join(dirname(__file__), "../liquidity_bounty/terms_and_conditions.txt")) async def bounty_registration(self, # type: HummingbotApplication ): """ Register for the bounty program """ if liquidity_bounty_config_map.get("liquidity_bounty_enabled").value and \ liquidity_bounty_config_map.get("liquidity_bounty_client_id").value: self._notify("You are already registered to collect bounties.") return await self.bounty_config_loop() self._notify("Registering for liquidity bounties...") self.liquidity_bounty = LiquidityBounty.get_instance() try: registration_results = await self.liquidity_bounty.register() self._notify("Registration successful.") client_id = registration_results["client_id"] liquidity_bounty_config_map.get("liquidity_bounty_client_id").value = client_id await save_to_yml(LIQUIDITY_BOUNTY_CONFIG_PATH, liquidity_bounty_config_map) self.liquidity_bounty.start() self._notify("Hooray! You are now collecting bounties. ") except Exception as e: self._notify(str(e)) self.liquidity_bounty = None async def bounty_list(self, # type: HummingbotApplication ): """ List available bounties """ if self.liquidity_bounty is None: self.liquidity_bounty = LiquidityBounty.get_instance() await self.liquidity_bounty.fetch_active_bounties() self._notify(self.liquidity_bounty.formatted_bounties()) async def bounty_config_loop(self, # type: HummingbotApplication ): """ Configuration loop for bounty registration """ self.placeholder_mode = True self.app.toggle_hide_input() self._notify("Starting registration process for liquidity bounties:") try: for key, cvar in liquidity_bounty_config_map.items(): if key == "liquidity_bounty_enabled": await self.print_doc(join(dirname(__file__), "../liquidity_bounty/requirements.txt")) elif key == "agree_to_terms": await self.bounty_print_terms() elif key == "agree_to_data_collection": await self.print_doc(join(dirname(__file__), "../liquidity_bounty/data_collection_policy.txt")) elif key == "eth_address": self._notify("\nYour wallets:") self.list("wallets") value = await self.config_single_variable(cvar) cvar.value = parse_cvar_value(cvar, value) if cvar.type == "bool" and cvar.value is False: raise ValueError(f"{cvar.key} is required.") await save_to_yml(LIQUIDITY_BOUNTY_CONFIG_PATH, liquidity_bounty_config_map) except ValueError as e: self._notify(f"Registration aborted: {str(e)}") except Exception as e: self.logger().error(f"Error configuring liquidity bounty: {str(e)}") self.app.change_prompt(prompt=">>> ") self.app.toggle_hide_input() self.placeholder_mode = False async def bounty_restore_id(self, # type: HummingbotApplication ): """ Retrieve bounty client id with email when the id is lost""" if self.liquidity_bounty is None: self.liquidity_bounty: LiquidityBounty = LiquidityBounty.get_instance() self.placeholder_mode = True self.app.toggle_hide_input() self._notify("Starting registration process for liquidity bounties:") try: email: str = await self.app.prompt("What is the email address you used to register for the bounty? >>> ") msg: str = await self.liquidity_bounty.restore_id(email) self._notify(msg) verification_code: str = await self.app.prompt("Please enter the verification code you received in the " "email >>> ") client_id = await self.liquidity_bounty.send_verification_code(email, verification_code) liquidity_bounty_config_map.get("liquidity_bounty_enabled").value = True liquidity_bounty_config_map.get("liquidity_bounty_client_id").value = client_id await save_to_yml(LIQUIDITY_BOUNTY_CONFIG_PATH, liquidity_bounty_config_map) self._notify("\nYour bounty ID has been reset successfully. You may now start collecting bounties!\n") self.liquidity_bounty.start() except Exception as e: self._notify(f"Bounty reset aborted: {str(e)}") self.app.change_prompt(prompt=">>> ") self.app.toggle_hide_input() self.placeholder_mode = False
[ "hummingbot.client.liquidity_bounty.liquidity_bounty_config_map.liquidity_bounty_config_map.get", "hummingbot.client.config.config_helpers.save_to_yml", "hummingbot.client.liquidity_bounty.liquidity_bounty_config_map.liquidity_bounty_config_map.items", "hummingbot.client.config.config_helpers.parse_cvar_value...
[((3121, 3151), 'hummingbot.client.liquidity_bounty.bounty_utils.LiquidityBounty.get_instance', 'LiquidityBounty.get_instance', ([], {}), '()\n', (3149, 3151), False, 'from hummingbot.client.liquidity_bounty.bounty_utils import LiquidityBounty\n'), ((3959, 3989), 'hummingbot.client.liquidity_bounty.bounty_utils.LiquidityBounty.get_instance', 'LiquidityBounty.get_instance', ([], {}), '()\n', (3987, 3989), False, 'from hummingbot.client.liquidity_bounty.bounty_utils import LiquidityBounty\n'), ((4476, 4511), 'hummingbot.client.liquidity_bounty.liquidity_bounty_config_map.liquidity_bounty_config_map.items', 'liquidity_bounty_config_map.items', ([], {}), '()\n', (4509, 4511), False, 'from hummingbot.client.liquidity_bounty.liquidity_bounty_config_map import liquidity_bounty_config_map\n'), ((6022, 6052), 'hummingbot.client.liquidity_bounty.bounty_utils.LiquidityBounty.get_instance', 'LiquidityBounty.get_instance', ([], {}), '()\n', (6050, 6052), False, 'from hummingbot.client.liquidity_bounty.bounty_utils import LiquidityBounty\n'), ((2739, 2798), 'hummingbot.client.liquidity_bounty.liquidity_bounty_config_map.liquidity_bounty_config_map.get', 'liquidity_bounty_config_map.get', (['"""liquidity_bounty_enabled"""'], {}), "('liquidity_bounty_enabled')\n", (2770, 2798), False, 'from hummingbot.client.liquidity_bounty.liquidity_bounty_config_map import liquidity_bounty_config_map\n'), ((2823, 2884), 'hummingbot.client.liquidity_bounty.liquidity_bounty_config_map.liquidity_bounty_config_map.get', 'liquidity_bounty_config_map.get', (['"""liquidity_bounty_client_id"""'], {}), "('liquidity_bounty_client_id')\n", (2854, 2884), False, 'from hummingbot.client.liquidity_bounty.liquidity_bounty_config_map import liquidity_bounty_config_map\n'), ((3362, 3423), 'hummingbot.client.liquidity_bounty.liquidity_bounty_config_map.liquidity_bounty_config_map.get', 'liquidity_bounty_config_map.get', (['"""liquidity_bounty_client_id"""'], {}), "('liquidity_bounty_client_id')\n", (3393, 3423), False, 'from hummingbot.client.liquidity_bounty.liquidity_bounty_config_map import liquidity_bounty_config_map\n'), ((3460, 3530), 'hummingbot.client.config.config_helpers.save_to_yml', 'save_to_yml', (['LIQUIDITY_BOUNTY_CONFIG_PATH', 'liquidity_bounty_config_map'], {}), '(LIQUIDITY_BOUNTY_CONFIG_PATH, liquidity_bounty_config_map)\n', (3471, 3530), False, 'from hummingbot.client.config.config_helpers import parse_cvar_value, save_to_yml\n'), ((5173, 5202), 'hummingbot.client.config.config_helpers.parse_cvar_value', 'parse_cvar_value', (['cvar', 'value'], {}), '(cvar, value)\n', (5189, 5202), False, 'from hummingbot.client.config.config_helpers import parse_cvar_value, save_to_yml\n'), ((6742, 6801), 'hummingbot.client.liquidity_bounty.liquidity_bounty_config_map.liquidity_bounty_config_map.get', 'liquidity_bounty_config_map.get', (['"""liquidity_bounty_enabled"""'], {}), "('liquidity_bounty_enabled')\n", (6773, 6801), False, 'from hummingbot.client.liquidity_bounty.liquidity_bounty_config_map import liquidity_bounty_config_map\n'), ((6827, 6888), 'hummingbot.client.liquidity_bounty.liquidity_bounty_config_map.liquidity_bounty_config_map.get', 'liquidity_bounty_config_map.get', (['"""liquidity_bounty_client_id"""'], {}), "('liquidity_bounty_client_id')\n", (6858, 6888), False, 'from hummingbot.client.liquidity_bounty.liquidity_bounty_config_map import liquidity_bounty_config_map\n'), ((6925, 6995), 'hummingbot.client.config.config_helpers.save_to_yml', 'save_to_yml', (['LIQUIDITY_BOUNTY_CONFIG_PATH', 'liquidity_bounty_config_map'], {}), '(LIQUIDITY_BOUNTY_CONFIG_PATH, liquidity_bounty_config_map)\n', (6936, 6995), False, 'from hummingbot.client.config.config_helpers import parse_cvar_value, save_to_yml\n'), ((2503, 2520), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (2510, 2520), False, 'from os.path import join, dirname\n'), ((5354, 5424), 'hummingbot.client.config.config_helpers.save_to_yml', 'save_to_yml', (['LIQUIDITY_BOUNTY_CONFIG_PATH', 'liquidity_bounty_config_map'], {}), '(LIQUIDITY_BOUNTY_CONFIG_PATH, liquidity_bounty_config_map)\n', (5365, 5424), False, 'from hummingbot.client.config.config_helpers import parse_cvar_value, save_to_yml\n'), ((4613, 4630), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (4620, 4630), False, 'from os.path import join, dirname\n'), ((4873, 4890), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (4880, 4890), False, 'from os.path import join, dirname\n')]
#!/usr/bin/env python import asyncio from contextlib import ExitStack import logging import threading from prompt_toolkit.application import Application from prompt_toolkit.clipboard.pyperclip import PyperclipClipboard from prompt_toolkit.completion import Completer from prompt_toolkit.document import Document from prompt_toolkit.layout.processors import BeforeInput, PasswordProcessor from prompt_toolkit.key_binding import KeyBindings from typing import Callable, Optional, Dict, Any, TYPE_CHECKING from hummingbot import init_logging, check_dev_mode if TYPE_CHECKING: from hummingbot.client.hummingbot_application import HummingbotApplication from hummingbot.client.ui.layout import ( create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button, ) from hummingbot.client.config.global_config_map import global_config_map from hummingbot.client.tab.data_types import CommandTab from hummingbot.client.ui.interface_utils import start_timer, start_process_monitor, start_trade_monitor from hummingbot.client.ui.stdout_redirection import patch_stdout from hummingbot.client.ui.style import load_style from hummingbot.core.event.events import HummingbotUIEvent from hummingbot.core.pubsub import PubSub from hummingbot.core.utils.async_utils import safe_ensure_future # Monkey patching here as _handle_exception gets the UI hanged into Press ENTER screen mode def _handle_exception_patch(self, loop, context): if "exception" in context: logging.getLogger(__name__).error(f"Unhandled error in prompt_toolkit: {context.get('exception')}", exc_info=True) Application._handle_exception = _handle_exception_patch class HummingbotCLI(PubSub): def __init__(self, input_handler: Callable, bindings: KeyBindings, completer: Completer, command_tabs: Dict[str, CommandTab]): super().__init__() self.command_tabs = command_tabs self.search_field = create_search_field() self.input_field = create_input_field(completer=completer) self.output_field = create_output_field() self.log_field = create_log_field(self.search_field) self.right_pane_toggle = create_log_toggle(self.toggle_right_pane) self.live_field = create_live_field() self.log_field_button = create_tab_button("Log-pane", self.log_button_clicked) self.timer = create_timer() self.process_usage = create_process_monitor() self.trade_monitor = create_trade_monitor() self.layout, self.layout_components = generate_layout(self.input_field, self.output_field, self.log_field, self.right_pane_toggle, self.log_field_button, self.search_field, self.timer, self.process_usage, self.trade_monitor, self.command_tabs) # add self.to_stop_config to know if cancel is triggered self.to_stop_config: bool = False self.live_updates = False self.bindings = bindings self.input_handler = input_handler self.input_field.accept_handler = self.accept self.app: Optional[Application] = None # settings self.prompt_text = ">>> " self.pending_input = None self.input_event = None self.hide_input = False # stdout redirection stack self._stdout_redirect_context: ExitStack = ExitStack() # start ui tasks loop = asyncio.get_event_loop() loop.create_task(start_timer(self.timer)) loop.create_task(start_process_monitor(self.process_usage)) loop.create_task(start_trade_monitor(self.trade_monitor)) def did_start_ui(self): self._stdout_redirect_context.enter_context(patch_stdout(log_field=self.log_field)) log_level = global_config_map.get("log_level").value dev_mode = check_dev_mode() init_logging("hummingbot_logs.yml", override_log_level=log_level, dev_mode=dev_mode) self.trigger_event(HummingbotUIEvent.Start, self) async def run(self): self.app = Application(layout=self.layout, full_screen=True, key_bindings=self.bindings, style=load_style(), mouse_support=True, clipboard=PyperclipClipboard()) await self.app.run_async(pre_run=self.did_start_ui) self._stdout_redirect_context.close() def accept(self, buff): self.pending_input = self.input_field.text.strip() if self.input_event: self.input_event.set() try: if self.hide_input: output = '' else: output = '\n>>> {}'.format(self.input_field.text,) self.input_field.buffer.append_to_history() except BaseException as e: output = str(e) self.log(output) self.input_handler(self.input_field.text) def clear_input(self): self.pending_input = None def log(self, text: str, save_log: bool = True): if save_log: if self.live_updates: self.output_field.log(text, silent=True) else: self.output_field.log(text) else: self.output_field.log(text, save_log=False) def change_prompt(self, prompt: str, is_password: bool = False): self.prompt_text = prompt processors = [] if is_password: processors.append(PasswordProcessor()) processors.append(BeforeInput(prompt)) self.input_field.control.input_processors = processors async def prompt(self, prompt: str, is_password: bool = False) -> str: self.change_prompt(prompt, is_password) self.app.invalidate() self.input_event = asyncio.Event() await self.input_event.wait() temp = self.pending_input self.clear_input() self.input_event = None if is_password: masked_string = "*" * len(temp) self.log(f"{prompt}{masked_string}") else: self.log(f"{prompt}{temp}") return temp def set_text(self, new_text: str): self.input_field.document = Document(text=new_text, cursor_position=len(new_text)) def toggle_hide_input(self): self.hide_input = not self.hide_input def toggle_right_pane(self): if self.layout_components["pane_right"].filter(): self.layout_components["pane_right"].filter = lambda: False self.layout_components["item_top_toggle"].text = '< log pane' else: self.layout_components["pane_right"].filter = lambda: True self.layout_components["item_top_toggle"].text = '> log pane' def log_button_clicked(self): for tab in self.command_tabs.values(): tab.is_selected = False self.redraw_app() def tab_button_clicked(self, command_name: str): for tab in self.command_tabs.values(): tab.is_selected = False self.command_tabs[command_name].is_selected = True self.redraw_app() def exit(self): self.app.exit() def redraw_app(self): self.layout, self.layout_components = generate_layout(self.input_field, self.output_field, self.log_field, self.right_pane_toggle, self.log_field_button, self.search_field, self.timer, self.process_usage, self.trade_monitor, self.command_tabs) self.app.layout = self.layout self.app.invalidate() def tab_navigate_left(self): selected_tabs = [t for t in self.command_tabs.values() if t.is_selected] if not selected_tabs: return selected_tab: CommandTab = selected_tabs[0] if selected_tab.tab_index == 1: self.log_button_clicked() else: left_tab = [t for t in self.command_tabs.values() if t.tab_index == selected_tab.tab_index - 1][0] self.tab_button_clicked(left_tab.name) def tab_navigate_right(self): current_tabs = [t for t in self.command_tabs.values() if t.tab_index > 0] if not current_tabs: return selected_tab = [t for t in current_tabs if t.is_selected] if selected_tab: right_tab = [t for t in current_tabs if t.tab_index == selected_tab[0].tab_index + 1] else: right_tab = [t for t in current_tabs if t.tab_index == 1] if right_tab: self.tab_button_clicked(right_tab[0].name) def close_buton_clicked(self, command_name: str): self.command_tabs[command_name].button = None self.command_tabs[command_name].close_button = None self.command_tabs[command_name].output_field = None self.command_tabs[command_name].is_selected = False for tab in self.command_tabs.values(): if tab.tab_index > self.command_tabs[command_name].tab_index: tab.tab_index -= 1 self.command_tabs[command_name].tab_index = 0 if self.command_tabs[command_name].task is not None: self.command_tabs[command_name].task.cancel() self.command_tabs[command_name].task = None self.redraw_app() def handle_tab_command(self, hummingbot: "HummingbotApplication", command_name: str, kwargs: Dict[str, Any]): if command_name not in self.command_tabs: return cmd_tab = self.command_tabs[command_name] if "close" in kwargs and kwargs["close"]: if cmd_tab.close_button is not None: self.close_buton_clicked(command_name) return if "close" in kwargs: kwargs.pop("close") if cmd_tab.button is None: cmd_tab.button = create_tab_button(command_name, lambda: self.tab_button_clicked(command_name)) cmd_tab.close_button = create_tab_button("x", lambda: self.close_buton_clicked(command_name), 1, '', ' ') cmd_tab.output_field = create_live_field() cmd_tab.tab_index = max(t.tab_index for t in self.command_tabs.values()) + 1 self.tab_button_clicked(command_name) self.display_tab_output(cmd_tab, hummingbot, kwargs) def display_tab_output(self, command_tab: CommandTab, hummingbot: "HummingbotApplication", kwargs: Dict[Any, Any]): if command_tab.task is not None and not command_tab.task.done(): return if threading.current_thread() != threading.main_thread(): hummingbot.ev_loop.call_soon_threadsafe(self.display_tab_output, command_tab, hummingbot, kwargs) return command_tab.task = safe_ensure_future(command_tab.tab_class.display(command_tab.output_field, hummingbot, **kwargs))
[ "hummingbot.check_dev_mode", "hummingbot.client.ui.layout.create_log_field", "hummingbot.client.ui.layout.generate_layout", "hummingbot.client.ui.interface_utils.start_timer", "hummingbot.client.ui.style.load_style", "hummingbot.init_logging", "hummingbot.client.ui.interface_utils.start_trade_monitor", ...
[((2195, 2216), 'hummingbot.client.ui.layout.create_search_field', 'create_search_field', ([], {}), '()\n', (2214, 2216), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2244, 2283), 'hummingbot.client.ui.layout.create_input_field', 'create_input_field', ([], {'completer': 'completer'}), '(completer=completer)\n', (2262, 2283), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2312, 2333), 'hummingbot.client.ui.layout.create_output_field', 'create_output_field', ([], {}), '()\n', (2331, 2333), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2359, 2394), 'hummingbot.client.ui.layout.create_log_field', 'create_log_field', (['self.search_field'], {}), '(self.search_field)\n', (2375, 2394), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2428, 2469), 'hummingbot.client.ui.layout.create_log_toggle', 'create_log_toggle', (['self.toggle_right_pane'], {}), '(self.toggle_right_pane)\n', (2445, 2469), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2496, 2515), 'hummingbot.client.ui.layout.create_live_field', 'create_live_field', ([], {}), '()\n', (2513, 2515), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2548, 2602), 'hummingbot.client.ui.layout.create_tab_button', 'create_tab_button', (['"""Log-pane"""', 'self.log_button_clicked'], {}), "('Log-pane', self.log_button_clicked)\n", (2565, 2602), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2624, 2638), 'hummingbot.client.ui.layout.create_timer', 'create_timer', ([], {}), '()\n', (2636, 2638), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2668, 2692), 'hummingbot.client.ui.layout.create_process_monitor', 'create_process_monitor', ([], {}), '()\n', (2690, 2692), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2722, 2744), 'hummingbot.client.ui.layout.create_trade_monitor', 'create_trade_monitor', ([], {}), '()\n', (2742, 2744), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((2791, 3005), 'hummingbot.client.ui.layout.generate_layout', 'generate_layout', (['self.input_field', 'self.output_field', 'self.log_field', 'self.right_pane_toggle', 'self.log_field_button', 'self.search_field', 'self.timer', 'self.process_usage', 'self.trade_monitor', 'self.command_tabs'], {}), '(self.input_field, self.output_field, self.log_field, self.\n right_pane_toggle, self.log_field_button, self.search_field, self.timer,\n self.process_usage, self.trade_monitor, self.command_tabs)\n', (2806, 3005), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((3803, 3814), 'contextlib.ExitStack', 'ExitStack', ([], {}), '()\n', (3812, 3814), False, 'from contextlib import ExitStack\n'), ((3856, 3880), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (3878, 3880), False, 'import asyncio\n'), ((4267, 4283), 'hummingbot.check_dev_mode', 'check_dev_mode', ([], {}), '()\n', (4281, 4283), False, 'from hummingbot import init_logging, check_dev_mode\n'), ((4292, 4381), 'hummingbot.init_logging', 'init_logging', (['"""hummingbot_logs.yml"""'], {'override_log_level': 'log_level', 'dev_mode': 'dev_mode'}), "('hummingbot_logs.yml', override_log_level=log_level, dev_mode=\n dev_mode)\n", (4304, 4381), False, 'from hummingbot import init_logging, check_dev_mode\n'), ((6176, 6191), 'asyncio.Event', 'asyncio.Event', ([], {}), '()\n', (6189, 6191), False, 'import asyncio\n'), ((7608, 7822), 'hummingbot.client.ui.layout.generate_layout', 'generate_layout', (['self.input_field', 'self.output_field', 'self.log_field', 'self.right_pane_toggle', 'self.log_field_button', 'self.search_field', 'self.timer', 'self.process_usage', 'self.trade_monitor', 'self.command_tabs'], {}), '(self.input_field, self.output_field, self.log_field, self.\n right_pane_toggle, self.log_field_button, self.search_field, self.timer,\n self.process_usage, self.trade_monitor, self.command_tabs)\n', (7623, 7822), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((3906, 3929), 'hummingbot.client.ui.interface_utils.start_timer', 'start_timer', (['self.timer'], {}), '(self.timer)\n', (3917, 3929), False, 'from hummingbot.client.ui.interface_utils import start_timer, start_process_monitor, start_trade_monitor\n'), ((3956, 3997), 'hummingbot.client.ui.interface_utils.start_process_monitor', 'start_process_monitor', (['self.process_usage'], {}), '(self.process_usage)\n', (3977, 3997), False, 'from hummingbot.client.ui.interface_utils import start_timer, start_process_monitor, start_trade_monitor\n'), ((4024, 4063), 'hummingbot.client.ui.interface_utils.start_trade_monitor', 'start_trade_monitor', (['self.trade_monitor'], {}), '(self.trade_monitor)\n', (4043, 4063), False, 'from hummingbot.client.ui.interface_utils import start_timer, start_process_monitor, start_trade_monitor\n'), ((4146, 4184), 'hummingbot.client.ui.stdout_redirection.patch_stdout', 'patch_stdout', ([], {'log_field': 'self.log_field'}), '(log_field=self.log_field)\n', (4158, 4184), False, 'from hummingbot.client.ui.stdout_redirection import patch_stdout\n'), ((4207, 4241), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""log_level"""'], {}), "('log_level')\n", (4228, 4241), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((5911, 5930), 'prompt_toolkit.layout.processors.BeforeInput', 'BeforeInput', (['prompt'], {}), '(prompt)\n', (5922, 5930), False, 'from prompt_toolkit.layout.processors import BeforeInput, PasswordProcessor\n'), ((10518, 10537), 'hummingbot.client.ui.layout.create_live_field', 'create_live_field', ([], {}), '()\n', (10535, 10537), False, 'from hummingbot.client.ui.layout import create_input_field, create_log_field, create_log_toggle, create_output_field, create_search_field, generate_layout, create_timer, create_process_monitor, create_trade_monitor, create_live_field, create_tab_button\n'), ((11039, 11065), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (11063, 11065), False, 'import threading\n'), ((11069, 11092), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (11090, 11092), False, 'import threading\n'), ((1654, 1681), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1671, 1681), False, 'import logging\n'), ((4607, 4619), 'hummingbot.client.ui.style.load_style', 'load_style', ([], {}), '()\n', (4617, 4619), False, 'from hummingbot.client.ui.style import load_style\n'), ((4682, 4702), 'prompt_toolkit.clipboard.pyperclip.PyperclipClipboard', 'PyperclipClipboard', ([], {}), '()\n', (4700, 4702), False, 'from prompt_toolkit.clipboard.pyperclip import PyperclipClipboard\n'), ((5864, 5883), 'prompt_toolkit.layout.processors.PasswordProcessor', 'PasswordProcessor', ([], {}), '()\n', (5881, 5883), False, 'from prompt_toolkit.layout.processors import BeforeInput, PasswordProcessor\n')]
from typing import List, Tuple import hummingbot from hummingbot.core.utils.symbol_fetcher import SymbolFetcher from hummingbot.strategy.discovery.discovery_config_map import discovery_config_map from hummingbot.strategy.discovery.discovery import DiscoveryMarketPair, DiscoveryStrategy def start(self: "hummingbot.client.hummingbot_application.HummingbotApplication"): try: market_1 = discovery_config_map.get("primary_market").value.lower() market_2 = discovery_config_map.get("secondary_market").value.lower() target_symbol_1 = list(discovery_config_map.get("target_symbol_1").value) target_symbol_2 = list(discovery_config_map.get("target_symbol_2").value) target_profitability = float(discovery_config_map.get("target_profitability").value) target_amount = float(discovery_config_map.get("target_amount").value) equivalent_token: List[List[str]] = list(discovery_config_map.get("equivalent_tokens").value) if not target_symbol_2: target_symbol_2 = SymbolFetcher.get_instance().symbols.get(market_2, []) if not target_symbol_1: target_symbol_1 = SymbolFetcher.get_instance().symbols.get(market_1, []) market_names: List[Tuple[str, List[str]]] = [(market_1, target_symbol_1), (market_2, target_symbol_2)] target_base_quote_1: List[Tuple[str, str]] = self._initialize_market_assets(market_1, target_symbol_1) target_base_quote_2: List[Tuple[str, str]] = self._initialize_market_assets(market_2, target_symbol_2) self._trading_required = False self._initialize_wallet(token_symbols=[]) # wallet required only for dex hard dependency self._initialize_markets(market_names) self.market_pair = DiscoveryMarketPair( *( [self.markets[market_1], self.markets[market_1].get_active_exchange_markets] + [self.markets[market_2], self.markets[market_2].get_active_exchange_markets] ) ) self.strategy = DiscoveryStrategy( market_pairs=[self.market_pair], target_symbols=target_base_quote_1 + target_base_quote_2, equivalent_token=equivalent_token, target_profitability=target_profitability, target_amount=target_amount, ) except Exception as e: self._notify(str(e)) self.logger().error("Error initializing strategy.", exc_info=True)
[ "hummingbot.strategy.discovery.discovery.DiscoveryStrategy", "hummingbot.core.utils.symbol_fetcher.SymbolFetcher.get_instance", "hummingbot.strategy.discovery.discovery.DiscoveryMarketPair", "hummingbot.strategy.discovery.discovery_config_map.discovery_config_map.get" ]
[((1756, 1945), 'hummingbot.strategy.discovery.discovery.DiscoveryMarketPair', 'DiscoveryMarketPair', (['*([self.markets[market_1], self.markets[market_1].\n get_active_exchange_markets] + [self.markets[market_2], self.markets[\n market_2].get_active_exchange_markets])'], {}), '(*([self.markets[market_1], self.markets[market_1].\n get_active_exchange_markets] + [self.markets[market_2], self.markets[\n market_2].get_active_exchange_markets]))\n', (1775, 1945), False, 'from hummingbot.strategy.discovery.discovery import DiscoveryMarketPair, DiscoveryStrategy\n'), ((2028, 2257), 'hummingbot.strategy.discovery.discovery.DiscoveryStrategy', 'DiscoveryStrategy', ([], {'market_pairs': '[self.market_pair]', 'target_symbols': '(target_base_quote_1 + target_base_quote_2)', 'equivalent_token': 'equivalent_token', 'target_profitability': 'target_profitability', 'target_amount': 'target_amount'}), '(market_pairs=[self.market_pair], target_symbols=\n target_base_quote_1 + target_base_quote_2, equivalent_token=\n equivalent_token, target_profitability=target_profitability,\n target_amount=target_amount)\n', (2045, 2257), False, 'from hummingbot.strategy.discovery.discovery import DiscoveryMarketPair, DiscoveryStrategy\n'), ((567, 610), 'hummingbot.strategy.discovery.discovery_config_map.discovery_config_map.get', 'discovery_config_map.get', (['"""target_symbol_1"""'], {}), "('target_symbol_1')\n", (591, 610), False, 'from hummingbot.strategy.discovery.discovery_config_map import discovery_config_map\n'), ((649, 692), 'hummingbot.strategy.discovery.discovery_config_map.discovery_config_map.get', 'discovery_config_map.get', (['"""target_symbol_2"""'], {}), "('target_symbol_2')\n", (673, 692), False, 'from hummingbot.strategy.discovery.discovery_config_map import discovery_config_map\n'), ((737, 785), 'hummingbot.strategy.discovery.discovery_config_map.discovery_config_map.get', 'discovery_config_map.get', (['"""target_profitability"""'], {}), "('target_profitability')\n", (761, 785), False, 'from hummingbot.strategy.discovery.discovery_config_map import discovery_config_map\n'), ((823, 864), 'hummingbot.strategy.discovery.discovery_config_map.discovery_config_map.get', 'discovery_config_map.get', (['"""target_amount"""'], {}), "('target_amount')\n", (847, 864), False, 'from hummingbot.strategy.discovery.discovery_config_map import discovery_config_map\n'), ((921, 966), 'hummingbot.strategy.discovery.discovery_config_map.discovery_config_map.get', 'discovery_config_map.get', (['"""equivalent_tokens"""'], {}), "('equivalent_tokens')\n", (945, 966), False, 'from hummingbot.strategy.discovery.discovery_config_map import discovery_config_map\n'), ((401, 443), 'hummingbot.strategy.discovery.discovery_config_map.discovery_config_map.get', 'discovery_config_map.get', (['"""primary_market"""'], {}), "('primary_market')\n", (425, 443), False, 'from hummingbot.strategy.discovery.discovery_config_map import discovery_config_map\n'), ((477, 521), 'hummingbot.strategy.discovery.discovery_config_map.discovery_config_map.get', 'discovery_config_map.get', (['"""secondary_market"""'], {}), "('secondary_market')\n", (501, 521), False, 'from hummingbot.strategy.discovery.discovery_config_map import discovery_config_map\n'), ((1037, 1065), 'hummingbot.core.utils.symbol_fetcher.SymbolFetcher.get_instance', 'SymbolFetcher.get_instance', ([], {}), '()\n', (1063, 1065), False, 'from hummingbot.core.utils.symbol_fetcher import SymbolFetcher\n'), ((1154, 1182), 'hummingbot.core.utils.symbol_fetcher.SymbolFetcher.get_instance', 'SymbolFetcher.get_instance', ([], {}), '()\n', (1180, 1182), False, 'from hummingbot.core.utils.symbol_fetcher import SymbolFetcher\n')]
#!/usr/bin/env python import asyncio import logging from typing import Any, Dict, List, Optional import ujson import hummingbot.connector.exchange.alpaca.alpaca_constants as CONSTANTS from hummingbot.connector.exchange.alpaca.alpaca_order_book import AlpacaOrderBook from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, \ convert_to_exchange_trading_pair, \ convert_snapshot_message_to_order_book_row, \ build_api_factory, \ decompress_ws_message from hummingbot.core.api_throttler.async_throttler import AsyncThrottler from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.data_type.order_book_message import OrderBookMessage from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource from hummingbot.core.web_assistant.connections.data_types import RESTMethod, RESTRequest, WSRequest from hummingbot.core.web_assistant.rest_assistant import RESTAssistant from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory from hummingbot.core.web_assistant.ws_assistant import WSAssistant from hummingbot.logger import HummingbotLogger class AlpacaAPIOrderBookDataSource(OrderBookTrackerDataSource): MESSAGE_TIMEOUT = 10.0 SNAPSHOT_TIMEOUT = 60 * 60 # expressed in seconds PING_TIMEOUT = 2.0 _logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._logger is None: cls._logger = logging.getLogger(__name__) return cls._logger def __init__(self, throttler: Optional[AsyncThrottler] = None, trading_pairs: List[str] = None, api_factory: Optional[WebAssistantsFactory] = None): super().__init__(trading_pairs) self._throttler = throttler or self._get_throttler_instance() self._api_factory = api_factory or build_api_factory() self._rest_assistant = None self._snapshot_msg: Dict[str, any] = {} @classmethod def _get_throttler_instance(cls) -> AsyncThrottler: throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS) return throttler async def _get_rest_assistant(self) -> RESTAssistant: if self._rest_assistant is None: self._rest_assistant = await self._api_factory.get_rest_assistant() return self._rest_assistant @classmethod async def get_last_traded_prices(cls, trading_pairs: List[str]) -> Dict[str, float]: throttler = cls._get_throttler_instance() async with throttler.execute_task(CONSTANTS.GET_LAST_TRADING_PRICES_PATH_URL): result = {} request = RESTRequest( method=RESTMethod.GET, url=f"{CONSTANTS.REST_URL}/{CONSTANTS.GET_LAST_TRADING_PRICES_PATH_URL}", ) rest_assistant = await build_api_factory().get_rest_assistant() response = await rest_assistant.call(request=request, timeout=10) response_json = await response.json() for ticker in response_json["data"]["tickers"]: t_pair = convert_from_exchange_trading_pair(ticker["symbol"]) if t_pair in trading_pairs and ticker["last_price"]: result[t_pair] = float(ticker["last_price"]) return result @staticmethod async def fetch_trading_pairs() -> List[str]: throttler = AlpacaAPIOrderBookDataSource._get_throttler_instance() async with throttler.execute_task(CONSTANTS.GET_TRADING_PAIRS_PATH_URL): request = RESTRequest( method=RESTMethod.GET, url=f"{CONSTANTS.REST_URL}/{CONSTANTS.GET_TRADING_PAIRS_PATH_URL}", ) rest_assistant = await build_api_factory().get_rest_assistant() response = await rest_assistant.call(request=request, timeout=10) if response.status == 200: try: response_json: Dict[str, Any] = await response.json() return [convert_from_exchange_trading_pair(symbol) for symbol in response_json["data"]["symbols"]] except Exception: pass # Do nothing if the request fails -- there will be no autocomplete for alpaca trading pairs return [] @staticmethod async def get_order_book_data(trading_pair: str) -> Dict[str, any]: """ Get whole orderbook """ throttler = AlpacaAPIOrderBookDataSource._get_throttler_instance() async with throttler.execute_task(CONSTANTS.GET_ORDER_BOOK_PATH_URL): request = RESTRequest( method=RESTMethod.GET, url=f"{CONSTANTS.REST_URL}/{CONSTANTS.GET_ORDER_BOOK_PATH_URL}?size=200&symbol=" f"{convert_to_exchange_trading_pair(trading_pair)}", ) rest_assistant = await build_api_factory().get_rest_assistant() response = await rest_assistant.call(request=request, timeout=10) if response.status != 200: raise IOError( f"Error fetching OrderBook for {trading_pair} at {CONSTANTS.EXCHANGE_NAME}. " f"HTTP status is {response.status}." ) orderbook_data: Dict[str, Any] = await response.json() orderbook_data = orderbook_data["data"] return orderbook_data async def get_new_order_book(self, trading_pair: str) -> OrderBook: snapshot: Dict[str, Any] = await self.get_order_book_data(trading_pair) snapshot_timestamp: float = float(snapshot["timestamp"]) snapshot_msg: OrderBookMessage = AlpacaOrderBook.snapshot_message_from_exchange( snapshot, snapshot_timestamp, metadata={"trading_pair": trading_pair} ) order_book = self.order_book_create_function() bids, asks = convert_snapshot_message_to_order_book_row(snapshot_msg) order_book.apply_snapshot(bids, asks, snapshot_msg.update_id) return order_book async def _sleep(self, delay): """ Function added only to facilitate patching the sleep in unit tests without affecting the asyncio module """ await asyncio.sleep(delay) async def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Listen for trades using websocket trade channel """ while True: try: ws: WSAssistant = await self._api_factory.get_ws_assistant() try: await ws.connect(ws_url=CONSTANTS.WSS_URL, message_timeout=self.MESSAGE_TIMEOUT, ping_timeout=self.PING_TIMEOUT) except RuntimeError: self.logger().info("Alpaca WebSocket already connected.") for trading_pair in self._trading_pairs: ws_message: WSRequest = WSRequest({ "op": "subscribe", "args": [f"spot/trade:{convert_to_exchange_trading_pair(trading_pair)}"] }) await ws.send(ws_message) while True: try: async for raw_msg in ws.iter_messages(): messages = decompress_ws_message(raw_msg.data) if messages is None: continue messages = ujson.loads(messages) if "errorCode" in messages.keys() or \ "data" not in messages.keys() or \ "table" not in messages.keys(): continue if messages["table"] != "spot/trade": # Not a trade message continue for msg in messages["data"]: # data is a list msg_timestamp: float = float(msg["s_t"] * 1000) t_pair = convert_from_exchange_trading_pair(msg["symbol"]) trade_msg: OrderBookMessage = AlpacaOrderBook.trade_message_from_exchange( msg=msg, timestamp=msg_timestamp, metadata={"trading_pair": t_pair}) output.put_nowait(trade_msg) break except asyncio.exceptions.TimeoutError: # Check whether connection is really dead await ws.ping() except asyncio.CancelledError: raise except asyncio.exceptions.TimeoutError: self.logger().warning("WebSocket ping timed out. Going to reconnect...") await ws.disconnect() await asyncio.sleep(30.0) except Exception: self.logger().error("Unexpected error.", exc_info=True) await ws.disconnect() await self._sleep(5.0) finally: await ws.disconnect() async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Listen for orderbook diffs using websocket book channel(all messages are snapshots) """ while True: try: ws: WSAssistant = await self._api_factory.get_ws_assistant() await ws.connect(ws_url=CONSTANTS.WSS_URL, message_timeout=self.MESSAGE_TIMEOUT, ping_timeout=self.PING_TIMEOUT) for trading_pair in self._trading_pairs: ws_message: WSRequest = WSRequest({ "op": "subscribe", "args": [f"spot/depth400:{convert_to_exchange_trading_pair(trading_pair)}"] }) await ws.send(ws_message) while True: try: async for raw_msg in ws.iter_messages(): messages = decompress_ws_message(raw_msg.data) if messages is None: continue messages = ujson.loads(messages) if "errorCode" in messages.keys() or \ "data" not in messages.keys() or \ "table" not in messages.keys(): continue if messages["table"] != "spot/depth5": # Not an order book message continue for msg in messages["data"]: # data is a list msg_timestamp: float = float(msg["ms_t"]) t_pair = convert_from_exchange_trading_pair(msg["symbol"]) snapshot_msg: OrderBookMessage = AlpacaOrderBook.snapshot_message_from_exchange( msg=msg, timestamp=msg_timestamp, metadata={"trading_pair": t_pair} ) output.put_nowait(snapshot_msg) break except asyncio.exceptions.TimeoutError: # Check whether connection is really dead await ws.ping() except asyncio.CancelledError: raise except asyncio.exceptions.TimeoutError: self.logger().warning("WebSocket ping timed out. Going to reconnect...") await ws.disconnect() await asyncio.sleep(30.0) except Exception: self.logger().network( "Unexpected error with WebSocket connection.", exc_info=True, app_warning_msg="Unexpected error with WebSocket connection. Retrying in 30 seconds. " "Check network connection." ) await ws.disconnect() await self._sleep(30.0) finally: await ws.disconnect() async def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Listen for orderbook snapshots by fetching orderbook """ while True: await self._sleep(self.SNAPSHOT_TIMEOUT) try: for trading_pair in self._trading_pairs: snapshot: Dict[str, any] = await self.get_order_book_data(trading_pair) snapshot_timestamp: float = float(snapshot["timestamp"]) snapshot_msg: OrderBookMessage = AlpacaOrderBook.snapshot_message_from_exchange( snapshot, snapshot_timestamp, metadata={"trading_pair": trading_pair} ) output.put_nowait(snapshot_msg) self.logger().debug(f"Saved order book snapshot for {trading_pair}") except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error occured listening for orderbook snapshots. Retrying in 5 secs...", exc_info=True) await self._sleep(5.0)
[ "hummingbot.core.web_assistant.connections.data_types.RESTRequest", "hummingbot.connector.exchange.alpaca.alpaca_utils.convert_snapshot_message_to_order_book_row", "hummingbot.connector.exchange.alpaca.alpaca_utils.convert_from_exchange_trading_pair", "hummingbot.connector.exchange.alpaca.alpaca_utils.convert...
[((2130, 2167), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['CONSTANTS.RATE_LIMITS'], {}), '(CONSTANTS.RATE_LIMITS)\n', (2144, 2167), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((5725, 5846), 'hummingbot.connector.exchange.alpaca.alpaca_order_book.AlpacaOrderBook.snapshot_message_from_exchange', 'AlpacaOrderBook.snapshot_message_from_exchange', (['snapshot', 'snapshot_timestamp'], {'metadata': "{'trading_pair': trading_pair}"}), "(snapshot, snapshot_timestamp,\n metadata={'trading_pair': trading_pair})\n", (5771, 5846), False, 'from hummingbot.connector.exchange.alpaca.alpaca_order_book import AlpacaOrderBook\n'), ((5965, 6021), 'hummingbot.connector.exchange.alpaca.alpaca_utils.convert_snapshot_message_to_order_book_row', 'convert_snapshot_message_to_order_book_row', (['snapshot_msg'], {}), '(snapshot_msg)\n', (6007, 6021), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((1519, 1546), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1536, 1546), False, 'import logging\n'), ((1932, 1951), 'hummingbot.connector.exchange.alpaca.alpaca_utils.build_api_factory', 'build_api_factory', ([], {}), '()\n', (1949, 1951), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((2700, 2813), 'hummingbot.core.web_assistant.connections.data_types.RESTRequest', 'RESTRequest', ([], {'method': 'RESTMethod.GET', 'url': 'f"""{CONSTANTS.REST_URL}/{CONSTANTS.GET_LAST_TRADING_PRICES_PATH_URL}"""'}), "(method=RESTMethod.GET, url=\n f'{CONSTANTS.REST_URL}/{CONSTANTS.GET_LAST_TRADING_PRICES_PATH_URL}')\n", (2711, 2813), False, 'from hummingbot.core.web_assistant.connections.data_types import RESTMethod, RESTRequest, WSRequest\n'), ((3607, 3714), 'hummingbot.core.web_assistant.connections.data_types.RESTRequest', 'RESTRequest', ([], {'method': 'RESTMethod.GET', 'url': 'f"""{CONSTANTS.REST_URL}/{CONSTANTS.GET_TRADING_PAIRS_PATH_URL}"""'}), "(method=RESTMethod.GET, url=\n f'{CONSTANTS.REST_URL}/{CONSTANTS.GET_TRADING_PAIRS_PATH_URL}')\n", (3618, 3714), False, 'from hummingbot.core.web_assistant.connections.data_types import RESTMethod, RESTRequest, WSRequest\n'), ((6304, 6324), 'asyncio.sleep', 'asyncio.sleep', (['delay'], {}), '(delay)\n', (6317, 6324), False, 'import asyncio\n'), ((3146, 3198), 'hummingbot.connector.exchange.alpaca.alpaca_utils.convert_from_exchange_trading_pair', 'convert_from_exchange_trading_pair', (["ticker['symbol']"], {}), "(ticker['symbol'])\n", (3180, 3198), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((13135, 13256), 'hummingbot.connector.exchange.alpaca.alpaca_order_book.AlpacaOrderBook.snapshot_message_from_exchange', 'AlpacaOrderBook.snapshot_message_from_exchange', (['snapshot', 'snapshot_timestamp'], {'metadata': "{'trading_pair': trading_pair}"}), "(snapshot, snapshot_timestamp,\n metadata={'trading_pair': trading_pair})\n", (13181, 13256), False, 'from hummingbot.connector.exchange.alpaca.alpaca_order_book import AlpacaOrderBook\n'), ((2891, 2910), 'hummingbot.connector.exchange.alpaca.alpaca_utils.build_api_factory', 'build_api_factory', ([], {}), '()\n', (2908, 2910), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((3792, 3811), 'hummingbot.connector.exchange.alpaca.alpaca_utils.build_api_factory', 'build_api_factory', ([], {}), '()\n', (3809, 3811), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((4074, 4116), 'hummingbot.connector.exchange.alpaca.alpaca_utils.convert_from_exchange_trading_pair', 'convert_from_exchange_trading_pair', (['symbol'], {}), '(symbol)\n', (4108, 4116), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((4948, 4967), 'hummingbot.connector.exchange.alpaca.alpaca_utils.build_api_factory', 'build_api_factory', ([], {}), '()\n', (4965, 4967), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((9091, 9110), 'asyncio.sleep', 'asyncio.sleep', (['(30.0)'], {}), '(30.0)\n', (9104, 9110), False, 'import asyncio\n'), ((12055, 12074), 'asyncio.sleep', 'asyncio.sleep', (['(30.0)'], {}), '(30.0)\n', (12068, 12074), False, 'import asyncio\n'), ((4849, 4895), 'hummingbot.connector.exchange.alpaca.alpaca_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (4881, 4895), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((7437, 7472), 'hummingbot.connector.exchange.alpaca.alpaca_utils.decompress_ws_message', 'decompress_ws_message', (['raw_msg.data'], {}), '(raw_msg.data)\n', (7458, 7472), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((7603, 7624), 'ujson.loads', 'ujson.loads', (['messages'], {}), '(messages)\n', (7614, 7624), False, 'import ujson\n'), ((10363, 10398), 'hummingbot.connector.exchange.alpaca.alpaca_utils.decompress_ws_message', 'decompress_ws_message', (['raw_msg.data'], {}), '(raw_msg.data)\n', (10384, 10398), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((10529, 10550), 'ujson.loads', 'ujson.loads', (['messages'], {}), '(messages)\n', (10540, 10550), False, 'import ujson\n'), ((8228, 8277), 'hummingbot.connector.exchange.alpaca.alpaca_utils.convert_from_exchange_trading_pair', 'convert_from_exchange_trading_pair', (["msg['symbol']"], {}), "(msg['symbol'])\n", (8262, 8277), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((8341, 8458), 'hummingbot.connector.exchange.alpaca.alpaca_order_book.AlpacaOrderBook.trade_message_from_exchange', 'AlpacaOrderBook.trade_message_from_exchange', ([], {'msg': 'msg', 'timestamp': 'msg_timestamp', 'metadata': "{'trading_pair': t_pair}"}), "(msg=msg, timestamp=\n msg_timestamp, metadata={'trading_pair': t_pair})\n", (8384, 8458), False, 'from hummingbot.connector.exchange.alpaca.alpaca_order_book import AlpacaOrderBook\n'), ((11155, 11204), 'hummingbot.connector.exchange.alpaca.alpaca_utils.convert_from_exchange_trading_pair', 'convert_from_exchange_trading_pair', (["msg['symbol']"], {}), "(msg['symbol'])\n", (11189, 11204), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((11271, 11391), 'hummingbot.connector.exchange.alpaca.alpaca_order_book.AlpacaOrderBook.snapshot_message_from_exchange', 'AlpacaOrderBook.snapshot_message_from_exchange', ([], {'msg': 'msg', 'timestamp': 'msg_timestamp', 'metadata': "{'trading_pair': t_pair}"}), "(msg=msg, timestamp=\n msg_timestamp, metadata={'trading_pair': t_pair})\n", (11317, 11391), False, 'from hummingbot.connector.exchange.alpaca.alpaca_order_book import AlpacaOrderBook\n'), ((7161, 7207), 'hummingbot.connector.exchange.alpaca.alpaca_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (7193, 7207), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n'), ((10086, 10132), 'hummingbot.connector.exchange.alpaca.alpaca_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (10118, 10132), False, 'from hummingbot.connector.exchange.alpaca.alpaca_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair, convert_snapshot_message_to_order_book_row, build_api_factory, decompress_ws_message\n')]
from decimal import Decimal import logging import asyncio import pandas as pd from typing import List, Dict, Tuple from enum import Enum from hummingbot.core.utils.async_utils import safe_ensure_future from hummingbot.core.clock import Clock from hummingbot.core.data_type.limit_order import LimitOrder from hummingbot.core.data_type.market_order import MarketOrder from hummingbot.logger import HummingbotLogger from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from hummingbot.strategy.strategy_py_base import StrategyPyBase from hummingbot.connector.connector_base import ConnectorBase from hummingbot.core.utils.async_utils import safe_gather from hummingbot.core.event.events import OrderType from hummingbot.core.event.events import TradeType,PriceType import time from hummingbot.core.event.events import ( PositionAction, PositionMode, BuyOrderCreatedEvent, SellOrderCreatedEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent, OrderCancelledEvent, ) from hummingbot.connector.derivative.position import Position from .arb_proposal import ArbProposalSide, ArbProposal,Proposal,PriceSize from .aroon_oscillator_indicator import AroonOscillatorIndicator, OscillatorPeriod NaN = float("nan") s_decimal_zero = Decimal(0) spa_logger = None class StrategyState(Enum): Closed = 0 Opening = 1 Stopping = 4 class TrendType(Enum): Up = 0 Down = 1 Sideway = 2 Extreme = 3 class BigspreadTradeStrategy(StrategyPyBase): """ This strategy arbitrages between a spot and a perpetual exchange. For a given order amount, the strategy checks for price discrepancy between buy and sell price on the 2 exchanges. Since perpetual contract requires closing position before profit is realised, there are 2 stages to this arbitrage operation - first to open and second to close. """ @classmethod def logger(cls) -> HummingbotLogger: global spa_logger if spa_logger is None: spa_logger = logging.getLogger(__name__) return spa_logger def init_params(self, spot_market_info: MarketTradingPairTuple, perp_market_info: MarketTradingPairTuple, order_amount: Decimal, perp_leverage: int, min_opening_arbitrage_pct: Decimal, min_closing_arbitrage_pct: Decimal, stop_loss_spread: Decimal, spread2price_num: Decimal, period_length: int, period_duration: int, use_aroon_osc: bool = True, spot_market_slippage_buffer: Decimal = Decimal("0"), perp_market_slippage_buffer: Decimal = Decimal("0"), next_arbitrage_opening_delay: float = 120, status_report_interval: float = 10): """ :param spot_market_info: The spot market info :param perp_market_info: The perpetual market info :param order_amount: The order amount :param perp_leverage: The leverage level to use on perpetual market :param min_opening_arbitrage_pct: The minimum spread to open arbitrage position (e.g. 0.0003 for 0.3%) :param min_closing_arbitrage_pct: The minimum spread to close arbitrage position (e.g. 0.0003 for 0.3%) :param spot_market_slippage_buffer: The buffer for which to adjust order price for higher chance of the order getting filled on spot market. :param perp_market_slippage_buffer: The slipper buffer for perpetual market. :param next_arbitrage_opening_delay: The number of seconds to delay before the next arb position can be opened :param status_report_interval: Amount of seconds to wait to refresh the status report """ self._spot_market_info = spot_market_info self._perp_market_info = perp_market_info self._min_opening_arbitrage_pct = min_opening_arbitrage_pct self._min_closing_arbitrage_pct = min_closing_arbitrage_pct self._spread2price_num = spread2price_num self._period_length = period_length self._period_duration = period_duration self._use_aroon_osc = use_aroon_osc self._aroon_osc = AroonOscillatorIndicator(self._period_length, self._period_duration) # self._spot_mode = self._spot_market_info.market.position_mode self._stop_loss_spread = stop_loss_spread self._order_amount = order_amount self._perp_leverage = perp_leverage self._spot_market_slippage_buffer = spot_market_slippage_buffer self._perp_market_slippage_buffer = perp_market_slippage_buffer self._next_arbitrage_opening_delay = next_arbitrage_opening_delay self._next_arbitrage_opening_ts = 0 # next arbitrage opening timestamp self._all_markets_ready = False self._ev_loop = asyncio.get_event_loop() self._last_timestamp = 0 self._status_report_interval = status_report_interval self.add_markets([spot_market_info.market, perp_market_info.market]) self._main_task = None self._in_flight_opening_order_ids = [] # Todo 这里应该使用 dict 来增减 order_id的信息,但初步使用list,减少的时候默认减少两条,即默认 减仓的两个单子都成交。后面再改。 self._completed_buy_order_ids = [] self._completed_sell_order_ids = [] self._created_buy_order_ids = [] self._created_sell_order_ids = [] # self._completed_closing_order_ids = [] self._opening_order_num = 0 self._strategy_state = StrategyState.Closed self._ready_to_start = False self._last_arb_op_reported_ts = 0 self._record_created_orders_period_duration = 5 *60 self._tolerance_trend_period_duration = 4 *60 self.farthest_open_order_timestamp = 0 self.trend_type = TrendType.Sideway perp_market_info.market.set_leverage(perp_market_info.trading_pair, self._perp_leverage) @property def strategy_state(self) -> StrategyState: return self._strategy_state @property def min_opening_arbitrage_pct(self) -> Decimal: return self._min_opening_arbitrage_pct @property def min_closing_arbitrage_pct(self) -> Decimal: return self._min_closing_arbitrage_pct @property def market_info_to_active_orders(self) -> Dict[MarketTradingPairTuple, List[LimitOrder]]: return self._sb_order_tracker.market_pair_to_active_orders @property def active_orders(self) -> List[LimitOrder]: if self._spot_market_info not in self.market_info_to_active_orders: return [] return self.market_info_to_active_orders[self._spot_market_info] @property def active_positions(self) -> List[LimitOrder]: return self._spot_market_info.market.account_positions @property def order_amount(self) -> Decimal: return self._order_amount @order_amount.setter def order_amount(self, value): self._order_amount = value @property def market_info_to_active_orders(self) -> Dict[MarketTradingPairTuple, List[LimitOrder]]: return self._sb_order_tracker.market_pair_to_active_orders # 这里的仓位为该进程交易币对的仓位,且只存该进程交易的数量,dydx实时动态加减交易的仓位。 @property def perp_positions(self) -> List[Position]: return [s for s in self._perp_market_info.market.account_positions.values() if s.trading_pair == self._perp_market_info.trading_pair and s.amount != s_decimal_zero] @property def aroon_up(self) -> float: return self._aroon_osc.c_aroon_up() @property def aroon_down(self) -> float: return self._aroon_osc.c_aroon_down() @property def aroon_osc(self) -> float: return self._aroon_osc.c_aroon_osc() @property def aroon_full(self) -> bool: return bool(self._aroon_osc.c_full()) @property def aroon_period_count(self) -> int: return self._aroon_osc.c_aroon_period_count() @property def aroon_periods(self) -> List[OscillatorPeriod]: return self._aroon_osc.c_aroon_periods() @property def aroon_last_period(self) -> OscillatorPeriod: return self._aroon_osc.c_last_period() def get_last_price(self) -> Decimal: last_price = self._spot_market_info.get_price_by_type(PriceType.LastTrade) if not last_price: return self.get_mid_price() return last_price def get_mid_price(self) -> float: return self._spot_market_info.get_mid_price() def tick(self, timestamp: float): """ Clock tick entry point, is run every second (on normal tick setting). :param timestamp: current tick timestamp """ if not self._all_markets_ready: self._all_markets_ready = all([market.ready for market in self.active_markets]) if not self._all_markets_ready: return else: self.logger().info("Markets are ready.") self.logger().info("Trading started.") if not self.check_budget_available(): self.logger().info("Trading not possible.") return if self._perp_market_info.market.position_mode != PositionMode.ONEWAY or \ len(self.perp_positions) > 1: self.logger().info("This strategy supports only Oneway position mode. Please update your position " "mode before starting this strategy.") return self._ready_to_start = True if self._ready_to_start and (self._main_task is None or self._main_task.done()): self._main_task = safe_ensure_future(self.main(timestamp)) # self._aroon_task = safe_ensure_future(self.main(timestamp)) async def main(self, timestamp): """ The main procedure for the arbitrage strategy. """ self.update_strategy_state() session_positions = [s for s in self.active_positions.values() if s.trading_pair == self._spot_market_info.trading_pair] if len(session_positions) != 0: proposals = self.stop_loss_feature(session_positions) if proposals is not None: self.execute_orders_proposal(proposals) if self._use_aroon_osc: self._aroon_osc.c_add_tick(self.current_timestamp, self.get_last_price()) if not self._aroon_osc.c_full(): return proposals = await self.create_base_proposals() # execute_proposals = [] if self._strategy_state == StrategyState.Stopping: return else: open_proposals = [p for p in proposals if p.profit_pct() >= self._min_opening_arbitrage_pct] execute_proposals = open_proposals if execute_proposals: self._opening_order_num += 2 if len(execute_proposals) == 0: return raw_pct = execute_proposals[0].profit_pct() if execute_proposals[0].profit_pct() > Decimal('0.003'): proposal = self.process_base_proposals(execute_proposals[0]) else: proposal = self.process_extreme_hanging_order_situation(execute_proposals[0]) or self.process_small_spread_pro_market_making(execute_proposals[0]) # if self._last_arb_op_reported_ts + 60 < self.current_timestamp: pos_txt='opening' self.logger().info(f"Arbitrage position opening opportunity found. opening order is {self._opening_order_num} ,farthest timestamp is {self.farthest_open_order_timestamp}") self.logger().info(f"Profitability ({raw_pct:.2%}) is now above min_{pos_txt}_arbitrage_pct. TrendType is {self.trend_type}. Price_Spread ({proposal.profit_pct():.2%}).") self.logger().info(f"Aroon Osc = {self.aroon_osc:.3g},Aroon Up = {self.aroon_up:.5g},Aroon Down = {self.aroon_down:.5g}") self._last_arb_op_reported_ts = self.current_timestamp # self.apply_slippage_buffers(proposal) # if self.check_budget_constraint(proposal): # self.execute_arb_proposal(proposal) self.execute_arb_proposal(proposal) bids_df, asks_df = self._spot_market_info.order_book.snapshot self.logger().info(f"Bid is {bids_df.head(3)}") self.logger().info(f"Ask is {asks_df.head(3)}") #Todo add logic for stop loss def stop_loss_feature(self, active_positions): market = self._spot_market_info.market active_orders = self.active_orders # all_exit_orders = [o for o in active_orders if o.client_order_id not in self._exit_orders] top_ask = market.get_price(self._spot_market_info.trading_pair, False) top_bid = market.get_price(self._spot_market_info.trading_pair, True) buys = [] sells = [] for position in active_positions: # check if stop loss order needs to be placed stop_loss_price = position.entry_price * (Decimal("1") + self._stop_loss_spread) if position.amount < 0 \ else position.entry_price * (Decimal("1") - self._stop_loss_spread) # 多头&亏损状态 if (top_ask <= stop_loss_price and position.amount > 0): price = market.quantize_order_price(self._spot_market_info.trading_pair, stop_loss_price) take_profit_orders = [o for o in active_orders if (not o.is_buy and o.price > price)] # cancel take profit orders if they exist for old_order in take_profit_orders: self.cancel_order(self._spot_market_info, old_order.client_order_id) exit_order_exists = [o for o in active_orders if o.price == price and not o.is_buy] if len(exit_order_exists) == 0: size = market.quantize_order_amount(self._spot_market_info.trading_pair, abs(position.amount)) if size > 0 and price > 0: self.logger().info(f"Creating stop loss sell order to close long position.") sells.append(PriceSize(price, size)) elif (top_bid >= stop_loss_price and position.amount < 0): price = market.quantize_order_price(self._spot_market_info.trading_pair, stop_loss_price) take_profit_orders = [o for o in active_orders if (o.is_buy and o.price < price)] # cancel take profit orders if they exist for old_order in take_profit_orders: self.cancel_order(self._spot_market_info, old_order.client_order_id) exit_order_exists = [o for o in active_orders if o.price == price and o.is_buy] if len(exit_order_exists) == 0: size = market.quantize_order_amount(self._spot_market_info.trading_pair, abs(position.amount)) if size > 0 and price > 0: self.logger().info(f"Creating stop loss buy order to close short position.") buys.append(PriceSize(price, size)) return Proposal(buys, sells) # 问题在于如何判断开仓、减仓的状态、订单数量的阈值、如果有限价单没有成交的话如何操作(造成单边以及持续单边,dydx是否要使用市价单), def update_strategy_state(self): """ Updates strategy state to either Opened or Closed if the condition is right. """ if self._opening_order_num >= 6: self._strategy_state = StrategyState.Stopping elif self._opening_order_num <= 0: self._strategy_state = StrategyState.Closed else: self._strategy_state = StrategyState.Opening # amount 量根据 perp的仓位,来决定,但现在还不清楚 position 的内部逻辑,到底是开仓后计算,还是交易所已有仓位来计算。 def process_small_spread_pro_market_making(self, p: ArbProposal): osc = Decimal(self._aroon_osc.c_aroon_osc()) if osc > Decimal('50'): self.trend_type = TrendType.Up elif osc < Decimal('-50'): self.trend_type = TrendType.Down else: #问题:如何解决挂单不对称以及挂单距离越来越远的情况。危害:占用 opening 资源。 #1.趋势市价单由于有单一趋势性,如果之前单子未能成交,则趋势出来时立刻止损或止盈。此时仓位方向唯一,且 loss 小于 _stop_loss_spread #2.没有明确方向,此时 self.trend_type = TrendType.Sideway base_price = p.spot_side.order_price # 这里采用币安作为基准价格,减少价差以规避存货风险。 for arb_side in (p.spot_side, p.perp_side): market = arb_side.market_info.market if arb_side.is_buy: s_buffer = Decimal('-1') * p._profit_pct * self._spread2price_num if self.trend_type == TrendType.Up: arb_side.order_type = OrderType.MARKET else: s_buffer = p._profit_pct * self._spread2price_num if self.trend_type == TrendType.Down: arb_side.order_type = OrderType.MARKET new_price = base_price * (Decimal('1') + s_buffer) arb_side.order_price = market.quantize_order_price(arb_side.market_info.trading_pair, new_price) # if p.spot_side.is_buy and self.trend_type == TrendType.Up: # p.spot_side.order_type = OrderType.MARKET # elif p.spot_side.is_buy and self.trend_type == TrendType.Down: # p.perp_side.order_type = OrderType.MARKET # else: # pass return p # 设置最近5分钟的滚动距离,如果最远单子距离当前开单小于4分钟,则开趋势单,否则开双边小限价单。即有开单,且最远开单距离当前4~5分钟时,开双边小限价单。 def process_extreme_hanging_order_situation(self,p :ArbProposal): if self._created_buy_order_ids: self._created_buy_order_ids = [p for p in self._created_buy_order_ids if (p.timestamp + self._record_created_orders_period_duration) > self.current_timestamp] self.farthest_open_order_timestamp = self._created_buy_order_ids[0] if self._created_buy_order_ids else 0 if self.farthest_open_order_timestamp + self._tolerance_trend_period_duration < self.current_timestamp: self.trend_type = TrendType.Extreme base_price = p.spot_side.order_price # 这里采用币安作为基准价格,减少价差以规避存货风险。 for arb_side in (p.spot_side, p.perp_side): market = arb_side.market_info.market if arb_side.is_buy: s_buffer = Decimal('-1') * p._profit_pct * (self._spread2price_num /Decimal('2')) else: s_buffer = p._profit_pct * (self._spread2price_num /Decimal('2')) new_price = base_price * (Decimal('1') + s_buffer) arb_side.order_price = market.quantize_order_price(arb_side.market_info.trading_pair, new_price) return p return None def process_base_proposals(self, p: ArbProposal): # one_decimal = Decimal('1') # _new_perp_price = p.perp_side.order_price * (one_decimal - p._profit_pct * self._spread2price_num) if p.perp_side.is_buy else \ # p.perp_side.order_price * (one_decimal + p._profit_pct * self._spread2price_num) # _new_spot_price = p.spot_side.order_price * (one_decimal - p._profit_pct * self._spread2price_num) if p.spot_side.is_buy else \ # p.spot_side.order_price * (one_decimal + p._profit_pct * self._spread2price_num) # # p.perp_side.order_price = self._perp_market_info.market.quantize_order_price(self._perp_market_info.market.trading_pair,_new_perp_price) # p.spot_side.order_price = self._spot_market_info.market.quantize_order_price(self._spot_market_info.market.trading_pair,_new_spot_price) # base_price = p.spot_side.order_price if p.spot_side.is_buy else p.perp_side.order_price base_price = p.spot_side.order_price #这里采用币安作为基准价格,减少价差以规避存货风险。 for arb_side in (p.spot_side,p.perp_side): market = arb_side.market_info.market if arb_side.is_buy: s_buffer = Decimal('-1') * p._profit_pct * self._spread2price_num else: s_buffer = p._profit_pct * self._spread2price_num new_price = base_price * (Decimal('1') +s_buffer) arb_side.order_price = market.quantize_order_price(arb_side.market_info.trading_pair, new_price) return p async def create_base_proposals(self) -> List[ArbProposal]: """ Creates a list of 2 base proposals, no filter. :return: A list of 2 base proposals. """ tasks = [self._spot_market_info.market.get_order_price(self._spot_market_info.trading_pair, True, self._order_amount), self._spot_market_info.market.get_order_price(self._spot_market_info.trading_pair, False, self._order_amount), self._perp_market_info.market.get_order_price(self._perp_market_info.trading_pair, True, self._order_amount), self._perp_market_info.market.get_order_price(self._perp_market_info.trading_pair, False, self._order_amount)] prices = await safe_gather(*tasks, return_exceptions=True) spot_buy, spot_sell, perp_buy, perp_sell = [*prices] return [ ArbProposal(ArbProposalSide(self._spot_market_info, True, spot_buy), ArbProposalSide(self._perp_market_info, False, perp_sell), self._order_amount), ArbProposal(ArbProposalSide(self._spot_market_info, False, spot_sell), ArbProposalSide(self._perp_market_info, True, perp_buy), self._order_amount) ] def apply_slippage_buffers(self, proposal: ArbProposal): """ Updates arb_proposals by adjusting order price for slipper buffer percentage. E.g. if it is a buy order, for an order price of 100 and 1% slipper buffer, the new order price is 101, for a sell order, the new order price is 99. :param proposal: the arbitrage proposal """ for arb_side in (proposal.spot_side, proposal.perp_side): market = arb_side.market_info.market # arb_side.amount = market.quantize_order_amount(arb_side.market_info.trading_pair, arb_side.amount) s_buffer = self._spot_market_slippage_buffer if market == self._spot_market_info.market \ else self._perp_market_slippage_buffer if not arb_side.is_buy: s_buffer *= Decimal("-1") arb_side.order_price *= Decimal("1") + s_buffer arb_side.order_price = market.quantize_order_price(arb_side.market_info.trading_pair, arb_side.order_price) def check_budget_available(self) -> bool: """ Checks if there's any balance for trading to be possible at all :return: True if user has available balance enough for orders submission. """ spot_base, spot_quote = self._spot_market_info.trading_pair.split("-") perp_base, perp_quote = self._perp_market_info.trading_pair.split("-") balance_spot_base = self._spot_market_info.market.get_available_balance(spot_base) balance_spot_quote = self._spot_market_info.market.get_available_balance(spot_quote) balance_perp_quote = self._perp_market_info.market.get_available_balance(perp_quote) # if balance_spot_base == s_decimal_zero and balance_spot_quote == s_decimal_zero: # self.logger().info(f"Cannot arbitrage, {self._spot_market_info.market.display_name} {spot_base} balance " # f"({balance_spot_base}) is 0 and {self._spot_market_info.market.display_name} {spot_quote} balance " # f"({balance_spot_quote}) is 0.") # return False # if balance_perp_quote == s_decimal_zero: # self.logger().info(f"Cannot arbitrage, {self._perp_market_info.market.display_name} {perp_quote} balance " # f"({balance_perp_quote}) is 0.") # return False return True def check_budget_constraint(self, proposal: ArbProposal) -> bool: """ Check balances on both exchanges if there is enough to submit both orders in a proposal. :param proposal: An arbitrage proposal :return: True if user has available balance enough for both orders submission. """ spot_side = proposal.spot_side spot_token = spot_side.market_info.quote_asset if spot_side.is_buy else spot_side.market_info.base_asset spot_avai_bal = spot_side.market_info.market.get_available_balance(spot_token) if spot_side.is_buy: fee = spot_side.market_info.market.get_fee( spot_side.market_info.base_asset, spot_side.market_info.quote_asset, OrderType.LIMIT, TradeType.BUY, s_decimal_zero, s_decimal_zero ) spot_required_bal = (proposal.order_amount * proposal.spot_side.order_price) * (Decimal("1") + fee.percent) else: spot_required_bal = proposal.order_amount # if spot_avai_bal < spot_required_bal: # self.logger().info(f"Cannot arbitrage, {spot_side.market_info.market.display_name} {spot_token} balance " # f"({spot_avai_bal}) is below required order amount ({spot_required_bal}).") # return False perp_side = proposal.perp_side if self.perp_positions and abs(self.perp_positions[0].amount) == proposal.order_amount: cur_perp_pos_is_buy = True if self.perp_positions[0].amount > 0 else False if perp_side != cur_perp_pos_is_buy: # For perpetual, the collateral in the existing position should be enough to cover the closing call return True perp_token = perp_side.market_info.quote_asset perp_avai_bal = perp_side.market_info.market.get_available_balance(perp_token) fee = spot_side.market_info.market.get_fee( spot_side.market_info.base_asset, spot_side.market_info.quote_asset, OrderType.LIMIT, TradeType.BUY, s_decimal_zero, s_decimal_zero ) pos_size = (proposal.order_amount * proposal.spot_side.order_price) perp_required_bal = (pos_size / self._perp_leverage) + (pos_size * fee.percent) # if perp_avai_bal < perp_required_bal: # self.logger().info(f"Cannot arbitrage, {perp_side.market_info.market.display_name} {perp_token} balance " # f"({perp_avai_bal}) is below required position amount ({perp_required_bal}).") # return False return True def execute_arb_proposal(self, proposal: ArbProposal): """ Execute both sides of the arbitrage trades concurrently. :param proposal: the arbitrage proposal """ if proposal.order_amount == s_decimal_zero: return perp_side = proposal.perp_side spot_side = proposal.spot_side perp_order_fn = self.buy_with_specific_market if perp_side.is_buy else self.sell_with_specific_market side = "BUY" if perp_side.is_buy else "SELL" # position_action = PositionAction.CLOSE if self._strategy_state == StrategyState.Closing or self._strategy_state == StrategyState.Stopping \ # else PositionAction.OPEN self.log_with_clock( logging.INFO, f"Placing {side} order for {proposal.order_amount} {perp_side.market_info.base_asset} " f"at {perp_side.market_info.market.display_name} at {perp_side.order_price} price, now is {time.time()} " # f"{position_action.name} position. now is {time.time()}" ) perp_order_fn( spot_side.market_info, proposal.order_amount, perp_side.order_type, # spot_side.market_info.market.get_taker_order_type(), perp_side.order_price, # position_action=position_action ) spot_order_fn = self.buy_with_specific_market if spot_side.is_buy else self.sell_with_specific_market side = "BUY" if spot_side.is_buy else "SELL" self.log_with_clock( logging.INFO, f"Placing {side} order for {proposal.order_amount} {spot_side.market_info.base_asset} " f"at {spot_side.market_info.market.display_name} at {spot_side.order_price} price now is {time.time()}" ) spot_order_fn( spot_side.market_info, proposal.order_amount, spot_side.order_type, # spot_side.market_info.market.get_taker_order_type(), spot_side.order_price, ) # 只有这里 会将策略标记为 正在减仓操作 # 给交易所发完单后清除 正在开仓和减仓的 order_id ,保证 orders completed 后 为 2。 # if self._strategy_state == StrategyState.Closing or self._strategy_state == StrategyState.Stopping: # if self._strategy_state == StrategyState.Opened: # self._strategy_state = StrategyState.Closing # self._completed_closing_order_ids.clear() # else: # self._strategy_state = StrategyState.Opening # self._completed_opening_order_ids.clear() def execute_orders_proposal(self,proposal): position_action = PositionAction.CLOSE order_type = OrderType.MARKET if len(proposal.buys) > 0: price_quote_str = [f"{buy.size.normalize()} {self._spot_market_info.base_asset}, " f"{buy.price.normalize()} {self._spot_market_info.quote_asset}" for buy in proposal.buys] self.log_with_clock( logging.INFO, f"({self._spot_market_info.trading_pair}) Creating {len(proposal.buys)} Market bid orders " f"at (Size, Price): {price_quote_str} to {position_action.name} position." ) #抵消由于 completed 而减少的次数 self._opening_order_num += 1 for buy in proposal.buys: bid_order_id = self.buy_with_specific_market( self._spot_market_info, buy.size, order_type=order_type, price=buy.price, # position_action=position_action ) df = self.active_positions_df() self.log_with_clock( logging.INFO, str(["", " Positions:"] + [" " + line for line in df.to_string(index=False).split("\n")]) ) if len(proposal.sells) > 0: price_quote_str = [f"{sell.size.normalize()} {self._spot_market_info.base_asset}, " f"{sell.price.normalize()} {self._spot_market_info.quote_asset}" for sell in proposal.sells] self.log_with_clock( logging.INFO, f"({self._spot_market_info.trading_pair}) Creating {len(proposal.sells)} Market ask " f"orders at (Size, Price): {price_quote_str} to {position_action.name} position." ) self._opening_order_num += 1 for sell in proposal.sells: ask_order_id = self.sell_with_specific_market( self._spot_market_info, sell.size, order_type=order_type, price=sell.price, # position_action=position_action ) df = self.active_positions_df() self.log_with_clock( logging.INFO, str(["", " Positions:"] + [" " + line for line in df.to_string(index=False).split("\n")]) ) def active_positions_df(self) -> pd.DataFrame: columns = ["Symbol", "Type", "Entry Price", "Amount", "Leverage", "Unrealized PnL","Stop loss Price"] data = [] market, trading_pair = self._spot_market_info.market, self._spot_market_info.trading_pair for idx in self.active_positions.values(): stop_loss_price = idx.entry_price * (Decimal("1") + self._stop_loss_spread) if idx.amount < 0 \ else idx.entry_price * (Decimal("1") - self._stop_loss_spread) is_buy = True if idx.amount > 0 else False unrealized_profit = ((market.get_price(trading_pair, is_buy) - idx.entry_price) * idx.amount) data.append([ idx.trading_pair, idx.position_side.name, idx.entry_price, idx.amount, idx.leverage, unrealized_profit, stop_loss_price ]) return pd.DataFrame(data=data, columns=columns) async def format_status(self) -> str: """ Returns a status string formatted to display nicely on terminal. The strings composes of 4 parts: markets, assets, spread and warnings(if any). """ columns = ["Exchange", "Market", "Sell Price", "Buy Price", "Mid Price"] data = [] for market_info in [self._spot_market_info, self._perp_market_info]: market, trading_pair, base_asset, quote_asset = market_info buy_price = await market.get_quote_price(trading_pair, True, self._order_amount) sell_price = await market.get_quote_price(trading_pair, False, self._order_amount) mid_price = (buy_price + sell_price) / 2 data.append([ market.display_name, trading_pair, float(sell_price), float(buy_price), float(mid_price) ]) markets_df = pd.DataFrame(data=data, columns=columns) lines = [] lines.extend(["", " Markets:"] + [" " + line for line in markets_df.to_string(index=False).split("\n")]) assets_df = self.wallet_balance_data_frame([self._spot_market_info, self._perp_market_info]) lines.extend(["", " Assets:"] + [" " + line for line in str(assets_df).split("\n")]) proposals = await self.create_base_proposals() lines.extend(["", " Opportunity:"] + self.short_proposal_msg(proposals)) last_aroon_period = self.aroon_last_period lines.extend([ "", f" Aroon Indicators:", f" Aroon Osc = {self.aroon_osc:.3g} Aroon Up = {self.aroon_up:.5g},Aroon Down = {self.aroon_down:.5g}", f" Aroon Indicator Full = {self.aroon_full}, Total periods {self.aroon_period_count}", # f" Current Period (start: {last_aroon_period.start:.0f}, end: {last_aroon_period.end:.0f}, high: {last_aroon_period.high:.5g}, low: {last_aroon_period.low:.5g})", ]) if len(self.active_positions) > 0: df = self.active_positions_df() lines.extend(["", " Positions:"] + [" " + line for line in df.to_string(index=False).split("\n")]) else: lines.extend(["", " No active positions."]) lines.extend(["", f" Opening order count: {self._opening_order_num}."]) warning_lines = self.network_warning([self._spot_market_info]) warning_lines.extend(self.network_warning([self._perp_market_info])) warning_lines.extend(self.balance_warning([self._spot_market_info])) warning_lines.extend(self.balance_warning([self._perp_market_info])) # if len(warning_lines) > 0: # lines.extend(["", "*** WARNINGS ***"] + warning_lines) return "\n".join(lines) def short_proposal_msg(self, arb_proposal: List[ArbProposal], indented: bool = True) -> List[str]: """ Composes a short proposal message. :param arb_proposal: The arbitrage proposal :param indented: If the message should be indented (by 4 spaces) :return A list of messages """ lines = [] for proposal in arb_proposal: spot_side = "buy" if proposal.spot_side.is_buy else "sell" perp_side = "buy" if proposal.perp_side.is_buy else "sell" profit_pct = proposal.profit_pct() lines.append(f"{' ' if indented else ''}{spot_side} at " f"{proposal.spot_side.market_info.market.display_name}" f", {perp_side} at {proposal.perp_side.market_info.market.display_name}: " f"{profit_pct:.2%}") return lines @property def tracked_market_orders(self) -> List[Tuple[ConnectorBase, MarketOrder]]: return self._sb_order_tracker.tracked_market_orders @property def tracked_limit_orders(self) -> List[Tuple[ConnectorBase, LimitOrder]]: return self._sb_order_tracker.tracked_limit_orders def start(self, clock: Clock, timestamp: float): self._ready_to_start = False def stop(self, clock: Clock): if self._main_task is not None: self._main_task.cancel() self._main_task = None self._ready_to_start = False def did_complete_buy_order(self, event: BuyOrderCompletedEvent): # self._completed_buy_order_ids.append(event) self._opening_order_num -= 1 def did_complete_sell_order(self, event: SellOrderCompletedEvent): self._opening_order_num -= 1 # self._completed_sell_order_ids.append(order_id) def did_cancel_order(self, cancelled_event: OrderCancelledEvent): self._opening_order_num -= 1 pass ################################################################################# # def did_create_buy_order(self, event: BuyOrderCreatedEvent): self._created_buy_order_ids.append(event) # def did_create_sell_order(self, event: SellOrderCreatedEvent): # self._created_sell_order_ids.append(event) # def update_complete_order_id_lists(self, order_id: str): # self._completed_opening_order_ids.append(order_id) # pass # # def update_created_order_id_lists(self, order_id: str): # self._created_opening_order_ids.append(order_id) # pass # if order_id[0] == 'x': # if self._strategy_state == StrategyState.Closing or self._strategy_state == StrategyState.Stopping: # self._completed_opening_order_ids.pop(0) # else: # self._completed_opening_order_ids.append(order_id)
[ "hummingbot.core.utils.async_utils.safe_gather" ]
[((1279, 1289), 'decimal.Decimal', 'Decimal', (['(0)'], {}), '(0)\n', (1286, 1289), False, 'from decimal import Decimal\n'), ((2712, 2724), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (2719, 2724), False, 'from decimal import Decimal\n'), ((2785, 2797), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (2792, 2797), False, 'from decimal import Decimal\n'), ((4944, 4968), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (4966, 4968), False, 'import asyncio\n'), ((33004, 33044), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'data', 'columns': 'columns'}), '(data=data, columns=columns)\n', (33016, 33044), True, 'import pandas as pd\n'), ((33992, 34032), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'data', 'columns': 'columns'}), '(data=data, columns=columns)\n', (34004, 34032), True, 'import pandas as pd\n'), ((2029, 2056), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2046, 2056), False, 'import logging\n'), ((11112, 11128), 'decimal.Decimal', 'Decimal', (['"""0.003"""'], {}), "('0.003')\n", (11119, 11128), False, 'from decimal import Decimal\n'), ((15913, 15926), 'decimal.Decimal', 'Decimal', (['"""50"""'], {}), "('50')\n", (15920, 15926), False, 'from decimal import Decimal\n'), ((21396, 21439), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*tasks'], {'return_exceptions': '(True)'}), '(*tasks, return_exceptions=True)\n', (21407, 21439), False, 'from hummingbot.core.utils.async_utils import safe_gather\n'), ((15990, 16004), 'decimal.Decimal', 'Decimal', (['"""-50"""'], {}), "('-50')\n", (15997, 16004), False, 'from decimal import Decimal\n'), ((22779, 22792), 'decimal.Decimal', 'Decimal', (['"""-1"""'], {}), "('-1')\n", (22786, 22792), False, 'from decimal import Decimal\n'), ((22829, 22841), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (22836, 22841), False, 'from decimal import Decimal\n'), ((16922, 16934), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (16929, 16934), False, 'from decimal import Decimal\n'), ((20209, 20221), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (20216, 20221), False, 'from decimal import Decimal\n'), ((25345, 25357), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (25352, 25357), False, 'from decimal import Decimal\n'), ((27968, 27979), 'time.time', 'time.time', ([], {}), '()\n', (27977, 27979), False, 'import time\n'), ((28769, 28780), 'time.time', 'time.time', ([], {}), '()\n', (28778, 28780), False, 'import time\n'), ((13031, 13043), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (13038, 13043), False, 'from decimal import Decimal\n'), ((13140, 13152), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (13147, 13152), False, 'from decimal import Decimal\n'), ((16520, 16533), 'decimal.Decimal', 'Decimal', (['"""-1"""'], {}), "('-1')\n", (16527, 16533), False, 'from decimal import Decimal\n'), ((20031, 20044), 'decimal.Decimal', 'Decimal', (['"""-1"""'], {}), "('-1')\n", (20038, 20044), False, 'from decimal import Decimal\n'), ((32416, 32428), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (32423, 32428), False, 'from decimal import Decimal\n'), ((32515, 32527), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (32522, 32527), False, 'from decimal import Decimal\n'), ((18582, 18594), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (18589, 18594), False, 'from decimal import Decimal\n'), ((18349, 18362), 'decimal.Decimal', 'Decimal', (['"""-1"""'], {}), "('-1')\n", (18356, 18362), False, 'from decimal import Decimal\n'), ((18406, 18418), 'decimal.Decimal', 'Decimal', (['"""2"""'], {}), "('2')\n", (18413, 18418), False, 'from decimal import Decimal\n'), ((18522, 18534), 'decimal.Decimal', 'Decimal', (['"""2"""'], {}), "('2')\n", (18529, 18534), False, 'from decimal import Decimal\n')]
from decimal import Decimal from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_methods import using_exchange from hummingbot.core.data_type.trade_fee import TradeFeeSchema CENTRALIZED = True EXAMPLE_PAIR = "ZRX-ETH" DEFAULT_FEES = TradeFeeSchema( maker_percent_fee_decimal=Decimal("0.0035"), taker_percent_fee_decimal=Decimal("0.0035"), ) KEYS = { "bittrex_api_key": ConfigVar(key="bittrex_api_key", prompt="Enter your Bittrex API key >>> ", required_if=using_exchange("bittrex"), is_secure=True, is_connect_key=True), "bittrex_secret_key": ConfigVar(key="bittrex_secret_key", prompt="Enter your Bittrex secret key >>> ", required_if=using_exchange("bittrex"), is_secure=True, is_connect_key=True), }
[ "hummingbot.client.config.config_methods.using_exchange" ]
[((325, 342), 'decimal.Decimal', 'Decimal', (['"""0.0035"""'], {}), "('0.0035')\n", (332, 342), False, 'from decimal import Decimal\n'), ((374, 391), 'decimal.Decimal', 'Decimal', (['"""0.0035"""'], {}), "('0.0035')\n", (381, 391), False, 'from decimal import Decimal\n'), ((559, 584), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""bittrex"""'], {}), "('bittrex')\n", (573, 584), False, 'from hummingbot.client.config.config_methods import using_exchange\n'), ((823, 848), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""bittrex"""'], {}), "('bittrex')\n", (837, 848), False, 'from hummingbot.client.config.config_methods import using_exchange\n')]
import unittest import asyncio import pandas as pd import time from hummingbot.core.clock import ( Clock, ClockMode ) from hummingbot.core.time_iterator import TimeIterator class ClockUnitTest(unittest.TestCase): backtest_start_timestamp: float = pd.Timestamp("2021-01-01", tz="UTC").timestamp() backtest_end_timestamp: float = pd.Timestamp("2021-01-01 01:00:00", tz="UTC").timestamp() tick_size: int = 1 @classmethod def setUpClass(cls): super().setUpClass() cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() def setUp(self): super().setUp() self.realtime_start_timestamp = int(time.time()) self.realtime_end_timestamp = self.realtime_start_timestamp + 2.0 # self.clock_realtime = Clock(ClockMode.REALTIME, self.tick_size, self.realtime_start_timestamp, self.realtime_end_timestamp) self.clock_backtest = Clock(ClockMode.BACKTEST, self.tick_size, self.backtest_start_timestamp, self.backtest_end_timestamp) def test_clock_mode(self): self.assertEqual(ClockMode.REALTIME, self.clock_realtime.clock_mode) self.assertEqual(ClockMode.BACKTEST, self.clock_backtest.clock_mode) def test_start_time(self): self.assertEqual(self.realtime_start_timestamp, self.clock_realtime.start_time) self.assertEqual(self.backtest_start_timestamp, self.clock_backtest.start_time) def test_tick_time(self): self.assertEqual(self.tick_size, self.clock_realtime.tick_size) self.assertEqual(self.tick_size, self.clock_backtest.tick_size) def test_child_iterators(self): # Tests child_iterators property after initialization. See also test_add_iterator self.assertEqual(0, len(self.clock_realtime.child_iterators)) self.assertEqual(0, len(self.clock_backtest.child_iterators)) def test_current_timestamp(self): self.assertEqual(self.backtest_start_timestamp, self.clock_backtest.current_timestamp) self.assertAlmostEqual((self.realtime_start_timestamp // self.tick_size) * self.tick_size, self.clock_realtime.current_timestamp) self.clock_backtest.backtest() self.clock_realtime.backtest() self.assertEqual(self.backtest_end_timestamp, self.clock_backtest.current_timestamp) self.assertLessEqual(self.realtime_end_timestamp, self.clock_realtime.current_timestamp) def test_add_iterator(self): self.assertEqual(0, len(self.clock_realtime.child_iterators)) self.assertEqual(0, len(self.clock_backtest.child_iterators)) time_iterator: TimeIterator = TimeIterator() self.clock_realtime.add_iterator(time_iterator) self.clock_backtest.add_iterator(time_iterator) self.assertEqual(1, len(self.clock_realtime.child_iterators)) self.assertEqual(time_iterator, self.clock_realtime.child_iterators[0]) self.assertEqual(1, len(self.clock_backtest.child_iterators)) self.assertEqual(time_iterator, self.clock_backtest.child_iterators[0]) def test_remove_iterator(self): self.assertEqual(0, len(self.clock_realtime.child_iterators)) self.assertEqual(0, len(self.clock_backtest.child_iterators)) time_iterator: TimeIterator = TimeIterator() self.clock_realtime.add_iterator(time_iterator) self.clock_backtest.add_iterator(time_iterator) self.assertEqual(1, len(self.clock_realtime.child_iterators)) self.assertEqual(time_iterator, self.clock_realtime.child_iterators[0]) self.assertEqual(1, len(self.clock_backtest.child_iterators)) self.assertEqual(time_iterator, self.clock_backtest.child_iterators[0]) self.clock_realtime.remove_iterator(time_iterator) self.clock_backtest.remove_iterator(time_iterator) self.assertEqual(0, len(self.clock_realtime.child_iterators)) self.assertEqual(0, len(self.clock_backtest.child_iterators)) def test_run(self): # Note: Technically you do not execute `run()` when in BACKTEST mode # Tests EnvironmentError raised when not runnning within a context with self.assertRaises(EnvironmentError): self.ev_loop.run_until_complete(self.clock_realtime.run()) # Note: run() will essentially run indefinitely hence the enforced timeout. with self.assertRaises(asyncio.TimeoutError), self.clock_realtime: self.ev_loop.run_until_complete(asyncio.wait_for(self.clock_realtime.run(), 1)) self.assertLess(self.realtime_start_timestamp, self.clock_realtime.current_timestamp) def test_run_til(self): # Note: Technically you do not execute `run_til()` when in BACKTEST mode # Tests EnvironmentError raised when not runnning within a context with self.assertRaises(EnvironmentError): self.ev_loop.run_until_complete(self.clock_realtime.run_til(self.realtime_end_timestamp)) with self.clock_realtime: self.ev_loop.run_until_complete(self.clock_realtime.run_til(self.realtime_end_timestamp)) self.assertGreaterEqual(self.clock_realtime.current_timestamp, self.realtime_end_timestamp) def test_backtest(self): # Note: Technically you do not execute `backtest()` when in REALTIME mode self.clock_backtest.backtest() self.assertGreaterEqual(self.clock_backtest.current_timestamp, self.backtest_end_timestamp) def test_backtest_til(self): # Note: Technically you do not execute `backtest_til()` when in REALTIME mode self.clock_backtest.backtest_til(self.backtest_start_timestamp + self.tick_size) self.assertGreater(self.clock_backtest.current_timestamp, self.clock_backtest.start_time) self.assertLess(self.clock_backtest.current_timestamp, self.backtest_end_timestamp)
[ "hummingbot.core.time_iterator.TimeIterator", "hummingbot.core.clock.Clock" ]
[((546, 570), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (568, 570), False, 'import asyncio\n'), ((781, 886), 'hummingbot.core.clock.Clock', 'Clock', (['ClockMode.REALTIME', 'self.tick_size', 'self.realtime_start_timestamp', 'self.realtime_end_timestamp'], {}), '(ClockMode.REALTIME, self.tick_size, self.realtime_start_timestamp,\n self.realtime_end_timestamp)\n', (786, 886), False, 'from hummingbot.core.clock import Clock, ClockMode\n'), ((913, 1018), 'hummingbot.core.clock.Clock', 'Clock', (['ClockMode.BACKTEST', 'self.tick_size', 'self.backtest_start_timestamp', 'self.backtest_end_timestamp'], {}), '(ClockMode.BACKTEST, self.tick_size, self.backtest_start_timestamp,\n self.backtest_end_timestamp)\n', (918, 1018), False, 'from hummingbot.core.clock import Clock, ClockMode\n'), ((2606, 2620), 'hummingbot.core.time_iterator.TimeIterator', 'TimeIterator', ([], {}), '()\n', (2618, 2620), False, 'from hummingbot.core.time_iterator import TimeIterator\n'), ((3250, 3264), 'hummingbot.core.time_iterator.TimeIterator', 'TimeIterator', ([], {}), '()\n', (3262, 3264), False, 'from hummingbot.core.time_iterator import TimeIterator\n'), ((263, 299), 'pandas.Timestamp', 'pd.Timestamp', (['"""2021-01-01"""'], {'tz': '"""UTC"""'}), "('2021-01-01', tz='UTC')\n", (275, 299), True, 'import pandas as pd\n'), ((348, 393), 'pandas.Timestamp', 'pd.Timestamp', (['"""2021-01-01 01:00:00"""'], {'tz': '"""UTC"""'}), "('2021-01-01 01:00:00', tz='UTC')\n", (360, 393), True, 'import pandas as pd\n'), ((661, 672), 'time.time', 'time.time', ([], {}), '()\n', (670, 672), False, 'import time\n')]
from bin import path_util # noqa: F401 from aiounittest import async_test from aiohttp import ClientSession import asyncio from async_timeout import timeout from contextlib import ExitStack, asynccontextmanager from decimal import Decimal from os.path import join, realpath import time from typing import Generator, Optional, Set import unittest from unittest.mock import patch from hummingbot.connector.gateway_EVM_AMM import GatewayEVMAMM from hummingbot.connector.gateway_in_flight_order import GatewayInFlightOrder from hummingbot.core.clock import Clock, ClockMode from hummingbot.core.event.event_logger import EventLogger from hummingbot.core.event.events import ( TradeType, MarketEvent, OrderCancelledEvent, TokenApprovalEvent, TokenApprovalCancelledEvent, ) from hummingbot.core.gateway.gateway_http_client import GatewayHttpClient from hummingbot.core.utils.async_utils import safe_ensure_future from test.mock.http_recorder import HttpPlayer WALLET_ADDRESS = "0x5821715133bB451bDE2d5BC6a4cE3430a4fdAF92" NETWORK = "ropsten" TRADING_PAIR = "WETH-DAI" MAX_FEE_PER_GAS = 2000 MAX_PRIORITY_FEE_PER_GAS = 200 ev_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() class GatewayCancelUnitTest(unittest.TestCase): _db_path: str _http_player: HttpPlayer _patch_stack: ExitStack _clock: Clock _clock_task: Optional[asyncio.Task] _connector: GatewayEVMAMM @classmethod def setUpClass(cls) -> None: cls._db_path = realpath(join(__file__, "../fixtures/gateway_cancel_fixture.db")) cls._http_player = HttpPlayer(cls._db_path) cls._clock: Clock = Clock(ClockMode.REALTIME) cls._connector: GatewayEVMAMM = GatewayEVMAMM( "uniswap", "ethereum", NETWORK, WALLET_ADDRESS, trading_pairs=[TRADING_PAIR], trading_required=True ) cls._clock.add_iterator(cls._connector) cls._patch_stack = ExitStack() cls._patch_stack.enter_context(cls._http_player.patch_aiohttp_client()) cls._patch_stack.enter_context( patch( "hummingbot.core.gateway.gateway_http_client.GatewayHttpClient._http_client", return_value=ClientSession() ) ) cls._patch_stack.enter_context(cls._clock) GatewayHttpClient.get_instance().base_url = "https://localhost:5000" ev_loop.run_until_complete(cls.wait_til_ready()) @classmethod def tearDownClass(cls) -> None: cls._patch_stack.close() def tearDown(self) -> None: self._connector._in_flight_orders.clear() @classmethod async def wait_til_ready(cls): while True: now: float = time.time() next_iteration = now // 1.0 + 1 if cls._connector.ready: break else: await cls._clock.run_til(next_iteration + 0.1) @asynccontextmanager async def run_clock(self) -> Generator[Clock, None, None]: self._clock_task = safe_ensure_future(self._clock.run()) try: yield self._clock finally: self._clock_task.cancel() try: await self._clock_task except asyncio.CancelledError: pass self._clock_task = None @async_test(loop=ev_loop) async def test_cancel_order(self): amount: Decimal = Decimal("0.001") connector: GatewayEVMAMM = self._connector event_logger: EventLogger = EventLogger() connector.add_listener(MarketEvent.OrderCancelled, event_logger) expected_order_tx_hash_set: Set[str] = { "0x08f410a0d5cd42446fef3faffc14251ccfa3e4388d83f75f3730c05bcba1c5ab", # noqa: mock "0xe09a9d9593e7ca19205edd3a4ddd1ab1f348dad3ea922ad0ef8efc5c00e3abfb", # noqa: mock } expected_cancel_tx_hash_set: Set[str] = { "0xcd03a16f309a01239b8f7c036865f1c413768f2809fd0355400e7595a3860988", # noqa: mock "0x044eb2c220ec160e157949b0f18f7ba5e36c6e7b115a36e976f92b469f45cab5", # noqa: mock } try: async with self.run_clock(): self._http_player.replay_timestamp_ms = 1648503302272 buy_price: Decimal = await connector.get_order_price(TRADING_PAIR, True, amount) * Decimal("1.02") sell_price: Decimal = await connector.get_order_price(TRADING_PAIR, False, amount) * Decimal("0.98") self._http_player.replay_timestamp_ms = 1648503304951 await connector._create_order( TradeType.BUY, GatewayEVMAMM.create_market_order_id(TradeType.BUY, TRADING_PAIR), TRADING_PAIR, amount, buy_price, max_fee_per_gas=MAX_FEE_PER_GAS, max_priority_fee_per_gas=MAX_PRIORITY_FEE_PER_GAS ) self._http_player.replay_timestamp_ms = 1648503309059 await connector._create_order( TradeType.SELL, GatewayEVMAMM.create_market_order_id(TradeType.SELL, TRADING_PAIR), TRADING_PAIR, amount, sell_price, max_fee_per_gas=MAX_FEE_PER_GAS, max_priority_fee_per_gas=MAX_PRIORITY_FEE_PER_GAS ) self.assertEqual(2, len(connector._in_flight_orders)) self.assertEqual(expected_order_tx_hash_set, set(o.exchange_order_id for o in connector._in_flight_orders.values())) for in_flight_order in connector._in_flight_orders.values(): in_flight_order._creation_timestamp = connector.current_timestamp - 86400 self._http_player.replay_timestamp_ms = 1648503313675 await connector.cancel_outdated_orders(600) self.assertEqual(2, len(connector._in_flight_orders)) self.assertTrue(all([o.is_cancelling for o in connector._in_flight_orders.values()])) self.assertEqual(expected_cancel_tx_hash_set, set(o.cancel_tx_hash for o in connector._in_flight_orders.values())) self._http_player.replay_timestamp_ms = 1648503331511 async with timeout(10): while len(event_logger.event_log) < 2: await event_logger.wait_for(OrderCancelledEvent) self.assertEqual(0, len(connector._in_flight_orders)) finally: connector.remove_listener(MarketEvent.OrderCancelled, event_logger) @async_test(loop=ev_loop) async def test_cancel_approval(self): connector: GatewayEVMAMM = self._connector event_logger: EventLogger = EventLogger() connector.add_listener(TokenApprovalEvent.ApprovalCancelled, event_logger) expected_evm_approve_tx_hash_set: Set[str] = { "0x7666bb5ba3ecec828e323f20685dfd03a067e7b2830b217363293b166b48a679", # noqa: mock "0x7291d26447e300bd37260add7ac7db9a745f64c7ee10854695b0a70b0897456f", # noqa: mock } expected_cancel_tx_hash_set: Set[str] = { "0x21b4d0e956241a497cf50d9c5dcefea4ec9fb225a1d11f80477ca434caab30ff", # noqa: mock "0x7ac85d5a77f28e9317127218c06eb3d70f4c68924a4b5b743fe8faef6d011d11", # noqa: mock } try: async with self.run_clock(): self._http_player.replay_timestamp_ms = 1648503333290 tracked_order_1: GatewayInFlightOrder = await connector.approve_token( "DAI", max_fee_per_gas=MAX_FEE_PER_GAS, max_priority_fee_per_gas=MAX_PRIORITY_FEE_PER_GAS ) self._http_player.replay_timestamp_ms = 1648503337964 tracked_order_2: GatewayInFlightOrder = await connector.approve_token( "WETH", max_fee_per_gas=MAX_FEE_PER_GAS, max_priority_fee_per_gas=MAX_PRIORITY_FEE_PER_GAS ) self.assertEqual(2, len(connector._in_flight_orders)) self.assertEqual(expected_evm_approve_tx_hash_set, set(o.exchange_order_id for o in connector._in_flight_orders.values())) self._http_player.replay_timestamp_ms = 1648503342513 tracked_order_1._creation_timestamp = connector.current_timestamp - 86400 tracked_order_2._creation_timestamp = connector.current_timestamp - 86400 await connector.cancel_outdated_orders(600) self.assertEqual(2, len(connector._in_flight_orders)) self.assertEqual(expected_cancel_tx_hash_set, set(o.cancel_tx_hash for o in connector._in_flight_orders.values())) self._http_player.replay_timestamp_ms = 1648503385484 async with timeout(10): while len(event_logger.event_log) < 2: await event_logger.wait_for(TokenApprovalCancelledEvent) self.assertEqual(0, len(connector._in_flight_orders)) finally: connector.remove_listener(TokenApprovalEvent.ApprovalCancelled, event_logger)
[ "hummingbot.core.event.event_logger.EventLogger", "hummingbot.core.clock.Clock", "hummingbot.connector.gateway_EVM_AMM.GatewayEVMAMM", "hummingbot.connector.gateway_EVM_AMM.GatewayEVMAMM.create_market_order_id", "hummingbot.core.gateway.gateway_http_client.GatewayHttpClient.get_instance" ]
[((1183, 1207), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1205, 1207), False, 'import asyncio\n'), ((3356, 3380), 'aiounittest.async_test', 'async_test', ([], {'loop': 'ev_loop'}), '(loop=ev_loop)\n', (3366, 3380), False, 'from aiounittest import async_test\n'), ((6759, 6783), 'aiounittest.async_test', 'async_test', ([], {'loop': 'ev_loop'}), '(loop=ev_loop)\n', (6769, 6783), False, 'from aiounittest import async_test\n'), ((1588, 1612), 'test.mock.http_recorder.HttpPlayer', 'HttpPlayer', (['cls._db_path'], {}), '(cls._db_path)\n', (1598, 1612), False, 'from test.mock.http_recorder import HttpPlayer\n'), ((1641, 1666), 'hummingbot.core.clock.Clock', 'Clock', (['ClockMode.REALTIME'], {}), '(ClockMode.REALTIME)\n', (1646, 1666), False, 'from hummingbot.core.clock import Clock, ClockMode\n'), ((1707, 1826), 'hummingbot.connector.gateway_EVM_AMM.GatewayEVMAMM', 'GatewayEVMAMM', (['"""uniswap"""', '"""ethereum"""', 'NETWORK', 'WALLET_ADDRESS'], {'trading_pairs': '[TRADING_PAIR]', 'trading_required': '(True)'}), "('uniswap', 'ethereum', NETWORK, WALLET_ADDRESS, trading_pairs\n =[TRADING_PAIR], trading_required=True)\n", (1720, 1826), False, 'from hummingbot.connector.gateway_EVM_AMM import GatewayEVMAMM\n'), ((1979, 1990), 'contextlib.ExitStack', 'ExitStack', ([], {}), '()\n', (1988, 1990), False, 'from contextlib import ExitStack, asynccontextmanager\n'), ((3446, 3462), 'decimal.Decimal', 'Decimal', (['"""0.001"""'], {}), "('0.001')\n", (3453, 3462), False, 'from decimal import Decimal\n'), ((3550, 3563), 'hummingbot.core.event.event_logger.EventLogger', 'EventLogger', ([], {}), '()\n', (3561, 3563), False, 'from hummingbot.core.event.event_logger import EventLogger\n'), ((6913, 6926), 'hummingbot.core.event.event_logger.EventLogger', 'EventLogger', ([], {}), '()\n', (6924, 6926), False, 'from hummingbot.core.event.event_logger import EventLogger\n'), ((1504, 1559), 'os.path.join', 'join', (['__file__', '"""../fixtures/gateway_cancel_fixture.db"""'], {}), "(__file__, '../fixtures/gateway_cancel_fixture.db')\n", (1508, 1559), False, 'from os.path import join, realpath\n'), ((2352, 2384), 'hummingbot.core.gateway.gateway_http_client.GatewayHttpClient.get_instance', 'GatewayHttpClient.get_instance', ([], {}), '()\n', (2382, 2384), False, 'from hummingbot.core.gateway.gateway_http_client import GatewayHttpClient\n'), ((2746, 2757), 'time.time', 'time.time', ([], {}), '()\n', (2755, 2757), False, 'import time\n'), ((2253, 2268), 'aiohttp.ClientSession', 'ClientSession', ([], {}), '()\n', (2266, 2268), False, 'from aiohttp import ClientSession\n'), ((4385, 4400), 'decimal.Decimal', 'Decimal', (['"""1.02"""'], {}), "('1.02')\n", (4392, 4400), False, 'from decimal import Decimal\n'), ((4502, 4517), 'decimal.Decimal', 'Decimal', (['"""0.98"""'], {}), "('0.98')\n", (4509, 4517), False, 'from decimal import Decimal\n'), ((6441, 6452), 'async_timeout.timeout', 'timeout', (['(10)'], {}), '(10)\n', (6448, 6452), False, 'from async_timeout import timeout\n'), ((9131, 9142), 'async_timeout.timeout', 'timeout', (['(10)'], {}), '(10)\n', (9138, 9142), False, 'from async_timeout import timeout\n'), ((4691, 4756), 'hummingbot.connector.gateway_EVM_AMM.GatewayEVMAMM.create_market_order_id', 'GatewayEVMAMM.create_market_order_id', (['TradeType.BUY', 'TRADING_PAIR'], {}), '(TradeType.BUY, TRADING_PAIR)\n', (4727, 4756), False, 'from hummingbot.connector.gateway_EVM_AMM import GatewayEVMAMM\n'), ((5165, 5231), 'hummingbot.connector.gateway_EVM_AMM.GatewayEVMAMM.create_market_order_id', 'GatewayEVMAMM.create_market_order_id', (['TradeType.SELL', 'TRADING_PAIR'], {}), '(TradeType.SELL, TRADING_PAIR)\n', (5201, 5231), False, 'from hummingbot.connector.gateway_EVM_AMM import GatewayEVMAMM\n')]
import unittest import asyncio import random from hummingbot.core.api_throttler.data_types import RateLimit from hummingbot.core.api_throttler.fixed_rate_api_throttler import FixedRateThrottler FIXED_RATE_LIMIT = [ RateLimit(5, 5) ] class FixedRateThrottlerUnitTests(unittest.TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.ev_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() def setUp(self) -> None: super().setUp() self.fixed_rate_throttler = FixedRateThrottler(rate_limit_list=FIXED_RATE_LIMIT, retry_interval=5.0) self.request_count = 0 async def execute_n_requests(self, n: int, throttler: FixedRateThrottler): for _ in range(n): async with throttler.execute_task(): self.request_count += 1 def test_fixed_rate_throttler_above_limit(self): # Test Scenario: API requests sent > Rate Limit n: int = 10 limit: int = FIXED_RATE_LIMIT[0].limit # Note: We assert a timeout ensuring that the throttler does not wait for the limit interval with self.assertRaises(asyncio.exceptions.TimeoutError): self.ev_loop.run_until_complete( asyncio.wait_for(self.execute_n_requests(n, throttler=self.fixed_rate_throttler), timeout=1.0) ) self.assertEqual(limit, self.request_count) def test_fixed_rate_throttler_below_limit(self): # Test Scenario: API requests sent < Rate Limit n: int = random.randint(1, FIXED_RATE_LIMIT[0].limit - 1) limit: int = FIXED_RATE_LIMIT[0].limit self.ev_loop.run_until_complete( self.execute_n_requests(n, throttler=self.fixed_rate_throttler)) self.assertEqual(self.request_count, n) self.assertLess(self.request_count, limit) def test_fixed_rate_throttler_equal_limit(self): # Test Scenario: API requests sent = Rate Limit n = limit = FIXED_RATE_LIMIT[0].limit self.ev_loop.run_until_complete( self.execute_n_requests(n, throttler=self.fixed_rate_throttler)) self.assertEqual(self.request_count, limit)
[ "hummingbot.core.api_throttler.fixed_rate_api_throttler.FixedRateThrottler", "hummingbot.core.api_throttler.data_types.RateLimit" ]
[((221, 236), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', (['(5)', '(5)'], {}), '(5, 5)\n', (230, 236), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((424, 448), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (446, 448), False, 'import asyncio\n'), ((539, 611), 'hummingbot.core.api_throttler.fixed_rate_api_throttler.FixedRateThrottler', 'FixedRateThrottler', ([], {'rate_limit_list': 'FIXED_RATE_LIMIT', 'retry_interval': '(5.0)'}), '(rate_limit_list=FIXED_RATE_LIMIT, retry_interval=5.0)\n', (557, 611), False, 'from hummingbot.core.api_throttler.fixed_rate_api_throttler import FixedRateThrottler\n'), ((1588, 1636), 'random.randint', 'random.randint', (['(1)', '(FIXED_RATE_LIMIT[0].limit - 1)'], {}), '(1, FIXED_RATE_LIMIT[0].limit - 1)\n', (1602, 1636), False, 'import random\n')]
import asyncio import logging from typing import Optional from hummingbot.core.data_type.user_stream_tracker import UserStreamTracker from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.core.utils.async_utils import safe_gather, safe_ensure_future from hummingbot.logger import HummingbotLogger from hummingbot.connector.derivative.binance_perpetual.binance_perpetual_user_stream_data_source import \ BinancePerpetualUserStreamDataSource class BinancePerpetualUserStreamTracker(UserStreamTracker): _bpust_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._bust_logger is None: cls._bust_logger = logging.getLogger(__name__) return cls._bust_logger def __init__(self, base_url: str, stream_url: str, api_key: str): super().__init__() self._api_key: str = api_key self._base_url = base_url self._stream_url = stream_url self._ev_loop: asyncio.events.AbstractEventLoop = asyncio.get_event_loop() self._data_source: Optional[UserStreamTrackerDataSource] = None self._user_stream_tracking_task: Optional[asyncio.Task] = None @property def exchange_name(self) -> str: return "binance_perpetuals" @property def data_source(self) -> UserStreamTrackerDataSource: if self._data_source is None: self._data_source = BinancePerpetualUserStreamDataSource(base_url=self._base_url, stream_url=self._stream_url, api_key=self._api_key) return self._data_source async def start(self): self._user_stream_tracking_task = safe_ensure_future( self.data_source.listen_for_user_stream(self._ev_loop, self._user_stream) ) await safe_gather(self._user_stream_tracking_task)
[ "hummingbot.connector.derivative.binance_perpetual.binance_perpetual_user_stream_data_source.BinancePerpetualUserStreamDataSource", "hummingbot.core.utils.async_utils.safe_gather" ]
[((1074, 1098), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1096, 1098), False, 'import asyncio\n'), ((749, 776), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (766, 776), False, 'import logging\n'), ((1472, 1590), 'hummingbot.connector.derivative.binance_perpetual.binance_perpetual_user_stream_data_source.BinancePerpetualUserStreamDataSource', 'BinancePerpetualUserStreamDataSource', ([], {'base_url': 'self._base_url', 'stream_url': 'self._stream_url', 'api_key': 'self._api_key'}), '(base_url=self._base_url, stream_url=\n self._stream_url, api_key=self._api_key)\n', (1508, 1590), False, 'from hummingbot.connector.derivative.binance_perpetual.binance_perpetual_user_stream_data_source import BinancePerpetualUserStreamDataSource\n'), ((1819, 1863), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['self._user_stream_tracking_task'], {}), '(self._user_stream_tracking_task)\n', (1830, 1863), False, 'from hummingbot.core.utils.async_utils import safe_gather, safe_ensure_future\n')]
import asyncio import json from dateutil.parser import parse as dateparse from decimal import Decimal from typing import Awaitable from unittest.mock import patch, AsyncMock from aioresponses import aioresponses from unittest import TestCase from hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source import CoinzoomAPIOrderBookDataSource from hummingbot.connector.exchange.coinzoom.coinzoom_constants import Constants from hummingbot.connector.exchange.coinzoom.coinzoom_order_book import CoinzoomOrderBook from hummingbot.core.api_throttler.async_throttler import AsyncThrottler from hummingbot.core.data_type.order_book_message import OrderBookMessageType from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant class CoinzoomAPIOrderBookDataSourceTests(TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.base_asset = "COINALPHA" cls.quote_asset = "HBOT" cls.trading_pair = f"{cls.base_asset}-{cls.quote_asset}" cls.api_key = "testKey" cls.api_secret_key = "testSecretKey" cls.username = "testUsername" cls.throttler = AsyncThrottler(Constants.RATE_LIMITS) def setUp(self) -> None: super().setUp() self.listening_task = None self.data_source = CoinzoomAPIOrderBookDataSource( throttler=self.throttler, trading_pairs=[self.trading_pair]) self.mocking_assistant = NetworkMockingAssistant() def tearDown(self) -> None: self.listening_task and self.listening_task.cancel() super().tearDown() def async_run_with_timeout(self, coroutine: Awaitable, timeout: int = 1): ret = asyncio.get_event_loop().run_until_complete(asyncio.wait_for(coroutine, timeout)) return ret @aioresponses() def test_get_last_traded_prices(self, mock_api): url = f"{Constants.REST_URL}/{Constants.ENDPOINT['TICKER']}" resp = {f"{self.base_asset}_{self.quote_asset}": {"last_price": 51234.56}} mock_api.get(url, body=json.dumps(resp)) results = self.async_run_with_timeout(CoinzoomAPIOrderBookDataSource.get_last_traded_prices( trading_pairs=[self.trading_pair], throttler=self.throttler)) self.assertIn(self.trading_pair, results) self.assertEqual(Decimal("51234.56"), results[self.trading_pair]) @aioresponses() def test_fetch_trading_pairs(self, mock_api): url = f"{Constants.REST_URL}/{Constants.ENDPOINT['SYMBOL']}" resp = [{"symbol": f"{self.base_asset}/{self.quote_asset}"}, {"symbol": "BTC/USDT"}] mock_api.get(url, body=json.dumps(resp)) results = self.async_run_with_timeout(CoinzoomAPIOrderBookDataSource.fetch_trading_pairs( throttler=self.throttler)) self.assertIn(self.trading_pair, results) self.assertIn("BTC-USDT", results) @aioresponses() def test_get_new_order_book(self, mock_api): url = f"{Constants.REST_URL}/" \ f"{Constants.ENDPOINT['ORDER_BOOK'].format(trading_pair=self.base_asset+'_'+self.quote_asset)}" resp = {"timestamp": 1234567899, "bids": [], "asks": []} mock_api.get(url, body=json.dumps(resp)) order_book: CoinzoomOrderBook = self.async_run_with_timeout( self.data_source.get_new_order_book(self.trading_pair)) self.assertEqual(1234567899, order_book.snapshot_uid) @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_trades(self, ws_connect_mock): ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() received_messages = asyncio.Queue() message = {"ts": [f"{self.base_asset}/{self.quote_asset}", 8772.05, 0.01, "2020-01-16T21:02:23Z"]} self.listening_task = asyncio.get_event_loop().create_task( self.data_source.listen_for_trades(ev_loop=asyncio.get_event_loop(), output=received_messages)) self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(message)) trade_message = self.async_run_with_timeout(received_messages.get()) self.assertEqual(OrderBookMessageType.TRADE, trade_message.type) self.assertEqual(int(dateparse("2020-01-16T21:02:23Z").timestamp() * 1e3), trade_message.timestamp) self.assertEqual(trade_message.timestamp, trade_message.trade_id) self.assertEqual(self.trading_pair, trade_message.trading_pair) @patch("hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source.CoinzoomAPIOrderBookDataSource._time") @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_order_book_diff(self, ws_connect_mock, time_mock): time_mock.return_value = 1234567890 ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() received_messages = asyncio.Queue() message = {"oi": f"{self.base_asset}/{self.quote_asset}", "b": [["9"], ["5"], ["7", 7193.27, 6.95094164], ["8", 7196.15, 0.69481598]], "s": [["2"], ["1"], ["4", 7222.08, 6.92321326], ["6", 7219.2, 0.69259752]]} self.listening_task = asyncio.get_event_loop().create_task( self.data_source.listen_for_order_book_diffs(ev_loop=asyncio.get_event_loop(), output=received_messages)) self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(message)) diff_message = self.async_run_with_timeout(received_messages.get()) self.assertEqual(OrderBookMessageType.DIFF, diff_message.type) self.assertEqual(1234567890 * 1e3, diff_message.timestamp) self.assertEqual(diff_message.timestamp, diff_message.update_id) self.assertEqual(-1, diff_message.trade_id) self.assertEqual(self.trading_pair, diff_message.trading_pair)
[ "hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source.CoinzoomAPIOrderBookDataSource.fetch_trading_pairs", "hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source.CoinzoomAPIOrderBookDataSource", "hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_sourc...
[((1829, 1843), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (1841, 1843), False, 'from aioresponses import aioresponses\n'), ((2417, 2431), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (2429, 2431), False, 'from aioresponses import aioresponses\n'), ((2947, 2961), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (2959, 2961), False, 'from aioresponses import aioresponses\n'), ((3515, 3566), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (3520, 3566), False, 'from unittest.mock import patch, AsyncMock\n'), ((4606, 4736), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source.CoinzoomAPIOrderBookDataSource._time"""'], {}), "(\n 'hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source.CoinzoomAPIOrderBookDataSource._time'\n )\n", (4611, 4736), False, 'from unittest.mock import patch, AsyncMock\n'), ((4732, 4783), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (4737, 4783), False, 'from unittest.mock import patch, AsyncMock\n'), ((1178, 1215), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['Constants.RATE_LIMITS'], {}), '(Constants.RATE_LIMITS)\n', (1192, 1215), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((1332, 1428), 'hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source.CoinzoomAPIOrderBookDataSource', 'CoinzoomAPIOrderBookDataSource', ([], {'throttler': 'self.throttler', 'trading_pairs': '[self.trading_pair]'}), '(throttler=self.throttler, trading_pairs=[\n self.trading_pair])\n', (1362, 1428), False, 'from hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source import CoinzoomAPIOrderBookDataSource\n'), ((1482, 1507), 'test.hummingbot.connector.network_mocking_assistant.NetworkMockingAssistant', 'NetworkMockingAssistant', ([], {}), '()\n', (1505, 1507), False, 'from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant\n'), ((3736, 3751), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (3749, 3751), False, 'import asyncio\n'), ((5017, 5032), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (5030, 5032), False, 'import asyncio\n'), ((1766, 1802), 'asyncio.wait_for', 'asyncio.wait_for', (['coroutine', 'timeout'], {}), '(coroutine, timeout)\n', (1782, 1802), False, 'import asyncio\n'), ((2145, 2264), 'hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source.CoinzoomAPIOrderBookDataSource.get_last_traded_prices', 'CoinzoomAPIOrderBookDataSource.get_last_traded_prices', ([], {'trading_pairs': '[self.trading_pair]', 'throttler': 'self.throttler'}), '(trading_pairs=[self.\n trading_pair], throttler=self.throttler)\n', (2198, 2264), False, 'from hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source import CoinzoomAPIOrderBookDataSource\n'), ((2362, 2381), 'decimal.Decimal', 'Decimal', (['"""51234.56"""'], {}), "('51234.56')\n", (2369, 2381), False, 'from decimal import Decimal\n'), ((2756, 2832), 'hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source.CoinzoomAPIOrderBookDataSource.fetch_trading_pairs', 'CoinzoomAPIOrderBookDataSource.fetch_trading_pairs', ([], {'throttler': 'self.throttler'}), '(throttler=self.throttler)\n', (2806, 2832), False, 'from hummingbot.connector.exchange.coinzoom.coinzoom_api_order_book_data_source import CoinzoomAPIOrderBookDataSource\n'), ((1722, 1746), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1744, 1746), False, 'import asyncio\n'), ((2080, 2096), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (2090, 2096), False, 'import json\n'), ((2691, 2707), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (2701, 2707), False, 'import json\n'), ((3290, 3306), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (3300, 3306), False, 'import json\n'), ((3891, 3915), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (3913, 3915), False, 'import asyncio\n'), ((4174, 4193), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (4184, 4193), False, 'import json\n'), ((5472, 5496), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (5494, 5496), False, 'import asyncio\n'), ((5765, 5784), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (5775, 5784), False, 'import json\n'), ((3984, 4008), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (4006, 4008), False, 'import asyncio\n'), ((5575, 5599), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (5597, 5599), False, 'import asyncio\n'), ((4375, 4408), 'dateutil.parser.parse', 'dateparse', (['"""2020-01-16T21:02:23Z"""'], {}), "('2020-01-16T21:02:23Z')\n", (4384, 4408), True, 'from dateutil.parser import parse as dateparse\n')]
import dateutil.parser from typing import ( Any, Dict, List, Tuple ) from hummingbot.core.utils.tracking_nonce import get_tracking_nonce from hummingbot.core.data_type.order_book_row import OrderBookRow from hummingbot.core.data_type.order_book_message import OrderBookMessage from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_methods import using_exchange CENTRALIZED = True EXAMPLE_PAIR = "BTC-USD" DEFAULT_FEES = [0.1, 0.1] def convert_from_exchange_trading_pair(exchange_trading_pair: str) -> str: return exchange_trading_pair.replace("/", "-") def convert_to_exchange_trading_pair(hb_trading_pair: str) -> str: return hb_trading_pair.replace("-", "/") def get_new_client_order_id(is_buy: bool, trading_pair: str) -> str: side = "B" if is_buy else "S" return f"{side}-{trading_pair}-{get_tracking_nonce()}" def convert_snapshot_message_to_order_book_row(message: OrderBookMessage) -> Tuple[List[OrderBookRow], List[OrderBookRow]]: update_id = message.update_id data = message.content["data"] bids, asks = [], [] for entry in data: order_row = OrderBookRow(entry["price"], entry["quantity"], update_id) if entry["type"] == "Buy": bids.append(order_row) else: # entry["type"] == "Sell": asks.append(order_row) return bids, asks def convert_diff_message_to_order_book_row(message: OrderBookMessage) -> Tuple[List[OrderBookRow], List[OrderBookRow]]: update_id = message.update_id data = message.content["data"] bids = [] asks = [] bid_entries: Dict[str, Any] = data[0] ask_entries: Dict[str, Any] = data[1] for key, orders in bid_entries.items(): if key == "side": continue elif key == "remove": for price in orders: order_row = OrderBookRow(price, float(0), update_id) bids.append(order_row) else: # key == "update" or key == "add": for order in orders: order_row = OrderBookRow(order["p"], order["q"], update_id) bids.append(order_row) for key, orders in ask_entries.items(): if key == "side": continue elif key == "remove": for price in orders: order_row = OrderBookRow(price, float(0), update_id) asks.append(order_row) else: # key == "update" or key == "add": for order in orders: order_row = OrderBookRow(order["p"], order["q"], update_id) asks.append(order_row) return bids, asks def convert_to_epoch_timestamp(timestamp: str) -> int: return int(dateutil.parser.parse(timestamp).timestamp() * 1e3) KEYS = { "k2_api_key": ConfigVar(key="k2_api_key", prompt="Enter your K2 API key >>> ", required_if=using_exchange("k2"), is_secure=True, is_connect_key=True), "k2_secret_key": ConfigVar(key="k2_secret_key", prompt="Enter your K2 secret key >>> ", required_if=using_exchange("k2"), is_secure=True, is_connect_key=True), }
[ "hummingbot.core.data_type.order_book_row.OrderBookRow", "hummingbot.core.utils.tracking_nonce.get_tracking_nonce", "hummingbot.client.config.config_methods.using_exchange" ]
[((1162, 1220), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (["entry['price']", "entry['quantity']", 'update_id'], {}), "(entry['price'], entry['quantity'], update_id)\n", (1174, 1220), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((876, 896), 'hummingbot.core.utils.tracking_nonce.get_tracking_nonce', 'get_tracking_nonce', ([], {}), '()\n', (894, 896), False, 'from hummingbot.core.utils.tracking_nonce import get_tracking_nonce\n'), ((2914, 2934), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""k2"""'], {}), "('k2')\n", (2928, 2934), False, 'from hummingbot.client.config.config_methods import using_exchange\n'), ((3158, 3178), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""k2"""'], {}), "('k2')\n", (3172, 3178), False, 'from hummingbot.client.config.config_methods import using_exchange\n'), ((2069, 2116), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (["order['p']", "order['q']", 'update_id'], {}), "(order['p'], order['q'], update_id)\n", (2081, 2116), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((2530, 2577), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (["order['p']", "order['q']", 'update_id'], {}), "(order['p'], order['q'], update_id)\n", (2542, 2577), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n')]
from typing import List, Optional from hummingbot.core.web_assistant.auth import AuthBase from hummingbot.core.web_assistant.connections.connections_factory import ConnectionsFactory from hummingbot.core.web_assistant.rest_assistant import RESTAssistant from hummingbot.core.web_assistant.rest_post_processors import RESTPostProcessorBase from hummingbot.core.web_assistant.rest_pre_processors import RESTPreProcessorBase from hummingbot.core.web_assistant.ws_assistant import WSAssistant from hummingbot.core.web_assistant.ws_post_processors import WSPostProcessorBase from hummingbot.core.web_assistant.ws_pre_processors import WSPreProcessorBase class WebAssistantsFactory: """Creates `RESTAssistant` and `WSAssistant` objects. The purpose of the `web_assistant` layer is to abstract away all WebSocket and REST operations from the exchange logic. The assistant objects are designed to be injectable with additional logic via the pre- and post-processor lists. Consult the documentation of the relevant assistant and/or pre-/post-processor class for additional information. todo: integrate AsyncThrottler """ def __init__( self, rest_pre_processors: Optional[List[RESTPreProcessorBase]] = None, rest_post_processors: Optional[List[RESTPostProcessorBase]] = None, ws_pre_processors: Optional[List[WSPreProcessorBase]] = None, ws_post_processors: Optional[List[WSPostProcessorBase]] = None, auth: Optional[AuthBase] = None, ): self._connections_factory = ConnectionsFactory() self._rest_pre_processors = rest_pre_processors or [] self._rest_post_processors = rest_post_processors or [] self._ws_pre_processors = ws_pre_processors or [] self._ws_post_processors = ws_post_processors or [] self._auth = auth async def get_rest_assistant(self) -> RESTAssistant: connection = await self._connections_factory.get_rest_connection() assistant = RESTAssistant( connection, self._rest_pre_processors, self._rest_post_processors, self._auth ) return assistant async def get_ws_assistant(self) -> WSAssistant: connection = await self._connections_factory.get_ws_connection() assistant = WSAssistant( connection, self._ws_pre_processors, self._ws_post_processors, self._auth ) return assistant
[ "hummingbot.core.web_assistant.ws_assistant.WSAssistant", "hummingbot.core.web_assistant.connections.connections_factory.ConnectionsFactory", "hummingbot.core.web_assistant.rest_assistant.RESTAssistant" ]
[((1553, 1573), 'hummingbot.core.web_assistant.connections.connections_factory.ConnectionsFactory', 'ConnectionsFactory', ([], {}), '()\n', (1571, 1573), False, 'from hummingbot.core.web_assistant.connections.connections_factory import ConnectionsFactory\n'), ((1997, 2094), 'hummingbot.core.web_assistant.rest_assistant.RESTAssistant', 'RESTAssistant', (['connection', 'self._rest_pre_processors', 'self._rest_post_processors', 'self._auth'], {}), '(connection, self._rest_pre_processors, self.\n _rest_post_processors, self._auth)\n', (2010, 2094), False, 'from hummingbot.core.web_assistant.rest_assistant import RESTAssistant\n'), ((2284, 2374), 'hummingbot.core.web_assistant.ws_assistant.WSAssistant', 'WSAssistant', (['connection', 'self._ws_pre_processors', 'self._ws_post_processors', 'self._auth'], {}), '(connection, self._ws_pre_processors, self._ws_post_processors,\n self._auth)\n', (2295, 2374), False, 'from hummingbot.core.web_assistant.ws_assistant import WSAssistant\n')]
from unittest import TestCase from mock import patch, MagicMock import asyncio class TestTradingPairFetcher(TestCase): @classmethod async def wait_until_trading_pair_fetcher_ready(cls, tpf): while True: if tpf.ready: break else: await asyncio.sleep(0) class MockConnectorSetting(MagicMock): name = 'mockConnector' def base_name(self): return 'mockConnector' class MockConnectorDataSource(MagicMock): async def fetch_trading_pairs(self, *args, **kwargs): return 'MOCK-HBOT' class MockConnectorDataSourceModule(MagicMock): @property def MockconnectorAPIOrderBookDataSource(self): return TestTradingPairFetcher.MockConnectorDataSource() @classmethod def tearDownClass(cls) -> None: # Need to reset TradingPairFetcher module so next time it gets imported it works as expected from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher TradingPairFetcher._sf_shared_instance = None def test_trading_pair_fetcher_returns_same_instance_when_get_new_instance_once_initialized(self): from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher instance = TradingPairFetcher.get_instance() self.assertIs(instance, TradingPairFetcher.get_instance()) def test_fetched_connector_trading_pairs(self): with patch('hummingbot.core.utils.trading_pair_fetcher.CONNECTOR_SETTINGS', {"mock_exchange_1": self.MockConnectorSetting()}) as _, \ patch('hummingbot.core.utils.trading_pair_fetcher.importlib.import_module', return_value=self.MockConnectorDataSourceModule()) as _, \ patch('hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher._sf_shared_instance', None): from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher trading_pair_fetcher = TradingPairFetcher() asyncio.get_event_loop().run_until_complete(self.wait_until_trading_pair_fetcher_ready(trading_pair_fetcher)) trading_pairs = trading_pair_fetcher.trading_pairs self.assertEqual(trading_pairs, {'mockConnector': 'MOCK-HBOT'})
[ "hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher.get_instance", "hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher" ]
[((1295, 1328), 'hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher.get_instance', 'TradingPairFetcher.get_instance', ([], {}), '()\n', (1326, 1328), False, 'from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher\n'), ((1361, 1394), 'hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher.get_instance', 'TradingPairFetcher.get_instance', ([], {}), '()\n', (1392, 1394), False, 'from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher\n'), ((1799, 1905), 'mock.patch', 'patch', (['"""hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher._sf_shared_instance"""', 'None'], {}), "(\n 'hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher._sf_shared_instance'\n , None)\n", (1804, 1905), False, 'from mock import patch, MagicMock\n'), ((2018, 2038), 'hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher', 'TradingPairFetcher', ([], {}), '()\n', (2036, 2038), False, 'from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher\n'), ((309, 325), 'asyncio.sleep', 'asyncio.sleep', (['(0)'], {}), '(0)\n', (322, 325), False, 'import asyncio\n'), ((2051, 2075), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2073, 2075), False, 'import asyncio\n')]
import math from typing import Dict, List, Tuple, Optional from decimal import Decimal from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_methods import using_exchange CENTRALIZED = True EXAMPLE_PAIR = "ETH-USD" DEFAULT_FEES = [0.1, 0.2] KEYS = { "bitfinex_api_key": ConfigVar(key="bitfinex_api_key", prompt="Enter your Bitfinex API key >>> ", required_if=using_exchange("bitfinex"), is_secure=True, is_connect_key=True), "bitfinex_secret_key": ConfigVar(key="bitfinex_secret_key", prompt="Enter your Bitfinex secret key >>> ", required_if=using_exchange("bitfinex"), is_secure=True, is_connect_key=True), } # deeply merge two dictionaries def merge_dicts(source: Dict, destination: Dict) -> Dict: for key, value in source.items(): if isinstance(value, dict): # get node or create one node = destination.setdefault(key, {}) merge_dicts(value, node) else: destination[key] = value return destination # join paths def join_paths(*paths: List[str]) -> str: return "/".join(paths) # get precision decimal from a number def get_precision(precision: int) -> Decimal: return Decimal(1) / Decimal(math.pow(10, precision)) def split_trading_pair(trading_pair: str) -> Tuple[str, str]: try: base, quote = trading_pair.split("-") return base, quote # exceptions are now logged as warnings in trading pair fetcher except Exception as e: raise e def split_trading_pair_from_exchange(trading_pair: str) -> Tuple[str, str]: # sometimes the exchange returns trading pairs like tBTCUSD isTradingPair = trading_pair[0].islower() and trading_pair[1].isupper() and trading_pair[0] == "t" pair = trading_pair[1:] if isTradingPair else trading_pair if ":" in pair: base, quote = pair.split(":") elif len(pair) == 6: base, quote = pair[:3], pair[3:] else: return None return base, quote def valid_exchange_trading_pair(trading_pair: str) -> bool: try: base, quote = split_trading_pair_from_exchange(trading_pair) return True except Exception: return False def convert_from_exchange_trading_pair(exchange_trading_pair: str) -> Optional[str]: try: # exchange does not split BASEQUOTE (BTCUSDT) base_asset, quote_asset = split_trading_pair_from_exchange(exchange_trading_pair) return f"{base_asset}-{quote_asset}" except Exception as e: raise e def convert_to_exchange_trading_pair(hb_trading_pair: str) -> str: # exchange does not split BASEQUOTE (BTCUSDT) return f't{hb_trading_pair.replace("-", "")}'
[ "hummingbot.client.config.config_methods.using_exchange" ]
[((1378, 1388), 'decimal.Decimal', 'Decimal', (['(1)'], {}), '(1)\n', (1385, 1388), False, 'from decimal import Decimal\n'), ((459, 485), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""bitfinex"""'], {}), "('bitfinex')\n", (473, 485), False, 'from hummingbot.client.config.config_methods import using_exchange\n'), ((727, 753), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""bitfinex"""'], {}), "('bitfinex')\n", (741, 753), False, 'from hummingbot.client.config.config_methods import using_exchange\n'), ((1399, 1422), 'math.pow', 'math.pow', (['(10)', 'precision'], {}), '(10, precision)\n', (1407, 1422), False, 'import math\n')]
import asyncio import json from typing import Awaitable from unittest import TestCase from unittest.mock import AsyncMock, patch from hummingbot.connector.exchange.coinzoom.coinzoom_constants import Constants from hummingbot.connector.exchange.coinzoom.coinzoom_websocket import CoinzoomWebsocket from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant from hummingbot.core.api_throttler.async_throttler import AsyncThrottler class CoinzoomWebsocketTests(TestCase): def setUp(self) -> None: super().setUp() self.mocking_assistant = NetworkMockingAssistant() def async_run_with_timeout(self, coroutine: Awaitable, timeout: int = 1): ret = asyncio.get_event_loop().run_until_complete(asyncio.wait_for(coroutine, timeout)) return ret @patch("websockets.connect", new_callable=AsyncMock) def test_send_subscription_message(self, ws_connect_mock): ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() throttler = AsyncThrottler(Constants.RATE_LIMITS) websocket = CoinzoomWebsocket(throttler=throttler) message = {Constants.WS_SUB["TRADES"]: {'symbol': "BTC/USDT"}} self.async_run_with_timeout(websocket.connect()) self.async_run_with_timeout(websocket.subscribe(message)) self.async_run_with_timeout(websocket.unsubscribe(message)) sent_requests = self.mocking_assistant.text_messages_sent_through_websocket(ws_connect_mock.return_value) sent_subscribe_message = json.loads(sent_requests[0]) expected_subscribe_message = {"TradeSummaryRequest": {"action": "subscribe", "symbol": "BTC/USDT"}} self.assertEquals(expected_subscribe_message, sent_subscribe_message) sent_unsubscribe_message = json.loads(sent_requests[0]) expected_unsubscribe_message = {"TradeSummaryRequest": {"action": "subscribe", "symbol": "BTC/USDT"}} self.assertEquals(expected_unsubscribe_message, sent_unsubscribe_message)
[ "hummingbot.connector.exchange.coinzoom.coinzoom_websocket.CoinzoomWebsocket", "hummingbot.core.api_throttler.async_throttler.AsyncThrottler" ]
[((815, 866), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (820, 866), False, 'from unittest.mock import AsyncMock, patch\n'), ((589, 614), 'test.hummingbot.connector.network_mocking_assistant.NetworkMockingAssistant', 'NetworkMockingAssistant', ([], {}), '()\n', (612, 614), False, 'from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant\n'), ((1036, 1073), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['Constants.RATE_LIMITS'], {}), '(Constants.RATE_LIMITS)\n', (1050, 1073), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((1094, 1132), 'hummingbot.connector.exchange.coinzoom.coinzoom_websocket.CoinzoomWebsocket', 'CoinzoomWebsocket', ([], {'throttler': 'throttler'}), '(throttler=throttler)\n', (1111, 1132), False, 'from hummingbot.connector.exchange.coinzoom.coinzoom_websocket import CoinzoomWebsocket\n'), ((1544, 1572), 'json.loads', 'json.loads', (['sent_requests[0]'], {}), '(sent_requests[0])\n', (1554, 1572), False, 'import json\n'), ((1794, 1822), 'json.loads', 'json.loads', (['sent_requests[0]'], {}), '(sent_requests[0])\n', (1804, 1822), False, 'import json\n'), ((752, 788), 'asyncio.wait_for', 'asyncio.wait_for', (['coroutine', 'timeout'], {}), '(coroutine, timeout)\n', (768, 788), False, 'import asyncio\n'), ((708, 732), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (730, 732), False, 'import asyncio\n')]
import asyncio import logging from typing import Optional from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather from hummingbot.logger import HummingbotLogger class UserStreamTracker: _ust_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._ust_logger is None: cls._ust_logger = logging.getLogger(__name__) return cls._ust_logger def __init__(self, data_source: UserStreamTrackerDataSource): self._user_stream: asyncio.Queue = asyncio.Queue() self._data_source = data_source self._user_stream_tracking_task: Optional[asyncio.Task] = None @property def data_source(self) -> UserStreamTrackerDataSource: return self._data_source @property def last_recv_time(self) -> float: return self.data_source.last_recv_time async def start(self): self._user_stream_tracking_task = safe_ensure_future( self.data_source.listen_for_user_stream(self._user_stream) ) await safe_gather(self._user_stream_tracking_task) @property def user_stream(self) -> asyncio.Queue: return self._user_stream
[ "hummingbot.core.utils.async_utils.safe_gather" ]
[((654, 669), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (667, 669), False, 'import asyncio\n'), ((485, 512), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (502, 512), False, 'import logging\n'), ((1173, 1217), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['self._user_stream_tracking_task'], {}), '(self._user_stream_tracking_task)\n', (1184, 1217), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n')]
from decimal import Decimal import math import numpy as np import pandas as pd import unittest from hummingbot.strategy.__utils__.trailing_indicators.trading_intensity import TradingIntensityIndicator class TradingIntensityTest(unittest.TestCase): INITIAL_RANDOM_SEED = 3141592653 BUFFER_LENGTH = 200 def setUp(self) -> None: np.random.seed(self.INITIAL_RANDOM_SEED) @staticmethod def make_order_books(original_price_mid, original_spread, original_amount, volatility, spread_stdev, amount_stdev, samples): # 0.1% quantization of prices in the orderbook PRICE_STEP_FRACTION = 0.001 # Generate BBO quotes samples_mid = np.random.normal(original_price_mid, volatility * original_price_mid, samples) samples_spread = np.random.normal(original_spread, spread_stdev, samples) samples_price_bid = np.subtract(samples_mid, np.divide(samples_spread, 2)) samples_price_ask = np.add(samples_mid, np.divide(samples_spread, 2)) samples_amount_bid = np.random.normal(original_amount, amount_stdev, samples) samples_amount_ask = np.random.normal(original_amount, amount_stdev, samples) # A full orderbook is not necessary, only up to the BBO max deviation price_depth_max = max(max(samples_price_bid) - min(samples_price_bid), max(samples_price_ask) - min(samples_price_ask)) bid_dfs = [] ask_dfs = [] # Generate an orderbook for every tick for price_bid, amount_bid, price_ask, amount_ask in zip(samples_price_bid, samples_amount_bid, samples_price_ask, samples_amount_ask): bid_df, ask_df = TradingIntensityTest.make_order_book(price_bid, amount_bid, price_ask, amount_ask, price_depth_max, original_price_mid * PRICE_STEP_FRACTION, amount_stdev) bid_dfs += [bid_df] ask_dfs += [ask_df] return bid_dfs, ask_dfs @staticmethod def make_order_book(price_bid, amount_bid, price_ask, amount_ask, price_depth, price_step, amount_stdev, ): prices_bid = np.linspace(price_bid, price_bid - price_depth, math.ceil(price_depth / price_step)) amounts_bid = np.random.normal(amount_bid, amount_stdev, len(prices_bid)) amounts_bid[0] = amount_bid prices_ask = np.linspace(price_ask, price_ask + price_depth, math.ceil(price_depth / price_step)) amounts_ask = np.random.normal(amount_ask, amount_stdev, len(prices_ask)) amounts_ask[0] = amount_ask data_bid = {'price': prices_bid, 'amount': amounts_bid} bid_df = pd.DataFrame(data=data_bid) data_ask = {'price': prices_ask, 'amount': amounts_ask} ask_df = pd.DataFrame(data=data_ask) return bid_df, ask_df def test_calculate_trading_intensity(self): N_SAMPLES = 1000 self.indicator = TradingIntensityIndicator(self.BUFFER_LENGTH) original_price_mid = 100 original_spread = Decimal("10") volatility = Decimal("5") / Decimal("100") original_amount = Decimal("1") spread_stdev = original_spread * Decimal("0.01") amount_stdev = original_amount * Decimal("0.01") # Generate orderbooks for all ticks bids_df, asks_df = TradingIntensityTest.make_order_books(original_price_mid, original_spread, original_amount, volatility, spread_stdev, amount_stdev, N_SAMPLES) for bid_df, ask_df in zip(bids_df, asks_df): snapshot = (bid_df, ask_df) self.indicator.add_sample(snapshot) self.assertAlmostEqual(self.indicator.current_value[0], 1.0006118838992204, 4) self.assertAlmostEqual(self.indicator.current_value[1], 0.00016076949224819458, 4)
[ "hummingbot.strategy.__utils__.trailing_indicators.trading_intensity.TradingIntensityIndicator" ]
[((349, 389), 'numpy.random.seed', 'np.random.seed', (['self.INITIAL_RANDOM_SEED'], {}), '(self.INITIAL_RANDOM_SEED)\n', (363, 389), True, 'import numpy as np\n'), ((682, 760), 'numpy.random.normal', 'np.random.normal', (['original_price_mid', '(volatility * original_price_mid)', 'samples'], {}), '(original_price_mid, volatility * original_price_mid, samples)\n', (698, 760), True, 'import numpy as np\n'), ((786, 842), 'numpy.random.normal', 'np.random.normal', (['original_spread', 'spread_stdev', 'samples'], {}), '(original_spread, spread_stdev, samples)\n', (802, 842), True, 'import numpy as np\n'), ((1035, 1091), 'numpy.random.normal', 'np.random.normal', (['original_amount', 'amount_stdev', 'samples'], {}), '(original_amount, amount_stdev, samples)\n', (1051, 1091), True, 'import numpy as np\n'), ((1121, 1177), 'numpy.random.normal', 'np.random.normal', (['original_amount', 'amount_stdev', 'samples'], {}), '(original_amount, amount_stdev, samples)\n', (1137, 1177), True, 'import numpy as np\n'), ((2564, 2591), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'data_bid'}), '(data=data_bid)\n', (2576, 2591), True, 'import pandas as pd\n'), ((2674, 2701), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'data_ask'}), '(data=data_ask)\n', (2686, 2701), True, 'import pandas as pd\n'), ((2833, 2878), 'hummingbot.strategy.__utils__.trailing_indicators.trading_intensity.TradingIntensityIndicator', 'TradingIntensityIndicator', (['self.BUFFER_LENGTH'], {}), '(self.BUFFER_LENGTH)\n', (2858, 2878), False, 'from hummingbot.strategy.__utils__.trailing_indicators.trading_intensity import TradingIntensityIndicator\n'), ((2939, 2952), 'decimal.Decimal', 'Decimal', (['"""10"""'], {}), "('10')\n", (2946, 2952), False, 'from decimal import Decimal\n'), ((3030, 3042), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (3037, 3042), False, 'from decimal import Decimal\n'), ((897, 925), 'numpy.divide', 'np.divide', (['samples_spread', '(2)'], {}), '(samples_spread, 2)\n', (906, 925), True, 'import numpy as np\n'), ((975, 1003), 'numpy.divide', 'np.divide', (['samples_spread', '(2)'], {}), '(samples_spread, 2)\n', (984, 1003), True, 'import numpy as np\n'), ((2102, 2137), 'math.ceil', 'math.ceil', (['(price_depth / price_step)'], {}), '(price_depth / price_step)\n', (2111, 2137), False, 'import math\n'), ((2327, 2362), 'math.ceil', 'math.ceil', (['(price_depth / price_step)'], {}), '(price_depth / price_step)\n', (2336, 2362), False, 'import math\n'), ((2974, 2986), 'decimal.Decimal', 'Decimal', (['"""5"""'], {}), "('5')\n", (2981, 2986), False, 'from decimal import Decimal\n'), ((2989, 3003), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (2996, 3003), False, 'from decimal import Decimal\n'), ((3085, 3100), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (3092, 3100), False, 'from decimal import Decimal\n'), ((3142, 3157), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (3149, 3157), False, 'from decimal import Decimal\n')]
import asyncio import json import re from collections import deque from decimal import Decimal from typing import Awaitable from unittest.mock import patch, AsyncMock from aioresponses import aioresponses from unittest import TestCase from hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source import AltmarketsAPIOrderBookDataSource from hummingbot.connector.exchange.altmarkets.altmarkets_constants import Constants from hummingbot.connector.exchange.altmarkets.altmarkets_order_book import AltmarketsOrderBook from hummingbot.connector.exchange.altmarkets.altmarkets_utils import convert_to_exchange_trading_pair from hummingbot.core.api_throttler.async_throttler import AsyncThrottler from hummingbot.core.data_type.order_book_message import OrderBookMessage, OrderBookMessageType from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant class AltmarketsAPIOrderBookDataSourceTests(TestCase): # logging.Level required to receive logs from the exchange level = 0 @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.ev_loop = asyncio.get_event_loop() cls.base_asset = "HBOT" cls.quote_asset = "USDT" cls.trading_pair = f"{cls.base_asset}-{cls.quote_asset}" cls.exchange_trading_pair = convert_to_exchange_trading_pair(cls.trading_pair) cls.api_key = "testKey" cls.api_secret_key = "testSecretKey" cls.username = "testUsername" cls.throttler = AsyncThrottler(Constants.RATE_LIMITS) def setUp(self) -> None: super().setUp() self.log_records = [] self.listening_task = None self.data_source = AltmarketsAPIOrderBookDataSource( throttler=self.throttler, trading_pairs=[self.trading_pair]) self.mocking_assistant = NetworkMockingAssistant() self.data_source.logger().setLevel(1) self.data_source.logger().addHandler(self) def tearDown(self) -> None: self.listening_task and self.listening_task.cancel() super().tearDown() def handle(self, record): self.log_records.append(record) def _is_logged(self, log_level: str, message: str) -> bool: return any(record.levelname == log_level and record.getMessage() == message for record in self.log_records) def async_run_with_timeout(self, coroutine: Awaitable, timeout: int = 1): ret = self.ev_loop.run_until_complete(asyncio.wait_for(coroutine, timeout)) return ret def test_throttler_rates(self): self.assertEqual(str(self.throttler._rate_limits[0]), str(self.data_source._get_throttler_instance()._rate_limits[0])) self.assertEqual(str(self.throttler._rate_limits[-1]), str(self.data_source._get_throttler_instance()._rate_limits[-1])) @aioresponses() def test_get_last_traded_prices(self, mock_api): url = f"{Constants.REST_URL}/{Constants.ENDPOINT['TICKER_SINGLE'].format(trading_pair=self.exchange_trading_pair)}" resp = {"ticker": {"last": 51234.56}} mock_api.get(url, body=json.dumps(resp)) results = self.async_run_with_timeout(AltmarketsAPIOrderBookDataSource.get_last_traded_prices( trading_pairs=[self.trading_pair], throttler=self.throttler)) self.assertIn(self.trading_pair, results) self.assertEqual(Decimal("51234.56"), results[self.trading_pair]) @aioresponses() @patch("hummingbot.connector.exchange.altmarkets.altmarkets_http_utils.retry_sleep_time") def test_get_last_traded_prices_multiple(self, mock_api, retry_sleep_time_mock): retry_sleep_time_mock.side_effect = lambda *args, **kwargs: 0 url = f"{Constants.REST_URL}/{Constants.ENDPOINT['TICKER']}" resp = { f"{self.exchange_trading_pair}": { "ticker": {"last": 51234.56} }, "rogerbtc": { "ticker": {"last": 0.00000002} }, "btcusdt": { "ticker": {"last": 51234.56} }, "hbotbtc": { "ticker": {"last": 0.9} }, } mock_api.get(url, body=json.dumps(resp)) results = self.async_run_with_timeout(AltmarketsAPIOrderBookDataSource.get_last_traded_prices( trading_pairs=[self.trading_pair, 'rogerbtc', 'btcusdt', 'hbotbtc'], throttler=self.throttler)) self.assertIn(self.trading_pair, results) self.assertEqual(Decimal("51234.56"), results[self.trading_pair]) self.assertEqual(Decimal("0.00000002"), results["rogerbtc"]) self.assertEqual(Decimal("51234.56"), results["btcusdt"]) self.assertEqual(Decimal("0.9"), results["hbotbtc"]) @aioresponses() def test_fetch_trading_pairs(self, mock_api): url = f"{Constants.REST_URL}/{Constants.ENDPOINT['SYMBOL']}" resp = [ { "name": f"{self.base_asset}/{self.quote_asset}", "state": "enabled" }, { "name": "ROGER/BTC", "state": "enabled" } ] mock_api.get(url, body=json.dumps(resp)) results = self.async_run_with_timeout(AltmarketsAPIOrderBookDataSource.fetch_trading_pairs( throttler=self.throttler)) self.assertIn(self.trading_pair, results) self.assertIn("ROGER-BTC", results) @aioresponses() @patch("hummingbot.connector.exchange.altmarkets.altmarkets_http_utils.retry_sleep_time") def test_fetch_trading_pairs_returns_empty_on_error(self, mock_api, retry_sleep_time_mock): retry_sleep_time_mock.side_effect = lambda *args, **kwargs: 0 url = f"{Constants.REST_URL}/{Constants.ENDPOINT['SYMBOL']}" for i in range(Constants.API_MAX_RETRIES): mock_api.get(url, body=json.dumps([{"noname": "empty"}])) results = self.async_run_with_timeout(AltmarketsAPIOrderBookDataSource.fetch_trading_pairs( throttler=self.throttler)) self.assertEqual(0, len(results)) @patch("hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time") @aioresponses() def test_get_new_order_book(self, time_mock, mock_api): time_mock.return_value = 1234567899 url = f"{Constants.REST_URL}/" \ f"{Constants.ENDPOINT['ORDER_BOOK'].format(trading_pair=self.exchange_trading_pair)}" \ "?limit=300" resp = {"timestamp": 1234567899, "bids": [], "asks": []} mock_api.get(url, body=json.dumps(resp)) order_book: AltmarketsOrderBook = self.async_run_with_timeout( self.data_source.get_new_order_book(self.trading_pair)) self.assertEqual(1234567899 * 1e3, order_book.snapshot_uid) @patch("hummingbot.connector.exchange.altmarkets.altmarkets_http_utils.retry_sleep_time") @patch("hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time") @aioresponses() def test_get_new_order_book_raises_error(self, retry_sleep_time_mock, time_mock, mock_api): retry_sleep_time_mock.side_effect = lambda *args, **kwargs: 0 time_mock.return_value = 1234567899 url = f"{Constants.REST_URL}/" \ f"{Constants.ENDPOINT['ORDER_BOOK'].format(trading_pair=self.exchange_trading_pair)}" \ "?limit=300" for i in range(Constants.API_MAX_RETRIES): mock_api.get(url, body=json.dumps({"errors": {"message": "Dummy error."}, "status": 500})) with self.assertRaises(IOError): self.async_run_with_timeout( self.data_source.get_new_order_book(self.trading_pair)) @aioresponses() def test_listen_for_snapshots_cancelled_when_fetching_snapshot(self, mock_get): trades_queue = asyncio.Queue() endpoint = Constants.ENDPOINT['ORDER_BOOK'].format(trading_pair=r'[\w]+') re_url = f"{Constants.REST_URL}/{endpoint}" regex_url = re.compile(re_url) resp = {"timestamp": 1234567899, "bids": [], "asks": []} mock_get.get(regex_url, body=json.dumps(resp)) self.listening_task = asyncio.get_event_loop().create_task( self.data_source.listen_for_order_book_snapshots(ev_loop=asyncio.get_event_loop(), output=trades_queue)) with self.assertRaises(asyncio.CancelledError): self.listening_task.cancel() asyncio.get_event_loop().run_until_complete(self.listening_task) @aioresponses() @patch( "hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._sleep", new_callable=AsyncMock) def test_listen_for_snapshots_logs_exception_when_fetching_snapshot(self, mock_get, mock_sleep): # the queue and the division by zero error are used just to synchronize the test sync_queue = deque() sync_queue.append(1) endpoint = Constants.ENDPOINT['ORDER_BOOK'].format(trading_pair=r'[\w]+') re_url = f"{Constants.REST_URL}/{endpoint}" regex_url = re.compile(re_url) for x in range(2): mock_get.get(regex_url, body=json.dumps({})) mock_sleep.side_effect = lambda delay: 1 / 0 if len(sync_queue) == 0 else sync_queue.pop() msg_queue: asyncio.Queue = asyncio.Queue() with self.assertRaises(ZeroDivisionError): self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_snapshots(self.ev_loop, msg_queue)) self.ev_loop.run_until_complete(self.listening_task) self.assertEqual(0, msg_queue.qsize()) self.assertTrue(self._is_logged("ERROR", "Unexpected error occurred listening for orderbook snapshots. Retrying in 5 secs...")) @aioresponses() @patch( "hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._sleep", new_callable=AsyncMock) def test_listen_for_snapshots_successful(self, mock_get, mock_sleep): # the queue and the division by zero error are used just to synchronize the test sync_queue = deque() sync_queue.append(1) mock_response = { "timestamp": 1234567890, "asks": [ [7221.08, 6.92321326], [7220.08, 6.92321326], [7222.08, 6.92321326], [7219.2, 0.69259752]], "bids": [ [7199.27, 6.95094164], [7192.27, 6.95094164], [7193.27, 6.95094164], [7196.15, 0.69481598]] } endpoint = Constants.ENDPOINT['ORDER_BOOK'].format(trading_pair=r'[\w]+') regex_url = re.compile(f"{Constants.REST_URL}/{endpoint}") for x in range(2): mock_get.get(regex_url, body=json.dumps(mock_response)) mock_sleep.side_effect = lambda delay: 1 / 0 if len(sync_queue) == 0 else sync_queue.pop() msg_queue: asyncio.Queue = asyncio.Queue() with self.assertRaises(ZeroDivisionError): self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_snapshots(self.ev_loop, msg_queue)) self.ev_loop.run_until_complete(self.listening_task) self.assertEqual(msg_queue.qsize(), 2) snapshot_msg: OrderBookMessage = msg_queue.get_nowait() self.assertEqual(snapshot_msg.update_id, mock_response["timestamp"] * 1e3) @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_trades(self, ws_connect_mock): ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() received_messages = asyncio.Queue() message = { "hbotusdt.trades": { "trades": [ { "date": 1234567899, "tid": '3333', "taker_type": "buy", "price": 8772.05, "amount": 0.1, } ] } } self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_trades(ev_loop=self.ev_loop, output=received_messages)) self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(message)) trade_message = self.async_run_with_timeout(received_messages.get()) self.assertEqual(OrderBookMessageType.TRADE, trade_message.type) self.assertEqual(1234567899, trade_message.timestamp) self.assertEqual('3333', trade_message.trade_id) self.assertEqual(self.trading_pair, trade_message.trading_pair) @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_trades_unrecognised(self, ws_connect_mock): ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() received_messages = asyncio.Queue() self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_trades(ev_loop=self.ev_loop, output=received_messages)) message = { "hbotusdttrades": {} } self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(message)) with self.assertRaises(asyncio.TimeoutError): self.async_run_with_timeout(received_messages.get()) self.assertTrue(self._is_logged("INFO", "Unrecognized message received from Altmarkets websocket: {'hbotusdttrades': {}}")) @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_trades_handles_exception(self, ws_connect_mock): ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() received_messages = asyncio.Queue() self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_trades(ev_loop=self.ev_loop, output=received_messages)) message = { "hbotusdt.trades": { "tradess": [] } } self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(message)) with self.assertRaises(asyncio.TimeoutError): self.async_run_with_timeout(received_messages.get()) self.assertTrue(self._is_logged("ERROR", "Trades: Unexpected error with WebSocket connection. Retrying after 30 seconds...")) @patch("hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time") @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_order_book_diff(self, ws_connect_mock, time_mock): time_mock.return_value = 1234567890 ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() received_messages = asyncio.Queue() message = { "hbotusdt.ob-inc": { "timestamp": 1234567890, "asks": [ [7220.08, 0], [7221.08, 0], [7222.08, 6.92321326], [7219.2, 0.69259752]], "bids": [ [7190.27, 0], [7192.27, 0], [7193.27, 6.95094164], [7196.15, 0.69481598]] } } self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_diffs(ev_loop=self.ev_loop, output=received_messages)) self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(message)) diff_message = self.async_run_with_timeout(received_messages.get()) self.assertEqual(OrderBookMessageType.DIFF, diff_message.type) self.assertEqual(4, len(diff_message.content.get("bids"))) self.assertEqual(4, len(diff_message.content.get("asks"))) self.assertEqual(1234567890, diff_message.timestamp) self.assertEqual(int(1234567890 * 1e3), diff_message.update_id) self.assertEqual(-1, diff_message.trade_id) self.assertEqual(self.trading_pair, diff_message.trading_pair) @patch("hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time") @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_order_book_snapshot(self, ws_connect_mock, time_mock): time_mock.return_value = 1234567890 ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() received_messages = asyncio.Queue() message = { "hbotusdt.ob-snap": { "timestamp": 1234567890, "asks": [ [7220.08, 6.92321326], [7221.08, 6.92321326], [7222.08, 6.92321326], [7219.2, 0.69259752]], "bids": [ [7190.27, 6.95094164], [7192.27, 6.95094164], [7193.27, 6.95094164], [7196.15, 0.69481598]] } } self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_diffs(ev_loop=self.ev_loop, output=received_messages)) self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(message)) diff_message = self.async_run_with_timeout(received_messages.get()) self.assertEqual(OrderBookMessageType.SNAPSHOT, diff_message.type) self.assertEqual(4, len(diff_message.content.get("bids"))) self.assertEqual(4, len(diff_message.content.get("asks"))) self.assertEqual(1234567890, diff_message.timestamp) self.assertEqual(int(1234567890 * 1e3), diff_message.update_id) self.assertEqual(-1, diff_message.trade_id) self.assertEqual(self.trading_pair, diff_message.trading_pair) @patch("hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time") @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_order_book_diff_unrecognised(self, ws_connect_mock, time_mock): time_mock.return_value = 1234567890 ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() received_messages = asyncio.Queue() message = { "snapcracklepop": {} } self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_diffs(ev_loop=self.ev_loop, output=received_messages)) self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(message)) with self.assertRaises(asyncio.TimeoutError): self.async_run_with_timeout(received_messages.get()) self.assertTrue(self._is_logged("INFO", "Unrecognized message received from Altmarkets websocket: {'snapcracklepop': {}}")) @patch("hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time") @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_order_book_diff_handles_exception(self, ws_connect_mock, time_mock): time_mock.return_value = "NaN" ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() received_messages = asyncio.Queue() message = { ".ob-snap": {} } self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_diffs(ev_loop=self.ev_loop, output=received_messages)) self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(message)) with self.assertRaises(asyncio.TimeoutError): self.async_run_with_timeout(received_messages.get()) self.assertTrue(self._is_logged("NETWORK", "Unexpected error with WebSocket connection."))
[ "hummingbot.connector.exchange.altmarkets.altmarkets_utils.convert_to_exchange_trading_pair", "hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource", "hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookD...
[((2831, 2845), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (2843, 2845), False, 'from aioresponses import aioresponses\n'), ((3439, 3453), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (3451, 3453), False, 'from aioresponses import aioresponses\n'), ((3459, 3557), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_http_utils.retry_sleep_time"""'], {}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_http_utils.retry_sleep_time'\n )\n", (3464, 3557), False, 'from unittest.mock import patch, AsyncMock\n'), ((4759, 4773), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (4771, 4773), False, 'from aioresponses import aioresponses\n'), ((5439, 5453), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (5451, 5453), False, 'from aioresponses import aioresponses\n'), ((5459, 5557), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_http_utils.retry_sleep_time"""'], {}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_http_utils.retry_sleep_time'\n )\n", (5464, 5557), False, 'from unittest.mock import patch, AsyncMock\n'), ((6093, 6229), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time"""'], {}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time'\n )\n", (6098, 6229), False, 'from unittest.mock import patch, AsyncMock\n'), ((6225, 6239), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (6237, 6239), False, 'from aioresponses import aioresponses\n'), ((6875, 6973), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_http_utils.retry_sleep_time"""'], {}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_http_utils.retry_sleep_time'\n )\n", (6880, 6973), False, 'from unittest.mock import patch, AsyncMock\n'), ((6969, 7105), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time"""'], {}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time'\n )\n", (6974, 7105), False, 'from unittest.mock import patch, AsyncMock\n'), ((7101, 7115), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (7113, 7115), False, 'from aioresponses import aioresponses\n'), ((7811, 7825), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (7823, 7825), False, 'from aioresponses import aioresponses\n'), ((8642, 8656), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (8654, 8656), False, 'from aioresponses import aioresponses\n'), ((8662, 8823), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._sleep"""'], {'new_callable': 'AsyncMock'}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._sleep'\n , new_callable=AsyncMock)\n", (8667, 8823), False, 'from unittest.mock import patch, AsyncMock\n'), ((9987, 10001), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (9999, 10001), False, 'from aioresponses import aioresponses\n'), ((10007, 10168), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._sleep"""'], {'new_callable': 'AsyncMock'}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._sleep'\n , new_callable=AsyncMock)\n", (10012, 10168), False, 'from unittest.mock import patch, AsyncMock\n'), ((11692, 11743), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (11697, 11743), False, 'from unittest.mock import patch, AsyncMock\n'), ((12965, 13016), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (12970, 13016), False, 'from unittest.mock import patch, AsyncMock\n'), ((13888, 13939), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (13893, 13939), False, 'from unittest.mock import patch, AsyncMock\n'), ((14862, 14998), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time"""'], {}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time'\n )\n", (14867, 14998), False, 'from unittest.mock import patch, AsyncMock\n'), ((14994, 15045), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (14999, 15045), False, 'from unittest.mock import patch, AsyncMock\n'), ((16639, 16775), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time"""'], {}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time'\n )\n", (16644, 16775), False, 'from unittest.mock import patch, AsyncMock\n'), ((16771, 16822), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (16776, 16822), False, 'from unittest.mock import patch, AsyncMock\n'), ((18461, 18597), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time"""'], {}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time'\n )\n", (18466, 18597), False, 'from unittest.mock import patch, AsyncMock\n'), ((18593, 18644), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (18598, 18644), False, 'from unittest.mock import patch, AsyncMock\n'), ((19590, 19726), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time"""'], {}), "(\n 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource._time'\n )\n", (19595, 19726), False, 'from unittest.mock import patch, AsyncMock\n'), ((19722, 19773), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (19727, 19773), False, 'from unittest.mock import patch, AsyncMock\n'), ((1136, 1160), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1158, 1160), False, 'import asyncio\n'), ((1327, 1377), 'hummingbot.connector.exchange.altmarkets.altmarkets_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['cls.trading_pair'], {}), '(cls.trading_pair)\n', (1359, 1377), False, 'from hummingbot.connector.exchange.altmarkets.altmarkets_utils import convert_to_exchange_trading_pair\n'), ((1517, 1554), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['Constants.RATE_LIMITS'], {}), '(Constants.RATE_LIMITS)\n', (1531, 1554), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((1701, 1799), 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource', 'AltmarketsAPIOrderBookDataSource', ([], {'throttler': 'self.throttler', 'trading_pairs': '[self.trading_pair]'}), '(throttler=self.throttler, trading_pairs=[\n self.trading_pair])\n', (1733, 1799), False, 'from hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source import AltmarketsAPIOrderBookDataSource\n'), ((1853, 1878), 'test.hummingbot.connector.network_mocking_assistant.NetworkMockingAssistant', 'NetworkMockingAssistant', ([], {}), '()\n', (1876, 1878), False, 'from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant\n'), ((7933, 7948), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (7946, 7948), False, 'import asyncio\n'), ((8104, 8122), 're.compile', 're.compile', (['re_url'], {}), '(re_url)\n', (8114, 8122), False, 'import re\n'), ((9042, 9049), 'collections.deque', 'deque', ([], {}), '()\n', (9047, 9049), False, 'from collections import deque\n'), ((9234, 9252), 're.compile', 're.compile', (['re_url'], {}), '(re_url)\n', (9244, 9252), False, 'import re\n'), ((9473, 9488), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (9486, 9488), False, 'import asyncio\n'), ((10360, 10367), 'collections.deque', 'deque', ([], {}), '()\n', (10365, 10367), False, 'from collections import deque\n'), ((10929, 10975), 're.compile', 're.compile', (['f"""{Constants.REST_URL}/{endpoint}"""'], {}), "(f'{Constants.REST_URL}/{endpoint}')\n", (10939, 10975), False, 'import re\n'), ((11207, 11222), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (11220, 11222), False, 'import asyncio\n'), ((11913, 11928), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (11926, 11928), False, 'import asyncio\n'), ((13199, 13214), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (13212, 13214), False, 'import asyncio\n'), ((14127, 14142), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (14140, 14142), False, 'import asyncio\n'), ((15279, 15294), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (15292, 15294), False, 'import asyncio\n'), ((17060, 17075), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (17073, 17075), False, 'import asyncio\n'), ((18891, 18906), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (18904, 18906), False, 'import asyncio\n'), ((20020, 20035), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (20033, 20035), False, 'import asyncio\n'), ((2475, 2511), 'asyncio.wait_for', 'asyncio.wait_for', (['coroutine', 'timeout'], {}), '(coroutine, timeout)\n', (2491, 2511), False, 'import asyncio\n'), ((3165, 3286), 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource.get_last_traded_prices', 'AltmarketsAPIOrderBookDataSource.get_last_traded_prices', ([], {'trading_pairs': '[self.trading_pair]', 'throttler': 'self.throttler'}), '(trading_pairs=[self\n .trading_pair], throttler=self.throttler)\n', (3220, 3286), False, 'from hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source import AltmarketsAPIOrderBookDataSource\n'), ((3384, 3403), 'decimal.Decimal', 'Decimal', (['"""51234.56"""'], {}), "('51234.56')\n", (3391, 3403), False, 'from decimal import Decimal\n'), ((4255, 4410), 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource.get_last_traded_prices', 'AltmarketsAPIOrderBookDataSource.get_last_traded_prices', ([], {'trading_pairs': "[self.trading_pair, 'rogerbtc', 'btcusdt', 'hbotbtc']", 'throttler': 'self.throttler'}), "(trading_pairs=[self\n .trading_pair, 'rogerbtc', 'btcusdt', 'hbotbtc'], throttler=self.throttler)\n", (4310, 4410), False, 'from hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source import AltmarketsAPIOrderBookDataSource\n'), ((4508, 4527), 'decimal.Decimal', 'Decimal', (['"""51234.56"""'], {}), "('51234.56')\n", (4515, 4527), False, 'from decimal import Decimal\n'), ((4582, 4603), 'decimal.Decimal', 'Decimal', (['"""0.00000002"""'], {}), "('0.00000002')\n", (4589, 4603), False, 'from decimal import Decimal\n'), ((4651, 4670), 'decimal.Decimal', 'Decimal', (['"""51234.56"""'], {}), "('51234.56')\n", (4658, 4670), False, 'from decimal import Decimal\n'), ((4717, 4731), 'decimal.Decimal', 'Decimal', (['"""0.9"""'], {}), "('0.9')\n", (4724, 4731), False, 'from decimal import Decimal\n'), ((5245, 5323), 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource.fetch_trading_pairs', 'AltmarketsAPIOrderBookDataSource.fetch_trading_pairs', ([], {'throttler': 'self.throttler'}), '(throttler=self.throttler)\n', (5297, 5323), False, 'from hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source import AltmarketsAPIOrderBookDataSource\n'), ((5951, 6029), 'hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source.AltmarketsAPIOrderBookDataSource.fetch_trading_pairs', 'AltmarketsAPIOrderBookDataSource.fetch_trading_pairs', ([], {'throttler': 'self.throttler'}), '(throttler=self.throttler)\n', (6003, 6029), False, 'from hummingbot.connector.exchange.altmarkets.altmarkets_api_order_book_data_source import AltmarketsAPIOrderBookDataSource\n'), ((3100, 3116), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (3110, 3116), False, 'import json\n'), ((4190, 4206), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (4200, 4206), False, 'import json\n'), ((5180, 5196), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (5190, 5196), False, 'import json\n'), ((6642, 6658), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (6652, 6658), False, 'import json\n'), ((8257, 8273), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (8267, 8273), False, 'import json\n'), ((8306, 8330), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (8328, 8330), False, 'import asyncio\n'), ((12596, 12615), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (12606, 12615), False, 'import json\n'), ((13569, 13588), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (13579, 13588), False, 'import json\n'), ((14541, 14560), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (14551, 14560), False, 'import json\n'), ((16074, 16093), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (16084, 16093), False, 'import json\n'), ((17892, 17911), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (17902, 17911), False, 'import json\n'), ((19271, 19290), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (19281, 19290), False, 'import json\n'), ((20394, 20413), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (20404, 20413), False, 'import json\n'), ((5869, 5902), 'json.dumps', 'json.dumps', (["[{'noname': 'empty'}]"], {}), "([{'noname': 'empty'}])\n", (5879, 5902), False, 'import json\n'), ((7582, 7648), 'json.dumps', 'json.dumps', (["{'errors': {'message': 'Dummy error.'}, 'status': 500}"], {}), "({'errors': {'message': 'Dummy error.'}, 'status': 500})\n", (7592, 7648), False, 'import json\n'), ((8413, 8437), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (8435, 8437), False, 'import asyncio\n'), ((8571, 8595), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (8593, 8595), False, 'import asyncio\n'), ((9321, 9335), 'json.dumps', 'json.dumps', (['{}'], {}), '({})\n', (9331, 9335), False, 'import json\n'), ((11044, 11069), 'json.dumps', 'json.dumps', (['mock_response'], {}), '(mock_response)\n', (11054, 11069), False, 'import json\n')]
from os.path import ( isfile, join, ) from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher from hummingbot.client.settings import ( EXCHANGES, STRATEGIES, CONF_FILE_PATH, ) # Validators def is_exchange(value: str) -> bool: return value in EXCHANGES def is_strategy(value: str) -> bool: return value in STRATEGIES def is_valid_percent(value: str) -> bool: try: return 0 <= float(value) < 1 except ValueError: return False def is_valid_expiration(value: str) -> bool: try: return float(value) >= 130.0 except Exception: return False def is_path(value: str) -> bool: return isfile(join(CONF_FILE_PATH, value)) and value.endswith('.yml') def is_valid_market_trading_pair(market: str, value: str) -> bool: # Since trading pair validation and autocomplete are UI optimizations that do not impact bot performances, # in case of network issues or slow wifi, this check returns true and does not prevent users from proceeding, trading_pair_fetcher: TradingPairFetcher = TradingPairFetcher.get_instance() if trading_pair_fetcher.ready: trading_pairs = trading_pair_fetcher.trading_pairs.get(market, []) return value in trading_pair_fetcher.trading_pairs.get(market) if len(trading_pairs) > 0 else True else: return True
[ "hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher.get_instance" ]
[((1086, 1119), 'hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher.get_instance', 'TradingPairFetcher.get_instance', ([], {}), '()\n', (1117, 1119), False, 'from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher\n'), ((689, 716), 'os.path.join', 'join', (['CONF_FILE_PATH', 'value'], {}), '(CONF_FILE_PATH, value)\n', (693, 716), False, 'from os.path import isfile, join\n')]
import asyncio import logging import time from collections import defaultdict from decimal import Decimal from typing import Any, Dict, List, Mapping, Optional from bidict import bidict import hummingbot.connector.exchange.binance.binance_constants as CONSTANTS from hummingbot.connector.exchange.binance import binance_utils from hummingbot.connector.exchange.binance import binance_web_utils as web_utils from hummingbot.connector.exchange.binance.binance_order_book import BinanceOrderBook from hummingbot.connector.time_synchronizer import TimeSynchronizer from hummingbot.connector.utils import combine_to_hb_trading_pair from hummingbot.core.api_throttler.async_throttler import AsyncThrottler from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.data_type.order_book_message import OrderBookMessage from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource from hummingbot.core.utils import async_ttl_cache from hummingbot.core.utils.async_utils import safe_gather from hummingbot.core.web_assistant.connections.data_types import RESTMethod, WSRequest from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory from hummingbot.core.web_assistant.ws_assistant import WSAssistant from hummingbot.logger import HummingbotLogger class BinanceAPIOrderBookDataSource(OrderBookTrackerDataSource): HEARTBEAT_TIME_INTERVAL = 30.0 TRADE_STREAM_ID = 1 DIFF_STREAM_ID = 2 ONE_HOUR = 60 * 60 _logger: Optional[HummingbotLogger] = None _trading_pair_symbol_map: Dict[str, Mapping[str, str]] = {} _mapping_initialization_lock = asyncio.Lock() def __init__(self, trading_pairs: List[str], domain: str = CONSTANTS.DEFAULT_DOMAIN, api_factory: Optional[WebAssistantsFactory] = None, throttler: Optional[AsyncThrottler] = None, time_synchronizer: Optional[TimeSynchronizer] = None): super().__init__(trading_pairs) self._time_synchronizer = time_synchronizer self._domain = domain self._throttler = throttler self._api_factory = api_factory or web_utils.build_api_factory( throttler=self._throttler, time_synchronizer=self._time_synchronizer, domain=self._domain, ) self._order_book_create_function = lambda: OrderBook() self._message_queue: Dict[str, asyncio.Queue] = defaultdict(asyncio.Queue) @classmethod def logger(cls) -> HummingbotLogger: if cls._logger is None: cls._logger = logging.getLogger(__name__) return cls._logger @classmethod async def get_last_traded_prices(cls, trading_pairs: List[str], domain: str = CONSTANTS.DEFAULT_DOMAIN, api_factory: Optional[WebAssistantsFactory] = None, throttler: Optional[AsyncThrottler] = None, time_synchronizer: Optional[TimeSynchronizer] = None) -> Dict[str, float]: """ Return a dictionary the trading_pair as key and the current price as value for each trading pair passed as parameter :param trading_pairs: list of trading pairs to get the prices for :param domain: which Binance domain we are connecting to (the default value is 'com') :param api_factory: the instance of the web assistant factory to be used when doing requests to the server. If no instance is provided then a new one will be created. :param throttler: the instance of the throttler to use to limit request to the server. If it is not specified the function will create a new one. :param time_synchronizer: the synchronizer instance being used to keep track of the time difference with the exchange :return: Dictionary of associations between token pair and its latest price """ tasks = [cls._get_last_traded_price( trading_pair=t_pair, domain=domain, api_factory=api_factory, throttler=throttler, time_synchronizer=time_synchronizer) for t_pair in trading_pairs] results = await safe_gather(*tasks) return {t_pair: result for t_pair, result in zip(trading_pairs, results)} @staticmethod @async_ttl_cache(ttl=2, maxsize=1) async def get_all_mid_prices(domain: str = CONSTANTS.DEFAULT_DOMAIN) -> Dict[str, Decimal]: """ Returns the mid price of all trading pairs, obtaining the information from the exchange. This functionality is required by the market price strategy. :param domain: Domain to use for the connection with the exchange (either "com" or "us"). Default value is "com" :return: Dictionary with the trading pair as key, and the mid price as value """ resp_json = await web_utils.api_request( path=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL, domain=domain, method=RESTMethod.GET, ) ret_val = {} for record in resp_json: try: pair = await BinanceAPIOrderBookDataSource.trading_pair_associated_to_exchange_symbol( symbol=record["symbol"], domain=domain) ret_val[pair] = ((Decimal(record.get("bidPrice", "0")) + Decimal(record.get("askPrice", "0"))) / Decimal("2")) except KeyError: # Ignore results for pairs that are not tracked continue return ret_val @classmethod def trading_pair_symbol_map_ready(cls, domain: str = CONSTANTS.DEFAULT_DOMAIN): """ Checks if the mapping from exchange symbols to client trading pairs has been initialized :param domain: the domain of the exchange being used (either "com" or "us"). Default value is "com" :return: True if the mapping has been initialized, False otherwise """ return domain in cls._trading_pair_symbol_map and len(cls._trading_pair_symbol_map[domain]) > 0 @classmethod async def trading_pair_symbol_map( cls, domain: str = CONSTANTS.DEFAULT_DOMAIN, api_factory: Optional[WebAssistantsFactory] = None, throttler: Optional[AsyncThrottler] = None, time_synchronizer: Optional[TimeSynchronizer] = None, ) -> Dict[str, str]: """ Returns the internal map used to translate trading pairs from and to the exchange notation. In general this should not be used. Instead call the methods `exchange_symbol_associated_to_pair` and `trading_pair_associated_to_exchange_symbol` :param domain: the domain of the exchange being used (either "com" or "us"). Default value is "com" :param api_factory: the web assistant factory to use in case the symbols information has to be requested :param throttler: the throttler instance to use in case the symbols information has to be requested :param time_synchronizer: the synchronizer instance being used to keep track of the time difference with the exchange :return: bidirectional mapping between trading pair exchange notation and client notation """ if not cls.trading_pair_symbol_map_ready(domain=domain): async with cls._mapping_initialization_lock: # Check condition again (could have been initialized while waiting for the lock to be released) if not cls.trading_pair_symbol_map_ready(domain=domain): await cls._init_trading_pair_symbols( domain=domain, api_factory=api_factory, throttler=throttler, time_synchronizer=time_synchronizer) return cls._trading_pair_symbol_map[domain] @staticmethod async def exchange_symbol_associated_to_pair( trading_pair: str, domain: str = CONSTANTS.DEFAULT_DOMAIN, api_factory: Optional[WebAssistantsFactory] = None, throttler: Optional[AsyncThrottler] = None, time_synchronizer: Optional[TimeSynchronizer] = None, ) -> str: """ Used to translate a trading pair from the client notation to the exchange notation :param trading_pair: trading pair in client notation :param domain: the domain of the exchange being used (either "com" or "us"). Default value is "com" :param api_factory: the web assistant factory to use in case the symbols information has to be requested :param throttler: the throttler instance to use in case the symbols information has to be requested :param time_synchronizer: the synchronizer instance being used to keep track of the time difference with the exchange :return: trading pair in exchange notation """ symbol_map = await BinanceAPIOrderBookDataSource.trading_pair_symbol_map( domain=domain, api_factory=api_factory, throttler=throttler, time_synchronizer=time_synchronizer) return symbol_map.inverse[trading_pair] @staticmethod async def trading_pair_associated_to_exchange_symbol( symbol: str, domain: str = CONSTANTS.DEFAULT_DOMAIN, api_factory: Optional[WebAssistantsFactory] = None, throttler: Optional[AsyncThrottler] = None, time_synchronizer: Optional[TimeSynchronizer] = None) -> str: """ Used to translate a trading pair from the exchange notation to the client notation :param symbol: trading pair in exchange notation :param domain: the domain of the exchange being used (either "com" or "us"). Default value is "com" :param api_factory: the web assistant factory to use in case the symbols information has to be requested :param throttler: the throttler instance to use in case the symbols information has to be requested :param time_synchronizer: the synchronizer instance being used to keep track of the time difference with the exchange :return: trading pair in client notation """ symbol_map = await BinanceAPIOrderBookDataSource.trading_pair_symbol_map( domain=domain, api_factory=api_factory, throttler=throttler, time_synchronizer=time_synchronizer) return symbol_map[symbol] @staticmethod async def fetch_trading_pairs( domain: str = CONSTANTS.DEFAULT_DOMAIN, throttler: Optional[AsyncThrottler] = None, api_factory: Optional[WebAssistantsFactory] = None, time_synchronizer: Optional[TimeSynchronizer] = None) -> List[str]: """ Returns a list of all known trading pairs enabled to operate with :param domain: the domain of the exchange being used (either "com" or "us"). Default value is "com" :param api_factory: the web assistant factory to use in case the symbols information has to be requested :param throttler: the throttler instance to use in case the symbols information has to be requested :param time_synchronizer: the synchronizer instance being used to keep track of the time difference with the exchange :return: list of trading pairs in client notation """ mapping = await BinanceAPIOrderBookDataSource.trading_pair_symbol_map( domain=domain, throttler=throttler, api_factory=api_factory, time_synchronizer=time_synchronizer, ) return list(mapping.values()) async def get_new_order_book(self, trading_pair: str) -> OrderBook: """ Creates a local instance of the exchange order book for a particular trading pair :param trading_pair: the trading pair for which the order book has to be retrieved :return: a local copy of the current order book in the exchange """ snapshot: Dict[str, Any] = await self.get_snapshot(trading_pair, 1000) snapshot_timestamp: float = time.time() snapshot_msg: OrderBookMessage = BinanceOrderBook.snapshot_message_from_exchange( snapshot, snapshot_timestamp, metadata={"trading_pair": trading_pair} ) order_book = self.order_book_create_function() order_book.apply_snapshot(snapshot_msg.bids, snapshot_msg.asks, snapshot_msg.update_id) return order_book async def listen_for_trades(self, ev_loop: asyncio.AbstractEventLoop, output: asyncio.Queue): """ Reads the trade events queue. For each event creates a trade message instance and adds it to the output queue :param ev_loop: the event loop the method will run in :param output: a queue to add the created trade messages """ message_queue = self._message_queue[CONSTANTS.TRADE_EVENT_TYPE] while True: try: json_msg = await message_queue.get() if "result" in json_msg: continue trading_pair = await BinanceAPIOrderBookDataSource.trading_pair_associated_to_exchange_symbol( symbol=json_msg["s"], domain=self._domain, api_factory=self._api_factory, throttler=self._throttler, time_synchronizer=self._time_synchronizer) trade_msg: OrderBookMessage = BinanceOrderBook.trade_message_from_exchange( json_msg, {"trading_pair": trading_pair}) output.put_nowait(trade_msg) except asyncio.CancelledError: raise except Exception: self.logger().exception("Unexpected error when processing public trade updates from exchange") async def listen_for_order_book_diffs(self, ev_loop: asyncio.AbstractEventLoop, output: asyncio.Queue): """ Reads the order diffs events queue. For each event creates a diff message instance and adds it to the output queue :param ev_loop: the event loop the method will run in :param output: a queue to add the created diff messages """ message_queue = self._message_queue[CONSTANTS.DIFF_EVENT_TYPE] while True: try: json_msg = await message_queue.get() if "result" in json_msg: continue trading_pair = await BinanceAPIOrderBookDataSource.trading_pair_associated_to_exchange_symbol( symbol=json_msg["s"], domain=self._domain, api_factory=self._api_factory, throttler=self._throttler, time_synchronizer=self._time_synchronizer) order_book_message: OrderBookMessage = BinanceOrderBook.diff_message_from_exchange( json_msg, time.time(), {"trading_pair": trading_pair}) output.put_nowait(order_book_message) except asyncio.CancelledError: raise except Exception: self.logger().exception("Unexpected error when processing public order book updates from exchange") async def listen_for_order_book_snapshots(self, ev_loop: asyncio.AbstractEventLoop, output: asyncio.Queue): """ This method runs continuously and request the full order book content from the exchange every hour. The method uses the REST API from the exchange because it does not provide an endpoint to get the full order book through websocket. With the information creates a snapshot messages that is added to the output queue :param ev_loop: the event loop the method will run in :param output: a queue to add the created snapshot messages """ while True: try: for trading_pair in self._trading_pairs: try: snapshot: Dict[str, Any] = await self.get_snapshot(trading_pair=trading_pair) snapshot_timestamp: float = time.time() snapshot_msg: OrderBookMessage = BinanceOrderBook.snapshot_message_from_exchange( snapshot, snapshot_timestamp, metadata={"trading_pair": trading_pair} ) output.put_nowait(snapshot_msg) self.logger().debug(f"Saved order book snapshot for {trading_pair}") except asyncio.CancelledError: raise except Exception: self.logger().error(f"Unexpected error fetching order book snapshot for {trading_pair}.", exc_info=True) await self._sleep(5.0) await self._sleep(self.ONE_HOUR) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error.", exc_info=True) await self._sleep(5.0) async def listen_for_subscriptions(self): """ Connects to the trade events and order diffs websocket endpoints and listens to the messages sent by the exchange. Each message is stored in its own queue. """ ws = None while True: try: ws: WSAssistant = await self._api_factory.get_ws_assistant() await ws.connect(ws_url=CONSTANTS.WSS_URL.format(self._domain), ping_timeout=CONSTANTS.WS_HEARTBEAT_TIME_INTERVAL) await self._subscribe_channels(ws) async for ws_response in ws.iter_messages(): data = ws_response.data if "result" in data: continue event_type = data.get("e") if event_type in [CONSTANTS.DIFF_EVENT_TYPE, CONSTANTS.TRADE_EVENT_TYPE]: self._message_queue[event_type].put_nowait(data) except asyncio.CancelledError: raise except Exception: self.logger().error( "Unexpected error occurred when listening to order book streams. Retrying in 5 seconds...", exc_info=True, ) await self._sleep(5.0) finally: ws and await ws.disconnect() async def get_snapshot( self, trading_pair: str, limit: int = 1000, ) -> Dict[str, Any]: """ Retrieves a copy of the full order book from the exchange, for a particular trading pair. :param trading_pair: the trading pair for which the order book will be retrieved :param limit: the depth of the order book to retrieve :return: the response from the exchange (JSON dictionary) """ params = { "symbol": await self.exchange_symbol_associated_to_pair( trading_pair=trading_pair, domain=self._domain, api_factory=self._api_factory, throttler=self._throttler, time_synchronizer=self._time_synchronizer) } if limit != 0: params["limit"] = str(limit) data = await web_utils.api_request( path=CONSTANTS.SNAPSHOT_PATH_URL, api_factory=self._api_factory, throttler=self._throttler, time_synchronizer=self._time_synchronizer, domain=self._domain, params=params, method=RESTMethod.GET, ) return data async def _subscribe_channels(self, ws: WSAssistant): """ Subscribes to the trade events and diff orders events through the provided websocket connection. :param ws: the websocket assistant used to connect to the exchange """ try: trade_params = [] depth_params = [] for trading_pair in self._trading_pairs: symbol = await self.exchange_symbol_associated_to_pair( trading_pair=trading_pair, domain=self._domain, api_factory=self._api_factory, throttler=self._throttler, time_synchronizer=self._time_synchronizer) trade_params.append(f"{symbol.lower()}@trade") depth_params.append(f"{symbol.lower()}@depth@100ms") payload = { "method": "SUBSCRIBE", "params": trade_params, "id": 1 } subscribe_trade_request: WSRequest = WSRequest(payload=payload) payload = { "method": "SUBSCRIBE", "params": depth_params, "id": 2 } subscribe_orderbook_request: WSRequest = WSRequest(payload=payload) await ws.send(subscribe_trade_request) await ws.send(subscribe_orderbook_request) self.logger().info("Subscribed to public order book and trade channels...") except asyncio.CancelledError: raise except Exception: self.logger().error( "Unexpected error occurred subscribing to order book trading and delta streams...", exc_info=True ) raise @classmethod async def _get_last_traded_price(cls, trading_pair: str, domain: str, api_factory: WebAssistantsFactory, throttler: AsyncThrottler, time_synchronizer: TimeSynchronizer) -> float: params = { "symbol": await cls.exchange_symbol_associated_to_pair( trading_pair=trading_pair, domain=domain, api_factory=api_factory, throttler=throttler, time_synchronizer=time_synchronizer) } resp_json = await web_utils.api_request( path=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL, api_factory=api_factory, throttler=throttler, time_synchronizer=time_synchronizer, domain=domain, params=params, method=RESTMethod.GET, ) return float(resp_json["lastPrice"]) @classmethod async def _init_trading_pair_symbols( cls, domain: str = CONSTANTS.DEFAULT_DOMAIN, api_factory: Optional[WebAssistantsFactory] = None, throttler: Optional[AsyncThrottler] = None, time_synchronizer: Optional[TimeSynchronizer] = None): """ Initialize mapping of trade symbols in exchange notation to trade symbols in client notation """ mapping = bidict() try: data = await web_utils.api_request( path=CONSTANTS.EXCHANGE_INFO_PATH_URL, api_factory=api_factory, throttler=throttler, time_synchronizer=time_synchronizer, domain=domain, method=RESTMethod.GET, ) for symbol_data in filter(binance_utils.is_exchange_information_valid, data["symbols"]): mapping[symbol_data["symbol"]] = combine_to_hb_trading_pair(base=symbol_data["baseAsset"], quote=symbol_data["quoteAsset"]) except Exception as ex: cls.logger().error(f"There was an error requesting exchange info ({str(ex)})") cls._trading_pair_symbol_map[domain] = mapping
[ "hummingbot.connector.exchange.binance.binance_order_book.BinanceOrderBook.snapshot_message_from_exchange", "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.core.data_type.order_book.OrderBook", "hummingbot.connector.exchange.binance.binance_web_utils.api_request", "hummingbot.core.utils.async_t...
[((1645, 1659), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (1657, 1659), False, 'import asyncio\n'), ((4466, 4499), 'hummingbot.core.utils.async_ttl_cache', 'async_ttl_cache', ([], {'ttl': '(2)', 'maxsize': '(1)'}), '(ttl=2, maxsize=1)\n', (4481, 4499), False, 'from hummingbot.core.utils import async_ttl_cache\n'), ((2472, 2498), 'collections.defaultdict', 'defaultdict', (['asyncio.Queue'], {}), '(asyncio.Queue)\n', (2483, 2498), False, 'from collections import defaultdict\n'), ((12367, 12378), 'time.time', 'time.time', ([], {}), '()\n', (12376, 12378), False, 'import time\n'), ((12420, 12542), 'hummingbot.connector.exchange.binance.binance_order_book.BinanceOrderBook.snapshot_message_from_exchange', 'BinanceOrderBook.snapshot_message_from_exchange', (['snapshot', 'snapshot_timestamp'], {'metadata': "{'trading_pair': trading_pair}"}), "(snapshot,\n snapshot_timestamp, metadata={'trading_pair': trading_pair})\n", (12467, 12542), False, 'from hummingbot.connector.exchange.binance.binance_order_book import BinanceOrderBook\n'), ((23342, 23350), 'bidict.bidict', 'bidict', ([], {}), '()\n', (23348, 23350), False, 'from bidict import bidict\n'), ((2187, 2310), 'hummingbot.connector.exchange.binance.binance_web_utils.build_api_factory', 'web_utils.build_api_factory', ([], {'throttler': 'self._throttler', 'time_synchronizer': 'self._time_synchronizer', 'domain': 'self._domain'}), '(throttler=self._throttler, time_synchronizer=\n self._time_synchronizer, domain=self._domain)\n', (2214, 2310), True, 'from hummingbot.connector.exchange.binance import binance_web_utils as web_utils\n'), ((2404, 2415), 'hummingbot.core.data_type.order_book.OrderBook', 'OrderBook', ([], {}), '()\n', (2413, 2415), False, 'from hummingbot.core.data_type.order_book import OrderBook\n'), ((2616, 2643), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2633, 2643), False, 'import logging\n'), ((4340, 4359), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*tasks'], {}), '(*tasks)\n', (4351, 4359), False, 'from hummingbot.core.utils.async_utils import safe_gather\n'), ((5019, 5128), 'hummingbot.connector.exchange.binance.binance_web_utils.api_request', 'web_utils.api_request', ([], {'path': 'CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL', 'domain': 'domain', 'method': 'RESTMethod.GET'}), '(path=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL, domain=\n domain, method=RESTMethod.GET)\n', (5040, 5128), True, 'from hummingbot.connector.exchange.binance import binance_web_utils as web_utils\n'), ((19736, 19966), 'hummingbot.connector.exchange.binance.binance_web_utils.api_request', 'web_utils.api_request', ([], {'path': 'CONSTANTS.SNAPSHOT_PATH_URL', 'api_factory': 'self._api_factory', 'throttler': 'self._throttler', 'time_synchronizer': 'self._time_synchronizer', 'domain': 'self._domain', 'params': 'params', 'method': 'RESTMethod.GET'}), '(path=CONSTANTS.SNAPSHOT_PATH_URL, api_factory=self.\n _api_factory, throttler=self._throttler, time_synchronizer=self.\n _time_synchronizer, domain=self._domain, params=params, method=\n RESTMethod.GET)\n', (19757, 19966), True, 'from hummingbot.connector.exchange.binance import binance_web_utils as web_utils\n'), ((21100, 21126), 'hummingbot.core.web_assistant.connections.data_types.WSRequest', 'WSRequest', ([], {'payload': 'payload'}), '(payload=payload)\n', (21109, 21126), False, 'from hummingbot.core.web_assistant.connections.data_types import RESTMethod, WSRequest\n'), ((21322, 21348), 'hummingbot.core.web_assistant.connections.data_types.WSRequest', 'WSRequest', ([], {'payload': 'payload'}), '(payload=payload)\n', (21331, 21348), False, 'from hummingbot.core.web_assistant.connections.data_types import RESTMethod, WSRequest\n'), ((22539, 22750), 'hummingbot.connector.exchange.binance.binance_web_utils.api_request', 'web_utils.api_request', ([], {'path': 'CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL', 'api_factory': 'api_factory', 'throttler': 'throttler', 'time_synchronizer': 'time_synchronizer', 'domain': 'domain', 'params': 'params', 'method': 'RESTMethod.GET'}), '(path=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL,\n api_factory=api_factory, throttler=throttler, time_synchronizer=\n time_synchronizer, domain=domain, params=params, method=RESTMethod.GET)\n', (22560, 22750), True, 'from hummingbot.connector.exchange.binance import binance_web_utils as web_utils\n'), ((13764, 13854), 'hummingbot.connector.exchange.binance.binance_order_book.BinanceOrderBook.trade_message_from_exchange', 'BinanceOrderBook.trade_message_from_exchange', (['json_msg', "{'trading_pair': trading_pair}"], {}), "(json_msg, {'trading_pair':\n trading_pair})\n", (13808, 13854), False, 'from hummingbot.connector.exchange.binance.binance_order_book import BinanceOrderBook\n'), ((23390, 23580), 'hummingbot.connector.exchange.binance.binance_web_utils.api_request', 'web_utils.api_request', ([], {'path': 'CONSTANTS.EXCHANGE_INFO_PATH_URL', 'api_factory': 'api_factory', 'throttler': 'throttler', 'time_synchronizer': 'time_synchronizer', 'domain': 'domain', 'method': 'RESTMethod.GET'}), '(path=CONSTANTS.EXCHANGE_INFO_PATH_URL, api_factory=\n api_factory, throttler=throttler, time_synchronizer=time_synchronizer,\n domain=domain, method=RESTMethod.GET)\n', (23411, 23580), True, 'from hummingbot.connector.exchange.binance import binance_web_utils as web_utils\n'), ((23834, 23929), 'hummingbot.connector.utils.combine_to_hb_trading_pair', 'combine_to_hb_trading_pair', ([], {'base': "symbol_data['baseAsset']", 'quote': "symbol_data['quoteAsset']"}), "(base=symbol_data['baseAsset'], quote=symbol_data\n ['quoteAsset'])\n", (23860, 23929), False, 'from hummingbot.connector.utils import combine_to_hb_trading_pair\n'), ((5606, 5618), 'decimal.Decimal', 'Decimal', (['"""2"""'], {}), "('2')\n", (5613, 5618), False, 'from decimal import Decimal\n'), ((15230, 15241), 'time.time', 'time.time', ([], {}), '()\n', (15239, 15241), False, 'import time\n'), ((16420, 16431), 'time.time', 'time.time', ([], {}), '()\n', (16429, 16431), False, 'import time\n'), ((16489, 16611), 'hummingbot.connector.exchange.binance.binance_order_book.BinanceOrderBook.snapshot_message_from_exchange', 'BinanceOrderBook.snapshot_message_from_exchange', (['snapshot', 'snapshot_timestamp'], {'metadata': "{'trading_pair': trading_pair}"}), "(snapshot,\n snapshot_timestamp, metadata={'trading_pair': trading_pair})\n", (16536, 16611), False, 'from hummingbot.connector.exchange.binance.binance_order_book import BinanceOrderBook\n'), ((17876, 17914), 'hummingbot.connector.exchange.binance.binance_constants.WSS_URL.format', 'CONSTANTS.WSS_URL.format', (['self._domain'], {}), '(self._domain)\n', (17900, 17914), True, 'import hummingbot.connector.exchange.binance.binance_constants as CONSTANTS\n')]
""" A collection of utility functions for querying and checking Ethereum data """ import aiohttp from hummingbot.client.config.global_config_map import global_config_map from hummingbot.core.utils import async_ttl_cache import itertools as it import logging from typing import List from web3 import Web3 def is_connected_to_web3(bsc_rpc_url: str) -> bool: """ This is abstracted out of check_web3 to make mock testing easier """ w3: Web3 = Web3(Web3.HTTPProvider(bsc_rpc_url, request_kwargs={"timeout": 2.0})) return w3.isConnected() def check_web3(bsc_rpc_url: str) -> bool: """ Confirm that the provided url is a valid bsc RPC url. """ try: ret = is_connected_to_web3(bsc_rpc_url) except Exception: ret = False if not ret: if bsc_rpc_url.startswith("http://bsc-dataseed.binance.org"): logging.getLogger().warning("You are connecting to an Infura using an insecure network protocol " "(\"http\"), which may not be allowed by Infura. " "Try using \"https://\" instead.") if bsc_rpc_url.startswith("bsc-dataseed.binance.org"): logging.getLogger().warning("Please add \"https://\" to your Infura node url.") return ret def check_transaction_exceptions(trade_data: dict) -> list: """ Check trade data for Binance decentralized exchanges """ exception_list = [] gas_limit = trade_data["gas_limit"] gas_cost = trade_data["gas_cost"] amount = trade_data["amount"] side = trade_data["side"] base = trade_data["base"] quote = trade_data["quote"] balances = trade_data["balances"] allowances = trade_data["allowances"] swaps_message = f"Total swaps: {trade_data['swaps']}" if "swaps" in trade_data.keys() else '' bsc_balance = balances["BSC"] # check for sufficient gas if bsc_balance < gas_cost: exception_list.append(f"Insufficient BSC balance to cover gas:" f" Balance: {bsc_balance}. Est. gas cost: {gas_cost}. {swaps_message}") trade_token = base if side == "side" else quote trade_allowance = allowances[trade_token] # check for gas limit set to low gas_limit_threshold = 21000 if gas_limit < gas_limit_threshold: exception_list.append(f"Gas limit {gas_limit} below recommended {gas_limit_threshold} threshold.") # check for insufficient token allowance if allowances[trade_token] < amount: exception_list.append(f"Insufficient {trade_token} allowance {trade_allowance}. Amount to trade: {amount}") return exception_list async def get_token_list(): """ This is abstracted out of fetch_trading_pairs to make mock testing easier """ token_list_url = global_config_map.get("bsc_token_list_url").value async with aiohttp.ClientSession() as client: resp = await client.get(token_list_url) return await resp.json() @async_ttl_cache(ttl=30) async def fetch_trading_pairs() -> List[str]: """ List of all trading pairs in all permutations, for example: BNB-BUSD,BNB-COVA """ tokens = set() resp_json = await get_token_list() for token in resp_json: tokens.add(token["original_symbol"]) trading_pairs = [] for base, quote in it.permutations(tokens, 2): trading_pairs.append(f"{base}-{quote}") return trading_pairs
[ "hummingbot.core.utils.async_ttl_cache", "hummingbot.client.config.global_config_map.global_config_map.get" ]
[((2997, 3020), 'hummingbot.core.utils.async_ttl_cache', 'async_ttl_cache', ([], {'ttl': '(30)'}), '(ttl=30)\n', (3012, 3020), False, 'from hummingbot.core.utils import async_ttl_cache\n'), ((3346, 3372), 'itertools.permutations', 'it.permutations', (['tokens', '(2)'], {}), '(tokens, 2)\n', (3361, 3372), True, 'import itertools as it\n'), ((464, 527), 'web3.Web3.HTTPProvider', 'Web3.HTTPProvider', (['bsc_rpc_url'], {'request_kwargs': "{'timeout': 2.0}"}), "(bsc_rpc_url, request_kwargs={'timeout': 2.0})\n", (481, 527), False, 'from web3 import Web3\n'), ((2813, 2856), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""bsc_token_list_url"""'], {}), "('bsc_token_list_url')\n", (2834, 2856), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((2878, 2901), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (2899, 2901), False, 'import aiohttp\n'), ((873, 892), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (890, 892), False, 'import logging\n'), ((1212, 1231), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1229, 1231), False, 'import logging\n')]
import unittest import hummingbot.connector.exchange.binance.binance_constants as CONSTANTS from hummingbot.connector.exchange.binance import binance_web_utils as web_utils class BinanceUtilTestCases(unittest.TestCase): def test_public_rest_url(self): path_url = "/TEST_PATH" domain = "com" expected_url = CONSTANTS.REST_URL.format(domain) + CONSTANTS.PUBLIC_API_VERSION + path_url self.assertEqual(expected_url, web_utils.public_rest_url(path_url, domain)) def test_private_rest_url(self): path_url = "/TEST_PATH" domain = "com" expected_url = CONSTANTS.REST_URL.format(domain) + CONSTANTS.PRIVATE_API_VERSION + path_url self.assertEqual(expected_url, web_utils.private_rest_url(path_url, domain))
[ "hummingbot.connector.exchange.binance.binance_web_utils.private_rest_url", "hummingbot.connector.exchange.binance.binance_constants.REST_URL.format", "hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url" ]
[((453, 496), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', (['path_url', 'domain'], {}), '(path_url, domain)\n', (478, 496), True, 'from hummingbot.connector.exchange.binance import binance_web_utils as web_utils\n'), ((730, 774), 'hummingbot.connector.exchange.binance.binance_web_utils.private_rest_url', 'web_utils.private_rest_url', (['path_url', 'domain'], {}), '(path_url, domain)\n', (756, 774), True, 'from hummingbot.connector.exchange.binance import binance_web_utils as web_utils\n'), ((338, 371), 'hummingbot.connector.exchange.binance.binance_constants.REST_URL.format', 'CONSTANTS.REST_URL.format', (['domain'], {}), '(domain)\n', (363, 371), True, 'import hummingbot.connector.exchange.binance.binance_constants as CONSTANTS\n'), ((614, 647), 'hummingbot.connector.exchange.binance.binance_constants.REST_URL.format', 'CONSTANTS.REST_URL.format', (['domain'], {}), '(domain)\n', (639, 647), True, 'import hummingbot.connector.exchange.binance.binance_constants as CONSTANTS\n')]
import sys from hummingbot.core.api_throttler.data_types import RateLimit # REST endpoints BASE_PATH_URL = "https://api.kucoin.com" PUBLIC_WS_DATA_PATH_URL = "/api/v1/bullet-public" PRIVATE_WS_DATA_PATH_URL = "/api/v1/bullet-private" TICKER_PRICE_CHANGE_PATH_URL = "/api/v1/market/allTickers" EXCHANGE_INFO_PATH_URL = "/api/v1/symbols" SNAPSHOT_PATH_URL = "/api/v3/market/orderbook/level2" SNAPSHOT_NO_AUTH_PATH_URL = "/api/v1/market/orderbook/level2_100" ACCOUNTS_PATH_URL = "/api/v1/accounts?type=trade" SERVER_TIME_PATH_URL = "/api/v1/timestamp" SYMBOLS_PATH_URL = "/api/v1/symbols" ORDERS_PATH_URL = "/api/v1/orders" TRADE_ORDERS_ENDPOINT_NAME = "/spotMarket/tradeOrders" BALANCE_ENDPOINT_NAME = "/account/balance" PRIVATE_ENDPOINT_NAMES = [ TRADE_ORDERS_ENDPOINT_NAME, BALANCE_ENDPOINT_NAME, ] WS_CONNECTION_LIMIT_ID = "WSConnection" WS_CONNECTION_LIMIT = 30 WS_CONNECTION_TIME_INTERVAL = 60 WS_REQUEST_LIMIT_ID = "WSRequest" GET_ORDER_LIMIT_ID = "GetOrders" POST_ORDER_LIMIT_ID = "PostOrder" DELETE_ORDER_LIMIT_ID = "DeleteOrder" WS_PING_HEARTBEAT = 10 NO_LIMIT = sys.maxsize RATE_LIMITS = [ RateLimit(WS_CONNECTION_LIMIT_ID, limit=WS_CONNECTION_LIMIT, time_interval=WS_CONNECTION_TIME_INTERVAL), RateLimit(WS_REQUEST_LIMIT_ID, limit=100, time_interval=10), RateLimit(limit_id=PUBLIC_WS_DATA_PATH_URL, limit=NO_LIMIT, time_interval=1), RateLimit(limit_id=PRIVATE_WS_DATA_PATH_URL, limit=NO_LIMIT, time_interval=1), RateLimit(limit_id=TICKER_PRICE_CHANGE_PATH_URL, limit=NO_LIMIT, time_interval=1), RateLimit(limit_id=EXCHANGE_INFO_PATH_URL, limit=NO_LIMIT, time_interval=1), RateLimit(limit_id=SNAPSHOT_PATH_URL, limit=NO_LIMIT, time_interval=1), RateLimit(limit_id=SNAPSHOT_NO_AUTH_PATH_URL, limit=NO_LIMIT, time_interval=1), RateLimit(limit_id=ACCOUNTS_PATH_URL, limit=NO_LIMIT, time_interval=1), RateLimit(limit_id=SERVER_TIME_PATH_URL, limit=NO_LIMIT, time_interval=1), RateLimit(limit_id=GET_ORDER_LIMIT_ID, limit=NO_LIMIT, time_interval=1), RateLimit(limit_id=POST_ORDER_LIMIT_ID, limit=45, time_interval=3), RateLimit(limit_id=DELETE_ORDER_LIMIT_ID, limit=60, time_interval=3), ]
[ "hummingbot.core.api_throttler.data_types.RateLimit" ]
[((1115, 1223), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', (['WS_CONNECTION_LIMIT_ID'], {'limit': 'WS_CONNECTION_LIMIT', 'time_interval': 'WS_CONNECTION_TIME_INTERVAL'}), '(WS_CONNECTION_LIMIT_ID, limit=WS_CONNECTION_LIMIT, time_interval=\n WS_CONNECTION_TIME_INTERVAL)\n', (1124, 1223), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1224, 1283), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', (['WS_REQUEST_LIMIT_ID'], {'limit': '(100)', 'time_interval': '(10)'}), '(WS_REQUEST_LIMIT_ID, limit=100, time_interval=10)\n', (1233, 1283), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1289, 1365), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'PUBLIC_WS_DATA_PATH_URL', 'limit': 'NO_LIMIT', 'time_interval': '(1)'}), '(limit_id=PUBLIC_WS_DATA_PATH_URL, limit=NO_LIMIT, time_interval=1)\n', (1298, 1365), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1371, 1448), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'PRIVATE_WS_DATA_PATH_URL', 'limit': 'NO_LIMIT', 'time_interval': '(1)'}), '(limit_id=PRIVATE_WS_DATA_PATH_URL, limit=NO_LIMIT, time_interval=1)\n', (1380, 1448), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1454, 1539), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'TICKER_PRICE_CHANGE_PATH_URL', 'limit': 'NO_LIMIT', 'time_interval': '(1)'}), '(limit_id=TICKER_PRICE_CHANGE_PATH_URL, limit=NO_LIMIT,\n time_interval=1)\n', (1463, 1539), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1541, 1616), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'EXCHANGE_INFO_PATH_URL', 'limit': 'NO_LIMIT', 'time_interval': '(1)'}), '(limit_id=EXCHANGE_INFO_PATH_URL, limit=NO_LIMIT, time_interval=1)\n', (1550, 1616), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1622, 1692), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'SNAPSHOT_PATH_URL', 'limit': 'NO_LIMIT', 'time_interval': '(1)'}), '(limit_id=SNAPSHOT_PATH_URL, limit=NO_LIMIT, time_interval=1)\n', (1631, 1692), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1698, 1776), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'SNAPSHOT_NO_AUTH_PATH_URL', 'limit': 'NO_LIMIT', 'time_interval': '(1)'}), '(limit_id=SNAPSHOT_NO_AUTH_PATH_URL, limit=NO_LIMIT, time_interval=1)\n', (1707, 1776), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1782, 1852), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'ACCOUNTS_PATH_URL', 'limit': 'NO_LIMIT', 'time_interval': '(1)'}), '(limit_id=ACCOUNTS_PATH_URL, limit=NO_LIMIT, time_interval=1)\n', (1791, 1852), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1858, 1931), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'SERVER_TIME_PATH_URL', 'limit': 'NO_LIMIT', 'time_interval': '(1)'}), '(limit_id=SERVER_TIME_PATH_URL, limit=NO_LIMIT, time_interval=1)\n', (1867, 1931), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((1937, 2008), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'GET_ORDER_LIMIT_ID', 'limit': 'NO_LIMIT', 'time_interval': '(1)'}), '(limit_id=GET_ORDER_LIMIT_ID, limit=NO_LIMIT, time_interval=1)\n', (1946, 2008), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((2014, 2080), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'POST_ORDER_LIMIT_ID', 'limit': '(45)', 'time_interval': '(3)'}), '(limit_id=POST_ORDER_LIMIT_ID, limit=45, time_interval=3)\n', (2023, 2080), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((2086, 2154), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'DELETE_ORDER_LIMIT_ID', 'limit': '(60)', 'time_interval': '(3)'}), '(limit_id=DELETE_ORDER_LIMIT_ID, limit=60, time_interval=3)\n', (2095, 2154), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n')]
import logging from typing import ( List, Optional, ) from hummingbot.connector.exchange.blocktane.blocktane_api_user_stream_data_source import \ BlocktaneAPIUserStreamDataSource from hummingbot.connector.exchange.blocktane.blocktane_auth import BlocktaneAuth from hummingbot.core.data_type.user_stream_tracker import ( UserStreamTracker ) from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from hummingbot.logger import HummingbotLogger class BlocktaneUserStreamTracker(UserStreamTracker): _bust_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._bust_logger is None: cls._bust_logger = logging.getLogger(__name__) return cls._bust_logger def __init__(self, blocktane_auth: Optional[BlocktaneAuth] = None, trading_pairs=None): self._blocktane_auth: BlocktaneAuth = blocktane_auth self._trading_pairs: List[str] = trading_pairs super().__init__(data_source=BlocktaneAPIUserStreamDataSource( blocktane_auth=self._blocktane_auth, trading_pairs=self._trading_pairs)) @property def data_source(self) -> UserStreamTrackerDataSource: if not self._data_source: self._data_source = BlocktaneAPIUserStreamDataSource( blocktane_auth=self._blocktane_auth, trading_pairs=self._trading_pairs ) return self._data_source @property def exchange_name(self) -> str: return "blocktane" async def start(self): self._user_stream_tracking_task = safe_ensure_future( self.data_source.listen_for_user_stream(self._user_stream) ) await safe_gather(self._user_stream_tracking_task)
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.connector.exchange.blocktane.blocktane_api_user_stream_data_source.BlocktaneAPIUserStreamDataSource" ]
[((827, 854), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (844, 854), False, 'import logging\n'), ((1437, 1545), 'hummingbot.connector.exchange.blocktane.blocktane_api_user_stream_data_source.BlocktaneAPIUserStreamDataSource', 'BlocktaneAPIUserStreamDataSource', ([], {'blocktane_auth': 'self._blocktane_auth', 'trading_pairs': 'self._trading_pairs'}), '(blocktane_auth=self._blocktane_auth,\n trading_pairs=self._trading_pairs)\n', (1469, 1545), False, 'from hummingbot.connector.exchange.blocktane.blocktane_api_user_stream_data_source import BlocktaneAPIUserStreamDataSource\n'), ((1868, 1912), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['self._user_stream_tracking_task'], {}), '(self._user_stream_tracking_task)\n', (1879, 1912), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((1167, 1275), 'hummingbot.connector.exchange.blocktane.blocktane_api_user_stream_data_source.BlocktaneAPIUserStreamDataSource', 'BlocktaneAPIUserStreamDataSource', ([], {'blocktane_auth': 'self._blocktane_auth', 'trading_pairs': 'self._trading_pairs'}), '(blocktane_auth=self._blocktane_auth,\n trading_pairs=self._trading_pairs)\n', (1199, 1275), False, 'from hummingbot.connector.exchange.blocktane.blocktane_api_user_stream_data_source import BlocktaneAPIUserStreamDataSource\n')]
import typing from dataclasses import dataclass from typing import Optional from hummingbot.client.config.config_methods import using_exchange from hummingbot.client.config.config_var import ConfigVar from hummingbot.connector.exchange.coinbase_pro import coinbase_pro_constants as CONSTANTS from hummingbot.core.web_assistant.connections.data_types import EndpointRESTRequest from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory if typing.TYPE_CHECKING: from hummingbot.connector.exchange.coinbase_pro.coinbase_pro_auth import CoinbaseProAuth CENTRALIZED = True EXAMPLE_PAIR = "ETH-USDC" DEFAULT_FEES = [0.5, 0.5] KEYS = { "coinbase_pro_api_key": ConfigVar(key="coinbase_pro_api_key", prompt="Enter your Coinbase API key >>> ", required_if=using_exchange("coinbase_pro"), is_secure=True, is_connect_key=True), "coinbase_pro_secret_key": ConfigVar(key="coinbase_pro_secret_key", prompt="Enter your Coinbase secret key >>> ", required_if=using_exchange("coinbase_pro"), is_secure=True, is_connect_key=True), "coinbase_pro_passphrase": ConfigVar(key="coinbase_pro_passphrase", prompt="Enter your Coinbase passphrase >>> ", required_if=using_exchange("coinbase_pro"), is_secure=True, is_connect_key=True), } @dataclass class CoinbaseProRESTRequest(EndpointRESTRequest): def __post_init__(self): super().__post_init__() self._ensure_endpoint_for_auth() @property def base_url(self) -> str: return CONSTANTS.REST_URL def _ensure_endpoint_for_auth(self): if self.is_auth_required and self.endpoint is None: raise ValueError("The endpoint must be specified if authentication is required.") def build_coinbase_pro_web_assistant_factory( auth: Optional['CoinbaseProAuth'] = None ) -> WebAssistantsFactory: """The web-assistant's composition root.""" api_factory = WebAssistantsFactory(auth=auth) return api_factory
[ "hummingbot.core.web_assistant.web_assistants_factory.WebAssistantsFactory", "hummingbot.client.config.config_methods.using_exchange" ]
[((2128, 2159), 'hummingbot.core.web_assistant.web_assistants_factory.WebAssistantsFactory', 'WebAssistantsFactory', ([], {'auth': 'auth'}), '(auth=auth)\n', (2148, 2159), False, 'from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory\n'), ((832, 862), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""coinbase_pro"""'], {}), "('coinbase_pro')\n", (846, 862), False, 'from hummingbot.client.config.config_methods import using_exchange\n'), ((1112, 1142), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""coinbase_pro"""'], {}), "('coinbase_pro')\n", (1126, 1142), False, 'from hummingbot.client.config.config_methods import using_exchange\n'), ((1392, 1422), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""coinbase_pro"""'], {}), "('coinbase_pro')\n", (1406, 1422), False, 'from hummingbot.client.config.config_methods import using_exchange\n')]
from typing import ( List, Tuple ) from decimal import Decimal from hummingbot.client.config.global_config_map import global_config_map from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_pair import CrossExchangeMarketPair from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making import CrossExchangeMarketMakingStrategy from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import \ cross_exchange_market_making_config_map as xemm_map def start(self): maker_market = xemm_map.get("maker_market").value.lower() taker_market = xemm_map.get("taker_market").value.lower() raw_maker_trading_pair = xemm_map.get("maker_market_trading_pair").value raw_taker_trading_pair = xemm_map.get("taker_market_trading_pair").value triangular_arbitrage_pair = xemm_map.get("triangular_arbitrage_pair").value min_profitability = xemm_map.get("min_profitability").value / Decimal("100") order_amount = xemm_map.get("order_amount").value strategy_report_interval = global_config_map.get("strategy_report_interval").value limit_order_min_expiration = xemm_map.get("limit_order_min_expiration").value cancel_order_threshold = xemm_map.get("cancel_order_threshold").value / Decimal("100") active_order_canceling = xemm_map.get("active_order_canceling").value adjust_order_enabled = xemm_map.get("adjust_order_enabled").value top_depth_tolerance = xemm_map.get("top_depth_tolerance").value top_depth_tolerance_taker = xemm_map.get("top_depth_tolerance_taker").value order_size_taker_volume_factor = xemm_map.get("order_size_taker_volume_factor").value / Decimal("100") order_size_taker_balance_factor = xemm_map.get("order_size_taker_balance_factor").value / Decimal("100") order_size_portfolio_ratio_limit = xemm_map.get("order_size_portfolio_ratio_limit").value / Decimal("100") order_size_maker_balance_factor = xemm_map.get("order_size_maker_balance_factor").value / Decimal("100") anti_hysteresis_duration = xemm_map.get("anti_hysteresis_duration").value filled_order_delay = xemm_map.get("filled_order_delay").value filled_order_delay_seconds = xemm_map.get("filled_order_delay_seconds").value use_oracle_conversion_rate = xemm_map.get("use_oracle_conversion_rate").value taker_to_maker_base_conversion_rate = xemm_map.get("taker_to_maker_base_conversion_rate").value taker_to_maker_quote_conversion_rate = xemm_map.get("taker_to_maker_quote_conversion_rate").value slippage_buffer = xemm_map.get("slippage_buffer").value / Decimal("100") min_order_amount = xemm_map.get("min_order_amount").value target_base_balance = xemm_map.get("target_base_balance").value slippage_buffer_fix = xemm_map.get("slippage_buffer_fix").value / Decimal("100") waiting_time = xemm_map.get("waiting_time").value keep_target_balance = xemm_map.get("keep_target_balance").value triangular_arbitrage = xemm_map.get("triangular_arbitrage").value triangular_switch = xemm_map.get("triangular_switch").value cancel_order_timer = xemm_map.get("cancel_order_timer").value cancel_order_timer_seconds = xemm_map.get("cancel_order_timer_seconds").value counter = 0 fix_counter = 0 taker_to_maker_base_conversion_rate = xemm_map.get("taker_to_maker_base_conversion_rate").value # check if top depth tolerance is a list or if trade size override exists if isinstance(top_depth_tolerance, list) or "trade_size_override" in xemm_map: self._notify("Current config is not compatible with cross exchange market making strategy. Please reconfigure") return try: maker_trading_pair: str = raw_maker_trading_pair taker_trading_pair: str = raw_taker_trading_pair third_trading_pair: str = triangular_arbitrage_pair maker_assets: Tuple[str, str] = self._initialize_market_assets(maker_market, [maker_trading_pair])[0] taker_assets: Tuple[str, str] = self._initialize_market_assets(taker_market, [taker_trading_pair])[0] if triangular_switch: third_assets: Tuple[str, str] = self._initialize_market_assets(maker_market, [third_trading_pair])[0] else: third_assets: Tuple[str, str] = self._initialize_market_assets(taker_market, [third_trading_pair])[0] except ValueError as e: self._notify(str(e)) return market_names: List[Tuple[str, List[str]]] = [ (maker_market, [maker_trading_pair]), (taker_market, [taker_trading_pair]), (maker_market, [third_trading_pair]), ] market_name: List[Tuple[str, List[str]]] = [ (maker_market, [maker_trading_pair]), (taker_market, [taker_trading_pair]), ] if triangular_arbitrage: self._initialize_markets(market_names) else: self._initialize_markets(market_name) maker_data = [self.markets[maker_market], maker_trading_pair] + list(maker_assets) taker_data = [self.markets[taker_market], taker_trading_pair] + list(taker_assets) third_data = [self.markets[maker_market], third_trading_pair] + list(third_assets) maker_market_trading_pair_tuple = MarketTradingPairTuple(*maker_data) taker_market_trading_pair_tuple = MarketTradingPairTuple(*taker_data) third_market_trading_pair_tuple = MarketTradingPairTuple(*third_data) self.market_trading_pair_tuples = [maker_market_trading_pair_tuple, taker_market_trading_pair_tuple, third_market_trading_pair_tuple] self.market_pair = CrossExchangeMarketPair(maker=maker_market_trading_pair_tuple, taker=taker_market_trading_pair_tuple) strategy_logging_options = ( CrossExchangeMarketMakingStrategy.OPTION_LOG_CREATE_ORDER | CrossExchangeMarketMakingStrategy.OPTION_LOG_ADJUST_ORDER | CrossExchangeMarketMakingStrategy.OPTION_LOG_MAKER_ORDER_FILLED | CrossExchangeMarketMakingStrategy.OPTION_LOG_REMOVING_ORDER | CrossExchangeMarketMakingStrategy.OPTION_LOG_STATUS_REPORT | CrossExchangeMarketMakingStrategy.OPTION_LOG_MAKER_ORDER_HEDGED ) self.strategy = CrossExchangeMarketMakingStrategy() self.strategy.init_params( market_pairs=[self.market_pair], third_market=third_market_trading_pair_tuple, min_profitability=min_profitability, status_report_interval=strategy_report_interval, logging_options=strategy_logging_options, order_amount=order_amount, limit_order_min_expiration=limit_order_min_expiration, cancel_order_threshold=cancel_order_threshold, active_order_canceling=active_order_canceling, adjust_order_enabled=adjust_order_enabled, top_depth_tolerance=top_depth_tolerance, top_depth_tolerance_taker=top_depth_tolerance_taker, order_size_taker_volume_factor=order_size_taker_volume_factor, order_size_taker_balance_factor=order_size_taker_balance_factor, order_size_portfolio_ratio_limit=order_size_portfolio_ratio_limit, order_size_maker_balance_factor=order_size_maker_balance_factor, anti_hysteresis_duration=anti_hysteresis_duration, filled_order_delay=filled_order_delay, filled_order_delay_seconds=filled_order_delay_seconds, use_oracle_conversion_rate=use_oracle_conversion_rate, taker_to_maker_base_conversion_rate=taker_to_maker_base_conversion_rate, taker_to_maker_quote_conversion_rate=taker_to_maker_quote_conversion_rate, slippage_buffer=slippage_buffer, target_base_balance=target_base_balance, slippage_buffer_fix = slippage_buffer_fix, waiting_time = waiting_time, keep_target_balance = keep_target_balance, min_order_amount=min_order_amount, hb_app_notification=True, counter = counter, cancel_order_timer = cancel_order_timer, cancel_order_timer_seconds = cancel_order_timer_seconds, triangular_arbitrage = triangular_arbitrage, triangular_switch = triangular_switch, fix_counter = fix_counter )
[ "hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making.CrossExchangeMarketMakingStrategy", "hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple", "hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_pair.CrossExchangeMarketPair", "hummingbot.client.c...
[((5282, 5317), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['*maker_data'], {}), '(*maker_data)\n', (5304, 5317), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((5356, 5391), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['*taker_data'], {}), '(*taker_data)\n', (5378, 5391), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((5430, 5465), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['*third_data'], {}), '(*third_data)\n', (5452, 5465), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((5628, 5734), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_pair.CrossExchangeMarketPair', 'CrossExchangeMarketPair', ([], {'maker': 'maker_market_trading_pair_tuple', 'taker': 'taker_market_trading_pair_tuple'}), '(maker=maker_market_trading_pair_tuple, taker=\n taker_market_trading_pair_tuple)\n', (5651, 5734), False, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_pair import CrossExchangeMarketPair\n'), ((6211, 6246), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making.CrossExchangeMarketMakingStrategy', 'CrossExchangeMarketMakingStrategy', ([], {}), '()\n', (6244, 6246), False, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making import CrossExchangeMarketMakingStrategy\n'), ((792, 833), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""maker_market_trading_pair"""'], {}), "('maker_market_trading_pair')\n", (804, 833), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((869, 910), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""taker_market_trading_pair"""'], {}), "('taker_market_trading_pair')\n", (881, 910), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((949, 990), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""triangular_arbitrage_pair"""'], {}), "('triangular_arbitrage_pair')\n", (961, 990), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1063, 1077), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (1070, 1077), False, 'from decimal import Decimal\n'), ((1097, 1125), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""order_amount"""'], {}), "('order_amount')\n", (1109, 1125), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1163, 1212), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""strategy_report_interval"""'], {}), "('strategy_report_interval')\n", (1184, 1212), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((1252, 1294), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""limit_order_min_expiration"""'], {}), "('limit_order_min_expiration')\n", (1264, 1294), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1377, 1391), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (1384, 1391), False, 'from decimal import Decimal\n'), ((1421, 1459), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""active_order_canceling"""'], {}), "('active_order_canceling')\n", (1433, 1459), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1493, 1529), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""adjust_order_enabled"""'], {}), "('adjust_order_enabled')\n", (1505, 1529), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1562, 1597), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""top_depth_tolerance"""'], {}), "('top_depth_tolerance')\n", (1574, 1597), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1636, 1677), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""top_depth_tolerance_taker"""'], {}), "('top_depth_tolerance_taker')\n", (1648, 1677), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1776, 1790), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (1783, 1790), False, 'from decimal import Decimal\n'), ((1885, 1899), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (1892, 1899), False, 'from decimal import Decimal\n'), ((1996, 2010), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (2003, 2010), False, 'from decimal import Decimal\n'), ((2105, 2119), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (2112, 2119), False, 'from decimal import Decimal\n'), ((2151, 2191), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""anti_hysteresis_duration"""'], {}), "('anti_hysteresis_duration')\n", (2163, 2191), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2223, 2257), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""filled_order_delay"""'], {}), "('filled_order_delay')\n", (2235, 2257), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2297, 2339), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""filled_order_delay_seconds"""'], {}), "('filled_order_delay_seconds')\n", (2309, 2339), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2379, 2421), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""use_oracle_conversion_rate"""'], {}), "('use_oracle_conversion_rate')\n", (2391, 2421), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2470, 2521), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""taker_to_maker_base_conversion_rate"""'], {}), "('taker_to_maker_base_conversion_rate')\n", (2482, 2521), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2571, 2623), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""taker_to_maker_quote_conversion_rate"""'], {}), "('taker_to_maker_quote_conversion_rate')\n", (2583, 2623), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2692, 2706), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (2699, 2706), False, 'from decimal import Decimal\n'), ((2730, 2762), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""min_order_amount"""'], {}), "('min_order_amount')\n", (2742, 2762), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2795, 2830), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""target_base_balance"""'], {}), "('target_base_balance')\n", (2807, 2830), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2907, 2921), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (2914, 2921), False, 'from decimal import Decimal\n'), ((2941, 2969), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""waiting_time"""'], {}), "('waiting_time')\n", (2953, 2969), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((3002, 3037), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""keep_target_balance"""'], {}), "('keep_target_balance')\n", (3014, 3037), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((3071, 3107), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""triangular_arbitrage"""'], {}), "('triangular_arbitrage')\n", (3083, 3107), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((3138, 3171), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""triangular_switch"""'], {}), "('triangular_switch')\n", (3150, 3171), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((3203, 3237), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""cancel_order_timer"""'], {}), "('cancel_order_timer')\n", (3215, 3237), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((3277, 3319), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""cancel_order_timer_seconds"""'], {}), "('cancel_order_timer_seconds')\n", (3289, 3319), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((3404, 3455), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""taker_to_maker_base_conversion_rate"""'], {}), "('taker_to_maker_base_conversion_rate')\n", (3416, 3455), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1021, 1054), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""min_profitability"""'], {}), "('min_profitability')\n", (1033, 1054), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1330, 1368), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""cancel_order_threshold"""'], {}), "('cancel_order_threshold')\n", (1342, 1368), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1721, 1767), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""order_size_taker_volume_factor"""'], {}), "('order_size_taker_volume_factor')\n", (1733, 1767), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1829, 1876), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""order_size_taker_balance_factor"""'], {}), "('order_size_taker_balance_factor')\n", (1841, 1876), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((1939, 1987), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""order_size_portfolio_ratio_limit"""'], {}), "('order_size_portfolio_ratio_limit')\n", (1951, 1987), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2049, 2096), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""order_size_maker_balance_factor"""'], {}), "('order_size_maker_balance_factor')\n", (2061, 2096), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2652, 2683), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""slippage_buffer"""'], {}), "('slippage_buffer')\n", (2664, 2683), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((2863, 2898), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""slippage_buffer_fix"""'], {}), "('slippage_buffer_fix')\n", (2875, 2898), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((658, 686), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""maker_market"""'], {}), "('maker_market')\n", (670, 686), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n'), ((720, 748), 'hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map.cross_exchange_market_making_config_map.get', 'xemm_map.get', (['"""taker_market"""'], {}), "('taker_market')\n", (732, 748), True, 'from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import cross_exchange_market_making_config_map as xemm_map\n')]
import asyncio import unittest from collections import Awaitable from copy import deepcopy from unittest.mock import patch, MagicMock from hummingbot.client.config.config_helpers import read_system_configs_from_yml from hummingbot.client.config.global_config_map import global_config_map from hummingbot.client.hummingbot_application import HummingbotApplication from test.mock.mock_paper_exchange import MockPaperExchange class OrderBookCommandTest(unittest.TestCase): @patch("hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher") def setUp(self, _: MagicMock) -> None: super().setUp() self.ev_loop = asyncio.get_event_loop() self.async_run_with_timeout(read_system_configs_from_yml()) self.app = HummingbotApplication() self.global_config_backup = deepcopy(global_config_map) def tearDown(self) -> None: self.reset_global_config() super().tearDown() def async_run_with_timeout(self, coroutine: Awaitable, timeout: float = 1): ret = self.ev_loop.run_until_complete(asyncio.wait_for(coroutine, timeout)) return ret def reset_global_config(self): for key, value in self.global_config_backup.items(): global_config_map[key] = value @patch("hummingbot.client.hummingbot_application.HummingbotApplication._notify") def test_show_order_book(self, notify_mock): global_config_map["tables_format"].value = "psql" captures = [] notify_mock.side_effect = lambda s: captures.append(s) exchange_name = "paper" exchange = MockPaperExchange() self.app.markets[exchange_name] = exchange trading_pair = "BTC-USDT" exchange.set_balanced_order_book( trading_pair, mid_price=10, min_price=8.5, max_price=11.5, price_step_size=1, volume_step_size=1, ) self.async_run_with_timeout(self.app.show_order_book(exchange=exchange_name, live=False)) self.assertEqual(1, len(captures)) df_str_expected = ( " market: MockPaperExchange BTC-USDT" "\n +-------------+--------------+-------------+--------------+" "\n | bid_price | bid_volume | ask_price | ask_volume |" "\n |-------------+--------------+-------------+--------------|" "\n | 9.5 | 1 | 10.5 | 1 |" "\n | 8.5 | 2 | 11.5 | 2 |" "\n +-------------+--------------+-------------+--------------+" ) self.assertEqual(df_str_expected, captures[0])
[ "hummingbot.client.config.config_helpers.read_system_configs_from_yml", "hummingbot.client.hummingbot_application.HummingbotApplication" ]
[((478, 548), 'unittest.mock.patch', 'patch', (['"""hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher"""'], {}), "('hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher')\n", (483, 548), False, 'from unittest.mock import patch, MagicMock\n'), ((1266, 1345), 'unittest.mock.patch', 'patch', (['"""hummingbot.client.hummingbot_application.HummingbotApplication._notify"""'], {}), "('hummingbot.client.hummingbot_application.HummingbotApplication._notify')\n", (1271, 1345), False, 'from unittest.mock import patch, MagicMock\n'), ((639, 663), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (661, 663), False, 'import asyncio\n'), ((753, 776), 'hummingbot.client.hummingbot_application.HummingbotApplication', 'HummingbotApplication', ([], {}), '()\n', (774, 776), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((813, 840), 'copy.deepcopy', 'deepcopy', (['global_config_map'], {}), '(global_config_map)\n', (821, 840), False, 'from copy import deepcopy\n'), ((1591, 1610), 'test.mock.mock_paper_exchange.MockPaperExchange', 'MockPaperExchange', ([], {}), '()\n', (1608, 1610), False, 'from test.mock.mock_paper_exchange import MockPaperExchange\n'), ((701, 731), 'hummingbot.client.config.config_helpers.read_system_configs_from_yml', 'read_system_configs_from_yml', ([], {}), '()\n', (729, 731), False, 'from hummingbot.client.config.config_helpers import read_system_configs_from_yml\n'), ((1063, 1099), 'asyncio.wait_for', 'asyncio.wait_for', (['coroutine', 'timeout'], {}), '(coroutine, timeout)\n', (1079, 1099), False, 'import asyncio\n')]
from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_validators import is_exchange, is_valid_market_symbol from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS def maker_symbol_prompt(): maker_market = cross_exchange_market_making_config_map.get("maker_market").value example = EXAMPLE_PAIRS.get(maker_market) return "Enter the token symbol you would like to trade on %s%s >>> " % ( maker_market, f" (e.g. {example})" if example else "", ) def taker_symbol_prompt(): taker_market = cross_exchange_market_making_config_map.get("taker_market").value example = EXAMPLE_PAIRS.get(taker_market) return "Enter the token symbol you would like to trade on %s%s >>> " % ( taker_market, f" (e.g. {example})" if example else "", ) # strategy specific validators def is_valid_maker_market_symbol(value: str) -> bool: maker_market = cross_exchange_market_making_config_map.get("maker_market").value return is_valid_market_symbol(maker_market, value) def is_valid_taker_market_symbol(value: str) -> bool: taker_market = cross_exchange_market_making_config_map.get("taker_market").value return is_valid_market_symbol(taker_market, value) cross_exchange_market_making_config_map = { "maker_market": ConfigVar( key="maker_market", prompt="Enter your maker exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value), ), "taker_market": ConfigVar( key="taker_market", prompt="Enter your taker exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value), ), "maker_market_symbol": ConfigVar( key="maker_market_symbol", prompt=maker_symbol_prompt, validator=is_valid_maker_market_symbol ), "taker_market_symbol": ConfigVar( key="taker_market_symbol", prompt=taker_symbol_prompt, validator=is_valid_taker_market_symbol ), "min_profitability": ConfigVar( key="min_profitability", prompt="What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> ", type_str="float", ), "order_amount": ConfigVar( key="order_amount", prompt="What is your preferred trade size? (denominated in the base asset) >>> ", default=0.0, type_str="float", ), "adjust_order_enabled": ConfigVar( key="adjust_order_enabled", prompt="", default=True, type_str="bool", required_if=lambda: False, ), "active_order_canceling": ConfigVar( key="active_order_canceling", prompt="", type_str="bool", default=True, required_if=lambda: False, ), # Setting the default threshold to 0.05 when to active_order_canceling is disabled # prevent canceling orders after it has expired "cancel_order_threshold": ConfigVar( key="cancel_order_threshold", prompt="", default=0.05, type_str="float", required_if=lambda: False, ), "limit_order_min_expiration": ConfigVar( key="limit_order_min_expiration", prompt="", default=130.0, type_str="float", required_if=lambda: False, ), "top_depth_tolerance": ConfigVar( key="top_depth_tolerance", prompt="", default=0, type_str="float", required_if=lambda: False, ), "anti_hysteresis_duration": ConfigVar( key="anti_hysteresis_duration", prompt="", default=60, type_str="float", required_if=lambda: False, ), "order_size_taker_volume_factor": ConfigVar( key="order_size_taker_volume_factor", prompt="", default=0.25, type_str="float", required_if=lambda: False, ), "order_size_taker_balance_factor": ConfigVar( key="order_size_taker_balance_factor", prompt="", default=0.995, type_str="float", required_if=lambda: False, ), "order_size_portfolio_ratio_limit": ConfigVar( key="order_size_taker_balance_factor", prompt="", default=0.1667, type_str="float", required_if=lambda: False, ) }
[ "hummingbot.client.settings.EXAMPLE_PAIRS.get", "hummingbot.client.settings.required_exchanges.append", "hummingbot.client.config.config_var.ConfigVar", "hummingbot.client.config.config_validators.is_valid_market_symbol" ]
[((350, 381), 'hummingbot.client.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['maker_market'], {}), '(maker_market)\n', (367, 381), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((664, 695), 'hummingbot.client.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['taker_market'], {}), '(taker_market)\n', (681, 695), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1033, 1076), 'hummingbot.client.config.config_validators.is_valid_market_symbol', 'is_valid_market_symbol', (['maker_market', 'value'], {}), '(maker_market, value)\n', (1055, 1076), False, 'from hummingbot.client.config.config_validators import is_exchange, is_valid_market_symbol\n'), ((1229, 1272), 'hummingbot.client.config.config_validators.is_valid_market_symbol', 'is_valid_market_symbol', (['taker_market', 'value'], {}), '(taker_market, value)\n', (1251, 1272), False, 'from hummingbot.client.config.config_validators import is_exchange, is_valid_market_symbol\n'), ((1786, 1895), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""maker_market_symbol"""', 'prompt': 'maker_symbol_prompt', 'validator': 'is_valid_maker_market_symbol'}), "(key='maker_market_symbol', prompt=maker_symbol_prompt, validator=\n is_valid_maker_market_symbol)\n", (1795, 1895), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((1933, 2042), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""taker_market_symbol"""', 'prompt': 'taker_symbol_prompt', 'validator': 'is_valid_taker_market_symbol'}), "(key='taker_market_symbol', prompt=taker_symbol_prompt, validator=\n is_valid_taker_market_symbol)\n", (1942, 2042), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((2078, 2242), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""min_profitability"""', 'prompt': '"""What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> """', 'type_str': '"""float"""'}), "(key='min_profitability', prompt=\n 'What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> '\n , type_str='float')\n", (2087, 2242), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((2285, 2436), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""order_amount"""', 'prompt': '"""What is your preferred trade size? (denominated in the base asset) >>> """', 'default': '(0.0)', 'type_str': '"""float"""'}), "(key='order_amount', prompt=\n 'What is your preferred trade size? (denominated in the base asset) >>> ',\n default=0.0, type_str='float')\n", (2294, 2436), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((2496, 2608), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""adjust_order_enabled"""', 'prompt': '""""""', 'default': '(True)', 'type_str': '"""bool"""', 'required_if': '(lambda : False)'}), "(key='adjust_order_enabled', prompt='', default=True, type_str=\n 'bool', required_if=lambda : False)\n", (2505, 2608), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((2681, 2795), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""active_order_canceling"""', 'prompt': '""""""', 'type_str': '"""bool"""', 'default': '(True)', 'required_if': '(lambda : False)'}), "(key='active_order_canceling', prompt='', type_str='bool', default\n =True, required_if=lambda : False)\n", (2690, 2795), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3007, 3122), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""cancel_order_threshold"""', 'prompt': '""""""', 'default': '(0.05)', 'type_str': '"""float"""', 'required_if': '(lambda : False)'}), "(key='cancel_order_threshold', prompt='', default=0.05, type_str=\n 'float', required_if=lambda : False)\n", (3016, 3122), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3199, 3318), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""limit_order_min_expiration"""', 'prompt': '""""""', 'default': '(130.0)', 'type_str': '"""float"""', 'required_if': '(lambda : False)'}), "(key='limit_order_min_expiration', prompt='', default=130.0,\n type_str='float', required_if=lambda : False)\n", (3208, 3318), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3389, 3497), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""top_depth_tolerance"""', 'prompt': '""""""', 'default': '(0)', 'type_str': '"""float"""', 'required_if': '(lambda : False)'}), "(key='top_depth_tolerance', prompt='', default=0, type_str='float',\n required_if=lambda : False)\n", (3398, 3497), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3573, 3688), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""anti_hysteresis_duration"""', 'prompt': '""""""', 'default': '(60)', 'type_str': '"""float"""', 'required_if': '(lambda : False)'}), "(key='anti_hysteresis_duration', prompt='', default=60, type_str=\n 'float', required_if=lambda : False)\n", (3582, 3688), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3769, 3891), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""order_size_taker_volume_factor"""', 'prompt': '""""""', 'default': '(0.25)', 'type_str': '"""float"""', 'required_if': '(lambda : False)'}), "(key='order_size_taker_volume_factor', prompt='', default=0.25,\n type_str='float', required_if=lambda : False)\n", (3778, 3891), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3974, 4098), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""order_size_taker_balance_factor"""', 'prompt': '""""""', 'default': '(0.995)', 'type_str': '"""float"""', 'required_if': '(lambda : False)'}), "(key='order_size_taker_balance_factor', prompt='', default=0.995,\n type_str='float', required_if=lambda : False)\n", (3983, 4098), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((4182, 4307), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""order_size_taker_balance_factor"""', 'prompt': '""""""', 'default': '(0.1667)', 'type_str': '"""float"""', 'required_if': '(lambda : False)'}), "(key='order_size_taker_balance_factor', prompt='', default=0.1667,\n type_str='float', required_if=lambda : False)\n", (4191, 4307), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((1498, 1530), 'hummingbot.client.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (1523, 1530), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1718, 1750), 'hummingbot.client.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (1743, 1750), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n')]
import aioprocessing from dataclasses import dataclass from decimal import Decimal import os from pathlib import Path from typing import Optional, Any, Dict, AsyncIterable, List from hummingbot.core.event.events import TradeType from hummingbot.core.utils import detect_available_port _default_paths: Optional["GatewayPaths"] = None _hummingbot_pipe: Optional[aioprocessing.AioConnection] = None GATEWAY_DOCKER_REPO: str = "coinalpha/gateway-v2-dev" GATEWAY_DOCKER_TAG: str = "20220401-arm" if os.uname().machine in {"arm64", "aarch64"} else "20220329" S_DECIMAL_0: Decimal = Decimal(0) def is_inside_docker() -> bool: """ Checks whether this Hummingbot instance is running inside a container. :return: True if running inside container, False otherwise. """ if os.name != "posix": return False try: with open("/proc/1/cmdline", "rb") as fd: cmdline_txt: bytes = fd.read() return b"quickstart" in cmdline_txt except Exception: return False def get_gateway_container_name() -> str: """ Calculates the name for the gateway container, for this Hummingbot instance. :return: Gateway container name """ from hummingbot.client.config.global_config_map import global_config_map instance_id_suffix: str = global_config_map["instance_id"].value[:8] return f"hummingbot-gateway-{instance_id_suffix}" @dataclass class GatewayPaths: """ Represents the local paths and Docker mount paths for a gateway container's conf, certs and logs directories. Local paths represent where Hummingbot client sees the paths from the perspective of its local environment. If Hummingbot is being run from source, then the local environment is the same as the host environment. However, if Hummingbot is being run as a container, then the local environment is the container's environment. Mount paths represent where the gateway container's paths are located on the host environment. If Hummingbot is being run from source, then these should be the same as the local paths. However, if Hummingbot is being run as a container - then these must be fed to it from external sources (e.g. environment variables), since containers generally only have very restricted access to the host filesystem. """ local_conf_path: Path local_certs_path: Path local_logs_path: Path mount_conf_path: Path mount_certs_path: Path mount_logs_path: Path def __post_init__(self): """ Ensure the local paths are created when a GatewayPaths object is created. """ for path in [self.local_conf_path, self.local_certs_path, self.local_logs_path]: path.mkdir(mode=0o755, parents=True, exist_ok=True) def get_gateway_paths() -> GatewayPaths: """ Calculates the default paths for a gateway container. For Hummingbot running from source, the gateway files are to be stored in ~/.hummingbot-gateway/<container name>/ For Hummingbot running inside container, the gateway files are to be stored in ~/.hummingbot-gateway/ locally; and inside the paths pointed to be CERTS_FOLDER, GATEWAY_CONF_FOLDER, GATEWAY_LOGS_FOLDER environment variables on the host system. """ global _default_paths if _default_paths is not None: return _default_paths inside_docker: bool = is_inside_docker() gateway_container_name: str = get_gateway_container_name() external_certs_path: Optional[Path] = os.getenv("CERTS_FOLDER") and Path(os.getenv("CERTS_FOLDER")) external_conf_path: Optional[Path] = os.getenv("GATEWAY_CONF_FOLDER") and Path(os.getenv("GATEWAY_CONF_FOLDER")) external_logs_path: Optional[Path] = os.getenv("GATEWAY_LOGS_FOLDER") and Path(os.getenv("GATEWAY_LOGS_FOLDER")) if inside_docker and not (external_certs_path and external_conf_path and external_logs_path): raise EnvironmentError("CERTS_FOLDER, GATEWAY_CONF_FOLDER and GATEWAY_LOGS_FOLDER must be defined when " "running as container.") base_path: Path = ( Path.home().joinpath(".hummingbot-gateway") if inside_docker else Path.home().joinpath(f".hummingbot-gateway/{gateway_container_name}") ) local_certs_path: Path = base_path.joinpath("certs") local_conf_path: Path = base_path.joinpath("conf") local_logs_path: Path = base_path.joinpath("logs") mount_certs_path: Path = external_certs_path or local_certs_path mount_conf_path: Path = external_conf_path or local_conf_path mount_logs_path: Path = external_logs_path or local_logs_path _default_paths = GatewayPaths( local_conf_path=local_conf_path, local_certs_path=local_certs_path, local_logs_path=local_logs_path, mount_conf_path=mount_conf_path, mount_certs_path=mount_certs_path, mount_logs_path=mount_logs_path ) return _default_paths def get_default_gateway_port() -> int: from hummingbot.client.config.global_config_map import global_config_map return detect_available_port(16000 + int(global_config_map.get("instance_id").value[:4], 16) % 16000) def set_hummingbot_pipe(conn: aioprocessing.AioConnection): global _hummingbot_pipe _hummingbot_pipe = conn async def detect_existing_gateway_container() -> Optional[Dict[str, Any]]: try: results: List[Dict[str, Any]] = await docker_ipc( "containers", all=True, filters={ "name": get_gateway_container_name(), }) if len(results) > 0: return results[0] return except Exception: return async def start_existing_gateway_container(): container_info: Optional[Dict[str, Any]] = await detect_existing_gateway_container() if container_info is not None and container_info["State"] != "running": await docker_ipc("start", get_gateway_container_name()) async def docker_ipc(method_name: str, *args, **kwargs) -> Any: from hummingbot.client.hummingbot_application import HummingbotApplication global _hummingbot_pipe if _hummingbot_pipe is None: raise RuntimeError("Not in the main process, or hummingbot wasn't started via `fork_and_start()`.") try: _hummingbot_pipe.send((method_name, args, kwargs)) data = await _hummingbot_pipe.coro_recv() if isinstance(data, Exception): HummingbotApplication.main_application().notify( "\nError: Unable to communicate with docker socket. " "\nEnsure dockerd is running and /var/run/docker.sock exists, then restart Hummingbot.") raise data return data except Exception as e: # unable to communicate with docker socket HummingbotApplication.main_application().notify( "\nError: Unable to communicate with docker socket. " "\nEnsure dockerd is running and /var/run/docker.sock exists, then restart Hummingbot.") raise e async def docker_ipc_with_generator(method_name: str, *args, **kwargs) -> AsyncIterable[str]: from hummingbot.client.hummingbot_application import HummingbotApplication global _hummingbot_pipe if _hummingbot_pipe is None: raise RuntimeError("Not in the main process, or hummingbot wasn't started via `fork_and_start()`.") try: _hummingbot_pipe.send((method_name, args, kwargs)) while True: data = await _hummingbot_pipe.coro_recv() if data is None: break if isinstance(data, Exception): HummingbotApplication.main_application().notify( "\nError: Unable to communicate with docker socket. " "\nEnsure dockerd is running and /var/run/docker.sock exists, then restart Hummingbot.") raise data yield data except Exception as e: # unable to communicate with docker socket HummingbotApplication.main_application().notify( "\nError: Unable to communicate with docker socket. " "\nEnsure dockerd is running and /var/run/docker.sock exists, then restart Hummingbot.") raise e def check_transaction_exceptions( allowances: Dict[str, Decimal], balances: Dict[str, Decimal], base_asset: str, quote_asset: str, amount: Decimal, side: TradeType, gas_limit: int, gas_cost: Decimal, gas_asset: str, swaps_count: int ) -> List[str]: """ Check trade data for Ethereum decentralized exchanges """ exception_list = [] swaps_message: str = f"Total swaps: {swaps_count}" gas_asset_balance: Decimal = balances.get(gas_asset, S_DECIMAL_0) # check for sufficient gas if gas_asset_balance < gas_cost: exception_list.append(f"Insufficient {gas_asset} balance to cover gas:" f" Balance: {gas_asset_balance}. Est. gas cost: {gas_cost}. {swaps_message}") asset_out: str = quote_asset if side is TradeType.BUY else base_asset asset_out_allowance: Decimal = allowances.get(asset_out, S_DECIMAL_0) # check for gas limit set to low gas_limit_threshold: int = 21000 if gas_limit < gas_limit_threshold: exception_list.append(f"Gas limit {gas_limit} below recommended {gas_limit_threshold} threshold.") # check for insufficient token allowance if allowances[asset_out] < amount: exception_list.append(f"Insufficient {asset_out} allowance {asset_out_allowance}. Amount to trade: {amount}") return exception_list async def start_gateway(): from hummingbot.client.hummingbot_application import HummingbotApplication try: response = await docker_ipc( "containers", all=True, filters={"name": get_gateway_container_name()} ) if len(response) == 0: raise ValueError(f"Gateway container {get_gateway_container_name()} not found. ") container_info = response[0] if container_info["State"] == "running": HummingbotApplication.main_application().notify(f"Gateway container {container_info['Id']} already running.") return await docker_ipc( "start", container=container_info["Id"] ) HummingbotApplication.main_application().notify(f"Gateway container {container_info['Id']} has started.") except Exception as e: HummingbotApplication.main_application().notify(f"Error occurred starting Gateway container. {e}") async def stop_gateway(): from hummingbot.client.hummingbot_application import HummingbotApplication try: response = await docker_ipc( "containers", all=True, filters={"name": get_gateway_container_name()} ) if len(response) == 0: raise ValueError(f"Gateway container {get_gateway_container_name()} not found.") container_info = response[0] if container_info["State"] != "running": HummingbotApplication.main_application().notify(f"Gateway container {container_info['Id']} not running.") return await docker_ipc( "stop", container=container_info["Id"], ) HummingbotApplication.main_application().notify(f"Gateway container {container_info['Id']} successfully stopped.") except Exception as e: HummingbotApplication.main_application().notify(f"Error occurred stopping Gateway container. {e}") async def restart_gateway(): from hummingbot.client.hummingbot_application import HummingbotApplication await stop_gateway() await start_gateway() HummingbotApplication.main_application().notify("Gateway will be ready momentarily.")
[ "hummingbot.client.hummingbot_application.HummingbotApplication.main_application", "hummingbot.client.config.global_config_map.global_config_map.get" ]
[((580, 590), 'decimal.Decimal', 'Decimal', (['(0)'], {}), '(0)\n', (587, 590), False, 'from decimal import Decimal\n'), ((3509, 3534), 'os.getenv', 'os.getenv', (['"""CERTS_FOLDER"""'], {}), "('CERTS_FOLDER')\n", (3518, 3534), False, 'import os\n'), ((3612, 3644), 'os.getenv', 'os.getenv', (['"""GATEWAY_CONF_FOLDER"""'], {}), "('GATEWAY_CONF_FOLDER')\n", (3621, 3644), False, 'import os\n'), ((3729, 3761), 'os.getenv', 'os.getenv', (['"""GATEWAY_LOGS_FOLDER"""'], {}), "('GATEWAY_LOGS_FOLDER')\n", (3738, 3761), False, 'import os\n'), ((498, 508), 'os.uname', 'os.uname', ([], {}), '()\n', (506, 508), False, 'import os\n'), ((3544, 3569), 'os.getenv', 'os.getenv', (['"""CERTS_FOLDER"""'], {}), "('CERTS_FOLDER')\n", (3553, 3569), False, 'import os\n'), ((3654, 3686), 'os.getenv', 'os.getenv', (['"""GATEWAY_CONF_FOLDER"""'], {}), "('GATEWAY_CONF_FOLDER')\n", (3663, 3686), False, 'import os\n'), ((3771, 3803), 'os.getenv', 'os.getenv', (['"""GATEWAY_LOGS_FOLDER"""'], {}), "('GATEWAY_LOGS_FOLDER')\n", (3780, 3803), False, 'import os\n'), ((11743, 11783), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (11781, 11783), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((4106, 4117), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (4115, 4117), False, 'from pathlib import Path\n'), ((4188, 4199), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (4197, 4199), False, 'from pathlib import Path\n'), ((10362, 10402), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (10400, 10402), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((11329, 11369), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (11367, 11369), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((6447, 6487), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (6485, 6487), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((6794, 6834), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (6832, 6834), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((7985, 8025), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (8023, 8025), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((10124, 10164), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (10162, 10164), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((10503, 10543), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (10541, 10543), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((11095, 11135), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (11133, 11135), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((11479, 11519), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (11517, 11519), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((7624, 7664), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (7662, 7664), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((5112, 5148), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""instance_id"""'], {}), "('instance_id')\n", (5133, 5148), False, 'from hummingbot.client.config.global_config_map import global_config_map\n')]
#!/usr/bin/env python import asyncio import aiohttp import base64 import logging import pandas as pd from typing import ( Dict, Optional, Tuple, AsyncIterable ) import pickle import time import websockets from websockets.exceptions import ConnectionClosed import conf from hummingbot.connector.exchange.binance.binance_order_book import BinanceOrderBook from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource from hummingbot.logger import HummingbotLogger from hummingbot.core.data_type.order_book_tracker_entry import OrderBookTrackerEntry class RemoteAPIOrderBookDataSource(OrderBookTrackerDataSource): SNAPSHOT_REST_URL = "https://api.coinalpha.com/order_book_tracker/snapshot" SNAPSHOT_STREAM_URL = "wss://api.coinalpha.com/ws/order_book_tracker/snapshot_stream" DIFF_STREAM_URL = "wss://api.coinalpha.com/ws/order_book_tracker/diff_stream" MESSAGE_TIMEOUT = 30.0 PING_TIMEOUT = 10.0 _raobds_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._raobds_logger is None: cls._raobds_logger = logging.getLogger(__name__) return cls._raobds_logger def __init__(self): super().__init__() self._client_session: Optional[aiohttp.ClientSession] = None @property def authentication_headers(self) -> Dict[str, str]: auth_str: str = f"{conf.coinalpha_order_book_api_username}:{conf.coinalpha_order_book_api_password}" encoded_auth: str = base64.standard_b64encode(auth_str.encode("utf8")).decode("utf8") return { "Authorization": f"Basic {encoded_auth}" } async def get_client_session(self) -> aiohttp.ClientSession: if self._client_session is None: self._client_session = aiohttp.ClientSession() return self._client_session async def get_tracking_pairs(self) -> Dict[str, OrderBookTrackerEntry]: auth: aiohttp.BasicAuth = aiohttp.BasicAuth(login=conf.coinalpha_order_book_api_username, password=conf.coinalpha_order_book_api_password) client_session: aiohttp.ClientSession = await self.get_client_session() response: aiohttp.ClientResponse = await client_session.get(self.SNAPSHOT_REST_URL, auth=auth) timestamp: float = time.time() if response.status != 200: raise EnvironmentError(f"Error fetching order book tracker snapshot from {self.SNAPSHOT_REST_URL}.") binary_data: bytes = await response.read() order_book_tracker_data: Dict[str, Tuple[pd.DataFrame, pd.DataFrame]] = pickle.loads(binary_data) retval: Dict[str, OrderBookTrackerEntry] = {} for trading_pair, (bids_df, asks_df) in order_book_tracker_data.items(): order_book: BinanceOrderBook = BinanceOrderBook() order_book.apply_numpy_snapshot(bids_df.values, asks_df.values) retval[trading_pair] = OrderBookTrackerEntry(trading_pair, timestamp, order_book) return retval async def _inner_messages(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]: # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect. try: while True: try: msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT) yield msg except asyncio.TimeoutError: try: pong_waiter = await ws.ping() await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT) except asyncio.TimeoutError: raise except asyncio.TimeoutError: self.logger().warning("WebSocket ping timed out. Going to reconnect...") return except ConnectionClosed: return finally: await ws.close() async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): while True: try: async with websockets.connect(self.DIFF_STREAM_URL, extra_headers=self.authentication_headers) as ws: ws: websockets.WebSocketClientProtocol = ws async for msg in self._inner_messages(ws): output.put_nowait(msg) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...", exc_info=True) await asyncio.sleep(30.0) async def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): while True: try: async with websockets.connect(self.SNAPSHOT_STREAM_URL, extra_headers=self.authentication_headers) as ws: ws: websockets.WebSocketClientProtocol = ws async for msg in self._inner_messages(ws): output.put_nowait(msg) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...", exc_info=True) await asyncio.sleep(30.0)
[ "hummingbot.connector.exchange.binance.binance_order_book.BinanceOrderBook", "hummingbot.core.data_type.order_book_tracker_entry.OrderBookTrackerEntry" ]
[((2006, 2123), 'aiohttp.BasicAuth', 'aiohttp.BasicAuth', ([], {'login': 'conf.coinalpha_order_book_api_username', 'password': 'conf.coinalpha_order_book_api_password'}), '(login=conf.coinalpha_order_book_api_username, password=\n conf.coinalpha_order_book_api_password)\n', (2023, 2123), False, 'import aiohttp\n'), ((2381, 2392), 'time.time', 'time.time', ([], {}), '()\n', (2390, 2392), False, 'import time\n'), ((2673, 2698), 'pickle.loads', 'pickle.loads', (['binary_data'], {}), '(binary_data)\n', (2685, 2698), False, 'import pickle\n'), ((1156, 1183), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1173, 1183), False, 'import logging\n'), ((1835, 1858), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (1856, 1858), False, 'import aiohttp\n'), ((2878, 2896), 'hummingbot.connector.exchange.binance.binance_order_book.BinanceOrderBook', 'BinanceOrderBook', ([], {}), '()\n', (2894, 2896), False, 'from hummingbot.connector.exchange.binance.binance_order_book import BinanceOrderBook\n'), ((3008, 3066), 'hummingbot.core.data_type.order_book_tracker_entry.OrderBookTrackerEntry', 'OrderBookTrackerEntry', (['trading_pair', 'timestamp', 'order_book'], {}), '(trading_pair, timestamp, order_book)\n', (3029, 3066), False, 'from hummingbot.core.data_type.order_book_tracker_entry import OrderBookTrackerEntry\n'), ((4209, 4297), 'websockets.connect', 'websockets.connect', (['self.DIFF_STREAM_URL'], {'extra_headers': 'self.authentication_headers'}), '(self.DIFF_STREAM_URL, extra_headers=self.\n authentication_headers)\n', (4227, 4297), False, 'import websockets\n'), ((4993, 5085), 'websockets.connect', 'websockets.connect', (['self.SNAPSHOT_STREAM_URL'], {'extra_headers': 'self.authentication_headers'}), '(self.SNAPSHOT_STREAM_URL, extra_headers=self.\n authentication_headers)\n', (5011, 5085), False, 'import websockets\n'), ((4800, 4819), 'asyncio.sleep', 'asyncio.sleep', (['(30.0)'], {}), '(30.0)\n', (4813, 4819), False, 'import asyncio\n'), ((5588, 5607), 'asyncio.sleep', 'asyncio.sleep', (['(30.0)'], {}), '(30.0)\n', (5601, 5607), False, 'import asyncio\n'), ((3665, 3721), 'asyncio.wait_for', 'asyncio.wait_for', (['pong_waiter'], {'timeout': 'self.PING_TIMEOUT'}), '(pong_waiter, timeout=self.PING_TIMEOUT)\n', (3681, 3721), False, 'import asyncio\n')]
import asyncio from aiohttp import ClientSession import unittest.mock import requests import json from hummingbot.core.mock_api.mock_web_server import MockWebServer class MockWebServerTest(unittest.TestCase): @classmethod def setUpClass(cls) -> None: cls.ev_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() cls.web_app: MockWebServer = MockWebServer.get_instance() cls.host = "www.google.com" cls.web_app.add_host_to_mock(cls.host) cls.web_app.start() cls.ev_loop.run_until_complete(cls.web_app.wait_til_started()) cls._patcher = unittest.mock.patch("aiohttp.client.URL") cls._url_mock = cls._patcher.start() cls._url_mock.side_effect = MockWebServer.reroute_local cls._req_patcher = unittest.mock.patch.object(requests.Session, "request", autospec=True) cls._req_url_mock = cls._req_patcher.start() cls._req_url_mock.side_effect = MockWebServer.reroute_request @classmethod def tearDownClass(cls) -> None: cls.web_app.stop() cls._patcher.stop() cls._req_patcher.stop() async def _test_web_app_response(self): self.web_app.clear_responses() self.web_app.update_response("get", self.host, "/", data=self.web_app.TEST_RESPONSE, is_json=False) async with ClientSession() as client: async with client.get("http://www.google.com/") as resp: text: str = await resp.text() print(text) self.assertEqual(self.web_app.TEST_RESPONSE, text) def test_web_app_response(self): self.ev_loop.run_until_complete(self._test_web_app_response()) def test_get_request_response(self): self.web_app.clear_responses() self.web_app.update_response("get", self.host, "/", data=self.web_app.TEST_RESPONSE, is_json=False) r = requests.get("http://www.google.com/") self.assertEqual(self.web_app.TEST_RESPONSE, r.text) def test_update_response(self): self.web_app.clear_responses() self.web_app.update_response('get', 'www.google.com', '/', {"a": 1, "b": 2}) r = requests.get("http://www.google.com/") r_json = json.loads(r.text) self.assertEqual(r_json["a"], 1) self.web_app.update_response('post', 'www.google.com', '/', "default") self.web_app.update_response('post', 'www.google.com', '/', {"a": 1, "b": 2}, params={"para_a": '11'}) r = requests.post("http://www.google.com/", data={"para_a": 11, "para_b": 22}) r_json = json.loads(r.text) self.assertEqual(r_json["a"], 1) def test_query_string(self): self.web_app.clear_responses() self.web_app.update_response('get', 'www.google.com', '/', "default") self.web_app.update_response('get', 'www.google.com', '/', {"a": 1}, params={"qs1": "1"}) r = requests.get("http://www.google.com/?qs1=1") r_json = json.loads(r.text) self.assertEqual(r_json["a"], 1) if __name__ == '__main__': unittest.main()
[ "hummingbot.core.mock_api.mock_web_server.MockWebServer.get_instance" ]
[((310, 334), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (332, 334), False, 'import asyncio\n'), ((372, 400), 'hummingbot.core.mock_api.mock_web_server.MockWebServer.get_instance', 'MockWebServer.get_instance', ([], {}), '()\n', (398, 400), False, 'from hummingbot.core.mock_api.mock_web_server import MockWebServer\n'), ((1878, 1916), 'requests.get', 'requests.get', (['"""http://www.google.com/"""'], {}), "('http://www.google.com/')\n", (1890, 1916), False, 'import requests\n'), ((2151, 2189), 'requests.get', 'requests.get', (['"""http://www.google.com/"""'], {}), "('http://www.google.com/')\n", (2163, 2189), False, 'import requests\n'), ((2207, 2225), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (2217, 2225), False, 'import json\n'), ((2470, 2544), 'requests.post', 'requests.post', (['"""http://www.google.com/"""'], {'data': "{'para_a': 11, 'para_b': 22}"}), "('http://www.google.com/', data={'para_a': 11, 'para_b': 22})\n", (2483, 2544), False, 'import requests\n'), ((2562, 2580), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (2572, 2580), False, 'import json\n'), ((2883, 2927), 'requests.get', 'requests.get', (['"""http://www.google.com/?qs1=1"""'], {}), "('http://www.google.com/?qs1=1')\n", (2895, 2927), False, 'import requests\n'), ((2945, 2963), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (2955, 2963), False, 'import json\n'), ((1331, 1346), 'aiohttp.ClientSession', 'ClientSession', ([], {}), '()\n', (1344, 1346), False, 'from aiohttp import ClientSession\n')]
#!/usr/bin/env python import logging from os.path import join, realpath import sys; sys.path.insert(0, realpath(join(__file__, "../../../"))) from hummingbot.logger.struct_logger import METRICS_LOG_LEVEL import asyncio import contextlib from decimal import Decimal import os import time from typing import ( List, Optional ) import unittest import conf from hummingbot.core.clock import ( Clock, ClockMode ) from hummingbot.core.event.event_logger import EventLogger from hummingbot.core.event.events import ( MarketEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent, OrderFilledEvent, OrderCancelledEvent, BuyOrderCreatedEvent, SellOrderCreatedEvent, TradeFee, TradeType, ) from hummingbot.market.bittrex.bittrex_market import BittrexMarket from hummingbot.market.market_base import OrderType from hummingbot.market.markets_recorder import MarketsRecorder from hummingbot.model.market_state import MarketState from hummingbot.model.order import Order from hummingbot.model.sql_connection_manager import ( SQLConnectionManager, SQLConnectionType ) from hummingbot.model.trade_fill import TradeFill from hummingbot.client.config.fee_overrides_config_map import fee_overrides_config_map from test.integration.humming_web_app import HummingWebApp from test.integration.humming_ws_server import HummingWsServerFactory from test.integration.assets.mock_data.fixture_bittrex import FixtureBittrex from unittest import mock import json API_MOCK_ENABLED = conf.mock_api_enabled is not None and conf.mock_api_enabled.lower() in ['true', 'yes', '1'] API_KEY = "XXXX" if API_MOCK_ENABLED else conf.bittrex_api_key API_SECRET = "YYYY" if API_MOCK_ENABLED else conf.bittrex_secret_key API_BASE_URL = "api.bittrex.com" WS_BASE_URL = "https://socket.bittrex.com/signalr" EXCHANGE_ORDER_ID = 20001 logging.basicConfig(level=METRICS_LOG_LEVEL) def _transform_raw_message_patch(self, msg): return json.loads(msg) class BittrexMarketUnitTest(unittest.TestCase): events: List[MarketEvent] = [ MarketEvent.ReceivedAsset, MarketEvent.BuyOrderCompleted, MarketEvent.SellOrderCompleted, MarketEvent.WithdrawAsset, MarketEvent.OrderFilled, MarketEvent.OrderCancelled, MarketEvent.TransactionFailure, MarketEvent.BuyOrderCreated, MarketEvent.SellOrderCreated, MarketEvent.OrderCancelled ] market: BittrexMarket market_logger: EventLogger stack: contextlib.ExitStack @classmethod def setUpClass(cls): cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() if API_MOCK_ENABLED: cls.web_app = HummingWebApp.get_instance() cls.web_app.add_host_to_mock(API_BASE_URL, []) cls.web_app.start() cls.ev_loop.run_until_complete(cls.web_app.wait_til_started()) cls._patcher = mock.patch("aiohttp.client.URL") cls._url_mock = cls._patcher.start() cls._url_mock.side_effect = cls.web_app.reroute_local cls.web_app.update_response("get", API_BASE_URL, "/v3/ping", FixtureBittrex.PING) cls.web_app.update_response("get", API_BASE_URL, "/v3/markets", FixtureBittrex.MARKETS) cls.web_app.update_response("get", API_BASE_URL, "/v3/markets/tickers", FixtureBittrex.MARKETS_TICKERS) cls.web_app.update_response("get", API_BASE_URL, "/v3/balances", FixtureBittrex.BALANCES) cls.web_app.update_response("get", API_BASE_URL, "/v3/orders/open", FixtureBittrex.ORDERS_OPEN) cls._t_nonce_patcher = unittest.mock.patch("hummingbot.market.bittrex.bittrex_market.get_tracking_nonce") cls._t_nonce_mock = cls._t_nonce_patcher.start() cls._us_patcher = unittest.mock.patch("hummingbot.market.bittrex.bittrex_api_user_stream_data_source." "BittrexAPIUserStreamDataSource._transform_raw_message", autospec=True) cls._us_mock = cls._us_patcher.start() cls._us_mock.side_effect = _transform_raw_message_patch cls._ob_patcher = unittest.mock.patch("hummingbot.market.bittrex.bittrex_api_order_book_data_source." "BittrexAPIOrderBookDataSource._transform_raw_message", autospec=True) cls._ob_mock = cls._ob_patcher.start() cls._ob_mock.side_effect = _transform_raw_message_patch HummingWsServerFactory.url_host_only = True ws_server = HummingWsServerFactory.start_new_server(WS_BASE_URL) cls._ws_patcher = unittest.mock.patch("websockets.connect", autospec=True) cls._ws_mock = cls._ws_patcher.start() cls._ws_mock.side_effect = HummingWsServerFactory.reroute_ws_connect ws_server.add_stock_response("queryExchangeState", FixtureBittrex.WS_ORDER_BOOK_SNAPSHOT.copy()) cls.clock: Clock = Clock(ClockMode.REALTIME) cls.market: BittrexMarket = BittrexMarket( bittrex_api_key=API_KEY, bittrex_secret_key=API_SECRET, trading_pairs=["ETH-USDT"] ) print("Initializing Bittrex market... this will take about a minute. ") cls.clock.add_iterator(cls.market) cls.stack = contextlib.ExitStack() cls._clock = cls.stack.enter_context(cls.clock) cls.ev_loop.run_until_complete(cls.wait_til_ready()) print("Ready.") @classmethod def tearDownClass(cls) -> None: cls.stack.close() if API_MOCK_ENABLED: cls.web_app.stop() cls._patcher.stop() cls._t_nonce_patcher.stop() cls._ob_patcher.stop() cls._us_patcher.stop() cls._ws_patcher.stop() @classmethod async def wait_til_ready(cls): while True: now = time.time() next_iteration = now // 1.0 + 1 if cls.market.ready: break else: await cls._clock.run_til(next_iteration) await asyncio.sleep(1.0) def setUp(self): self.db_path: str = realpath(join(__file__, "../bittrex_test.sqlite")) try: os.unlink(self.db_path) except FileNotFoundError: pass self.market_logger = EventLogger() for event_tag in self.events: self.market.add_listener(event_tag, self.market_logger) def tearDown(self): for event_tag in self.events: self.market.remove_listener(event_tag, self.market_logger) self.market_logger = None async def run_parallel_async(self, *tasks): future: asyncio.Future = asyncio.ensure_future(asyncio.gather(*tasks)) while not future.done(): now = time.time() next_iteration = now // 1.0 + 1 await self.clock.run_til(next_iteration) return future.result() def run_parallel(self, *tasks): return self.ev_loop.run_until_complete(self.run_parallel_async(*tasks)) def test_get_fee(self): limit_fee: TradeFee = self.market.get_fee("ETH", "USDT", OrderType.LIMIT, TradeType.BUY, 1, 1) self.assertGreater(limit_fee.percent, 0) self.assertEqual(len(limit_fee.flat_fees), 0) market_fee: TradeFee = self.market.get_fee("ETH", "USDT", OrderType.MARKET, TradeType.BUY, 1) self.assertGreater(market_fee.percent, 0) self.assertEqual(len(market_fee.flat_fees), 0) def test_fee_overrides_config(self): fee_overrides_config_map["bittrex_taker_fee"].value = None taker_fee: TradeFee = self.market.get_fee("LINK", "ETH", OrderType.MARKET, TradeType.BUY, Decimal(1), Decimal('0.1')) self.assertAlmostEqual(Decimal("0.0025"), taker_fee.percent) fee_overrides_config_map["bittrex_taker_fee"].value = Decimal('0.2') taker_fee: TradeFee = self.market.get_fee("LINK", "ETH", OrderType.MARKET, TradeType.BUY, Decimal(1), Decimal('0.1')) self.assertAlmostEqual(Decimal("0.002"), taker_fee.percent) fee_overrides_config_map["bittrex_maker_fee"].value = None maker_fee: TradeFee = self.market.get_fee("LINK", "ETH", OrderType.LIMIT, TradeType.BUY, Decimal(1), Decimal('0.1')) self.assertAlmostEqual(Decimal("0.0025"), maker_fee.percent) fee_overrides_config_map["bittrex_maker_fee"].value = Decimal('0.5') maker_fee: TradeFee = self.market.get_fee("LINK", "ETH", OrderType.LIMIT, TradeType.BUY, Decimal(1), Decimal('0.1')) self.assertAlmostEqual(Decimal("0.005"), maker_fee.percent) def place_order(self, is_buy, trading_pair, amount, order_type, price, nonce, post_resp, ws_resp): global EXCHANGE_ORDER_ID order_id, exch_order_id = None, None if API_MOCK_ENABLED: exch_order_id = f"BITTREX_{EXCHANGE_ORDER_ID}" EXCHANGE_ORDER_ID += 1 self._t_nonce_mock.return_value = nonce resp = post_resp.copy() resp["id"] = exch_order_id side = 'buy' if is_buy else 'sell' resp["direction"] = side.upper() resp["type"] = order_type.name.upper() if order_type == OrderType.MARKET: del resp["limit"] self.web_app.update_response("post", API_BASE_URL, "/v3/orders", resp) if is_buy: order_id = self.market.buy(trading_pair, amount, order_type, price) else: order_id = self.market.sell(trading_pair, amount, order_type, price) if API_MOCK_ENABLED: resp = ws_resp.copy() resp["content"]["o"]["OU"] = exch_order_id HummingWsServerFactory.send_json_threadsafe(WS_BASE_URL, resp, delay=1.0) return order_id, exch_order_id def cancel_order(self, trading_pair, order_id, exch_order_id): if API_MOCK_ENABLED: resp = FixtureBittrex.ORDER_CANCEL.copy() resp["id"] = exch_order_id self.web_app.update_response("delete", API_BASE_URL, f"/v3/orders/{exch_order_id}", resp) self.market.cancel(trading_pair, order_id) def test_limit_buy(self): self.assertGreater(self.market.get_balance("USDT"), 20) trading_pair = "ETH-USDT" self.run_parallel(asyncio.sleep(3)) current_bid_price: Decimal = self.market.get_price(trading_pair, True) bid_price: Decimal = current_bid_price * Decimal('1.005') quantize_bid_price: Decimal = self.market.quantize_order_price(trading_pair, bid_price) amount: Decimal = Decimal("0.06") quantized_amount: Decimal = self.market.quantize_order_amount(trading_pair, amount) order_id, _ = self.place_order(True, trading_pair, quantized_amount, OrderType.LIMIT, quantize_bid_price, 10001, FixtureBittrex.ORDER_PLACE_FILLED, FixtureBittrex.WS_ORDER_FILLED) [order_completed_event] = self.run_parallel(self.market_logger.wait_for(BuyOrderCompletedEvent)) order_completed_event: BuyOrderCompletedEvent = order_completed_event trade_events: List[OrderFilledEvent] = [t for t in self.market_logger.event_log if isinstance(t, OrderFilledEvent)] base_amount_traded: Decimal = sum(t.amount for t in trade_events) quote_amount_traded: Decimal = sum(t.amount * t.price for t in trade_events) self.assertTrue([evt.order_type == OrderType.LIMIT for evt in trade_events]) self.assertEqual(order_id, order_completed_event.order_id) self.assertAlmostEqual(quantized_amount, order_completed_event.base_asset_amount) self.assertEqual("ETH", order_completed_event.base_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.assertTrue(any([isinstance(event, BuyOrderCreatedEvent) and event.order_id == order_id for event in self.market_logger.event_log])) # Reset the logs self.market_logger.clear() def test_limit_sell(self): trading_pair = "ETH-USDT" current_ask_price: Decimal = self.market.get_price(trading_pair, False) ask_price: Decimal = current_ask_price - Decimal('0.005') * current_ask_price quantize_ask_price: Decimal = self.market.quantize_order_price(trading_pair, ask_price) amount: Decimal = Decimal("0.06") quantized_amount: Decimal = self.market.quantize_order_amount(trading_pair, amount) order_id, _ = self.place_order(False, trading_pair, quantized_amount, OrderType.LIMIT, quantize_ask_price, 10001, FixtureBittrex.ORDER_PLACE_FILLED, FixtureBittrex.WS_ORDER_FILLED) [order_completed_event] = self.run_parallel(self.market_logger.wait_for(SellOrderCompletedEvent)) order_completed_event: SellOrderCompletedEvent = order_completed_event trade_events = [t for t in self.market_logger.event_log if isinstance(t, OrderFilledEvent)] base_amount_traded = sum(t.amount for t in trade_events) quote_amount_traded = sum(t.amount * t.price for t in trade_events) self.assertTrue([evt.order_type == OrderType.LIMIT for evt in trade_events]) self.assertEqual(order_id, order_completed_event.order_id) self.assertAlmostEqual(quantized_amount, order_completed_event.base_asset_amount) self.assertEqual("ETH", order_completed_event.base_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.assertTrue(any([isinstance(event, SellOrderCreatedEvent) and event.order_id == order_id for event in self.market_logger.event_log])) # Reset the logs self.market_logger.clear() def test_market_buy(self): self.assertGreater(self.market.get_balance("USDT"), 20) trading_pair = "ETH-USDT" amount: Decimal = Decimal("0.06") quantized_amount: Decimal = self.market.quantize_order_amount(trading_pair, amount) order_id, _ = self.place_order(True, trading_pair, quantized_amount, OrderType.MARKET, 0, 10001, FixtureBittrex.ORDER_PLACE_FILLED, FixtureBittrex.WS_ORDER_FILLED) [order_completed_event] = self.run_parallel(self.market_logger.wait_for(BuyOrderCompletedEvent)) order_completed_event: BuyOrderCompletedEvent = order_completed_event trade_events: List[OrderFilledEvent] = [t for t in self.market_logger.event_log if isinstance(t, OrderFilledEvent)] base_amount_traded: Decimal = sum(t.amount for t in trade_events) quote_amount_traded: Decimal = sum(t.amount * t.price for t in trade_events) self.assertTrue([evt.order_type == OrderType.MARKET for evt in trade_events]) self.assertEqual(order_id, order_completed_event.order_id) self.assertAlmostEqual(quantized_amount, order_completed_event.base_asset_amount) self.assertEqual("ETH", order_completed_event.base_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.assertTrue(any([isinstance(event, BuyOrderCreatedEvent) and event.order_id == order_id for event in self.market_logger.event_log])) # Reset the logs self.market_logger.clear() def test_market_sell(self): trading_pair = "ETH-USDT" self.assertGreater(self.market.get_balance("ETH"), 0.06) amount: Decimal = Decimal("0.06") quantized_amount: Decimal = self.market.quantize_order_amount(trading_pair, amount) order_id, _ = self.place_order(False, trading_pair, quantized_amount, OrderType.MARKET, 0, 10001, FixtureBittrex.ORDER_PLACE_FILLED, FixtureBittrex.WS_ORDER_FILLED) [order_completed_event] = self.run_parallel(self.market_logger.wait_for(SellOrderCompletedEvent)) order_completed_event: SellOrderCompletedEvent = order_completed_event trade_events = [t for t in self.market_logger.event_log if isinstance(t, OrderFilledEvent)] base_amount_traded = sum(t.amount for t in trade_events) quote_amount_traded = sum(t.amount * t.price for t in trade_events) self.assertTrue([evt.order_type == OrderType.MARKET for evt in trade_events]) self.assertEqual(order_id, order_completed_event.order_id) self.assertAlmostEqual(quantized_amount, order_completed_event.base_asset_amount) self.assertEqual("ETH", order_completed_event.base_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.assertTrue(any([isinstance(event, SellOrderCreatedEvent) and event.order_id == order_id for event in self.market_logger.event_log])) # Reset the logs self.market_logger.clear() def test_cancel_order(self): trading_pair = "ETH-USDT" current_bid_price: Decimal = self.market.get_price(trading_pair, True) * Decimal('0.80') quantize_bid_price: Decimal = self.market.quantize_order_price(trading_pair, current_bid_price) amount: Decimal = Decimal("0.06") quantized_amount: Decimal = self.market.quantize_order_amount(trading_pair, amount) order_id, exch_order_id = self.place_order(True, trading_pair, quantized_amount, OrderType.LIMIT, quantize_bid_price, 10001, FixtureBittrex.ORDER_PLACE_OPEN, FixtureBittrex.WS_ORDER_OPEN) self.run_parallel(self.market_logger.wait_for(BuyOrderCreatedEvent)) self.cancel_order(trading_pair, order_id, exch_order_id) [order_cancelled_event] = self.run_parallel(self.market_logger.wait_for(OrderCancelledEvent)) order_cancelled_event: OrderCancelledEvent = order_cancelled_event self.assertEqual(order_cancelled_event.order_id, order_id) def test_cancel_all(self): self.assertGreater(self.market.get_balance("USDT"), 20) trading_pair = "ETH-USDT" current_bid_price: Decimal = self.market.get_price(trading_pair, True) * Decimal('0.80') quantize_bid_price: Decimal = self.market.quantize_order_price(trading_pair, current_bid_price) bid_amount: Decimal = Decimal('0.06') quantized_bid_amount: Decimal = self.market.quantize_order_amount(trading_pair, bid_amount) current_ask_price: Decimal = self.market.get_price(trading_pair, False) quantize_ask_price: Decimal = self.market.quantize_order_price(trading_pair, current_ask_price) ask_amount: Decimal = Decimal('0.06') quantized_ask_amount: Decimal = self.market.quantize_order_amount(trading_pair, ask_amount) _, exch_order_id_1 = self.place_order(True, trading_pair, quantized_bid_amount, OrderType.LIMIT, quantize_bid_price, 10001, FixtureBittrex.ORDER_PLACE_OPEN, FixtureBittrex.WS_ORDER_OPEN) _, exch_order_id_2 = self.place_order(False, trading_pair, quantized_ask_amount, OrderType.LIMIT, quantize_ask_price, 10002, FixtureBittrex.ORDER_PLACE_OPEN, FixtureBittrex.WS_ORDER_OPEN) self.run_parallel(asyncio.sleep(1)) if API_MOCK_ENABLED: resp = FixtureBittrex.ORDER_CANCEL.copy() resp["id"] = exch_order_id_1 self.web_app.update_response("delete", API_BASE_URL, f"/v3/orders/{exch_order_id_1}", resp) resp = FixtureBittrex.ORDER_CANCEL.copy() resp["id"] = exch_order_id_2 self.web_app.update_response("delete", API_BASE_URL, f"/v3/orders/{exch_order_id_2}", resp) [cancellation_results] = self.run_parallel(self.market.cancel_all(5)) for cr in cancellation_results: self.assertEqual(cr.success, True) @unittest.skipUnless(any("test_list_orders" in arg for arg in sys.argv), "List order test requires manual action.") def test_list_orders(self): self.assertGreater(self.market.get_balance("USDT"), 20) trading_pair = "ETH-USDT" current_bid_price: Decimal = self.market.get_price(trading_pair, True) * Decimal('0.80') quantize_bid_price: Decimal = self.market.quantize_order_price(trading_pair, current_bid_price) bid_amount: Decimal = Decimal('0.06') quantized_bid_amount: Decimal = self.market.quantize_order_amount(trading_pair, bid_amount) self.market.buy(trading_pair, quantized_bid_amount, OrderType.LIMIT, quantize_bid_price) self.run_parallel(asyncio.sleep(1)) [order_details] = self.run_parallel(self.market.list_orders()) self.assertGreaterEqual(len(order_details), 1) self.market_logger.clear() [cancellation_results] = self.run_parallel(self.market.cancel_all(5)) for cr in cancellation_results: self.assertEqual(cr.success, True) def test_orders_saving_and_restoration(self): config_path: str = "test_config" strategy_name: str = "test_strategy" trading_pair: str = "ETH-USDT" sql: SQLConnectionManager = SQLConnectionManager(SQLConnectionType.TRADE_FILLS, db_path=self.db_path) order_id: Optional[str] = None recorder: MarketsRecorder = MarketsRecorder(sql, [self.market], config_path, strategy_name) recorder.start() try: self.assertEqual(0, len(self.market.tracking_states)) current_bid_price: Decimal = self.market.get_price(trading_pair, True) * Decimal('0.80') quantize_bid_price: Decimal = self.market.quantize_order_price(trading_pair, current_bid_price) bid_amount: Decimal = Decimal('0.06') quantized_bid_amount: Decimal = self.market.quantize_order_amount(trading_pair, bid_amount) order_id, exch_order_id = self.place_order(True, trading_pair, quantized_bid_amount, OrderType.LIMIT, quantize_bid_price, 10001, FixtureBittrex.ORDER_PLACE_OPEN, FixtureBittrex.WS_ORDER_OPEN) [order_created_event] = self.run_parallel(self.market_logger.wait_for(BuyOrderCreatedEvent)) order_created_event: BuyOrderCreatedEvent = order_created_event self.assertEqual(order_id, order_created_event.order_id) # Verify tracking states self.assertEqual(1, len(self.market.tracking_states)) self.assertEqual(order_id, list(self.market.tracking_states.keys())[0]) # Verify orders from recorder recorded_orders: List[Order] = recorder.get_orders_for_config_and_market(config_path, self.market) self.assertEqual(1, len(recorded_orders)) self.assertEqual(order_id, recorded_orders[0].id) # Verify saved market states saved_market_states: MarketState = recorder.get_market_states(config_path, self.market) self.assertIsNotNone(saved_market_states) self.assertIsInstance(saved_market_states.saved_state, dict) self.assertGreater(len(saved_market_states.saved_state), 0) # Close out the current market and start another market. self.clock.remove_iterator(self.market) for event_tag in self.events: self.market.remove_listener(event_tag, self.market_logger) self.market: BittrexMarket = BittrexMarket( bittrex_api_key=API_KEY, bittrex_secret_key=API_SECRET, trading_pairs=["XRP-BTC"] ) for event_tag in self.events: self.market.add_listener(event_tag, self.market_logger) recorder.stop() recorder = MarketsRecorder(sql, [self.market], config_path, strategy_name) recorder.start() saved_market_states = recorder.get_market_states(config_path, self.market) self.clock.add_iterator(self.market) self.assertEqual(0, len(self.market.limit_orders)) self.assertEqual(0, len(self.market.tracking_states)) self.market.restore_tracking_states(saved_market_states.saved_state) self.assertEqual(1, len(self.market.limit_orders)) self.assertEqual(1, len(self.market.tracking_states)) # Cancel the order and verify that the change is saved. self.cancel_order(trading_pair, order_id, exch_order_id) self.run_parallel(self.market_logger.wait_for(OrderCancelledEvent)) order_id = None self.assertEqual(0, len(self.market.limit_orders)) self.assertEqual(0, len(self.market.tracking_states)) saved_market_states = recorder.get_market_states(config_path, self.market) self.assertEqual(0, len(saved_market_states.saved_state)) finally: if order_id is not None: self.market.cancel(trading_pair, order_id) self.run_parallel(self.market_logger.wait_for(OrderCancelledEvent)) recorder.stop() os.unlink(self.db_path) def test_order_fill_record(self): config_path: str = "test_config" strategy_name: str = "test_strategy" trading_pair: str = "ETH-USDT" sql: SQLConnectionManager = SQLConnectionManager(SQLConnectionType.TRADE_FILLS, db_path=self.db_path) order_id: Optional[str] = None recorder: MarketsRecorder = MarketsRecorder(sql, [self.market], config_path, strategy_name) recorder.start() try: amount: Decimal = Decimal("0.06") quantized_amount: Decimal = self.market.quantize_order_amount(trading_pair, amount) order_id, _ = self.place_order(True, trading_pair, quantized_amount, OrderType.MARKET, 0, 10001, FixtureBittrex.ORDER_PLACE_FILLED, FixtureBittrex.WS_ORDER_FILLED) [buy_order_completed_event] = self.run_parallel(self.market_logger.wait_for(BuyOrderCompletedEvent)) # Reset the logs self.market_logger.clear() amount = Decimal(buy_order_completed_event.base_asset_amount) order_id, _ = self.place_order(False, trading_pair, amount, OrderType.MARKET, 0, 10001, FixtureBittrex.ORDER_PLACE_FILLED, FixtureBittrex.WS_ORDER_FILLED) [sell_order_completed_event] = self.run_parallel(self.market_logger.wait_for(SellOrderCompletedEvent)) # Query the persisted trade logs trade_fills: List[TradeFill] = recorder.get_trades_for_config(config_path) self.assertEqual(2, len(trade_fills)) buy_fills: List[TradeFill] = [t for t in trade_fills if t.trade_type == "BUY"] sell_fills: List[TradeFill] = [t for t in trade_fills if t.trade_type == "SELL"] self.assertEqual(1, len(buy_fills)) self.assertEqual(1, len(sell_fills)) order_id = None finally: if order_id is not None: self.market.cancel(trading_pair, order_id) self.run_parallel(self.market_logger.wait_for(OrderCancelledEvent)) recorder.stop() os.unlink(self.db_path) if __name__ == "__main__": unittest.main()
[ "hummingbot.market.markets_recorder.MarketsRecorder", "hummingbot.market.bittrex.bittrex_market.BittrexMarket", "hummingbot.core.event.event_logger.EventLogger", "hummingbot.core.clock.Clock", "hummingbot.model.sql_connection_manager.SQLConnectionManager" ]
[((1850, 1894), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'METRICS_LOG_LEVEL'}), '(level=METRICS_LOG_LEVEL)\n', (1869, 1894), False, 'import logging\n'), ((1953, 1968), 'json.loads', 'json.loads', (['msg'], {}), '(msg)\n', (1963, 1968), False, 'import json\n'), ((28511, 28526), 'unittest.main', 'unittest.main', ([], {}), '()\n', (28524, 28526), False, 'import unittest\n'), ((112, 139), 'os.path.join', 'join', (['__file__', '"""../../../"""'], {}), "(__file__, '../../../')\n", (116, 139), False, 'from os.path import join, realpath\n'), ((1554, 1583), 'conf.mock_api_enabled.lower', 'conf.mock_api_enabled.lower', ([], {}), '()\n', (1581, 1583), False, 'import conf\n'), ((2605, 2629), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2627, 2629), False, 'import asyncio\n'), ((5056, 5081), 'hummingbot.core.clock.Clock', 'Clock', (['ClockMode.REALTIME'], {}), '(ClockMode.REALTIME)\n', (5061, 5081), False, 'from hummingbot.core.clock import Clock, ClockMode\n'), ((5118, 5219), 'hummingbot.market.bittrex.bittrex_market.BittrexMarket', 'BittrexMarket', ([], {'bittrex_api_key': 'API_KEY', 'bittrex_secret_key': 'API_SECRET', 'trading_pairs': "['ETH-USDT']"}), "(bittrex_api_key=API_KEY, bittrex_secret_key=API_SECRET,\n trading_pairs=['ETH-USDT'])\n", (5131, 5219), False, 'from hummingbot.market.bittrex.bittrex_market import BittrexMarket\n'), ((5406, 5428), 'contextlib.ExitStack', 'contextlib.ExitStack', ([], {}), '()\n', (5426, 5428), False, 'import contextlib\n'), ((6432, 6445), 'hummingbot.core.event.event_logger.EventLogger', 'EventLogger', ([], {}), '()\n', (6443, 6445), False, 'from hummingbot.core.event.event_logger import EventLogger\n'), ((8014, 8028), 'decimal.Decimal', 'Decimal', (['"""0.2"""'], {}), "('0.2')\n", (8021, 8028), False, 'from decimal import Decimal\n'), ((8646, 8660), 'decimal.Decimal', 'Decimal', (['"""0.5"""'], {}), "('0.5')\n", (8653, 8660), False, 'from decimal import Decimal\n'), ((10865, 10880), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (10872, 10880), False, 'from decimal import Decimal\n'), ((12868, 12883), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (12875, 12883), False, 'from decimal import Decimal\n'), ((14587, 14602), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (14594, 14602), False, 'from decimal import Decimal\n'), ((16378, 16393), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (16385, 16393), False, 'from decimal import Decimal\n'), ((18221, 18236), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (18228, 18236), False, 'from decimal import Decimal\n'), ((19376, 19391), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (19383, 19391), False, 'from decimal import Decimal\n'), ((19707, 19722), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (19714, 19722), False, 'from decimal import Decimal\n'), ((21518, 21533), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (21525, 21533), False, 'from decimal import Decimal\n'), ((22315, 22388), 'hummingbot.model.sql_connection_manager.SQLConnectionManager', 'SQLConnectionManager', (['SQLConnectionType.TRADE_FILLS'], {'db_path': 'self.db_path'}), '(SQLConnectionType.TRADE_FILLS, db_path=self.db_path)\n', (22335, 22388), False, 'from hummingbot.model.sql_connection_manager import SQLConnectionManager, SQLConnectionType\n'), ((22464, 22527), 'hummingbot.market.markets_recorder.MarketsRecorder', 'MarketsRecorder', (['sql', '[self.market]', 'config_path', 'strategy_name'], {}), '(sql, [self.market], config_path, strategy_name)\n', (22479, 22527), False, 'from hummingbot.market.markets_recorder import MarketsRecorder\n'), ((26526, 26599), 'hummingbot.model.sql_connection_manager.SQLConnectionManager', 'SQLConnectionManager', (['SQLConnectionType.TRADE_FILLS'], {'db_path': 'self.db_path'}), '(SQLConnectionType.TRADE_FILLS, db_path=self.db_path)\n', (26546, 26599), False, 'from hummingbot.model.sql_connection_manager import SQLConnectionManager, SQLConnectionType\n'), ((26675, 26738), 'hummingbot.market.markets_recorder.MarketsRecorder', 'MarketsRecorder', (['sql', '[self.market]', 'config_path', 'strategy_name'], {}), '(sql, [self.market], config_path, strategy_name)\n', (26690, 26738), False, 'from hummingbot.market.markets_recorder import MarketsRecorder\n'), ((2685, 2713), 'test.integration.humming_web_app.HummingWebApp.get_instance', 'HummingWebApp.get_instance', ([], {}), '()\n', (2711, 2713), False, 'from test.integration.humming_web_app import HummingWebApp\n'), ((2907, 2939), 'unittest.mock.patch', 'mock.patch', (['"""aiohttp.client.URL"""'], {}), "('aiohttp.client.URL')\n", (2917, 2939), False, 'from unittest import mock\n'), ((3610, 3697), 'unittest.mock.patch', 'unittest.mock.patch', (['"""hummingbot.market.bittrex.bittrex_market.get_tracking_nonce"""'], {}), "(\n 'hummingbot.market.bittrex.bittrex_market.get_tracking_nonce')\n", (3629, 3697), False, 'import unittest\n'), ((3785, 3948), 'unittest.mock.patch', 'unittest.mock.patch', (['"""hummingbot.market.bittrex.bittrex_api_user_stream_data_source.BittrexAPIUserStreamDataSource._transform_raw_message"""'], {'autospec': '(True)'}), "(\n 'hummingbot.market.bittrex.bittrex_api_user_stream_data_source.BittrexAPIUserStreamDataSource._transform_raw_message'\n , autospec=True)\n", (3804, 3948), False, 'import unittest\n'), ((4192, 4353), 'unittest.mock.patch', 'unittest.mock.patch', (['"""hummingbot.market.bittrex.bittrex_api_order_book_data_source.BittrexAPIOrderBookDataSource._transform_raw_message"""'], {'autospec': '(True)'}), "(\n 'hummingbot.market.bittrex.bittrex_api_order_book_data_source.BittrexAPIOrderBookDataSource._transform_raw_message'\n , autospec=True)\n", (4211, 4353), False, 'import unittest\n'), ((4647, 4699), 'test.integration.humming_ws_server.HummingWsServerFactory.start_new_server', 'HummingWsServerFactory.start_new_server', (['WS_BASE_URL'], {}), '(WS_BASE_URL)\n', (4686, 4699), False, 'from test.integration.humming_ws_server import HummingWsServerFactory\n'), ((4730, 4786), 'unittest.mock.patch', 'unittest.mock.patch', (['"""websockets.connect"""'], {'autospec': '(True)'}), "('websockets.connect', autospec=True)\n", (4749, 4786), False, 'import unittest\n'), ((5978, 5989), 'time.time', 'time.time', ([], {}), '()\n', (5987, 5989), False, 'import time\n'), ((6260, 6300), 'os.path.join', 'join', (['__file__', '"""../bittrex_test.sqlite"""'], {}), "(__file__, '../bittrex_test.sqlite')\n", (6264, 6300), False, 'from os.path import join, realpath\n'), ((6327, 6350), 'os.unlink', 'os.unlink', (['self.db_path'], {}), '(self.db_path)\n', (6336, 6350), False, 'import os\n'), ((6824, 6846), 'asyncio.gather', 'asyncio.gather', (['*tasks'], {}), '(*tasks)\n', (6838, 6846), False, 'import asyncio\n'), ((6899, 6910), 'time.time', 'time.time', ([], {}), '()\n', (6908, 6910), False, 'import time\n'), ((7805, 7815), 'decimal.Decimal', 'Decimal', (['(1)'], {}), '(1)\n', (7812, 7815), False, 'from decimal import Decimal\n'), ((7867, 7881), 'decimal.Decimal', 'Decimal', (['"""0.1"""'], {}), "('0.1')\n", (7874, 7881), False, 'from decimal import Decimal\n'), ((7914, 7931), 'decimal.Decimal', 'Decimal', (['"""0.0025"""'], {}), "('0.0025')\n", (7921, 7931), False, 'from decimal import Decimal\n'), ((8127, 8137), 'decimal.Decimal', 'Decimal', (['(1)'], {}), '(1)\n', (8134, 8137), False, 'from decimal import Decimal\n'), ((8189, 8203), 'decimal.Decimal', 'Decimal', (['"""0.1"""'], {}), "('0.1')\n", (8196, 8203), False, 'from decimal import Decimal\n'), ((8236, 8252), 'decimal.Decimal', 'Decimal', (['"""0.002"""'], {}), "('0.002')\n", (8243, 8252), False, 'from decimal import Decimal\n'), ((8437, 8447), 'decimal.Decimal', 'Decimal', (['(1)'], {}), '(1)\n', (8444, 8447), False, 'from decimal import Decimal\n'), ((8499, 8513), 'decimal.Decimal', 'Decimal', (['"""0.1"""'], {}), "('0.1')\n", (8506, 8513), False, 'from decimal import Decimal\n'), ((8546, 8563), 'decimal.Decimal', 'Decimal', (['"""0.0025"""'], {}), "('0.0025')\n", (8553, 8563), False, 'from decimal import Decimal\n'), ((8758, 8768), 'decimal.Decimal', 'Decimal', (['(1)'], {}), '(1)\n', (8765, 8768), False, 'from decimal import Decimal\n'), ((8820, 8834), 'decimal.Decimal', 'Decimal', (['"""0.1"""'], {}), "('0.1')\n", (8827, 8834), False, 'from decimal import Decimal\n'), ((8867, 8883), 'decimal.Decimal', 'Decimal', (['"""0.005"""'], {}), "('0.005')\n", (8874, 8883), False, 'from decimal import Decimal\n'), ((9967, 10040), 'test.integration.humming_ws_server.HummingWsServerFactory.send_json_threadsafe', 'HummingWsServerFactory.send_json_threadsafe', (['WS_BASE_URL', 'resp'], {'delay': '(1.0)'}), '(WS_BASE_URL, resp, delay=1.0)\n', (10010, 10040), False, 'from test.integration.humming_ws_server import HummingWsServerFactory\n'), ((10196, 10230), 'test.integration.assets.mock_data.fixture_bittrex.FixtureBittrex.ORDER_CANCEL.copy', 'FixtureBittrex.ORDER_CANCEL.copy', ([], {}), '()\n', (10228, 10230), False, 'from test.integration.assets.mock_data.fixture_bittrex import FixtureBittrex\n'), ((10579, 10595), 'asyncio.sleep', 'asyncio.sleep', (['(3)'], {}), '(3)\n', (10592, 10595), False, 'import asyncio\n'), ((10725, 10741), 'decimal.Decimal', 'Decimal', (['"""1.005"""'], {}), "('1.005')\n", (10732, 10741), False, 'from decimal import Decimal\n'), ((18074, 18089), 'decimal.Decimal', 'Decimal', (['"""0.80"""'], {}), "('0.80')\n", (18081, 18089), False, 'from decimal import Decimal\n'), ((19226, 19241), 'decimal.Decimal', 'Decimal', (['"""0.80"""'], {}), "('0.80')\n", (19233, 19241), False, 'from decimal import Decimal\n'), ((20425, 20441), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (20438, 20441), False, 'import asyncio\n'), ((20491, 20525), 'test.integration.assets.mock_data.fixture_bittrex.FixtureBittrex.ORDER_CANCEL.copy', 'FixtureBittrex.ORDER_CANCEL.copy', ([], {}), '()\n', (20523, 20525), False, 'from test.integration.assets.mock_data.fixture_bittrex import FixtureBittrex\n'), ((20690, 20724), 'test.integration.assets.mock_data.fixture_bittrex.FixtureBittrex.ORDER_CANCEL.copy', 'FixtureBittrex.ORDER_CANCEL.copy', ([], {}), '()\n', (20722, 20724), False, 'from test.integration.assets.mock_data.fixture_bittrex import FixtureBittrex\n'), ((21368, 21383), 'decimal.Decimal', 'Decimal', (['"""0.80"""'], {}), "('0.80')\n", (21375, 21383), False, 'from decimal import Decimal\n'), ((21758, 21774), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (21771, 21774), False, 'import asyncio\n'), ((22876, 22891), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (22883, 22891), False, 'from decimal import Decimal\n'), ((24640, 24740), 'hummingbot.market.bittrex.bittrex_market.BittrexMarket', 'BittrexMarket', ([], {'bittrex_api_key': 'API_KEY', 'bittrex_secret_key': 'API_SECRET', 'trading_pairs': "['XRP-BTC']"}), "(bittrex_api_key=API_KEY, bittrex_secret_key=API_SECRET,\n trading_pairs=['XRP-BTC'])\n", (24653, 24740), False, 'from hummingbot.market.bittrex.bittrex_market import BittrexMarket\n'), ((24964, 25027), 'hummingbot.market.markets_recorder.MarketsRecorder', 'MarketsRecorder', (['sql', '[self.market]', 'config_path', 'strategy_name'], {}), '(sql, [self.market], config_path, strategy_name)\n', (24979, 25027), False, 'from hummingbot.market.markets_recorder import MarketsRecorder\n'), ((26302, 26325), 'os.unlink', 'os.unlink', (['self.db_path'], {}), '(self.db_path)\n', (26311, 26325), False, 'import os\n'), ((26809, 26824), 'decimal.Decimal', 'Decimal', (['"""0.06"""'], {}), "('0.06')\n", (26816, 26824), False, 'from decimal import Decimal\n'), ((27344, 27396), 'decimal.Decimal', 'Decimal', (['buy_order_completed_event.base_asset_amount'], {}), '(buy_order_completed_event.base_asset_amount)\n', (27351, 27396), False, 'from decimal import Decimal\n'), ((28454, 28477), 'os.unlink', 'os.unlink', (['self.db_path'], {}), '(self.db_path)\n', (28463, 28477), False, 'import os\n'), ((4982, 5026), 'test.integration.assets.mock_data.fixture_bittrex.FixtureBittrex.WS_ORDER_BOOK_SNAPSHOT.copy', 'FixtureBittrex.WS_ORDER_BOOK_SNAPSHOT.copy', ([], {}), '()\n', (5024, 5026), False, 'from test.integration.assets.mock_data.fixture_bittrex import FixtureBittrex\n'), ((6182, 6200), 'asyncio.sleep', 'asyncio.sleep', (['(1.0)'], {}), '(1.0)\n', (6195, 6200), False, 'import asyncio\n'), ((12708, 12724), 'decimal.Decimal', 'Decimal', (['"""0.005"""'], {}), "('0.005')\n", (12715, 12724), False, 'from decimal import Decimal\n'), ((22718, 22733), 'decimal.Decimal', 'Decimal', (['"""0.80"""'], {}), "('0.80')\n", (22725, 22733), False, 'from decimal import Decimal\n')]
import unittest from copy import deepcopy from hummingbot.client.settings import AllConnectorSettings from hummingbot.strategy.spot_perpetual_arbitrage.spot_perpetual_arbitrage_config_map import ( spot_perpetual_arbitrage_config_map, spot_market_prompt, perpetual_market_prompt, ) class SpotPerpetualArbitrageConfigMapTest(unittest.TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.spot_exchange = "binance" cls.perp_exchange = "binance_perpetual" def setUp(self) -> None: super().setUp() self.config_backup = deepcopy(spot_perpetual_arbitrage_config_map) def tearDown(self) -> None: self.reset_config_map() super().tearDown() def reset_config_map(self): for key, value in self.config_backup.items(): spot_perpetual_arbitrage_config_map[key] = value def test_spot_market_prompt(self): spot_perpetual_arbitrage_config_map["spot_connector"].value = self.spot_exchange example = AllConnectorSettings.get_example_pairs().get(self.spot_exchange) prompt = spot_market_prompt() expected = f"Enter the token trading pair you would like to trade on {self.spot_exchange} (e.g. {example}) >>> " self.assertEqual(expected, prompt) def test_perpetual_market_prompt(self): spot_perpetual_arbitrage_config_map["perpetual_connector"].value = self.perp_exchange example = AllConnectorSettings.get_example_pairs().get(self.perp_exchange) prompt = perpetual_market_prompt() expected = f"Enter the token trading pair you would like to trade on {self.perp_exchange} (e.g. {example}) >>> " self.assertEqual(expected, prompt)
[ "hummingbot.client.settings.AllConnectorSettings.get_example_pairs", "hummingbot.strategy.spot_perpetual_arbitrage.spot_perpetual_arbitrage_config_map.spot_market_prompt", "hummingbot.strategy.spot_perpetual_arbitrage.spot_perpetual_arbitrage_config_map.perpetual_market_prompt" ]
[((608, 653), 'copy.deepcopy', 'deepcopy', (['spot_perpetual_arbitrage_config_map'], {}), '(spot_perpetual_arbitrage_config_map)\n', (616, 653), False, 'from copy import deepcopy\n'), ((1124, 1144), 'hummingbot.strategy.spot_perpetual_arbitrage.spot_perpetual_arbitrage_config_map.spot_market_prompt', 'spot_market_prompt', ([], {}), '()\n', (1142, 1144), False, 'from hummingbot.strategy.spot_perpetual_arbitrage.spot_perpetual_arbitrage_config_map import spot_perpetual_arbitrage_config_map, spot_market_prompt, perpetual_market_prompt\n'), ((1550, 1575), 'hummingbot.strategy.spot_perpetual_arbitrage.spot_perpetual_arbitrage_config_map.perpetual_market_prompt', 'perpetual_market_prompt', ([], {}), '()\n', (1573, 1575), False, 'from hummingbot.strategy.spot_perpetual_arbitrage.spot_perpetual_arbitrage_config_map import spot_perpetual_arbitrage_config_map, spot_market_prompt, perpetual_market_prompt\n'), ((1041, 1081), 'hummingbot.client.settings.AllConnectorSettings.get_example_pairs', 'AllConnectorSettings.get_example_pairs', ([], {}), '()\n', (1079, 1081), False, 'from hummingbot.client.settings import AllConnectorSettings\n'), ((1467, 1507), 'hummingbot.client.settings.AllConnectorSettings.get_example_pairs', 'AllConnectorSettings.get_example_pairs', ([], {}), '()\n', (1505, 1507), False, 'from hummingbot.client.settings import AllConnectorSettings\n')]
""" Unit tests for hummingbot.core.utils.ssl_cert """ from hummingbot import set_cert_path from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist import os import tempfile import unittest class SslCertTest(unittest.TestCase): def test_generate_private_key(self): """ Unit tests for generate_private_key """ # Assert that it generates a file temp_dir = tempfile.gettempdir() private_key_file_path = temp_dir + "/private_key_test" generate_private_key("topsecret", private_key_file_path) self.assertEqual(os.path.exists(private_key_file_path), True) def test_generate_public_key(self): """ Unit tests for generate_public_key """ # create a private key temp_dir = tempfile.gettempdir() private_key_file_path = temp_dir + "/private_key_test" private_key = generate_private_key("topsecret", private_key_file_path) # create the public key, assert that the file exists public_key_file_path = temp_dir + "/public_key_test" generate_public_key(private_key, public_key_file_path) self.assertEqual(os.path.exists(public_key_file_path), True) def test_generate_csr(self): """ Unit tests for generate_csr """ # create a private key temp_dir = tempfile.gettempdir() private_key_file_path = temp_dir + "/private_key_test" private_key = generate_private_key("topsecret", private_key_file_path) # create a csr and assert that it exists csr_file_path = temp_dir + "/csr_test" generate_csr(private_key, csr_file_path) self.assertEqual(os.path.exists(csr_file_path), True) def test_sign_csr(self): """ Unit tests for sign_csr """ # create a private key temp_dir = tempfile.gettempdir() private_key_file_path = temp_dir + "/private_key_test" private_key = generate_private_key("topsecret", private_key_file_path) # create a public key public_key_file_path = temp_dir + "/public_key_test" public_key = generate_public_key(private_key, public_key_file_path) # create a csr csr_file_path = temp_dir + "/csr_test" csr = generate_csr(private_key, csr_file_path) # create a verified public key verified_public_key_file_path = temp_dir + "/verified_public_key" sign_csr(csr, public_key, private_key, verified_public_key_file_path) self.assertEqual(os.path.exists(verified_public_key_file_path), True) # try to create a verified public key with the wrong private key # x509 does not stop you from doing this and will still output a file # so we just do a simple check that the outputs are not the same private_key_file_path2 = temp_dir + "/private_key_test2" private_key2 = generate_private_key("topsecret2", private_key_file_path2) verified_public_key_file_path2 = temp_dir + "/verified_public_key2" sign_csr(csr, public_key, private_key2, verified_public_key_file_path2) with open(verified_public_key_file_path, "rb") as verified_public_key: with open(verified_public_key_file_path2, "rb") as verified_public_key2: self.assertNotEqual(verified_public_key, verified_public_key2) def test_create_self_sign_certs(self): """ Unit tests for create_self_sign_certs and certs_files_exist """ # setup global cert_path and make sure it is empty with tempfile.TemporaryDirectory() as tempdir: cp = tempdir + "/certs" set_cert_path(cp) if not os.path.exists(cp): os.mkdir(cp) self.assertEqual(certs_files_exist(), False) # generate all necessary certs then confirm they exist in the expected place create_self_sign_certs("abc123") self.assertEqual(certs_files_exist(), True)
[ "hummingbot.core.utils.ssl_cert.generate_public_key", "hummingbot.core.utils.ssl_cert.create_self_sign_certs", "hummingbot.core.utils.ssl_cert.generate_csr", "hummingbot.core.utils.ssl_cert.sign_csr", "hummingbot.set_cert_path", "hummingbot.core.utils.ssl_cert.certs_files_exist", "hummingbot.core.utils....
[((496, 517), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (515, 517), False, 'import tempfile\n'), ((589, 645), 'hummingbot.core.utils.ssl_cert.generate_private_key', 'generate_private_key', (['"""topsecret"""', 'private_key_file_path'], {}), "('topsecret', private_key_file_path)\n", (609, 645), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((875, 896), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (894, 896), False, 'import tempfile\n'), ((982, 1038), 'hummingbot.core.utils.ssl_cert.generate_private_key', 'generate_private_key', (['"""topsecret"""', 'private_key_file_path'], {}), "('topsecret', private_key_file_path)\n", (1002, 1038), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((1170, 1224), 'hummingbot.core.utils.ssl_cert.generate_public_key', 'generate_public_key', (['private_key', 'public_key_file_path'], {}), '(private_key, public_key_file_path)\n', (1189, 1224), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((1439, 1460), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (1458, 1460), False, 'import tempfile\n'), ((1546, 1602), 'hummingbot.core.utils.ssl_cert.generate_private_key', 'generate_private_key', (['"""topsecret"""', 'private_key_file_path'], {}), "('topsecret', private_key_file_path)\n", (1566, 1602), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((1708, 1748), 'hummingbot.core.utils.ssl_cert.generate_csr', 'generate_csr', (['private_key', 'csr_file_path'], {}), '(private_key, csr_file_path)\n', (1720, 1748), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((1948, 1969), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (1967, 1969), False, 'import tempfile\n'), ((2055, 2111), 'hummingbot.core.utils.ssl_cert.generate_private_key', 'generate_private_key', (['"""topsecret"""', 'private_key_file_path'], {}), "('topsecret', private_key_file_path)\n", (2075, 2111), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((2225, 2279), 'hummingbot.core.utils.ssl_cert.generate_public_key', 'generate_public_key', (['private_key', 'public_key_file_path'], {}), '(private_key, public_key_file_path)\n', (2244, 2279), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((2365, 2405), 'hummingbot.core.utils.ssl_cert.generate_csr', 'generate_csr', (['private_key', 'csr_file_path'], {}), '(private_key, csr_file_path)\n', (2377, 2405), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((2528, 2597), 'hummingbot.core.utils.ssl_cert.sign_csr', 'sign_csr', (['csr', 'public_key', 'private_key', 'verified_public_key_file_path'], {}), '(csr, public_key, private_key, verified_public_key_file_path)\n', (2536, 2597), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((2989, 3047), 'hummingbot.core.utils.ssl_cert.generate_private_key', 'generate_private_key', (['"""topsecret2"""', 'private_key_file_path2'], {}), "('topsecret2', private_key_file_path2)\n", (3009, 3047), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((3132, 3203), 'hummingbot.core.utils.ssl_cert.sign_csr', 'sign_csr', (['csr', 'public_key', 'private_key2', 'verified_public_key_file_path2'], {}), '(csr, public_key, private_key2, verified_public_key_file_path2)\n', (3140, 3203), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((671, 708), 'os.path.exists', 'os.path.exists', (['private_key_file_path'], {}), '(private_key_file_path)\n', (685, 708), False, 'import os\n'), ((1250, 1286), 'os.path.exists', 'os.path.exists', (['public_key_file_path'], {}), '(public_key_file_path)\n', (1264, 1286), False, 'import os\n'), ((1774, 1803), 'os.path.exists', 'os.path.exists', (['csr_file_path'], {}), '(csr_file_path)\n', (1788, 1803), False, 'import os\n'), ((2623, 2668), 'os.path.exists', 'os.path.exists', (['verified_public_key_file_path'], {}), '(verified_public_key_file_path)\n', (2637, 2668), False, 'import os\n'), ((3657, 3686), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3684, 3686), False, 'import tempfile\n'), ((3747, 3764), 'hummingbot.set_cert_path', 'set_cert_path', (['cp'], {}), '(cp)\n', (3760, 3764), False, 'from hummingbot import set_cert_path\n'), ((3993, 4025), 'hummingbot.core.utils.ssl_cert.create_self_sign_certs', 'create_self_sign_certs', (['"""abc123"""'], {}), "('abc123')\n", (4015, 4025), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((3784, 3802), 'os.path.exists', 'os.path.exists', (['cp'], {}), '(cp)\n', (3798, 3802), False, 'import os\n'), ((3820, 3832), 'os.mkdir', 'os.mkdir', (['cp'], {}), '(cp)\n', (3828, 3832), False, 'import os\n'), ((3863, 3882), 'hummingbot.core.utils.ssl_cert.certs_files_exist', 'certs_files_exist', ([], {}), '()\n', (3880, 3882), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n'), ((4055, 4074), 'hummingbot.core.utils.ssl_cert.certs_files_exist', 'certs_files_exist', ([], {}), '()\n', (4072, 4074), False, 'from hummingbot.core.utils.ssl_cert import generate_private_key, generate_public_key, generate_csr, sign_csr, create_self_sign_certs, certs_files_exist\n')]
import asyncio import json import time import unittest from typing import Dict, Awaitable from unittest.mock import patch, AsyncMock import numpy as np from hummingbot.connector.exchange.altmarkets.altmarkets_api_user_stream_data_source import AltmarketsAPIUserStreamDataSource from hummingbot.connector.exchange.altmarkets.altmarkets_auth import AltmarketsAuth from hummingbot.connector.exchange.altmarkets.altmarkets_constants import Constants from hummingbot.core.api_throttler.async_throttler import AsyncThrottler from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant class TestAltmarketsAPIUserStreamDataSource(unittest.TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.ev_loop = asyncio.get_event_loop() cls.base_asset = "COINALPHA" cls.quote_asset = "HBOT" cls.trading_pair = f"{cls.base_asset}-{cls.quote_asset}" def setUp(self) -> None: super().setUp() self.mocking_assistant = NetworkMockingAssistant() altmarkets_auth = AltmarketsAuth(api_key="someKey", secret_key="someSecret") self.data_source = AltmarketsAPIUserStreamDataSource(AsyncThrottler(Constants.RATE_LIMITS), altmarkets_auth=altmarkets_auth, trading_pairs=[self.trading_pair]) def async_run_with_timeout(self, coroutine: Awaitable, timeout: int = 1): ret = self.ev_loop.run_until_complete(asyncio.wait_for(coroutine, timeout)) return ret def get_user_trades_mock(self) -> Dict: user_trades = { "trade": { "amount": "1.0", "created_at": 1615978645, "id": 9618578, "market": "rogerbtc", "order_id": 2324774, "price": "0.00000004", "side": "sell", "taker_type": "sell", "total": "0.00000004" } } return user_trades def get_user_orders_mock(self) -> Dict: user_orders = { "order": { "id": 9401, "market": "rogerbtc", "kind": "ask", "side": "sell", "ord_type": "limit", "price": "0.00000099", "avg_price": "0.00000099", "state": "wait", "origin_volume": "7000.0", "remaining_volume": "2810.1", "executed_volume": "4189.9", "at": 1596481983, "created_at": 1596481983, "updated_at": 1596553643, "trades_count": 272 } } return user_orders def get_user_balance_mock(self) -> Dict: user_balance = { "balance": { "currency": self.base_asset, "balance": "1032951.325075926", "locked": "1022943.325075926", } } return user_balance @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_user_stream_user_trades(self, ws_connect_mock): ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() output_queue = asyncio.Queue() self.ev_loop.create_task(self.data_source.listen_for_user_stream(self.ev_loop, output_queue)) resp = self.get_user_trades_mock() self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(resp)) ret = self.async_run_with_timeout(coroutine=output_queue.get()) self.assertEqual(ret, resp) resp = self.get_user_orders_mock() self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(resp)) ret = self.async_run_with_timeout(coroutine=output_queue.get()) self.assertEqual(ret, resp) resp = self.get_user_balance_mock() self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(resp)) ret = self.async_run_with_timeout(coroutine=output_queue.get()) self.assertEqual(ret, resp) @patch("websockets.connect", new_callable=AsyncMock) def test_listen_for_user_stream_skips_subscribe_unsubscribe_messages_updates_last_recv_time(self, ws_connect_mock): ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() resp = { "success": { "message": "subscribed", "time": 1632223851, "streams": "trade" } } self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(resp)) resp = { "success": { "message": "unsubscribed", "time": 1632223851, "streams": "trade" } } self.mocking_assistant.add_websocket_text_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(resp)) output_queue = asyncio.Queue() self.ev_loop.create_task(self.data_source.listen_for_user_stream(self.ev_loop, output_queue)) self.mocking_assistant.run_until_all_text_messages_delivered(ws_connect_mock.return_value) self.assertTrue(output_queue.empty()) np.testing.assert_allclose([time.time()], self.data_source.last_recv_time, rtol=1)
[ "hummingbot.connector.exchange.altmarkets.altmarkets_auth.AltmarketsAuth", "hummingbot.core.api_throttler.async_throttler.AsyncThrottler" ]
[((2961, 3012), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (2966, 3012), False, 'from unittest.mock import patch, AsyncMock\n'), ((4239, 4290), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (4244, 4290), False, 'from unittest.mock import patch, AsyncMock\n'), ((776, 800), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (798, 800), False, 'import asyncio\n'), ((1023, 1048), 'test.hummingbot.connector.network_mocking_assistant.NetworkMockingAssistant', 'NetworkMockingAssistant', ([], {}), '()\n', (1046, 1048), False, 'from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant\n'), ((1075, 1133), 'hummingbot.connector.exchange.altmarkets.altmarkets_auth.AltmarketsAuth', 'AltmarketsAuth', ([], {'api_key': '"""someKey"""', 'secret_key': '"""someSecret"""'}), "(api_key='someKey', secret_key='someSecret')\n", (1089, 1133), False, 'from hummingbot.connector.exchange.altmarkets.altmarkets_auth import AltmarketsAuth\n'), ((3194, 3209), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (3207, 3209), False, 'import asyncio\n'), ((5187, 5202), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (5200, 5202), False, 'import asyncio\n'), ((1195, 1232), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['Constants.RATE_LIMITS'], {}), '(Constants.RATE_LIMITS)\n', (1209, 1232), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((1427, 1463), 'asyncio.wait_for', 'asyncio.wait_for', (['coroutine', 'timeout'], {}), '(coroutine, timeout)\n', (1443, 1463), False, 'import asyncio\n'), ((3492, 3508), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (3502, 3508), False, 'import json\n'), ((3798, 3814), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (3808, 3814), False, 'import json\n'), ((4106, 4122), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (4116, 4122), False, 'import json\n'), ((4811, 4827), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (4821, 4827), False, 'import json\n'), ((5145, 5161), 'json.dumps', 'json.dumps', (['resp'], {}), '(resp)\n', (5155, 5161), False, 'import json\n'), ((5487, 5498), 'time.time', 'time.time', ([], {}), '()\n', (5496, 5498), False, 'import time\n')]
from decimal import Decimal import pandas as pd import threading from typing import ( Any, Dict, Set, Tuple, Optional, TYPE_CHECKING, ) from hummingbot.client.performance_analysis import PerformanceAnalysis from hummingbot.core.utils.exchange_rate_conversion import ExchangeRateConversion from hummingbot.market.market_base import MarketBase from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple s_float_0 = float(0) if TYPE_CHECKING: from hummingbot.client.hummingbot_application import HummingbotApplication class HistoryCommand: def history(self, # type: HummingbotApplication ): if threading.current_thread() != threading.main_thread(): self.ev_loop.call_soon_threadsafe(self.history) return if not all(market.ready for market in self.markets.values()): self._notify(" History stats are not available before Markets are ready.") return self.list_trades() self.trade_performance_report() def balance_snapshot(self, # type: HummingbotApplication ) -> Dict[str, Dict[str, Decimal]]: snapshot: Dict[str, Any] = {} for market_name in self.markets: balance_dict = self.markets[market_name].get_all_balances() balance_dict = {k.upper(): v for k, v in balance_dict.items()} for asset in self.assets: asset = asset.upper() if asset not in snapshot: snapshot[asset] = {} if asset in balance_dict: snapshot[asset][market_name] = Decimal(balance_dict[asset]) else: snapshot[asset][market_name] = Decimal("0") return snapshot def balance_comparison_data_frame(self, # type: HummingbotApplication market_trading_pair_stats: Dict[MarketTradingPairTuple, any], ) -> pd.DataFrame: if len(self.starting_balances) == 0: self._notify(" Balance snapshots are not available before bot starts") return rows = [] for market_trading_pair_tuple in self.market_trading_pair_tuples: market: MarketBase = market_trading_pair_tuple.market for asset in set(a.upper() for a in self.assets): asset_delta: Dict[str, Decimal] = market_trading_pair_stats[market_trading_pair_tuple]["asset"].get( asset, {"delta": Decimal("0")}) starting_balance = self.starting_balances.get(asset).get(market.name) current_balance = self.balance_snapshot().get(asset).get(market.name) rows.append([market.display_name, asset, f"{starting_balance:.4f}", f"{current_balance:.4f}", f"{current_balance - starting_balance:.4f}", f"{asset_delta['delta']:.4f}", f"{ExchangeRateConversion.get_instance().adjust_token_rate(asset, Decimal(1)):.4f}"]) df = pd.DataFrame(rows, index=None, columns=["Market", "Asset", "Starting", "Current", "Net_Delta", "Trade_Delta", "Conversion_Rate"]) return df def _calculate_trade_performance(self, # type: HummingbotApplication ) -> Tuple[Dict, Dict]: raw_queried_trades = self._get_trades_from_session(self.init_time) current_strategy_name: str = self.markets_recorder.strategy_name performance_analysis: PerformanceAnalysis = PerformanceAnalysis() trade_performance_stats, market_trading_pair_stats = performance_analysis.calculate_trade_performance( current_strategy_name, self.market_trading_pair_tuples, raw_queried_trades, self.starting_balances ) return trade_performance_stats, market_trading_pair_stats def calculate_profitability(self, # type: HummingbotApplication ) -> Decimal: """ Determines the profitability of the trading bot. This function is used by the KillSwitch class. Must be updated if the method of performance report gets updated. """ if not self.markets_recorder: return Decimal("0.0") trade_performance_stats, _ = self._calculate_trade_performance() portfolio_delta_percentage: Decimal = trade_performance_stats["portfolio_delta_percentage"] return portfolio_delta_percentage def trade_performance_report(self, # type: HummingbotApplication ) -> Optional[pd.DataFrame]: if len(self.market_trading_pair_tuples) == 0 or self.markets_recorder is None: self._notify(" Performance analysis is not available when the bot is stopped.") return try: trade_performance_stats, market_trading_pair_stats = self._calculate_trade_performance() primary_quote_asset: str = self.market_trading_pair_tuples[0].quote_asset.upper() trade_performance_status_line = [] market_df_data: Set[Tuple[str, str, Decimal, Decimal, str, str]] = set() market_df_columns = ["Market", "Trading_Pair", "Start_Price", "End_Price", "Total_Value_Delta", "Profit"] for market_trading_pair_tuple, trading_pair_stats in market_trading_pair_stats.items(): market_df_data.add(( market_trading_pair_tuple.market.display_name, market_trading_pair_tuple.trading_pair.upper(), trading_pair_stats["starting_quote_rate"], trading_pair_stats["end_quote_rate"], f"{trading_pair_stats['trading_pair_delta']:.8f} {primary_quote_asset}", f"{trading_pair_stats['trading_pair_delta_percentage']:.4f} %" )) inventory_df: pd.DataFrame = self.balance_comparison_data_frame(market_trading_pair_stats) market_df: pd.DataFrame = pd.DataFrame(data=list(market_df_data), columns=market_df_columns) portfolio_delta: Decimal = trade_performance_stats["portfolio_delta"] portfolio_delta_percentage: Decimal = trade_performance_stats["portfolio_delta_percentage"] trade_performance_status_line.extend(["", " Inventory:"] + [" " + line for line in inventory_df.to_string().split("\n")]) trade_performance_status_line.extend(["", " Market Trading Pair Performance:"] + [" " + line for line in market_df.to_string().split("\n")]) trade_performance_status_line.extend( ["", " Portfolio Performance:"] + [f" Quote Value Delta: {portfolio_delta:.7g} {primary_quote_asset}"] + [f" Delta Percentage: {portfolio_delta_percentage:.4f} %"]) self._notify("\n".join(trade_performance_status_line)) except Exception: self.logger().error("Unexpected error running performance analysis.", exc_info=True) self._notify("Error running performance analysis.")
[ "hummingbot.client.performance_analysis.PerformanceAnalysis", "hummingbot.core.utils.exchange_rate_conversion.ExchangeRateConversion.get_instance" ]
[((3198, 3331), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'index': 'None', 'columns': "['Market', 'Asset', 'Starting', 'Current', 'Net_Delta', 'Trade_Delta',\n 'Conversion_Rate']"}), "(rows, index=None, columns=['Market', 'Asset', 'Starting',\n 'Current', 'Net_Delta', 'Trade_Delta', 'Conversion_Rate'])\n", (3210, 3331), True, 'import pandas as pd\n'), ((3735, 3756), 'hummingbot.client.performance_analysis.PerformanceAnalysis', 'PerformanceAnalysis', ([], {}), '()\n', (3754, 3756), False, 'from hummingbot.client.performance_analysis import PerformanceAnalysis\n'), ((676, 702), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (700, 702), False, 'import threading\n'), ((706, 729), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (727, 729), False, 'import threading\n'), ((4474, 4488), 'decimal.Decimal', 'Decimal', (['"""0.0"""'], {}), "('0.0')\n", (4481, 4488), False, 'from decimal import Decimal\n'), ((1658, 1686), 'decimal.Decimal', 'Decimal', (['balance_dict[asset]'], {}), '(balance_dict[asset])\n', (1665, 1686), False, 'from decimal import Decimal\n'), ((1760, 1772), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (1767, 1772), False, 'from decimal import Decimal\n'), ((2552, 2564), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (2559, 2564), False, 'from decimal import Decimal\n'), ((3165, 3175), 'decimal.Decimal', 'Decimal', (['(1)'], {}), '(1)\n', (3172, 3175), False, 'from decimal import Decimal\n'), ((3102, 3139), 'hummingbot.core.utils.exchange_rate_conversion.ExchangeRateConversion.get_instance', 'ExchangeRateConversion.get_instance', ([], {}), '()\n', (3137, 3139), False, 'from hummingbot.core.utils.exchange_rate_conversion import ExchangeRateConversion\n')]
#!/usr/bin/env python import asyncio import logging import time import ujson import websockets import hummingbot.connector.exchange.probit.probit_constants as CONSTANTS from typing import ( Any, AsyncIterable, Dict, List, Optional, ) from hummingbot.connector.exchange.probit.probit_auth import ProbitAuth from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.logger import HummingbotLogger class ProbitAPIUserStreamDataSource(UserStreamTrackerDataSource): MAX_RETRIES = 20 MESSAGE_TIMEOUT = 30.0 PING_TIMEOUT = 10.0 _logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._logger is None: cls._logger = logging.getLogger(__name__) return cls._logger def __init__(self, probit_auth: ProbitAuth, trading_pairs: Optional[List[str]] = [], domain: str = "com"): self._domain: str = domain self._websocket_client: websockets.WebSocketClientProtocol = None self._probit_auth: ProbitAuth = probit_auth self._trading_pairs = trading_pairs self._last_recv_time: float = 0 super().__init__() @property def exchange_name(self) -> str: if self._domain == "com": return CONSTANTS.EXCHANGE_NAME else: return f"{CONSTANTS.EXCHANGE_NAME}_{self._domain}" @property def last_recv_time(self) -> float: return self._last_recv_time async def _init_websocket_connection(self) -> websockets.WebSocketClientProtocol: """ Initialize WebSocket client for UserStreamDataSource """ try: if self._websocket_client is None: self._websocket_client = await websockets.connect(CONSTANTS.WSS_URL.format(self._domain)) return self._websocket_client except Exception: self.logger().network("Unexpected error occured with ProBit WebSocket Connection") async def _authenticate(self, ws: websockets.WebSocketClientProtocol): """ Authenticates user to websocket """ try: auth_payload: Dict[str, Any] = await self._probit_auth.get_ws_auth_payload() await ws.send(ujson.dumps(auth_payload, escape_forward_slashes=False)) auth_resp = await ws.recv() auth_resp: Dict[str, Any] = ujson.loads(auth_resp) if auth_resp["result"] != "ok": self.logger().error(f"Response: {auth_resp}", exc_info=True) raise except asyncio.CancelledError: raise except Exception: self.logger().info("Error occurred when authenticating to user stream. ", exc_info=True) raise async def _subscribe_to_channels(self, ws: websockets.WebSocketClientProtocol): """ Subscribes to Private User Channels """ try: for channel in CONSTANTS.WS_PRIVATE_CHANNELS: sub_payload = { "type": "subscribe", "channel": channel } await ws.send(ujson.dumps(sub_payload)) except asyncio.CancelledError: raise except Exception: self.logger().error(f"Error occured subscribing to {self.exchange_name} private channels. ", exc_info=True) async def _inner_messages(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]: try: while True: msg: str = await ws.recv() self._last_recv_time = int(time.time()) yield msg except websockets.exceptions.ConnectionClosed: return finally: await ws.close() async def listen_for_user_stream(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue) -> AsyncIterable[Any]: """ *required Subscribe to user stream via web socket, and keep the connection open for incoming messages :param ev_loop: ev_loop to execute this function in :param output: an async queue where the incoming messages are stored """ while True: try: ws: websockets.WebSocketClientProtocol = await self._init_websocket_connection() self.logger().info("Authenticating to User Stream...") await self._authenticate(ws) self.logger().info("Successfully authenticated to User Stream.") await self._subscribe_to_channels(ws) self.logger().info("Successfully subscribed to all Private channels.") async for msg in self._inner_messages(ws): output.put_nowait(ujson.loads(msg)) except asyncio.CancelledError: raise except Exception: self.logger().error( "Unexpected error with Probit WebSocket connection. Retrying after 30 seconds...", exc_info=True ) if self._websocket_client is not None: await self._websocket_client.close() self._websocket_client = None await asyncio.sleep(30.0)
[ "hummingbot.connector.exchange.probit.probit_constants.WSS_URL.format" ]
[((780, 807), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (797, 807), False, 'import logging\n'), ((2472, 2494), 'ujson.loads', 'ujson.loads', (['auth_resp'], {}), '(auth_resp)\n', (2483, 2494), False, 'import ujson\n'), ((2335, 2390), 'ujson.dumps', 'ujson.dumps', (['auth_payload'], {'escape_forward_slashes': '(False)'}), '(auth_payload, escape_forward_slashes=False)\n', (2346, 2390), False, 'import ujson\n'), ((3807, 3818), 'time.time', 'time.time', ([], {}), '()\n', (3816, 3818), False, 'import time\n'), ((1864, 1902), 'hummingbot.connector.exchange.probit.probit_constants.WSS_URL.format', 'CONSTANTS.WSS_URL.format', (['self._domain'], {}), '(self._domain)\n', (1888, 1902), True, 'import hummingbot.connector.exchange.probit.probit_constants as CONSTANTS\n'), ((3292, 3316), 'ujson.dumps', 'ujson.dumps', (['sub_payload'], {}), '(sub_payload)\n', (3303, 3316), False, 'import ujson\n'), ((4938, 4954), 'ujson.loads', 'ujson.loads', (['msg'], {}), '(msg)\n', (4949, 4954), False, 'import ujson\n'), ((5427, 5446), 'asyncio.sleep', 'asyncio.sleep', (['(30.0)'], {}), '(30.0)\n', (5440, 5446), False, 'import asyncio\n')]
import re from typing import ( Optional, Tuple) from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_methods import using_exchange from hummingbot.core.utils.tracking_nonce import get_tracking_nonce_low_res RE_4_LETTERS_QUOTE = re.compile(r"^(\w+)(usdt|husd)$") RE_3_LETTERS_QUOTE = re.compile(r"^(\w+)(btc|eth|trx)$") RE_2_LETTERS_QUOTE = re.compile(r"^(\w+)(ht)$") CENTRALIZED = True EXAMPLE_PAIR = "ETH-USDT" DEFAULT_FEES = [0.2, 0.2] def split_trading_pair(trading_pair: str) -> Optional[Tuple[str, str]]: try: m = RE_4_LETTERS_QUOTE.match(trading_pair) if m is None: m = RE_3_LETTERS_QUOTE.match(trading_pair) if m is None: m = RE_2_LETTERS_QUOTE.match(trading_pair) return m.group(1), m.group(2) # Exceptions are now logged as warnings in trading pair fetcher except Exception: return None def convert_from_exchange_trading_pair(exchange_trading_pair: str) -> Optional[str]: if split_trading_pair(exchange_trading_pair) is None: return None base_asset, quote_asset = split_trading_pair(exchange_trading_pair) return f"{base_asset.upper()}-{quote_asset.upper()}" def convert_to_exchange_trading_pair(hb_trading_pair: str) -> str: return hb_trading_pair.replace("-", "").lower() # get timestamp in milliseconds def get_ms_timestamp() -> int: return get_tracking_nonce_low_res() KEYS = { "eunion_api_key": ConfigVar(key="eunion_api_key", prompt="Enter your Eunion API key >>> ", required_if=using_exchange("eunion"), is_secure=True, is_connect_key=True), "eunion_secret_key": ConfigVar(key="eunion_secret_key", prompt="Enter your Eunion secret key >>> ", required_if=using_exchange("eunion"), is_secure=True, is_connect_key=True), }
[ "hummingbot.client.config.config_methods.using_exchange", "hummingbot.core.utils.tracking_nonce.get_tracking_nonce_low_res" ]
[((279, 312), 're.compile', 're.compile', (['"""^(\\\\w+)(usdt|husd)$"""'], {}), "('^(\\\\w+)(usdt|husd)$')\n", (289, 312), False, 'import re\n'), ((334, 369), 're.compile', 're.compile', (['"""^(\\\\w+)(btc|eth|trx)$"""'], {}), "('^(\\\\w+)(btc|eth|trx)$')\n", (344, 369), False, 'import re\n'), ((391, 417), 're.compile', 're.compile', (['"""^(\\\\w+)(ht)$"""'], {}), "('^(\\\\w+)(ht)$')\n", (401, 417), False, 'import re\n'), ((1428, 1456), 'hummingbot.core.utils.tracking_nonce.get_tracking_nonce_low_res', 'get_tracking_nonce_low_res', ([], {}), '()\n', (1454, 1456), False, 'from hummingbot.core.utils.tracking_nonce import get_tracking_nonce_low_res\n'), ((1619, 1643), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""eunion"""'], {}), "('eunion')\n", (1633, 1643), False, 'from hummingbot.client.config.config_methods import using_exchange\n'), ((1879, 1903), 'hummingbot.client.config.config_methods.using_exchange', 'using_exchange', (['"""eunion"""'], {}), "('eunion')\n", (1893, 1903), False, 'from hummingbot.client.config.config_methods import using_exchange\n')]
from typing import Optional, Dict from decimal import Decimal import importlib from hummingbot.client.settings import AllConnectorSettings, ConnectorType from hummingbot.connector.exchange.binance.binance_api_order_book_data_source import BinanceAPIOrderBookDataSource async def get_binance_mid_price(trading_pair: str) -> Dict[str, Decimal]: # Binance is the place to go to for pricing atm prices = await BinanceAPIOrderBookDataSource.get_all_mid_prices() return prices.get(trading_pair, None) async def get_last_price(exchange: str, trading_pair: str) -> Optional[Decimal]: if exchange in AllConnectorSettings.get_connector_settings(): conn_setting = AllConnectorSettings.get_connector_settings()[exchange] if AllConnectorSettings.get_connector_settings()[exchange].type in (ConnectorType.Exchange, ConnectorType.Derivative): module_name = f"{conn_setting.base_name()}_api_order_book_data_source" class_name = "".join([o.capitalize() for o in conn_setting.base_name().split("_")]) + \ "APIOrderBookDataSource" module_path = f"hummingbot.connector.{conn_setting.type.name.lower()}." \ f"{conn_setting.base_name()}.{module_name}" module = getattr(importlib.import_module(module_path), class_name) args = {"trading_pairs": [trading_pair]} if conn_setting.is_sub_domain: args["domain"] = conn_setting.domain_parameter last_prices = await module.get_last_traded_prices(**args) if last_prices: return Decimal(str(last_prices[trading_pair]))
[ "hummingbot.connector.exchange.binance.binance_api_order_book_data_source.BinanceAPIOrderBookDataSource.get_all_mid_prices", "hummingbot.client.settings.AllConnectorSettings.get_connector_settings" ]
[((416, 466), 'hummingbot.connector.exchange.binance.binance_api_order_book_data_source.BinanceAPIOrderBookDataSource.get_all_mid_prices', 'BinanceAPIOrderBookDataSource.get_all_mid_prices', ([], {}), '()\n', (464, 466), False, 'from hummingbot.connector.exchange.binance.binance_api_order_book_data_source import BinanceAPIOrderBookDataSource\n'), ((611, 656), 'hummingbot.client.settings.AllConnectorSettings.get_connector_settings', 'AllConnectorSettings.get_connector_settings', ([], {}), '()\n', (654, 656), False, 'from hummingbot.client.settings import AllConnectorSettings, ConnectorType\n'), ((681, 726), 'hummingbot.client.settings.AllConnectorSettings.get_connector_settings', 'AllConnectorSettings.get_connector_settings', ([], {}), '()\n', (724, 726), False, 'from hummingbot.client.settings import AllConnectorSettings, ConnectorType\n'), ((1282, 1318), 'importlib.import_module', 'importlib.import_module', (['module_path'], {}), '(module_path)\n', (1305, 1318), False, 'import importlib\n'), ((748, 793), 'hummingbot.client.settings.AllConnectorSettings.get_connector_settings', 'AllConnectorSettings.get_connector_settings', ([], {}), '()\n', (791, 793), False, 'from hummingbot.client.settings import AllConnectorSettings, ConnectorType\n')]
import logging from typing import Optional from hummingbot.connector.exchange.loopring.loopring_api_order_book_data_source import LoopringAPIOrderBookDataSource from hummingbot.connector.exchange.loopring.loopring_api_user_stream_data_source import LoopringAPIUserStreamDataSource from hummingbot.connector.exchange.loopring.loopring_auth import LoopringAuth from hummingbot.core.data_type.user_stream_tracker import UserStreamTracker from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from hummingbot.logger import HummingbotLogger class LoopringUserStreamTracker(UserStreamTracker): _krust_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._krust_logger is None: cls._krust_logger = logging.getLogger(__name__) return cls._krust_logger def __init__(self, orderbook_tracker_data_source: LoopringAPIOrderBookDataSource, loopring_auth: LoopringAuth): self._orderbook_tracker_data_source = orderbook_tracker_data_source self._loopring_auth: LoopringAuth = loopring_auth super().__init__(data_source=LoopringAPIUserStreamDataSource( orderbook_tracker_data_source=self._orderbook_tracker_data_source, loopring_auth=self._loopring_auth)) @property def data_source(self) -> UserStreamTrackerDataSource: if not self._data_source: self._data_source = LoopringAPIUserStreamDataSource( orderbook_tracker_data_source=self._orderbook_tracker_data_source, loopring_auth=self._loopring_auth) return self._data_source @property def exchange_name(self) -> str: return "loopring" async def start(self): self._user_stream_tracking_task = safe_ensure_future( self.data_source.listen_for_user_stream(self._user_stream) ) await safe_gather(self._user_stream_tracking_task)
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.connector.exchange.loopring.loopring_api_user_stream_data_source.LoopringAPIUserStreamDataSource" ]
[((908, 935), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (925, 935), False, 'import logging\n'), ((1590, 1728), 'hummingbot.connector.exchange.loopring.loopring_api_user_stream_data_source.LoopringAPIUserStreamDataSource', 'LoopringAPIUserStreamDataSource', ([], {'orderbook_tracker_data_source': 'self._orderbook_tracker_data_source', 'loopring_auth': 'self._loopring_auth'}), '(orderbook_tracker_data_source=self.\n _orderbook_tracker_data_source, loopring_auth=self._loopring_auth)\n', (1621, 1728), False, 'from hummingbot.connector.exchange.loopring.loopring_api_user_stream_data_source import LoopringAPIUserStreamDataSource\n'), ((2052, 2096), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['self._user_stream_tracking_task'], {}), '(self._user_stream_tracking_task)\n', (2063, 2096), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((1291, 1429), 'hummingbot.connector.exchange.loopring.loopring_api_user_stream_data_source.LoopringAPIUserStreamDataSource', 'LoopringAPIUserStreamDataSource', ([], {'orderbook_tracker_data_source': 'self._orderbook_tracker_data_source', 'loopring_auth': 'self._loopring_auth'}), '(orderbook_tracker_data_source=self.\n _orderbook_tracker_data_source, loopring_auth=self._loopring_auth)\n', (1322, 1429), False, 'from hummingbot.connector.exchange.loopring.loopring_api_user_stream_data_source import LoopringAPIUserStreamDataSource\n')]
import logging from decimal import Decimal import asyncio import aiohttp from typing import Dict, Any, List, Optional import json import time import ssl import copy from hummingbot.logger.struct_logger import METRICS_LOG_LEVEL from hummingbot.core.event.events import TradeFee from hummingbot.core.utils import async_ttl_cache from hummingbot.core.network_iterator import NetworkStatus from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather from hummingbot.logger import HummingbotLogger from hummingbot.core.utils.tracking_nonce import get_tracking_nonce from hummingbot.core.utils.estimate_fee import estimate_fee from hummingbot.core.data_type.limit_order import LimitOrder from hummingbot.core.data_type.cancellation_result import CancellationResult from hummingbot.core.event.events import ( MarketEvent, BuyOrderCreatedEvent, SellOrderCreatedEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent, MarketOrderFailureEvent, OrderFilledEvent, OrderType, TradeType, PositionSide, PositionAction ) from hummingbot.connector.derivative_base import DerivativeBase from hummingbot.connector.derivative.mcdex.mcdex_in_flight_order import McdexInFlightOrder from hummingbot.client.settings import GATEAWAY_CA_CERT_PATH, GATEAWAY_CLIENT_CERT_PATH, GATEAWAY_CLIENT_KEY_PATH from hummingbot.client.config.global_config_map import global_config_map from hummingbot.connector.derivative.position import Position s_logger = None s_decimal_0 = Decimal("0") s_decimal_NaN = Decimal("nan") logging.basicConfig(level=METRICS_LOG_LEVEL) class McdexDerivative(DerivativeBase): """ McdexConnector connects with mcdex gateway APIs and provides pricing, user account tracking and trading functionality. """ POLL_INTERVAL = 1.0 UPDATE_ACCOUNT_INTERVAL = 5.0 @classmethod def logger(cls) -> HummingbotLogger: global s_logger if s_logger is None: s_logger = logging.getLogger(__name__) return s_logger def __init__(self, trading_pairs: List[str], wallet_private_key: str, ethereum_rpc_url: str, # not used, but left in place to be consistent with other gateway connectors trading_pair_2_symbol: dict, trading_required: bool = True, ): """ :param trading_pairs: a list of trading pairs :param wallet_private_key: a private key for eth wallet :param trading_required: Whether actual trading is needed. """ super().__init__() self._trading_pairs = trading_pairs self._wallet_private_key = wallet_private_key self._trading_pair_2_symbol = trading_pair_2_symbol self._trading_required = trading_required self._ev_loop = asyncio.get_event_loop() self._shared_client = None self._last_poll_timestamp = 0.0 self._last_account_poll_timestamp = time.time() self._in_flight_orders = {} self._allowances = {} self._status_polling_task = None self._auto_approve_task = None self._real_time_balance_update = False self._poll_notifier = None self._funding_payment_span = [-120, -120] self._fundingPayment = {} @property def name(self): return "mcdex" @property def limit_orders(self) -> List[LimitOrder]: return [ in_flight_order.to_limit_order() for in_flight_order in self._in_flight_orders.values() ] @async_ttl_cache(ttl=5, maxsize=10) async def get_quote_price(self, trading_pair: str, is_buy: bool, amount: Decimal) -> Optional[Decimal]: """ Retrieves a quote price. :param trading_pair: The market trading pair :param is_buy: True for an intention to buy, False for an intention to sell :param amount: The amount required (in base token unit) :return: The quote price. """ try: side = "buy" if is_buy else "sell" resp = await self._api_request("get", "mcdex/price", {"symbol": self._trading_pair_2_symbol[trading_pair], "amount": str(amount if is_buy else - amount)}) if resp["price"] is not None: return Decimal(str(resp["price"])) except asyncio.CancelledError: raise except Exception as e: self.logger().network( f"Error getting quote price for {trading_pair} {side} order for {amount} amount.", exc_info=True, app_warning_msg=str(e) ) async def get_order_price(self, trading_pair: str, is_buy: bool, amount: Decimal) -> Decimal: """ This is simply the quote price """ return await self.get_quote_price(trading_pair, is_buy, amount) def buy(self, trading_pair: str, amount: Decimal, order_type: OrderType, price: Decimal, **kwargs) -> str: """ Buys an amount of base token for a given price (or cheaper). :param trading_pair: The market trading pair :param amount: The order amount (in base token unit) :param order_type: Any order type is fine, not needed for this. :param price: The maximum price for the order. :param position_action: Either OPEN or CLOSE position action. :return: A newly created order id (internal). """ return self.place_order(True, trading_pair, amount, price, kwargs["position_action"]) def sell(self, trading_pair: str, amount: Decimal, order_type: OrderType, price: Decimal, **kwargs) -> str: """ Sells an amount of base token for a given price (or at a higher price). :param trading_pair: The market trading pair :param amount: The order amount (in base token unit) :param order_type: Any order type is fine, not needed for this. :param price: The minimum price for the order. :param position_action: Either OPEN or CLOSE position action. :return: A newly created order id (internal). """ return self.place_order(False, trading_pair, amount, price, kwargs["position_action"]) def place_order(self, is_buy: bool, trading_pair: str, amount: Decimal, price: Decimal, position_action: PositionAction) -> str: """ Places an order. :param is_buy: True for buy order :param trading_pair: The market trading pair :param amount: The order amount (in base token unit) :param price: The minimum price for the order. :param position_action: Either OPEN or CLOSE position action. :return: A newly created order id (internal). """ side = TradeType.BUY if is_buy else TradeType.SELL order_id = f"{side.name.lower()}-{trading_pair}-{get_tracking_nonce()}" safe_ensure_future(self._create_order(side, order_id, trading_pair, amount, price, position_action)) return order_id async def _create_order(self, trade_type: TradeType, order_id: str, trading_pair: str, amount: Decimal, price: Decimal, position_action: PositionAction): """ Calls buy or sell API end point to place an order, starts tracking the order and triggers relevant order events. :param trade_type: BUY or SELL :param order_id: Internal order id (also called client_order_id) :param trading_pair: The market to place order :param amount: The order amount (in base token value) :param price: The order price :param position_action: Either OPEN or CLOSE position action. """ amount = self.quantize_order_amount(trading_pair, amount) price = self.quantize_order_price(trading_pair, price) api_params = { "symbol": self._trading_pair_2_symbol[trading_pair], "amount": str(amount if trade_type == TradeType.BUY else -amount), "limitPrice": str(price) } if position_action == PositionAction.CLOSE: api_params.update({"isCloseOnly": True}) self.start_tracking_order(order_id, None, trading_pair, trade_type, price, amount, self._leverage[trading_pair], position_action.name) try: order_result = await self._api_request("post", "mcdex/trade", api_params) hash = order_result.get("txHash") tracked_order = self._in_flight_orders.get(order_id) if tracked_order is not None: self.logger().info(f"Created {trade_type.name} order {order_id} txHash: {hash} " f"for {amount} {trading_pair}.") tracked_order.update_exchange_order_id(hash) if hash is not None: tracked_order.fee_asset = "ETH" tracked_order.executed_amount_base = amount tracked_order.executed_amount_quote = amount * price event_tag = MarketEvent.BuyOrderCreated if trade_type is TradeType.BUY else MarketEvent.SellOrderCreated event_class = BuyOrderCreatedEvent if trade_type is TradeType.BUY else SellOrderCreatedEvent self.trigger_event(event_tag, event_class(self.current_timestamp, OrderType.LIMIT, trading_pair, amount, price, order_id, hash, leverage=self._leverage[trading_pair], position=position_action.name)) else: self.trigger_event(MarketEvent.OrderFailure, MarketOrderFailureEvent(self.current_timestamp, order_id, OrderType.LIMIT)) except asyncio.CancelledError: raise except Exception as e: self.stop_tracking_order(order_id) self.logger().network( f"Error submitting {trade_type.name} order to Mcdex for " f"{amount} {trading_pair} " f"{price}.", exc_info=True, app_warning_msg=str(e) ) self.trigger_event(MarketEvent.OrderFailure, MarketOrderFailureEvent(self.current_timestamp, order_id, OrderType.LIMIT)) def start_tracking_order(self, order_id: str, exchange_order_id: str, trading_pair: str, trade_type: TradeType, price: Decimal, amount: Decimal, leverage: int, position: str,): """ Starts tracking an order by simply adding it into _in_flight_orders dictionary. """ self._in_flight_orders[order_id] = McdexInFlightOrder( client_order_id=order_id, exchange_order_id=exchange_order_id, trading_pair=trading_pair, order_type=OrderType.LIMIT, trade_type=trade_type, price=price, amount=amount, leverage=leverage, position=position ) def stop_tracking_order(self, order_id: str): """ Stops tracking an order by simply removing it from _in_flight_orders dictionary. """ if order_id in self._in_flight_orders: del self._in_flight_orders[order_id] async def _update_order_status(self): """ Calls REST API to get status update for each in-flight order. """ if len(self._in_flight_orders) > 0: tracked_orders = list(self._in_flight_orders.values()) tasks = [] for tracked_order in tracked_orders: order_id = await tracked_order.get_exchange_order_id() tasks.append(self._api_request("get", "mcdex/receipt", {"txHash": order_id})) update_results = await safe_gather(*tasks, return_exceptions=True) for update_result in update_results: self.logger().info(f"Polling for order status updates of {len(tasks)} orders.") if isinstance(update_result, Exception): raise update_result if "txHash" not in update_result: self.logger().info(f"_update_order_status txHash not in resp: {update_result}") continue if update_result["confirmed"] is True: if update_result["receipt"]["status"] == 1: fee = estimate_fee("mcdex", False) fee = TradeFee(fee.percent, [("ETH", Decimal(str(update_result["receipt"]["gasUsed"])))]) self.trigger_event( MarketEvent.OrderFilled, OrderFilledEvent( self.current_timestamp, tracked_order.client_order_id, tracked_order.trading_pair, tracked_order.trade_type, tracked_order.order_type, Decimal(str(tracked_order.price)), Decimal(str(tracked_order.amount)), fee, exchange_trade_id=order_id, leverage=self._leverage[tracked_order.trading_pair], position=tracked_order.position ) ) tracked_order.last_state = "FILLED" self.logger().info(f"The {tracked_order.trade_type.name} order " f"{tracked_order.client_order_id} has completed " f"according to order status API.") event_tag = MarketEvent.BuyOrderCompleted if tracked_order.trade_type is TradeType.BUY \ else MarketEvent.SellOrderCompleted event_class = BuyOrderCompletedEvent if tracked_order.trade_type is TradeType.BUY \ else SellOrderCompletedEvent self.trigger_event(event_tag, event_class(self.current_timestamp, tracked_order.client_order_id, tracked_order.base_asset, tracked_order.quote_asset, tracked_order.fee_asset, tracked_order.executed_amount_base, tracked_order.executed_amount_quote, float(fee.fee_amount_in_quote(tracked_order.trading_pair, Decimal(str(tracked_order.price)), Decimal(str(tracked_order.amount)))), # this ignores the gas fee, which is fine for now tracked_order.order_type)) self.stop_tracking_order(tracked_order.client_order_id) else: self.logger().info( f"The market order {tracked_order.client_order_id} has failed according to order status API. ") self.trigger_event(MarketEvent.OrderFailure, MarketOrderFailureEvent( self.current_timestamp, tracked_order.client_order_id, tracked_order.order_type )) self.stop_tracking_order(tracked_order.client_order_id) def get_taker_order_type(self): return OrderType.LIMIT def get_order_price_quantum(self, trading_pair: str, price: Decimal) -> Decimal: return Decimal("1e-7") def get_order_size_quantum(self, trading_pair: str, order_size: Decimal) -> Decimal: return Decimal("1e-7") @property def ready(self): return all(self.status_dict.values()) @property def status_dict(self) -> Dict[str, bool]: return { "account_balance": len(self._account_balances) > 0 and len(self._account_available_balances) > 0 if self._trading_required else True, "funding_info": len(self._funding_info) > 0 } async def start_network(self): if self._trading_required: self._status_polling_task = safe_ensure_future(self._status_polling_loop()) self._funding_info_polling_task = safe_ensure_future(self._funding_info_polling_loop()) async def stop_network(self): if self._status_polling_task is not None: self._status_polling_task.cancel() self._status_polling_task = None if self._funding_info_polling_task is not None: self._funding_info_polling_task.cancel() self._funding_info_polling_task = None async def check_network(self) -> NetworkStatus: try: response = await self._api_request("get", "api") if response["status"] != "ok": raise Exception(f"Error connecting to Gateway API. HTTP status is {response.status}.") except asyncio.CancelledError: raise except Exception: return NetworkStatus.NOT_CONNECTED return NetworkStatus.CONNECTED def tick(self, timestamp: float): """ Is called automatically by the clock for each clock's tick (1 second by default). It checks if status polling task is due for execution. """ if time.time() - self._last_poll_timestamp > self.POLL_INTERVAL: if self._poll_notifier is not None and not self._poll_notifier.is_set(): self._poll_notifier.set() async def _status_polling_loop(self): while True: try: self._poll_notifier = asyncio.Event() await self._poll_notifier.wait() await safe_gather( self._update_account(), self._update_order_status(), ) self._last_poll_timestamp = self.current_timestamp except asyncio.CancelledError: raise except Exception as e: self.logger().error(str(e), exc_info=True) self.logger().network("Unexpected error while fetching account updates.", exc_info=True, app_warning_msg="Could not fetch accounts from Gateway API.") await asyncio.sleep(0.5) async def _update_account(self): """ Calls REST API to update account status. """ last_tick = self._last_account_poll_timestamp current_tick = self.current_timestamp if (current_tick - last_tick) > self.UPDATE_ACCOUNT_INTERVAL: self._last_account_poll_timestamp = current_tick account_tasks = [] for pair in self._trading_pairs: account_tasks.append(self._api_request("post", "mcdex/account", {"symbol": self._trading_pair_2_symbol[pair]})) accounts = await safe_gather(*account_tasks, return_exceptions=True) for trading_pair, account in zip(self._trading_pairs, accounts): if isinstance(account, Exception): self.logger().network(f"Unexpected error while fetching account info: {str(account)}", exc_info=True, app_warning_msg="Could not fetch new account info from Mcdex protocol. " "Check network connection on gateway.") continue _, quote_token = trading_pair.split("-") self._account_available_balances[quote_token] = Decimal(account["account"]["availableCashBalance"]) self._account_balances[quote_token] = Decimal(account["account"]["marginBalance"]) position = self.quantize_order_amount(trading_pair, Decimal(account["account"]["position"])) if position != Decimal("0"): position_side = PositionSide.LONG if position > 0 else PositionSide.SHORT unrealized_pnl = self.quantize_order_amount(trading_pair, Decimal(account["account"]["pnl"])) entry_price = self.quantize_order_price(trading_pair, Decimal(account["account"]["entryPrice"])) leverage = self._leverage[trading_pair] self._account_positions[trading_pair] = Position( trading_pair=trading_pair, position_side=position_side, unrealized_pnl=unrealized_pnl, entry_price=entry_price, amount=position, leverage=leverage ) else: if trading_pair in self._account_positions: del self._account_positions[trading_pair] self._in_flight_orders_snapshot = {k: copy.copy(v) for k, v in self._in_flight_orders.items()} self._in_flight_orders_snapshot_timestamp = self.current_timestamp async def _funding_info_polling_loop(self): while True: try: funding_info_tasks = [] for pair in self._trading_pairs: funding_info_tasks.append(self._api_request("get", "mcdex/perpetual", {"symbol": self._trading_pair_2_symbol[pair]})) funding_infos = await safe_gather(*funding_info_tasks, return_exceptions=True) for trading_pair, funding_info in zip(self._trading_pairs, funding_infos): if isinstance(funding_info, Exception): self.logger().network(f"Unexpected error while fetching funding info: {str(funding_info)}", exc_info=True, app_warning_msg="Could not fetch new funding info from Mcdex protocol. " "Check network connection on gateway.") continue self._funding_info[trading_pair] = { "nextFundingTime": time.time(), "rate": funding_info["perpetual"]["fundingRate"] } except Exception: self.logger().network("Unexpected error while fetching funding info.", exc_info=True, app_warning_msg="Could not fetch new funding info from Mcdex protocol. " "Check network connection on gateway.") await asyncio.sleep(30) def get_funding_info(self, trading_pair): return self._funding_info[trading_pair] def set_leverage(self, trading_pair: str, leverage: int = 1): self._leverage[trading_pair] = leverage async def _http_client(self) -> aiohttp.ClientSession: """ :returns Shared client session instance """ if self._shared_client is None: ssl_ctx = ssl.create_default_context(cafile=GATEAWAY_CA_CERT_PATH) ssl_ctx.load_cert_chain(GATEAWAY_CLIENT_CERT_PATH, GATEAWAY_CLIENT_KEY_PATH) conn = aiohttp.TCPConnector(ssl_context=ssl_ctx) self._shared_client = aiohttp.ClientSession(connector=conn) return self._shared_client async def _api_request(self, method: str, path_url: str, params: Dict[str, Any] = {}) -> Dict[str, Any]: """ Sends an aiohttp request and waits for a response. :param method: The HTTP method, e.g. get or post :param path_url: The path url or the API end point :param params: A dictionary of required params for the end point :returns A response in json format. """ base_url = f"https://{global_config_map['gateway_api_host'].value}:" \ f"{global_config_map['gateway_api_port'].value}" url = f"{base_url}/{path_url}" client = await self._http_client() if method == "get": if len(params) > 0: response = await client.get(url, params=params) else: response = await client.get(url) elif method == "post": params["privateKey"] = self._wallet_private_key if params["privateKey"][:2] != "0x": params["privateKey"] = "0x" + params["privateKey"] response = await client.post(url, data=params) parsed_response = json.loads(await response.text()) if response.status != 200: err_msg = "" if "error" in parsed_response: err_msg = f" Message: {parsed_response['error']}" raise IOError(f"Error fetching data from {url}. HTTP status is {response.status}.{err_msg}") if "error" in parsed_response: raise Exception(f"Error: {parsed_response['error']}") return parsed_response async def cancel_all(self, timeout_seconds: float) -> List[CancellationResult]: return [] @property def in_flight_orders(self) -> Dict[str, McdexInFlightOrder]: return self._in_flight_orders
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.connector.derivative.position.Position", "hummingbot.core.utils.async_ttl_cache", "hummingbot.core.utils.tracking_nonce.get_tracking_nonce", "hummingbot.core.utils.estimate_fee.estimate_fee", "hummingbot.core.event.events.MarketOrderFailureEvent...
[((1503, 1515), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (1510, 1515), False, 'from decimal import Decimal\n'), ((1532, 1546), 'decimal.Decimal', 'Decimal', (['"""nan"""'], {}), "('nan')\n", (1539, 1546), False, 'from decimal import Decimal\n'), ((1547, 1591), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'METRICS_LOG_LEVEL'}), '(level=METRICS_LOG_LEVEL)\n', (1566, 1591), False, 'import logging\n'), ((3564, 3598), 'hummingbot.core.utils.async_ttl_cache', 'async_ttl_cache', ([], {'ttl': '(5)', 'maxsize': '(10)'}), '(ttl=5, maxsize=10)\n', (3579, 3598), False, 'from hummingbot.core.utils import async_ttl_cache\n'), ((2830, 2854), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2852, 2854), False, 'import asyncio\n'), ((2974, 2985), 'time.time', 'time.time', ([], {}), '()\n', (2983, 2985), False, 'import time\n'), ((11096, 11336), 'hummingbot.connector.derivative.mcdex.mcdex_in_flight_order.McdexInFlightOrder', 'McdexInFlightOrder', ([], {'client_order_id': 'order_id', 'exchange_order_id': 'exchange_order_id', 'trading_pair': 'trading_pair', 'order_type': 'OrderType.LIMIT', 'trade_type': 'trade_type', 'price': 'price', 'amount': 'amount', 'leverage': 'leverage', 'position': 'position'}), '(client_order_id=order_id, exchange_order_id=\n exchange_order_id, trading_pair=trading_pair, order_type=OrderType.\n LIMIT, trade_type=trade_type, price=price, amount=amount, leverage=\n leverage, position=position)\n', (11114, 11336), False, 'from hummingbot.connector.derivative.mcdex.mcdex_in_flight_order import McdexInFlightOrder\n'), ((16670, 16685), 'decimal.Decimal', 'Decimal', (['"""1e-7"""'], {}), "('1e-7')\n", (16677, 16685), False, 'from decimal import Decimal\n'), ((16791, 16806), 'decimal.Decimal', 'Decimal', (['"""1e-7"""'], {}), "('1e-7')\n", (16798, 16806), False, 'from decimal import Decimal\n'), ((1969, 1996), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1986, 1996), False, 'import logging\n'), ((20133, 20184), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*account_tasks'], {'return_exceptions': '(True)'}), '(*account_tasks, return_exceptions=True)\n', (20144, 20184), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((20767, 20818), 'decimal.Decimal', 'Decimal', (["account['account']['availableCashBalance']"], {}), "(account['account']['availableCashBalance'])\n", (20774, 20818), False, 'from decimal import Decimal\n'), ((20869, 20913), 'decimal.Decimal', 'Decimal', (["account['account']['marginBalance']"], {}), "(account['account']['marginBalance'])\n", (20876, 20913), False, 'from decimal import Decimal\n'), ((21967, 21979), 'copy.copy', 'copy.copy', (['v'], {}), '(v)\n', (21976, 21979), False, 'import copy\n'), ((24156, 24212), 'ssl.create_default_context', 'ssl.create_default_context', ([], {'cafile': 'GATEAWAY_CA_CERT_PATH'}), '(cafile=GATEAWAY_CA_CERT_PATH)\n', (24182, 24212), False, 'import ssl\n'), ((24321, 24362), 'aiohttp.TCPConnector', 'aiohttp.TCPConnector', ([], {'ssl_context': 'ssl_ctx'}), '(ssl_context=ssl_ctx)\n', (24341, 24362), False, 'import aiohttp\n'), ((24397, 24434), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {'connector': 'conn'}), '(connector=conn)\n', (24418, 24434), False, 'import aiohttp\n'), ((6966, 6986), 'hummingbot.core.utils.tracking_nonce.get_tracking_nonce', 'get_tracking_nonce', ([], {}), '()\n', (6984, 6986), False, 'from hummingbot.core.utils.tracking_nonce import get_tracking_nonce\n'), ((12315, 12358), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*tasks'], {'return_exceptions': '(True)'}), '(*tasks, return_exceptions=True)\n', (12326, 12358), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((18444, 18455), 'time.time', 'time.time', ([], {}), '()\n', (18453, 18455), False, 'import time\n'), ((18751, 18766), 'asyncio.Event', 'asyncio.Event', ([], {}), '()\n', (18764, 18766), False, 'import asyncio\n'), ((20978, 21017), 'decimal.Decimal', 'Decimal', (["account['account']['position']"], {}), "(account['account']['position'])\n", (20985, 21017), False, 'from decimal import Decimal\n'), ((21046, 21058), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (21053, 21058), False, 'from decimal import Decimal\n'), ((21485, 21649), 'hummingbot.connector.derivative.position.Position', 'Position', ([], {'trading_pair': 'trading_pair', 'position_side': 'position_side', 'unrealized_pnl': 'unrealized_pnl', 'entry_price': 'entry_price', 'amount': 'position', 'leverage': 'leverage'}), '(trading_pair=trading_pair, position_side=position_side,\n unrealized_pnl=unrealized_pnl, entry_price=entry_price, amount=position,\n leverage=leverage)\n', (21493, 21649), False, 'from hummingbot.connector.derivative.position import Position\n'), ((23734, 23751), 'asyncio.sleep', 'asyncio.sleep', (['(30)'], {}), '(30)\n', (23747, 23751), False, 'import asyncio\n'), ((9886, 9960), 'hummingbot.core.event.events.MarketOrderFailureEvent', 'MarketOrderFailureEvent', (['self.current_timestamp', 'order_id', 'OrderType.LIMIT'], {}), '(self.current_timestamp, order_id, OrderType.LIMIT)\n', (9909, 9960), False, 'from hummingbot.core.event.events import MarketEvent, BuyOrderCreatedEvent, SellOrderCreatedEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent, MarketOrderFailureEvent, OrderFilledEvent, OrderType, TradeType, PositionSide, PositionAction\n'), ((10451, 10525), 'hummingbot.core.event.events.MarketOrderFailureEvent', 'MarketOrderFailureEvent', (['self.current_timestamp', 'order_id', 'OrderType.LIMIT'], {}), '(self.current_timestamp, order_id, OrderType.LIMIT)\n', (10474, 10525), False, 'from hummingbot.core.event.events import MarketEvent, BuyOrderCreatedEvent, SellOrderCreatedEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent, MarketOrderFailureEvent, OrderFilledEvent, OrderType, TradeType, PositionSide, PositionAction\n'), ((21224, 21258), 'decimal.Decimal', 'Decimal', (["account['account']['pnl']"], {}), "(account['account']['pnl'])\n", (21231, 21258), False, 'from decimal import Decimal\n'), ((21330, 21371), 'decimal.Decimal', 'Decimal', (["account['account']['entryPrice']"], {}), "(account['account']['entryPrice'])\n", (21337, 21371), False, 'from decimal import Decimal\n'), ((22578, 22634), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*funding_info_tasks'], {'return_exceptions': '(True)'}), '(*funding_info_tasks, return_exceptions=True)\n', (22589, 22634), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((12929, 12957), 'hummingbot.core.utils.estimate_fee.estimate_fee', 'estimate_fee', (['"""mcdex"""', '(False)'], {}), "('mcdex', False)\n", (12941, 12957), False, 'from hummingbot.core.utils.estimate_fee import estimate_fee\n'), ((19453, 19471), 'asyncio.sleep', 'asyncio.sleep', (['(0.5)'], {}), '(0.5)\n', (19466, 19471), False, 'import asyncio\n'), ((23271, 23282), 'time.time', 'time.time', ([], {}), '()\n', (23280, 23282), False, 'import time\n'), ((16129, 16238), 'hummingbot.core.event.events.MarketOrderFailureEvent', 'MarketOrderFailureEvent', (['self.current_timestamp', 'tracked_order.client_order_id', 'tracked_order.order_type'], {}), '(self.current_timestamp, tracked_order.\n client_order_id, tracked_order.order_type)\n', (16152, 16238), False, 'from hummingbot.core.event.events import MarketEvent, BuyOrderCreatedEvent, SellOrderCreatedEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent, MarketOrderFailureEvent, OrderFilledEvent, OrderType, TradeType, PositionSide, PositionAction\n')]
from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_validators import ( is_exchange, is_valid_market_trading_pair ) from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS from decimal import Decimal from hummingbot.client.config.config_helpers import ( minimum_order_amount ) def maker_trading_pair_prompt(): maker_market = cross_exchange_market_making_config_map.get("maker_market").value example = EXAMPLE_PAIRS.get(maker_market) return "Enter the token trading pair you would like to trade on maker market: %s%s >>> " % ( maker_market, f" (e.g. {example})" if example else "", ) def taker_trading_pair_prompt(): taker_market = cross_exchange_market_making_config_map.get("taker_market").value example = EXAMPLE_PAIRS.get(taker_market) return "Enter the token trading pair you would like to trade on taker market: %s%s >>> " % ( taker_market, f" (e.g. {example})" if example else "", ) # strategy specific validators def is_valid_maker_market_trading_pair(value: str) -> bool: maker_market = cross_exchange_market_making_config_map.get("maker_market").value return is_valid_market_trading_pair(maker_market, value) def is_valid_taker_market_trading_pair(value: str) -> bool: taker_market = cross_exchange_market_making_config_map.get("taker_market").value return is_valid_market_trading_pair(taker_market, value) def order_amount_prompt() -> str: trading_pair = cross_exchange_market_making_config_map["maker_market_trading_pair"].value base_asset, quote_asset = trading_pair.split("-") min_amount = minimum_order_amount(trading_pair) return f"What is the amount of {base_asset} per order? (minimum {min_amount}) >>> " def is_valid_order_amount(value: str) -> bool: try: trading_pair = cross_exchange_market_making_config_map["maker_market_trading_pair"].value return Decimal(value) >= minimum_order_amount(trading_pair) except Exception: return False cross_exchange_market_making_config_map = { "maker_market": ConfigVar( key="maker_market", prompt="Enter your maker exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value), ), "taker_market": ConfigVar( key="taker_market", prompt="Enter your taker exchange name >>> ", validator=is_exchange, on_validated=lambda value: required_exchanges.append(value), ), "maker_market_trading_pair": ConfigVar( key="maker_market_trading_pair", prompt=maker_trading_pair_prompt, validator=is_valid_maker_market_trading_pair ), "taker_market_trading_pair": ConfigVar( key="taker_market_trading_pair", prompt=taker_trading_pair_prompt, validator=is_valid_taker_market_trading_pair ), "min_profitability": ConfigVar( key="min_profitability", prompt="What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> ", type_str="decimal", ), "order_amount": ConfigVar( key="order_amount", prompt=order_amount_prompt, type_str="decimal", validator=is_valid_order_amount, ), "adjust_order_enabled": ConfigVar( key="adjust_order_enabled", prompt="", default=True, type_str="bool", required_if=lambda: False, ), "active_order_canceling": ConfigVar( key="active_order_canceling", prompt="", type_str="bool", default=True, required_if=lambda: False, ), # Setting the default threshold to 0.05 when to active_order_canceling is disabled # prevent canceling orders after it has expired "cancel_order_threshold": ConfigVar( key="cancel_order_threshold", prompt="", default=0.05, type_str="decimal", required_if=lambda: False, ), "limit_order_min_expiration": ConfigVar( key="limit_order_min_expiration", prompt="", default=130.0, type_str="float", required_if=lambda: False, ), "top_depth_tolerance": ConfigVar( key="top_depth_tolerance", prompt="", default=0, type_str="decimal", required_if=lambda: False, ), "anti_hysteresis_duration": ConfigVar( key="anti_hysteresis_duration", prompt="", default=60, type_str="float", required_if=lambda: False, ), "order_size_taker_volume_factor": ConfigVar( key="order_size_taker_volume_factor", prompt="", default=0.25, type_str="decimal", required_if=lambda: False, ), "order_size_taker_balance_factor": ConfigVar( key="order_size_taker_balance_factor", prompt="", default=0.995, type_str="decimal", required_if=lambda: False, ), "order_size_portfolio_ratio_limit": ConfigVar( key="order_size_portfolio_ratio_limit", prompt="", default=0.1667, type_str="decimal", required_if=lambda: False, ) }
[ "hummingbot.client.config.config_var.ConfigVar", "hummingbot.client.config.config_helpers.minimum_order_amount", "hummingbot.client.config.config_validators.is_valid_market_trading_pair", "hummingbot.client.settings.EXAMPLE_PAIRS.get", "hummingbot.client.settings.required_exchanges.append" ]
[((483, 514), 'hummingbot.client.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['maker_market'], {}), '(maker_market)\n', (500, 514), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((823, 854), 'hummingbot.client.settings.EXAMPLE_PAIRS.get', 'EXAMPLE_PAIRS.get', (['taker_market'], {}), '(taker_market)\n', (840, 854), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((1218, 1267), 'hummingbot.client.config.config_validators.is_valid_market_trading_pair', 'is_valid_market_trading_pair', (['maker_market', 'value'], {}), '(maker_market, value)\n', (1246, 1267), False, 'from hummingbot.client.config.config_validators import is_exchange, is_valid_market_trading_pair\n'), ((1426, 1475), 'hummingbot.client.config.config_validators.is_valid_market_trading_pair', 'is_valid_market_trading_pair', (['taker_market', 'value'], {}), '(taker_market, value)\n', (1454, 1475), False, 'from hummingbot.client.config.config_validators import is_exchange, is_valid_market_trading_pair\n'), ((1677, 1711), 'hummingbot.client.config.config_helpers.minimum_order_amount', 'minimum_order_amount', (['trading_pair'], {}), '(trading_pair)\n', (1697, 1711), False, 'from hummingbot.client.config.config_helpers import minimum_order_amount\n'), ((2586, 2712), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""maker_market_trading_pair"""', 'prompt': 'maker_trading_pair_prompt', 'validator': 'is_valid_maker_market_trading_pair'}), "(key='maker_market_trading_pair', prompt=maker_trading_pair_prompt,\n validator=is_valid_maker_market_trading_pair)\n", (2595, 2712), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((2773, 2899), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""taker_market_trading_pair"""', 'prompt': 'taker_trading_pair_prompt', 'validator': 'is_valid_taker_market_trading_pair'}), "(key='taker_market_trading_pair', prompt=taker_trading_pair_prompt,\n validator=is_valid_taker_market_trading_pair)\n", (2782, 2899), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((2952, 3118), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""min_profitability"""', 'prompt': '"""What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> """', 'type_str': '"""decimal"""'}), "(key='min_profitability', prompt=\n 'What is the minimum profitability for you to make a trade? (Enter 0.01 to indicate 1%) >>> '\n , type_str='decimal')\n", (2961, 3118), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3161, 3276), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""order_amount"""', 'prompt': 'order_amount_prompt', 'type_str': '"""decimal"""', 'validator': 'is_valid_order_amount'}), "(key='order_amount', prompt=order_amount_prompt, type_str=\n 'decimal', validator=is_valid_order_amount)\n", (3170, 3276), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3340, 3452), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""adjust_order_enabled"""', 'prompt': '""""""', 'default': '(True)', 'type_str': '"""bool"""', 'required_if': '(lambda : False)'}), "(key='adjust_order_enabled', prompt='', default=True, type_str=\n 'bool', required_if=lambda : False)\n", (3349, 3452), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3525, 3639), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""active_order_canceling"""', 'prompt': '""""""', 'type_str': '"""bool"""', 'default': '(True)', 'required_if': '(lambda : False)'}), "(key='active_order_canceling', prompt='', type_str='bool', default\n =True, required_if=lambda : False)\n", (3534, 3639), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((3851, 3968), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""cancel_order_threshold"""', 'prompt': '""""""', 'default': '(0.05)', 'type_str': '"""decimal"""', 'required_if': '(lambda : False)'}), "(key='cancel_order_threshold', prompt='', default=0.05, type_str=\n 'decimal', required_if=lambda : False)\n", (3860, 3968), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((4045, 4164), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""limit_order_min_expiration"""', 'prompt': '""""""', 'default': '(130.0)', 'type_str': '"""float"""', 'required_if': '(lambda : False)'}), "(key='limit_order_min_expiration', prompt='', default=130.0,\n type_str='float', required_if=lambda : False)\n", (4054, 4164), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((4235, 4346), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""top_depth_tolerance"""', 'prompt': '""""""', 'default': '(0)', 'type_str': '"""decimal"""', 'required_if': '(lambda : False)'}), "(key='top_depth_tolerance', prompt='', default=0, type_str=\n 'decimal', required_if=lambda : False)\n", (4244, 4346), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((4421, 4536), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""anti_hysteresis_duration"""', 'prompt': '""""""', 'default': '(60)', 'type_str': '"""float"""', 'required_if': '(lambda : False)'}), "(key='anti_hysteresis_duration', prompt='', default=60, type_str=\n 'float', required_if=lambda : False)\n", (4430, 4536), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((4617, 4741), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""order_size_taker_volume_factor"""', 'prompt': '""""""', 'default': '(0.25)', 'type_str': '"""decimal"""', 'required_if': '(lambda : False)'}), "(key='order_size_taker_volume_factor', prompt='', default=0.25,\n type_str='decimal', required_if=lambda : False)\n", (4626, 4741), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((4824, 4950), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""order_size_taker_balance_factor"""', 'prompt': '""""""', 'default': '(0.995)', 'type_str': '"""decimal"""', 'required_if': '(lambda : False)'}), "(key='order_size_taker_balance_factor', prompt='', default=0.995,\n type_str='decimal', required_if=lambda : False)\n", (4833, 4950), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((5034, 5162), 'hummingbot.client.config.config_var.ConfigVar', 'ConfigVar', ([], {'key': '"""order_size_portfolio_ratio_limit"""', 'prompt': '""""""', 'default': '(0.1667)', 'type_str': '"""decimal"""', 'required_if': '(lambda : False)'}), "(key='order_size_portfolio_ratio_limit', prompt='', default=0.1667,\n type_str='decimal', required_if=lambda : False)\n", (5043, 5162), False, 'from hummingbot.client.config.config_var import ConfigVar\n'), ((1971, 1985), 'decimal.Decimal', 'Decimal', (['value'], {}), '(value)\n', (1978, 1985), False, 'from decimal import Decimal\n'), ((1989, 2023), 'hummingbot.client.config.config_helpers.minimum_order_amount', 'minimum_order_amount', (['trading_pair'], {}), '(trading_pair)\n', (2009, 2023), False, 'from hummingbot.client.config.config_helpers import minimum_order_amount\n'), ((2292, 2324), 'hummingbot.client.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (2317, 2324), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n'), ((2512, 2544), 'hummingbot.client.settings.required_exchanges.append', 'required_exchanges.append', (['value'], {}), '(value)\n', (2537, 2544), False, 'from hummingbot.client.settings import required_exchanges, EXAMPLE_PAIRS\n')]
#!/usr/bin/env python import asyncio import logging import aiohttp import ujson import time import pandas as pd from collections import defaultdict from typing import Optional, List, Dict, Any, AsyncIterable from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.api_throttler.async_throttler import AsyncThrottler from hummingbot.core.data_type.order_book_message import OrderBookMessage from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource from hummingbot.core.utils.async_utils import safe_ensure_future from hummingbot.logger import HummingbotLogger from hummingbot.connector.exchange.ascend_ex.ascend_ex_active_order_tracker import AscendExActiveOrderTracker from hummingbot.connector.exchange.ascend_ex.ascend_ex_order_book import AscendExOrderBook from hummingbot.connector.exchange.ascend_ex.ascend_ex_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair from hummingbot.connector.exchange.ascend_ex import ascend_ex_constants as CONSTANTS class AscendExAPIOrderBookDataSource(OrderBookTrackerDataSource): MAX_RETRIES = 20 MESSAGE_TIMEOUT = 30.0 SNAPSHOT_TIMEOUT = 10.0 PING_TIMEOUT = 15.0 HEARTBEAT_PING_INTERVAL = 15.0 TRADE_TOPIC_ID = "trades" DIFF_TOPIC_ID = "depth" _logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._logger is None: cls._logger = logging.getLogger(__name__) return cls._logger def __init__(self, shared_client: Optional[aiohttp.ClientSession] = None, throttler: Optional[AsyncThrottler] = None, trading_pairs: List[str] = None): super().__init__(trading_pairs) self._shared_client = shared_client or self._get_session_instance() self._throttler = throttler or self._get_throttler_instance() self._trading_pairs: List[str] = trading_pairs self._message_queue: Dict[str, asyncio.Queue] = defaultdict(asyncio.Queue) @classmethod def _get_session_instance(cls) -> aiohttp.ClientSession: session = aiohttp.ClientSession() return session @classmethod def _get_throttler_instance(cls) -> AsyncThrottler: throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS) return throttler @classmethod async def get_last_traded_prices( cls, trading_pairs: List[str], client: Optional[aiohttp.ClientSession] = None, throttler: Optional[AsyncThrottler] = None ) -> Dict[str, float]: result = {} for trading_pair in trading_pairs: client = client or cls._get_session_instance() throttler = throttler or cls._get_throttler_instance() async with throttler.execute_task(CONSTANTS.TRADES_PATH_URL): resp = await client.get( f"{CONSTANTS.REST_URL}/{CONSTANTS.TRADES_PATH_URL}" f"?symbol={convert_to_exchange_trading_pair(trading_pair)}" ) if resp.status != 200: raise IOError( f"Error fetching last traded prices at {CONSTANTS.EXCHANGE_NAME}. " f"HTTP status is {resp.status}." ) resp_json = await resp.json() if resp_json.get("code") != 0: raise IOError( f"Error fetching last traded prices at {CONSTANTS.EXCHANGE_NAME}. " f"Error is {resp_json.message}." ) trades = resp_json.get("data").get("data") if (len(trades) == 0): continue # last trade is the most recent trade result[trading_pair] = float(trades[-1].get("p")) return result @staticmethod async def fetch_trading_pairs(client: Optional[aiohttp.ClientSession] = None, throttler: Optional[AsyncThrottler] = None) -> List[str]: client = client or AscendExAPIOrderBookDataSource._get_session_instance() throttler = throttler or AscendExAPIOrderBookDataSource._get_throttler_instance() async with throttler.execute_task(CONSTANTS.TICKER_PATH_URL): resp = await client.get(f"{CONSTANTS.REST_URL}/{CONSTANTS.TICKER_PATH_URL}") if resp.status != 200: # Do nothing if the request fails -- there will be no autocomplete for kucoin trading pairs return [] data: Dict[str, Dict[str, Any]] = await resp.json() return [convert_from_exchange_trading_pair(item["symbol"]) for item in data["data"]] @staticmethod async def get_order_book_data(trading_pair: str, client: Optional[aiohttp.ClientSession] = None, throttler: Optional[AsyncThrottler] = None) -> Dict[str, any]: """ Get whole orderbook """ client = client or AscendExAPIOrderBookDataSource._get_session_instance() throttler = throttler or AscendExAPIOrderBookDataSource._get_throttler_instance() async with throttler.execute_task(CONSTANTS.DEPTH_PATH_URL): resp = await client.get( f"{CONSTANTS.REST_URL}/{CONSTANTS.DEPTH_PATH_URL}" f"?symbol={convert_to_exchange_trading_pair(trading_pair)}" ) if resp.status != 200: raise IOError( f"Error fetching OrderBook for {trading_pair} at {CONSTANTS.EXCHANGE_NAME}. " f"HTTP status is {resp.status}." ) data: Dict[str, Any] = await resp.json() if data.get("code") != 0: raise IOError( f"Error fetching OrderBook for {trading_pair} at {CONSTANTS.EXCHANGE_NAME}. " f"Error is {data['reason']}." ) return data["data"] async def get_new_order_book(self, trading_pair: str) -> OrderBook: snapshot: Dict[str, Any] = await self.get_order_book_data(trading_pair, client=self._shared_client, throttler=self._throttler) snapshot_timestamp: float = snapshot.get("data").get("ts") snapshot_msg: OrderBookMessage = AscendExOrderBook.snapshot_message_from_exchange( snapshot.get("data"), snapshot_timestamp, metadata={"trading_pair": trading_pair} ) order_book = self.order_book_create_function() active_order_tracker: AscendExActiveOrderTracker = AscendExActiveOrderTracker() bids, asks = active_order_tracker.convert_snapshot_message_to_order_book_row(snapshot_msg) order_book.apply_snapshot(bids, asks, snapshot_msg.update_id) return order_book async def _subscribe_to_order_book_streams(self) -> aiohttp.ClientWebSocketResponse: try: trading_pairs = ",".join([ convert_to_exchange_trading_pair(trading_pair) for trading_pair in self._trading_pairs ]) subscription_payloads = [ { "op": CONSTANTS.SUB_ENDPOINT_NAME, "ch": f"{topic}:{trading_pairs}" } for topic in [self.DIFF_TOPIC_ID, self.TRADE_TOPIC_ID] ] ws = await aiohttp.ClientSession().ws_connect(url=CONSTANTS.WS_URL, heartbeat=self.HEARTBEAT_PING_INTERVAL) for payload in subscription_payloads: async with self._throttler.execute_task(CONSTANTS.SUB_ENDPOINT_NAME): await ws.send_json(payload) self.logger().info(f"Subscribed to {self._trading_pairs} orderbook trading and delta streams...") return ws except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error occurred subscribing to order book trading and delta streams...") raise async def _handle_ping_message(self, ws: aiohttp.ClientWebSocketResponse): async with self._throttler.execute_task(CONSTANTS.PONG_ENDPOINT_NAME): pong_payload = { "op": "pong" } await ws.send_json(pong_payload) async def _iter_messages(self, ws: aiohttp.ClientWebSocketResponse) -> AsyncIterable[str]: # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect. try: while True: raw_msg = await ws.receive() if raw_msg.type == aiohttp.WSMsgType.CLOSED: raise ConnectionError yield raw_msg.data except Exception: self.logger().error("Unexpected error occurred iterating through websocket messages.", exc_info=True) raise finally: await ws.close() async def listen_for_subscriptions(self): ws = None while True: try: ws = await self._subscribe_to_order_book_streams() async for raw_msg in self._iter_messages(ws): msg = ujson.loads(raw_msg) if msg.get("m", '') == "ping": safe_ensure_future(self._handle_ping_message(ws)) elif (msg.get("m") == self.TRADE_TOPIC_ID): self._message_queue[self.TRADE_TOPIC_ID].put_nowait(msg) elif msg.get("m", '') == self.DIFF_TOPIC_ID: self._message_queue[self.DIFF_TOPIC_ID].put_nowait(msg) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error occurred when listening to order book streams. " "Retrying in 5 seconds...", exc_info=True) await self._sleep(5.0) finally: ws and await ws.close() async def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): msg_queue = self._message_queue[self.TRADE_TOPIC_ID] while True: try: msg = await msg_queue.get() trading_pair: str = convert_from_exchange_trading_pair(msg.get("symbol")) trades = msg.get("data") for trade in trades: trade_timestamp: int = trade.get("ts") trade_msg: OrderBookMessage = AscendExOrderBook.trade_message_from_exchange( trade, trade_timestamp, metadata={"trading_pair": trading_pair} ) output.put_nowait(trade_msg) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...", exc_info=True) async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): msg_queue = self._message_queue[self.DIFF_TOPIC_ID] while True: try: msg = await msg_queue.get() msg_timestamp: int = msg.get("data").get("ts") trading_pair: str = convert_from_exchange_trading_pair(msg.get("symbol")) order_book_message: OrderBookMessage = AscendExOrderBook.diff_message_from_exchange( msg.get("data"), msg_timestamp, metadata={"trading_pair": trading_pair} ) output.put_nowait(order_book_message) except asyncio.CancelledError: raise except Exception as e: self.logger().debug(str(e)) self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...", exc_info=True) await self._sleep(30.0) async def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Listen for orderbook snapshots by fetching orderbook """ while True: try: for trading_pair in self._trading_pairs: try: snapshot: Dict[str, any] = await self.get_order_book_data(trading_pair, client=self._shared_client, throttler=self._throttler) snapshot_timestamp: float = snapshot.get("data").get("ts") snapshot_msg: OrderBookMessage = AscendExOrderBook.snapshot_message_from_exchange( snapshot.get("data"), snapshot_timestamp, metadata={"trading_pair": trading_pair} ) output.put_nowait(snapshot_msg) self.logger().debug(f"Saved order book snapshot for {trading_pair}") # Be careful not to go above API rate limits. await asyncio.sleep(5.0) except asyncio.CancelledError: raise except Exception: self.logger().network( "Unexpected error with WebSocket connection.", exc_info=True, app_warning_msg="Unexpected error with WebSocket connection. Retrying in 5 seconds. " "Check network connection." ) await asyncio.sleep(5.0) this_hour: pd.Timestamp = pd.Timestamp.utcnow().replace(minute=0, second=0, microsecond=0) next_hour: pd.Timestamp = this_hour + pd.Timedelta(hours=1) delta: float = next_hour.timestamp() - time.time() await asyncio.sleep(delta) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error.", exc_info=True) await asyncio.sleep(5.0)
[ "hummingbot.connector.exchange.ascend_ex.ascend_ex_active_order_tracker.AscendExActiveOrderTracker", "hummingbot.connector.exchange.ascend_ex.ascend_ex_utils.convert_to_exchange_trading_pair", "hummingbot.connector.exchange.ascend_ex.ascend_ex_utils.convert_from_exchange_trading_pair", "hummingbot.connector.e...
[((1984, 2010), 'collections.defaultdict', 'defaultdict', (['asyncio.Queue'], {}), '(asyncio.Queue)\n', (1995, 2010), False, 'from collections import defaultdict\n'), ((2108, 2131), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (2129, 2131), False, 'import aiohttp\n'), ((2249, 2286), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['CONSTANTS.RATE_LIMITS'], {}), '(CONSTANTS.RATE_LIMITS)\n', (2263, 2286), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((6342, 6370), 'hummingbot.connector.exchange.ascend_ex.ascend_ex_active_order_tracker.AscendExActiveOrderTracker', 'AscendExActiveOrderTracker', ([], {}), '()\n', (6368, 6370), False, 'from hummingbot.connector.exchange.ascend_ex.ascend_ex_active_order_tracker import AscendExActiveOrderTracker\n'), ((1474, 1501), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1491, 1501), False, 'import logging\n'), ((4478, 4528), 'hummingbot.connector.exchange.ascend_ex.ascend_ex_utils.convert_from_exchange_trading_pair', 'convert_from_exchange_trading_pair', (["item['symbol']"], {}), "(item['symbol'])\n", (4512, 4528), False, 'from hummingbot.connector.exchange.ascend_ex.ascend_ex_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair\n'), ((6724, 6770), 'hummingbot.connector.exchange.ascend_ex.ascend_ex_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (6756, 6770), False, 'from hummingbot.connector.exchange.ascend_ex.ascend_ex_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair\n'), ((9015, 9035), 'ujson.loads', 'ujson.loads', (['raw_msg'], {}), '(raw_msg)\n', (9026, 9035), False, 'import ujson\n'), ((10379, 10493), 'hummingbot.connector.exchange.ascend_ex.ascend_ex_order_book.AscendExOrderBook.trade_message_from_exchange', 'AscendExOrderBook.trade_message_from_exchange', (['trade', 'trade_timestamp'], {'metadata': "{'trading_pair': trading_pair}"}), "(trade, trade_timestamp,\n metadata={'trading_pair': trading_pair})\n", (10424, 10493), False, 'from hummingbot.connector.exchange.ascend_ex.ascend_ex_order_book import AscendExOrderBook\n'), ((13762, 13783), 'pandas.Timedelta', 'pd.Timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (13774, 13783), True, 'import pandas as pd\n'), ((13839, 13850), 'time.time', 'time.time', ([], {}), '()\n', (13848, 13850), False, 'import time\n'), ((13873, 13893), 'asyncio.sleep', 'asyncio.sleep', (['delta'], {}), '(delta)\n', (13886, 13893), False, 'import asyncio\n'), ((7132, 7155), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (7153, 7155), False, 'import aiohttp\n'), ((13643, 13664), 'pandas.Timestamp.utcnow', 'pd.Timestamp.utcnow', ([], {}), '()\n', (13662, 13664), True, 'import pandas as pd\n'), ((14083, 14101), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (14096, 14101), False, 'import asyncio\n'), ((5162, 5208), 'hummingbot.connector.exchange.ascend_ex.ascend_ex_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (5194, 5208), False, 'from hummingbot.connector.exchange.ascend_ex.ascend_ex_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair\n'), ((13037, 13055), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (13050, 13055), False, 'import asyncio\n'), ((2933, 2979), 'hummingbot.connector.exchange.ascend_ex.ascend_ex_utils.convert_to_exchange_trading_pair', 'convert_to_exchange_trading_pair', (['trading_pair'], {}), '(trading_pair)\n', (2965, 2979), False, 'from hummingbot.connector.exchange.ascend_ex.ascend_ex_utils import convert_from_exchange_trading_pair, convert_to_exchange_trading_pair\n'), ((13582, 13600), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (13595, 13600), False, 'import asyncio\n')]
from decimal import Decimal from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from hummingbot.strategy.liquidity_mining.liquidity_mining import LiquidityMiningStrategy from hummingbot.strategy.liquidity_mining.liquidity_mining_config_map import liquidity_mining_config_map as c_map def start(self): exchange = c_map.get("exchange").value.lower() markets_text = c_map.get("markets").value initial_spread = c_map.get("initial_spread").value / Decimal("100") order_refresh_time = c_map.get("order_refresh_time").value order_refresh_tolerance_pct = c_map.get("order_refresh_tolerance_pct").value / Decimal("100") reserved_balances = c_map.get("reserved_balances").value or {} reserved_balances = {k: Decimal(str(v)) for k, v in reserved_balances.items()} markets = list(markets_text.split(",")) self._initialize_markets([(exchange, markets)]) exchange = self.markets[exchange] market_infos = {} for market in markets: base, quote = market.split("-") market_infos[market] = MarketTradingPairTuple(exchange, market, base, quote) self.strategy = LiquidityMiningStrategy( exchange=exchange, market_infos=market_infos, initial_spread=initial_spread, order_refresh_time=order_refresh_time, reserved_balances=reserved_balances, order_refresh_tolerance_pct=order_refresh_tolerance_pct )
[ "hummingbot.strategy.liquidity_mining.liquidity_mining_config_map.liquidity_mining_config_map.get", "hummingbot.strategy.liquidity_mining.liquidity_mining.LiquidityMiningStrategy", "hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple" ]
[((1141, 1387), 'hummingbot.strategy.liquidity_mining.liquidity_mining.LiquidityMiningStrategy', 'LiquidityMiningStrategy', ([], {'exchange': 'exchange', 'market_infos': 'market_infos', 'initial_spread': 'initial_spread', 'order_refresh_time': 'order_refresh_time', 'reserved_balances': 'reserved_balances', 'order_refresh_tolerance_pct': 'order_refresh_tolerance_pct'}), '(exchange=exchange, market_infos=market_infos,\n initial_spread=initial_spread, order_refresh_time=order_refresh_time,\n reserved_balances=reserved_balances, order_refresh_tolerance_pct=\n order_refresh_tolerance_pct)\n', (1164, 1387), False, 'from hummingbot.strategy.liquidity_mining.liquidity_mining import LiquidityMiningStrategy\n'), ((402, 422), 'hummingbot.strategy.liquidity_mining.liquidity_mining_config_map.liquidity_mining_config_map.get', 'c_map.get', (['"""markets"""'], {}), "('markets')\n", (411, 422), True, 'from hummingbot.strategy.liquidity_mining.liquidity_mining_config_map import liquidity_mining_config_map as c_map\n'), ((486, 500), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (493, 500), False, 'from decimal import Decimal\n'), ((526, 557), 'hummingbot.strategy.liquidity_mining.liquidity_mining_config_map.liquidity_mining_config_map.get', 'c_map.get', (['"""order_refresh_time"""'], {}), "('order_refresh_time')\n", (535, 557), True, 'from hummingbot.strategy.liquidity_mining.liquidity_mining_config_map import liquidity_mining_config_map as c_map\n'), ((647, 661), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (654, 661), False, 'from decimal import Decimal\n'), ((1067, 1120), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['exchange', 'market', 'base', 'quote'], {}), '(exchange, market, base, quote)\n', (1089, 1120), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((450, 477), 'hummingbot.strategy.liquidity_mining.liquidity_mining_config_map.liquidity_mining_config_map.get', 'c_map.get', (['"""initial_spread"""'], {}), "('initial_spread')\n", (459, 477), True, 'from hummingbot.strategy.liquidity_mining.liquidity_mining_config_map import liquidity_mining_config_map as c_map\n'), ((598, 638), 'hummingbot.strategy.liquidity_mining.liquidity_mining_config_map.liquidity_mining_config_map.get', 'c_map.get', (['"""order_refresh_tolerance_pct"""'], {}), "('order_refresh_tolerance_pct')\n", (607, 638), True, 'from hummingbot.strategy.liquidity_mining.liquidity_mining_config_map import liquidity_mining_config_map as c_map\n'), ((686, 716), 'hummingbot.strategy.liquidity_mining.liquidity_mining_config_map.liquidity_mining_config_map.get', 'c_map.get', (['"""reserved_balances"""'], {}), "('reserved_balances')\n", (695, 716), True, 'from hummingbot.strategy.liquidity_mining.liquidity_mining_config_map import liquidity_mining_config_map as c_map\n'), ((347, 368), 'hummingbot.strategy.liquidity_mining.liquidity_mining_config_map.liquidity_mining_config_map.get', 'c_map.get', (['"""exchange"""'], {}), "('exchange')\n", (356, 368), True, 'from hummingbot.strategy.liquidity_mining.liquidity_mining_config_map import liquidity_mining_config_map as c_map\n')]
#!/usr/bin/env python import sys from hummingbot.core.data_type.order_book_row import OrderBookRow from hummingbot.connector.exchange.binance.binance_exchange import BinanceExchange import asyncio import contextlib import unittest import os import time from os.path import join, realpath from hummingbot.core.clock import ( ClockMode, Clock ) from hummingbot.core.data_type.limit_order import LimitOrder from hummingbot.core.event.events import ( BuyOrderCompletedEvent, BuyOrderCreatedEvent, MarketEvent, OrderCancelledEvent, OrderFilledEvent, OrderType, SellOrderCompletedEvent, SellOrderCreatedEvent, TradeType, OrderBookTradeEvent, ) from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from hummingbot.core.event.event_logger import EventLogger from hummingbot.connector.exchange.binance.binance_order_book_tracker import BinanceOrderBookTracker from hummingbot.connector.exchange.paper_trade.paper_trade_exchange import PaperTradeExchange, QueuedOrder from hummingbot.connector.exchange.paper_trade.trading_pair import TradingPair from hummingbot.connector.exchange.paper_trade.market_config import MarketConfig import pandas as pd from typing import List, Iterator, NamedTuple, Dict import logging logging.basicConfig(level=logging.INFO) sys.path.insert(0, realpath(join(__file__, "../../../"))) class TestUtils: @staticmethod def filter_events_by_type(event_logs, event_type): return [e for e in event_logs if type(e) == event_type] @classmethod def get_match_events(cls, event_logs: List[NamedTuple], event_type: NamedTuple, match_dict: Dict[str, any]): match_events = [] for e in cls.filter_events_by_type(event_logs, event_type): match = True for k, v in match_dict.items(): try: event_value = getattr(e, k) if type(v) in [float]: if abs(v - float(event_value)) <= 1 * 10 ** (-8): continue elif event_value != v: match = False break except Exception as err: print(f"Key {k} does not exist in event {e}. Error: {err}") if match: match_events.append(e) return match_events @classmethod def get_match_limit_orders(cls, limit_orders: List[LimitOrder], match_dict: Dict[str, any]): match_orders = [] for o in limit_orders: match = True for k, v in match_dict.items(): try: order_value = getattr(o, k) if type(v) in [float]: if abs(v - float(order_value)) <= 1 * 10 ** (-8): continue elif order_value != v: match = False break except Exception as err: print(f"Key {k} does not exist in LimitOrder {o}. Error: {err}") if match: match_orders.append(o) return match_orders class OrderBookUtils: @classmethod def ob_rows_data_frame(cls, ob_rows): data = [] try: for ob_row in ob_rows: data.append([ ob_row.price, ob_row.amount ]) df = pd.DataFrame(data=data, columns=[ "price", "amount"]) df.index = df.price return df except Exception as e: print(f"Error formatting market stats. {e}") @classmethod def get_compare_df(cls, row_it_1: Iterator[OrderBookRow], row_it_2: Iterator[OrderBookRow], n_rows: int = 20000, diffs_only: bool = False) -> pd.DataFrame: rows_1 = list(row_it_1) rows_2 = list(row_it_2) book_1: pd.DataFrame = cls.ob_rows_data_frame(rows_1) book_2: pd.DataFrame = cls.ob_rows_data_frame(rows_2) book_1.index = book_1.price book_2.index = book_2.price compare_df: pd.DataFrame = pd.concat([book_1.iloc[0:n_rows], book_2.iloc[0:n_rows]], axis="columns", keys=["pre", "post"]) compare_df = compare_df.fillna(0.0) compare_df['diff'] = compare_df['pre'].amount - compare_df['post'].amount if not diffs_only: return compare_df else: return compare_df[(compare_df["pre"]["amount"] - compare_df["post"]["amount"]).abs() > 1e-8] class PaperTradeExchangeTest(unittest.TestCase): events: List[MarketEvent] = [ MarketEvent.BuyOrderCompleted, MarketEvent.SellOrderCompleted, MarketEvent.OrderFilled, MarketEvent.TransactionFailure, MarketEvent.BuyOrderCreated, MarketEvent.SellOrderCreated, MarketEvent.OrderCancelled ] market: PaperTradeExchange market_logger: EventLogger stack: contextlib.ExitStack @classmethod def setUpClass(cls): global MAINNET_RPC_URL cls.clock: Clock = Clock(ClockMode.REALTIME) cls.market: PaperTradeExchange = PaperTradeExchange( order_book_tracker=BinanceOrderBookTracker(trading_pairs=["ETH-USDT", "BTC-USDT"]), config=MarketConfig.default_config(), target_market=BinanceExchange ) print("Initializing PaperTrade execute orders market... this will take about a minute.") cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() cls.clock.add_iterator(cls.market) cls.stack: contextlib.ExitStack = contextlib.ExitStack() cls._clock = cls.stack.enter_context(cls.clock) cls.ev_loop.run_until_complete(cls.wait_til_ready()) print("Ready.") @classmethod def tearDownClass(cls) -> None: cls.stack.close() @classmethod async def wait_til_ready(cls): while True: now = time.time() next_iteration = now // 1.0 + 1 if cls.market.ready: break else: await cls._clock.run_til(next_iteration) await asyncio.sleep(1.0) def setUp(self): self.db_path: str = realpath(join(__file__, "../binance_test.sqlite")) try: os.unlink(self.db_path) except FileNotFoundError: pass self.market_logger = EventLogger() for event_tag in self.events: self.market.add_listener(event_tag, self.market_logger) for trading_pair, orderbook in self.market.order_books.items(): orderbook.clear_traded_order_book() def tearDown(self): for event_tag in self.events: self.market.remove_listener(event_tag, self.market_logger) self.market_logger = None async def run_parallel_async(self, *tasks): future: asyncio.Future = safe_ensure_future(safe_gather(*tasks)) while not future.done(): now = time.time() next_iteration = now // 1.0 + 1 await self._clock.run_til(next_iteration) await asyncio.sleep(1.0) return future.result() def run_parallel(self, *tasks): return self.ev_loop.run_until_complete(self.run_parallel_async(*tasks)) def test_place_market_orders(self): self.market.sell("ETH-USDT", 30, OrderType.MARKET) list_queued_orders: List[QueuedOrder] = self.market.queued_orders first_queued_order: QueuedOrder = list_queued_orders[0] self.assertFalse(first_queued_order.is_buy, msg="Market order is not sell") self.assertEqual(first_queued_order.trading_pair, "ETH-USDT", msg="Trading pair is incorrect") self.assertEqual(first_queued_order.amount, 30, msg="Quantity is incorrect") self.assertEqual(len(list_queued_orders), 1, msg="First market order did not get added") # Figure out why this test is failing self.market.buy("BTC-USDT", 30, OrderType.MARKET) list_queued_orders: List[QueuedOrder] = self.market.queued_orders second_queued_order: QueuedOrder = list_queued_orders[1] self.assertTrue(second_queued_order.is_buy, msg="Market order is not buy") self.assertEqual(second_queued_order.trading_pair, "BTC-USDT", msg="Trading pair is incorrect") self.assertEqual(second_queued_order.amount, 30, msg="Quantity is incorrect") self.assertEqual(second_queued_order.amount, 30, msg="Quantity is incorrect") self.assertEqual(len(list_queued_orders), 2, msg="Second market order did not get added") def test_market_order_simulation(self): self.market.set_balance("ETH", 20) self.market.set_balance("USDT", 100) self.market.sell("ETH-USDT", 10, OrderType.MARKET) self.run_parallel(self.market_logger.wait_for(SellOrderCompletedEvent)) # Get diff between composite bid entries and original bid entries compare_df = OrderBookUtils.get_compare_df( self.market.order_books['ETH-USDT'].original_bid_entries(), self.market.order_books['ETH-USDT'].bid_entries(), diffs_only=True).sort_index().round(10) filled_bids = OrderBookUtils.ob_rows_data_frame( list(self.market.order_books['ETH-USDT'].traded_order_book.bid_entries())).sort_index().round(10) # assert filled orders matches diff diff_bid = compare_df["diff"] - filled_bids["amount"] self.assertFalse(diff_bid.to_numpy().any()) self.assertEqual(10, self.market.get_balance("ETH"), msg="Balance was not updated.") self.market.buy("ETH-USDT", 5, OrderType.MARKET) self.run_parallel(self.market_logger.wait_for(BuyOrderCompletedEvent)) # Get diff between composite bid entries and original bid entries compare_df = OrderBookUtils.get_compare_df( self.market.order_books['ETH-USDT'].original_ask_entries(), self.market.order_books['ETH-USDT'].ask_entries(), diffs_only=True).sort_index().round(10) filled_asks = OrderBookUtils.ob_rows_data_frame( list(self.market.order_books['ETH-USDT'].traded_order_book.ask_entries())).sort_index().round(10) # assert filled orders matches diff diff_ask = compare_df["diff"] - filled_asks["amount"] self.assertFalse(diff_ask.to_numpy().any()) self.assertEqual(15, self.market.get_balance("ETH"), msg="Balance was not updated.") def test_limit_order_crossed(self): starting_base_balance = 20 starting_quote_balance = 1000 self.market.set_balance("ETH", starting_base_balance) self.market.set_balance("USDT", starting_quote_balance) self.market.sell("ETH-USDT", 10, OrderType.LIMIT, 100) self.run_parallel(self.market_logger.wait_for(SellOrderCompletedEvent)) self.assertEqual(starting_base_balance - 10, self.market.get_balance("ETH"), msg="ETH Balance was not updated.") self.assertEqual(starting_quote_balance + 1000, self.market.get_balance("USDT"), msg="USDT Balance was not updated.") self.market.buy("ETH-USDT", 1, OrderType.LIMIT, 500) self.run_parallel(self.market_logger.wait_for(BuyOrderCompletedEvent)) self.assertEqual(11, self.market.get_balance("ETH"), msg="ETH Balance was not updated.") self.assertEqual(1500, self.market.get_balance("USDT"), msg="USDT Balance was not updated.") def test_bid_limit_order_trade_match(self): """ Test bid limit order fill and balance simulation, and market events emission """ trading_pair = TradingPair("ETH-USDT", "ETH", "USDT") base_quantity = 2.0 starting_base_balance = 200 starting_quote_balance = 2000 self.market.set_balance(trading_pair.base_asset, starting_base_balance) self.market.set_balance(trading_pair.quote_asset, starting_quote_balance) best_bid_price = self.market.order_books[trading_pair.trading_pair].get_price(True) client_order_id = self.market.buy(trading_pair.trading_pair, base_quantity, OrderType.LIMIT, best_bid_price) matched_limit_orders = TestUtils.get_match_limit_orders(self.market.limit_orders, { "client_order_id": client_order_id, "trading_pair": trading_pair.trading_pair, "is_buy": True, "base_currency": trading_pair.base_asset, "quote_currency": trading_pair.quote_asset, "price": best_bid_price, "quantity": base_quantity }) # Market should track limit orders self.assertEqual(1, len(matched_limit_orders)) # Market should on hold balance for the created order self.assertAlmostEqual(float(self.market.on_hold_balances[trading_pair.quote_asset]), base_quantity * best_bid_price) # Market should reflect on hold balance in available balance self.assertAlmostEqual(float(self.market.get_available_balance(trading_pair.quote_asset)), starting_quote_balance - base_quantity * best_bid_price) matched_order_create_events = TestUtils.get_match_events(self.market_logger.event_log, BuyOrderCreatedEvent, { "type": OrderType.LIMIT, "amount": base_quantity, "price": best_bid_price, "order_id": client_order_id }) # Market should emit BuyOrderCreatedEvent self.assertEqual(1, len(matched_order_create_events)) async def delay_trigger_event1(): await asyncio.sleep(1) trade_event1 = OrderBookTradeEvent( trading_pair="ETH-USDT", timestamp=time.time(), type=TradeType.SELL, price=best_bid_price + 1, amount=1.0) self.market.order_books['ETH-USDT'].apply_trade(trade_event1) safe_ensure_future(delay_trigger_event1()) self.run_parallel(self.market_logger.wait_for(BuyOrderCompletedEvent)) placed_bid_orders: List[LimitOrder] = [o for o in self.market.limit_orders if o.is_buy] # Market should delete limit order when it is filled self.assertEqual(0, len(placed_bid_orders)) matched_order_complete_events = TestUtils.get_match_events( self.market_logger.event_log, BuyOrderCompletedEvent, { "order_type": OrderType.LIMIT, "quote_asset_amount": base_quantity * best_bid_price, "order_id": client_order_id }) # Market should emit BuyOrderCompletedEvent self.assertEqual(1, len(matched_order_complete_events)) matched_order_fill_events = TestUtils.get_match_events( self.market_logger.event_log, OrderFilledEvent, { "order_type": OrderType.LIMIT, "trade_type": TradeType.BUY, "trading_pair": trading_pair.trading_pair, "order_id": client_order_id }) # Market should emit OrderFilledEvent self.assertEqual(1, len(matched_order_fill_events)) # Market should have no more on hold balance self.assertAlmostEqual(float(self.market.on_hold_balances[trading_pair.quote_asset]), 0) # Market should update balance for the filled order self.assertAlmostEqual(float(self.market.get_available_balance(trading_pair.quote_asset)), starting_quote_balance - base_quantity * best_bid_price) def test_ask_limit_order_trade_match(self): """ Test ask limit order fill and balance simulation, and market events emission """ trading_pair = TradingPair("ETH-USDT", "ETH", "USDT") base_quantity = 2.0 starting_base_balance = 200 starting_quote_balance = 2000 self.market.set_balance(trading_pair.base_asset, starting_base_balance) self.market.set_balance(trading_pair.quote_asset, starting_quote_balance) best_ask_price = self.market.order_books[trading_pair.trading_pair].get_price(False) client_order_id = self.market.sell(trading_pair.trading_pair, base_quantity, OrderType.LIMIT, best_ask_price) matched_limit_orders = TestUtils.get_match_limit_orders(self.market.limit_orders, { "client_order_id": client_order_id, "trading_pair": trading_pair.trading_pair, "is_buy": False, "base_currency": trading_pair.base_asset, "quote_currency": trading_pair.quote_asset, "price": best_ask_price, "quantity": base_quantity }) # Market should track limit orders self.assertEqual(1, len(matched_limit_orders)) # Market should on hold balance for the created order self.assertAlmostEqual(float(self.market.on_hold_balances[trading_pair.base_asset]), base_quantity) # Market should reflect on hold balance in available balance self.assertAlmostEqual(self.market.get_available_balance(trading_pair.base_asset), starting_base_balance - base_quantity) matched_order_create_events = TestUtils.get_match_events(self.market_logger.event_log, SellOrderCreatedEvent, { "type": OrderType.LIMIT, "amount": base_quantity, "price": best_ask_price, "order_id": client_order_id }) # Market should emit BuyOrderCreatedEvent self.assertEqual(1, len(matched_order_create_events)) async def delay_trigger_event2(): await asyncio.sleep(1) trade_event = OrderBookTradeEvent( trading_pair=trading_pair.trading_pair, timestamp=time.time(), type=TradeType.BUY, price=best_ask_price - 1, amount=base_quantity) self.market.order_books[trading_pair.trading_pair].apply_trade(trade_event) safe_ensure_future(delay_trigger_event2()) self.run_parallel(self.market_logger.wait_for(SellOrderCompletedEvent)) placed_ask_orders: List[LimitOrder] = [o for o in self.market.limit_orders if not o.is_buy] # Market should delete limit order when it is filled self.assertEqual(0, len(placed_ask_orders)) matched_order_complete_events = TestUtils.get_match_events( self.market_logger.event_log, SellOrderCompletedEvent, { "order_type": OrderType.LIMIT, "quote_asset_amount": base_quantity * base_quantity, "order_id": client_order_id }) # Market should emit BuyOrderCompletedEvent self.assertEqual(1, len(matched_order_complete_events)) matched_order_fill_events = TestUtils.get_match_events( self.market_logger.event_log, OrderFilledEvent, { "order_type": OrderType.LIMIT, "trade_type": TradeType.SELL, "trading_pair": trading_pair.trading_pair, "order_id": client_order_id }) # Market should emit OrderFilledEvent self.assertEqual(1, len(matched_order_fill_events)) # Market should have no more on hold balance self.assertAlmostEqual(float(self.market.on_hold_balances[trading_pair.base_asset]), 0) # Market should update balance for the filled order self.assertAlmostEqual(self.market.get_available_balance(trading_pair.base_asset), starting_base_balance - base_quantity) def test_order_cancellation(self): trading_pair = TradingPair("ETH-USDT", "ETH", "USDT") base_quantity = 2.0 starting_base_balance = 200 starting_quote_balance = 2000 self.market.set_balance(trading_pair.base_asset, starting_base_balance) self.market.set_balance(trading_pair.quote_asset, starting_quote_balance) best_ask_price = self.market.order_books[trading_pair.trading_pair].get_price(False) ask_client_order_id = self.market.sell(trading_pair.trading_pair, base_quantity, OrderType.LIMIT, best_ask_price) best_bid_price = self.market.order_books[trading_pair.trading_pair].get_price(True) self.market.buy(trading_pair.trading_pair, base_quantity, OrderType.LIMIT, best_bid_price) # Market should track limit orders self.assertEqual(2, len(self.market.limit_orders)) self.market.cancel(trading_pair.trading_pair, ask_client_order_id) matched_limit_orders = TestUtils.get_match_limit_orders(self.market.limit_orders, { "client_order_id": ask_client_order_id, "trading_pair": trading_pair.trading_pair, "is_buy": False, "base_currency": trading_pair.base_asset, "quote_currency": trading_pair.quote_asset, "price": best_ask_price, "quantity": base_quantity }) # Market should remove canceled orders self.assertEqual(0, len(matched_limit_orders)) matched_order_cancel_events = TestUtils.get_match_events( self.market_logger.event_log, OrderCancelledEvent, { "order_id": ask_client_order_id }) # Market should emit cancel event self.assertEqual(1, len(matched_order_cancel_events)) def test_order_cancel_all(self): trading_pair = TradingPair("ETH-USDT", "ETH", "USDT") base_quantity = 2.0 starting_base_balance = 200 starting_quote_balance = 2000 self.market.set_balance(trading_pair.base_asset, starting_base_balance) self.market.set_balance(trading_pair.quote_asset, starting_quote_balance) best_ask_price = self.market.order_books[trading_pair.trading_pair].get_price(False) self.market.sell(trading_pair.trading_pair, base_quantity, OrderType.LIMIT, best_ask_price) best_bid_price = self.market.order_books[trading_pair.trading_pair].get_price(True) self.market.buy(trading_pair.trading_pair, base_quantity, OrderType.LIMIT, best_bid_price) # Market should track limit orders self.assertEqual(2, len(self.market.limit_orders)) asyncio.get_event_loop().run_until_complete(self.market.cancel_all(0)) # Market should remove all canceled orders self.assertEqual(0, len(self.market.limit_orders)) matched_order_cancel_events = TestUtils.get_match_events( self.market_logger.event_log, OrderCancelledEvent, {}) # Market should emit cancel event self.assertEqual(2, len(matched_order_cancel_events))
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.connector.exchange.paper_trade.trading_pair.TradingPair", "hummingbot.core.event.event_logger.EventLogger", "hummingbot.connector.exchange.paper_trade.market_config.MarketConfig.default_config", "hummingbot.core.clock.Clock", "hummingbot.connect...
[((1291, 1330), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (1310, 1330), False, 'import logging\n'), ((1359, 1386), 'os.path.join', 'join', (['__file__', '"""../../../"""'], {}), "(__file__, '../../../')\n", (1363, 1386), False, 'from os.path import join, realpath\n'), ((4144, 4243), 'pandas.concat', 'pd.concat', (['[book_1.iloc[0:n_rows], book_2.iloc[0:n_rows]]'], {'axis': '"""columns"""', 'keys': "['pre', 'post']"}), "([book_1.iloc[0:n_rows], book_2.iloc[0:n_rows]], axis='columns',\n keys=['pre', 'post'])\n", (4153, 4243), True, 'import pandas as pd\n'), ((5137, 5162), 'hummingbot.core.clock.Clock', 'Clock', (['ClockMode.REALTIME'], {}), '(ClockMode.REALTIME)\n', (5142, 5162), False, 'from hummingbot.core.clock import ClockMode, Clock\n'), ((5564, 5588), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (5586, 5588), False, 'import asyncio\n'), ((5674, 5696), 'contextlib.ExitStack', 'contextlib.ExitStack', ([], {}), '()\n', (5694, 5696), False, 'import contextlib\n'), ((6463, 6476), 'hummingbot.core.event.event_logger.EventLogger', 'EventLogger', ([], {}), '()\n', (6474, 6476), False, 'from hummingbot.core.event.event_logger import EventLogger\n'), ((11750, 11788), 'hummingbot.connector.exchange.paper_trade.trading_pair.TradingPair', 'TradingPair', (['"""ETH-USDT"""', '"""ETH"""', '"""USDT"""'], {}), "('ETH-USDT', 'ETH', 'USDT')\n", (11761, 11788), False, 'from hummingbot.connector.exchange.paper_trade.trading_pair import TradingPair\n'), ((15782, 15820), 'hummingbot.connector.exchange.paper_trade.trading_pair.TradingPair', 'TradingPair', (['"""ETH-USDT"""', '"""ETH"""', '"""USDT"""'], {}), "('ETH-USDT', 'ETH', 'USDT')\n", (15793, 15820), False, 'from hummingbot.connector.exchange.paper_trade.trading_pair import TradingPair\n'), ((19643, 19681), 'hummingbot.connector.exchange.paper_trade.trading_pair.TradingPair', 'TradingPair', (['"""ETH-USDT"""', '"""ETH"""', '"""USDT"""'], {}), "('ETH-USDT', 'ETH', 'USDT')\n", (19654, 19681), False, 'from hummingbot.connector.exchange.paper_trade.trading_pair import TradingPair\n'), ((21465, 21503), 'hummingbot.connector.exchange.paper_trade.trading_pair.TradingPair', 'TradingPair', (['"""ETH-USDT"""', '"""ETH"""', '"""USDT"""'], {}), "('ETH-USDT', 'ETH', 'USDT')\n", (21476, 21503), False, 'from hummingbot.connector.exchange.paper_trade.trading_pair import TradingPair\n'), ((3436, 3488), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'data', 'columns': "['price', 'amount']"}), "(data=data, columns=['price', 'amount'])\n", (3448, 3488), True, 'import pandas as pd\n'), ((6009, 6020), 'time.time', 'time.time', ([], {}), '()\n', (6018, 6020), False, 'import time\n'), ((6291, 6331), 'os.path.join', 'join', (['__file__', '"""../binance_test.sqlite"""'], {}), "(__file__, '../binance_test.sqlite')\n", (6295, 6331), False, 'from os.path import join, realpath\n'), ((6358, 6381), 'os.unlink', 'os.unlink', (['self.db_path'], {}), '(self.db_path)\n', (6367, 6381), False, 'import os\n'), ((6973, 6992), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*tasks'], {}), '(*tasks)\n', (6984, 6992), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((7045, 7056), 'time.time', 'time.time', ([], {}), '()\n', (7054, 7056), False, 'import time\n'), ((5255, 5318), 'hummingbot.connector.exchange.binance.binance_order_book_tracker.BinanceOrderBookTracker', 'BinanceOrderBookTracker', ([], {'trading_pairs': "['ETH-USDT', 'BTC-USDT']"}), "(trading_pairs=['ETH-USDT', 'BTC-USDT'])\n", (5278, 5318), False, 'from hummingbot.connector.exchange.binance.binance_order_book_tracker import BinanceOrderBookTracker\n'), ((5339, 5368), 'hummingbot.connector.exchange.paper_trade.market_config.MarketConfig.default_config', 'MarketConfig.default_config', ([], {}), '()\n', (5366, 5368), False, 'from hummingbot.connector.exchange.paper_trade.market_config import MarketConfig\n'), ((6213, 6231), 'asyncio.sleep', 'asyncio.sleep', (['(1.0)'], {}), '(1.0)\n', (6226, 6231), False, 'import asyncio\n'), ((7173, 7191), 'asyncio.sleep', 'asyncio.sleep', (['(1.0)'], {}), '(1.0)\n', (7186, 7191), False, 'import asyncio\n'), ((13712, 13728), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (13725, 13728), False, 'import asyncio\n'), ((17673, 17689), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (17686, 17689), False, 'import asyncio\n'), ((22289, 22313), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (22311, 22313), False, 'import asyncio\n'), ((13828, 13839), 'time.time', 'time.time', ([], {}), '()\n', (13837, 13839), False, 'import time\n'), ((17803, 17814), 'time.time', 'time.time', ([], {}), '()\n', (17812, 17814), False, 'import time\n')]
import asyncio import json import re import unittest from typing import Any, Awaitable, Dict, List from unittest.mock import AsyncMock, MagicMock, patch from aioresponses.core import aioresponses from bidict import bidict import hummingbot.connector.exchange.binance.binance_constants as CONSTANTS import hummingbot.connector.exchange.binance.binance_web_utils as web_utils from hummingbot.connector.exchange.binance.binance_api_order_book_data_source import BinanceAPIOrderBookDataSource from hummingbot.connector.time_synchronizer import TimeSynchronizer from hummingbot.core.api_throttler.async_throttler import AsyncThrottler from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.data_type.order_book_message import OrderBookMessage from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant class BinanceAPIOrderBookDataSourceUnitTests(unittest.TestCase): # logging.Level required to receive logs from the data source logger level = 0 @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.ev_loop = asyncio.get_event_loop() cls.base_asset = "COINALPHA" cls.quote_asset = "HBOT" cls.trading_pair = f"{cls.base_asset}-{cls.quote_asset}" cls.ex_trading_pair = cls.base_asset + cls.quote_asset cls.domain = "com" def setUp(self) -> None: super().setUp() self.log_records = [] self.listening_task = None self.mocking_assistant = NetworkMockingAssistant() self.time_synchronizer = TimeSynchronizer() self.time_synchronizer.add_time_offset_ms_sample(1000) self.throttler = AsyncThrottler(rate_limits=CONSTANTS.RATE_LIMITS) self.data_source = BinanceAPIOrderBookDataSource(trading_pairs=[self.trading_pair], throttler=self.throttler, domain=self.domain, time_synchronizer=self.time_synchronizer) self.data_source.logger().setLevel(1) self.data_source.logger().addHandler(self) self.resume_test_event = asyncio.Event() BinanceAPIOrderBookDataSource._trading_pair_symbol_map = { "com": bidict( {f"{self.base_asset}{self.quote_asset}": self.trading_pair}) } def tearDown(self) -> None: self.listening_task and self.listening_task.cancel() BinanceAPIOrderBookDataSource._trading_pair_symbol_map = {} super().tearDown() def handle(self, record): self.log_records.append(record) def _is_logged(self, log_level: str, message: str) -> bool: return any(record.levelname == log_level and record.getMessage() == message for record in self.log_records) def _create_exception_and_unlock_test_with_event(self, exception): self.resume_test_event.set() raise exception def async_run_with_timeout(self, coroutine: Awaitable, timeout: float = 1): ret = self.ev_loop.run_until_complete(asyncio.wait_for(coroutine, timeout)) return ret def _successfully_subscribed_event(self): resp = { "result": None, "id": 1 } return resp def _trade_update_event(self): resp = { "e": "trade", "E": 123456789, "s": self.ex_trading_pair, "t": 12345, "p": "0.001", "q": "100", "b": 88, "a": 50, "T": 123456785, "m": True, "M": True } return resp def _order_diff_event(self): resp = { "e": "depthUpdate", "E": 123456789, "s": self.ex_trading_pair, "U": 157, "u": 160, "b": [["0.0024", "10"]], "a": [["0.0026", "100"]] } return resp def _snapshot_response(self): resp = { "lastUpdateId": 1027024, "bids": [ [ "4.00000000", "431.00000000" ] ], "asks": [ [ "4.00000200", "12.00000000" ] ] } return resp @aioresponses() def test_get_last_trade_prices(self, mock_api): url = web_utils.public_rest_url(path_url=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL, domain=self.domain) url = f"{url}?symbol={self.base_asset}{self.quote_asset}" regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_response = { "symbol": "BNBBTC", "priceChange": "-94.99999800", "priceChangePercent": "-95.960", "weightedAvgPrice": "0.29628482", "prevClosePrice": "0.10002000", "lastPrice": "100.0", "lastQty": "200.00000000", "bidPrice": "4.00000000", "bidQty": "100.00000000", "askPrice": "4.00000200", "askQty": "100.00000000", "openPrice": "99.00000000", "highPrice": "100.00000000", "lowPrice": "0.10000000", "volume": "8913.30000000", "quoteVolume": "15.30000000", "openTime": 1499783499040, "closeTime": 1499869899040, "firstId": 28385, "lastId": 28460, "count": 76, } mock_api.get(regex_url, body=json.dumps(mock_response)) result: Dict[str, float] = self.async_run_with_timeout( self.data_source.get_last_traded_prices(trading_pairs=[self.trading_pair], throttler=self.throttler, time_synchronizer=self.time_synchronizer) ) self.assertEqual(1, len(result)) self.assertEqual(100, result[self.trading_pair]) @aioresponses() def test_get_all_mid_prices(self, mock_api): url = web_utils.public_rest_url(CONSTANTS.SERVER_TIME_PATH_URL, domain=self.domain) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) response = {"serverTime": 1640000003000} mock_api.get(regex_url, body=json.dumps(response)) url = web_utils.public_rest_url(path_url=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL, domain=self.domain) mock_response: List[Dict[str, Any]] = [ { # Truncated Response "symbol": self.ex_trading_pair, "bidPrice": "99", "askPrice": "101", }, { # Truncated Response for unrecognized pair "symbol": "BCCBTC", "bidPrice": "99", "askPrice": "101", } ] mock_api.get(url, body=json.dumps(mock_response)) result: Dict[str, float] = self.async_run_with_timeout( self.data_source.get_all_mid_prices() ) self.assertEqual(1, len(result)) self.assertEqual(100, result[self.trading_pair]) @aioresponses() def test_fetch_trading_pairs(self, mock_api): BinanceAPIOrderBookDataSource._trading_pair_symbol_map = {} url = web_utils.public_rest_url(path_url=CONSTANTS.EXCHANGE_INFO_PATH_URL, domain=self.domain) mock_response: Dict[str, Any] = { "timezone": "UTC", "serverTime": 1639598493658, "rateLimits": [], "exchangeFilters": [], "symbols": [ { "symbol": "ETHBTC", "status": "TRADING", "baseAsset": "ETH", "baseAssetPrecision": 8, "quoteAsset": "BTC", "quotePrecision": 8, "quoteAssetPrecision": 8, "baseCommissionPrecision": 8, "quoteCommissionPrecision": 8, "orderTypes": [ "LIMIT", "LIMIT_MAKER", "MARKET", "STOP_LOSS_LIMIT", "TAKE_PROFIT_LIMIT" ], "icebergAllowed": True, "ocoAllowed": True, "quoteOrderQtyMarketAllowed": True, "isSpotTradingAllowed": True, "isMarginTradingAllowed": True, "filters": [], "permissions": [ "SPOT", "MARGIN" ] }, { "symbol": "LTCBTC", "status": "TRADING", "baseAsset": "LTC", "baseAssetPrecision": 8, "quoteAsset": "BTC", "quotePrecision": 8, "quoteAssetPrecision": 8, "baseCommissionPrecision": 8, "quoteCommissionPrecision": 8, "orderTypes": [ "LIMIT", "LIMIT_MAKER", "MARKET", "STOP_LOSS_LIMIT", "TAKE_PROFIT_LIMIT" ], "icebergAllowed": True, "ocoAllowed": True, "quoteOrderQtyMarketAllowed": True, "isSpotTradingAllowed": True, "isMarginTradingAllowed": True, "filters": [], "permissions": [ "SPOT", "MARGIN" ] }, { "symbol": "BNBBTC", "status": "TRADING", "baseAsset": "BNB", "baseAssetPrecision": 8, "quoteAsset": "BTC", "quotePrecision": 8, "quoteAssetPrecision": 8, "baseCommissionPrecision": 8, "quoteCommissionPrecision": 8, "orderTypes": [ "LIMIT", "LIMIT_MAKER", "MARKET", "STOP_LOSS_LIMIT", "TAKE_PROFIT_LIMIT" ], "icebergAllowed": True, "ocoAllowed": True, "quoteOrderQtyMarketAllowed": True, "isSpotTradingAllowed": True, "isMarginTradingAllowed": True, "filters": [], "permissions": [ "MARGIN" ] }, ] } mock_api.get(url, body=json.dumps(mock_response)) result: Dict[str] = self.async_run_with_timeout( self.data_source.fetch_trading_pairs(time_synchronizer=self.time_synchronizer) ) self.assertEqual(2, len(result)) self.assertIn("ETH-BTC", result) self.assertIn("LTC-BTC", result) self.assertNotIn("BNB-BTC", result) @aioresponses() def test_fetch_trading_pairs_exception_raised(self, mock_api): BinanceAPIOrderBookDataSource._trading_pair_symbol_map = {} url = web_utils.public_rest_url(path_url=CONSTANTS.EXCHANGE_INFO_PATH_URL, domain=self.domain) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_api.get(regex_url, exception=Exception) result: Dict[str] = self.async_run_with_timeout( self.data_source.fetch_trading_pairs(time_synchronizer=self.time_synchronizer) ) self.assertEqual(0, len(result)) @aioresponses() def test_get_snapshot_successful(self, mock_api): url = web_utils.public_rest_url(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self.domain) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_api.get(regex_url, body=json.dumps(self._snapshot_response())) result: Dict[str, Any] = self.async_run_with_timeout( self.data_source.get_snapshot(self.trading_pair) ) self.assertEqual(self._snapshot_response(), result) @aioresponses() def test_get_snapshot_catch_exception(self, mock_api): url = web_utils.public_rest_url(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self.domain) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_api.get(regex_url, status=400) with self.assertRaises(IOError): self.async_run_with_timeout( self.data_source.get_snapshot(self.trading_pair) ) @aioresponses() def test_get_new_order_book(self, mock_api): url = web_utils.public_rest_url(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self.domain) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_response: Dict[str, Any] = { "lastUpdateId": 1, "bids": [ [ "4.00000000", "431.00000000" ] ], "asks": [ [ "4.00000200", "12.00000000" ] ] } mock_api.get(regex_url, body=json.dumps(mock_response)) result: OrderBook = self.async_run_with_timeout( self.data_source.get_new_order_book(self.trading_pair) ) self.assertEqual(1, result.snapshot_uid) @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) def test_listen_for_subscriptions_subscribes_to_trades_and_order_diffs(self, ws_connect_mock): ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() result_subscribe_trades = { "result": None, "id": 1 } result_subscribe_diffs = { "result": None, "id": 2 } self.mocking_assistant.add_websocket_aiohttp_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(result_subscribe_trades)) self.mocking_assistant.add_websocket_aiohttp_message( websocket_mock=ws_connect_mock.return_value, message=json.dumps(result_subscribe_diffs)) self.listening_task = self.ev_loop.create_task(self.data_source.listen_for_subscriptions()) self.mocking_assistant.run_until_all_aiohttp_messages_delivered(ws_connect_mock.return_value) sent_subscription_messages = self.mocking_assistant.json_messages_sent_through_websocket( websocket_mock=ws_connect_mock.return_value) self.assertEqual(2, len(sent_subscription_messages)) expected_trade_subscription = { "method": "SUBSCRIBE", "params": [f"{self.ex_trading_pair.lower()}@trade"], "id": 1} self.assertEqual(expected_trade_subscription, sent_subscription_messages[0]) expected_diff_subscription = { "method": "SUBSCRIBE", "params": [f"{self.ex_trading_pair.lower()}@depth@100ms"], "id": 2} self.assertEqual(expected_diff_subscription, sent_subscription_messages[1]) self.assertTrue(self._is_logged( "INFO", "Subscribed to public order book and trade channels..." )) @patch("hummingbot.core.data_type.order_book_tracker_data_source.OrderBookTrackerDataSource._sleep") @patch("aiohttp.ClientSession.ws_connect") def test_listen_for_subscriptions_raises_cancel_exception(self, mock_ws, _: AsyncMock): mock_ws.side_effect = asyncio.CancelledError with self.assertRaises(asyncio.CancelledError): self.listening_task = self.ev_loop.create_task(self.data_source.listen_for_subscriptions()) self.async_run_with_timeout(self.listening_task) @patch("hummingbot.core.data_type.order_book_tracker_data_source.OrderBookTrackerDataSource._sleep") @patch("aiohttp.ClientSession.ws_connect", new_callable=AsyncMock) def test_listen_for_subscriptions_logs_exception_details(self, mock_ws, sleep_mock): mock_ws.side_effect = Exception("TEST ERROR.") sleep_mock.side_effect = lambda _: self._create_exception_and_unlock_test_with_event(asyncio.CancelledError()) self.listening_task = self.ev_loop.create_task(self.data_source.listen_for_subscriptions()) self.async_run_with_timeout(self.resume_test_event.wait()) self.assertTrue( self._is_logged( "ERROR", "Unexpected error occurred when listening to order book streams. Retrying in 5 seconds...")) def test_subscribe_channels_raises_cancel_exception(self): mock_ws = MagicMock() mock_ws.send.side_effect = asyncio.CancelledError with self.assertRaises(asyncio.CancelledError): self.listening_task = self.ev_loop.create_task(self.data_source._subscribe_channels(mock_ws)) self.async_run_with_timeout(self.listening_task) def test_subscribe_channels_raises_exception_and_logs_error(self): mock_ws = MagicMock() mock_ws.send.side_effect = Exception("Test Error") with self.assertRaises(Exception): self.listening_task = self.ev_loop.create_task(self.data_source._subscribe_channels(mock_ws)) self.async_run_with_timeout(self.listening_task) self.assertTrue( self._is_logged("ERROR", "Unexpected error occurred subscribing to order book trading and delta streams...") ) def test_listen_for_trades_cancelled_when_listening(self): mock_queue = MagicMock() mock_queue.get.side_effect = asyncio.CancelledError() self.data_source._message_queue[CONSTANTS.TRADE_EVENT_TYPE] = mock_queue msg_queue: asyncio.Queue = asyncio.Queue() with self.assertRaises(asyncio.CancelledError): self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_trades(self.ev_loop, msg_queue) ) self.async_run_with_timeout(self.listening_task) def test_listen_for_trades_logs_exception(self): incomplete_resp = { "m": 1, "i": 2, } mock_queue = AsyncMock() mock_queue.get.side_effect = [incomplete_resp, asyncio.CancelledError()] self.data_source._message_queue[CONSTANTS.TRADE_EVENT_TYPE] = mock_queue msg_queue: asyncio.Queue = asyncio.Queue() self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_trades(self.ev_loop, msg_queue) ) try: self.async_run_with_timeout(self.listening_task) except asyncio.CancelledError: pass self.assertTrue( self._is_logged("ERROR", "Unexpected error when processing public trade updates from exchange")) def test_listen_for_trades_successful(self): mock_queue = AsyncMock() mock_queue.get.side_effect = [self._trade_update_event(), asyncio.CancelledError()] self.data_source._message_queue[CONSTANTS.TRADE_EVENT_TYPE] = mock_queue msg_queue: asyncio.Queue = asyncio.Queue() try: self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_trades(self.ev_loop, msg_queue) ) except asyncio.CancelledError: pass msg: OrderBookMessage = self.async_run_with_timeout(msg_queue.get()) self.assertTrue(12345, msg.trade_id) def test_listen_for_order_book_diffs_cancelled(self): mock_queue = AsyncMock() mock_queue.get.side_effect = asyncio.CancelledError() self.data_source._message_queue[CONSTANTS.DIFF_EVENT_TYPE] = mock_queue msg_queue: asyncio.Queue = asyncio.Queue() with self.assertRaises(asyncio.CancelledError): self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_diffs(self.ev_loop, msg_queue) ) self.async_run_with_timeout(self.listening_task) def test_listen_for_order_book_diffs_logs_exception(self): incomplete_resp = { "m": 1, "i": 2, } mock_queue = AsyncMock() mock_queue.get.side_effect = [incomplete_resp, asyncio.CancelledError()] self.data_source._message_queue[CONSTANTS.DIFF_EVENT_TYPE] = mock_queue msg_queue: asyncio.Queue = asyncio.Queue() self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_diffs(self.ev_loop, msg_queue) ) try: self.async_run_with_timeout(self.listening_task) except asyncio.CancelledError: pass self.assertTrue( self._is_logged("ERROR", "Unexpected error when processing public order book updates from exchange")) def test_listen_for_order_book_diffs_successful(self): mock_queue = AsyncMock() mock_queue.get.side_effect = [self._order_diff_event(), asyncio.CancelledError()] self.data_source._message_queue[CONSTANTS.DIFF_EVENT_TYPE] = mock_queue msg_queue: asyncio.Queue = asyncio.Queue() try: self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_diffs(self.ev_loop, msg_queue) ) except asyncio.CancelledError: pass msg: OrderBookMessage = self.async_run_with_timeout(msg_queue.get()) self.assertTrue(12345, msg.update_id) @aioresponses() def test_listen_for_order_book_snapshots_cancelled_when_fetching_snapshot(self, mock_api): url = web_utils.public_rest_url(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self.domain) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_api.get(regex_url, exception=asyncio.CancelledError) with self.assertRaises(asyncio.CancelledError): self.async_run_with_timeout( self.data_source.listen_for_order_book_snapshots(self.ev_loop, asyncio.Queue()) ) @aioresponses() @patch("hummingbot.connector.exchange.binance.binance_api_order_book_data_source" ".BinanceAPIOrderBookDataSource._sleep") def test_listen_for_order_book_snapshots_log_exception(self, mock_api, sleep_mock): msg_queue: asyncio.Queue = asyncio.Queue() sleep_mock.side_effect = lambda _: self._create_exception_and_unlock_test_with_event(asyncio.CancelledError()) url = web_utils.public_rest_url(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self.domain) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_api.get(regex_url, exception=Exception) self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_snapshots(self.ev_loop, msg_queue) ) self.async_run_with_timeout(self.resume_test_event.wait()) self.assertTrue( self._is_logged("ERROR", f"Unexpected error fetching order book snapshot for {self.trading_pair}.")) @aioresponses() def test_listen_for_order_book_snapshots_successful(self, mock_api, ): msg_queue: asyncio.Queue = asyncio.Queue() url = web_utils.public_rest_url(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self.domain) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_api.get(regex_url, body=json.dumps(self._snapshot_response())) self.listening_task = self.ev_loop.create_task( self.data_source.listen_for_order_book_snapshots(self.ev_loop, msg_queue) ) msg: OrderBookMessage = self.async_run_with_timeout(msg_queue.get()) self.assertEqual(1027024, msg.update_id)
[ "hummingbot.connector.time_synchronizer.TimeSynchronizer", "hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url", "hummingbot.connector.exchange.binance.binance_api_order_book_data_source.BinanceAPIOrderBookDataSource", "hummingbot.core.api_throttler.async_throttler.AsyncThrottler" ]
[((4397, 4411), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (4409, 4411), False, 'from aioresponses.core import aioresponses\n'), ((6060, 6074), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (6072, 6074), False, 'from aioresponses.core import aioresponses\n'), ((7262, 7276), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (7274, 7276), False, 'from aioresponses.core import aioresponses\n'), ((11342, 11356), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (11354, 11356), False, 'from aioresponses.core import aioresponses\n'), ((11939, 11953), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (11951, 11953), False, 'from aioresponses.core import aioresponses\n'), ((12466, 12480), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (12478, 12480), False, 'from aioresponses.core import aioresponses\n'), ((12932, 12946), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (12944, 12946), False, 'from aioresponses.core import aioresponses\n'), ((13797, 13862), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.ws_connect"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.ws_connect', new_callable=AsyncMock)\n", (13802, 13862), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((15653, 15762), 'unittest.mock.patch', 'patch', (['"""hummingbot.core.data_type.order_book_tracker_data_source.OrderBookTrackerDataSource._sleep"""'], {}), "(\n 'hummingbot.core.data_type.order_book_tracker_data_source.OrderBookTrackerDataSource._sleep'\n )\n", (15658, 15762), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((15758, 15799), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.ws_connect"""'], {}), "('aiohttp.ClientSession.ws_connect')\n", (15763, 15799), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((16173, 16282), 'unittest.mock.patch', 'patch', (['"""hummingbot.core.data_type.order_book_tracker_data_source.OrderBookTrackerDataSource._sleep"""'], {}), "(\n 'hummingbot.core.data_type.order_book_tracker_data_source.OrderBookTrackerDataSource._sleep'\n )\n", (16178, 16282), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((16278, 16343), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.ws_connect"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.ws_connect', new_callable=AsyncMock)\n", (16283, 16343), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((21916, 21930), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (21928, 21930), False, 'from aioresponses.core import aioresponses\n'), ((22487, 22501), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (22499, 22501), False, 'from aioresponses.core import aioresponses\n'), ((22507, 22635), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.binance.binance_api_order_book_data_source.BinanceAPIOrderBookDataSource._sleep"""'], {}), "(\n 'hummingbot.connector.exchange.binance.binance_api_order_book_data_source.BinanceAPIOrderBookDataSource._sleep'\n )\n", (22512, 22635), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((23498, 23512), 'aioresponses.core.aioresponses', 'aioresponses', ([], {}), '()\n', (23510, 23512), False, 'from aioresponses.core import aioresponses\n'), ((1109, 1133), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1131, 1133), False, 'import asyncio\n'), ((1511, 1536), 'test.hummingbot.connector.network_mocking_assistant.NetworkMockingAssistant', 'NetworkMockingAssistant', ([], {}), '()\n', (1534, 1536), False, 'from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant\n'), ((1570, 1588), 'hummingbot.connector.time_synchronizer.TimeSynchronizer', 'TimeSynchronizer', ([], {}), '()\n', (1586, 1588), False, 'from hummingbot.connector.time_synchronizer import TimeSynchronizer\n'), ((1678, 1727), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', ([], {'rate_limits': 'CONSTANTS.RATE_LIMITS'}), '(rate_limits=CONSTANTS.RATE_LIMITS)\n', (1692, 1727), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((1755, 1917), 'hummingbot.connector.exchange.binance.binance_api_order_book_data_source.BinanceAPIOrderBookDataSource', 'BinanceAPIOrderBookDataSource', ([], {'trading_pairs': '[self.trading_pair]', 'throttler': 'self.throttler', 'domain': 'self.domain', 'time_synchronizer': 'self.time_synchronizer'}), '(trading_pairs=[self.trading_pair], throttler=\n self.throttler, domain=self.domain, time_synchronizer=self.\n time_synchronizer)\n', (1784, 1917), False, 'from hummingbot.connector.exchange.binance.binance_api_order_book_data_source import BinanceAPIOrderBookDataSource\n'), ((2210, 2225), 'asyncio.Event', 'asyncio.Event', ([], {}), '()\n', (2223, 2225), False, 'import asyncio\n'), ((4478, 4576), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL,\n domain=self.domain)\n', (4503, 4576), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((6138, 6215), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', (['CONSTANTS.SERVER_TIME_PATH_URL'], {'domain': 'self.domain'}), '(CONSTANTS.SERVER_TIME_PATH_URL, domain=self.domain)\n', (6163, 6215), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((6444, 6542), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL,\n domain=self.domain)\n', (6469, 6542), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((7409, 7502), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.EXCHANGE_INFO_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.EXCHANGE_INFO_PATH_URL, domain\n =self.domain)\n', (7434, 7502), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((11507, 11600), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.EXCHANGE_INFO_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.EXCHANGE_INFO_PATH_URL, domain\n =self.domain)\n', (11532, 11600), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((12022, 12110), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.SNAPSHOT_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self\n .domain)\n', (12047, 12110), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((12554, 12642), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.SNAPSHOT_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self\n .domain)\n', (12579, 12642), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((13010, 13098), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.SNAPSHOT_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self\n .domain)\n', (13035, 13098), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((17047, 17058), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (17056, 17058), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((17431, 17442), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (17440, 17442), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((17955, 17966), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (17964, 17966), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((18004, 18028), 'asyncio.CancelledError', 'asyncio.CancelledError', ([], {}), '()\n', (18026, 18028), False, 'import asyncio\n'), ((18146, 18161), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (18159, 18161), False, 'import asyncio\n'), ((18584, 18595), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (18593, 18595), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((18794, 18809), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (18807, 18809), False, 'import asyncio\n'), ((19286, 19297), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (19295, 19297), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((19507, 19522), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (19520, 19522), False, 'import asyncio\n'), ((19947, 19958), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (19956, 19958), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((19996, 20020), 'asyncio.CancelledError', 'asyncio.CancelledError', ([], {}), '()\n', (20018, 20020), False, 'import asyncio\n'), ((20137, 20152), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (20150, 20152), False, 'import asyncio\n'), ((20595, 20606), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (20604, 20606), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((20804, 20819), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (20817, 20819), False, 'import asyncio\n'), ((21321, 21332), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (21330, 21332), False, 'from unittest.mock import AsyncMock, MagicMock, patch\n'), ((21539, 21554), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (21552, 21554), False, 'import asyncio\n'), ((22040, 22128), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.SNAPSHOT_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self\n .domain)\n', (22065, 22128), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((22763, 22778), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (22776, 22778), False, 'import asyncio\n'), ((22913, 23001), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.SNAPSHOT_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self\n .domain)\n', (22938, 23001), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((23623, 23638), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (23636, 23638), False, 'import asyncio\n'), ((23653, 23741), 'hummingbot.connector.exchange.binance.binance_web_utils.public_rest_url', 'web_utils.public_rest_url', ([], {'path_url': 'CONSTANTS.SNAPSHOT_PATH_URL', 'domain': 'self.domain'}), '(path_url=CONSTANTS.SNAPSHOT_PATH_URL, domain=self\n .domain)\n', (23678, 23741), True, 'import hummingbot.connector.exchange.binance.binance_web_utils as web_utils\n'), ((2313, 2380), 'bidict.bidict', 'bidict', (["{f'{self.base_asset}{self.quote_asset}': self.trading_pair}"], {}), "({f'{self.base_asset}{self.quote_asset}': self.trading_pair})\n", (2319, 2380), False, 'from bidict import bidict\n'), ((3128, 3164), 'asyncio.wait_for', 'asyncio.wait_for', (['coroutine', 'timeout'], {}), '(coroutine, timeout)\n', (3144, 3164), False, 'import asyncio\n'), ((18651, 18675), 'asyncio.CancelledError', 'asyncio.CancelledError', ([], {}), '()\n', (18673, 18675), False, 'import asyncio\n'), ((19364, 19388), 'asyncio.CancelledError', 'asyncio.CancelledError', ([], {}), '()\n', (19386, 19388), False, 'import asyncio\n'), ((20662, 20686), 'asyncio.CancelledError', 'asyncio.CancelledError', ([], {}), '()\n', (20684, 20686), False, 'import asyncio\n'), ((21397, 21421), 'asyncio.CancelledError', 'asyncio.CancelledError', ([], {}), '()\n', (21419, 21421), False, 'import asyncio\n'), ((5594, 5619), 'json.dumps', 'json.dumps', (['mock_response'], {}), '(mock_response)\n', (5604, 5619), False, 'import json\n'), ((6407, 6427), 'json.dumps', 'json.dumps', (['response'], {}), '(response)\n', (6417, 6427), False, 'import json\n'), ((7005, 7030), 'json.dumps', 'json.dumps', (['mock_response'], {}), '(mock_response)\n', (7015, 7030), False, 'import json\n'), ((10982, 11007), 'json.dumps', 'json.dumps', (['mock_response'], {}), '(mock_response)\n', (10992, 11007), False, 'import json\n'), ((13579, 13604), 'json.dumps', 'json.dumps', (['mock_response'], {}), '(mock_response)\n', (13589, 13604), False, 'import json\n'), ((14376, 14411), 'json.dumps', 'json.dumps', (['result_subscribe_trades'], {}), '(result_subscribe_trades)\n', (14386, 14411), False, 'import json\n'), ((14552, 14586), 'json.dumps', 'json.dumps', (['result_subscribe_diffs'], {}), '(result_subscribe_diffs)\n', (14562, 14586), False, 'import json\n'), ((16581, 16605), 'asyncio.CancelledError', 'asyncio.CancelledError', ([], {}), '()\n', (16603, 16605), False, 'import asyncio\n'), ((22872, 22896), 'asyncio.CancelledError', 'asyncio.CancelledError', ([], {}), '()\n', (22894, 22896), False, 'import asyncio\n'), ((22450, 22465), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (22463, 22465), False, 'import asyncio\n')]
from decimal import Decimal import pandas as pd import threading import time from typing import ( Set, Tuple, TYPE_CHECKING, List, Optional ) from datetime import datetime from hummingbot.client.config.global_config_map import global_config_map from hummingbot.client.settings import ( MAXIMUM_TRADE_FILLS_DISPLAY_OUTPUT, CONNECTOR_SETTINGS, ConnectorType, DERIVATIVES ) from hummingbot.model.trade_fill import TradeFill from hummingbot.user.user_balances import UserBalances from hummingbot.core.utils.async_utils import safe_ensure_future from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round s_float_0 = float(0) s_decimal_0 = Decimal("0") if TYPE_CHECKING: from hummingbot.client.hummingbot_application import HummingbotApplication def get_timestamp(days_ago: float = 0.) -> float: return time.time() - (60. * 60. * 24. * days_ago) class HistoryCommand: def history(self, # type: HummingbotApplication days: float = 0, verbose: bool = False, precision: Optional[int] = None ): if threading.current_thread() != threading.main_thread(): self.ev_loop.call_soon_threadsafe(self.history) return if self.strategy_file_name is None: self._notify("\n Please first import a strategy config file of which to show historical performance.") return if global_config_map.get("paper_trade_enabled").value: self._notify("\n Paper Trading ON: All orders are simulated, and no real orders are placed.") start_time = get_timestamp(days) if days > 0 else self.init_time trades: List[TradeFill] = self._get_trades_from_session(int(start_time * 1e3), config_file_path=self.strategy_file_name) if not trades: self._notify("\n No past trades to report.") return if verbose: self.list_trades(start_time) if self.strategy_name != "celo_arb": safe_ensure_future(self.history_report(start_time, trades, precision)) async def history_report(self, # type: HummingbotApplication start_time: float, trades: List[TradeFill], precision: Optional[int] = None, display_report: bool = True) -> Decimal: market_info: Set[Tuple[str, str]] = set((t.market, t.symbol) for t in trades) if display_report: self.report_header(start_time) return_pcts = [] for market, symbol in market_info: cur_trades = [t for t in trades if t.market == market and t.symbol == symbol] cur_balances = await self.get_current_balances(market) perf = await calculate_performance_metrics(market, symbol, cur_trades, cur_balances) if display_report: self.report_performance_by_market(market, symbol, perf, precision) return_pcts.append(perf.return_pct) avg_return = sum(return_pcts) / len(return_pcts) if len(return_pcts) > 0 else s_decimal_0 if display_report and len(return_pcts) > 1: self._notify(f"\nAveraged Return = {avg_return:.2%}") return avg_return async def get_current_balances(self, # type: HummingbotApplication market: str): if market in self.markets and self.markets[market].ready: return self.markets[market].get_all_balances() elif "Paper" in market: paper_balances = global_config_map["paper_trade_account_balance"].value if paper_balances is None: return {} return {token: Decimal(str(bal)) for token, bal in paper_balances.items()} else: gateway_eth_connectors = [cs.name for cs in CONNECTOR_SETTINGS.values() if cs.use_ethereum_wallet and cs.type == ConnectorType.Connector] if market in gateway_eth_connectors: return await UserBalances.instance().eth_n_erc20_balances() else: await UserBalances.instance().update_exchange_balance(market) return UserBalances.instance().all_balances(market) def report_header(self, # type: HummingbotApplication start_time: float): lines = [] current_time = get_timestamp() lines.extend( [f"\nStart Time: {datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S')}"] + [f"Curent Time: {datetime.fromtimestamp(current_time).strftime('%Y-%m-%d %H:%M:%S')}"] + [f"Duration: {pd.Timedelta(seconds=int(current_time - start_time))}"] ) self._notify("\n".join(lines)) def report_performance_by_market(self, # type: HummingbotApplication market: str, trading_pair: str, perf: PerformanceMetrics, precision: int): lines = [] base, quote = trading_pair.split("-") lines.extend( [f"\n{market} / {trading_pair}"] ) trades_columns = ["", "buy", "sell", "total"] trades_data = [ [f"{'Number of trades':<27}", perf.num_buys, perf.num_sells, perf.num_trades], [f"{f'Total trade volume ({base})':<27}", smart_round(perf.b_vol_base, precision), smart_round(perf.s_vol_base, precision), smart_round(perf.tot_vol_base, precision)], [f"{f'Total trade volume ({quote})':<27}", smart_round(perf.b_vol_quote, precision), smart_round(perf.s_vol_quote, precision), smart_round(perf.tot_vol_quote, precision)], [f"{'Avg price':<27}", smart_round(perf.avg_b_price, precision), smart_round(perf.avg_s_price, precision), smart_round(perf.avg_tot_price, precision)], ] trades_df: pd.DataFrame = pd.DataFrame(data=trades_data, columns=trades_columns) lines.extend(["", " Trades:"] + [" " + line for line in trades_df.to_string(index=False).split("\n")]) assets_columns = ["", "start", "current", "change"] assets_data = [ [f"{base:<17}", "-", "-", "-"] if market in DERIVATIVES else # No base asset for derivatives because they are margined [f"{base:<17}", smart_round(perf.start_base_bal, precision), smart_round(perf.cur_base_bal, precision), smart_round(perf.tot_vol_base, precision)], [f"{quote:<17}", smart_round(perf.start_quote_bal, precision), smart_round(perf.cur_quote_bal, precision), smart_round(perf.tot_vol_quote, precision)], [f"{trading_pair + ' price':<17}", smart_round(perf.start_price), smart_round(perf.cur_price), smart_round(perf.cur_price - perf.start_price)], [f"{'Base asset %':<17}", "-", "-", "-"] if market in DERIVATIVES else # No base asset for derivatives because they are margined [f"{'Base asset %':<17}", f"{perf.start_base_ratio_pct:.2%}", f"{perf.cur_base_ratio_pct:.2%}", f"{perf.cur_base_ratio_pct - perf.start_base_ratio_pct:.2%}"], ] assets_df: pd.DataFrame = pd.DataFrame(data=assets_data, columns=assets_columns) lines.extend(["", " Assets:"] + [" " + line for line in assets_df.to_string(index=False).split("\n")]) perf_data = [ ["Hold portfolio value ", f"{smart_round(perf.hold_value, precision)} {quote}"], ["Current portfolio value ", f"{smart_round(perf.cur_value, precision)} {quote}"], ["Trade P&L ", f"{smart_round(perf.trade_pnl, precision)} {quote}"] ] perf_data.extend( ["Fees paid ", f"{smart_round(fee_amount, precision)} {fee_token}"] for fee_token, fee_amount in perf.fees.items() ) perf_data.extend( [["Total P&L ", f"{smart_round(perf.total_pnl, precision)} {quote}"], ["Return % ", f"{perf.return_pct:.2%}"]] ) perf_df: pd.DataFrame = pd.DataFrame(data=perf_data) lines.extend(["", " Performance:"] + [" " + line for line in perf_df.to_string(index=False, header=False).split("\n")]) self._notify("\n".join(lines)) async def calculate_profitability(self, # type: HummingbotApplication ) -> Decimal: """ Determines the profitability of the trading bot. This function is used by the KillSwitch class. Must be updated if the method of performance report gets updated. """ if not self.markets_recorder: return s_decimal_0 if any(not market.ready for market in self.markets.values()): return s_decimal_0 start_time = self.init_time trades: List[TradeFill] = self._get_trades_from_session(int(start_time * 1e3), config_file_path=self.strategy_file_name) avg_return = await self.history_report(start_time, trades, display_report=False) return avg_return def list_trades(self, # type: HummingbotApplication start_time: float): if threading.current_thread() != threading.main_thread(): self.ev_loop.call_soon_threadsafe(self.list_trades, start_time) return lines = [] queried_trades: List[TradeFill] = self._get_trades_from_session(int(start_time * 1e3), MAXIMUM_TRADE_FILLS_DISPLAY_OUTPUT + 1, self.strategy_file_name) if self.strategy_name == "celo_arb": celo_trades = self.strategy.celo_orders_to_trade_fills() queried_trades = queried_trades + celo_trades df: pd.DataFrame = TradeFill.to_pandas(queried_trades) if len(df) > 0: # Check if number of trades exceed maximum number of trades to display if len(df) > MAXIMUM_TRADE_FILLS_DISPLAY_OUTPUT: df_lines = str(df[:MAXIMUM_TRADE_FILLS_DISPLAY_OUTPUT]).split("\n") self._notify( f"\n Showing last {MAXIMUM_TRADE_FILLS_DISPLAY_OUTPUT} trades in the current session.") else: df_lines = str(df).split("\n") lines.extend(["", " Recent trades:"] + [" " + line for line in df_lines]) else: lines.extend(["\n No past trades in this session."]) self._notify("\n".join(lines))
[ "hummingbot.model.trade_fill.TradeFill.to_pandas", "hummingbot.user.user_balances.UserBalances.instance", "hummingbot.client.performance.smart_round", "hummingbot.client.performance.calculate_performance_metrics", "hummingbot.client.config.global_config_map.global_config_map.get", "hummingbot.client.setti...
[((718, 730), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (725, 730), False, 'from decimal import Decimal\n'), ((893, 904), 'time.time', 'time.time', ([], {}), '()\n', (902, 904), False, 'import time\n'), ((6204, 6258), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'trades_data', 'columns': 'trades_columns'}), '(data=trades_data, columns=trades_columns)\n', (6216, 6258), True, 'import pandas as pd\n'), ((7584, 7638), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'assets_data', 'columns': 'assets_columns'}), '(data=assets_data, columns=assets_columns)\n', (7596, 7638), True, 'import pandas as pd\n'), ((8494, 8522), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'perf_data'}), '(data=perf_data)\n', (8506, 8522), True, 'import pandas as pd\n'), ((10351, 10386), 'hummingbot.model.trade_fill.TradeFill.to_pandas', 'TradeFill.to_pandas', (['queried_trades'], {}), '(queried_trades)\n', (10370, 10386), False, 'from hummingbot.model.trade_fill import TradeFill\n'), ((1163, 1189), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (1187, 1189), False, 'import threading\n'), ((1193, 1216), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (1214, 1216), False, 'import threading\n'), ((1488, 1532), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""paper_trade_enabled"""'], {}), "('paper_trade_enabled')\n", (1509, 1532), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((9678, 9704), 'threading.current_thread', 'threading.current_thread', ([], {}), '()\n', (9702, 9704), False, 'import threading\n'), ((9708, 9731), 'threading.main_thread', 'threading.main_thread', ([], {}), '()\n', (9729, 9731), False, 'import threading\n'), ((2909, 2980), 'hummingbot.client.performance.calculate_performance_metrics', 'calculate_performance_metrics', (['market', 'symbol', 'cur_trades', 'cur_balances'], {}), '(market, symbol, cur_trades, cur_balances)\n', (2938, 2980), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((5582, 5621), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.b_vol_base', 'precision'], {}), '(perf.b_vol_base, precision)\n', (5593, 5621), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((5636, 5675), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.s_vol_base', 'precision'], {}), '(perf.s_vol_base, precision)\n', (5647, 5675), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((5690, 5731), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.tot_vol_base', 'precision'], {}), '(perf.tot_vol_base, precision)\n', (5701, 5731), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((5802, 5842), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.b_vol_quote', 'precision'], {}), '(perf.b_vol_quote, precision)\n', (5813, 5842), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((5857, 5897), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.s_vol_quote', 'precision'], {}), '(perf.s_vol_quote, precision)\n', (5868, 5897), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((5912, 5954), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.tot_vol_quote', 'precision'], {}), '(perf.tot_vol_quote, precision)\n', (5923, 5954), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((6005, 6045), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.avg_b_price', 'precision'], {}), '(perf.avg_b_price, precision)\n', (6016, 6045), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((6060, 6100), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.avg_s_price', 'precision'], {}), '(perf.avg_s_price, precision)\n', (6071, 6100), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((6115, 6157), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.avg_tot_price', 'precision'], {}), '(perf.avg_tot_price, precision)\n', (6126, 6157), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((6832, 6876), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.start_quote_bal', 'precision'], {}), '(perf.start_quote_bal, precision)\n', (6843, 6876), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((6891, 6933), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.cur_quote_bal', 'precision'], {}), '(perf.cur_quote_bal, precision)\n', (6902, 6933), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((6948, 6990), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.tot_vol_quote', 'precision'], {}), '(perf.tot_vol_quote, precision)\n', (6959, 6990), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((7053, 7082), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.start_price'], {}), '(perf.start_price)\n', (7064, 7082), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((7097, 7124), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.cur_price'], {}), '(perf.cur_price)\n', (7108, 7124), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((7139, 7185), 'hummingbot.client.performance.smart_round', 'smart_round', (['(perf.cur_price - perf.start_price)'], {}), '(perf.cur_price - perf.start_price)\n', (7150, 7185), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((6632, 6675), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.start_base_bal', 'precision'], {}), '(perf.start_base_bal, precision)\n', (6643, 6675), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((6690, 6731), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.cur_base_bal', 'precision'], {}), '(perf.cur_base_bal, precision)\n', (6701, 6731), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((6746, 6787), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.tot_vol_base', 'precision'], {}), '(perf.tot_vol_base, precision)\n', (6757, 6787), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((3970, 3997), 'hummingbot.client.settings.CONNECTOR_SETTINGS.values', 'CONNECTOR_SETTINGS.values', ([], {}), '()\n', (3995, 3997), False, 'from hummingbot.client.settings import MAXIMUM_TRADE_FILLS_DISPLAY_OUTPUT, CONNECTOR_SETTINGS, ConnectorType, DERIVATIVES\n'), ((7821, 7860), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.hold_value', 'precision'], {}), '(perf.hold_value, precision)\n', (7832, 7860), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((7917, 7955), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.cur_value', 'precision'], {}), '(perf.cur_value, precision)\n', (7928, 7955), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((8012, 8050), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.trade_pnl', 'precision'], {}), '(perf.trade_pnl, precision)\n', (8023, 8050), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((4346, 4369), 'hummingbot.user.user_balances.UserBalances.instance', 'UserBalances.instance', ([], {}), '()\n', (4367, 4369), False, 'from hummingbot.user.user_balances import UserBalances\n'), ((8142, 8176), 'hummingbot.client.performance.smart_round', 'smart_round', (['fee_amount', 'precision'], {}), '(fee_amount, precision)\n', (8153, 8176), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((8332, 8370), 'hummingbot.client.performance.smart_round', 'smart_round', (['perf.total_pnl', 'precision'], {}), '(perf.total_pnl, precision)\n', (8343, 8370), False, 'from hummingbot.client.performance import PerformanceMetrics, calculate_performance_metrics, smart_round\n'), ((4180, 4203), 'hummingbot.user.user_balances.UserBalances.instance', 'UserBalances.instance', ([], {}), '()\n', (4201, 4203), False, 'from hummingbot.user.user_balances import UserBalances\n'), ((4267, 4290), 'hummingbot.user.user_balances.UserBalances.instance', 'UserBalances.instance', ([], {}), '()\n', (4288, 4290), False, 'from hummingbot.user.user_balances import UserBalances\n'), ((4603, 4637), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', (['start_time'], {}), '(start_time)\n', (4625, 4637), False, 'from datetime import datetime\n'), ((4702, 4738), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', (['current_time'], {}), '(current_time)\n', (4724, 4738), False, 'from datetime import datetime\n')]
import asyncio import json from unittest import TestCase from unittest.mock import AsyncMock from hummingbot.connector.exchange.ndax.ndax_websocket_adaptor import NdaxWebSocketAdaptor from hummingbot.connector.exchange.ndax import ndax_constants as CONSTANTS from hummingbot.core.api_throttler.async_throttler import AsyncThrottler class NdaxWebSocketAdaptorTests(TestCase): def test_sending_messages_increment_message_number(self): sent_messages = [] throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS) ws = AsyncMock() ws.send.side_effect = lambda sent_message: sent_messages.append(sent_message) adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws) payload = {} asyncio.get_event_loop().run_until_complete(adaptor.send_request(endpoint_name=CONSTANTS.WS_PING_REQUEST, payload=payload, limit_id=CONSTANTS.WS_PING_ID)) asyncio.get_event_loop().run_until_complete(adaptor.send_request(endpoint_name=CONSTANTS.WS_PING_REQUEST, payload=payload, limit_id=CONSTANTS.WS_PING_ID)) asyncio.get_event_loop().run_until_complete(adaptor.send_request(endpoint_name=CONSTANTS.WS_ORDER_BOOK_CHANNEL, payload=payload)) self.assertEqual(3, len(sent_messages)) message = json.loads(sent_messages[0]) self.assertEqual(1, message.get('i')) message = json.loads(sent_messages[1]) self.assertEqual(2, message.get('i')) message = json.loads(sent_messages[2]) self.assertEqual(3, message.get('i')) def test_request_message_structure(self): sent_messages = [] throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS) ws = AsyncMock() ws.send.side_effect = lambda sent_message: sent_messages.append(sent_message) adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws) payload = {"TestElement1": "Value1", "TestElement2": "Value2"} asyncio.get_event_loop().run_until_complete(adaptor.send_request(endpoint_name=CONSTANTS.WS_PING_REQUEST, payload=payload, limit_id=CONSTANTS.WS_PING_ID)) self.assertEqual(1, len(sent_messages)) message = json.loads(sent_messages[0]) self.assertEqual(0, message.get('m')) self.assertEqual(1, message.get('i')) self.assertEqual(CONSTANTS.WS_PING_REQUEST, message.get('n')) message_payload = json.loads(message.get('o')) self.assertEqual(payload, message_payload) def test_receive_message(self): throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS) ws = AsyncMock() ws.recv.return_value = 'test message' adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws) received_message = asyncio.get_event_loop().run_until_complete(adaptor.recv()) self.assertEqual('test message', received_message) def test_close(self): throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS) ws = AsyncMock() adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws) asyncio.get_event_loop().run_until_complete(adaptor.close()) self.assertEquals(1, ws.close.await_count) def test_get_payload_from_raw_received_message(self): throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS) ws = AsyncMock() payload = {"Key1": True, "Key2": "Value2"} message = {"m": 1, "i": 1, "n": "Endpoint", "o": json.dumps(payload)} raw_message = json.dumps(message) adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws) extracted_payload = adaptor.payload_from_raw_message(raw_message=raw_message) self.assertEqual(payload, extracted_payload) def test_get_endpoint_from_raw_received_message(self): throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS) ws = AsyncMock() payload = {"Key1": True, "Key2": "Value2"} message = {"m": 1, "i": 1, "n": "Endpoint", "o": json.dumps(payload)} raw_message = json.dumps(message) adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws) extracted_endpoint = adaptor.endpoint_from_raw_message(raw_message=raw_message) self.assertEqual("Endpoint", extracted_endpoint)
[ "hummingbot.core.api_throttler.async_throttler.AsyncThrottler", "hummingbot.connector.exchange.ndax.ndax_websocket_adaptor.NdaxWebSocketAdaptor" ]
[((488, 525), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['CONSTANTS.RATE_LIMITS'], {}), '(CONSTANTS.RATE_LIMITS)\n', (502, 525), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((539, 550), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (548, 550), False, 'from unittest.mock import AsyncMock\n'), ((656, 701), 'hummingbot.connector.exchange.ndax.ndax_websocket_adaptor.NdaxWebSocketAdaptor', 'NdaxWebSocketAdaptor', (['throttler'], {'websocket': 'ws'}), '(throttler, websocket=ws)\n', (676, 701), False, 'from hummingbot.connector.exchange.ndax.ndax_websocket_adaptor import NdaxWebSocketAdaptor\n'), ((1619, 1647), 'json.loads', 'json.loads', (['sent_messages[0]'], {}), '(sent_messages[0])\n', (1629, 1647), False, 'import json\n'), ((1712, 1740), 'json.loads', 'json.loads', (['sent_messages[1]'], {}), '(sent_messages[1])\n', (1722, 1740), False, 'import json\n'), ((1805, 1833), 'json.loads', 'json.loads', (['sent_messages[2]'], {}), '(sent_messages[2])\n', (1815, 1833), False, 'import json\n'), ((1974, 2011), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['CONSTANTS.RATE_LIMITS'], {}), '(CONSTANTS.RATE_LIMITS)\n', (1988, 2011), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((2025, 2036), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (2034, 2036), False, 'from unittest.mock import AsyncMock\n'), ((2142, 2187), 'hummingbot.connector.exchange.ndax.ndax_websocket_adaptor.NdaxWebSocketAdaptor', 'NdaxWebSocketAdaptor', (['throttler'], {'websocket': 'ws'}), '(throttler, websocket=ws)\n', (2162, 2187), False, 'from hummingbot.connector.exchange.ndax.ndax_websocket_adaptor import NdaxWebSocketAdaptor\n'), ((2635, 2663), 'json.loads', 'json.loads', (['sent_messages[0]'], {}), '(sent_messages[0])\n', (2645, 2663), False, 'import json\n'), ((2990, 3027), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['CONSTANTS.RATE_LIMITS'], {}), '(CONSTANTS.RATE_LIMITS)\n', (3004, 3027), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((3041, 3052), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (3050, 3052), False, 'from unittest.mock import AsyncMock\n'), ((3118, 3163), 'hummingbot.connector.exchange.ndax.ndax_websocket_adaptor.NdaxWebSocketAdaptor', 'NdaxWebSocketAdaptor', (['throttler'], {'websocket': 'ws'}), '(throttler, websocket=ws)\n', (3138, 3163), False, 'from hummingbot.connector.exchange.ndax.ndax_websocket_adaptor import NdaxWebSocketAdaptor\n'), ((3358, 3395), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['CONSTANTS.RATE_LIMITS'], {}), '(CONSTANTS.RATE_LIMITS)\n', (3372, 3395), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((3409, 3420), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (3418, 3420), False, 'from unittest.mock import AsyncMock\n'), ((3440, 3485), 'hummingbot.connector.exchange.ndax.ndax_websocket_adaptor.NdaxWebSocketAdaptor', 'NdaxWebSocketAdaptor', (['throttler'], {'websocket': 'ws'}), '(throttler, websocket=ws)\n', (3460, 3485), False, 'from hummingbot.connector.exchange.ndax.ndax_websocket_adaptor import NdaxWebSocketAdaptor\n'), ((3686, 3723), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['CONSTANTS.RATE_LIMITS'], {}), '(CONSTANTS.RATE_LIMITS)\n', (3700, 3723), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((3737, 3748), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (3746, 3748), False, 'from unittest.mock import AsyncMock\n'), ((3976, 3995), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (3986, 3995), False, 'import json\n'), ((4015, 4060), 'hummingbot.connector.exchange.ndax.ndax_websocket_adaptor.NdaxWebSocketAdaptor', 'NdaxWebSocketAdaptor', (['throttler'], {'websocket': 'ws'}), '(throttler, websocket=ws)\n', (4035, 4060), False, 'from hummingbot.connector.exchange.ndax.ndax_websocket_adaptor import NdaxWebSocketAdaptor\n'), ((4281, 4318), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['CONSTANTS.RATE_LIMITS'], {}), '(CONSTANTS.RATE_LIMITS)\n', (4295, 4318), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((4332, 4343), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (4341, 4343), False, 'from unittest.mock import AsyncMock\n'), ((4571, 4590), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (4581, 4590), False, 'import json\n'), ((4610, 4655), 'hummingbot.connector.exchange.ndax.ndax_websocket_adaptor.NdaxWebSocketAdaptor', 'NdaxWebSocketAdaptor', (['throttler'], {'websocket': 'ws'}), '(throttler, websocket=ws)\n', (4630, 4655), False, 'from hummingbot.connector.exchange.ndax.ndax_websocket_adaptor import NdaxWebSocketAdaptor\n'), ((3933, 3952), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (3943, 3952), False, 'import json\n'), ((4528, 4547), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (4538, 4547), False, 'import json\n'), ((731, 755), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (753, 755), False, 'import asyncio\n'), ((1040, 1064), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1062, 1064), False, 'import asyncio\n'), ((1349, 1373), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1371, 1373), False, 'import asyncio\n'), ((2267, 2291), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2289, 2291), False, 'import asyncio\n'), ((3191, 3215), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (3213, 3215), False, 'import asyncio\n'), ((3494, 3518), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (3516, 3518), False, 'import asyncio\n')]
from typing import Optional import aiohttp from hummingbot.core.web_assistant.connections.rest_connection import RESTConnection from hummingbot.core.web_assistant.connections.ws_connection import WSConnection class ConnectionsFactory: """This class is a thin wrapper around the underlying REST and WebSocket third-party library. The purpose of the class is to isolate the general `web_assistant` infrastructure from the underlying library (in this case, `aiohttp`) to enable dependency change with minimal refactoring of the code. Note: One future possibility is to enable injection of a specific connection factory implementation in the `WebAssistantsFactory` to accommodate cases such as Bittrex that uses a specific WebSocket technology requiring a separate third-party library. In that case, a factory can be created that returns `RESTConnection`s using `aiohttp` and `WSConnection`s using `signalr_aio`. """ def __init__(self): self._shared_client: Optional[aiohttp.ClientSession] = None async def get_rest_connection(self) -> RESTConnection: shared_client = await self._get_shared_client() connection = RESTConnection(aiohttp_client_session=shared_client) return connection async def get_ws_connection(self) -> WSConnection: shared_client = await self._get_shared_client() connection = WSConnection(aiohttp_client_session=shared_client) return connection async def _get_shared_client(self) -> aiohttp.ClientSession: self._shared_client = self._shared_client or aiohttp.ClientSession() return self._shared_client
[ "hummingbot.core.web_assistant.connections.rest_connection.RESTConnection", "hummingbot.core.web_assistant.connections.ws_connection.WSConnection" ]
[((1180, 1232), 'hummingbot.core.web_assistant.connections.rest_connection.RESTConnection', 'RESTConnection', ([], {'aiohttp_client_session': 'shared_client'}), '(aiohttp_client_session=shared_client)\n', (1194, 1232), False, 'from hummingbot.core.web_assistant.connections.rest_connection import RESTConnection\n'), ((1392, 1442), 'hummingbot.core.web_assistant.connections.ws_connection.WSConnection', 'WSConnection', ([], {'aiohttp_client_session': 'shared_client'}), '(aiohttp_client_session=shared_client)\n', (1404, 1442), False, 'from hummingbot.core.web_assistant.connections.ws_connection import WSConnection\n'), ((1588, 1611), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (1609, 1611), False, 'import aiohttp\n')]
import unittest import asyncio from hummingbot.core.api_throttler.data_types import RateLimit from hummingbot.core.api_throttler.weighted_api_throttler import WeightedAPIThrottler TEST_PATH_URL = "TEST_PATH_URL" WEIGHTED_RATE_LIMIT = [ RateLimit(5, 5, TEST_PATH_URL, 2) ] class WeightedAPIThrottlerUnitTests(unittest.TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.ev_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() def setUp(self) -> None: super().setUp() self.weighted_rate_throttler = WeightedAPIThrottler(rate_limit_list=WEIGHTED_RATE_LIMIT, retry_interval=5.0) self.request_count = 0 async def execute_n_requests(self, n: int, throttler: WeightedAPIThrottler): for _ in range(n): async with throttler.execute_task(path_url=TEST_PATH_URL): self.request_count += 1 def test_weighted_rate_throttler_above_limit(self): # Test Scenario: API requests sent > Rate Limit n: int = 10 limit: int = WEIGHTED_RATE_LIMIT[0].limit weight: int = WEIGHTED_RATE_LIMIT[0].weight expected_request_count: int = limit // weight # Note: We assert a timeout ensuring that the throttler does not wait for the limit interval with self.assertRaises(asyncio.exceptions.TimeoutError): self.ev_loop.run_until_complete( asyncio.wait_for(self.execute_n_requests(n, throttler=self.weighted_rate_throttler), timeout=1.0) ) self.assertEqual(expected_request_count, self.request_count) def test_weighted_rate_throttler_below_limit(self): n: int = WEIGHTED_RATE_LIMIT[0].limit // WEIGHTED_RATE_LIMIT[0].weight self.ev_loop.run_until_complete( self.execute_n_requests(n, throttler=self.weighted_rate_throttler)) self.assertEqual(n, self.request_count) def test_weighted_rate_throttler_equal_limit(self): rate_limit: RateLimit = WEIGHTED_RATE_LIMIT[0] n: int = rate_limit.limit // rate_limit.weight self.ev_loop.run_until_complete( self.execute_n_requests(n, throttler=self.weighted_rate_throttler)) self.assertEqual(n, self.request_count)
[ "hummingbot.core.api_throttler.weighted_api_throttler.WeightedAPIThrottler", "hummingbot.core.api_throttler.data_types.RateLimit" ]
[((242, 275), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', (['(5)', '(5)', 'TEST_PATH_URL', '(2)'], {}), '(5, 5, TEST_PATH_URL, 2)\n', (251, 275), False, 'from hummingbot.core.api_throttler.data_types import RateLimit\n'), ((465, 489), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (487, 489), False, 'import asyncio\n'), ((583, 660), 'hummingbot.core.api_throttler.weighted_api_throttler.WeightedAPIThrottler', 'WeightedAPIThrottler', ([], {'rate_limit_list': 'WEIGHTED_RATE_LIMIT', 'retry_interval': '(5.0)'}), '(rate_limit_list=WEIGHTED_RATE_LIMIT, retry_interval=5.0)\n', (603, 660), False, 'from hummingbot.core.api_throttler.weighted_api_throttler import WeightedAPIThrottler\n')]
import aiohttp import asyncio import logging import statistics import time import dateutil.parser from collections import deque from hummingbot.client.config.global_config_map import global_config_map from hummingbot.logger import HummingbotLogger from hummingbot.core.utils.async_utils import safe_ensure_future class OpenwareTime: """ Used to monkey patch Openware client's time module to adjust request timestamp when needed """ _bt_logger = None _bt_shared_instance = None @classmethod def logger(cls) -> HummingbotLogger: if cls._bt_logger is None: cls._bt_logger = logging.getLogger(__name__) return cls._bt_logger @classmethod def get_instance(cls) -> "OpenwareTime": if cls._bt_shared_instance is None: cls._bt_shared_instance = OpenwareTime() return cls._bt_shared_instance def __init__(self, check_interval: float = 60.0): self._time_offset_ms = deque([]) self._set_server_time_offset_task = None self._started = False self.SERVER_TIME_OFFSET_CHECK_INTERVAL = check_interval self.median_window = 100 @property def started(self): return self._started @property def time_offset_ms(self): if not self._time_offset_ms: return 0.0 return statistics.median(self._time_offset_ms) def set_time_offset_ms(self, offset): self._time_offset_ms.append(offset) if len(self._time_offset_ms) > self.median_window : self._time_offset_ms.popleft() def time(self): return time.time() + self.time_offset_ms * 1e-3 def start(self): if self._set_server_time_offset_task is None: self._set_server_time_offset_task = safe_ensure_future(self.set_server_time_offset()) self._started = True def stop(self): if self._set_server_time_offset_task: self._set_server_time_offset_task.cancel() self._set_server_time_offset_task = None self._time_offset_ms.clear() self._started = False async def set_server_time_offset(self): while True: #try: async with aiohttp.ClientSession() as session: api_url = global_config_map.get("openware_api_url").value uri = "%s/public/timestamp" % api_url self.logger().network(f"TIME STAMP URL {uri}") async with session.get(uri) as resp: time_now_ms = time.time() * 1e3 openware_server_time = dateutil.parser.parse((await resp.text()).replace('"', '')).timestamp() * 1e3 self.logger().warning("!!!!!!! server TIME %s", openware_server_time) time_after_ms = time.time() * 1e3 expected_server_time = int((time_after_ms + time_now_ms)//2) time_offset = openware_server_time - expected_server_time self.set_time_offset_ms(time_offset) #except asyncio.CancelledError: # raise #except Exception: # self.logger().network(f"Error getting Openware server time.", exc_info=True, # app_warning_msg=f"Could not refresh Openware server time. " # f"Check network connection.") await asyncio.sleep(self.SERVER_TIME_OFFSET_CHECK_INTERVAL)
[ "hummingbot.client.config.global_config_map.global_config_map.get" ]
[((965, 974), 'collections.deque', 'deque', (['[]'], {}), '([])\n', (970, 974), False, 'from collections import deque\n'), ((1338, 1377), 'statistics.median', 'statistics.median', (['self._time_offset_ms'], {}), '(self._time_offset_ms)\n', (1355, 1377), False, 'import statistics\n'), ((622, 649), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (639, 649), False, 'import logging\n'), ((1604, 1615), 'time.time', 'time.time', ([], {}), '()\n', (1613, 1615), False, 'import time\n'), ((2208, 2231), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (2229, 2231), False, 'import aiohttp\n'), ((3394, 3447), 'asyncio.sleep', 'asyncio.sleep', (['self.SERVER_TIME_OFFSET_CHECK_INTERVAL'], {}), '(self.SERVER_TIME_OFFSET_CHECK_INTERVAL)\n', (3407, 3447), False, 'import asyncio\n'), ((2270, 2311), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""openware_api_url"""'], {}), "('openware_api_url')\n", (2291, 2311), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((2522, 2533), 'time.time', 'time.time', ([], {}), '()\n', (2531, 2533), False, 'import time\n'), ((2787, 2798), 'time.time', 'time.time', ([], {}), '()\n', (2796, 2798), False, 'import time\n')]
import asyncio import datetime import pandas as pd import psutil from decimal import Decimal from typing import ( List, Set, Tuple, Optional, ) from tabulate import tabulate from hummingbot.client.config.global_config_map import global_config_map from hummingbot.client.performance import PerformanceMetrics from hummingbot.model.trade_fill import TradeFill s_decimal_0 = Decimal("0") def format_bytes(size): for unit in ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB"]: if abs(size) < 1024.0: return f"{size:.2f} {unit}" size /= 1024.0 return f"{size:.2f} YB" async def start_timer(timer): count = 1 while True: count += 1 timer.log(f"Duration: {datetime.timedelta(seconds=count)}") await _sleep(1) async def _sleep(delay): """ A wrapper function that facilitates patching the sleep in unit tests without affecting the asyncio module """ await asyncio.sleep(delay) async def start_process_monitor(process_monitor): hb_process = psutil.Process() while True: with hb_process.oneshot(): threads = hb_process.num_threads() process_monitor.log("CPU: {:>5}%, ".format(hb_process.cpu_percent()) + "Mem: {:>10} ({}), ".format( format_bytes(hb_process.memory_info().vms / threads), format_bytes(hb_process.memory_info().rss)) + "Threads: {:>3}, ".format(threads) ) await _sleep(1) async def start_trade_monitor(trade_monitor): from hummingbot.client.hummingbot_application import HummingbotApplication hb = HummingbotApplication.main_application() trade_monitor.log("Trades: 0, Total P&L: 0.00, Return %: 0.00%") return_pcts = [] pnls = [] while True: try: if hb.strategy_task is not None and not hb.strategy_task.done(): if all(market.ready for market in hb.markets.values()): with hb.trade_fill_db.get_new_session() as session: trades: List[TradeFill] = hb._get_trades_from_session( int(hb.init_time * 1e3), session=session, config_file_path=hb.strategy_file_name) if len(trades) > 0: market_info: Set[Tuple[str, str]] = set((t.market, t.symbol) for t in trades) for market, symbol in market_info: cur_trades = [t for t in trades if t.market == market and t.symbol == symbol] cur_balances = await hb.get_current_balances(market) perf = await PerformanceMetrics.create(market, symbol, cur_trades, cur_balances) return_pcts.append(perf.return_pct) pnls.append(perf.total_pnl) avg_return = sum(return_pcts) / len(return_pcts) if len(return_pcts) > 0 else s_decimal_0 quote_assets = set(t.symbol.split("-")[1] for t in trades) if len(quote_assets) == 1: total_pnls = f"{PerformanceMetrics.smart_round(sum(pnls))} {list(quote_assets)[0]}" else: total_pnls = "N/A" trade_monitor.log(f"Trades: {len(trades)}, Total P&L: {total_pnls}, " f"Return %: {avg_return:.2%}") return_pcts.clear() pnls.clear() await _sleep(2) # sleeping for longer to manage resources except asyncio.CancelledError: raise except Exception: hb.logger().exception("start_trade_monitor failed.") def format_df_for_printout( df: pd.DataFrame, max_col_width: Optional[int] = None, index: bool = False, table_format: Optional[str] = None ) -> str: if max_col_width is not None: # in anticipation of the next release of tabulate which will include maxcolwidth max_col_width = max(max_col_width, 4) df = df.astype(str).apply( lambda s: s.apply( lambda e: e if len(e) < max_col_width else f"{e[:max_col_width - 3]}..." ) ) df.columns = [c if len(c) < max_col_width else f"{c[:max_col_width - 3]}..." for c in df.columns] table_format = table_format or global_config_map.get("tables_format").value formatted_df = tabulate(df, tablefmt=table_format, showindex=index, headers="keys") return formatted_df
[ "hummingbot.client.performance.PerformanceMetrics.create", "hummingbot.client.hummingbot_application.HummingbotApplication.main_application", "hummingbot.client.config.global_config_map.global_config_map.get" ]
[((393, 405), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (400, 405), False, 'from decimal import Decimal\n'), ((1045, 1061), 'psutil.Process', 'psutil.Process', ([], {}), '()\n', (1059, 1061), False, 'import psutil\n'), ((1737, 1777), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (1775, 1777), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((4672, 4740), 'tabulate.tabulate', 'tabulate', (['df'], {'tablefmt': 'table_format', 'showindex': 'index', 'headers': '"""keys"""'}), "(df, tablefmt=table_format, showindex=index, headers='keys')\n", (4680, 4740), False, 'from tabulate import tabulate\n'), ((955, 975), 'asyncio.sleep', 'asyncio.sleep', (['delay'], {}), '(delay)\n', (968, 975), False, 'import asyncio\n'), ((4608, 4646), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""tables_format"""'], {}), "('tables_format')\n", (4629, 4646), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((731, 764), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'count'}), '(seconds=count)\n', (749, 764), False, 'import datetime\n'), ((2831, 2898), 'hummingbot.client.performance.PerformanceMetrics.create', 'PerformanceMetrics.create', (['market', 'symbol', 'cur_trades', 'cur_balances'], {}), '(market, symbol, cur_trades, cur_balances)\n', (2856, 2898), False, 'from hummingbot.client.performance import PerformanceMetrics\n')]
import logging from typing import Optional import aiohttp from hummingbot.connector.exchange.crypto_com.crypto_com_api_user_stream_data_source import \ CryptoComAPIUserStreamDataSource from hummingbot.connector.exchange.crypto_com.crypto_com_auth import CryptoComAuth from hummingbot.connector.exchange.crypto_com.crypto_com_constants import EXCHANGE_NAME from hummingbot.core.data_type.user_stream_tracker import UserStreamTracker from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from hummingbot.logger import HummingbotLogger class CryptoComUserStreamTracker(UserStreamTracker): _cbpust_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._bust_logger is None: cls._bust_logger = logging.getLogger(__name__) return cls._bust_logger def __init__(self, crypto_com_auth: Optional[CryptoComAuth] = None, shared_client: Optional[aiohttp.ClientSession] = None, ): self._crypto_com_auth: CryptoComAuth = crypto_com_auth self._shared_client = shared_client or aiohttp.ClientSession() super().__init__(data_source=CryptoComAPIUserStreamDataSource( crypto_com_auth=self._crypto_com_auth, shared_client=self._shared_client )) @property def data_source(self) -> UserStreamTrackerDataSource: """ *required Initializes a user stream data source (user specific order diffs from live socket stream) :return: OrderBookTrackerDataSource """ if not self._data_source: self._data_source = CryptoComAPIUserStreamDataSource( crypto_com_auth=self._crypto_com_auth, shared_client=self._shared_client ) return self._data_source @property def exchange_name(self) -> str: """ *required Name of the current exchange """ return EXCHANGE_NAME async def start(self): """ *required Start all listeners and tasks """ self._user_stream_tracking_task = safe_ensure_future( self.data_source.listen_for_user_stream(self._user_stream) ) await safe_gather(self._user_stream_tracking_task)
[ "hummingbot.connector.exchange.crypto_com.crypto_com_api_user_stream_data_source.CryptoComAPIUserStreamDataSource", "hummingbot.core.utils.async_utils.safe_gather" ]
[((910, 937), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (927, 937), False, 'import logging\n'), ((1262, 1285), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (1283, 1285), False, 'import aiohttp\n'), ((1788, 1898), 'hummingbot.connector.exchange.crypto_com.crypto_com_api_user_stream_data_source.CryptoComAPIUserStreamDataSource', 'CryptoComAPIUserStreamDataSource', ([], {'crypto_com_auth': 'self._crypto_com_auth', 'shared_client': 'self._shared_client'}), '(crypto_com_auth=self._crypto_com_auth,\n shared_client=self._shared_client)\n', (1820, 1898), False, 'from hummingbot.connector.exchange.crypto_com.crypto_com_api_user_stream_data_source import CryptoComAPIUserStreamDataSource\n'), ((2398, 2442), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['self._user_stream_tracking_task'], {}), '(self._user_stream_tracking_task)\n', (2409, 2442), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((1323, 1433), 'hummingbot.connector.exchange.crypto_com.crypto_com_api_user_stream_data_source.CryptoComAPIUserStreamDataSource', 'CryptoComAPIUserStreamDataSource', ([], {'crypto_com_auth': 'self._crypto_com_auth', 'shared_client': 'self._shared_client'}), '(crypto_com_auth=self._crypto_com_auth,\n shared_client=self._shared_client)\n', (1355, 1433), False, 'from hummingbot.connector.exchange.crypto_com.crypto_com_api_user_stream_data_source import CryptoComAPIUserStreamDataSource\n')]
import asyncio import logging import math import time import unittest from decimal import Decimal from typing import ( Dict, List, ) from hummingbot.client.config.global_config_map import global_config_map from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler from hummingbot.core.api_throttler.data_types import RateLimit, TaskLog from hummingbot.logger.struct_logger import METRICS_LOG_LEVEL TEST_PATH_URL = "/hummingbot" TEST_POLL_ID = "TEST" logging.basicConfig(level=METRICS_LOG_LEVEL) class AsyncThrottlerUnitTests(unittest.TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.ev_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() cls.rate_limits: List[RateLimit] = [ RateLimit(limit_id=TEST_POLL_ID, limit=1, time_interval=5.0), RateLimit(limit_id=TEST_PATH_URL, limit=1, time_interval=5.0, linked_limits=[TEST_POLL_ID]) ] def setUp(self) -> None: super().setUp() self.throttler = AsyncThrottler(rate_limits=self.rate_limits) self._req_counters: Dict[str, int] = {limit.limit_id: 0 for limit in self.rate_limits} def tearDown(self) -> None: global_config_map["rate_limits_share_pct"].value = None super().tearDown() async def execute_requests(self, no_request: int, limit_id: str, throttler: AsyncThrottler): for _ in range(no_request): async with throttler.execute_task(limit_id=limit_id): self._req_counters[limit_id] += 1 def test_init_without_rate_limits_share_pct(self): self.assertEqual(0.1, self.throttler._retry_interval) self.assertEqual(2, len(self.throttler._rate_limits)) self.assertEqual(1, self.throttler._id_to_limit_map[TEST_POLL_ID].limit) self.assertEqual(1, self.throttler._id_to_limit_map[TEST_PATH_URL].limit) def test_init_with_rate_limits_share_pct(self): rate_share_pct: Decimal = Decimal("55") global_config_map["rate_limits_share_pct"].value = rate_share_pct rate_limits = self.rate_limits.copy() rate_limits.append(RateLimit(limit_id="ANOTHER_TEST", limit=10, time_interval=5)) expected_limit = math.floor(Decimal("10") * rate_share_pct / Decimal("100")) throttler = AsyncThrottler(rate_limits=rate_limits) self.assertEqual(0.1, throttler._retry_interval) self.assertEqual(3, len(throttler._rate_limits)) self.assertEqual(Decimal("1"), throttler._id_to_limit_map[TEST_POLL_ID].limit) self.assertEqual(Decimal("1"), throttler._id_to_limit_map[TEST_PATH_URL].limit) self.assertEqual(expected_limit, throttler._id_to_limit_map["ANOTHER_TEST"].limit) def test_get_relevant_limits(self): self.assertEqual(2, len(self.throttler._rate_limits)) self.assertEqual(1, len(self.throttler.get_relevant_limits(TEST_POLL_ID))) self.assertEqual(2, len(self.throttler.get_relevant_limits(TEST_PATH_URL))) def test_flush_empty_task_logs(self): # Test: No entries in task_logs to flush lock = asyncio.Lock() self.assertEqual(0, len(self.throttler._task_logs)) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limits=self.rate_limits, lock=lock, safety_margin_pct=self.throttler._safety_margin_pct) context.flush() self.assertEqual(0, len(self.throttler._task_logs)) def test_flush_only_elapsed_tasks_are_flushed(self): lock = asyncio.Lock() self.throttler._task_logs = [ TaskLog(timestamp=1.0, rate_limits=self.rate_limits), TaskLog(timestamp=time.time(), rate_limits=self.rate_limits) ] self.assertEqual(2, len(self.throttler._task_logs)) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limits=self.rate_limits, lock=lock, safety_margin_pct=self.throttler._safety_margin_pct) context.flush() self.assertEqual(1, len(self.throttler._task_logs)) def test_within_capacity_returns_false(self): self.throttler._task_logs.append(TaskLog(timestamp=time.time(), rate_limits=self.rate_limits)) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limits=self.rate_limits, lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) self.assertFalse(context.within_capacity()) def test_within_capacity_returns_true(self): lock = asyncio.Lock() context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limits=self.rate_limits, lock=lock, safety_margin_pct=self.throttler._safety_margin_pct) self.assertTrue(context.within_capacity()) def test_acquire_appends_to_task_logs(self): context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limits=self.rate_limits, lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) self.ev_loop.run_until_complete(context.acquire()) self.assertEqual(1, len(self.throttler._task_logs)) def test_acquire_awaits_when_exceed_capacity(self): self.throttler._task_logs.append(TaskLog(timestamp=time.time(), rate_limits=self.rate_limits)) context = AsyncRequestContext(task_logs=self.throttler._task_logs, rate_limits=self.rate_limits, lock=asyncio.Lock(), safety_margin_pct=self.throttler._safety_margin_pct) with self.assertRaises(asyncio.exceptions.TimeoutError): self.ev_loop.run_until_complete( asyncio.wait_for(context.acquire(), 1.0) )
[ "hummingbot.core.api_throttler.async_throttler.AsyncRequestContext", "hummingbot.core.api_throttler.data_types.TaskLog", "hummingbot.core.api_throttler.data_types.RateLimit", "hummingbot.core.api_throttler.async_throttler.AsyncThrottler" ]
[((500, 544), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'METRICS_LOG_LEVEL'}), '(level=METRICS_LOG_LEVEL)\n', (519, 544), False, 'import logging\n'), ((725, 749), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (747, 749), False, 'import asyncio\n'), ((1063, 1107), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', ([], {'rate_limits': 'self.rate_limits'}), '(rate_limits=self.rate_limits)\n', (1077, 1107), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((2008, 2021), 'decimal.Decimal', 'Decimal', (['"""55"""'], {}), "('55')\n", (2015, 2021), False, 'from decimal import Decimal\n'), ((2339, 2378), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', ([], {'rate_limits': 'rate_limits'}), '(rate_limits=rate_limits)\n', (2353, 2378), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((3137, 3151), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (3149, 3151), False, 'import asyncio\n'), ((3231, 3391), 'hummingbot.core.api_throttler.async_throttler.AsyncRequestContext', 'AsyncRequestContext', ([], {'task_logs': 'self.throttler._task_logs', 'rate_limits': 'self.rate_limits', 'lock': 'lock', 'safety_margin_pct': 'self.throttler._safety_margin_pct'}), '(task_logs=self.throttler._task_logs, rate_limits=self.\n rate_limits, lock=lock, safety_margin_pct=self.throttler._safety_margin_pct\n )\n', (3250, 3391), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((3653, 3667), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (3665, 3667), False, 'import asyncio\n'), ((3935, 4095), 'hummingbot.core.api_throttler.async_throttler.AsyncRequestContext', 'AsyncRequestContext', ([], {'task_logs': 'self.throttler._task_logs', 'rate_limits': 'self.rate_limits', 'lock': 'lock', 'safety_margin_pct': 'self.throttler._safety_margin_pct'}), '(task_logs=self.throttler._task_logs, rate_limits=self.\n rate_limits, lock=lock, safety_margin_pct=self.throttler._safety_margin_pct\n )\n', (3954, 4095), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((4849, 4863), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (4861, 4863), False, 'import asyncio\n'), ((4882, 5042), 'hummingbot.core.api_throttler.async_throttler.AsyncRequestContext', 'AsyncRequestContext', ([], {'task_logs': 'self.throttler._task_logs', 'rate_limits': 'self.rate_limits', 'lock': 'lock', 'safety_margin_pct': 'self.throttler._safety_margin_pct'}), '(task_logs=self.throttler._task_logs, rate_limits=self.\n rate_limits, lock=lock, safety_margin_pct=self.throttler._safety_margin_pct\n )\n', (4901, 5042), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncRequestContext, AsyncThrottler\n'), ((808, 868), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'TEST_POLL_ID', 'limit': '(1)', 'time_interval': '(5.0)'}), '(limit_id=TEST_POLL_ID, limit=1, time_interval=5.0)\n', (817, 868), False, 'from hummingbot.core.api_throttler.data_types import RateLimit, TaskLog\n'), ((882, 978), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': 'TEST_PATH_URL', 'limit': '(1)', 'time_interval': '(5.0)', 'linked_limits': '[TEST_POLL_ID]'}), '(limit_id=TEST_PATH_URL, limit=1, time_interval=5.0, linked_limits\n =[TEST_POLL_ID])\n', (891, 978), False, 'from hummingbot.core.api_throttler.data_types import RateLimit, TaskLog\n'), ((2170, 2231), 'hummingbot.core.api_throttler.data_types.RateLimit', 'RateLimit', ([], {'limit_id': '"""ANOTHER_TEST"""', 'limit': '(10)', 'time_interval': '(5)'}), "(limit_id='ANOTHER_TEST', limit=10, time_interval=5)\n", (2179, 2231), False, 'from hummingbot.core.api_throttler.data_types import RateLimit, TaskLog\n'), ((2518, 2530), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (2525, 2530), False, 'from decimal import Decimal\n'), ((2605, 2617), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (2612, 2617), False, 'from decimal import Decimal\n'), ((3719, 3771), 'hummingbot.core.api_throttler.data_types.TaskLog', 'TaskLog', ([], {'timestamp': '(1.0)', 'rate_limits': 'self.rate_limits'}), '(timestamp=1.0, rate_limits=self.rate_limits)\n', (3726, 3771), False, 'from hummingbot.core.api_throttler.data_types import RateLimit, TaskLog\n'), ((2302, 2316), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (2309, 2316), False, 'from decimal import Decimal\n'), ((4625, 4639), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (4637, 4639), False, 'import asyncio\n'), ((5434, 5448), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (5446, 5448), False, 'import asyncio\n'), ((6006, 6020), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (6018, 6020), False, 'import asyncio\n'), ((2269, 2282), 'decimal.Decimal', 'Decimal', (['"""10"""'], {}), "('10')\n", (2276, 2282), False, 'from decimal import Decimal\n'), ((3803, 3814), 'time.time', 'time.time', ([], {}), '()\n', (3812, 3814), False, 'import time\n'), ((4394, 4405), 'time.time', 'time.time', ([], {}), '()\n', (4403, 4405), False, 'import time\n'), ((5776, 5787), 'time.time', 'time.time', ([], {}), '()\n', (5785, 5787), False, 'import time\n')]
import asyncio import logging from decimal import Decimal from typing import Optional from hummingbot.client.config.global_config_map import global_config_map from hummingbot.logger import HummingbotLogger from hummingbot.core.utils.async_utils import safe_ensure_future class KillSwitch: ks_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls.ks_logger is None: cls.ks_logger = logging.getLogger(__name__) return cls.ks_logger def __init__(self, hummingbot_application: "HummingbotApplication"): # noqa F821 self._hummingbot_application = hummingbot_application self._kill_switch_enabled: bool = global_config_map.get("kill_switch_enabled").value self._kill_switch_rate: Decimal = Decimal(global_config_map.get("kill_switch_rate").value or "0.0") self._started = False self._update_interval = 10.0 self._check_profitability_task: Optional[asyncio.Task] = None self._profitability: Optional[Decimal] = None async def check_profitability_loop(self): while True: try: if self._kill_switch_enabled: # calculate_profitability gives profitability in percent terms i.e. 0.015 to indicate 0.015% # self._kill_switch_rate is in numerical term 1.e. 0.015 to indicate 1.5% self._profitability: Decimal = \ self._hummingbot_application.calculate_profitability() / Decimal("100") # Stop the bot if losing too much money, or if gained a certain amount of profit if (self._profitability <= self._kill_switch_rate < Decimal("0.0")) or \ (self._profitability >= self._kill_switch_rate > Decimal("0.0")): self.logger().info("Kill switch threshold reached. Stopping the bot...") self._hummingbot_application._notify(f"\n[Kill switch triggered]\n" f"Current profitability " f"is {self._profitability}. Stopping the bot...") self._hummingbot_application.trade_performance_report() self._hummingbot_application.stop() break except asyncio.CancelledError: raise except Exception as e: self.logger().error(f"Error calculating profitability: {e}", exc_info=True) await asyncio.sleep(self._update_interval) def start(self): safe_ensure_future(self.start_loop()) async def start_loop(self): self.stop() self._check_profitability_task = safe_ensure_future(self.check_profitability_loop()) self._started = True def stop(self): if self._check_profitability_task and not self._check_profitability_task.done(): self._check_profitability_task.cancel() self._started = False
[ "hummingbot.client.config.global_config_map.global_config_map.get" ]
[((461, 488), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (478, 488), False, 'import logging\n'), ((727, 771), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""kill_switch_enabled"""'], {}), "('kill_switch_enabled')\n", (748, 771), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((2622, 2658), 'asyncio.sleep', 'asyncio.sleep', (['self._update_interval'], {}), '(self._update_interval)\n', (2635, 2658), False, 'import asyncio\n'), ((828, 869), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""kill_switch_rate"""'], {}), "('kill_switch_rate')\n", (849, 869), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((1549, 1563), 'decimal.Decimal', 'Decimal', (['"""100"""'], {}), "('100')\n", (1556, 1563), False, 'from decimal import Decimal\n'), ((1738, 1752), 'decimal.Decimal', 'Decimal', (['"""0.0"""'], {}), "('0.0')\n", (1745, 1752), False, 'from decimal import Decimal\n'), ((1836, 1850), 'decimal.Decimal', 'Decimal', (['"""0.0"""'], {}), "('0.0')\n", (1843, 1850), False, 'from decimal import Decimal\n')]
import asyncio import aiohttp import logging import pandas as pd import time from typing import Any, AsyncIterable, Dict, List, Optional import ujson import websockets from websockets.exceptions import ConnectionClosed from hummingbot.core.utils import async_ttl_cache from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.data_type.order_book_message import OrderBookMessage from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource from hummingbot.logger import HummingbotLogger from hummingbot.market.liquid.liquid_order_book import LiquidOrderBook from hummingbot.market.liquid.liquid_order_book_tracker_entry import LiquidOrderBookTrackerEntry from hummingbot.market.liquid.constants import Constants class LiquidAPIOrderBookDataSource(OrderBookTrackerDataSource): _laobds_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> (HummingbotLogger): if cls._laobds_logger is None: cls._laobds_logger = logging.getLogger(__name__) return cls._laobds_logger def __init__(self, trading_pairs: Optional[List[str]] = None): super().__init__() self._trading_pairs: Optional[List[str]] = trading_pairs self._order_book_create_function = lambda: OrderBook() self.trading_pair_id_conversion_dict: Dict[str, int] = {} @staticmethod def reformat_trading_pairs(products): """ Add a new key 'trading_pair' to the incoming json list Modify trading pair from '{baseAsset}{quoteAsset}' to '{baseAsset}-{quoteAsset}' format """ for data in products: data['trading_pair'] = '-'.join([data['base_currency'], data['quoted_currency']]) return products @classmethod @async_ttl_cache(ttl=60 * 30, maxsize=1) # TODO: Not really sure what this does async def get_active_exchange_markets(cls) -> (pd.DataFrame): """ Returned data frame should have 'currency_pair_code' as index and include * usd volume * baseAsset * quoteAsset """ # Fetch raw exchange and markets data from Liquid exchange_markets_data: list = await cls.get_exchange_markets_data() # TODO: Understand the behavior of a non async method wrapped by another async method # Make sure doing this will not block other task market_data: List[str, Any] = cls.filter_market_data( exchange_markets_data=exchange_markets_data) market_data = cls.reformat_trading_pairs(market_data) # Build the data frame all_markets_df: pd.DataFrame = pd.DataFrame.from_records(data=market_data, index='trading_pair') btc_price: float = float(all_markets_df.loc['BTC-USD'].last_traded_price) eth_price: float = float(all_markets_df.loc['ETH-USD'].last_traded_price) usd_volume: float = [ ( volume * quote_price if trading_pair.endswith(("USD", "USDC")) else volume * quote_price * btc_price if trading_pair.endswith("BTC") else volume * quote_price * eth_price if trading_pair.endswith("ETH") else volume ) for trading_pair, volume, quote_price in zip( all_markets_df.index, all_markets_df.volume_24h.astype('float'), all_markets_df.last_traded_price.astype('float') ) ] all_markets_df.loc[:, 'USDVolume'] = usd_volume all_markets_df.loc[:, 'volume'] = all_markets_df.volume_24h all_markets_df.rename( {"base_currency": "baseAsset", "quoted_currency": "quoteAsset"}, axis="columns", inplace=True ) return all_markets_df.sort_values("USDVolume", ascending=False) @classmethod async def get_exchange_markets_data(cls) -> (List): """ Fetch Liquid exchange data from '/products' with following structure: exchange_markets_data (Dict) |-- id: str |-- product_type: str |-- code: str |-- name: str |-- market_ask: float |-- market_bid: float |-- indicator: int |-- currency: str |-- currency_pair_code: str |-- symbol: str |-- btc_minimum_withdraw: float |-- fiat_minimum_withdraw: float |-- pusher_channel: str |-- taker_fee: str (float) |-- maker_fee: str (float) |-- low_market_bid: str (float) |-- high_market_ask: str (float) |-- volume_24h: str (float) |-- last_price_24h: str (float) |-- last_traded_price: str (float) |-- last_traded_quantity: str (float) |-- quoted_currency: str |-- base_currency: str |-- disabled: bool |-- margin_enabled: bool |-- cfd_enabled: bool |-- last_event_timestamp: str """ async with aiohttp.ClientSession() as client: exchange_markets_response: aiohttp.ClientResponse = await client.get( Constants.GET_EXCHANGE_MARKETS_URL) if exchange_markets_response.status != 200: raise IOError(f"Error fetching Liquid markets information. " f"HTTP status is {exchange_markets_response.status}.") exchange_markets_data = await exchange_markets_response.json() return exchange_markets_data @classmethod def filter_market_data(cls, exchange_markets_data) -> (List[dict]): """ Filter out: * Market with invalid 'symbol' key, note: symbol here is not the same as trading pair * Market with 'disabled' field set to True """ return [ item for item in exchange_markets_data if item['disabled'] is False ] async def get_trading_pairs(self) -> List[str]: """ Extract trading_pairs information from all_markets_df generated in get_active_exchange_markets method. Along the way, also populate the self._trading_pair_id_conversion_dict, for downstream reference since Liquid API uses id instead of trading pair as the identifier """ try: if not self.trading_pair_id_conversion_dict: active_markets_df: pd.DataFrame = await self.get_active_exchange_markets() if not self._trading_pairs: self._trading_pairs = active_markets_df.index.tolist() self.trading_pair_id_conversion_dict = { trading_pair: active_markets_df.loc[trading_pair, 'id'] for trading_pair in self._trading_pairs } except Exception: self._trading_pairs = [] self.logger().network( f"Error getting active exchange information.", exe_info=True, app_warning_msg=f"Error getting active exchange information. Check network connection." ) return self._trading_pairs async def get_snapshot(self, client: aiohttp.ClientSession, trading_pair: str, full: int = 1) -> Dict[str, Any]: """ Method designed to fetch individual trading_pair corresponded order book, aka snapshot param: client - aiohttp client session param: trading_pair - used to identify different order book, will be converted to id param: full - with full set to 1, return full order book, otherwise return 20 records if 0 is selected snapshot (dict) |-- buy_price_levels: list[str, str] # [price, amount] |-- sell_price_levels: list[str, str] # [price, amount] """ product_id = self.trading_pair_id_conversion_dict.get(trading_pair, None) if not product_id: raise ValueError(f"Invalid trading pair {trading_pair} and product id {product_id} found") async with client.get(Constants.GET_SNAPSHOT_URL.format(id=product_id, full=full)) as response: response: aiohttp.ClientResponse = response if response.status != 200: raise IOError(f"Error fetching Liquid market snapshot for {id}. " f"HTTP status is {response.status}.") snapshot: Dict[str, Any] = await response.json() return { **snapshot, 'trading_pair': trading_pair } async def get_tracking_pairs(self) -> Dict[str, LiquidOrderBookTrackerEntry]: """ Create tracking pairs by using trading pairs (trading_pairs) fetched from active markets """ # Get the currently active markets async with aiohttp.ClientSession() as client: trading_pairs: List[str] = await self.get_trading_pairs() retval: Dict[str, LiquidOrderBookTrackerEntry] = {} number_of_pairs: int = len(trading_pairs) for index, trading_pair in enumerate(trading_pairs): try: snapshot: Dict[str, Any] = await self.get_snapshot(client, trading_pair, 1) snapshot_timestamp: float = time.time() snapshot_msg: OrderBookMessage = LiquidOrderBook.snapshot_message_from_exchange( snapshot, snapshot_timestamp, metadata={"trading_pair": trading_pair} ) order_book: OrderBook = self.order_book_create_function() order_book.apply_snapshot(snapshot_msg.bids, snapshot_msg.asks, snapshot_msg.update_id) retval[trading_pair] = LiquidOrderBookTrackerEntry(trading_pair, snapshot_timestamp, order_book) self.logger().info(f"Initialized order book for {trading_pair}." f"{index*1}/{number_of_pairs} completed") # Each 1000 limit snapshot costs ?? requests and Liquid rate limit is ?? requests per second. await asyncio.sleep(1.0) # Might need to be changed except Exception: self.logger().error(f"Error getting snapshot for {trading_pair}. ", exc_info=True) await asyncio.sleep(5) return retval async def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): pass async def _inner_messages(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]: """ Generator function that returns messages from the web socket stream :param ws: current web socket connection :returns: message in AsyncIterable format """ # Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect. try: while True: try: msg: str = await asyncio.wait_for(ws.recv(), timeout=Constants.MESSAGE_TIMEOUT) yield msg except asyncio.TimeoutError: try: pong_waiter = await ws.ping() await asyncio.wait_for(pong_waiter, timeout=Constants.PING_TIMEOUT) except asyncio.TimeoutError: raise except asyncio.TimeoutError: self.logger().warning("WebSocket ping timed out. Going to reconnect...") return except ConnectionClosed: return finally: await ws.close() async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Subscribe to diff channel via web socket, and keep the connection open for incoming messages :param ev_loop: ev_loop to execute this function in :param output: an async queue where the incoming messages are stored """ # {old_trading_pair: new_trading_pair} old_trading_pair_conversions = {} while True: try: trading_pairs: List[str] = await self.get_trading_pairs() async with websockets.connect(Constants.BAEE_WS_URL) as ws: ws: websockets.WebSocketClientProtocol = ws for trading_pair in trading_pairs: old_trading_pair = trading_pair.replace('-', '') old_trading_pair_conversions[old_trading_pair] = trading_pair for side in [Constants.SIDE_BID, Constants.SIDE_ASK]: subscribe_request: Dict[str, Any] = { "event": Constants.WS_PUSHER_SUBSCRIBE_EVENT, "data": { "channel": Constants.WS_ORDER_BOOK_DIFF_SUBSCRIPTION.format( currency_pair_code=old_trading_pair.lower(), side=side) } } await ws.send(ujson.dumps(subscribe_request)) async for raw_msg in self._inner_messages(ws): diff_msg: Dict[str, Any] = ujson.loads(raw_msg) event_type = diff_msg.get('event', None) if event_type == 'updated': # Channel example: 'price_ladders_cash_ethusd_sell' old_trading_pair = diff_msg.get('channel').split('_')[-2].upper() trading_pair = old_trading_pair_conversions[old_trading_pair] buy_or_sell = diff_msg.get('channel').split('_')[-1].lower() side = 'asks' if buy_or_sell == Constants.SIDE_ASK else 'bids' diff_msg = { '{0}'.format(side): ujson.loads(diff_msg.get('data', [])), 'trading_pair': trading_pair } diff_timestamp: float = time.time() msg: OrderBookMessage = LiquidOrderBook.diff_message_from_exchange( diff_msg, diff_timestamp, metadata={ "trading_pair": trading_pair, "update_id": int(diff_timestamp * 1e-3) } ) output.put_nowait(msg) elif not event_type: raise ValueError(f"Liquid Websocket message does not contain an event type - {diff_msg}") except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...", exc_info=True) await asyncio.sleep(30.0) async def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): """ Fetches order book snapshots for each trading pair, and use them to update the local order book :param ev_loop: ev_loop to execute this function in :param output: an async queue where the incoming messages are stored TODO: This method needs to be further break down, otherwise, whenever error occurs, the only message getting is something similar to `Unexpected error with WebSocket connection.` """ while True: try: trading_pairs: List[str] = await self.get_trading_pairs() async with aiohttp.ClientSession() as client: for trading_pair in trading_pairs: try: snapshot: Dict[str, any] = await self.get_snapshot(client, trading_pair) snapshot_timestamp: float = time.time() snapshot['asks'] = snapshot.get('sell_price_levels') snapshot['bids'] = snapshot.get('buy_price_levels') snapshot_msg: OrderBookMessage = LiquidOrderBook.snapshot_message_from_exchange( msg=snapshot, timestamp=snapshot_timestamp, metadata={ 'trading_pair': trading_pair } ) output.put_nowait(snapshot_msg) self.logger().debug(f"Saved order book snapshot for {trading_pair}") # Be careful not to go above API rate limits. await asyncio.sleep(5.0) except asyncio.CancelledError: raise except Exception as e: print(e) self.logger().network( f"Unexpected error with WebSocket connection.", exc_info=True, app_warning_msg=f"Unexpected error with WebSocket connection. Retrying in 5 seconds. " f"Check network connection." ) await asyncio.sleep(5.0) this_hour: pd.Timestamp = pd.Timestamp.utcnow().replace(minute=0, second=0, microsecond=0) next_hour: pd.Timestamp = this_hour + pd.Timedelta(hours=1) delta: float = next_hour.timestamp() - time.time() await asyncio.sleep(delta) except asyncio.CancelledError: raise except Exception: self.logger().error("Unexpected error.", exc_info=True) await asyncio.sleep(5.0)
[ "hummingbot.core.data_type.order_book.OrderBook", "hummingbot.core.utils.async_ttl_cache", "hummingbot.market.liquid.constants.Constants.GET_SNAPSHOT_URL.format", "hummingbot.market.liquid.liquid_order_book.LiquidOrderBook.snapshot_message_from_exchange", "hummingbot.market.liquid.liquid_order_book_tracker_...
[((1794, 1833), 'hummingbot.core.utils.async_ttl_cache', 'async_ttl_cache', ([], {'ttl': '(60 * 30)', 'maxsize': '(1)'}), '(ttl=60 * 30, maxsize=1)\n', (1809, 1833), False, 'from hummingbot.core.utils import async_ttl_cache\n'), ((2647, 2712), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', ([], {'data': 'market_data', 'index': '"""trading_pair"""'}), "(data=market_data, index='trading_pair')\n", (2672, 2712), True, 'import pandas as pd\n'), ((1025, 1052), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1042, 1052), False, 'import logging\n'), ((1299, 1310), 'hummingbot.core.data_type.order_book.OrderBook', 'OrderBook', ([], {}), '()\n', (1308, 1310), False, 'from hummingbot.core.data_type.order_book import OrderBook\n'), ((4924, 4947), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (4945, 4947), False, 'import aiohttp\n'), ((8718, 8741), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (8739, 8741), False, 'import aiohttp\n'), ((7956, 8015), 'hummingbot.market.liquid.constants.Constants.GET_SNAPSHOT_URL.format', 'Constants.GET_SNAPSHOT_URL.format', ([], {'id': 'product_id', 'full': 'full'}), '(id=product_id, full=full)\n', (7989, 8015), False, 'from hummingbot.market.liquid.constants import Constants\n'), ((9175, 9186), 'time.time', 'time.time', ([], {}), '()\n', (9184, 9186), False, 'import time\n'), ((9240, 9361), 'hummingbot.market.liquid.liquid_order_book.LiquidOrderBook.snapshot_message_from_exchange', 'LiquidOrderBook.snapshot_message_from_exchange', (['snapshot', 'snapshot_timestamp'], {'metadata': "{'trading_pair': trading_pair}"}), "(snapshot, snapshot_timestamp,\n metadata={'trading_pair': trading_pair})\n", (9286, 9361), False, 'from hummingbot.market.liquid.liquid_order_book import LiquidOrderBook\n'), ((9683, 9756), 'hummingbot.market.liquid.liquid_order_book_tracker_entry.LiquidOrderBookTrackerEntry', 'LiquidOrderBookTrackerEntry', (['trading_pair', 'snapshot_timestamp', 'order_book'], {}), '(trading_pair, snapshot_timestamp, order_book)\n', (9710, 9756), False, 'from hummingbot.market.liquid.liquid_order_book_tracker_entry import LiquidOrderBookTrackerEntry\n'), ((12181, 12222), 'websockets.connect', 'websockets.connect', (['Constants.BAEE_WS_URL'], {}), '(Constants.BAEE_WS_URL)\n', (12199, 12222), False, 'import websockets\n'), ((15754, 15777), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (15775, 15777), False, 'import aiohttp\n'), ((10064, 10082), 'asyncio.sleep', 'asyncio.sleep', (['(1.0)'], {}), '(1.0)\n', (10077, 10082), False, 'import asyncio\n'), ((13225, 13245), 'ujson.loads', 'ujson.loads', (['raw_msg'], {}), '(raw_msg)\n', (13236, 13245), False, 'import ujson\n'), ((15027, 15046), 'asyncio.sleep', 'asyncio.sleep', (['(30.0)'], {}), '(30.0)\n', (15040, 15046), False, 'import asyncio\n'), ((17675, 17696), 'pandas.Timedelta', 'pd.Timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (17687, 17696), True, 'import pandas as pd\n'), ((17756, 17767), 'time.time', 'time.time', ([], {}), '()\n', (17765, 17767), False, 'import time\n'), ((17794, 17814), 'asyncio.sleep', 'asyncio.sleep', (['delta'], {}), '(delta)\n', (17807, 17814), False, 'import asyncio\n'), ((18004, 18022), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (18017, 18022), False, 'import asyncio\n'), ((10274, 10290), 'asyncio.sleep', 'asyncio.sleep', (['(5)'], {}), '(5)\n', (10287, 10290), False, 'import asyncio\n'), ((14085, 14096), 'time.time', 'time.time', ([], {}), '()\n', (14094, 14096), False, 'import time\n'), ((16030, 16041), 'time.time', 'time.time', ([], {}), '()\n', (16039, 16041), False, 'import time\n'), ((16264, 16400), 'hummingbot.market.liquid.liquid_order_book.LiquidOrderBook.snapshot_message_from_exchange', 'LiquidOrderBook.snapshot_message_from_exchange', ([], {'msg': 'snapshot', 'timestamp': 'snapshot_timestamp', 'metadata': "{'trading_pair': trading_pair}"}), "(msg=snapshot, timestamp=\n snapshot_timestamp, metadata={'trading_pair': trading_pair})\n", (16310, 16400), False, 'from hummingbot.market.liquid.liquid_order_book import LiquidOrderBook\n'), ((17552, 17573), 'pandas.Timestamp.utcnow', 'pd.Timestamp.utcnow', ([], {}), '()\n', (17571, 17573), True, 'import pandas as pd\n'), ((11204, 11265), 'asyncio.wait_for', 'asyncio.wait_for', (['pong_waiter'], {'timeout': 'Constants.PING_TIMEOUT'}), '(pong_waiter, timeout=Constants.PING_TIMEOUT)\n', (11220, 11265), False, 'import asyncio\n'), ((16857, 16875), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (16870, 16875), False, 'import asyncio\n'), ((13074, 13104), 'ujson.dumps', 'ujson.dumps', (['subscribe_request'], {}), '(subscribe_request)\n', (13085, 13104), False, 'import ujson\n'), ((17487, 17505), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (17500, 17505), False, 'import asyncio\n')]
#!/usr/bin/env python import path_util # noqa: F401 import asyncio import logging from typing import ( Coroutine, List, ) from hummingbot import ( check_dev_mode, init_logging, ) from hummingbot.client.hummingbot_application import HummingbotApplication from hummingbot.client.config.global_config_map import global_config_map from hummingbot.client.config.in_memory_config_map import in_memory_config_map from hummingbot.client.config.config_helpers import ( create_yml_files, load_required_configs, read_configs_from_yml, ) from hummingbot.client.ui.stdout_redirection import patch_stdout from hummingbot.client.ui.parser import ThrowingArgumentParser from hummingbot.client.settings import STRATEGIES from hummingbot.core.utils.wallet_setup import unlock_wallet from hummingbot.core.utils.async_utils import safe_gather from hummingbot.core.management.console import start_management_console from bin.hummingbot import ( detect_available_port, main as normal_start, ) from hummingbot.client.config.config_helpers import write_config_to_yml class CmdlineParser(ThrowingArgumentParser): def __init__(self): super().__init__() self.add_argument("--strategy", "-s", type=str, choices=STRATEGIES, required=True, help="Choose the strategy you would like to run.") self.add_argument("--config-file-name", "-f", type=str, required=True, help="Specify a file in `conf/` to load as the strategy config file.") self.add_argument("--wallet", "-w", type=str, required=False, help="Specify the wallet public key you would like to use.") self.add_argument("--config-password", "--wallet-password", "-p", type=str, required=False, help="Specify the password to unlock your encrypted files and wallets.") async def quick_start(): try: args = CmdlineParser().parse_args() strategy = args.strategy config_file_name = args.config_file_name wallet = args.wallet password = args.config_password await create_yml_files() init_logging("hummingbot_logs.yml") read_configs_from_yml() hb = HummingbotApplication.main_application() in_memory_config_map.get("password").value = password in_memory_config_map.get("strategy").value = strategy in_memory_config_map.get("strategy").validate(strategy) in_memory_config_map.get("strategy_file_path").value = config_file_name in_memory_config_map.get("strategy_file_path").validate(config_file_name) # To ensure quickstart runs with the default value of False for kill_switch_enabled if not present if not global_config_map.get("kill_switch_enabled"): global_config_map.get("kill_switch_enabled").value = False if wallet and password: global_config_map.get("wallet").value = wallet hb.acct = unlock_wallet(public_key=wallet, password=password) if not hb.config_complete: config_map = load_required_configs() empty_configs = [key for key, config in config_map.items() if config.value is None and config.required] empty_config_description: str = "\n- ".join([""] + empty_configs) raise ValueError(f"Missing empty configs: {empty_config_description}\n") with patch_stdout(log_field=hb.app.log_field): dev_mode = check_dev_mode() if dev_mode: hb.app.log("Running from dev branches. Full remote logging will be enabled.") log_level = global_config_map.get("log_level").value init_logging("hummingbot_logs.yml", override_log_level=log_level, dev_mode=dev_mode, strategy_file_path=config_file_name) await write_config_to_yml() hb.start(log_level) tasks: List[Coroutine] = [hb.run()] if global_config_map.get("debug_console").value: management_port: int = detect_available_port(8211) tasks.append(start_management_console(locals(), host="localhost", port=management_port)) await safe_gather(*tasks) except Exception as e: # In case of quick start failure, start the bot normally to allow further configuration logging.getLogger().warning(f"Bot config incomplete: {str(e)}. Starting normally...") await normal_start() if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(quick_start())
[ "hummingbot.client.config.config_helpers.write_config_to_yml", "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.core.utils.wallet_setup.unlock_wallet", "hummingbot.client.config.config_helpers.read_configs_from_yml", "hummingbot.check_dev_mode", "hummingbot.client.config.in_memory_config_map.i...
[((2394, 2429), 'hummingbot.init_logging', 'init_logging', (['"""hummingbot_logs.yml"""'], {}), "('hummingbot_logs.yml')\n", (2406, 2429), False, 'from hummingbot import check_dev_mode, init_logging\n'), ((2438, 2461), 'hummingbot.client.config.config_helpers.read_configs_from_yml', 'read_configs_from_yml', ([], {}), '()\n', (2459, 2461), False, 'from hummingbot.client.config.config_helpers import create_yml_files, load_required_configs, read_configs_from_yml\n'), ((2475, 2515), 'hummingbot.client.hummingbot_application.HummingbotApplication.main_application', 'HummingbotApplication.main_application', ([], {}), '()\n', (2513, 2515), False, 'from hummingbot.client.hummingbot_application import HummingbotApplication\n'), ((2367, 2385), 'hummingbot.client.config.config_helpers.create_yml_files', 'create_yml_files', ([], {}), '()\n', (2383, 2385), False, 'from hummingbot.client.config.config_helpers import create_yml_files, load_required_configs, read_configs_from_yml\n'), ((2525, 2561), 'hummingbot.client.config.in_memory_config_map.in_memory_config_map.get', 'in_memory_config_map.get', (['"""password"""'], {}), "('password')\n", (2549, 2561), False, 'from hummingbot.client.config.in_memory_config_map import in_memory_config_map\n'), ((2587, 2623), 'hummingbot.client.config.in_memory_config_map.in_memory_config_map.get', 'in_memory_config_map.get', (['"""strategy"""'], {}), "('strategy')\n", (2611, 2623), False, 'from hummingbot.client.config.in_memory_config_map import in_memory_config_map\n'), ((2713, 2759), 'hummingbot.client.config.in_memory_config_map.in_memory_config_map.get', 'in_memory_config_map.get', (['"""strategy_file_path"""'], {}), "('strategy_file_path')\n", (2737, 2759), False, 'from hummingbot.client.config.in_memory_config_map import in_memory_config_map\n'), ((2990, 3034), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""kill_switch_enabled"""'], {}), "('kill_switch_enabled')\n", (3011, 3034), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((3221, 3272), 'hummingbot.core.utils.wallet_setup.unlock_wallet', 'unlock_wallet', ([], {'public_key': 'wallet', 'password': 'password'}), '(public_key=wallet, password=password)\n', (3234, 3272), False, 'from hummingbot.core.utils.wallet_setup import unlock_wallet\n'), ((3334, 3357), 'hummingbot.client.config.config_helpers.load_required_configs', 'load_required_configs', ([], {}), '()\n', (3355, 3357), False, 'from hummingbot.client.config.config_helpers import create_yml_files, load_required_configs, read_configs_from_yml\n'), ((3651, 3691), 'hummingbot.client.ui.stdout_redirection.patch_stdout', 'patch_stdout', ([], {'log_field': 'hb.app.log_field'}), '(log_field=hb.app.log_field)\n', (3663, 3691), False, 'from hummingbot.client.ui.stdout_redirection import patch_stdout\n'), ((3716, 3732), 'hummingbot.check_dev_mode', 'check_dev_mode', ([], {}), '()\n', (3730, 3732), False, 'from hummingbot import check_dev_mode, init_logging\n'), ((3930, 4056), 'hummingbot.init_logging', 'init_logging', (['"""hummingbot_logs.yml"""'], {'override_log_level': 'log_level', 'dev_mode': 'dev_mode', 'strategy_file_path': 'config_file_name'}), "('hummingbot_logs.yml', override_log_level=log_level, dev_mode=\n dev_mode, strategy_file_path=config_file_name)\n", (3942, 4056), False, 'from hummingbot import check_dev_mode, init_logging\n'), ((4799, 4823), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (4821, 4823), False, 'import asyncio\n'), ((2649, 2685), 'hummingbot.client.config.in_memory_config_map.in_memory_config_map.get', 'in_memory_config_map.get', (['"""strategy"""'], {}), "('strategy')\n", (2673, 2685), False, 'from hummingbot.client.config.in_memory_config_map import in_memory_config_map\n'), ((2793, 2839), 'hummingbot.client.config.in_memory_config_map.in_memory_config_map.get', 'in_memory_config_map.get', (['"""strategy_file_path"""'], {}), "('strategy_file_path')\n", (2817, 2839), False, 'from hummingbot.client.config.in_memory_config_map import in_memory_config_map\n'), ((3048, 3092), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""kill_switch_enabled"""'], {}), "('kill_switch_enabled')\n", (3069, 3092), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((3152, 3183), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""wallet"""'], {}), "('wallet')\n", (3173, 3183), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((3877, 3911), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""log_level"""'], {}), "('log_level')\n", (3898, 3911), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((4145, 4166), 'hummingbot.client.config.config_helpers.write_config_to_yml', 'write_config_to_yml', ([], {}), '()\n', (4164, 4166), False, 'from hummingbot.client.config.config_helpers import write_config_to_yml\n'), ((4263, 4301), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""debug_console"""'], {}), "('debug_console')\n", (4284, 4301), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((4348, 4375), 'bin.hummingbot.detect_available_port', 'detect_available_port', (['(8211)'], {}), '(8211)\n', (4369, 4375), False, 'from bin.hummingbot import detect_available_port, main as normal_start\n'), ((4499, 4518), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*tasks'], {}), '(*tasks)\n', (4510, 4518), False, 'from hummingbot.core.utils.async_utils import safe_gather\n'), ((4751, 4765), 'bin.hummingbot.main', 'normal_start', ([], {}), '()\n', (4763, 4765), True, 'from bin.hummingbot import detect_available_port, main as normal_start\n'), ((4651, 4670), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (4668, 4670), False, 'import logging\n')]
import asyncio import time from decimal import Decimal from typing import List, Dict import unittest from hummingbot.client.performance_analysis import calculate_asset_delta_from_trades, calculate_trade_performance from hummingbot.core.event.events import TradeFee, OrderType from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from hummingbot.connector.exchange_base import ExchangeBase from hummingbot.model.sql_connection_manager import SQLConnectionManager, SQLConnectionType from hummingbot.model.trade_fill import TradeFill from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple class MockMarket1(ExchangeBase): def __init__(self): super().__init__() self.mock_mid_price: Dict[str, float] = { "WETHDAI": 115.0 } @property def display_name(self): return "coinalpha" def get_mid_price(self, trading_pair: str) -> Decimal: return Decimal(repr(self.mock_mid_price[trading_pair])) class MockMarket2(ExchangeBase): def __init__(self): super().__init__() self.mock_mid_price: Dict[str, float] = { "WETHDAI": 110.0 } @property def display_name(self): return "coinalpha2" def get_mid_price(self, trading_pair: str) -> Decimal: return Decimal(repr(self.mock_mid_price[trading_pair])) class TestTradePerformanceAnalysis(unittest.TestCase): @staticmethod async def run_parallel_async(*tasks): future: asyncio.Future = safe_ensure_future(safe_gather(*tasks)) while not future.done(): await asyncio.sleep(1.0) return future.result() def run_parallel(self, *tasks): return self.ev_loop.run_until_complete(self.run_parallel_async(*tasks)) @classmethod def setUpClass(cls): cls.maxDiff = None cls.trade_fill_sql = SQLConnectionManager(SQLConnectionType.TRADE_FILLS, db_path="") cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() cls._weth_price = 1.0 cls._eth_price = 1.0 cls._dai_price = 0.95 cls._usdc_price = 1.05 cls.trading_pair_tuple_1 = MarketTradingPairTuple(MockMarket1(), "WETHDAI", "WETH", "DAI") cls.trading_pair_tuple_2 = MarketTradingPairTuple(MockMarket2(), "WETHDAI", "WETH", "DAI") cls.strategy_1 = "strategy_1" def setUp(self): for table in [TradeFill.__table__]: self.trade_fill_sql.get_shared_session().execute(table.delete()) def create_trade_fill_records(self, trade_price_amount_list, market_trading_pair_tuple: MarketTradingPairTuple, order_type, start_time, strategy): for i, trade_data in enumerate(trade_price_amount_list): yield { "config_file_path": "path", "strategy": strategy, "market": market_trading_pair_tuple.market.display_name, "symbol": market_trading_pair_tuple.trading_pair, "base_asset": market_trading_pair_tuple.base_asset, "quote_asset": market_trading_pair_tuple.quote_asset, "timestamp": start_time + i + 1, "order_id": f"{i}_{market_trading_pair_tuple.trading_pair}", "trade_type": trade_data[0], "order_type": order_type, "price": float(trade_data[1]), "amount": float(trade_data[2]), "trade_fee": TradeFee.to_json(TradeFee(0.01)), "exchange_trade_id": f"{i}_{market_trading_pair_tuple.trading_pair}" } def save_trade_fill_records(self, trade_price_amount_list, market_trading_pair_tuple: MarketTradingPairTuple, order_type, start_time, strategy): trade_records: List[TradeFill] = [] for trade in self.create_trade_fill_records(trade_price_amount_list, market_trading_pair_tuple, order_type, start_time, strategy): trade_records.append(TradeFill(**trade)) self.trade_fill_sql.get_shared_session().add_all(trade_records) def get_trades_from_session(self, start_timestamp: int) -> List[TradeFill]: session = self.trade_fill_sql.get_shared_session() query = (session .query(TradeFill) .filter(TradeFill.timestamp >= start_timestamp) .order_by(TradeFill.timestamp.desc())) result: List[TradeFill] = query.all() or [] result.reverse() return result def test_calculate_trade_quote_delta_with_fees(self): test_trades = [ ("BUY", 100, 1), ("SELL", 100, 0.9), ("BUY", 110, 1), ("SELL", 115, 1) ] start_time = int(time.time() * 1e3) - 100000 self.save_trade_fill_records(test_trades, self.trading_pair_tuple_1, OrderType.MARKET.name, start_time, self.strategy_1) raw_queried_trades = self.get_trades_from_session(start_time) m_name = self.trading_pair_tuple_1.market.name starting_balances = {"DAI": {m_name: Decimal("1000")}, "WETH": {m_name: Decimal("5")}} trade_performance_stats, market_trading_pair_stats = calculate_trade_performance( self.strategy_1, [self.trading_pair_tuple_1], raw_queried_trades, starting_balances ) expected_trade_performance_stats = { 'portfolio_acquired_quote_value': Decimal('430.6500'), 'portfolio_spent_quote_value': Decimal('428.50'), 'portfolio_delta': Decimal('2.1500'), 'portfolio_delta_percentage': Decimal('0.1365079365079365079365079365')} expected_market_trading_pair_stats = { 'starting_quote_rate': Decimal('100.0'), 'asset': { 'WETH': {'spent': Decimal('1.9'), 'acquired': Decimal('1.980'), 'delta': Decimal('0.080'), 'delta_percentage': Decimal('4.210526315789473684210526300')}, 'DAI': {'spent': Decimal('210.00'), 'acquired': Decimal('202.9500'), 'delta': Decimal('-7.0500'), 'delta_percentage': Decimal('-3.357142857142857142857142860')}}, 'trade_count': 4, 'end_quote_rate': Decimal('115.0'), 'acquired_quote_value': Decimal('430.6500'), 'spent_quote_value': Decimal('428.50'), 'starting_quote_value': Decimal('1575.0'), 'trading_pair_delta': Decimal('2.1500'), 'trading_pair_delta_percentage': Decimal('0.1365079365079365079365079365')} self.assertDictEqual(trade_performance_stats, expected_trade_performance_stats) self.assertDictEqual(expected_market_trading_pair_stats, market_trading_pair_stats[self.trading_pair_tuple_1]) def test_calculate_asset_delta_from_trades(self): test_trades = [ ("BUY", 1, 100), ("SELL", 0.9, 110), ("BUY", 0.1, 100), ("SELL", 1, 120) ] start_time = int(time.time() * 1e3) - 100000 self.save_trade_fill_records(test_trades, self.trading_pair_tuple_1, OrderType.MARKET.name, start_time, self.strategy_1 ) raw_queried_trades = self.get_trades_from_session(start_time) market_trading_pair_stats = calculate_asset_delta_from_trades( self.strategy_1, [self.trading_pair_tuple_1], raw_queried_trades ) expected_stats = { 'starting_quote_rate': Decimal('1.0'), 'asset': {'WETH': {'spent': Decimal('230.0'), 'acquired': Decimal('198.000')}, 'DAI': {'spent': Decimal('110.00'), 'acquired': Decimal('216.8100')}}, 'trade_count': 4 } self.assertDictEqual(expected_stats, market_trading_pair_stats[self.trading_pair_tuple_1]) def test_calculate_trade_performance(self): test_trades = [ ("BUY", 100, 2), ("SELL", 110, 0.9), ("BUY", 105, 0.5), ("SELL", 120, 1) ] start_time = int(time.time() * 1e3) - 100000 self.save_trade_fill_records(test_trades, self.trading_pair_tuple_1, OrderType.MARKET.name, start_time, self.strategy_1 ) raw_queried_trades = self.get_trades_from_session(start_time) m_name = self.trading_pair_tuple_1.market.name starting_balances = {"DAI": {m_name: Decimal("1000")}, "WETH": {m_name: Decimal("5")}} trade_performance_stats, market_trading_pair_stats = calculate_trade_performance( self.strategy_1, [self.trading_pair_tuple_1], raw_queried_trades, starting_balances ) expected_trade_performance_stats = { 'portfolio_acquired_quote_value': Decimal('501.4350'), 'portfolio_spent_quote_value': Decimal('471.00'), 'portfolio_delta': Decimal('30.4350'), 'portfolio_delta_percentage': Decimal('1.932380952380952380952380952') } expected_market_trading_pair_stats = { 'starting_quote_rate': Decimal('100.0'), 'asset': { 'WETH': {'spent': Decimal('1.9'), 'acquired': Decimal('2.475'), 'delta': Decimal('0.575'), 'delta_percentage': Decimal('30.26315789473684210526315790')}, 'DAI': {'spent': Decimal('252.50'), 'acquired': Decimal('216.8100'), 'delta': Decimal('-35.6900'), 'delta_percentage': Decimal( '-14.13465346534653465346534653')}}, 'trade_count': 4, 'end_quote_rate': Decimal('115.0'), 'acquired_quote_value': Decimal('501.4350'), 'spent_quote_value': Decimal('471.00'), 'starting_quote_value': Decimal('1575.0'), 'trading_pair_delta': Decimal('30.4350'), 'trading_pair_delta_percentage': Decimal('1.932380952380952380952380952') } self.assertDictEqual(expected_trade_performance_stats, trade_performance_stats) self.assertDictEqual(expected_market_trading_pair_stats, market_trading_pair_stats[self.trading_pair_tuple_1]) def test_multiple_market(self): test_trades_1 = [ ("BUY", 100, 1), ("SELL", 100, 0.9), ("BUY", 110, 1), ("SELL", 115, 1) ] start_time = int(time.time() * 1e3) - 100000 self.save_trade_fill_records(test_trades_1, self.trading_pair_tuple_1, OrderType.MARKET.name, start_time, self.strategy_1 ) test_trades_2 = [ ("BUY", 100, 2), ("SELL", 110, 0.9), ("BUY", 105, 0.5), ("SELL", 120, 1) ] self.save_trade_fill_records(test_trades_2, self.trading_pair_tuple_2, OrderType.MARKET.name, start_time, self.strategy_1 ) raw_queried_trades = self.get_trades_from_session(start_time) m_name_1 = self.trading_pair_tuple_1.market.name m_name_2 = self.trading_pair_tuple_2.market.name starting_balances = {"DAI": {m_name_1: Decimal("1000"), m_name_2: Decimal("500")}, "WETH": {m_name_1: Decimal("5"), m_name_2: Decimal("1")}} trade_performance_stats, market_trading_pair_stats = calculate_trade_performance( self.strategy_1, [self.trading_pair_tuple_1, self.trading_pair_tuple_2], raw_queried_trades, starting_balances ) expected_trade_performance_stats = { 'portfolio_acquired_quote_value': Decimal('919.7100'), 'portfolio_spent_quote_value': Decimal('890.00'), 'portfolio_delta': Decimal('29.7100'), 'portfolio_delta_percentage': Decimal('1.359725400457665903890160183') } expected_markettrading_pair_stats_1 = { 'starting_quote_rate': Decimal('100.0'), 'asset': { 'WETH': {'spent': Decimal('1.9'), 'acquired': Decimal('1.980'), 'delta': Decimal('0.080'), 'delta_percentage': Decimal('4.210526315789473684210526300')}, 'DAI': {'spent': Decimal('210.00'), 'acquired': Decimal('202.9500'), 'delta': Decimal('-7.0500'), 'delta_percentage': Decimal( '-3.357142857142857142857142860')} }, 'trade_count': 4, 'end_quote_rate': Decimal('115.0'), 'acquired_quote_value': Decimal('430.6500'), 'spent_quote_value': Decimal('428.50'), 'starting_quote_value': Decimal('1575.0'), 'trading_pair_delta': Decimal('2.1500'), 'trading_pair_delta_percentage': Decimal('0.1365079365079365079365079365') } expected_markettrading_pair_stats_2 = { 'starting_quote_rate': Decimal('100.0'), 'asset': { 'WETH': {'spent': Decimal('1.9'), 'acquired': Decimal('2.475'), 'delta': Decimal('0.575'), 'delta_percentage': Decimal('30.26315789473684210526315790')}, 'DAI': {'spent': Decimal('252.50'), 'acquired': Decimal('216.8100'), 'delta': Decimal('-35.6900'), 'delta_percentage': Decimal('-14.13465346534653465346534653')}}, 'trade_count': 4, 'end_quote_rate': Decimal('110.0'), 'acquired_quote_value': Decimal('489.0600'), 'spent_quote_value': Decimal('461.50'), 'starting_quote_value': Decimal('610.0'), 'trading_pair_delta': Decimal('27.5600'), 'trading_pair_delta_percentage': Decimal('4.518032786885245901639344262') } self.assertDictEqual(expected_trade_performance_stats, trade_performance_stats) self.assertDictEqual(expected_markettrading_pair_stats_1, market_trading_pair_stats[self.trading_pair_tuple_1]) self.assertDictEqual(expected_markettrading_pair_stats_2, market_trading_pair_stats[self.trading_pair_tuple_2])
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.model.trade_fill.TradeFill.timestamp.desc", "hummingbot.core.event.events.TradeFee", "hummingbot.model.trade_fill.TradeFill", "hummingbot.client.performance_analysis.calculate_asset_delta_from_trades", "hummingbot.model.sql_connection_manager.SQ...
[((1896, 1959), 'hummingbot.model.sql_connection_manager.SQLConnectionManager', 'SQLConnectionManager', (['SQLConnectionType.TRADE_FILLS'], {'db_path': '""""""'}), "(SQLConnectionType.TRADE_FILLS, db_path='')\n", (1916, 1959), False, 'from hummingbot.model.sql_connection_manager import SQLConnectionManager, SQLConnectionType\n'), ((2005, 2029), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2027, 2029), False, 'import asyncio\n'), ((5679, 5795), 'hummingbot.client.performance_analysis.calculate_trade_performance', 'calculate_trade_performance', (['self.strategy_1', '[self.trading_pair_tuple_1]', 'raw_queried_trades', 'starting_balances'], {}), '(self.strategy_1, [self.trading_pair_tuple_1],\n raw_queried_trades, starting_balances)\n', (5706, 5795), False, 'from hummingbot.client.performance_analysis import calculate_asset_delta_from_trades, calculate_trade_performance\n'), ((7946, 8050), 'hummingbot.client.performance_analysis.calculate_asset_delta_from_trades', 'calculate_asset_delta_from_trades', (['self.strategy_1', '[self.trading_pair_tuple_1]', 'raw_queried_trades'], {}), '(self.strategy_1, [self.\n trading_pair_tuple_1], raw_queried_trades)\n', (7979, 8050), False, 'from hummingbot.client.performance_analysis import calculate_asset_delta_from_trades, calculate_trade_performance\n'), ((9322, 9438), 'hummingbot.client.performance_analysis.calculate_trade_performance', 'calculate_trade_performance', (['self.strategy_1', '[self.trading_pair_tuple_1]', 'raw_queried_trades', 'starting_balances'], {}), '(self.strategy_1, [self.trading_pair_tuple_1],\n raw_queried_trades, starting_balances)\n', (9349, 9438), False, 'from hummingbot.client.performance_analysis import calculate_asset_delta_from_trades, calculate_trade_performance\n'), ((12386, 12529), 'hummingbot.client.performance_analysis.calculate_trade_performance', 'calculate_trade_performance', (['self.strategy_1', '[self.trading_pair_tuple_1, self.trading_pair_tuple_2]', 'raw_queried_trades', 'starting_balances'], {}), '(self.strategy_1, [self.trading_pair_tuple_1,\n self.trading_pair_tuple_2], raw_queried_trades, starting_balances)\n', (12413, 12529), False, 'from hummingbot.client.performance_analysis import calculate_asset_delta_from_trades, calculate_trade_performance\n'), ((1558, 1577), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*tasks'], {}), '(*tasks)\n', (1569, 1577), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((4727, 4753), 'hummingbot.model.trade_fill.TradeFill.timestamp.desc', 'TradeFill.timestamp.desc', ([], {}), '()\n', (4751, 4753), False, 'from hummingbot.model.trade_fill import TradeFill\n'), ((5906, 5925), 'decimal.Decimal', 'Decimal', (['"""430.6500"""'], {}), "('430.6500')\n", (5913, 5925), False, 'from decimal import Decimal\n'), ((5970, 5987), 'decimal.Decimal', 'Decimal', (['"""428.50"""'], {}), "('428.50')\n", (5977, 5987), False, 'from decimal import Decimal\n'), ((6020, 6037), 'decimal.Decimal', 'Decimal', (['"""2.1500"""'], {}), "('2.1500')\n", (6027, 6037), False, 'from decimal import Decimal\n'), ((6081, 6122), 'decimal.Decimal', 'Decimal', (['"""0.1365079365079365079365079365"""'], {}), "('0.1365079365079365079365079365')\n", (6088, 6122), False, 'from decimal import Decimal\n'), ((6207, 6223), 'decimal.Decimal', 'Decimal', (['"""100.0"""'], {}), "('100.0')\n", (6214, 6223), False, 'from decimal import Decimal\n'), ((6755, 6771), 'decimal.Decimal', 'Decimal', (['"""115.0"""'], {}), "('115.0')\n", (6762, 6771), False, 'from decimal import Decimal\n'), ((6797, 6816), 'decimal.Decimal', 'Decimal', (['"""430.6500"""'], {}), "('430.6500')\n", (6804, 6816), False, 'from decimal import Decimal\n'), ((6851, 6868), 'decimal.Decimal', 'Decimal', (['"""428.50"""'], {}), "('428.50')\n", (6858, 6868), False, 'from decimal import Decimal\n'), ((6894, 6911), 'decimal.Decimal', 'Decimal', (['"""1575.0"""'], {}), "('1575.0')\n", (6901, 6911), False, 'from decimal import Decimal\n'), ((6947, 6964), 'decimal.Decimal', 'Decimal', (['"""2.1500"""'], {}), "('2.1500')\n", (6954, 6964), False, 'from decimal import Decimal\n'), ((7011, 7052), 'decimal.Decimal', 'Decimal', (['"""0.1365079365079365079365079365"""'], {}), "('0.1365079365079365079365079365')\n", (7018, 7052), False, 'from decimal import Decimal\n'), ((8131, 8145), 'decimal.Decimal', 'Decimal', (['"""1.0"""'], {}), "('1.0')\n", (8138, 8145), False, 'from decimal import Decimal\n'), ((9549, 9568), 'decimal.Decimal', 'Decimal', (['"""501.4350"""'], {}), "('501.4350')\n", (9556, 9568), False, 'from decimal import Decimal\n'), ((9613, 9630), 'decimal.Decimal', 'Decimal', (['"""471.00"""'], {}), "('471.00')\n", (9620, 9630), False, 'from decimal import Decimal\n'), ((9663, 9681), 'decimal.Decimal', 'Decimal', (['"""30.4350"""'], {}), "('30.4350')\n", (9670, 9681), False, 'from decimal import Decimal\n'), ((9725, 9765), 'decimal.Decimal', 'Decimal', (['"""1.932380952380952380952380952"""'], {}), "('1.932380952380952380952380952')\n", (9732, 9765), False, 'from decimal import Decimal\n'), ((9858, 9874), 'decimal.Decimal', 'Decimal', (['"""100.0"""'], {}), "('100.0')\n", (9865, 9874), False, 'from decimal import Decimal\n'), ((10387, 10403), 'decimal.Decimal', 'Decimal', (['"""115.0"""'], {}), "('115.0')\n", (10394, 10403), False, 'from decimal import Decimal\n'), ((10441, 10460), 'decimal.Decimal', 'Decimal', (['"""501.4350"""'], {}), "('501.4350')\n", (10448, 10460), False, 'from decimal import Decimal\n'), ((10495, 10512), 'decimal.Decimal', 'Decimal', (['"""471.00"""'], {}), "('471.00')\n", (10502, 10512), False, 'from decimal import Decimal\n'), ((10550, 10567), 'decimal.Decimal', 'Decimal', (['"""1575.0"""'], {}), "('1575.0')\n", (10557, 10567), False, 'from decimal import Decimal\n'), ((10603, 10621), 'decimal.Decimal', 'Decimal', (['"""30.4350"""'], {}), "('30.4350')\n", (10610, 10621), False, 'from decimal import Decimal\n'), ((10668, 10708), 'decimal.Decimal', 'Decimal', (['"""1.932380952380952380952380952"""'], {}), "('1.932380952380952380952380952')\n", (10675, 10708), False, 'from decimal import Decimal\n'), ((12652, 12671), 'decimal.Decimal', 'Decimal', (['"""919.7100"""'], {}), "('919.7100')\n", (12659, 12671), False, 'from decimal import Decimal\n'), ((12716, 12733), 'decimal.Decimal', 'Decimal', (['"""890.00"""'], {}), "('890.00')\n", (12723, 12733), False, 'from decimal import Decimal\n'), ((12766, 12784), 'decimal.Decimal', 'Decimal', (['"""29.7100"""'], {}), "('29.7100')\n", (12773, 12784), False, 'from decimal import Decimal\n'), ((12828, 12868), 'decimal.Decimal', 'Decimal', (['"""1.359725400457665903890160183"""'], {}), "('1.359725400457665903890160183')\n", (12835, 12868), False, 'from decimal import Decimal\n'), ((12962, 12978), 'decimal.Decimal', 'Decimal', (['"""100.0"""'], {}), "('100.0')\n", (12969, 12978), False, 'from decimal import Decimal\n'), ((13503, 13519), 'decimal.Decimal', 'Decimal', (['"""115.0"""'], {}), "('115.0')\n", (13510, 13519), False, 'from decimal import Decimal\n'), ((13557, 13576), 'decimal.Decimal', 'Decimal', (['"""430.6500"""'], {}), "('430.6500')\n", (13564, 13576), False, 'from decimal import Decimal\n'), ((13611, 13628), 'decimal.Decimal', 'Decimal', (['"""428.50"""'], {}), "('428.50')\n", (13618, 13628), False, 'from decimal import Decimal\n'), ((13666, 13683), 'decimal.Decimal', 'Decimal', (['"""1575.0"""'], {}), "('1575.0')\n", (13673, 13683), False, 'from decimal import Decimal\n'), ((13719, 13736), 'decimal.Decimal', 'Decimal', (['"""2.1500"""'], {}), "('2.1500')\n", (13726, 13736), False, 'from decimal import Decimal\n'), ((13783, 13824), 'decimal.Decimal', 'Decimal', (['"""0.1365079365079365079365079365"""'], {}), "('0.1365079365079365079365079365')\n", (13790, 13824), False, 'from decimal import Decimal\n'), ((13918, 13934), 'decimal.Decimal', 'Decimal', (['"""100.0"""'], {}), "('100.0')\n", (13925, 13934), False, 'from decimal import Decimal\n'), ((14418, 14434), 'decimal.Decimal', 'Decimal', (['"""110.0"""'], {}), "('110.0')\n", (14425, 14434), False, 'from decimal import Decimal\n'), ((14472, 14491), 'decimal.Decimal', 'Decimal', (['"""489.0600"""'], {}), "('489.0600')\n", (14479, 14491), False, 'from decimal import Decimal\n'), ((14526, 14543), 'decimal.Decimal', 'Decimal', (['"""461.50"""'], {}), "('461.50')\n", (14533, 14543), False, 'from decimal import Decimal\n'), ((14581, 14597), 'decimal.Decimal', 'Decimal', (['"""610.0"""'], {}), "('610.0')\n", (14588, 14597), False, 'from decimal import Decimal\n'), ((14633, 14651), 'decimal.Decimal', 'Decimal', (['"""27.5600"""'], {}), "('27.5600')\n", (14640, 14651), False, 'from decimal import Decimal\n'), ((14698, 14738), 'decimal.Decimal', 'Decimal', (['"""4.518032786885245901639344262"""'], {}), "('4.518032786885245901639344262')\n", (14705, 14738), False, 'from decimal import Decimal\n'), ((1630, 1648), 'asyncio.sleep', 'asyncio.sleep', (['(1.0)'], {}), '(1.0)\n', (1643, 1648), False, 'import asyncio\n'), ((4343, 4361), 'hummingbot.model.trade_fill.TradeFill', 'TradeFill', ([], {}), '(**trade)\n', (4352, 4361), False, 'from hummingbot.model.trade_fill import TradeFill\n'), ((5568, 5583), 'decimal.Decimal', 'Decimal', (['"""1000"""'], {}), "('1000')\n", (5575, 5583), False, 'from decimal import Decimal\n'), ((5603, 5615), 'decimal.Decimal', 'Decimal', (['"""5"""'], {}), "('5')\n", (5610, 5615), False, 'from decimal import Decimal\n'), ((9211, 9226), 'decimal.Decimal', 'Decimal', (['"""1000"""'], {}), "('1000')\n", (9218, 9226), False, 'from decimal import Decimal\n'), ((9246, 9258), 'decimal.Decimal', 'Decimal', (['"""5"""'], {}), "('5')\n", (9253, 9258), False, 'from decimal import Decimal\n'), ((12194, 12209), 'decimal.Decimal', 'Decimal', (['"""1000"""'], {}), "('1000')\n", (12201, 12209), False, 'from decimal import Decimal\n'), ((12221, 12235), 'decimal.Decimal', 'Decimal', (['"""500"""'], {}), "('500')\n", (12228, 12235), False, 'from decimal import Decimal\n'), ((12286, 12298), 'decimal.Decimal', 'Decimal', (['"""5"""'], {}), "('5')\n", (12293, 12298), False, 'from decimal import Decimal\n'), ((12310, 12322), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (12317, 12322), False, 'from decimal import Decimal\n'), ((5092, 5103), 'time.time', 'time.time', ([], {}), '()\n', (5101, 5103), False, 'import time\n'), ((6282, 6296), 'decimal.Decimal', 'Decimal', (['"""1.9"""'], {}), "('1.9')\n", (6289, 6296), False, 'from decimal import Decimal\n'), ((6310, 6326), 'decimal.Decimal', 'Decimal', (['"""1.980"""'], {}), "('1.980')\n", (6317, 6326), False, 'from decimal import Decimal\n'), ((6362, 6378), 'decimal.Decimal', 'Decimal', (['"""0.080"""'], {}), "('0.080')\n", (6369, 6378), False, 'from decimal import Decimal\n'), ((6425, 6465), 'decimal.Decimal', 'Decimal', (['"""4.210526315789473684210526300"""'], {}), "('4.210526315789473684210526300')\n", (6432, 6465), False, 'from decimal import Decimal\n'), ((6501, 6518), 'decimal.Decimal', 'Decimal', (['"""210.00"""'], {}), "('210.00')\n", (6508, 6518), False, 'from decimal import Decimal\n'), ((6532, 6551), 'decimal.Decimal', 'Decimal', (['"""202.9500"""'], {}), "('202.9500')\n", (6539, 6551), False, 'from decimal import Decimal\n'), ((6586, 6604), 'decimal.Decimal', 'Decimal', (['"""-7.0500"""'], {}), "('-7.0500')\n", (6593, 6604), False, 'from decimal import Decimal\n'), ((6650, 6691), 'decimal.Decimal', 'Decimal', (['"""-3.357142857142857142857142860"""'], {}), "('-3.357142857142857142857142860')\n", (6657, 6691), False, 'from decimal import Decimal\n'), ((7497, 7508), 'time.time', 'time.time', ([], {}), '()\n', (7506, 7508), False, 'import time\n'), ((8187, 8203), 'decimal.Decimal', 'Decimal', (['"""230.0"""'], {}), "('230.0')\n", (8194, 8203), False, 'from decimal import Decimal\n'), ((8217, 8235), 'decimal.Decimal', 'Decimal', (['"""198.000"""'], {}), "('198.000')\n", (8224, 8235), False, 'from decimal import Decimal\n'), ((8277, 8294), 'decimal.Decimal', 'Decimal', (['"""110.00"""'], {}), "('110.00')\n", (8284, 8294), False, 'from decimal import Decimal\n'), ((8308, 8327), 'decimal.Decimal', 'Decimal', (['"""216.8100"""'], {}), "('216.8100')\n", (8315, 8327), False, 'from decimal import Decimal\n'), ((8698, 8709), 'time.time', 'time.time', ([], {}), '()\n', (8707, 8709), False, 'import time\n'), ((9933, 9947), 'decimal.Decimal', 'Decimal', (['"""1.9"""'], {}), "('1.9')\n", (9940, 9947), False, 'from decimal import Decimal\n'), ((9961, 9977), 'decimal.Decimal', 'Decimal', (['"""2.475"""'], {}), "('2.475')\n", (9968, 9977), False, 'from decimal import Decimal\n'), ((9988, 10004), 'decimal.Decimal', 'Decimal', (['"""0.575"""'], {}), "('0.575')\n", (9995, 10004), False, 'from decimal import Decimal\n'), ((10051, 10091), 'decimal.Decimal', 'Decimal', (['"""30.26315789473684210526315790"""'], {}), "('30.26315789473684210526315790')\n", (10058, 10091), False, 'from decimal import Decimal\n'), ((10127, 10144), 'decimal.Decimal', 'Decimal', (['"""252.50"""'], {}), "('252.50')\n", (10134, 10144), False, 'from decimal import Decimal\n'), ((10158, 10177), 'decimal.Decimal', 'Decimal', (['"""216.8100"""'], {}), "('216.8100')\n", (10165, 10177), False, 'from decimal import Decimal\n'), ((10188, 10207), 'decimal.Decimal', 'Decimal', (['"""-35.6900"""'], {}), "('-35.6900')\n", (10195, 10207), False, 'from decimal import Decimal\n'), ((10253, 10294), 'decimal.Decimal', 'Decimal', (['"""-14.13465346534653465346534653"""'], {}), "('-14.13465346534653465346534653')\n", (10260, 10294), False, 'from decimal import Decimal\n'), ((11143, 11154), 'time.time', 'time.time', ([], {}), '()\n', (11152, 11154), False, 'import time\n'), ((13037, 13051), 'decimal.Decimal', 'Decimal', (['"""1.9"""'], {}), "('1.9')\n", (13044, 13051), False, 'from decimal import Decimal\n'), ((13065, 13081), 'decimal.Decimal', 'Decimal', (['"""1.980"""'], {}), "('1.980')\n", (13072, 13081), False, 'from decimal import Decimal\n'), ((13092, 13108), 'decimal.Decimal', 'Decimal', (['"""0.080"""'], {}), "('0.080')\n", (13099, 13108), False, 'from decimal import Decimal\n'), ((13155, 13195), 'decimal.Decimal', 'Decimal', (['"""4.210526315789473684210526300"""'], {}), "('4.210526315789473684210526300')\n", (13162, 13195), False, 'from decimal import Decimal\n'), ((13231, 13248), 'decimal.Decimal', 'Decimal', (['"""210.00"""'], {}), "('210.00')\n", (13238, 13248), False, 'from decimal import Decimal\n'), ((13262, 13281), 'decimal.Decimal', 'Decimal', (['"""202.9500"""'], {}), "('202.9500')\n", (13269, 13281), False, 'from decimal import Decimal\n'), ((13292, 13310), 'decimal.Decimal', 'Decimal', (['"""-7.0500"""'], {}), "('-7.0500')\n", (13299, 13310), False, 'from decimal import Decimal\n'), ((13356, 13397), 'decimal.Decimal', 'Decimal', (['"""-3.357142857142857142857142860"""'], {}), "('-3.357142857142857142857142860')\n", (13363, 13397), False, 'from decimal import Decimal\n'), ((13993, 14007), 'decimal.Decimal', 'Decimal', (['"""1.9"""'], {}), "('1.9')\n", (14000, 14007), False, 'from decimal import Decimal\n'), ((14021, 14037), 'decimal.Decimal', 'Decimal', (['"""2.475"""'], {}), "('2.475')\n", (14028, 14037), False, 'from decimal import Decimal\n'), ((14048, 14064), 'decimal.Decimal', 'Decimal', (['"""0.575"""'], {}), "('0.575')\n", (14055, 14064), False, 'from decimal import Decimal\n'), ((14111, 14151), 'decimal.Decimal', 'Decimal', (['"""30.26315789473684210526315790"""'], {}), "('30.26315789473684210526315790')\n", (14118, 14151), False, 'from decimal import Decimal\n'), ((14187, 14204), 'decimal.Decimal', 'Decimal', (['"""252.50"""'], {}), "('252.50')\n", (14194, 14204), False, 'from decimal import Decimal\n'), ((14218, 14237), 'decimal.Decimal', 'Decimal', (['"""216.8100"""'], {}), "('216.8100')\n", (14225, 14237), False, 'from decimal import Decimal\n'), ((14248, 14267), 'decimal.Decimal', 'Decimal', (['"""-35.6900"""'], {}), "('-35.6900')\n", (14255, 14267), False, 'from decimal import Decimal\n'), ((14313, 14354), 'decimal.Decimal', 'Decimal', (['"""-14.13465346534653465346534653"""'], {}), "('-14.13465346534653465346534653')\n", (14320, 14354), False, 'from decimal import Decimal\n'), ((3649, 3663), 'hummingbot.core.event.events.TradeFee', 'TradeFee', (['(0.01)'], {}), '(0.01)\n', (3657, 3663), False, 'from hummingbot.core.event.events import TradeFee, OrderType\n')]
import itertools from os.path import join, realpath import sys; sys.path.insert(0, realpath(join(__file__, "../../../"))) import asyncio import inspect import unittest import aiohttp import logging from typing import List from unittest.mock import patch, AsyncMock from decimal import Decimal from hummingbot.core.data_type.order_book_tracker_entry import OrderBookTrackerEntry from test.integration.assets.mock_data.fixture_idex import FixtureIdex from hummingbot.connector.exchange.idex.idex_api_order_book_data_source import IdexAPIOrderBookDataSource from hummingbot.connector.exchange.idex.idex_order_book_message import IdexOrderBookMessage from hummingbot.core.data_type.order_book_message import OrderBookMessageType from hummingbot.core.data_type.order_book import OrderBook class IdexAPIOrderBookDataSourceUnitTest(unittest.TestCase): class AsyncIterator: def __init__(self, seq): self.iter = iter(seq) def __aiter__(self): return self async def __anext__(self): try: return next(self.iter) except StopIteration: raise StopAsyncIteration eth_sample_pairs: List[str] = [ "UNI-ETH", "LBA-ETH" ] bsc_sample_pairs: List[str] = [ "EOS-USDT", "BTCB-BNB" ] RESOLVE_PATH: str = 'hummingbot.connector.exchange.idex.idex_resolve.{method}' GET_MOCK: str = 'aiohttp.ClientSession.get' PATCH_BASE_PATH = \ 'hummingbot.connector.exchange.idex.idex_api_order_book_data_source.IdexAPIOrderBookDataSource.{method}' @classmethod def setUpClass(cls) -> None: cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() cls.eth_order_book_data_source: IdexAPIOrderBookDataSource = IdexAPIOrderBookDataSource(cls.eth_sample_pairs) cls.bsc_order_book_data_source: IdexAPIOrderBookDataSource = IdexAPIOrderBookDataSource(cls.bsc_sample_pairs) def run_async(self, task): return self.ev_loop.run_until_complete(task) ''' def test_get_idex_rest_url(self): # Calls blockchain default ("eth") in global_config[blockchain] if blockchain value is None # Todo: test with user inputs and blockchain value to ensure ETH and BSC blockchain inputs work self.assertEqual("https://api-sandbox-ETH.idex.io/", IdexAPIOrderBookDataSource.get_idex_rest_url()) def test_get_idex_ws_feed(self): # Calls blockchain default ("eth") in global_config[blockchain] if blockchain value is None # Todo: test with user inputs and blockchain value to ensure ETH and BSC blockchain inputs work. self.assertEqual("wss://websocket-sandbox-ETH.idex.io/v1", IdexAPIOrderBookDataSource.get_idex_ws_feed()) ''' # Test returns: Success # Uses PropertyMock to mock the API URL. Test confirms ability to fetch all trading pairs # on both exchanges (ETH, BSC). def test_fetch_trading_pairs(self): # ETH URL trading_pairs: List[str] = self.run_async( self.eth_order_book_data_source.fetch_trading_pairs()) self.assertIn("UNI-ETH", trading_pairs) self.assertIn("LBA-ETH", trading_pairs) def test_get_last_traded_price(self): with patch(self.GET_MOCK, new_callable=AsyncMock) as mocked_get: # ETH URL for t_pair in self.eth_sample_pairs: mocked_get.return_value.json.return_value = FixtureIdex.TRADING_PAIR_TRADES last_traded_price: float = self.run_async( self.eth_order_book_data_source.get_last_traded_price(t_pair, "https://api-eth.idex.io")) self.assertEqual(0.01780000, last_traded_price) @patch(RESOLVE_PATH.format(method='get_idex_rest_url')) @patch(GET_MOCK, new_callable=AsyncMock) def test_get_last_traded_prices(self, mocked_get, mocked_api_url): # ETH URL mocked_api_url.return_value = "https://api-eth.idex.io" mocked_get.return_value.json.return_value = FixtureIdex.TRADING_PAIR_TRADES last_traded_prices: List[str] = self.run_async( self.eth_order_book_data_source.get_last_traded_prices(self.eth_sample_pairs)) self.assertEqual({"UNI-ETH": 0.01780000, "LBA-ETH": 0.01780000}, last_traded_prices) # BSC URL mocked_api_url.return_value = "https://api-bsc.idex.io" mocked_get.return_value.json.return_value = FixtureIdex.TRADING_PAIR_TRADES last_traded_prices: List[str] = self.run_async( self.bsc_order_book_data_source.get_last_traded_prices(self.bsc_sample_pairs)) self.assertEqual({"EOS-USDT": 0.01780000, "BTCB-BNB": 0.01780000}, last_traded_prices) @patch(RESOLVE_PATH.format(method='get_idex_rest_url')) @patch(GET_MOCK, new_callable=AsyncMock) def test_get_mid_price(self, mocked_get, mocked_api_url): # ETH URL mocked_api_url.return_value = "https://api-eth.idex.io" mocked_get.return_value.json.return_value = FixtureIdex.TRADING_PAIR_TICKER for t_pair in self.eth_sample_pairs: t_pair_mid_price: List[str] = self.run_async( self.eth_order_book_data_source.get_mid_price(t_pair)) self.assertEqual(Decimal("0.016175005"), t_pair_mid_price) self.assertIsInstance(t_pair_mid_price, Decimal) async def get_snapshot(self, trading_pair): async with aiohttp.ClientSession() as client: try: snapshot = await self.eth_order_book_data_source.get_snapshot(client, trading_pair) return snapshot except Exception: return None # @unittest.skip("failing aiohttp response context manager mocks") # @patch(REST_URL, new_callable=PropertyMock) # @patch(GET_MOCK, new_callable=AsyncMock) @patch(RESOLVE_PATH.format(method='get_idex_rest_url')) @patch('aiohttp.ClientResponse.json') def test_get_snapshot(self, mocked_json, mocked_api_url): # mocked_get.return_value.json.return_value = FixtureIdex.ORDER_BOOK_LEVEL2 # mocked_get.return_value.status = 200 # Mock aiohttp response f = asyncio.Future() f.set_result(FixtureIdex.ORDER_BOOK_LEVEL2) mocked_json.return_value = f mocked_api_url.return_value = "https://api-eth.idex.io" # mocked_get.return_value.__aenter__.return_value.text = AsyncMock(side_effect=["custom text"]) # mocked_get.return_value.__aexit__.return_value = AsyncMock(side_effect=lambda *args: True) # mocked_get.return_value = MockGetResponse(FixtureIdex.ORDER_BOOK_LEVEL2, 200) snapshot = self.ev_loop.run_until_complete(self.get_snapshot("UNI-ETH")) # an artifact created by the way we mock. Normally run_until_complete() returns a result directly snapshot = snapshot.result() self.assertEqual(FixtureIdex.ORDER_BOOK_LEVEL2, snapshot) @patch(RESOLVE_PATH.format(method='get_idex_rest_url')) @patch(PATCH_BASE_PATH.format(method='get_snapshot')) def test_get_new_order_book(self, mock_get_snapshot, mocked_api_url): # Mock Future() object return value as the request response # For this particular test, the return value from get_snapshot is not relevant, therefore # setting it with a random snapshot from fixture f = asyncio.Future() f.set_result(FixtureIdex.SNAPSHOT_2) mock_get_snapshot.return_value = f.result() mocked_api_url.return_value = "https://api-eth.idex.io" orderbook = self.ev_loop.run_until_complete(self.eth_order_book_data_source.get_new_order_book("UNI-ETH")) print(orderbook.snapshot[0]) # Validate the returned value is OrderBook self.assertIsInstance(orderbook, OrderBook) # Ensure the number of bids / asks provided in the snapshot are equal to the respective number of orderbook rows self.assertEqual(len(orderbook.snapshot[0].index), len(FixtureIdex.SNAPSHOT_2["bids"])) @patch(RESOLVE_PATH.format(method='get_idex_rest_url')) @patch(PATCH_BASE_PATH.format(method='get_snapshot')) def test_get_tracking_pairs(self, mock_get_snapshot, mocked_api_url): mocked_api_url.return_value = "https://api-eth.idex.io" # Mock Future() object return value as the request response # For this particular test, the return value from get_snapshot is not relevant, therefore # setting it with a random snapshot from fixture f = asyncio.Future() f.set_result(FixtureIdex.SNAPSHOT_2) mock_get_snapshot.return_value = f.result() tracking_pairs = self.ev_loop.run_until_complete(self.eth_order_book_data_source.get_tracking_pairs()) # Validate the number of tracking pairs is equal to the number of trading pairs received self.assertEqual(len(self.eth_sample_pairs), len(tracking_pairs)) # Make sure the entry key in tracking pairs matches with what's in the trading pairs for trading_pair, tracking_pair_obj in zip(self.eth_sample_pairs, list(tracking_pairs.keys())): self.assertEqual(trading_pair, tracking_pair_obj) # Validate the data type for each tracking pair value is OrderBookTrackerEntry for order_book_tracker_entry in tracking_pairs.values(): self.assertIsInstance(order_book_tracker_entry, OrderBookTrackerEntry) # Validate the order book tracker entry trading_pairs are valid for trading_pair, order_book_tracker_entry in zip(self.eth_sample_pairs, tracking_pairs.values()): self.assertEqual(order_book_tracker_entry.trading_pair, trading_pair) @patch(RESOLVE_PATH.format(method='get_idex_rest_url')) @patch(PATCH_BASE_PATH.format(method='get_snapshot')) def test_listen_for_order_book_snapshots(self, mock_get_snapshot, mock_api_url): """ test_listen_for_order_book_snapshots (test.integration.test_idex_api_order_book_data_source. IdexAPIOrderBookDataSourceUnitTest) Example order book message added to the queue: IdexOrderBookMessage( type = < OrderBookMessageType.SNAPSHOT: 1 > , content = { 'sequence': int, 'bids': [ ['181.95138', '0.69772000', 2], ... ], 'asks': [ ['182.11620', '0.32400000', 4], ... ], }, timestamp = 1573041256.2376761) """ mock_api_url.return_value = "https://api-eth.idex.io" # Instantiate empty async queue and make sure the initial size is 0 q = asyncio.Queue() self.assertEqual(q.qsize(), 0) # Mock Future() object return value as the request response # For this particular test, the return value from get_snapshot is not relevant, therefore # setting it with a random snapshot from fixture f1 = asyncio.Future() f1.set_result(FixtureIdex.SNAPSHOT_1) # Mock Future() object return value as the request response # For this particular test, the return value from get_snapshot is not relevant, therefore # setting it with a random snapshot from fixture f2 = asyncio.Future() f2.set_result(FixtureIdex.SNAPSHOT_2) mock_get_snapshot.side_effect = [f1.result(), f2.result()] # Listening for tracking pairs within the set timeout timeframe timeout = 6 print('{test_name} is going to run for {timeout} seconds, starting now'.format( test_name=inspect.stack()[0][3], timeout=timeout)) try: self.run_async( # Force exit from event loop after set timeout seconds asyncio.wait_for( self.eth_order_book_data_source.listen_for_order_book_snapshots(ev_loop=self.ev_loop, output=q), timeout=timeout ) ) except asyncio.exceptions.TimeoutError as e: print(e) # Make sure that the number of items in the queue after certain seconds make sense # For instance, when the asyncio sleep time is set to 5 seconds in the method # If we configure timeout to be the same length, only 1 item has enough time to be received self.assertGreaterEqual(q.qsize(), 1) # Validate received response has correct data types first_item = q.get_nowait() self.assertIsInstance(first_item, IdexOrderBookMessage) self.assertIsInstance(first_item.type, OrderBookMessageType) # Validate order book message type self.assertEqual(first_item.type, OrderBookMessageType.SNAPSHOT) # Validate snapshot received matches with the original snapshot received from API self.assertEqual(first_item.content['bids'], FixtureIdex.SNAPSHOT_1['bids']) self.assertEqual(first_item.content['asks'], FixtureIdex.SNAPSHOT_1['asks']) # Validate the rest of the content self.assertEqual(first_item.content['trading_pair'], self.eth_sample_pairs[0]) self.assertEqual(first_item.content['sequence'], FixtureIdex.SNAPSHOT_1['sequence']) @patch(RESOLVE_PATH.format(method='get_idex_ws_feed')) @patch(PATCH_BASE_PATH.format(method='_inner_messages')) def test_listen_for_order_book_diffs(self, mock_inner_messages, mock_ws_feed): timeout = 2 mock_ws_feed.return_value = "wss://websocket-eth.idex.io/v1" q = asyncio.Queue() # Socket events receiving in the order from top to bottom mocked_socket_responses = itertools.cycle( [ FixtureIdex.WS_PRICE_LEVEL_UPDATE_1, FixtureIdex.WS_PRICE_LEVEL_UPDATE_2, FixtureIdex.WS_SUBSCRIPTION_SUCCESS ] ) mock_inner_messages.return_value = self.AsyncIterator(seq=mocked_socket_responses) print('{test_name} is going to run for {timeout} seconds, starting now'.format( test_name=inspect.stack()[0][3], timeout=timeout)) try: self.run_async( # Force exit from event loop after set timeout seconds asyncio.wait_for( self.eth_order_book_data_source.listen_for_order_book_diffs(ev_loop=self.ev_loop, output=q), timeout=timeout ) ) except asyncio.exceptions.TimeoutError as e: print(e) first_event = q.get_nowait() second_event = q.get_nowait() recv_events = [first_event, second_event] for event in recv_events: # Validate the data inject into async queue is in Liquid order book message type self.assertIsInstance(event, IdexOrderBookMessage) # Validate the event type is equal to DIFF self.assertEqual(event.type, OrderBookMessageType.DIFF) # Validate the actual content injected is dict type self.assertIsInstance(event.content, dict) @patch(PATCH_BASE_PATH.format(method='_inner_messages')) def test_listen_for_trades(self, mock_inner_messages): timeout = 2 q = asyncio.Queue() # Socket events receiving in the order from top to bottom mocked_socket_responses = itertools.cycle( [ FixtureIdex.WS_TRADE_1, FixtureIdex.WS_TRADE_2 ] ) mock_inner_messages.return_value = self.AsyncIterator(seq=mocked_socket_responses) print('{test_name} is going to run for {timeout} seconds, starting now'.format( test_name=inspect.stack()[0][3], timeout=timeout)) try: self.run_async( # Force exit from event loop after set timeout seconds asyncio.wait_for( self.eth_order_book_data_source.listen_for_trades(ev_loop=self.ev_loop, output=q), timeout=timeout ) ) except asyncio.exceptions.TimeoutError as e: print(e) first_event = q.get_nowait() second_event = q.get_nowait() recv_events = [first_event, second_event] for event in recv_events: # Validate the data inject into async queue is in Liquid order book message type self.assertIsInstance(event, IdexOrderBookMessage) # Validate the event type is equal to DIFF self.assertEqual(event.type, OrderBookMessageType.TRADE) # Validate the actual content injected is dict type self.assertIsInstance(event.content, dict) def main(): logging.basicConfig(level=logging.INFO) unittest.main() if __name__ == "__main__": main()
[ "hummingbot.connector.exchange.idex.idex_api_order_book_data_source.IdexAPIOrderBookDataSource" ]
[((3770, 3809), 'unittest.mock.patch', 'patch', (['GET_MOCK'], {'new_callable': 'AsyncMock'}), '(GET_MOCK, new_callable=AsyncMock)\n', (3775, 3809), False, 'from unittest.mock import patch, AsyncMock\n'), ((4812, 4851), 'unittest.mock.patch', 'patch', (['GET_MOCK'], {'new_callable': 'AsyncMock'}), '(GET_MOCK, new_callable=AsyncMock)\n', (4817, 4851), False, 'from unittest.mock import patch, AsyncMock\n'), ((5930, 5966), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientResponse.json"""'], {}), "('aiohttp.ClientResponse.json')\n", (5935, 5966), False, 'from unittest.mock import patch, AsyncMock\n'), ((16760, 16799), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (16779, 16799), False, 'import logging\n'), ((16804, 16819), 'unittest.main', 'unittest.main', ([], {}), '()\n', (16817, 16819), False, 'import unittest\n'), ((92, 119), 'os.path.join', 'join', (['__file__', '"""../../../"""'], {}), "(__file__, '../../../')\n", (96, 119), False, 'from os.path import join, realpath\n'), ((1692, 1716), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1714, 1716), False, 'import asyncio\n'), ((1786, 1834), 'hummingbot.connector.exchange.idex.idex_api_order_book_data_source.IdexAPIOrderBookDataSource', 'IdexAPIOrderBookDataSource', (['cls.eth_sample_pairs'], {}), '(cls.eth_sample_pairs)\n', (1812, 1834), False, 'from hummingbot.connector.exchange.idex.idex_api_order_book_data_source import IdexAPIOrderBookDataSource\n'), ((1904, 1952), 'hummingbot.connector.exchange.idex.idex_api_order_book_data_source.IdexAPIOrderBookDataSource', 'IdexAPIOrderBookDataSource', (['cls.bsc_sample_pairs'], {}), '(cls.bsc_sample_pairs)\n', (1930, 1952), False, 'from hummingbot.connector.exchange.idex.idex_api_order_book_data_source import IdexAPIOrderBookDataSource\n'), ((6206, 6222), 'asyncio.Future', 'asyncio.Future', ([], {}), '()\n', (6220, 6222), False, 'import asyncio\n'), ((7391, 7407), 'asyncio.Future', 'asyncio.Future', ([], {}), '()\n', (7405, 7407), False, 'import asyncio\n'), ((8539, 8555), 'asyncio.Future', 'asyncio.Future', ([], {}), '()\n', (8553, 8555), False, 'import asyncio\n'), ((10725, 10740), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (10738, 10740), False, 'import asyncio\n'), ((11017, 11033), 'asyncio.Future', 'asyncio.Future', ([], {}), '()\n', (11031, 11033), False, 'import asyncio\n'), ((11317, 11333), 'asyncio.Future', 'asyncio.Future', ([], {}), '()\n', (11331, 11333), False, 'import asyncio\n'), ((13574, 13589), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (13587, 13589), False, 'import asyncio\n'), ((13692, 13825), 'itertools.cycle', 'itertools.cycle', (['[FixtureIdex.WS_PRICE_LEVEL_UPDATE_1, FixtureIdex.WS_PRICE_LEVEL_UPDATE_2,\n FixtureIdex.WS_SUBSCRIPTION_SUCCESS]'], {}), '([FixtureIdex.WS_PRICE_LEVEL_UPDATE_1, FixtureIdex.\n WS_PRICE_LEVEL_UPDATE_2, FixtureIdex.WS_SUBSCRIPTION_SUCCESS])\n', (13707, 13825), False, 'import itertools\n'), ((15279, 15294), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (15292, 15294), False, 'import asyncio\n'), ((15397, 15462), 'itertools.cycle', 'itertools.cycle', (['[FixtureIdex.WS_TRADE_1, FixtureIdex.WS_TRADE_2]'], {}), '([FixtureIdex.WS_TRADE_1, FixtureIdex.WS_TRADE_2])\n', (15412, 15462), False, 'import itertools\n'), ((3248, 3292), 'unittest.mock.patch', 'patch', (['self.GET_MOCK'], {'new_callable': 'AsyncMock'}), '(self.GET_MOCK, new_callable=AsyncMock)\n', (3253, 3292), False, 'from unittest.mock import patch, AsyncMock\n'), ((5454, 5477), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (5475, 5477), False, 'import aiohttp\n'), ((5283, 5305), 'decimal.Decimal', 'Decimal', (['"""0.016175005"""'], {}), "('0.016175005')\n", (5290, 5305), False, 'from decimal import Decimal\n'), ((11652, 11667), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (11665, 11667), False, 'import inspect\n'), ((14108, 14123), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (14121, 14123), False, 'import inspect\n'), ((15734, 15749), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (15747, 15749), False, 'import inspect\n')]
import logging import unittest from decimal import Decimal import pandas as pd from hummingbot.connector.exchange.paper_trade.paper_trade_exchange import QuantizationParams from hummingbot.core.clock import ( Clock, ClockMode ) from hummingbot.core.data_type.common import TradeType from hummingbot.core.event.event_logger import EventLogger from hummingbot.core.event.events import ( MarketEvent, OrderBookTradeEvent, ) from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from hummingbot.strategy.pure_market_making.pure_market_making import PureMarketMakingStrategy from test.mock.mock_paper_exchange import MockPaperExchange logging.basicConfig(level=logging.ERROR) class PMMRefreshToleranceUnitTest(unittest.TestCase): start: pd.Timestamp = pd.Timestamp("2019-01-01", tz="UTC") end: pd.Timestamp = pd.Timestamp("2019-01-01 01:00:00", tz="UTC") start_timestamp: float = start.timestamp() end_timestamp: float = end.timestamp() trading_pair = "HBOT-ETH" base_asset = trading_pair.split("-")[0] quote_asset = trading_pair.split("-")[1] def simulate_maker_market_trade(self, is_buy: bool, quantity: Decimal, price: Decimal): order_book = self.market.get_order_book(self.trading_pair) trade_event = OrderBookTradeEvent( self.trading_pair, self.clock.current_timestamp, TradeType.BUY if is_buy else TradeType.SELL, price, quantity ) order_book.apply_trade(trade_event) def setUp(self): self.clock_tick_size = 1 self.clock: Clock = Clock(ClockMode.BACKTEST, self.clock_tick_size, self.start_timestamp, self.end_timestamp) self.market: MockPaperExchange = MockPaperExchange() self.mid_price = 100 self.bid_spread = 0.01 self.ask_spread = 0.01 self.order_refresh_time = 30 self.market.set_balanced_order_book(trading_pair=self.trading_pair, mid_price=self.mid_price, min_price=1, max_price=200, price_step_size=1, volume_step_size=10) self.market.set_balance("HBOT", 500) self.market.set_balance("ETH", 5000) self.market.set_quantization_param( QuantizationParams( self.trading_pair, 6, 6, 6, 6 ) ) self.market_info = MarketTradingPairTuple(self.market, self.trading_pair, self.base_asset, self.quote_asset) self.clock.add_iterator(self.market) self.maker_order_fill_logger: EventLogger = EventLogger() self.cancel_order_logger: EventLogger = EventLogger() self.market.add_listener(MarketEvent.OrderFilled, self.maker_order_fill_logger) self.market.add_listener(MarketEvent.OrderCancelled, self.cancel_order_logger) def test_strategy_ping_pong_on_ask_fill(self): self.strategy = PureMarketMakingStrategy() self.strategy.init_params( self.market_info, bid_spread=Decimal("0.01"), ask_spread=Decimal("0.01"), order_amount=Decimal("1"), order_refresh_time=5, filled_order_delay=5, order_refresh_tolerance_pct=-1, ping_pong_enabled=True, ) self.clock.add_iterator(self.strategy) self.clock.backtest_til(self.start_timestamp + self.clock_tick_size) self.assertEqual(1, len(self.strategy.active_buys)) self.assertEqual(1, len(self.strategy.active_sells)) self.simulate_maker_market_trade(True, Decimal(100), Decimal("101.1")) self.clock.backtest_til( self.start_timestamp + 2 * self.clock_tick_size ) self.assertEqual(1, len(self.strategy.active_buys)) self.assertEqual(0, len(self.strategy.active_sells)) old_bid = self.strategy.active_buys[0] self.clock.backtest_til( self.start_timestamp + 7 * self.clock_tick_size ) self.assertEqual(1, len(self.strategy.active_buys)) self.assertEqual(0, len(self.strategy.active_sells)) # After new order create cycle (after filled_order_delay), check if a new order is created self.assertTrue(old_bid.client_order_id != self.strategy.active_buys[0].client_order_id) self.simulate_maker_market_trade(False, Decimal(100), Decimal("98.9")) self.clock.backtest_til( self.start_timestamp + 15 * self.clock_tick_size ) self.assertEqual(1, len(self.strategy.active_buys)) self.assertEqual(1, len(self.strategy.active_sells)) def test_strategy_ping_pong_on_bid_fill(self): self.strategy = PureMarketMakingStrategy() self.strategy.init_params( self.market_info, bid_spread=Decimal("0.01"), ask_spread=Decimal("0.01"), order_amount=Decimal("1"), order_refresh_time=5, filled_order_delay=5, order_refresh_tolerance_pct=-1, ping_pong_enabled=True, ) self.clock.add_iterator(self.strategy) self.clock.backtest_til(self.start_timestamp + self.clock_tick_size) self.assertEqual(1, len(self.strategy.active_buys)) self.assertEqual(1, len(self.strategy.active_sells)) self.simulate_maker_market_trade(False, Decimal(100), Decimal("98.9")) self.clock.backtest_til( self.start_timestamp + 2 * self.clock_tick_size ) self.assertEqual(0, len(self.strategy.active_buys)) self.assertEqual(1, len(self.strategy.active_sells)) old_ask = self.strategy.active_sells[0] self.clock.backtest_til( self.start_timestamp + 7 * self.clock_tick_size ) self.assertEqual(0, len(self.strategy.active_buys)) self.assertEqual(1, len(self.strategy.active_sells)) # After new order create cycle (after filled_order_delay), check if a new order is created self.assertTrue(old_ask.client_order_id != self.strategy.active_sells[0].client_order_id) self.simulate_maker_market_trade(True, Decimal(100), Decimal("101.1")) self.clock.backtest_til( self.start_timestamp + 15 * self.clock_tick_size ) self.assertEqual(1, len(self.strategy.active_buys)) self.assertEqual(1, len(self.strategy.active_sells)) def test_multiple_orders_ping_pong(self): self.strategy = PureMarketMakingStrategy() self.strategy.init_params( self.market_info, bid_spread=Decimal("0.01"), ask_spread=Decimal("0.01"), order_amount=Decimal("1"), order_levels=5, order_level_amount=Decimal("1"), order_level_spread=Decimal("0.01"), order_refresh_time=5, order_refresh_tolerance_pct=-1, filled_order_delay=5, ping_pong_enabled=True, ) self.clock.add_iterator(self.strategy) self.clock.backtest_til(self.start_timestamp + self.clock_tick_size) self.assertEqual(5, len(self.strategy.active_buys)) self.assertEqual(5, len(self.strategy.active_sells)) self.simulate_maker_market_trade(True, Decimal(100), Decimal("102.50")) # After market trade happens, 2 of the asks orders are filled. self.assertEqual(5, len(self.strategy.active_buys)) self.assertEqual(3, len(self.strategy.active_sells)) self.clock.backtest_til( self.start_timestamp + 2 * self.clock_tick_size ) # Not refreshing time yet, still same active orders self.assertEqual(5, len(self.strategy.active_buys)) self.assertEqual(3, len(self.strategy.active_sells)) old_bids = self.strategy.active_buys old_asks = self.strategy.active_sells self.clock.backtest_til( self.start_timestamp + 7 * self.clock_tick_size ) # After order refresh, same numbers of orders but it's a new set. self.assertEqual(5, len(self.strategy.active_buys)) self.assertEqual(3, len(self.strategy.active_sells)) self.assertNotEqual([o.client_order_id for o in old_asks], [o.client_order_id for o in self.strategy.active_sells]) self.assertNotEqual([o.client_order_id for o in old_bids], [o.client_order_id for o in self.strategy.active_buys]) # Simulate sell trade, the first bid gets taken out self.simulate_maker_market_trade(False, Decimal(100), Decimal("98.9")) self.assertEqual(4, len(self.strategy.active_buys)) self.assertEqual(3, len(self.strategy.active_sells)) self.clock.backtest_til( self.start_timestamp + 13 * self.clock_tick_size ) # After refresh, same numbers of orders self.assertEqual(4, len(self.strategy.active_buys)) self.assertEqual(3, len(self.strategy.active_sells)) # Another bid order is filled. self.simulate_maker_market_trade(False, Decimal(100), Decimal("97.9")) self.assertEqual(3, len(self.strategy.active_buys)) self.assertEqual(3, len(self.strategy.active_sells)) self.clock.backtest_til( self.start_timestamp + 20 * self.clock_tick_size ) # After refresh, numbers of orders back to order_levels of 5 self.assertEqual(5, len(self.strategy.active_buys)) self.assertEqual(5, len(self.strategy.active_sells))
[ "hummingbot.connector.exchange.paper_trade.paper_trade_exchange.QuantizationParams", "hummingbot.core.event.events.OrderBookTradeEvent", "hummingbot.core.event.event_logger.EventLogger", "hummingbot.core.clock.Clock", "hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple", "hummingbot.stra...
[((676, 716), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.ERROR'}), '(level=logging.ERROR)\n', (695, 716), False, 'import logging\n'), ((799, 835), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01"""'], {'tz': '"""UTC"""'}), "('2019-01-01', tz='UTC')\n", (811, 835), True, 'import pandas as pd\n'), ((860, 905), 'pandas.Timestamp', 'pd.Timestamp', (['"""2019-01-01 01:00:00"""'], {'tz': '"""UTC"""'}), "('2019-01-01 01:00:00', tz='UTC')\n", (872, 905), True, 'import pandas as pd\n'), ((1297, 1432), 'hummingbot.core.event.events.OrderBookTradeEvent', 'OrderBookTradeEvent', (['self.trading_pair', 'self.clock.current_timestamp', '(TradeType.BUY if is_buy else TradeType.SELL)', 'price', 'quantity'], {}), '(self.trading_pair, self.clock.current_timestamp, \n TradeType.BUY if is_buy else TradeType.SELL, price, quantity)\n', (1316, 1432), False, 'from hummingbot.core.event.events import MarketEvent, OrderBookTradeEvent\n'), ((1625, 1719), 'hummingbot.core.clock.Clock', 'Clock', (['ClockMode.BACKTEST', 'self.clock_tick_size', 'self.start_timestamp', 'self.end_timestamp'], {}), '(ClockMode.BACKTEST, self.clock_tick_size, self.start_timestamp, self.\n end_timestamp)\n', (1630, 1719), False, 'from hummingbot.core.clock import Clock, ClockMode\n'), ((1756, 1775), 'test.mock.mock_paper_exchange.MockPaperExchange', 'MockPaperExchange', ([], {}), '()\n', (1773, 1775), False, 'from test.mock.mock_paper_exchange import MockPaperExchange\n'), ((2557, 2650), 'hummingbot.strategy.market_trading_pair_tuple.MarketTradingPairTuple', 'MarketTradingPairTuple', (['self.market', 'self.trading_pair', 'self.base_asset', 'self.quote_asset'], {}), '(self.market, self.trading_pair, self.base_asset,\n self.quote_asset)\n', (2579, 2650), False, 'from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple\n'), ((2794, 2807), 'hummingbot.core.event.event_logger.EventLogger', 'EventLogger', ([], {}), '()\n', (2805, 2807), False, 'from hummingbot.core.event.event_logger import EventLogger\n'), ((2856, 2869), 'hummingbot.core.event.event_logger.EventLogger', 'EventLogger', ([], {}), '()\n', (2867, 2869), False, 'from hummingbot.core.event.event_logger import EventLogger\n'), ((3121, 3147), 'hummingbot.strategy.pure_market_making.pure_market_making.PureMarketMakingStrategy', 'PureMarketMakingStrategy', ([], {}), '()\n', (3145, 3147), False, 'from hummingbot.strategy.pure_market_making.pure_market_making import PureMarketMakingStrategy\n'), ((4891, 4917), 'hummingbot.strategy.pure_market_making.pure_market_making.PureMarketMakingStrategy', 'PureMarketMakingStrategy', ([], {}), '()\n', (4915, 4917), False, 'from hummingbot.strategy.pure_market_making.pure_market_making import PureMarketMakingStrategy\n'), ((6659, 6685), 'hummingbot.strategy.pure_market_making.pure_market_making.PureMarketMakingStrategy', 'PureMarketMakingStrategy', ([], {}), '()\n', (6683, 6685), False, 'from hummingbot.strategy.pure_market_making.pure_market_making import PureMarketMakingStrategy\n'), ((2440, 2489), 'hummingbot.connector.exchange.paper_trade.paper_trade_exchange.QuantizationParams', 'QuantizationParams', (['self.trading_pair', '(6)', '(6)', '(6)', '(6)'], {}), '(self.trading_pair, 6, 6, 6, 6)\n', (2458, 2489), False, 'from hummingbot.connector.exchange.paper_trade.paper_trade_exchange import QuantizationParams\n'), ((3784, 3796), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (3791, 3796), False, 'from decimal import Decimal\n'), ((3798, 3814), 'decimal.Decimal', 'Decimal', (['"""101.1"""'], {}), "('101.1')\n", (3805, 3814), False, 'from decimal import Decimal\n'), ((4558, 4570), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (4565, 4570), False, 'from decimal import Decimal\n'), ((4572, 4587), 'decimal.Decimal', 'Decimal', (['"""98.9"""'], {}), "('98.9')\n", (4579, 4587), False, 'from decimal import Decimal\n'), ((5555, 5567), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (5562, 5567), False, 'from decimal import Decimal\n'), ((5569, 5584), 'decimal.Decimal', 'Decimal', (['"""98.9"""'], {}), "('98.9')\n", (5576, 5584), False, 'from decimal import Decimal\n'), ((6330, 6342), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (6337, 6342), False, 'from decimal import Decimal\n'), ((6344, 6360), 'decimal.Decimal', 'Decimal', (['"""101.1"""'], {}), "('101.1')\n", (6351, 6360), False, 'from decimal import Decimal\n'), ((7443, 7455), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (7450, 7455), False, 'from decimal import Decimal\n'), ((7457, 7474), 'decimal.Decimal', 'Decimal', (['"""102.50"""'], {}), "('102.50')\n", (7464, 7474), False, 'from decimal import Decimal\n'), ((8753, 8765), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (8760, 8765), False, 'from decimal import Decimal\n'), ((8767, 8782), 'decimal.Decimal', 'Decimal', (['"""98.9"""'], {}), "('98.9')\n", (8774, 8782), False, 'from decimal import Decimal\n'), ((9267, 9279), 'decimal.Decimal', 'Decimal', (['(100)'], {}), '(100)\n', (9274, 9279), False, 'from decimal import Decimal\n'), ((9281, 9296), 'decimal.Decimal', 'Decimal', (['"""97.9"""'], {}), "('97.9')\n", (9288, 9296), False, 'from decimal import Decimal\n'), ((3236, 3251), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (3243, 3251), False, 'from decimal import Decimal\n'), ((3276, 3291), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (3283, 3291), False, 'from decimal import Decimal\n'), ((3318, 3330), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (3325, 3330), False, 'from decimal import Decimal\n'), ((5006, 5021), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (5013, 5021), False, 'from decimal import Decimal\n'), ((5046, 5061), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (5053, 5061), False, 'from decimal import Decimal\n'), ((5088, 5100), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (5095, 5100), False, 'from decimal import Decimal\n'), ((6774, 6789), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (6781, 6789), False, 'from decimal import Decimal\n'), ((6814, 6829), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (6821, 6829), False, 'from decimal import Decimal\n'), ((6856, 6868), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (6863, 6868), False, 'from decimal import Decimal\n'), ((6929, 6941), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (6936, 6941), False, 'from decimal import Decimal\n'), ((6974, 6989), 'decimal.Decimal', 'Decimal', (['"""0.01"""'], {}), "('0.01')\n", (6981, 6989), False, 'from decimal import Decimal\n')]
#!/usr/bin/env python import asyncio import logging import websockets import json from hummingbot.core.api_throttler.async_throttler import AsyncThrottler from hummingbot.core.utils.async_utils import safe_ensure_future from typing import ( Any, AsyncIterable, Dict, List, Optional, ) from websockets.exceptions import ConnectionClosed from hummingbot.logger import HummingbotLogger from hummingbot.connector.exchange.altmarkets.altmarkets_constants import Constants from hummingbot.connector.exchange.altmarkets.altmarkets_auth import AltmarketsAuth from hummingbot.connector.exchange.altmarkets.altmarkets_utils import RequestId # reusable websocket class # ToDo: We should eventually remove this class, and instantiate web socket connection normally (see Binance for example) class AltmarketsWebsocket(RequestId): _logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._logger is None: cls._logger = logging.getLogger(__name__) return cls._logger def __init__(self, auth: Optional[AltmarketsAuth] = None, throttler: Optional[AsyncThrottler] = None): self._auth: Optional[AltmarketsAuth] = auth self._isPrivate = True if self._auth is not None else False self._WS_URL = Constants.WS_PRIVATE_URL if self._isPrivate else Constants.WS_PUBLIC_URL self._client: Optional[websockets.WebSocketClientProtocol] = None self._is_subscribed = False self._throttler = throttler or AsyncThrottler(Constants.RATE_LIMITS) @property def is_connected(self): return self._client.open if self._client is not None else False @property def is_subscribed(self): return self._is_subscribed # connect to exchange async def connect(self): extra_headers = self._auth.get_headers() if self._isPrivate else {"User-Agent": Constants.USER_AGENT} self._client = await websockets.connect(self._WS_URL, extra_headers=extra_headers) return self._client # disconnect from exchange async def disconnect(self): if self._client is None: return await self._client.close() # receive & parse messages async def _messages(self) -> AsyncIterable[Any]: try: while True: try: raw_msg_str: str = await asyncio.wait_for(self._client.recv(), timeout=Constants.MESSAGE_TIMEOUT) try: msg = json.loads(raw_msg_str) if "ping" in msg: payload = {"op": "pong", "timestamp": str(msg["ping"])} safe_ensure_future(self._client.send(json.dumps(payload))) yield None elif "success" in msg: ws_method: str = msg.get('success', {}).get('message') if ws_method in ['subscribed', 'unsubscribed']: if ws_method == 'subscribed' and len(msg['success']['streams']) > 0: self._is_subscribed = True yield None elif ws_method == 'unsubscribed': self._is_subscribed = False yield None else: yield msg except ValueError: continue except asyncio.TimeoutError: await asyncio.wait_for(self._client.ping(), timeout=Constants.PING_TIMEOUT) except asyncio.TimeoutError: self.logger().warning("WebSocket ping timed out. Going to reconnect...") return except ConnectionClosed: return finally: await self.disconnect() # emit messages async def _emit(self, method: str, data: Optional[Dict[str, Any]] = {}, no_id: bool = False) -> int: async with self._throttler.execute_task(method): id = self.generate_request_id() payload = { "id": id, "event": method, } await self._client.send(json.dumps({**payload, **data})) return id # request via websocket async def request(self, method: str, data: Optional[Dict[str, Any]] = {}) -> int: return await self._emit(method, data) # subscribe to a method async def subscribe(self, streams: Optional[Dict[str, List]] = {}) -> int: return await self.request(Constants.WS_EVENT_SUBSCRIBE, {"streams": streams}) # unsubscribe to a method async def unsubscribe(self, streams: Optional[Dict[str, List]] = {}) -> int: return await self.request(Constants.WS_EVENT_UNSUBSCRIBE, {"streams": streams}) # listen to messages by method async def on_message(self) -> AsyncIterable[Any]: async for msg in self._messages(): if msg is None: yield None yield msg
[ "hummingbot.core.api_throttler.async_throttler.AsyncThrottler" ]
[((1004, 1031), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1021, 1031), False, 'import logging\n'), ((1566, 1603), 'hummingbot.core.api_throttler.async_throttler.AsyncThrottler', 'AsyncThrottler', (['Constants.RATE_LIMITS'], {}), '(Constants.RATE_LIMITS)\n', (1580, 1603), False, 'from hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n'), ((1993, 2054), 'websockets.connect', 'websockets.connect', (['self._WS_URL'], {'extra_headers': 'extra_headers'}), '(self._WS_URL, extra_headers=extra_headers)\n', (2011, 2054), False, 'import websockets\n'), ((4311, 4342), 'json.dumps', 'json.dumps', (['{**payload, **data}'], {}), '({**payload, **data})\n', (4321, 4342), False, 'import json\n'), ((2552, 2575), 'json.loads', 'json.loads', (['raw_msg_str'], {}), '(raw_msg_str)\n', (2562, 2575), False, 'import json\n'), ((2767, 2786), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (2777, 2786), False, 'import json\n')]
import asyncio import re import ujson import unittest import hummingbot.connector.exchange.binance.binance_constants as CONSTANTS import hummingbot.connector.exchange.binance.binance_utils as utils import hummingbot.core.utils.market_price as market_price from aioresponses import aioresponses from decimal import Decimal from typing import Any, Awaitable, Dict, List from unittest.mock import patch class MarketPriceUnitTests(unittest.TestCase): @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.ev_loop = asyncio.get_event_loop() cls.base_asset = "COINALPHA" cls.quote_asset = "HBOT" cls.trading_pair = f"{cls.base_asset}-{cls.quote_asset}" cls.binance_ex_trading_pair = f"{cls.base_asset}{cls.quote_asset}" def async_run_with_timeout(self, coroutine: Awaitable, timeout: float = 1): ret = self.ev_loop.run_until_complete(asyncio.wait_for(coroutine, timeout)) return ret @aioresponses() @patch("hummingbot.connector.exchange.binance.binance_utils.convert_from_exchange_trading_pair") def test_get_binanace_mid_price(self, mock_api, mock_utils): mock_utils.return_value = self.trading_pair url = utils.public_rest_url(path_url=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_response: List[Dict[str, Any]] = [ { # Truncated Response "symbol": self.binance_ex_trading_pair, "bidPrice": "1.0", "askPrice": "2.0", }, ] mock_api.get(regex_url, body=ujson.dumps(mock_response)) result = self.async_run_with_timeout(market_price.get_binance_mid_price(trading_pair=self.trading_pair)) self.assertEqual(result, Decimal("1.5")) @aioresponses() @patch("hummingbot.connector.exchange.binance.binance_utils.convert_from_exchange_trading_pair") def test_get_last_price(self, mock_api, mock_utils): mock_utils.return_value = self.trading_pair url = utils.public_rest_url(path_url=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL) regex_url = re.compile(f"^{url}".replace(".", r"\.").replace("?", r"\?")) mock_response: Dict[str, Any] = { # truncated response "symbol": self.binance_ex_trading_pair, "lastPrice": "1", } mock_api.get(regex_url, body=ujson.dumps(mock_response)) result = self.async_run_with_timeout(market_price.get_last_price(exchange="binance", trading_pair=self.trading_pair)) self.assertEqual(result, Decimal("1.0"))
[ "hummingbot.connector.exchange.binance.binance_utils.public_rest_url", "hummingbot.core.utils.market_price.get_last_price", "hummingbot.core.utils.market_price.get_binance_mid_price" ]
[((978, 992), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (990, 992), False, 'from aioresponses import aioresponses\n'), ((998, 1103), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.binance.binance_utils.convert_from_exchange_trading_pair"""'], {}), "(\n 'hummingbot.connector.exchange.binance.binance_utils.convert_from_exchange_trading_pair'\n )\n", (1003, 1103), False, 'from unittest.mock import patch\n'), ((1864, 1878), 'aioresponses.aioresponses', 'aioresponses', ([], {}), '()\n', (1876, 1878), False, 'from aioresponses import aioresponses\n'), ((1884, 1989), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.binance.binance_utils.convert_from_exchange_trading_pair"""'], {}), "(\n 'hummingbot.connector.exchange.binance.binance_utils.convert_from_exchange_trading_pair'\n )\n", (1889, 1989), False, 'from unittest.mock import patch\n'), ((552, 576), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (574, 576), False, 'import asyncio\n'), ((1226, 1296), 'hummingbot.connector.exchange.binance.binance_utils.public_rest_url', 'utils.public_rest_url', ([], {'path_url': 'CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL'}), '(path_url=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL)\n', (1247, 1296), True, 'import hummingbot.connector.exchange.binance.binance_utils as utils\n'), ((2104, 2174), 'hummingbot.connector.exchange.binance.binance_utils.public_rest_url', 'utils.public_rest_url', ([], {'path_url': 'CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL'}), '(path_url=CONSTANTS.TICKER_PRICE_CHANGE_PATH_URL)\n', (2125, 2174), True, 'import hummingbot.connector.exchange.binance.binance_utils as utils\n'), ((915, 951), 'asyncio.wait_for', 'asyncio.wait_for', (['coroutine', 'timeout'], {}), '(coroutine, timeout)\n', (931, 951), False, 'import asyncio\n'), ((1740, 1806), 'hummingbot.core.utils.market_price.get_binance_mid_price', 'market_price.get_binance_mid_price', ([], {'trading_pair': 'self.trading_pair'}), '(trading_pair=self.trading_pair)\n', (1774, 1806), True, 'import hummingbot.core.utils.market_price as market_price\n'), ((1842, 1856), 'decimal.Decimal', 'Decimal', (['"""1.5"""'], {}), "('1.5')\n", (1849, 1856), False, 'from decimal import Decimal\n'), ((2535, 2614), 'hummingbot.core.utils.market_price.get_last_price', 'market_price.get_last_price', ([], {'exchange': '"""binance"""', 'trading_pair': 'self.trading_pair'}), "(exchange='binance', trading_pair=self.trading_pair)\n", (2562, 2614), True, 'import hummingbot.core.utils.market_price as market_price\n'), ((2723, 2737), 'decimal.Decimal', 'Decimal', (['"""1.0"""'], {}), "('1.0')\n", (2730, 2737), False, 'from decimal import Decimal\n'), ((1666, 1692), 'ujson.dumps', 'ujson.dumps', (['mock_response'], {}), '(mock_response)\n', (1677, 1692), False, 'import ujson\n'), ((2461, 2487), 'ujson.dumps', 'ujson.dumps', (['mock_response'], {}), '(mock_response)\n', (2472, 2487), False, 'import ujson\n')]
from hummingbot.core.utils.market_mid_price import get_mid_price from hummingbot.client.settings import CEXES, DEXES, DERIVATIVES, EXCHANGES from hummingbot.client.config.security import Security from hummingbot.client.config.config_helpers import get_connector_class from hummingbot.core.utils.async_utils import safe_gather from hummingbot.client.config.global_config_map import global_config_map from typing import Optional, Dict from decimal import Decimal from web3 import Web3 class UserBalances: __instance = None @staticmethod def connect_market(exchange, **api_details): connector = None if exchange in CEXES or exchange in DERIVATIVES: connector_class = get_connector_class(exchange) connector = connector_class(**api_details) return connector # return error message if the _update_balances fails @staticmethod async def _update_balances(market) -> Optional[str]: try: await market._update_balances() except Exception as e: return str(e) return None @staticmethod def instance(): if UserBalances.__instance is None: UserBalances() return UserBalances.__instance def __init__(self): if UserBalances.__instance is not None: raise Exception("This class is a singleton!") else: UserBalances.__instance = self self._markets = {} async def add_exchange(self, exchange, **api_details) -> Optional[str]: self._markets.pop(exchange, None) market = UserBalances.connect_market(exchange, **api_details) err_msg = await UserBalances._update_balances(market) if err_msg is None: self._markets[exchange] = market return err_msg def all_balances(self, exchange) -> Dict[str, Decimal]: if exchange not in self._markets: return None return self._markets[exchange].get_all_balances() async def update_exchange_balance(self, exchange) -> Optional[str]: if exchange in self._markets: return await self._update_balances(self._markets[exchange]) else: api_keys = await Security.api_keys(exchange) if api_keys: return await self.add_exchange(exchange, **api_keys) else: return "API keys have not been added." # returns error message for each exchange async def update_exchanges(self, reconnect=False, exchanges=EXCHANGES) -> Dict[str, Optional[str]]: tasks = [] # We can only update user exchange balances on CEXes, for DEX we'll need to implement web3 wallet query later. exchanges = [ex for ex in exchanges if ex not in DEXES] if reconnect: self._markets.clear() for exchange in exchanges: tasks.append(self.update_exchange_balance(exchange)) results = await safe_gather(*tasks) return {ex: err_msg for ex, err_msg in zip(exchanges, results)} async def all_balances_all_exchanges(self) -> Dict[str, Dict[str, Decimal]]: await self.update_exchanges() return {k: v.get_all_balances() for k, v in sorted(self._markets.items(), key=lambda x: x[0])} async def balances(self, exchange, *symbols) -> Dict[str, Decimal]: if await self.update_exchange_balance(exchange) is None: results = {} for token, bal in self.all_balances(exchange).items(): matches = [s for s in symbols if s.lower() == token.lower()] if matches: results[matches[0]] = bal return results @staticmethod def ethereum_balance() -> Decimal: ethereum_wallet = global_config_map.get("ethereum_wallet").value ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value web3 = Web3(Web3.HTTPProvider(ethereum_rpc_url)) balance = web3.eth.getBalance(ethereum_wallet) balance = web3.fromWei(balance, "ether") return balance @staticmethod def validate_ethereum_wallet() -> Optional[str]: if global_config_map.get("ethereum_wallet").value is None: return "Ethereum wallet is required." if global_config_map.get("ethereum_rpc_url").value is None: return "ethereum_rpc_url is required." if global_config_map.get("ethereum_rpc_ws_url").value is None: return "ethereum_rpc_ws_url is required." if global_config_map.get("ethereum_wallet").value not in Security.private_keys(): return "Ethereum private key file does not exist or corrupts." try: UserBalances.ethereum_balance() except Exception as e: return str(e) return None @staticmethod def base_amount_ratio(exchange, trading_pair, balances) -> Optional[Decimal]: try: base, quote = trading_pair.split("-") base_amount = balances.get(base, 0) quote_amount = balances.get(quote, 0) price = get_mid_price(exchange, trading_pair) total_value = base_amount + (quote_amount / price) return None if total_value <= 0 else base_amount / total_value except Exception: return None
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.client.config.config_helpers.get_connector_class", "hummingbot.client.config.security.Security.private_keys", "hummingbot.client.config.security.Security.api_keys", "hummingbot.client.config.global_config_map.global_config_map.get", "hummingbot....
[((708, 737), 'hummingbot.client.config.config_helpers.get_connector_class', 'get_connector_class', (['exchange'], {}), '(exchange)\n', (727, 737), False, 'from hummingbot.client.config.config_helpers import get_connector_class\n'), ((2936, 2955), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['*tasks'], {}), '(*tasks)\n', (2947, 2955), False, 'from hummingbot.core.utils.async_utils import safe_gather\n'), ((3743, 3783), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_wallet"""'], {}), "('ethereum_wallet')\n", (3764, 3783), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((3817, 3858), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_rpc_url"""'], {}), "('ethereum_rpc_url')\n", (3838, 3858), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((3885, 3920), 'web3.Web3.HTTPProvider', 'Web3.HTTPProvider', (['ethereum_rpc_url'], {}), '(ethereum_rpc_url)\n', (3902, 3920), False, 'from web3 import Web3\n'), ((4547, 4570), 'hummingbot.client.config.security.Security.private_keys', 'Security.private_keys', ([], {}), '()\n', (4568, 4570), False, 'from hummingbot.client.config.security import Security\n'), ((5063, 5100), 'hummingbot.core.utils.market_mid_price.get_mid_price', 'get_mid_price', (['exchange', 'trading_pair'], {}), '(exchange, trading_pair)\n', (5076, 5100), False, 'from hummingbot.core.utils.market_mid_price import get_mid_price\n'), ((2208, 2235), 'hummingbot.client.config.security.Security.api_keys', 'Security.api_keys', (['exchange'], {}), '(exchange)\n', (2225, 2235), False, 'from hummingbot.client.config.security import Security\n'), ((4132, 4172), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_wallet"""'], {}), "('ethereum_wallet')\n", (4153, 4172), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((4249, 4290), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_rpc_url"""'], {}), "('ethereum_rpc_url')\n", (4270, 4290), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((4368, 4412), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_rpc_ws_url"""'], {}), "('ethereum_rpc_ws_url')\n", (4389, 4412), False, 'from hummingbot.client.config.global_config_map import global_config_map\n'), ((4493, 4533), 'hummingbot.client.config.global_config_map.global_config_map.get', 'global_config_map.get', (['"""ethereum_wallet"""'], {}), "('ethereum_wallet')\n", (4514, 4533), False, 'from hummingbot.client.config.global_config_map import global_config_map\n')]
import logging from typing import ( List, Optional, ) from hummingbot.connector.exchange.hitbtc.hitbtc_api_user_stream_data_source import \ HitbtcAPIUserStreamDataSource from hummingbot.connector.exchange.hitbtc.hitbtc_auth import HitbtcAuth from hummingbot.connector.exchange.hitbtc.hitbtc_constants import Constants from hummingbot.core.data_type.user_stream_tracker import ( UserStreamTracker ) from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.core.utils.async_utils import ( safe_ensure_future, safe_gather, ) from hummingbot.logger import HummingbotLogger class HitbtcUserStreamTracker(UserStreamTracker): _cbpust_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._bust_logger is None: cls._bust_logger = logging.getLogger(__name__) return cls._bust_logger def __init__(self, hitbtc_auth: Optional[HitbtcAuth] = None, trading_pairs: Optional[List[str]] = None): self._hitbtc_auth: HitbtcAuth = hitbtc_auth self._trading_pairs: List[str] = trading_pairs or [] super().__init__(data_source=HitbtcAPIUserStreamDataSource( hitbtc_auth=self._hitbtc_auth, trading_pairs=self._trading_pairs )) @property def data_source(self) -> UserStreamTrackerDataSource: """ *required Initializes a user stream data source (user specific order diffs from live socket stream) :return: OrderBookTrackerDataSource """ if not self._data_source: self._data_source = HitbtcAPIUserStreamDataSource( hitbtc_auth=self._hitbtc_auth, trading_pairs=self._trading_pairs ) return self._data_source @property def exchange_name(self) -> str: """ *required Name of the current exchange """ return Constants.EXCHANGE_NAME async def start(self): """ *required Start all listeners and tasks """ self._user_stream_tracking_task = safe_ensure_future( self.data_source.listen_for_user_stream(self._user_stream) ) await safe_gather(self._user_stream_tracking_task)
[ "hummingbot.core.utils.async_utils.safe_gather", "hummingbot.connector.exchange.hitbtc.hitbtc_api_user_stream_data_source.HitbtcAPIUserStreamDataSource" ]
[((884, 911), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (901, 911), False, 'import logging\n'), ((1692, 1792), 'hummingbot.connector.exchange.hitbtc.hitbtc_api_user_stream_data_source.HitbtcAPIUserStreamDataSource', 'HitbtcAPIUserStreamDataSource', ([], {'hitbtc_auth': 'self._hitbtc_auth', 'trading_pairs': 'self._trading_pairs'}), '(hitbtc_auth=self._hitbtc_auth, trading_pairs=\n self._trading_pairs)\n', (1721, 1792), False, 'from hummingbot.connector.exchange.hitbtc.hitbtc_api_user_stream_data_source import HitbtcAPIUserStreamDataSource\n'), ((2301, 2345), 'hummingbot.core.utils.async_utils.safe_gather', 'safe_gather', (['self._user_stream_tracking_task'], {}), '(self._user_stream_tracking_task)\n', (2312, 2345), False, 'from hummingbot.core.utils.async_utils import safe_ensure_future, safe_gather\n'), ((1238, 1338), 'hummingbot.connector.exchange.hitbtc.hitbtc_api_user_stream_data_source.HitbtcAPIUserStreamDataSource', 'HitbtcAPIUserStreamDataSource', ([], {'hitbtc_auth': 'self._hitbtc_auth', 'trading_pairs': 'self._trading_pairs'}), '(hitbtc_auth=self._hitbtc_auth, trading_pairs=\n self._trading_pairs)\n', (1267, 1338), False, 'from hummingbot.connector.exchange.hitbtc.hitbtc_api_user_stream_data_source import HitbtcAPIUserStreamDataSource\n')]
#!/usr/bin/env python import asyncio import logging import time from base64 import b64decode from typing import Optional, List, Dict, AsyncIterable, Any from zlib import decompress, MAX_WBITS import aiohttp import pandas as pd import signalr_aio import ujson from signalr_aio import Connection from signalr_aio.hubs import Hub from async_timeout import timeout from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.data_type.order_book_message import OrderBookMessage from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource from hummingbot.core.data_type.order_book_tracker_entry import OrderBookTrackerEntry, BittrexOrderBookTrackerEntry from hummingbot.core.utils import async_ttl_cache from hummingbot.core.utils.async_utils import safe_gather from hummingbot.logger import HummingbotLogger from hummingbot.market.bittrex.bittrex_active_order_tracker import BittrexActiveOrderTracker from hummingbot.market.bittrex.bittrex_order_book import BittrexOrderBook EXCHANGE_NAME = "Bittrex" BITTREX_REST_URL = "https://api.bittrex.com/v3" BITTREX_EXCHANGE_INFO_PATH = "/markets" BITTREX_MARKET_SUMMARY_PATH = "/markets/summaries" BITTREX_TICKER_PATH = "/markets/tickers" BITTREX_WS_FEED = "https://socket.bittrex.com/signalr" MAX_RETRIES = 20 MESSAGE_TIMEOUT = 30.0 SNAPSHOT_TIMEOUT = 10.0 NaN = float("nan") class BittrexAPIOrderBookDataSource(OrderBookTrackerDataSource): PING_TIMEOUT = 10.0 _bittrexaobds_logger: Optional[HummingbotLogger] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._bittrexaobds_logger is None: cls._bittrexaobds_logger = logging.getLogger(__name__) return cls._bittrexaobds_logger def __init__(self, symbols: Optional[List[str]] = None): super().__init__() self._symbols: Optional[List[str]] = symbols self._websocket_connection: Optional[Connection] = None self._websocket_hub: Optional[Hub] = None self._snapshot_msg: Dict[str, any] = {} @classmethod @async_ttl_cache(ttl=60 * 30, maxsize=1) async def get_active_exchange_markets(cls) -> pd.DataFrame: """ Returned data frame should have symbol as index and include USDVolume, baseAsset and quoteAsset """ market_path_url = f"{BITTREX_REST_URL}{BITTREX_EXCHANGE_INFO_PATH}" summary_path_url = f"{BITTREX_REST_URL}{BITTREX_MARKET_SUMMARY_PATH}" ticker_path_url = f"{BITTREX_REST_URL}{BITTREX_TICKER_PATH}" async with aiohttp.ClientSession() as client: market_response, ticker_response, summary_response = await safe_gather( client.get(market_path_url), client.get(ticker_path_url), client.get(summary_path_url) ) market_response: aiohttp.ClientResponse = market_response ticker_response: aiohttp.ClientResponse = ticker_response summary_response: aiohttp.ClientResponse = summary_response if market_response.status != 200: raise IOError( f"Error fetching active Bittrex markets information. " f"HTTP status is {market_response.status}." ) if ticker_response.status != 200: raise IOError( f"Error fetching active Bittrex market tickers. " f"HTTP status is {ticker_response.status}." ) if summary_response.status != 200: raise IOError( f"Error fetching active Bittrex market summaries. " f"HTTP status is {summary_response.status}." ) market_data, ticker_data, summary_data = await safe_gather( market_response.json(), ticker_response.json(), summary_response.json() ) ticker_data: Dict[str, Any] = {item["symbol"]: item for item in ticker_data} summary_data: Dict[str, Any] = {item["symbol"]: item for item in summary_data} market_data: List[Dict[str, Any]] = [ {**item, **ticker_data[item["symbol"]], **summary_data[item["symbol"]]} for item in market_data if item["symbol"] in ticker_data and item["symbol"] in summary_data ] all_markets: pd.DataFrame = pd.DataFrame.from_records(data=market_data, index="symbol") all_markets.rename( {"baseCurrencySymbol": "baseAsset", "quoteCurrencySymbol": "quoteAsset"}, axis="columns", inplace=True ) btc_usd_price: float = float(all_markets.loc["BTC-USD"].lastTradeRate) eth_usd_price: float = float(all_markets.loc["ETH-USD"].lastTradeRate) usd_volume: List[float] = [ ( volume * quote_price if symbol.endswith(("USD", "USDT")) else volume * quote_price * btc_usd_price if symbol.endswith("BTC") else volume * quote_price * eth_usd_price if symbol.endswith("ETH") else volume ) for symbol, volume, quote_price in zip(all_markets.index, all_markets.volume.astype("float"), all_markets.lastTradeRate.astype("float")) ] old_symbols: List[str] = [ ( f"{quoteAsset}-{baseAsset}" ) for baseAsset, quoteAsset in zip(all_markets.baseAsset, all_markets.quoteAsset) ] all_markets.loc[:, "USDVolume"] = usd_volume all_markets.loc[:, "old_symbol"] = old_symbols await client.close() return all_markets.sort_values("USDVolume", ascending=False) async def get_trading_pairs(self) -> List[str]: if not self._symbols: try: active_markets: pd.DataFrame = await self.get_active_exchange_markets() self._symbols = active_markets.index.tolist() except Exception: self._symbols = [] self.logger().network( f"Error getting active exchange information.", exc_info=True, app_warning_msg=f"Error getting active exchange information. Check network connection.", ) return self._symbols async def websocket_connection(self) -> (signalr_aio.Connection, signalr_aio.hubs.Hub): if self._websocket_connection and self._websocket_hub: return self._websocket_connection, self._websocket_hub self._websocket_connection = signalr_aio.Connection(BITTREX_WS_FEED, session=None) self._websocket_hub = self._websocket_connection.register_hub("c2") trading_pairs = await self.get_trading_pairs() for trading_pair in trading_pairs: # TODO: Refactor accordingly when V3 WebSocket API is released # WebSocket API requires trading_pair to be in 'Quote-Base' format trading_pair = f"{trading_pair.split('-')[1]}-{trading_pair.split('-')[0]}" self.logger().info(f"Subscribed to {trading_pair} deltas") self._websocket_hub.server.invoke("SubscribeToExchangeDeltas", trading_pair) self.logger().info(f"Query {trading_pair} snapshot.") self._websocket_hub.server.invoke("queryExchangeState", trading_pair) self._websocket_connection.start() return self._websocket_connection, self._websocket_hub async def wait_for_snapshot(self, trading_pair: str, invoke_timestamp: int) -> Optional[OrderBookMessage]: try: async with timeout(SNAPSHOT_TIMEOUT): while True: msg: Dict[str, any] = self._snapshot_msg.pop(trading_pair, None) if msg and msg["timestamp"] >= invoke_timestamp: return msg["content"] await asyncio.sleep(1) except asyncio.TimeoutError: raise async def get_snapshot(self, trading_pair: str) -> OrderBookMessage: # TODO: Refactor accordingly when V3 WebSocket API is released temp_trading_pair = f"{trading_pair.split('-')[1]}-{trading_pair.split('-')[0]}" get_snapshot_attempts = 0 while get_snapshot_attempts < MAX_RETRIES: get_snapshot_attempts += 1 # Creates/Reuses connection to obtain a single snapshot of the trading_pair connection, hub = await self.websocket_connection() hub.server.invoke("queryExchangeState", trading_pair) invoke_timestamp = int(time.time()) self.logger().info(f"Query {trading_pair} snapshot[{invoke_timestamp}]. " f"{get_snapshot_attempts}/{MAX_RETRIES}") try: return await self.wait_for_snapshot(temp_trading_pair, invoke_timestamp) except asyncio.TimeoutError: self.logger().warning("Snapshot query timed out. Retrying...") except Exception: self.logger().error(f"Unexpected error occurred when retrieving {trading_pair} snapshot. " f"Retrying...", exc_info=True) await asyncio.sleep(0.5) raise IOError async def get_tracking_pairs(self) -> Dict[str, OrderBookTrackerEntry]: # Get the current active markets trading_pairs: List[str] = await self.get_trading_pairs() retval: Dict[str, OrderBookTrackerEntry] = {} number_of_pairs: int = len(trading_pairs) for index, trading_pair in enumerate(trading_pairs): # TODO: Refactor accordingly when V3 WebSocket API is released # get_snapshot() utilizes WebSocket API. Requires market symbols in 'Quote-Base' format # Code below converts 'Base-Quote' -> 'Quote-Base' temp_trading_pair = f"{trading_pair.split('-')[1]}-{trading_pair.split('-')[0]}" try: snapshot: OrderBookMessage = await self.get_snapshot(temp_trading_pair) order_book: OrderBook = self.order_book_create_function() active_order_tracker: BittrexActiveOrderTracker = BittrexActiveOrderTracker() bids, asks = active_order_tracker.convert_snapshot_message_to_order_book_row(snapshot) order_book.apply_snapshot(bids, asks, snapshot.update_id) retval[trading_pair] = BittrexOrderBookTrackerEntry( trading_pair, snapshot.timestamp, order_book, active_order_tracker ) self.logger().info( f"Initialized order book for {trading_pair}. " f"{index + 1}/{number_of_pairs} completed." ) await asyncio.sleep(0.5) except (IOError, OSError): self.logger().network( f"Max retries met fetching snapshot for {trading_pair}.", exc_info=True, app_warning_msg=f"Error getting snapshot for {trading_pair}. Check network connection.", ) except Exception: self.logger().error(f"Error initiailizing order book for {trading_pair}. ", exc_info=True) await asyncio.sleep(5.0) return retval async def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): # Trade messages are received as Orderbook Deltas and handled by listen_for_order_book_stream() pass async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): # Orderbooks Deltas and Snapshots are handled by listen_for_order_book_stream() pass async def _socket_stream(self) -> AsyncIterable[str]: try: while True: async with timeout(MESSAGE_TIMEOUT): # Timeouts if not receiving any messages for 10 seconds(ping) conn: signalr_aio.Connection = (await self.websocket_connection())[0] yield await conn.msg_queue.get() except asyncio.TimeoutError: self.logger().warning("Message recv() timed out. Going to reconnect...") return async def _transform_raw_message(self, msg) -> Dict[str, Any]: def _decode_message(raw_message: bytes) -> Dict[str, Any]: try: decoded_msg: bytes = decompress(b64decode(raw_message, validate=True), -MAX_WBITS) except SyntaxError: decoded_msg: bytes = decompress(b64decode(raw_message, validate=True)) except Exception: return {} return ujson.loads(decoded_msg.decode()) def _is_snapshot(msg) -> bool: return type(msg.get("R", False)) is not bool def _is_market_delta(msg) -> bool: return len(msg.get("M", [])) > 0 and type(msg["M"][0]) == dict and msg["M"][0].get("M", None) == "uE" output: Dict[str, Any] = {"nonce": None, "type": None, "results": {}} msg: Dict[str, Any] = ujson.loads(msg) if _is_snapshot(msg): output["results"] = _decode_message(msg["R"]) # TODO: Refactor accordingly when V3 WebSocket API is released # WebSocket API returns market symbols in 'Quote-Base' format # Code below converts 'Quote-Base' -> 'Base-Quote' output["results"].update({ "M": f"{output['results']['M'].split('-')[1]}-{output['results']['M'].split('-')[0]}" }) output["type"] = "snapshot" output["nonce"] = output["results"]["N"] elif _is_market_delta(msg): output["results"] = _decode_message(msg["M"][0]["A"][0]) # TODO: Refactor accordingly when V3 WebSocket API is released # WebSocket API returns market symbols in 'Quote-Base' format # Code below converts 'Quote-Base' -> 'Base-Quote' output["results"].update({ "M": f"{output['results']['M'].split('-')[1]}-{output['results']['M'].split('-')[0]}" }) output["type"] = "update" output["nonce"] = output["results"]["N"] return output async def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue): # Technically this does not listen for snapshot, Instead it periodically queries for snapshots. while True: try: connection, hub = await self.websocket_connection() trading_pairs = await self.get_trading_pairs() # Symbols of trading pair in V3 format i.e. 'Base-Quote' for trading_pair in trading_pairs: # TODO: Refactor accordingly when V3 WebSocket API is released # WebSocket API requires trading_pair to be in 'Quote-Base' format trading_pair = f"{trading_pair.split('-')[1]}-{trading_pair.split('-')[0]}" hub.server.invoke("queryExchangeState", trading_pair) self.logger().info(f"Query {trading_pair} snapshots.[Scheduled]") # Waits for delta amount of time before getting new snapshots this_hour: pd.Timestamp = pd.Timestamp.utcnow().replace(minute=0, second=0, microsecond=0) next_hour: pd.Timestamp = this_hour + pd.Timedelta(hours=1) delta: float = next_hour.timestamp() - time.time() await asyncio.sleep(delta) except Exception: self.logger().error("Unexpected error occurred invoking queryExchangeState", exc_info=True) async def listen_for_order_book_stream(self, ev_loop: asyncio.BaseEventLoop, snapshot_queue: asyncio.Queue, diff_queue: asyncio.Queue): while True: connection, hub = await self.websocket_connection() try: async for raw_message in self._socket_stream(): decoded: Dict[str, Any] = await self._transform_raw_message(raw_message) symbol: str = decoded["results"].get("M") if not symbol: # Ignores any other websocket response messages continue # Processes snapshot messages if decoded["type"] == "snapshot": snapshot: Dict[str, any] = decoded snapshot_timestamp = snapshot["nonce"] snapshot_msg: OrderBookMessage = BittrexOrderBook.snapshot_message_from_exchange( snapshot["results"], snapshot_timestamp, metadata={"product_id": symbol} ) snapshot_queue.put_nowait(snapshot_msg) self._snapshot_msg[symbol] = { "timestamp": int(time.time()), "content": snapshot_msg } # Processes diff messages if decoded["type"] == "update": diff: Dict[str, any] = decoded diff_timestamp = diff["nonce"] diff_msg: OrderBookMessage = BittrexOrderBook.diff_message_from_exchange( diff["results"], diff_timestamp, metadata={"product_id": symbol} ) diff_queue.put_nowait(diff_msg) except Exception: self.logger().error("Unexpected error when listening on socket stream.", exc_info=True) finally: connection.close() self._websocket_connection = self._websocket_hub = None self.logger().info("Reinitializing websocket connection...")
[ "hummingbot.core.utils.async_ttl_cache", "hummingbot.core.data_type.order_book_tracker_entry.BittrexOrderBookTrackerEntry", "hummingbot.market.bittrex.bittrex_order_book.BittrexOrderBook.snapshot_message_from_exchange", "hummingbot.market.bittrex.bittrex_order_book.BittrexOrderBook.diff_message_from_exchange"...
[((2066, 2105), 'hummingbot.core.utils.async_ttl_cache', 'async_ttl_cache', ([], {'ttl': '(60 * 30)', 'maxsize': '(1)'}), '(ttl=60 * 30, maxsize=1)\n', (2081, 2105), False, 'from hummingbot.core.utils import async_ttl_cache\n'), ((6662, 6715), 'signalr_aio.Connection', 'signalr_aio.Connection', (['BITTREX_WS_FEED'], {'session': 'None'}), '(BITTREX_WS_FEED, session=None)\n', (6684, 6715), False, 'import signalr_aio\n'), ((13155, 13171), 'ujson.loads', 'ujson.loads', (['msg'], {}), '(msg)\n', (13166, 13171), False, 'import ujson\n'), ((1671, 1698), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1688, 1698), False, 'import logging\n'), ((2541, 2564), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (2562, 2564), False, 'import aiohttp\n'), ((4302, 4361), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', ([], {'data': 'market_data', 'index': '"""symbol"""'}), "(data=market_data, index='symbol')\n", (4327, 4361), True, 'import pandas as pd\n'), ((7698, 7723), 'async_timeout.timeout', 'timeout', (['SNAPSHOT_TIMEOUT'], {}), '(SNAPSHOT_TIMEOUT)\n', (7705, 7723), False, 'from async_timeout import timeout\n'), ((8665, 8676), 'time.time', 'time.time', ([], {}), '()\n', (8674, 8676), False, 'import time\n'), ((9322, 9340), 'asyncio.sleep', 'asyncio.sleep', (['(0.5)'], {}), '(0.5)\n', (9335, 9340), False, 'import asyncio\n'), ((10293, 10320), 'hummingbot.market.bittrex.bittrex_active_order_tracker.BittrexActiveOrderTracker', 'BittrexActiveOrderTracker', ([], {}), '()\n', (10318, 10320), False, 'from hummingbot.market.bittrex.bittrex_active_order_tracker import BittrexActiveOrderTracker\n'), ((10538, 10638), 'hummingbot.core.data_type.order_book_tracker_entry.BittrexOrderBookTrackerEntry', 'BittrexOrderBookTrackerEntry', (['trading_pair', 'snapshot.timestamp', 'order_book', 'active_order_tracker'], {}), '(trading_pair, snapshot.timestamp, order_book,\n active_order_tracker)\n', (10566, 10638), False, 'from hummingbot.core.data_type.order_book_tracker_entry import OrderBookTrackerEntry, BittrexOrderBookTrackerEntry\n'), ((10860, 10878), 'asyncio.sleep', 'asyncio.sleep', (['(0.5)'], {}), '(0.5)\n', (10873, 10878), False, 'import asyncio\n'), ((11938, 11962), 'async_timeout.timeout', 'timeout', (['MESSAGE_TIMEOUT'], {}), '(MESSAGE_TIMEOUT)\n', (11945, 11962), False, 'from async_timeout import timeout\n'), ((12511, 12548), 'base64.b64decode', 'b64decode', (['raw_message'], {'validate': '(True)'}), '(raw_message, validate=True)\n', (12520, 12548), False, 'from base64 import b64decode\n'), ((15470, 15491), 'pandas.Timedelta', 'pd.Timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (15482, 15491), True, 'import pandas as pd\n'), ((15547, 15558), 'time.time', 'time.time', ([], {}), '()\n', (15556, 15558), False, 'import time\n'), ((15581, 15601), 'asyncio.sleep', 'asyncio.sleep', (['delta'], {}), '(delta)\n', (15594, 15601), False, 'import asyncio\n'), ((7979, 7995), 'asyncio.sleep', 'asyncio.sleep', (['(1)'], {}), '(1)\n', (7992, 7995), False, 'import asyncio\n'), ((11356, 11374), 'asyncio.sleep', 'asyncio.sleep', (['(5.0)'], {}), '(5.0)\n', (11369, 11374), False, 'import asyncio\n'), ((12642, 12679), 'base64.b64decode', 'b64decode', (['raw_message'], {'validate': '(True)'}), '(raw_message, validate=True)\n', (12651, 12679), False, 'from base64 import b64decode\n'), ((15351, 15372), 'pandas.Timestamp.utcnow', 'pd.Timestamp.utcnow', ([], {}), '()\n', (15370, 15372), True, 'import pandas as pd\n'), ((16732, 16857), 'hummingbot.market.bittrex.bittrex_order_book.BittrexOrderBook.snapshot_message_from_exchange', 'BittrexOrderBook.snapshot_message_from_exchange', (["snapshot['results']", 'snapshot_timestamp'], {'metadata': "{'product_id': symbol}"}), "(snapshot['results'],\n snapshot_timestamp, metadata={'product_id': symbol})\n", (16779, 16857), False, 'from hummingbot.market.bittrex.bittrex_order_book import BittrexOrderBook\n'), ((17426, 17539), 'hummingbot.market.bittrex.bittrex_order_book.BittrexOrderBook.diff_message_from_exchange', 'BittrexOrderBook.diff_message_from_exchange', (["diff['results']", 'diff_timestamp'], {'metadata': "{'product_id': symbol}"}), "(diff['results'], diff_timestamp,\n metadata={'product_id': symbol})\n", (17469, 17539), False, 'from hummingbot.market.bittrex.bittrex_order_book import BittrexOrderBook\n'), ((17072, 17083), 'time.time', 'time.time', ([], {}), '()\n', (17081, 17083), False, 'import time\n')]
#!/usr/bin/env python from os.path import join, realpath import sys; sys.path.insert(0, realpath(join(__file__, "../../../"))) import logging import unittest from typing import ( Any, Dict, Optional ) from hummingbot.market.coinbase_pro.coinbase_pro_order_book_tracker import CoinbaseProOrderBookTracker from hummingbot.core.data_type.order_book import OrderBook from hummingbot.core.data_type.order_book_tracker import OrderBookTrackerDataSourceType from hummingbot.core.data_type.order_book_message import CoinbaseProOrderBookMessage from hummingbot.core.data_type.order_book_row import OrderBookRow test_trading_pair = "BTC-USD" class CoinbaseProOrderBookTrackerUnitTest(unittest.TestCase): order_book_tracker: Optional[CoinbaseProOrderBookTracker] = None @classmethod def setUpClass(cls): cls.order_book_tracker: CoinbaseProOrderBookTracker = CoinbaseProOrderBookTracker( OrderBookTrackerDataSourceType.EXCHANGE_API, trading_pairs=[test_trading_pair]) def test_diff_message_not_found(self): order_books: Dict[str, OrderBook] = self.order_book_tracker.order_books test_order_book: OrderBook = order_books[test_trading_pair] test_active_order_tracker = self.order_book_tracker._active_order_trackers[test_trading_pair] # receive match message that is not in active orders (should be ignored) match_msg_to_ignore: Dict[str, Any] = { "type": "match", "trade_id": 10, "sequence": 50, "maker_order_id": "ac928c66-ca53-498f-9c13-a110027a60e8", "taker_order_id": "132fb6ae-456b-4654-b4e0-d681ac05cea1", "time": "2014-11-07T08:19:27.028459Z", "product_id": test_trading_pair, "size": "5.23512", "price": "400.23", "side": "sell" } ignore_msg: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(match_msg_to_ignore) open_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(ignore_msg) self.assertEqual(open_ob_row, ([], [])) def test_buy_diff_message(self): order_books: Dict[str, OrderBook] = self.order_book_tracker.order_books test_order_book: OrderBook = order_books[test_trading_pair] test_active_order_tracker = self.order_book_tracker._active_order_trackers[test_trading_pair] # receive open buy message to be added to active orders order_id = "abc" side = "buy" price = 1337.0 open_size = 100.0 open_sequence = 1 open_message_dict: Dict[str, Any] = { "type": "open", "time": "2014-11-07T08:19:27.028459Z", "product_id": test_trading_pair, "sequence": open_sequence, "order_id": order_id, "price": str(price), "remaining_size": str(open_size), "side": side } open_message: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(open_message_dict) open_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(open_message) self.assertEqual(open_ob_row[0], [OrderBookRow(price, open_size, open_sequence)]) # receive change message change_size = 50.0 change_sequence = 2 change_message_dict: Dict[str, Any] = { "type": "change", "time": "2014-11-07T08:19:27.028459Z", "sequence": change_sequence, "order_id": order_id, "product_id": test_trading_pair, "new_size": str(change_size), "old_size": "100.0", "price": str(price), "side": side } change_message: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(change_message_dict) change_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(change_message) self.assertEqual(change_ob_row[0], [OrderBookRow(price, change_size, change_sequence)]) # receive match message match_size = 30.0 match_sequence = 3 match_message_dict: Dict[str, Any] = { "type": "match", "trade_id": 10, "sequence": match_sequence, "maker_order_id": order_id, "taker_order_id": "132fb6ae-456b-4654-b4e0-d681ac05cea1", "time": "2014-11-07T08:19:27.028459Z", "product_id": test_trading_pair, "size": str(match_size), "price": str(price), "side": side } match_message: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(match_message_dict) match_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(match_message) self.assertEqual(match_ob_row[0], [OrderBookRow(price, change_size - match_size, match_sequence)]) # receive done message done_size = 0.0 done_sequence = 4 done_message_dict: Dict[str, Any] = { "type": "done", "time": "2014-11-07T08:19:27.028459Z", "product_id": test_trading_pair, "sequence": done_sequence, "price": str(price), "order_id": order_id, "reason": "filled", "side": side, "remaining_size": "0" } done_message: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(done_message_dict) done_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(done_message) self.assertEqual(done_ob_row[0], [OrderBookRow(price, done_size, done_sequence)]) def test_sell_diff_message(self): order_books: Dict[str, OrderBook] = self.order_book_tracker.order_books test_order_book: OrderBook = order_books[test_trading_pair] test_active_order_tracker = self.order_book_tracker._active_order_trackers[test_trading_pair] # receive open sell message to be added to active orders order_id = "abc" side = "sell" price = 1337.0 open_size = 100.0 open_sequence = 1 open_message_dict: Dict[str, Any] = { "type": "open", "time": "2014-11-07T08:19:27.028459Z", "product_id": test_trading_pair, "sequence": open_sequence, "order_id": order_id, "price": str(price), "remaining_size": str(open_size), "side": side } open_message: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(open_message_dict) open_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(open_message) self.assertEqual(open_ob_row[1], [OrderBookRow(price, open_size, open_sequence)]) # receive open sell message to be added to active orders order_id_2 = "def" side = "sell" price = 1337.0 open_size_2 = 100.0 open_sequence_2 = 2 open_message_dict_2: Dict[str, Any] = { "type": "open", "time": "2014-11-07T08:19:27.028459Z", "product_id": test_trading_pair, "sequence": open_sequence_2, "order_id": order_id_2, "price": str(price), "remaining_size": str(open_size), "side": side } open_message: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(open_message_dict_2) open_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(open_message) self.assertEqual(open_ob_row[1], [OrderBookRow(price, open_size + open_size_2, open_sequence_2)]) # receive change message change_size = 50.0 change_sequence = 3 change_message_dict: Dict[str, Any] = { "type": "change", "time": "2014-11-07T08:19:27.028459Z", "sequence": change_sequence, "order_id": order_id, "product_id": test_trading_pair, "new_size": str(change_size), "old_size": "100.0", "price": str(price), "side": side } change_message: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(change_message_dict) change_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(change_message) self.assertEqual(change_ob_row[1], [OrderBookRow(price, change_size + open_size_2, change_sequence)]) # receive match message match_size = 30.0 match_sequence = 4 match_message_dict: Dict[str, Any] = { "type": "match", "trade_id": 10, "sequence": match_sequence, "maker_order_id": order_id, "taker_order_id": "132fb6ae-456b-4654-b4e0-d681ac05cea1", "time": "2014-11-07T08:19:27.028459Z", "product_id": test_trading_pair, "size": str(match_size), "price": str(price), "side": side } match_message: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(match_message_dict) match_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(match_message) self.assertEqual(match_ob_row[1], [OrderBookRow(price, change_size - match_size + open_size_2, match_sequence)]) # receive done message done_size = 0.0 done_sequence = 5 done_message_dict: Dict[str, Any] = { "type": "done", "time": "2014-11-07T08:19:27.028459Z", "product_id": test_trading_pair, "sequence": done_sequence, "price": str(price), "order_id": order_id, "reason": "filled", "side": side, "remaining_size": "0" } done_message: CoinbaseProOrderBookMessage = test_order_book.diff_message_from_exchange(done_message_dict) done_ob_row: OrderBookRow = test_active_order_tracker.convert_diff_message_to_order_book_row(done_message) self.assertEqual(done_ob_row[1], [OrderBookRow(price, done_size + open_size_2, done_sequence)]) def main(): logging.basicConfig(level=logging.INFO) unittest.main() if __name__ == "__main__": main()
[ "hummingbot.market.coinbase_pro.coinbase_pro_order_book_tracker.CoinbaseProOrderBookTracker", "hummingbot.core.data_type.order_book_row.OrderBookRow" ]
[((10384, 10423), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (10403, 10423), False, 'import logging\n'), ((10428, 10443), 'unittest.main', 'unittest.main', ([], {}), '()\n', (10441, 10443), False, 'import unittest\n'), ((98, 125), 'os.path.join', 'join', (['__file__', '"""../../../"""'], {}), "(__file__, '../../../')\n", (102, 125), False, 'from os.path import join, realpath\n'), ((885, 996), 'hummingbot.market.coinbase_pro.coinbase_pro_order_book_tracker.CoinbaseProOrderBookTracker', 'CoinbaseProOrderBookTracker', (['OrderBookTrackerDataSourceType.EXCHANGE_API'], {'trading_pairs': '[test_trading_pair]'}), '(OrderBookTrackerDataSourceType.EXCHANGE_API,\n trading_pairs=[test_trading_pair])\n', (912, 996), False, 'from hummingbot.market.coinbase_pro.coinbase_pro_order_book_tracker import CoinbaseProOrderBookTracker\n'), ((3239, 3284), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (['price', 'open_size', 'open_sequence'], {}), '(price, open_size, open_sequence)\n', (3251, 3284), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((4058, 4107), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (['price', 'change_size', 'change_sequence'], {}), '(price, change_size, change_sequence)\n', (4070, 4107), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((4932, 4993), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (['price', '(change_size - match_size)', 'match_sequence'], {}), '(price, change_size - match_size, match_sequence)\n', (4944, 4993), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((5732, 5777), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (['price', 'done_size', 'done_sequence'], {}), '(price, done_size, done_sequence)\n', (5744, 5777), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((6885, 6930), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (['price', 'open_size', 'open_sequence'], {}), '(price, open_size, open_sequence)\n', (6897, 6930), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((7771, 7832), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (['price', '(open_size + open_size_2)', 'open_sequence_2'], {}), '(price, open_size + open_size_2, open_sequence_2)\n', (7783, 7832), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((8602, 8665), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (['price', '(change_size + open_size_2)', 'change_sequence'], {}), '(price, change_size + open_size_2, change_sequence)\n', (8614, 8665), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((9490, 9565), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (['price', '(change_size - match_size + open_size_2)', 'match_sequence'], {}), '(price, change_size - match_size + open_size_2, match_sequence)\n', (9502, 9565), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n'), ((10304, 10363), 'hummingbot.core.data_type.order_book_row.OrderBookRow', 'OrderBookRow', (['price', '(done_size + open_size_2)', 'done_sequence'], {}), '(price, done_size + open_size_2, done_sequence)\n', (10316, 10363), False, 'from hummingbot.core.data_type.order_book_row import OrderBookRow\n')]
#!/usr/bin/env python import sys import asyncio import unittest import aiohttp import conf import logging import ujson from os.path import join, realpath from typing import Dict, Any from hummingbot.connector.exchange.gate_io.gate_io_auth import GateIoAuth from hummingbot.connector.exchange.gate_io.gate_io_utils import aiohttp_response_with_errors from hummingbot.connector.exchange.gate_io.gate_io_websocket import GateIoWebsocket from hummingbot.logger.struct_logger import METRICS_LOG_LEVEL from hummingbot.connector.exchange.gate_io.gate_io_constants import Constants sys.path.insert(0, realpath(join(__file__, "../../../../../"))) logging.basicConfig(level=METRICS_LOG_LEVEL) class TestAuth(unittest.TestCase): @classmethod def setUpClass(cls): cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() api_key = conf.gate_io_api_key secret_key = conf.gate_io_secret_key cls.auth = GateIoAuth(api_key, secret_key) async def rest_auth(self) -> Dict[Any, Any]: endpoint = Constants.ENDPOINT['USER_BALANCES'] headers = self.auth.get_headers("GET", f"{Constants.REST_URL_AUTH}/{endpoint}", None) http_client = aiohttp.ClientSession() response = await http_client.get(f"{Constants.REST_URL}/{endpoint}", headers=headers) await http_client.close() return await response.json() async def rest_auth_post(self) -> Dict[Any, Any]: endpoint = Constants.ENDPOINT['ORDER_CREATE'] http_client = aiohttp.ClientSession() order_params = ujson.dumps({ 'currency_pair': 'ETH_BTC', 'type': 'limit', 'side': 'buy', 'amount': '0.00000001', 'price': '0.0000001', }) headers = self.auth.get_headers("POST", f"{Constants.REST_URL_AUTH}/{endpoint}", order_params) http_status, response, request_errors = await aiohttp_response_with_errors(http_client.request(method='POST', url=f"{Constants.REST_URL}/{endpoint}", headers=headers, data=order_params)) await http_client.close() return response async def ws_auth(self) -> Dict[Any, Any]: ws = GateIoWebsocket(self.auth) await ws.connect() await ws.subscribe(Constants.WS_SUB["USER_BALANCE"]) async for response in ws.on_message(): if ws.is_subscribed: return True return False def test_rest_auth(self): result = self.ev_loop.run_until_complete(self.rest_auth()) if len(result) == 0 or "currency" not in result[0].keys(): print(f"Unexpected response for API call: {result}") assert "currency" in result[0].keys() def test_rest_auth_post(self): result = self.ev_loop.run_until_complete(self.rest_auth_post()) if "message" not in result.keys(): print(f"Unexpected response for API call: {result}") assert "message" in result.keys() assert "Your order size 0.00000001 is too small" in result['message'] def test_ws_auth(self): response = self.ev_loop.run_until_complete(self.ws_auth()) assert response is True
[ "hummingbot.connector.exchange.gate_io.gate_io_websocket.GateIoWebsocket", "hummingbot.connector.exchange.gate_io.gate_io_auth.GateIoAuth" ]
[((639, 683), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'METRICS_LOG_LEVEL'}), '(level=METRICS_LOG_LEVEL)\n', (658, 683), False, 'import logging\n'), ((603, 636), 'os.path.join', 'join', (['__file__', '"""../../../../../"""'], {}), "(__file__, '../../../../../')\n", (607, 636), False, 'from os.path import join, realpath\n'), ((808, 832), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (830, 832), False, 'import asyncio\n'), ((936, 967), 'hummingbot.connector.exchange.gate_io.gate_io_auth.GateIoAuth', 'GateIoAuth', (['api_key', 'secret_key'], {}), '(api_key, secret_key)\n', (946, 967), False, 'from hummingbot.connector.exchange.gate_io.gate_io_auth import GateIoAuth\n'), ((1189, 1212), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (1210, 1212), False, 'import aiohttp\n'), ((1509, 1532), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (1530, 1532), False, 'import aiohttp\n'), ((1556, 1679), 'ujson.dumps', 'ujson.dumps', (["{'currency_pair': 'ETH_BTC', 'type': 'limit', 'side': 'buy', 'amount':\n '0.00000001', 'price': '0.0000001'}"], {}), "({'currency_pair': 'ETH_BTC', 'type': 'limit', 'side': 'buy',\n 'amount': '0.00000001', 'price': '0.0000001'})\n", (1567, 1679), False, 'import ujson\n'), ((2370, 2396), 'hummingbot.connector.exchange.gate_io.gate_io_websocket.GateIoWebsocket', 'GateIoWebsocket', (['self.auth'], {}), '(self.auth)\n', (2385, 2396), False, 'from hummingbot.connector.exchange.gate_io.gate_io_websocket import GateIoWebsocket\n')]
#!/usr/bin/env python from os.path import join, realpath import sys; sys.path.insert(0, realpath(join(__file__, "../../../../../"))) from hummingbot.connector.exchange.dydx.dydx_api_order_book_data_source import DydxAPIOrderBookDataSource import asyncio import aiohttp import logging from typing import ( Dict, Optional, Any, # List, ) # import pandas as pd import unittest trading_pairs = ["WETH-DAI"] class DydxAPIOrderBookDataSourceUnitTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() cls.order_book_data_source: DydxAPIOrderBookDataSource = DydxAPIOrderBookDataSource(trading_pairs) def run_async(self, task): return self.ev_loop.run_until_complete(task) async def get_snapshot(self): async with aiohttp.ClientSession() as client: trading_pair: str = trading_pairs[0] try: snapshot: Dict[str, Any] = await self.order_book_data_source.get_snapshot(client, trading_pair, 1000) return snapshot except Exception: return None def test_get_snapshot(self): snapshot: Optional[Dict[str, Any]] = self.run_async(self.get_snapshot()) self.assertIsNotNone(snapshot) self.assertIn(snapshot["market"], trading_pairs) def main(): logging.basicConfig(level=logging.INFO) unittest.main() if __name__ == "__main__": main()
[ "hummingbot.connector.exchange.dydx.dydx_api_order_book_data_source.DydxAPIOrderBookDataSource" ]
[((1380, 1419), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (1399, 1419), False, 'import logging\n'), ((1424, 1439), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1437, 1439), False, 'import unittest\n'), ((97, 130), 'os.path.join', 'join', (['__file__', '"""../../../../../"""'], {}), "(__file__, '../../../../../')\n", (101, 130), False, 'from os.path import join, realpath\n'), ((571, 595), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (593, 595), False, 'import asyncio\n'), ((661, 702), 'hummingbot.connector.exchange.dydx.dydx_api_order_book_data_source.DydxAPIOrderBookDataSource', 'DydxAPIOrderBookDataSource', (['trading_pairs'], {}), '(trading_pairs)\n', (687, 702), False, 'from hummingbot.connector.exchange.dydx.dydx_api_order_book_data_source import DydxAPIOrderBookDataSource\n'), ((842, 865), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (863, 865), False, 'import aiohttp\n')]
from datetime import datetime from unittest import TestCase from unittest.mock import MagicMock from hummingbot.strategy.conditional_execution_state import RunAlwaysExecutionState, RunInTimeConditionalExecutionState class RunAlwaysExecutionStateTests(TestCase): def test_always_process_tick(self): strategy = MagicMock() state = RunAlwaysExecutionState() state.process_tick(datetime.now, strategy) strategy.process_tick.assert_called() class RunInTimeSpanExecutionStateTests(TestCase): def setUp(self) -> None: super().setUp() self.debug_logs = [] def debug(self, message: str): self.debug_logs.append(message) def test_process_tick_when_current_time_in_span(self): start_timestamp = datetime.fromisoformat("2021-06-22 09:00:00") end_timestamp = datetime.fromisoformat("2021-06-22 10:00:00") state = RunInTimeConditionalExecutionState(start_timestamp=start_timestamp, end_timestamp=end_timestamp) strategy = MagicMock() strategy.logger().debug.side_effect = self.debug state.process_tick(datetime.fromisoformat("2021-06-22 08:59:59").timestamp(), strategy) strategy.process_tick.assert_not_called() self.assertEqual(len(self.debug_logs), 1) self.assertEqual(self.debug_logs[0], "Time span execution: tick will not be processed " f"(executing between {start_timestamp} and {end_timestamp})") state.process_tick(datetime.fromisoformat("2021-06-22 09:00:00").timestamp(), strategy) strategy.process_tick.assert_called() state.process_tick(datetime.fromisoformat("2021-06-22 09:00:00").timestamp(), strategy) strategy.process_tick.assert_called() strategy.process_tick.reset_mock() state.process_tick(datetime.fromisoformat("2021-06-22 10:00:01").timestamp(), strategy) strategy.process_tick.assert_not_called() self.assertEqual(len(self.debug_logs), 2) self.assertEqual(self.debug_logs[1], "Time span execution: tick will not be processed " f"(executing between {start_timestamp} and {end_timestamp})") state = RunInTimeConditionalExecutionState(start_timestamp=start_timestamp.time(), end_timestamp=end_timestamp.time()) state.process_tick(datetime.fromisoformat("2021-06-22 08:59:59").timestamp(), strategy) strategy.process_tick.assert_not_called() self.assertEqual(len(self.debug_logs), 3) self.assertEqual(self.debug_logs[0], "Time span execution: tick will not be processed " f"(executing between {start_timestamp} and {end_timestamp})") state.process_tick(datetime.fromisoformat("2021-06-22 09:00:00").timestamp(), strategy) strategy.process_tick.assert_called() state.process_tick(datetime.fromisoformat("2021-06-22 09:00:00").timestamp(), strategy) strategy.process_tick.assert_called() strategy.process_tick.reset_mock() state.process_tick(datetime.fromisoformat("2021-06-22 10:00:01").timestamp(), strategy) strategy.process_tick.assert_not_called() self.assertEqual(len(self.debug_logs), 4) self.assertEqual(self.debug_logs[1], "Time span execution: tick will not be processed " f"(executing between {start_timestamp} and {end_timestamp})") state.process_tick(datetime.fromisoformat("2021-06-30 08:59:59").timestamp(), strategy) strategy.process_tick.assert_not_called() self.assertEqual(len(self.debug_logs), 5) self.assertEqual(self.debug_logs[0], "Time span execution: tick will not be processed " f"(executing between {start_timestamp} and {end_timestamp})") state.process_tick(datetime.fromisoformat("2021-06-30 09:00:00").timestamp(), strategy) strategy.process_tick.assert_called() state.process_tick(datetime.fromisoformat("2021-06-30 09:00:00").timestamp(), strategy) strategy.process_tick.assert_called() strategy.process_tick.reset_mock() state.process_tick(datetime.fromisoformat("2021-06-30 10:00:01").timestamp(), strategy) strategy.process_tick.assert_not_called() self.assertEqual(len(self.debug_logs), 6) self.assertEqual(self.debug_logs[1], "Time span execution: tick will not be processed " f"(executing between {start_timestamp} and {end_timestamp})")
[ "hummingbot.strategy.conditional_execution_state.RunInTimeConditionalExecutionState", "hummingbot.strategy.conditional_execution_state.RunAlwaysExecutionState" ]
[((325, 336), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (334, 336), False, 'from unittest.mock import MagicMock\n'), ((353, 378), 'hummingbot.strategy.conditional_execution_state.RunAlwaysExecutionState', 'RunAlwaysExecutionState', ([], {}), '()\n', (376, 378), False, 'from hummingbot.strategy.conditional_execution_state import RunAlwaysExecutionState, RunInTimeConditionalExecutionState\n'), ((775, 820), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 09:00:00"""'], {}), "('2021-06-22 09:00:00')\n", (797, 820), False, 'from datetime import datetime\n'), ((845, 890), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 10:00:00"""'], {}), "('2021-06-22 10:00:00')\n", (867, 890), False, 'from datetime import datetime\n'), ((907, 1007), 'hummingbot.strategy.conditional_execution_state.RunInTimeConditionalExecutionState', 'RunInTimeConditionalExecutionState', ([], {'start_timestamp': 'start_timestamp', 'end_timestamp': 'end_timestamp'}), '(start_timestamp=start_timestamp,\n end_timestamp=end_timestamp)\n', (941, 1007), False, 'from hummingbot.strategy.conditional_execution_state import RunAlwaysExecutionState, RunInTimeConditionalExecutionState\n'), ((1024, 1035), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (1033, 1035), False, 'from unittest.mock import MagicMock\n'), ((1121, 1166), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 08:59:59"""'], {}), "('2021-06-22 08:59:59')\n", (1143, 1166), False, 'from datetime import datetime\n'), ((1521, 1566), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 09:00:00"""'], {}), "('2021-06-22 09:00:00')\n", (1543, 1566), False, 'from datetime import datetime\n'), ((1664, 1709), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 09:00:00"""'], {}), "('2021-06-22 09:00:00')\n", (1686, 1709), False, 'from datetime import datetime\n'), ((1850, 1895), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 10:00:01"""'], {}), "('2021-06-22 10:00:01')\n", (1872, 1895), False, 'from datetime import datetime\n'), ((2378, 2423), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 08:59:59"""'], {}), "('2021-06-22 08:59:59')\n", (2400, 2423), False, 'from datetime import datetime\n'), ((2778, 2823), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 09:00:00"""'], {}), "('2021-06-22 09:00:00')\n", (2800, 2823), False, 'from datetime import datetime\n'), ((2921, 2966), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 09:00:00"""'], {}), "('2021-06-22 09:00:00')\n", (2943, 2966), False, 'from datetime import datetime\n'), ((3107, 3152), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-22 10:00:01"""'], {}), "('2021-06-22 10:00:01')\n", (3129, 3152), False, 'from datetime import datetime\n'), ((3507, 3552), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-30 08:59:59"""'], {}), "('2021-06-30 08:59:59')\n", (3529, 3552), False, 'from datetime import datetime\n'), ((3907, 3952), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-30 09:00:00"""'], {}), "('2021-06-30 09:00:00')\n", (3929, 3952), False, 'from datetime import datetime\n'), ((4050, 4095), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-30 09:00:00"""'], {}), "('2021-06-30 09:00:00')\n", (4072, 4095), False, 'from datetime import datetime\n'), ((4236, 4281), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['"""2021-06-30 10:00:01"""'], {}), "('2021-06-30 10:00:01')\n", (4258, 4281), False, 'from datetime import datetime\n')]
import unittest import math import pandas as pd from hummingbot.core.clock import ( Clock, ClockMode ) from hummingbot.core.py_time_iterator import PyTimeIterator NaN = float("nan") class MockPyTimeIterator(PyTimeIterator): def __init__(self): super().__init__() self._mock_variable = None @property def mock_variable(self): return self._mock_variable def tick(self, timestamp: float): self._mock_variable = timestamp class PyTimeIteratorUnitTest(unittest.TestCase): start_timestamp: float = pd.Timestamp("2021-01-01", tz="UTC").timestamp() end_timestamp: float = pd.Timestamp("2022-01-01 01:00:00", tz="UTC").timestamp() tick_size: int = 10 def setUp(self): self.py_time_iterator = MockPyTimeIterator() self.clock = Clock(ClockMode.BACKTEST, self.tick_size, self.start_timestamp, self.end_timestamp) self.clock.add_iterator(self.py_time_iterator) def test_current_timestamp(self): # On initialization, current_timestamp should be NaN self.assertTrue(math.isnan(self.py_time_iterator.current_timestamp)) self.py_time_iterator.start(self.clock) self.clock.backtest_til(self.start_timestamp) self.assertEqual(self.start_timestamp, self.py_time_iterator.current_timestamp) def test_clock(self): # On initialization, clock should be None self.assertTrue(self.py_time_iterator.clock is None) self.py_time_iterator.start(self.clock) self.assertEqual(self.clock, self.py_time_iterator.clock) def test_start(self): self.py_time_iterator.start(self.clock) self.assertEqual(self.clock, self.py_time_iterator.clock) self.assertEqual(self.start_timestamp, self.py_time_iterator.current_timestamp) def test_stop(self): self.py_time_iterator.start(self.clock) self.assertEqual(self.clock, self.py_time_iterator.clock) self.assertEqual(self.start_timestamp, self.py_time_iterator.current_timestamp) self.py_time_iterator.stop(self.clock) self.assertTrue(math.isnan(self.py_time_iterator.current_timestamp)) self.assertTrue(self.py_time_iterator.clock is None) def test_tick(self): self.py_time_iterator.start(self.clock) self.assertEqual(self.start_timestamp, self.py_time_iterator.current_timestamp) # c_tick is called within Clock self.clock.backtest_til(self.start_timestamp + self.tick_size) self.assertEqual(self.start_timestamp + self.tick_size, self.py_time_iterator.current_timestamp) self.assertEqual(self.start_timestamp + self.tick_size, self.py_time_iterator.mock_variable)
[ "hummingbot.core.clock.Clock" ]
[((816, 904), 'hummingbot.core.clock.Clock', 'Clock', (['ClockMode.BACKTEST', 'self.tick_size', 'self.start_timestamp', 'self.end_timestamp'], {}), '(ClockMode.BACKTEST, self.tick_size, self.start_timestamp, self.\n end_timestamp)\n', (821, 904), False, 'from hummingbot.core.clock import Clock, ClockMode\n'), ((562, 598), 'pandas.Timestamp', 'pd.Timestamp', (['"""2021-01-01"""'], {'tz': '"""UTC"""'}), "('2021-01-01', tz='UTC')\n", (574, 598), True, 'import pandas as pd\n'), ((638, 683), 'pandas.Timestamp', 'pd.Timestamp', (['"""2022-01-01 01:00:00"""'], {'tz': '"""UTC"""'}), "('2022-01-01 01:00:00', tz='UTC')\n", (650, 683), True, 'import pandas as pd\n'), ((1079, 1130), 'math.isnan', 'math.isnan', (['self.py_time_iterator.current_timestamp'], {}), '(self.py_time_iterator.current_timestamp)\n', (1089, 1130), False, 'import math\n'), ((2105, 2156), 'math.isnan', 'math.isnan', (['self.py_time_iterator.current_timestamp'], {}), '(self.py_time_iterator.current_timestamp)\n', (2115, 2156), False, 'import math\n')]
""" hummingbot.client.config.config_var defines ConfigVar. One of its parameters is a validator, a function that takes a string and determines whether it is valid input. This file contains many validator functions that are used by various hummingbot ConfigVars. """ from datetime import datetime from decimal import Decimal from typing import Optional def validate_exchange(value: str) -> Optional[str]: """ Restrict valid exchanges to the exchange file names """ from hummingbot.client.settings import EXCHANGES if value not in EXCHANGES: return f"Invalid exchange, please choose value from {EXCHANGES}" def validate_derivative(value: str) -> Optional[str]: """ restrict valid derivatives to the derivative file names """ from hummingbot.client.settings import DERIVATIVES if value not in DERIVATIVES: return f"Invalid derivative, please choose value from {DERIVATIVES}" def validate_connector(value: str) -> Optional[str]: """ Restrict valid derivatives to the connector file names """ from hummingbot.client.settings import CONNECTOR_SETTINGS if value not in CONNECTOR_SETTINGS: return f"Invalid connector, please choose value from {CONNECTOR_SETTINGS.keys()}" def validate_strategy(value: str) -> Optional[str]: """ Restrict valid derivatives to the strategy file names """ from hummingbot.client.settings import STRATEGIES if value not in STRATEGIES: return f"Invalid strategy, please choose value from {STRATEGIES}" def validate_decimal(value: str, min_value: Decimal = None, max_value: Decimal = None, inclusive=True) -> Optional[str]: """ Parse a decimal value from a string. This value can also be clamped. """ try: decimal_value = Decimal(value) except Exception: return f"{value} is not in decimal format." if inclusive: if min_value is not None and max_value is not None: if not (Decimal(str(min_value)) <= decimal_value <= Decimal(str(max_value))): return f"Value must be between {min_value} and {max_value}." elif min_value is not None and not decimal_value >= Decimal(str(min_value)): return f"Value cannot be less than {min_value}." elif max_value is not None and not decimal_value <= Decimal(str(max_value)): return f"Value cannot be more than {max_value}." else: if min_value is not None and max_value is not None: if not (Decimal(str(min_value)) < decimal_value < Decimal(str(max_value))): return f"Value must be between {min_value} and {max_value} (exclusive)." elif min_value is not None and not decimal_value > Decimal(str(min_value)): return f"Value must be more than {min_value}." elif max_value is not None and not decimal_value < Decimal(str(max_value)): return f"Value must be less than {max_value}." def validate_market_trading_pair(market: str, value: str) -> Optional[str]: """ Since trading pair validation and autocomplete are UI optimizations that do not impact bot performances, in case of network issues or slow wifi, this check returns true and does not prevent users from proceeding, """ from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher trading_pair_fetcher: TradingPairFetcher = TradingPairFetcher.get_instance() if trading_pair_fetcher.ready: trading_pairs = trading_pair_fetcher.trading_pairs.get(market, []) if len(trading_pairs) == 0: return None elif value not in trading_pairs: return f"{value} is not an active market on {market}." def validate_bool(value: str) -> Optional[str]: """ Permissively interpret a string as a boolean """ valid_values = ('true', 'yes', 'y', 'false', 'no', 'n') if value.lower() not in valid_values: return f"Invalid value, please choose value from {valid_values}" def validate_int(value: str, min_value: int = None, max_value: int = None, inclusive=True) -> Optional[str]: """ Parse an int value from a string. This value can also be clamped. """ try: int_value = int(value) except Exception: return f"{value} is not in integer format." if inclusive: if min_value is not None and max_value is not None: if not (min_value <= int_value <= max_value): return f"Value must be between {min_value} and {max_value}." elif min_value is not None and not int_value >= min_value: return f"Value cannot be less than {min_value}." elif max_value is not None and not int_value <= max_value: return f"Value cannot be more than {max_value}." else: if min_value is not None and max_value is not None: if not (min_value < int_value < max_value): return f"Value must be between {min_value} and {max_value} (exclusive)." elif min_value is not None and not int_value > min_value: return f"Value must be more than {min_value}." elif max_value is not None and not int_value < max_value: return f"Value must be less than {max_value}." def validate_timestamp_iso_string(value: str) -> Optional[str]: try: datetime.fromisoformat(value) except ValueError: return "Incorrect date time format (expected is YYYY-MM-DD HH:MM:SS)"
[ "hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher.get_instance", "hummingbot.client.settings.CONNECTOR_SETTINGS.keys" ]
[((3387, 3420), 'hummingbot.core.utils.trading_pair_fetcher.TradingPairFetcher.get_instance', 'TradingPairFetcher.get_instance', ([], {}), '()\n', (3418, 3420), False, 'from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher\n'), ((1788, 1802), 'decimal.Decimal', 'Decimal', (['value'], {}), '(value)\n', (1795, 1802), False, 'from decimal import Decimal\n'), ((5317, 5346), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['value'], {}), '(value)\n', (5339, 5346), False, 'from datetime import datetime\n'), ((1227, 1252), 'hummingbot.client.settings.CONNECTOR_SETTINGS.keys', 'CONNECTOR_SETTINGS.keys', ([], {}), '()\n', (1250, 1252), False, 'from hummingbot.client.settings import CONNECTOR_SETTINGS\n')]
import asyncio import json import unittest from typing import Any, List, Dict from unittest.mock import patch, AsyncMock import pandas as pd from hummingbot.connector.derivative.binance_perpetual.binance_perpetual_derivative import BinancePerpetualDerivative from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant class BinancePerpetualDerivativeUnitTest(unittest.TestCase): start_timestamp: float = pd.Timestamp("2021-01-01", tz="UTC").timestamp() @classmethod def setUpClass(cls) -> None: super().setUpClass() cls.base_asset = "COINALPHA" cls.quote_asset = "HBOT" cls.trading_pair = f"{cls.base_asset}-{cls.quote_asset}" cls.symbol = f"{cls.base_asset}{cls.quote_asset}" @patch("hummingbot.connector.exchange.binance.binance_time.BinanceTime.start") def setUp(self, mocked_binance_time_start) -> None: super().setUp() self.ev_loop = asyncio.get_event_loop() self.api_responses = asyncio.Queue() self.ws_sent_messages = [] self.ws_incoming_messages = asyncio.Queue() self.resume_test_event = asyncio.Event() self._finalMessage = 'FinalDummyMessage' self.exchange = BinancePerpetualDerivative( binance_perpetual_api_key="testAPIKey", binance_perpetual_api_secret="testSecret", trading_pairs=[self.trading_pair], ) self.mocking_assistant = NetworkMockingAssistant() async def _get_next_api_response(self): message = await self.api_responses.get() self.api_responses.task_done() return message def _set_mock_response(self, mock_api, status: int, json_data: Any, text_data: str = ""): self.api_responses.put_nowait(json_data) mock_api.return_value.status = status mock_api.return_value.json.side_effect = self._get_next_api_response mock_api.return_value.text = AsyncMock(return_value=text_data) async def _await_all_api_responses_delivered(self): await self.api_responses.join() def _get_position_risk_api_endpoint_single_position_list(self) -> List[Dict[str, Any]]: positions = [ { "symbol": self.symbol, "positionAmt": "1", "entryPrice": "10", "markPrice": "11", "unRealizedProfit": "1", "liquidationPrice": "100", "leverage": "1", "maxNotionalValue": "9", "marginType": "cross", "isolatedMargin": "0", "isAutoAddMargin": "false", "positionSide": "BOTH", "notional": "11", "isolatedWallet": "0", "updateTime": int(self.start_timestamp), } ] return positions def _create_ws_mock(self): ws = AsyncMock() ws.send.side_effect = lambda sent_message: self.ws_sent_messages.append(sent_message) ws.recv.side_effect = self._get_next_ws_received_message return ws async def _get_next_ws_received_message(self): message = await self.ws_incoming_messages.get() if json.loads(message) == self._finalMessage: self.resume_test_event.set() return message def _get_account_update_ws_event_single_position_dict(self) -> Dict[str, Any]: account_update = { "e": "ACCOUNT_UPDATE", "E": 1564745798939, "T": 1564745798938, "a": { "m": "POSITION", "B": [ { "a": "USDT", "wb": "122624.12345678", "cw": "100.12345678", "bc": "50.12345678" }, ], "P": [ { "s": self.symbol, "pa": "1", "ep": "10", "cr": "200", "up": "1", "mt": "cross", "iw": "0.00000000", "ps": "BOTH" }, ] } } return account_update @patch("aiohttp.ClientSession.request", new_callable=AsyncMock) def test_existing_account_position_detected_on_positions_update(self, req_mock): positions = self._get_position_risk_api_endpoint_single_position_list() self.mocking_assistant.configure_http_request_mock(req_mock) self.mocking_assistant.add_http_response(req_mock, 200, positions) task = self.ev_loop.create_task(self.exchange._update_positions()) self.ev_loop.run_until_complete(task) self.assertEqual(len(self.exchange.account_positions), 1) pos = list(self.exchange.account_positions.values())[0] self.assertEqual(pos.trading_pair.replace("-", ""), self.symbol) @patch("aiohttp.ClientSession.request", new_callable=AsyncMock) def test_account_position_updated_on_positions_update(self, req_mock): positions = self._get_position_risk_api_endpoint_single_position_list() self.mocking_assistant.configure_http_request_mock(req_mock) self.mocking_assistant.add_http_response(req_mock, 200, positions) task = self.ev_loop.create_task(self.exchange._update_positions()) self.ev_loop.run_until_complete(task) self.assertEqual(len(self.exchange.account_positions), 1) pos = list(self.exchange.account_positions.values())[0] self.assertEqual(pos.amount, 1) positions[0]["positionAmt"] = "2" self.mocking_assistant.add_http_response(req_mock, 200, positions) task = self.ev_loop.create_task(self.exchange._update_positions()) self.ev_loop.run_until_complete(task) pos = list(self.exchange.account_positions.values())[0] self.assertEqual(pos.amount, 2) @patch("aiohttp.ClientSession.request", new_callable=AsyncMock) def test_new_account_position_detected_on_positions_update(self, req_mock): self.mocking_assistant.configure_http_request_mock(req_mock) self.mocking_assistant.add_http_response(req_mock, 200, []) task = self.ev_loop.create_task(self.exchange._update_positions()) self.ev_loop.run_until_complete(task) self.assertEqual(len(self.exchange.account_positions), 0) positions = self._get_position_risk_api_endpoint_single_position_list() self.mocking_assistant.add_http_response(req_mock, 200, positions) task = self.ev_loop.create_task(self.exchange._update_positions()) self.ev_loop.run_until_complete(task) self.assertEqual(len(self.exchange.account_positions), 1) @patch("aiohttp.ClientSession.request", new_callable=AsyncMock) def test_closed_account_position_removed_on_positions_update(self, req_mock): positions = self._get_position_risk_api_endpoint_single_position_list() self.mocking_assistant.configure_http_request_mock(req_mock) self.mocking_assistant.add_http_response(req_mock, 200, positions) task = self.ev_loop.create_task(self.exchange._update_positions()) self.ev_loop.run_until_complete(task) self.assertEqual(len(self.exchange.account_positions), 1) positions[0]["positionAmt"] = "0" self.mocking_assistant.add_http_response(req_mock, 200, positions) task = self.ev_loop.create_task(self.exchange._update_positions()) self.ev_loop.run_until_complete(task) self.assertEqual(len(self.exchange.account_positions), 0) @patch("aiohttp.ClientSession.request", new_callable=AsyncMock) @patch("websockets.connect", new_callable=AsyncMock) @patch("aiohttp.ClientSession.post", new_callable=AsyncMock) def test_new_account_position_detected_on_stream_event(self, post_mock, ws_connect_mock, req_mock): self.mocking_assistant.configure_http_request_mock(post_mock) self.mocking_assistant.add_http_response(post_mock, 200, {"listenKey": "someListenKey"}) ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() self.ev_loop.create_task(self.exchange._user_stream_tracker.start()) self.assertEqual(len(self.exchange.account_positions), 0) account_update = self._get_account_update_ws_event_single_position_dict() self.mocking_assistant.add_websocket_text_message(ws_connect_mock.return_value, json.dumps(account_update)) positions = self._get_position_risk_api_endpoint_single_position_list() self.mocking_assistant.configure_http_request_mock(req_mock) self.mocking_assistant.add_http_response(req_mock, 200, positions) self.ev_loop.create_task(self.exchange._user_stream_event_listener()) asyncio.get_event_loop().run_until_complete(asyncio.sleep(0.3)) self.assertEqual(len(self.exchange.account_positions), 1) @patch("aiohttp.ClientSession.request", new_callable=AsyncMock) @patch("websockets.connect", new_callable=AsyncMock) @patch("aiohttp.ClientSession.post", new_callable=AsyncMock) def test_account_position_updated_on_stream_event(self, post_mock, ws_connect_mock, req_mock): positions = self._get_position_risk_api_endpoint_single_position_list() self.mocking_assistant.configure_http_request_mock(req_mock) self.mocking_assistant.add_http_response(req_mock, 200, positions) task = self.ev_loop.create_task(self.exchange._update_positions()) self.ev_loop.run_until_complete(task) self.mocking_assistant.configure_http_request_mock(post_mock) self.mocking_assistant.add_http_response(post_mock, 200, {"listenKey": "someListenKey"}) ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() self.ev_loop.create_task(self.exchange._user_stream_tracker.start()) self.ev_loop.run_until_complete(self._await_all_api_responses_delivered()) self.assertEqual(len(self.exchange.account_positions), 1) pos = list(self.exchange.account_positions.values())[0] self.assertEqual(pos.amount, 1) account_update = self._get_account_update_ws_event_single_position_dict() account_update["a"]["P"][0]["pa"] = 2 self.mocking_assistant.add_websocket_text_message(ws_connect_mock.return_value, json.dumps(account_update)) self.ev_loop.create_task(self.exchange._user_stream_event_listener()) self.ev_loop.run_until_complete(asyncio.sleep(0.3)) self.assertEqual(len(self.exchange.account_positions), 1) pos = list(self.exchange.account_positions.values())[0] self.assertEqual(pos.amount, 2) @patch("aiohttp.ClientSession.request", new_callable=AsyncMock) @patch("websockets.connect", new_callable=AsyncMock) @patch("aiohttp.ClientSession.post", new_callable=AsyncMock) def test_closed_account_position_removed_on_stream_event(self, post_mock, ws_connect_mock, req_mock): positions = self._get_position_risk_api_endpoint_single_position_list() self.mocking_assistant.configure_http_request_mock(req_mock) self.mocking_assistant.add_http_response(req_mock, 200, positions) task = self.ev_loop.create_task(self.exchange._update_positions()) self.ev_loop.run_until_complete(task) self.mocking_assistant.configure_http_request_mock(post_mock) self.mocking_assistant.add_http_response(post_mock, 200, {"listenKey": "someListenKey"}) ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock() self.ev_loop.create_task(self.exchange._user_stream_tracker.start()) self.ev_loop.run_until_complete(self._await_all_api_responses_delivered()) self.assertEqual(len(self.exchange.account_positions), 1) account_update = self._get_account_update_ws_event_single_position_dict() account_update["a"]["P"][0]["pa"] = 0 self.mocking_assistant.add_websocket_text_message(ws_connect_mock.return_value, json.dumps(account_update)) self.ev_loop.create_task(self.exchange._user_stream_event_listener()) self.ev_loop.run_until_complete(asyncio.sleep(0.3)) self.assertEqual(len(self.exchange.account_positions), 0)
[ "hummingbot.connector.derivative.binance_perpetual.binance_perpetual_derivative.BinancePerpetualDerivative" ]
[((769, 846), 'unittest.mock.patch', 'patch', (['"""hummingbot.connector.exchange.binance.binance_time.BinanceTime.start"""'], {}), "('hummingbot.connector.exchange.binance.binance_time.BinanceTime.start')\n", (774, 846), False, 'from unittest.mock import patch, AsyncMock\n'), ((4285, 4347), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.request"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.request', new_callable=AsyncMock)\n", (4290, 4347), False, 'from unittest.mock import patch, AsyncMock\n'), ((4989, 5051), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.request"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.request', new_callable=AsyncMock)\n", (4994, 5051), False, 'from unittest.mock import patch, AsyncMock\n'), ((5993, 6055), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.request"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.request', new_callable=AsyncMock)\n", (5998, 6055), False, 'from unittest.mock import patch, AsyncMock\n'), ((6811, 6873), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.request"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.request', new_callable=AsyncMock)\n", (6816, 6873), False, 'from unittest.mock import patch, AsyncMock\n'), ((7680, 7742), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.request"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.request', new_callable=AsyncMock)\n", (7685, 7742), False, 'from unittest.mock import patch, AsyncMock\n'), ((7748, 7799), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (7753, 7799), False, 'from unittest.mock import patch, AsyncMock\n'), ((7805, 7864), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.post"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.post', new_callable=AsyncMock)\n", (7810, 7864), False, 'from unittest.mock import patch, AsyncMock\n'), ((9015, 9077), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.request"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.request', new_callable=AsyncMock)\n", (9020, 9077), False, 'from unittest.mock import patch, AsyncMock\n'), ((9083, 9134), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (9088, 9134), False, 'from unittest.mock import patch, AsyncMock\n'), ((9140, 9199), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.post"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.post', new_callable=AsyncMock)\n", (9145, 9199), False, 'from unittest.mock import patch, AsyncMock\n'), ((10790, 10852), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.request"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.request', new_callable=AsyncMock)\n", (10795, 10852), False, 'from unittest.mock import patch, AsyncMock\n'), ((10858, 10909), 'unittest.mock.patch', 'patch', (['"""websockets.connect"""'], {'new_callable': 'AsyncMock'}), "('websockets.connect', new_callable=AsyncMock)\n", (10863, 10909), False, 'from unittest.mock import patch, AsyncMock\n'), ((10915, 10974), 'unittest.mock.patch', 'patch', (['"""aiohttp.ClientSession.post"""'], {'new_callable': 'AsyncMock'}), "('aiohttp.ClientSession.post', new_callable=AsyncMock)\n", (10920, 10974), False, 'from unittest.mock import patch, AsyncMock\n'), ((950, 974), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (972, 974), False, 'import asyncio\n'), ((1005, 1020), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (1018, 1020), False, 'import asyncio\n'), ((1093, 1108), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (1106, 1108), False, 'import asyncio\n'), ((1142, 1157), 'asyncio.Event', 'asyncio.Event', ([], {}), '()\n', (1155, 1157), False, 'import asyncio\n'), ((1232, 1385), 'hummingbot.connector.derivative.binance_perpetual.binance_perpetual_derivative.BinancePerpetualDerivative', 'BinancePerpetualDerivative', ([], {'binance_perpetual_api_key': '"""testAPIKey"""', 'binance_perpetual_api_secret': '"""testSecret"""', 'trading_pairs': '[self.trading_pair]'}), "(binance_perpetual_api_key='testAPIKey',\n binance_perpetual_api_secret='testSecret', trading_pairs=[self.\n trading_pair])\n", (1258, 1385), False, 'from hummingbot.connector.derivative.binance_perpetual.binance_perpetual_derivative import BinancePerpetualDerivative\n'), ((1458, 1483), 'test.hummingbot.connector.network_mocking_assistant.NetworkMockingAssistant', 'NetworkMockingAssistant', ([], {}), '()\n', (1481, 1483), False, 'from test.hummingbot.connector.network_mocking_assistant import NetworkMockingAssistant\n'), ((1944, 1977), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {'return_value': 'text_data'}), '(return_value=text_data)\n', (1953, 1977), False, 'from unittest.mock import patch, AsyncMock\n'), ((2894, 2905), 'unittest.mock.AsyncMock', 'AsyncMock', ([], {}), '()\n', (2903, 2905), False, 'from unittest.mock import patch, AsyncMock\n'), ((441, 477), 'pandas.Timestamp', 'pd.Timestamp', (['"""2021-01-01"""'], {'tz': '"""UTC"""'}), "('2021-01-01', tz='UTC')\n", (453, 477), True, 'import pandas as pd\n'), ((3202, 3221), 'json.loads', 'json.loads', (['message'], {}), '(message)\n', (3212, 3221), False, 'import json\n'), ((8538, 8564), 'json.dumps', 'json.dumps', (['account_update'], {}), '(account_update)\n', (8548, 8564), False, 'import json\n'), ((8922, 8940), 'asyncio.sleep', 'asyncio.sleep', (['(0.3)'], {}), '(0.3)\n', (8935, 8940), False, 'import asyncio\n'), ((10446, 10472), 'json.dumps', 'json.dumps', (['account_update'], {}), '(account_update)\n', (10456, 10472), False, 'import json\n'), ((10593, 10611), 'asyncio.sleep', 'asyncio.sleep', (['(0.3)'], {}), '(0.3)\n', (10606, 10611), False, 'import asyncio\n'), ((12124, 12150), 'json.dumps', 'json.dumps', (['account_update'], {}), '(account_update)\n', (12134, 12150), False, 'import json\n'), ((12271, 12289), 'asyncio.sleep', 'asyncio.sleep', (['(0.3)'], {}), '(0.3)\n', (12284, 12289), False, 'import asyncio\n'), ((8878, 8902), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (8900, 8902), False, 'import asyncio\n')]