code stringlengths 541 76.7k | apis sequence | 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')] |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 5