Client Documentation

SwitcheoApi

These highlevel functions can be used to interact with Switcheo dex.

Base API implementation for pyswitcheo.

class pyswitcheo.api.SwitcheoApi(base_url, api_version='v2')[source]

Base implementation for interacting with pyswitcheo APIs.

create_cancellation(order_id, priv_key_wif)[source]

This API is responsible for order cancellation.

Only orders with makes and with an available_amount of more than 0 can be cancelled.

Parameters

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

create_order(priv_key_wif, pair, side, price, want_amount, asset_id, use_native_tokens, contract_hash, blockchain='neo', order_type='limit')[source]

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)

Parameters
  • 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

deposit(priv_key_wif, asset_id, amount, contract_hash, blockchain='NEO')[source]

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.

Parameters
  • 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

get_candle_sticks(pair, start_time, end_time, interval)[source]

Get candlestick chart data filtered by url parameters.

Parameters
  • pair (str) – Show chart data of this trading pair

  • start_time (int) – Start of time range for data in epoch seconds

  • end_time (int) – End of time range for data in epoch seconds

  • interval (int) – Candlestick period in minutes Possible values are: 1, 5, 30, 60, 360, 1440

Returns

If response from the server is HTTP_OK (200) then this returns the requests.response object

Example response: [

{

“time”: “1531215240”, “open”: “0.00049408”, “close”: “0.00049238”, “high”: “0.000497”, “low”: “0.00048919”, “volume”: “110169445.0”, “quote_volume”: “222900002152.0”

}, {

”time”: “1531219800”, “open”: “0.00050366”, “close”: “0.00049408”, “high”: “0.00050366”, “low”: “0.00049408”, “volume”: “102398958.0”, “quote_volume”: “205800003323.0”

]

get_contract_tokens_info()[source]

Fetch updated hashes of contracts deployed by Switcheo along with their precision.

Parameters

base_url (str) – This paramter governs whether to connect to test or mainnet.

Returns

If response from the server is HTTP_OK (200) then this returns the requests.response object

Example response {

”NEO”: {

“hash”: “c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b”, “decimals”: 8

}, “GAS”: {

”hash”: “602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7”, “decimals”: 8

}, “SWTH”: {

”hash”: “ab38352559b8b203bde5fddfa0b07d8b2525e132”, “decimals”: 8

}

get_exchange_timestamp()[source]

Returns the current timestamp in the exchange.

This value should be fetched and used when a timestamp parameter is required for API requests. If the timestamp used for your API request is not within an acceptable range of the exchange’s timestamp then an invalid signature error will be returned. The acceptable range might vary, but it should be less than one minute.

Returns

If response from the server is HTTP_OK (200) then this returns the requests.response object

Example response {

”timestamp”: 1534392760908

}

list_balances(addresses, contract_hashes)[source]

List contract balances of the given address and contract hashes.

Parameters
  • base_url (str) – This paramter governs whether to connect to test or mainnet..

  • addresses (list[str]) – Only return balances for these addresses.

  • contract_hashes (list[str]) – Only return balances from these contract hashes.

Returns

If response from the server is HTTP_OK (200) then this returns the requests.response object

Example response: {

”confirming”: {
“GAS”: [
{

“event_type”: “withdrawal”, “asset_id”: “602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7”, “amount”: -100000000, “transaction_hash”: null, “created_at”: “2018-07-12T10:48:48.866Z”

}

]

}, “confirmed”: {

”GAS”: “47320000000.0”, “SWTH”: “421549852102.0”, “NEO”: “50269113921.0”

}, “locked”: {

”GAS”: “500000000.0”, “NEO”: “1564605000.0”

}

}

list_contracts()[source]

Fetch updated hashes of contracts deployed by Switcheo.

Returns

If response from the server is HTTP_OK (200) then this returns the requests.response object

Example response {

”NEO”: {

”V1”: “0ec5712e0f7c63e4b0fea31029a28cea5e9d551f”, “V1_5”: “c41d8b0c30252ce7e8b6d95e9ce13fdd68d2a5a8”, “V2”: “48756743d524af03aa75729e911651ffd3cbe7d8”

}

}

list_offers(blockchain, pair, contract_hash)[source]

Retrieves the best 70 offers (per side) on the offer book.

Parameters
  • blockchain (str) – Only return offers from this blockchain. Possible values are neo.

  • pair (str) – Only return offers from this pair, for eg. SWTH_NEO

  • contract_hash (str) – Only return offers for contract hash. e.g. eed0d2e14b0027f5f30ade45f2b23dc57dd54ad2

Returns

If response from the server is HTTP_OK (200) then this returns the requests.response object

Example response: [

{

“id”: “b3a91e19-3726-4d09-8488-7c22eca76fc0”, “offer_asset”: “SWTH”, “want_asset”: “NEO”, “available_amount”: 2550000013, “offer_amount”: 4000000000, “want_amount”: 320000000

}

]

list_orders(address, contract_hash, pair=None)[source]

Retrieves the best 70 offers (per side) on the offer book.

Parameters
  • address (str) – Only returns orders made by this address.

  • contract_hash (str) – Only return offers for the contract hash. e.g. eed0d2e14b0027f5f30ad2b23dc57dd54ad2

  • pair (str) – The pair to buy or sell on. (optional)

Returns

If response from the server is HTTP_OK (200) then this returns the requests.response object

Example response: [

{

“id”: “c415f943-bea8-4dbf-82e3-8460c559d8b7”, “blockchain”: “neo”, “contract_hash”: “c41d8b0c30252ce7e8b6d95e9ce13fdd68d2a5a8”, “address”: “20abeefe84e4059f6681bf96d5dcb5ddeffcc377”, “side”: “buy”, “offer_asset_id”: “c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b”, “want_asset_id”: “602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7”, “offer_amount”: “100000000”, “want_amount”: “20000000”, “transfer_amount”: “0”, “priority_gas_amount”: “0”, “use_native_token”: false, “native_fee_transfer_amount”: 0, “deposit_txn”: null, “created_at”: “2018-05-15T10:54:20.054Z”, “status”: “processed”, “fills”: […], “makes”: […]

}

]

list_pairs(bases)[source]

Fetch available currency pairs on Switcheo Exchange filtered by the base parameter. Defaults to all pairs.

Parameters
  • base_url (str) – This paramter governs whether to connect to test or mainnet..

  • bases (list[str]) – Provides pairs for these base symbols. Possible values are NEO, GAS, SWTH, USD.

Returns

If response from the server is HTTP_OK (200) then this returns the requests.response object

Example response [

”GAS_NEO”, “SWTH_NEO”

]

list_trades(contract_hash, pair, from_time=None, to_time=None, limit=None)[source]

Retrieve trades that have already occurred on Switcheo Exchange filtered by the request parameters.

Parameters
  • contract_hash (str) – Only return trades for this contract hash.

  • pair (str) – Only return trades for this pair.

  • from_time (int) – Only return trades after this time in epoch seconds.

  • to_time (int) – Only return trades before this time in epoch seconds.

  • limit (int) – Only return this number of trades (min: 1, max: 10000, default: 5000).

Returns

If response from the server is HTTP_OK (200) then this returns the requests.response object

Example response: [

{

“id”: “712a5019-3a23-463e-b0e1-80e9f0ad4f91”, “fill_amount”: 9122032316, “take_amount”: 20921746, “event_time”: “2018-06-08T11:32:03.219Z”, “is_buy”: false

}, {

”id”: “5d7e42a2-a8f3-40a9-bce5-7304921ff691”, “fill_amount”: 280477933, “take_amount”: 4207169, “event_time”: “2018-06-08T11:31:42.200Z”, “is_buy”: false

]

withdraw(priv_key_wif, asset_id, amount, contract_hash, blockchain='NEO')[source]

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.

Parameters
  • 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”

}

Helper Modules

pyswitcheo.crypto_utils module

Crypto related wrapper functions.

pyswitcheo.crypto_utils.encode_msg(msg)[source]

Convert a given msg to its hex representation.

This is generally used when we send signed payload to the Switcheo api.

Parameters

msg (str) – Input message which needs to be encoded.

Returns

encoded message (str)

pyswitcheo.crypto_utils.ensure_hex(input_hex)[source]

Check if the passed string is a hex string else raise exception.

Empty string is always treated as hex.

pyswitcheo.crypto_utils.get_private_key_from_wif(wif)[source]

Fetch the private key from a wif represented in string format.

Parameters

wif (str) – wif from which we need to extract the private key

Returns

private key in bytearray format

pyswitcheo.crypto_utils.get_script_hash_from_address(address)[source]

Convert a given address to script hash. This code has been taken from: https://github.com/CityOfZion/neo-python-core/blob/fcb0837e8f69e6f4dc01f2861b856affd2213446/neocore/bin/cli.py#L23

pyswitcheo.crypto_utils.get_script_hash_from_wif(wif)[source]

Fetch the script hash of the public key from a wif represented in string format.

Parameters

wif (str) – wif from which we need to extract the public key script hash

Returns

public key script hash in string format

pyswitcheo.crypto_utils.get_wif_from_private_key(priv_key)[source]

Convert the given privatekey to a wif format.

Parameters

priv_key (str) – private key in its hex string format.

Returns

WIF format

pyswitcheo.crypto_utils.is_hex(input_hex)[source]

Check if the passed string is a hex string.

Empty string is always treated as hex.

pyswitcheo.crypto_utils.num_to_hex_string(num, size=1, little_endian=False)[source]

Convert a given number to hex string.

Converts a number to a big endian hexstring of a suitable size, optionally little endian

Parameters
  • num (int) – Input int for which we need to get the hex string

  • size (int) – The required size in bytes, eg 1 for Uint8, 2 for Uint16. Defaults to 1.

Returns

(str)

pyswitcheo.crypto_utils.num_to_var_int(num)[source]

Convert a number to a variable length Int. Used for array length header.

Detailed explanation

Parameters

num (int) – A number

Returns

(str) hexstring of the variable Int

pyswitcheo.crypto_utils.reverse_hex(input_hex)[source]

Reverse a HEX string, treating 2 chars as a byte.

Expected results look like this: reverse_hex(‘abcdef’) = ‘efcdab’

Parameters

input_hex (str) – Input string in hex which needs to be converted.

Returns

Hex string reversed.

pyswitcheo.utils module

Utilities to be used.

pyswitcheo.utils.convert_to_neo_asset_amount(amount, asset_id, base_url)[source]

Convert a given input to a neo asset precision.

Internally this API queries the Switcheo exchange to get the correct precision for a given asset.

Parameters
  • amount (int) – Input amount for which precision needs to be calculated.

  • asset_id (str) – A string representing the correct asset.

  • base_url (str) – URL of the switcheo exchange which will return the correct decimal precision.

pyswitcheo.utils.format_urls(base_url, end_point)[source]

Create a url given a base url and an end point.

Parameters
  • base_url (str) – A base url which needs to be queried.

  • end_point (str) – The other part of the end point

Returns

A properly formatted url to query

pyswitcheo.utils.get_current_epoch_milli()[source]

Get the current time in epoch milliseconds.

pyswitcheo.utils.jsonify(json_obj)[source]

Convert a given json object to string with sorted key and without spaces.

pyswitcheo.utils.response_else_exception(response)[source]

Return a response in case HTTPStatus is 200, else raise a custom exception.

pyswitcheo.utils.response_to_json(response)[source]

A simple wrapper to convert requests.content or requests.text to a corresponding json object.

pyswitcheo.serialization module

Crypto related wrapper functions.

pyswitcheo.serialization.serialize_claim_exclusive()[source]

.

pyswitcheo.serialization.serialize_contract_exclusive()[source]

.

pyswitcheo.serialization.serialize_exclusive(transaction_type)[source]

.

pyswitcheo.serialization.serialize_invocation_exclusive(transaction)[source]

Short explanation.

Detailed explanation

Args:

Returns:

pyswitcheo.serialization.serialize_transaction(tx, signed=True)[source]

Serialize a transaction object

Whenever an operation is invoked on the blockchain, we get a transaction object. As a rest response we can pass this here to sign it.

Args:

Returns:

pyswitcheo.serialization.serialize_transaction_attribute(attr)[source]

Serialize a TransactionAttribute

Detailed explanation

Args:

Returns

str

pyswitcheo.serialization.serialize_transaction_input(input)[source]

Serialize an object of type TransactionInput

TransactionInput has two params 1. prevHash: Transaction hash (Uint256) 2. prevIndex: Index of the coin in the previous transaction (Uint16)

Parameters

input (TransactionInput) – TransactionInput which needs to be serialized.

Returns

(str) serialized version of TransactionInput

pyswitcheo.serialization.serialize_transaction_output(output)[source]

Serialize an object of type TransactionOutput

TransactionOutput has three params 1. assetId: assetId, Uint256 2. value: value of output, Fixed8 3. scriptHash of type Uint160

Parameters

input (TransactionOutput) – TransactionOutput which needs to be serialized.

Returns

(str) serialized version of TransactionOutput

pyswitcheo.serialization.serialize_witness(witness)[source]

Serialize an object of type Witness

Witness object has two params 1. invocationScript: This data is stored as is (Little Endian) 2. verificationScript: This data is stored as is (Little Endian)

Parameters

input (witness) – witness which needs to be serialized.

Returns

(str) serialized version of witness

pyswitcheo.serialization.sign_array(input_arr, priv_key)[source]

Sign each item in an input array.

Parameters

input_arr (dict) – An input array with transaction objects. This is a dictionary with “txn” key in it.

Returns

A dictionary of signed objects, where key is the id of each element in the input_arr.

pyswitcheo.serialization.sign_msg(msg, priv_key)[source]

Sign a given message using a private key.

Parameters
  • msg (str) – Message which needs to be signed.

  • priv_key (bytes) – Private key to be used to sign this.

Returns

Signed message as a byte array.

pyswitcheo.serialization.sign_transaction(transaction, priv_key)[source]

Sign a transaction object returned as a part of any transaction creation using user’s private key.

Parameters
  • transaction (json) – Transaction is dictionary object which is returned after creating a transaction.

  • priv_key (bytes) – Private key to be used to sign this.

Returns

A signed transaction string