Best Python code snippet using autotest_python
_client.py
Source:_client.py
...42 COMPARE_URL = "https://www.cryptocompare.com"43 def __init__(self, api_key):44 self.api_key = api_key45 @retry(tries=2, delay=3, max_delay=5)46 def _make_request(self, endpoint, payload=None, **kwargs):47 """You can use either endpoint key or endpoint value from dictionary ENDPOINTS48 All of request will be handled"""49 if endpoint in ENDPOINTS:50 endpoint_path = ENDPOINTS.get(endpoint)51 elif endpoint in list(ENDPOINTS.values()):52 endpoint_path = endpoint53 else:54 raise ValueError(55 f"Wrong endpoint\nPlease Use one from List {list(ENDPOINTS.keys())}"56 )57 url = self.BASE_URL + endpoint_path58 if payload is None:59 payload = {}60 if kwargs:61 payload.update(kwargs)62 headers = {"authorization": "Apikey " + self.api_key}63 req = requests.get(url, params=payload, headers=headers)64 return req.json()65 def _get_price(self, symbol="BTC", currency="USD", **kwargs):66 """Full data"""67 endpoint = ENDPOINTS["PRICE_MULTI_FULL"]68 payload = {69 "fsyms": symbol,70 "tsyms": currency,71 "relaxedValidation": "false",72 }73 return self._make_request(endpoint, payload, **kwargs)74 def _get_top_list_by_market_cap(self, currency="USD", limit=100, **kwargs):75 endpoint = ENDPOINTS["TOP_BY_MARKET_CAP"]76 payload = {"tsym": currency, "limit": limit}77 return self._make_request(endpoint, payload, **kwargs)78 def _get_top_exchanges(self, symbol="BTC", currency="USD", limit=100, **kwargs):79 endpoint = ENDPOINTS["TOP_EXCHANGES_FULL_DATA"]80 payload = {81 "fsym": symbol,82 "tsym": currency,83 "limit": limit,84 }85 return self._make_request(endpoint, payload, **kwargs)86 def _get_exchanges_top_symbols_by_volume(87 self, exchange="Binance", limit=100, **kwargs88 ):89 "/data/exchange/top/volume?e=Binance&direction=TO"90 "e=Kraken"91 endpoint = ENDPOINTS["EXCHANGE_TOP_SYMBOLS"]92 payload = {"e": exchange.capitalize(), "limit": limit, "direction": "FROM"}93 return self._make_request(endpoint, payload, **kwargs)94 def _get_top_list_by_pair_volume(self, currency="USD", limit=100, **kwargs):95 endpoint = ENDPOINTS["TOP_LIST_PAIR_VOLUME"]96 payload = {97 "tsym": currency,98 "limit": limit,99 }100 return self._make_request(endpoint, payload, **kwargs)101 def _get_top_of_trading_pairs(self, symbol="ETH", limit=50, **kwargs):102 endpoint = ENDPOINTS["TOP_LIST_OF_PAIRS"]103 payload = {104 "fsym": symbol,105 "limit": limit,106 }107 return self._make_request(endpoint, payload, **kwargs)108 # TODO --> Add mappings that use can use either coinId, symbol, or name for requests109 def _get_latest_social_coin_stats(self, coin_id=7605, **kwargs):110 endpoint = ENDPOINTS["LATEST_COIN_SOCIAL_STATS"]111 payload = {"coinId": int(coin_id)}112 return self._make_request(endpoint, payload, **kwargs)113 def _get_historical_social_stats(114 self, coin_id=7605, limit=2000, aggregate=1, **kwargs115 ):116 endpoint = ENDPOINTS["HISTO_DAY_SOCIAL_STATS"]117 payload = {118 "coinId": int(coin_id),119 "limit": limit,120 "aggregate": aggregate,121 }122 return self._make_request(endpoint, payload, **kwargs)123 def _get_latest_news(self, lang="EN", sort_order="latest", **kwargs):124 endpoint = ENDPOINTS["NEWS"]125 payload = {"lang": lang, "sortOrder": sort_order}126 return self._make_request(endpoint, payload, **kwargs)127 def _get_blockchain_available_coins_list(self):128 endpoint = ENDPOINTS["BLOCKCHAIN_COINS"]129 return self._make_request(endpoint=endpoint)130 def _get_all_coins_list(self, summary="true", **kwargs):131 endpoint = ENDPOINTS["ALL_COINS_LIST"]132 if isinstance(summary, bool):133 summary = str(summary).lower()134 payload = {"summary": summary}135 return self._make_request(endpoint, payload, **kwargs)136 def _get_historical_day_prices(137 self, symbol="BTC", currency="USD", limit=2000, **kwargs138 ):139 endpoint = ENDPOINTS["HISTO_DAY"]140 payload = {141 "fsym": symbol,142 "tsym": currency,143 "limit": limit,144 }145 return self._make_request(endpoint, payload, **kwargs)146 def _get_historical_hour_prices(147 self, symbol="BTC", currency="USD", limit=2000, **kwargs148 ):149 endpoint = ENDPOINTS["HISTO_HOUR"]150 payload = {151 "fsym": symbol,152 "tsym": currency,153 "limit": limit,154 }155 return self._make_request(endpoint, payload, **kwargs)156 def _get_historical_minutes_prices(157 self, symbol="BTC", currency="USD", limit=2000, **kwargs158 ):159 endpoint = ENDPOINTS["HISTO_MINUTE"]160 payload = {161 "fsym": symbol,162 "tsym": currency,163 "limit": limit,164 }165 return self._make_request(endpoint, payload, **kwargs)166 def _get_daily_exchange_volume(167 self, currency="USD", exchange="CCCAGG", limit=365, **kwargs168 ):169 """The CCCAGG is calculated for each crypto coin in each currency it is trading in (example: CCCAGG BTC-USD)170 See more: https://www.cryptocompare.com/media/12318004/cccagg.pdf171 """172 endpoint = ENDPOINTS["DAILY_EXCHANGE_VOLUME"]173 payload = {174 "tsym": currency,175 "e": exchange,176 "limit": limit,177 }178 return self._make_request(endpoint, payload, **kwargs)179 def _get_hourly_exchange_volume(180 self, currency="USD", exchange="CCCAGG", limit=60 * 24, **kwargs181 ):182 """The CCCAGG is calculated for each crypto coin in each currency it is trading in (example: CCCAGG BTC-USD)183 See more: https://www.cryptocompare.com/media/12318004/cccagg.pdf184 """185 endpoint = ENDPOINTS["HOURLY_EXCHANGE_VOLUME"]186 payload = {187 "tsym": currency,188 "e": exchange,189 "limit": limit,190 }191 return self._make_request(endpoint, payload, **kwargs)192 def _get_daily_symbol_volume(193 self, symbol="BTC", currency="USD", limit=365, **kwargs194 ):195 endpoint = ENDPOINTS["DAILY_SYMBOL_VOLUME"]196 payload = {197 "fsym": symbol,198 "tsym": currency,199 "limit": limit,200 }201 return self._make_request(endpoint, payload, **kwargs)202 def _get_hourly_symbol_volume(203 self, symbol="BTC", currency="USD", limit=60 * 24, **kwargs204 ):205 endpoint = ENDPOINTS["HOURLY_SYMBOL_VOLUME"]206 payload = {207 "fsym": symbol,208 "tsym": currency,209 "limit": limit,210 }211 return self._make_request(endpoint, payload, **kwargs)212 def _get_latest_blockchain_data(self, symbol="BTC", **kwargs):213 endpoint = ENDPOINTS["LATEST_BLOCKCHAIN_DATA"]214 payload = {215 "fsym": symbol,216 }217 return self._make_request(endpoint, payload, **kwargs)218 def _get_historical_blockchain_data(self, symbol="BTC", limit=365, **kwargs):219 endpoint = ENDPOINTS["HISTO_BLOCKCHAIN_DATA"]220 payload = {221 "fsym": symbol,222 "limit": limit,223 }224 return self._make_request(endpoint, payload, **kwargs)225 def _get_latest_trading_signals(self, symbol="BTC", **kwargs):226 endpoint = ENDPOINTS["TRADING_SIGNALS"]227 payload = {228 "fsym": symbol,229 }230 return self._make_request(endpoint, payload, **kwargs)231 def _get_order_books_exchanges(self, **kwargs):232 endpoint = ENDPOINTS["EXCHANGES_ORDER_BOOK"]233 return self._make_request(endpoint, {}, **kwargs)234 def _get_order_book_top(235 self, symbol="ETH", to_symbol="BTC", exchange="binance", **kwargs236 ):237 """Returns latest order book Level 1 bid/ask values238 for the requested exchange and pairs in both raw and display formats"""239 endpoint = ENDPOINTS["ORDER_BOOK_L1_TOP"]240 payload = {241 "fsyms": symbol,242 "tsyms": to_symbol,243 "e": exchange,244 }245 return self._make_request(endpoint, payload, **kwargs)246 def _get_order_book_snapshot(247 self, symbol="ETH", to_symbol="BTC", exchange="binance", **kwargs248 ):249 """Returns latest order book Level 2 data snapshot for the requested exchang"""250 endpoint = ENDPOINTS["ORDER_BOOK_L2_SNAPSHOT"]251 payload = {252 "fsyms": symbol,253 "tsyms": to_symbol,254 "e": exchange,255 }256 return self._make_request(endpoint, payload, **kwargs)257 def _get_all_exchanges_and_trading_pairs(258 self, symbol=None, exchange=None, top_tier="false", **kwargs259 ):260 endpoint = ENDPOINTS["EXCHANGES_PAIRS"]261 payload = {262 "fsym": symbol,263 "e": exchange,264 "topTier": top_tier,265 }266 return self._make_request(endpoint, payload, **kwargs)267 def _get_all_exchanges_info(self, symbol="BTC", **kwargs):268 endpoint = ENDPOINTS["EXCHANGES_INFO"]269 payload = {270 "tsym": symbol,271 }272 return self._make_request(endpoint, payload, **kwargs)273 def _get_all_wallet_info(self, **kwargs):274 endpoint = ENDPOINTS["WALLETS"]275 payload = {}276 return self._make_request(endpoint, payload, **kwargs)277 def _get_all_gambling_info(self, **kwargs):278 endpoint = ENDPOINTS["GAMBLING"]279 payload = {}280 return self._make_request(endpoint, payload, **kwargs)281 def _get_recommendations(self, symbol="BTC", **kwargs):282 """Returns general info about our recommended entities.283 * wallets,284 * gambling285 * mining companies286 * exchanges287 """288 endpoint = ENDPOINTS["RECOMMENDED"]289 payload = {"tsym": symbol}...
wallet.py
Source:wallet.py
...11 def __init__(self, password, host='127.0.0.1', port=8070):12 self.url = f'http://{host}:{port}/json_rpc'13 self.headers = {'content-type': 'application/json'}14 self.password = password15 def _make_request(self, method, **kwargs):16 payload = {17 "jsonrpc": "2.0",18 "method": method,19 "password": self.password,20 "id": 0,21 "params": kwargs22 }23 logging.debug(json.dumps(payload, indent=4))24 response = requests.post(self.url,25 data=json.dumps(payload),26 headers=self.headers).json()27 if 'error' in response:28 raise ValueError(response['error'])29 return response['result']30 def save(self):31 return self._make_request('save')32 def export(self, file_name):33 kwargs = {'fileName': file_name}34 return self._make_request('export', **kwargs)35 def get_balance(self, address=''):36 """37 Returns the balance.38 Note:39 Amount needs to be divided by 100 to get decimal places.40 If balance returned is 1000 it means 10.00 TRTL41 Args:42 address (str): The address for which to return the balance43 Returns:44 dict: available balance (int) and locked amount (int)45 {46 'availableBalance': 1000,47 'lockedAmount': 048 }49 """50 kwargs = {'address': address}51 return self._make_request('getBalance', **kwargs)52 def get_status(self):53 return self._make_request('getStatus')54 def get_addresses(self):55 return self._make_request('getAddresses')['addresses']56 def get_view_key(self):57 return self._make_request('getViewKey')58 def get_spend_keys(self, address):59 kwargs = {'address': address}60 return self._make_request('getSpendKeys', **kwargs)61 def get_unconfirmed_transaction_hashes(self, addresses=[]):62 kwargs = {'addresses': addresses}63 return self._make_request('getUnconfirmedTransactionHashes', **kwargs)64 def create_address(self, spend_secret_key='', spend_public_key=''):65 """66 Create a new address67 Args:68 spend_secret_key (str)69 spend_public_key (str)70 Returns:71 str: the hash of the new address72 """73 kwargs = {'spendSecretKey': spend_secret_key}74 # kwargs = {'spendPublicKey': spend_public_key}75 return self._make_request('createAddress', **kwargs)76 def create_address_list(self, spend_secret_keys):77 kwargs = {'spendSecretKeys': spend_secret_keys}78 return self._make_request('createAddressList', **kwargs)79 def delete_address(self, address):80 """81 Delete address from wallet82 Args:83 address (str): the address to delete84 Returns:85 bool: True if successful86 """87 kwargs = {'address': address}88 self._make_request('deleteAddress', **kwargs)89 return True90 def get_block_hashes(self, first_block_index, block_count):91 kwargs = {'firstBlockIndex': first_block_index,92 'blockCount': block_count}93 return self._make_request('getBlockHashes', **kwargs)94 def get_transaction(self, transaction_hash):95 kwargs = {'transactionHash': transaction_hash}96 self._make_request('getTransaction', **kwargs)97 def get_transactions(self, addresses, block_hash_string, block_count,98 payment_id):99 kwargs = {'addresses': addresses,100 'blockHashString': block_hash_string,101 'blockCount': block_count,102 'paymentId': payment_id}103 self._make_request('getTransactions', **kwargs)104 def get_transaction_hashes(self, addresses, block_hash, block_count,105 payment_id):106 kwargs = {'addresses': addresses,107 'blockHash': block_hash,108 'blockCount': block_count,109 'paymentId': payment_id}110 return self._make_request('getTransactionHashes', **kwargs)111 def send_transaction(self, anonymity, transfers, fee=10,112 source_addresses='', change_address='', extra='',113 payment_id='', unlock_time=0):114 """115 Send a transaction to one or multiple addresses.116 Note:117 The amount/fee need to be multiplied by 100 to get TRTL amount.118 If you want to transfer 10 TRTL with a fee of 0.1 TRLT you should119 set transfer amount to 1000 and fee to 10120 Params:121 anonymity: mixin amount122 transfers: address where to send the funds to. (address, amount)123 fee: transaction fee (default 100 (0.1 TRTL))124 source_addresses: addresses from which to take the funds from.125 change_address: address where to send the change to.126 extra (bytes): extra data to include127 payment_id: can be given to receiver to identify transaction128 unlock_time (int)129 Example:130 >>> wallet.send_transaction(131 anonymity=3,132 transfers=[133 {'address': 'TRTL...',134 'amount': 500}],135 fee=10136 )137 {'transactionHash': '1b87a........'}138 """139 params = {'sourceAddresses': source_addresses,140 'transfers': transfers,141 'changeAddress': change_address,142 'fee': fee,143 'anonymity': anonymity,144 'unlockTime': unlock_time}145 # payment_id and extra cannot be present at the same time146 # either none of them is included, or one of them147 if payment_id and extra:148 raise ValueError('payment_id and extra cannot be set together')149 elif payment_id:150 params['payment_id'] = payment_id151 elif extra:152 params['extra'] = convert_bytes_to_hex_str(extra)153 r = self._make_request('sendTransaction', **params)154 return r['transactionHash']155 def get_delayed_transaction_hashes(self):156 """157 Returns a list of delayed transaction hashes158 """159 r = self._make_request('getDelayedTransactionHashes')160 return r['transactionHashes']161 def create_delayed_transaction(self, anonymity, transfers, fee=10,162 source_addresses='', change_address='',163 extra='', payment_id='', unlock_time=0):164 params = {'sourceAddresses': source_addresses,165 'transfers': transfers,166 'changeAddress': change_address,167 'fee': fee,168 'anonymity': anonymity,169 'unlockTime': unlock_time}170 # payment_id and extra cannot be present at the same time171 # either none of them is included, or one of them172 if payment_id and extra:173 raise ValueError('payment_id and extra cannot be set together')174 elif payment_id:175 params['payment_id'] = payment_id176 elif extra:177 params['extra'] = convert_bytes_to_hex_str(extra)178 r = self._make_request('createDelayedTransaction', **params)179 return r['transactionHash']180 def send_delayed_transaction(self, transaction_hash):181 """182 Send a delayed transaction183 Example:184 >>> wallet.send_delayed_transaction('8dea3...')185 Raises:186 If the delayed tx is not valid:187 ValueError: {188 'code': -32000,189 'data': {'application_code': 15},190 'message': 'Transaction transfer impossible'191 }192 """193 kwargs = {'transactionHash': transaction_hash}194 self._make_request('sendDelayedTransaction', **kwargs)195 return True196 def delete_delayed_transaction(self, transaction_hash):197 """198 Delete a delayed transaction199 Example:200 >>> wallet.delete_delayed_transaction('8dea3....')201 """202 kwargs = {'transactionHash': transaction_hash}203 self._make_request('deleteDelayedTransaction', **kwargs)204 return True205 def send_fusion_transaction(self, threshold, anonymity, addresses,206 destination_address):207 """208 Send a fusion transaction, by taking funds from selected addresses and209 transferring them to the destination address.210 Returns:211 str: hash of the sent transaction212 """213 kwargs = {'threshold': threshold,214 'anonymity': anonymity,215 'addresses': addresses,216 'destinationAddress': destination_address}217 return self._make_request('sendFusionTransaction', **kwargs)218 def estimate_fusion(self, threshold, addresses=[]):219 """220 Counts the number of unspent outputs of the specified addresses and221 returns how many of those outputs can be optimized.222 """223 kwargs = {'threshold': threshold,224 'addresses': addresses}...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!