def test_create_and_execute_deposit(url): """Test creation and execution of deposits.""" # encrypted_key = b"6PYKozqwKwRYi77GN3AwTwXEssJZWbfneYKEYbiSeuNtVTGPFT2Q7EJpjY" # pub_key = "ANVLCD3xqGXKhDnrivpVFvDLcvkpgPbbMt" priv_key_wif = "L2vHHz8L4rtkUkFaxzQoPro33bo7McYMRoUU69DjE334a8NT8zc9" deposit_response = deposits._create_deposit( base_url=url.testnet, asset_id="SWTH", amount=10, contract_hash="a195c1549e7da61b8da315765a790ac7e7633b82", priv_key_wif=priv_key_wif, blockchain="neo") deposit_json_resp = response_to_json(deposit_response) assert validate(deposit_json_resp, CREATE_DEPOSIT_SCHEMA ) is None, "Failed to validate resp from deposit offers" assert deposit_response.status_code == HTTPStatus.OK execute_response = deposits._execute_deposit( base_url=url.testnet, deposit=deposit_json_resp, priv_key_wif=priv_key_wif, ) assert execute_response.status_code == HTTPStatus.OK
def test_create_and_execute_withdrawal(url): """Create an execute followed by withdrawal transaction.""" contract_hash = "a195c1549e7da61b8da315765a790ac7e7633b82" # encrypted_key = b"6PYKozqwKwRYi77GN3AwTwXEssJZWbfneYKEYbiSeuNtVTGPFT2Q7EJpjY" priv_key_wif = "L4FSnRosoUv22cCu5z7VEEGd2uQWTK7Me83vZxgQQEsJZ2MReHbu" # address = "AG9YqjpmoQC5Ufxo2JUr8zCSrXba9krc7g" withdrawals_response = withdrawals._create_withdrawal( base_url=url.testnet, asset_id="SWTH", contract_hash=contract_hash, amount=10, priv_key_wif=priv_key_wif, blockchain="neo") withdrawals_response_json_obj = response_to_json(withdrawals_response) assert validate( withdrawals_response_json_obj, CREATE_WITHDRAWAL_SCHEMA) is None, ("Failed to validate " " response from withdrawals") assert withdrawals_response.status_code == HTTPStatus.OK # Now lets execute withdrawal exec_withdrawal_resp = withdrawals._execute_withdrawal( base_url=url.testnet, withdrawal=withdrawals_response_json_obj, priv_key_wif=priv_key_wif) assert exec_withdrawal_resp.status_code == HTTPStatus.OK
def deposit(self, priv_key_wif, asset_id, amount, contract_hash, blockchain="NEO"): """This api creates a deposit of provided asset on smart-contract. To be able to make a deposit, sufficient funds are required in the depositing wallet. This method performs two tasks 1. Creates a deposit on smart-contract 2. Executes it. Args: priv_key_wif (str) : The private key wif of the user. asset_id (str) : The asset symbol or ID to deposit. for eg. SWTH amount (int) : Amount of tokens to deposit. contract_hash (str) : Switcheo Exchange contract hash to execute the deposit on. blockchain (str) : Blockchain that the token to deposit is on. Possible values are: neo. Returns: If response from the server is HTTP_OK (200) then this returns the requests.response object """ deposits_resp = deposits._create_deposit(base_url=self.base_url, priv_key_wif=priv_key_wif, asset_id=asset_id, amount=amount, contract_hash=contract_hash, blockchain=blockchain) return deposits._execute_deposit( base_url=self.base_url, deposit=response_to_json(deposits_resp), priv_key_wif=priv_key_wif, )
def test_create_and_execute_orders(url): """Test creation and execution of orders.""" contract_hash = "a195c1549e7da61b8da315765a790ac7e7633b82" # address = "AG9YqjpmoQC5Ufxo2JUr8zCSrXba9krc7g" priv_key_wif = "L4FSnRosoUv22cCu5z7VEEGd2uQWTK7Me83vZxgQQEsJZ2MReHbu" orders_response = orders._create_order(base_url=url.testnet, priv_key_wif=priv_key_wif, pair="SWTH_NEO", blockchain="neo", side="sell", price=0.1, want_amount=0.5, asset_id="SWTH", use_native_tokens=True, order_type="limit", contract_hash=contract_hash) orders_json_resp = response_to_json(orders_response) assert validate(orders_json_resp, CREATE_ORDER_RESPONSE_SCHEMA) is None, ( "Failed to validate response" "from create orders") assert orders_response.status_code == HTTPStatus.OK execute_response = orders._execute_order( base_url=url.testnet, order=orders_json_resp, priv_key_wif=priv_key_wif, ) assert execute_response.status_code == HTTPStatus.OK
def create_order(self, priv_key_wif, pair, side, price, want_amount, asset_id, use_native_tokens, contract_hash, blockchain="neo", order_type='limit'): """Create an order on SWTH DEX. Orders can only be created after sufficient funds have been deposited into the user's contract balance. A successful order will have zero or one make and/or zero or more fills. NOTE: Based on the params you are using, let's say you are trying to sell SWTH for NEO at the price of 0.01 exchange rate. The `want_amount` for a sell would be the amount of NEO you want. For eg we want_amount of neo = 0.1 and we want to sell 1 SWTH for 0.0005 NEOs. In this case the sell order would become at 0.0005 exchange rate for 0.1 NEO and 200 SWTH ( so you need to have 200 SWTH in your smart-contract) Args: base_url (str) : This paramter governs whether to connect to test or mainnet. priv_key_wif (str) : The private key wif of the user. pair (str) : The pair to buy or sell on. blockchain (str) : Blockchain that the pair is on. Possible values are: neo. side (str) : Whether to buy or sell on this pair. Possible values are: buy, sell. price (str) : Buy or sell price to 8 decimal places precision. want_amount (int) : Amount of tokens offered in the order. asset_id (str) : Asset which is being traded for eg. in SWTH_NEO then its SWTH use_native_tokens (bool) : Whether to use SWTH as fees or not. Possible values are: true or false. order_type (str) : Order type, possible values are: limit. contract_hash (str) : Switcheo Exchange contract hash to execute the deposit on. Returns: If response from the server is HTTP_OK (200) then this returns the requests.response object """ orders_response = orders._create_order( base_url=self.base_url, priv_key_wif=priv_key_wif, pair=pair, blockchain=blockchain, side=side, price=price, want_amount=want_amount, use_native_tokens=use_native_tokens, asset_id=asset_id, order_type=order_type, contract_hash=contract_hash, ) orders_json_resp = response_to_json(orders_response) return orders._execute_order( base_url=self.base_url, order=orders_json_resp, priv_key_wif=priv_key_wif, )
def test_list_contracts(url): """Test list contracts end points.""" response = exchange._list_contracts(url.testnet) assert response.status_code == HTTPStatus.OK # Assuming NEO will always be in the deployed contracts. json_response = response_to_json(response) assert "NEO" in list(json_response.keys())
def list_order(client, address, contract_hash): """List order example.""" response = client.list_orders(address=address, contract_hash=contract_hash, pair="SWTH_NEO") orders = response_to_json(response) # for eg. print only orders which were of type sell # check the schema `schemas.CREATE_ORDER_RESPONSE_SCHEMA` (from pyswitcheo import schemas) for order in orders: if order["side"] == 'sell': print(order)
def test_list_currency_pairs(url): """Test end points related to pairs.""" response = exchange._list_currency_pairs(base_url=url.testnet, bases=["NEO"]) json_response = response_to_json(response) schema = { "type": "array", } assert validate(json_response, schema) is None, "Failed to validate response from pairs end point" assert response.status_code == HTTPStatus.OK
def test_get_last_price(symbols, key, error_msg, url): """Get last price for the resources.""" response = tickers._get_last_price(url.testnet, symbols=symbols) assert response.status_code == HTTPStatus.OK, error_msg response_json = response_to_json(response) if symbols is None: assert len(response_json.keys()) > 0 else: assert key in response_json.keys()
def test_list_balances(url): """Test end points related to balances.""" contract_hashes_list = ["a195c1549e7da61b8da315765a790ac7e7633b82"] addresses_list = ["ANVLCD3xqGXKhDnrivpVFvDLcvkpgPbbMt"] response = balances._list_balances(base_url=url.testnet, addresses=addresses_list, contract_hashes=contract_hashes_list) json_response = response_to_json(response) assert response.status_code == HTTPStatus.OK assert sorted(['confirmed', 'confirming', 'locked']) == sorted(list(json_response.keys()))
def test_list_orders(url): """Test listing of orders.""" contract_hash = "a195c1549e7da61b8da315765a790ac7e7633b82" # encrypted_key = b"6PYKozqwKwRYi77GN3AwTwXEssJZWbfneYKEYbiSeuNtVTGPFT2Q7EJpjY" pub_key = "ANVLCD3xqGXKhDnrivpVFvDLcvkpgPbbMt" # priv_key_wif = "L2vHHz8L4rtkUkFaxzQoPro33bo7McYMRoUU69DjE334a8NT8zc9" orders_response = orders._list_orders(base_url=url.testnet, address=pub_key, contract_hash=contract_hash) json_response = response_to_json(orders_response) assert orders_response.status_code == HTTPStatus.OK # json response comes out to be a list [{},{}] assert len(json_response[0].keys()) > 0
def test_list_trades(pair, contract_hash, error_msg, url): """Get list of trades.""" # This is another format to query # response = trades._list_trades(base_url=url.testnet, contract_hash=contract_hash, pair=pair, # from_time=1531387142, to_time=1531387439, limit=2) response = trades._list_trades(base_url=url.testnet, contract_hash=contract_hash, pair=pair, limit=2) json_response = response_to_json(response) if contract_hash == "unknown_contract_hash": assert len(json_response) == 0 else: # If there is data, it should match the schema assert validate(json_response, LIST_TRADES_SCHEMA) is None, "Failed to validate response from List offers" # If there is data, since we used limit, there should be only two entries assert len(json_response) == 2 assert response.status_code == HTTPStatus.OK, error_msg
def test_get_exchange_timestamp(url): """Test end points to fetch exchange timestamp.""" response = exchange._get_exchange_timestamp(base_url=url.testnet) json_response = response_to_json(response) schema = { "type": "object", } assert validate(json_response, schema) is None, "Failed to validate response from get_exchange_timestamp end point" assert response.status_code == HTTPStatus.OK assert "timestamp" in json_response now = get_current_epoch_milli() allowed_drift = 60 * 1000 # 60 seconds, represented in milliseconds assert abs(json_response["timestamp"] - now) <= allowed_drift, "Exchange ts is way off than current timestmap"
def create_cancellation(self, order_id, priv_key_wif): """This API is responsible for order cancellation. Only orders with makes and with an available_amount of more than 0 can be cancelled. Args: order_id (str) : The order id which needs to be cancelled. Returns: If response from the server is HTTP_OK (200) then this returns the requests.response object """ cancellation_response = orders._create_cancellation( self.base_url, order_id, priv_key_wif) cancellation_resp_json = response_to_json(cancellation_response) return orders._execute_cancellation(self.base_url, cancellation_resp_json, priv_key_wif)
def test_get_contract_tokens(url): """Test listing of contract tokens with the deployed hash and their precision.""" response = exchange._get_contract_tokens_info(url.testnet) assert response.status_code == HTTPStatus.OK # Assuming NEO will always be in the deployed contracts. json_response = response_to_json(response) assert "NEO" in list(json_response.keys()) assert "GAS" in list(json_response.keys()) assert "SWTH" in list(json_response.keys()) assert "decimals" in json_response["NEO"] assert "decimals" in json_response["GAS"] assert "decimals" in json_response["SWTH"] assert json_response["GAS"]["decimals"] == 8, "Precision for GAS is different than in codebase" assert json_response["SWTH"]["decimals"] == 8, "Precision for SWTH is different than in codebase"
def test_get_candle_sticks(url): """Get candle sticks test.""" # expected = json.loads('[{"time":"1531214820","open":"0.00045893","close":"0.00049953","high":"0.00049953",' # '"low":"0.00045893","volume":"68597677.0","quote_volume":"142900000330.0"},' # '{"time":"1531214880","open":"0.00045893","close":"0.00050373","high":"0.00050373",' # '"low":"0.00045893","volume":"71485077.0","quote_volume":"148600000330.0"}]') # contract_hash = "a195c1549e7da61b8da315765a790ac7e7633b82" response = tickers._get_candle_sticks(pair="SWTH_NEO", start_time=1532390400, end_time=1532736000, interval=1440, base_url=url.testnet) # Just sorting the incoming json based on `time` key to make sure the ordering inside json is maintained # def sorted_with_time(x): # return x.get('time', 0) # assert sorted(expected, key=sorted_with_time) == sorted(response_to_json(response), key=sorted_with_time) json_response_list = response_to_json(response) assert len(json_response_list[0].keys()) > 0 assert response.status_code == HTTPStatus.OK
def withdraw(self, priv_key_wif, asset_id, amount, contract_hash, blockchain="NEO"): """Withdraw your balanaces from Switcheo smart contract balance. This function creates a withdrawal which is later executed. To be able to make a withdrawal, sufficient funds are required in the contract balance. A signature of the request payload has to be provided for this API call. Args: priv_key_wif (str) : The private key wif of the user. asset_id (str) : The asset symbol or ID to withdraw. for eg. SWTH amount (int) : Amount of tokens to withdraw. contract_hash (str) : Switcheo Exchange contract hash to execute the withdraw on. blockchain (str) : Blockchain that the token to withdraw is on. Possible values are: neo. Returns: An id representing this transaction Example response: { "id": "e0f56e23-2e11-4848-b749-a147c872cbe6" } """ withdrawals_response = withdrawals._create_withdrawal( base_url=self.base_url, asset_id=asset_id, contract_hash=contract_hash, amount=amount, priv_key_wif=priv_key_wif, blockchain=blockchain) withdrawals_response_json_obj = response_to_json(withdrawals_response) # Now lets execute withdrawal return withdrawals._execute_withdrawal( base_url=self.base_url, withdrawal=withdrawals_response_json_obj, priv_key_wif=priv_key_wif)
def test_list_offers(blockchain, pair, contract_hash, error_msg, url): """Get offers for the resources.""" response = offers._list_offers(base_url=url.testnet, blockchain=blockchain, pair=pair, contract_hash=contract_hash) json_response = response_to_json(response) schema = { "type": "array", "properties": { "price": { "type": "number" }, "name": { "type": "string" }, }, } assert validate( json_response, schema) is None, "Failed to validate response from List offers" assert response.status_code == HTTPStatus.OK, error_msg
response = client.list_orders(address=address, contract_hash=contract_hash, pair="SWTH_NEO") orders = response_to_json(response) # for eg. print only orders which were of type sell # check the schema `schemas.CREATE_ORDER_RESPONSE_SCHEMA` (from pyswitcheo import schemas) for order in orders: if order["side"] == 'sell': print(order) if __name__ == '__main__': client = SwitcheoApi(base_url="https://test-api.switcheo.network") contract_hash = 'a195c1549e7da61b8da315765a790ac7e7633b82' priv_key_wif = 'L4FSnRosoUv22cCu5z7VEEGd2uQWTK7Me83vZxgQQEsJZ2MReHbu' address = "AG9YqjpmoQC5Ufxo2JUr8zCSrXba9krc7g" # Use this example for listing orders # list_order(client, address, contract_hash) # Following can be used to create orders create_order_resp = client.create_order(priv_key_wif=priv_key_wif, pair="SWTH_NEO", asset_id="SWTH", blockchain="neo", side="sell", price=0.01, want_amount=0.05, use_native_tokens=True, order_type="limit", contract_hash=contract_hash) order_object = response_to_json(create_order_resp) # This order object then can be used to cancel orders # client.create_cancellation(order_id=order_object["id"], priv_key_wif=priv_key_wif)