Stablecoins: Things you need to know

Stablecoins: Things you need to know

Overview of stablecoins and their role in the market Cryptocurrencies

What are stablecoins?

Stablecoins are a special type of digital asset that represent the value of another currency or asset found outside of this asset’s blockchain. Investors may think of it almost as a derivative product, in that there is an underlying asset involved. “Stable” references that the outside asset is more constant relative to the value held on this asset’s current blockchain. Major cryptocurrencies, Bitcoin and Ether, are renowned for their volatility — which have been the boon and bane of many investors. The most popular currency that stablecoins represent is the US Dollar, thereby allowing for stable on-and-off ramps for investors, a process that previously involved multiple costly transfers between fiat and cryptocurrencies.

Why use cryptocurrencies?

Cryptocurrencies have several potential advantages over using regular fiat. Fiat requires trust in the central issuing government body. Since all major currencies have decoupled from the gold standard in the latter half of the last century, fiat is no longer backed by a hard asset, meaning that value in a fiat currency is tied to trust in the issuing body. The US Dollar and Euro have a high amount of trust and support, but that’s not the case with other currencies. Zimbabwe’s dollar was effectively abandoned as a national currency in 2009 due to hyperinflation. Cryptocurrencies offer a higher level of transparency since all transactions are stored on an immutable ledger. This detailed record-keeping reduces the need for paid intermediaries to verify if and when transactions occurred. Also, consumers benefit from lower transaction fees with remittances. Cross border transactions no longer have to do multiple hops between intermediary currencies based on what individual banks support. Value can be moved in a single step from one user to another. Certain cryptocurrencies allow for programmable logic to be built into blockchains as well.

Cryptocurrencies aren’t sufficient?

Investors have entered the digital asset ecosystem for a number of reasons. Ethereum¹, with the use of smart contracts², offers a multifunctional protocol that has seen significant application development and financial proofs of concept. Ethereum provides a decentralized network for running resilient, secure, and borderless applications. While Ethereum enables the world computer, the majority of transactions are still tied to the real financial world. Bills, insurance, and everyday expenses are still primarily paid in fiat. Complex financial products and commodities, as well as all domestic transactions, are still denominated in US Dollars. With cryptocurrency volatility persisting, having a solution where one gets fiat price stability and blockchain technology is an essential component in the development of the global digital financial ecosystem.

How do stablecoins solve this problem?

  • Stablecoins bridge existing financial markets and crypto-related ones by using the same reference pricing. Users are able to stay in the “digital sphere” while allowing for real-world assets to come online.
  • A digital token with price stability gives investors the opportunity to interact with the digital ecosystem while avoiding the middlemen’s costly conversions between fiat and crypto. The investment experience can remain entirely digital.
  • Fiat currencies’ inherent benefit also applies to stablecoins: the stability of the US Dollar or another asset/currency to which it is linked. Countries with weaker or volatile fiat currencies could utilize stablecoins similar to embracing the USD to manage risk and participate in global monetary systems.
  • Cryptocurrencies’ inherent benefit applies to stablecoins: fast and trustless settlement, frictionless transfer, and use of blockchain technology.

Source CMC

Collateralized Stablecoins

Fiat-backed

Example: TUSD, GUSD, USDC, PAX, USDT

  • Fiat-backed stablecoins are issued in accordance to a set ratio pegged to fiat currency. The total amount of tokens issued must be 1:1 with the total cash in the bank or vault. For example, the USD Coin (USDC) is pegged 1:1 to the US Dollar. This stabilization method presents risks around the trust of centralized third parties. These fiat custodians are audited frequently to prove that the digital tokens are fully backed by fiat deposits.

Asset-backed

Example: Digix

  • The structure of asset-backed stablecoins is similar to fiat-backed, however, the digital coin is pegged to the value of a hard asset instead of a fiat currency. For example, Digix offers a token, DGX, where one token is equal to one gram of gold. This gold is stored in a vault in Singapore and is audited quarterly to ensure the gold reserves correlate to the total market cap of the token.
  • The risks associated with asset-backed stablecoins are similar to the risks of fiat-backed stablecoins in that third parties must be trusted with audits to ensure the peg ratio holds true.

Crypto-backed

Example: DAI

  • Crypto-backed stablecoins are digital tokens that are backed by the value of another digital asset like Bitcoin or ETH. This structure is a bit more complicated as the price of cryptocurrencies can swing wildly; thus simply pegging the two assets, Ether and the stablecoin, 1:1 will not serve to stabilize the price. Thus, more creative solutions, like that of MakerDAO and their stablecoin DAI, have been introduced. Maker uses collateral debt positions (CDP) which operate similar to a bank. Smart contracts on Ethereum hold collateral in ETH and in return give a “loan” of 66% of DAI. If the value of ETH goes below a certain threshold, the user either pays back the CDP, or the position is auctioned to the highest bidder.
  • Currency risk exists in this initial deployment of CDPs due to lack of diversification of a single digital asset, ETH, held as collateral. Future developments of the CDP functionality will allow the smart contracts to hold multiple asset types thereby increasing diversification and reducing volatility.

Non-collateralized Stablecoins

Algorithmic

Example: Basis

  • Algorithmic stablecoins are not backed by a hard asset, but instead automated logic modifies the token supply based on supply and demand. Think of this as an automated central bank that enacts monetary policy through programmatic capital controls.
  • User adoption is one risk faced by algorithmic stablecoins, like Basis, since the functionality of the system required participation for stability.

What do stablecoins enable?

  • Growth of applications using blockchain technology by serving as an intermediary between the digital and fiat world.
  • Greater access to the global financial system: anyone with internet access can gain exposure to stablecoins.
  • Stablecoins are poised to be a powerful vehicle for fundamental long-term changes in the global economy: decentralized stablecoins transcend economic controls and policies.
  • Intersection of stablecoins and tokenized securities: investments and dividends become practical.
  • Programmability: payments via stablecoin are not subject to the volatility of cryptocurrencies.

What comes next?

The next generation of currency, payment, and settlement will undoubtedly occur in digital form. The composition of the initial attempts gives us an idea of where this technology can go. Fiat-backed currencies offer familiarity and ideological comfort of 1:1 backing of the underlying pegged currency. Although introducing centralized risk, they serve an important function to familiarize and build trust with newcomers to the digital ecosystem.

The next generation of currency should allow alternative pegging so that they can be shielded from extraordinary events. Ideally, it should be backed by a diversified uncorrelated basket of assets to avoid effects of such events. Additionally, an ideal stablecoin would execute smart contract logic on-chain and be backed by decentralized assets. Each of the first attempts highlighted above successfully accomplish essential tasks in this development. With certainty, the next evolution in stablecoins is coming.

Thanks for reading ...


Build Your Own Cryptocurrency Blockchain in Python

Build Your Own Cryptocurrency Blockchain in Python

This tutorial demonstrates how to create a cryptocurrency blockchain using Python by building a chain, adding constructor methods, confirming ...

Cryptocurrency is a decentralized digital currency that uses encryption techniques to regulate the generation of currency units and to verify the transfer of funds. Anonymity, decentralization, and security are among its main features. Cryptocurrency is not regulated or tracked by any centralized authority, government, or bank.

Blockchain, a decentralized peer-to-peer (P2P) network, which is comprised of data blocks, is an integral part of cryptocurrency. These blocks chronologically store information about transactions and adhere to a protocol for inter-node communication and validating new blocks. The data recorded in blocks cannot be altered without the alteration of all subsequent blocks.

In this article, we are going to explain how you can create a simple blockchain using the Python programming language.

Here is the basic blueprint of the Python class we’ll use for creating the blockchain:

class Block(object):
    def __init__():
        pass
    #initial structure of the block class 
    def compute_hash():
        pass
    #producing the cryptographic hash of each block 
  class BlockChain(object):
    def __init__(self):
    #building the chain
    def build_genesis(self):
        pass
    #creating the initial block
    def build_block(self, proof_number, previous_hash):
        pass
    #builds new block and adds to the chain
   @staticmethod
    def confirm_validity(block, previous_block):
        pass
    #checks whether the blockchain is valid
    def get_data(self, sender, receiver, amount):
        pass
    # declares data of transactions
    @staticmethod
    def proof_of_work(last_proof):
        pass
    #adds to the security of the blockchain
    @property
    def latest_block(self):
        pass
    #returns the last block in the chain

Now, let’s explain how the blockchain class works.

Initial Structure of the Block Class

Here is the code for our initial block class:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()

As you can see above, the class constructor or initiation method ( init()) above takes the following parameters:

  • self — just like any other Python class, this parameter is used to refer to the class itself. Any variable associated with the class can be accessed using it.

  • index — it’s used to track the position of a block within the blockchain.

  • previous_hash — it used to reference the hash of the previous block within the blockchain.

  • data—it gives details of the transactions done, for example, the amount bought.

  • timestamp—it inserts a timestamp for all the transactions performed.

The second method in the class, compute_hash , is used to produce the cryptographic hash of each block based on the above values.

As you can see, we imported the SHA-256 algorithm into the cryptocurrency blockchain project to help in getting the hashes of the blocks.

Once the values have been placed inside the hashing module, the algorithm will return a 256-bit string denoting the contents of the block.

So, this is what gives the blockchain immutability. Since each block will be represented by a hash, which will be computed from the hash of the previous block, corrupting any block in the chain will make the other blocks have invalid hashes, resulting in breakage of the whole blockchain network.

Building the Chain

The whole concept of a blockchain is based on the fact that the blocks are “chained” to each other. Now, we’ll create a blockchain class that will play the critical role of managing the entire chain.

It will keep the transactions data and include other helper methods for completing various roles, such as adding new blocks.

Let’s talk about the helper methods.

Adding the Constructor Method

Here is the code:

class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()

The init() constructor method is what instantiates the blockchain.

Here are the roles of its attributes:

  • self.chain — this variable stores all the blocks.

  • self.current_data — this variable stores information about the transactions in the block.

  • self.build_genesis() — this method is used to create the initial block in the chain.

Building the Genesis Block

The build_genesis() method is used for creating the initial block in the chain, that is, a block without any predecessors. The genesis block is what represents the beginning of the blockchain.

To create it, we’ll call the build_block() method and give it some default values. The parameters proof_number and previous_hash are both given a value of zero, though you can give them any value you desire.

Here is the code:

def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
 def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block

Confirming Validity of the Blockchain

The confirm_validity method is critical in examining the integrity of the blockchain and making sure inconsistencies are lacking.

As explained earlier, hashes are pivotal for realizing the security of the cryptocurrency blockchain, because any slight alteration in an object will result in the creation of an entirely different hash.

Thus, the confirm_validity method utilizes a series of if statements to assess whether the hash of each block has been compromised.

Furthermore, it also compares the hash values of every two successive blocks to identify any anomalies. If the chain is working properly, it returns true; otherwise, it returns false.

Here is the code:

def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True

Declaring Data of Transactions

The get_data method is important in declaring the data of transactions on a block. This method takes three parameters (sender’s information, receiver’s information, and amount) and adds the transaction data to the self.current_data list.

Here is the code:

def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True
Effecting the Proof of Work

In blockchain technology, Proof of Work (PoW) refers to the complexity involved in mining or generating new blocks on the blockchain.

For example, the PoW can be implemented by identifying a number that solves a problem whenever a user completes some computing work. Anyone on the blockchain network should find the number complex to identify but easy to verify — this is the main concept of PoW.

This way, it discourages spamming and compromising the integrity of the network.

In this article, we’ll illustrate how to include a Proof of Work algorithm in a blockchain cryptocurrency project.

Finalizing With the Last Block

Finally, the latest_block() helper method is used for retrieving the last block on the network, which is actually the current block.

Here is the code:

def latest_block(self):
        return self.chain[-1]
Implementing Blockchain Mining

Now, this is the most exciting section!

Initially, the transactions are kept in a list of unverified transactions. Mining refers to the process of placing the unverified transactions in a block and solving the PoW problem. It can be referred to as the computing work involved in verifying the transactions.

If everything has been figured out correctly, a block is created or mined and joined together with the others in the blockchain. If users have successfully mined a block, they are often rewarded for using their computing resources to solve the PoW problem.

Here is the mining method in this simple cryptocurrency blockchain project:

def block_mining(self, details_miner):
            self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)
Summary

Here is the whole code for our crypto blockchain class in Python:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()
    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()
    def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
    def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block
    @staticmethod
    def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True
    def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True        
    @staticmethod
    def proof_of_work(last_proof):
        pass
    @property
    def latest_block(self):
        return self.chain[-1]
    def chain_validity(self):
        pass        
    def block_mining(self, details_miner):       
        self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awared with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)  
    def create_node(self, address):
        self.nodes.add(address)
        return True
    @staticmethod
    def get_block_object(block_data):        
        return Block(
            block_data['index'],
            block_data['proof_number'],
            block_data['previous_hash'],
            block_data['data'],
            timestamp=block_data['timestamp']
        )
blockchain = BlockChain()
print("GET READY MINING ABOUT TO START")
print(blockchain.chain)
last_block = blockchain.latest_block
last_proof_number = last_block.proof_number
proof_number = blockchain.proof_of_work(last_proof_number)
blockchain.get_data(
    sender="0", #this means that this node has constructed another block
    receiver="LiveEdu.tv", 
    amount=1, #building a new block (or figuring out the proof number) is awarded with 1
)
last_hash = last_block.compute_hash
block = blockchain.build_block(proof_number, last_hash)
print("WOW, MINING HAS BEEN SUCCESSFUL!")
print(blockchain.chain)

Now, let’s try to run our code to see if we can generate some digital coins...

Wow, it worked!

Conclusion

That is it!

We hope that this article has assisted you to understand the underlying technology that powers cryptocurrencies such as Bitcoin and Ethereum.

We just illustrated the basic ideas for making your feet wet in the innovative blockchain technology. The project above can still be enhanced by incorporating other features to make it more useful and robust.

Learn More

Thanks for reading !

Do you have any comments or questions? Please share them below.

How to Plot Cryptocurrency Price Charts with Python in 10 minutes

How to Plot Cryptocurrency Price Charts with Python in 10 minutes

Starting from complete scratch, you will plot your first Cryptocurrency candlestick data charts by the end of this article

Starting from complete scratch, you will plot your first cryptocurrency candlestick data chart by the end of this article - In less than 10 minutes.

Building tools which take advantage of exchange data is a nightmare in the cryptocurrency space. The limited number of available tools means you need to develop features from nothing.

Since every exchange provides different endpoints for collecting data, this quickly turns into a black hole which will consume your time.

Each exchange requires custom code and infrastructure to handle the intricacies of what they offer.

Thankfully, the Universal Crypto Exchange APIs normalize this data for us. An API which you can freely use to access historical and live data.

This article will describe how to set up your first script to access live market data from any exchange, normalize it into a cohesive format, and plot it. There is no complex configuration or development.

Let’s get started!

Install Libraries

Before we get started writing the script, we need to install a few libraries. If you use pip, this can be done simply by running the following commands.

pip install shrimpy-python
pip install pandas
pip install plotly==4.1.0

Generate API Keys

After installing the necessary libraries, sign up for a Shrimpy Developer API account. These are the APIs which provide the exchange data. It’s free and takes only a few seconds to sign up.

After signing up, generate your master key. These keys are used to sign requests to Shrimpy and access crypto market data.

Make sure to securely store your public and secret keys. They will be needed for later steps.

Writing Our First Script

We’re now ready to begin writing our first script. The script for this article will collect candlestick market data from the exchange we specify, organize it in a way that’s understandable for the plotting library, and display it.

Import Libraries

In this script, we will be using the Plotly Library. This will provide a convenient way for us to get up and running without much effort.

Import these libraries into your script so we can collect our data and graph it.

import shrimpy
import plotly.graph_objects as go

Assign Keys

Before we can access any data from Shrimpy, we need to make sure we correctly sign our requests. This requires us to pass in our public and private keys. For now, let’s just assign them for later use.

public_key = '8x71n32d8cfbnnn1xzimjustkeyboardmashing8xn1t8jyv5098'
secret_key = '771dc5nxct4709672v4n09xn0morekeyboardmashing9475c029374n0xx4n50'

Create Client

To create the client, pass in the public and secret keys which were assigned in the previous step. The client will then conveniently handle the signing of each request, so you can focus on accessing the data and building tools with the data.

client = shrimpy.ShrimpyApiClient(public_key, secret_key)

Get Candles

It’s time to get our candlestick data from Shrimpy. Use the client to call the endpoint for retrieving the candlesticks.

Just make sure to pass in the exchange, trading pair, and interval you wish to access.

Example 1:

candles = client.get_candles(
    'binance',  # exchange
    'XLM',      # base_trading_symbol
    'BTC',      # quote_trading_symbol
    '15m'       # interval
)

Example 2:

candles = client.get_candles(
    'bittrex',  # exchange
    'LTC',      # base_trading_symbol
    'BTC',      # quote_trading_symbol
    '1h'        # interval
)

Example 3:

candles = client.get_candles(
    'kucoin',   # exchange
    'ETH',      # base_trading_symbol
    'USDT',     # quote_trading_symbol
    '1d'        # interval
)

Observe how we are able to change each of these parameters to configure the data we want to access.

The supported time intervals for each candle include the following:

1m, 5m, 15m, 1h, 6h, or 1d

Convert Data

Once the data has been collected from Shrimpy, we want to convert the data to the format which is accepted by the plotting library Plotly. To do this, we will go through the candlesticks we collected from Shrimpy and assign each of the candlestick components to an element of the candle.

dates = []
open_data = []
high_data = []
low_data = []
close_data = []

for candle in candles:
    dates.append(candle['time'])
    open_data.append(candle['open'])
    high_data.append(candle['high'])
    low_data.append(candle['low'])
    close_data.append(candle['close'])

The result of this step is each individual candlestick will be broken out into a list which holds the individual component of every candlestick.

Generate Figure

Finally, it’s time to generate the figure. Use the Plotly library to create the chart that we will display, then display the chart.

fig = go.Figure(data=[go.Candlestick(x=dates,
                       open=open_data, high=high_data,
                       low=low_data, close=close_data)])

fig.show()

Calling fig.show() displays the graph. This will look something like the following chart.

This is image title

The end result of the script is a graph which displays the candlesticks for an individual asset on an individual exchange over time.

Putting It All Together

Now that we’ve walked through each element of the script step-by-step, it’s time to put everything together.

# import the libraries we need
import shrimpy
import plotly.graph_objects as go

# insert your public and secret keys here
public_key = '8x71n32d8cfbnnn1xzimjustkeyboardmashing8xn1t8jyv5098'
secret_key = '771dc5nxct4709672v4n09xn0morekeyboardmashing9475c029374n0xx4n50'

# create the client
client = shrimpy.ShrimpyApiClient(public_key, secret_key)

# get the candles
candles = client.get_candles(
    'binance',  # exchange
    'XLM',      # base_trading_symbol
    'BTC',      # quote_trading_symbol
    '15m'       # interval
)

# create lists to hold our different data elements
dates = []
open_data = []
high_data = []
low_data = []
close_data = []

# convert from the Shrimpy candlesticks to the plotly graph objects format
for candle in candles:
    dates.append(candle['time'])
    open_data.append(candle['open'])
    high_data.append(candle['high'])
    low_data.append(candle['low'])
    close_data.append(candle['close'])

# construct the figure
fig = go.Figure(data=[go.Candlestick(x=dates,
                       open=open_data, high=high_data,
                       low=low_data, close=close_data)])

# display our graph
fig.show()

The final script can be run, altered, and leveraged to generate graphs similar to the one depicted above. Just make sure to insert your own public and secret keys so your client can properly sign requests.

More Scripts

If you want more ideas for developing your own scripts, explore everything that’s offered by the Universal Crypto Exchange APIs. You can find the Node and Python libraries for these APIs here:

Node

Python

Thank for reading! Please share if you liked it!

Automating Crypto Portfolios Value with Trading Scripts using Python

Automating Crypto Portfolios Value with Trading Scripts using Python

A Python Script to Check Your Crypto Portfolio Value. Install Library. Import Library. API Keys. Create Client. Create User. Link Exchange Account. Get Asset Balances.

Instead of collecting more market data, let’s try something different. Most cryptocurrency users currently have funds located on an exchange. We can leverage the exchange’s APIs to access the asset balances and calculate their value without ever going to the exchange.

The following tutorial will take a step-by-step approach to detail how you can connect to an exchange account through APIs and access your balance data without ever logging into your exchanges.

Install Library

Before we can start writing our scripts and connecting to exchanges, let’s set up our development environment by first installing the libraries we need to complete our project.

pip install shrimpy-python

For this script, we will only need access to the Shrimpy Developer API Python library. This library makes it easy to connect to exchanges, manage assets, collect data, and build applications. The full APIs and their documentation can be found here.

Import Library

Once the library is installed, we can import it into our script to access all the features it provides.

import shrimpy

That’s it for libraries, so we’re ready to start constructing the meat of our script.

API Keys

There are 2 different sets of API keys we need in order to access our balance data on the exchange.

Exchange Account

The first set of API keys we need is the exchange API keys. These keys are found by going to your exchange of choice and creating a new set of API keys.

Our script will require the ability to access balance data, so make sure you have enabled the permissions on your exchange API keys for reading balance data from your exchange account. In this tutorial, you won’t need to enable the permissions for trading or withdrawals.

You can find a number of helpful tutorials on how to access exchange API keys here.

Once you’ve generated your API keys, save them as variables which we will use in the next steps to access your exchange account balances.

exchange_name = 'bittrex'
exchange_public_key = 'fbnnn1xzimjustkeyboardmashing8xn1t8'
exchange_secret_key = '09672v4n09xn0morekeyboardmashing947'

Note: Shrimpy supports 16 different exchanges. Use the following names when creating your exchange_name variable: binance, bittrex, bittrexinternational, kucoin, poloniex, bibox, huobi, hitbtc, bitstamp, bitfinex, coinbasepro, kraken, gemini, huobiglobal, bitmart, and okex.

Shrimpy Account

The second set of API keys we need to access our balance data on the exchange is the Shrimpy Developer API Master Keys.

To get your set of keys, sign up for your free Shrimpy account and select the option to “Create Api Master Key”.

When selecting the permissions for this key, ensure you have enabled the options for “User” and “Account”. These are required to link and access exchange accounts for users.

With your Shrimpy Developer API key in hand, assign it to variables which can be accessed in a future step.

shrimpy_public_key = '8x7138n1xzimjustkeyboardmashing8xn1t8jv5098'
shrimpy_secret_key = '771dc5n72v4n09xn0morekeyboardmashing9475c0294n50'
Create Client

Use the keys we generated in the previous step to create your Shrimpy client.

client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)
Create User

The Shrimpy APIs require exchange accounts to be connected to users. That way we can generate any number of users who manage multiple individual exchange accounts. This provides a built-in way to determine who owns which exchange account.

Let’s create our user who will be the one which gets linked to our exchange accounts.

create_user_response = client.create_user('Satoshi Nakamoto')
user_id = create_user_response['id']
Link Exchange Account

Once the user is created, linking an exchange to the user is straight forward. Simply specify the user, exchange name, and the API keys for that exchange.

link_account_response = client.link_account(
    user_id,
    exchange_name,
    exchange_public_key,
    exchange_secret_key
)

account_id = link_account_response['id']

As soon as the exchange account is linked, Shrimpy will automatically begin collecting data from the exchange regarding the account’s balances. This process can take a moment, so let’s take 5 seconds before going on to the next step.

Note: You can link up to 20 exchange accounts to a single user. That means if you have accounts with Bittrex, Binance, KuCoin, BitStamp, Kraken, and Coinbase Pro (and more) you can link them all to a single user.

Get Asset Balances

We’re almost done. Let’s grab the exchange account balance from Shrimpy. Simply call the library and ask for the balance data for a specific user and account.

The response to this call will return every asset we own, the balances for these assets, and the dollar values.

balance = client.get_balance(user_id, account_id)
holdings = balance['balances']
Print Out Balances

The final step is to calculate the balances and display them. In this case, we will just print them out, but you can certainly do anything you wish with the balances.

We will iterate over each asset in the returned list and display the asset and the value of our asset holdings.

total = 0

for asset in holdings:
    print(asset['symbol'] + ' ' + str(asset['usdValue']))
    total += asset['usdValue']

print("Total" + ' $' + str(total))

That’s it! You have successfully connected to your exchange account and accessed your balances without logging into the exchange through the UI.

Whenever you wish to update your balances, you can simply request the latest balances from Shrimpy again by passing in your user ID and account ID. Shrimpy will handle the rest by accessing your linked exchange account and collecting the balance data. You DO NOT need to re-link your keys every time or create a new user each time. Those steps are a one-time thing.

Putting it All Together

This is image title

The first time you want to connect to an exchange and access the balance data for the assets you hold on the exchange, you can run the entire script here. Each subsequent time, you only need to run the portion which collects the balance data

This script can also easily be modified to link multiple exchanges, so you can access your balances across every exchange for which you have an account.

First Run

Fill in the information for your Shrimpy Master API keys and Exchange Keys to run this script. I’ve used fake keys for this tutorial.

# import required libraries
import shrimpy
import time

# assign your Shrimpy Master API keys for later use
shrimpy_public_key = '8x7138n1xzimjustkeyboardmashing8xn1t8jv5098'
shrimpy_secret_key = '771dc5n72v4n09xn0morekeyboardmashing9475c0294n50'

# assign your exchange keys for which you wish to access the balance data
exchange_name = "bittrex"
exchange_public_key = 'fbnnn1xzimjustkeyboardmashing8xn1t8'
exchange_secret_key = '09672v4n09xn0morekeyboardmashing947'

# create the Shrimpy client
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)

# create a user which will be linked to our exchange
create_user_response = client.create_user('The Shrimp Master')
user_id = create_user_response['id']

# link our first exchange so we can access balance data
link_account_response = client.link_account(
    user_id,
    exchange_name,
    exchange_public_key,
    exchange_secret_key
)

account_id = link_account_response['id']

# wait while Shrimpy collects data for the exchange account
# only required the first time linking
time.sleep(5)

# collect asset balances on the exchange
balance = client.get_balance(user_id, account_id)
holdings = balance['balances']

total = 0

# calculate and print balances for each asset. 
for asset in holdings:
    print(asset['symbol'] + ' $' + str(round(asset['usdValue'], 2)))
    total += asset['usdValue']

print("Total" + ' $' + str(round(total, 2)))

Subsequent Runs

After running the initial script, you can simply access your balances at any time by running this second script.

Notice this script removed the steps to create a user, link an exchange account, and sleep for a few seconds.

Shrimpy will automatically remember this information for you, so all you need to do is connect to the Shrimpy APIs again, tell Shrimpy what account you want balance data for, and print out the balance data which is returned in the response.

# import required libraries
import shrimpy

# input your user and account IDs
user_id = 'dc12349b-1234-12k4-123n12n12nnf'
account_id = 12345

# assign your Shrimpy Master API keys for later use
shrimpy_public_key = '8x7138n1xzimjustkeyboardmashing8xn1t8jv5098'
shrimpy_secret_key = '771dc5n72v4n09xn0morekeyboardmashing9475c0294n50'

# create the Shrimpy client
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)

# collect asset balances on the exchange
balance = client.get_balance(user_id, account_id)
holdings = balance['balances']

total = 0

# calculate and print balances for each asset. 
for asset in holdings:
    print(asset['symbol'] + ' $' + str(asset['usdValue']))
    total += asset['usdValue']

print("Total" + ' $' + str(total))
Crypto Developers

The Shrimpy community is becoming the largest network of builders. People who are looking to push the bounds of what’s possible with crypto application development, trading, and market data analysis.

Find the full Python and Node libraries here:

Node

Python

We would love to hear more about what you’re building, so don’t hesitate to reach out and share your story!

Thank for reading! Please share if you liked it!

Script for Live Bitcoin Price Ticker using Websockets

Script for Live Bitcoin Price Ticker using Websockets

Websockets are just part of the equation. Executing real-time trades, collecting historical order book snapshots, and managing exchange accounts is all part of the API.

Websockets are just part of the equation. Executing real-time trades, collecting historical order book snapshots, and managing exchange accounts is all part of the API.

A 5-minute tutorial to connect to cryptocurrency exchange websockets.

Check the time - I have 5 minutes to get you connected to a cryptocurrency exchange’s websocket.

That’s a bold assertion, so let’s not waste any time.

Install Libraries

Before we can write our Python script to connect to exchange websockets, we need to install a library. Yes, exactly one library.

Run the following command to install Shrimpy:

pip install shrimpy-python

1 minute down - already 20% done.

Generate API Keys

After installing the Shrimpy Python Library, register for a Shrimpy Developer API account. This service will be used to access the exchange websockets.

Once you’ve signed up for an account, create a new master key. The master key is how you sign requests and access crypto market data. Save the public and private keys for later use. Make sure to enable “data” permissions on these keys. Some data which is available through the APIs includes candlestick (OHLCV) data, historical order book snapshots, and live trade data.

3 minutes passed - Uh oh, we haven’t even started coding yet.

The Code

Stretch those fingers because we’re about to set a new record for the fastest time anyone has ever connected to a crypto exchange websocket.

Library Import

The Shrimpy library has already been installed, so import it into your script.

import shrimpy

Define Handler

To receive data out of the websocket, we need to create a handler. This handler will simply print the price of each trade which is received through the trade websocket.

Since we can receive multiple trades per message, we will only consider the last trade in the message to be the current ticker price.

def error_handler(err):
    print(err)

def handler(msg):
    ticker = msg['content'][len(msg['content']) - 1]['price']
    print(ticker)

Client Creation

Create a client object by calling into the Shrimpy library. Don’t forget to first get the token which is required to create the client. You can get this client by creating an API client, which is created by passing in your public and private API keys. This will help you manage your websocket connection and subscriptions.

public_key = '6d73c2464a71b94a81aa7b13d...'
private_key = 'e6238b0de3cdf19c7861f8e8f5d137ce7113ac1e884b191a14bbb2...'

api_client = shrimpy.ShrimpyApiClient(public_key, private_key)
raw_token = api_client.get_token()
client = shrimpy.ShrimpyWsClient(error_handler, raw_token['token'])

4 minutes now - it’s going to be close.

Declare Subscribe Data

Before we can subscribe to a websocket stream, we must define the subscription for which we want to connect.

subscribe_data = {
    "type": "subscribe",
    "exchange": "binance",
    "pair": "btc-usdt",
    "channel": "trade"
}

Connect Websocket

Start processing the Shrimpy websocket stream by subscribing to the channel.

client.connect()
client.subscribe(subscribe_data, handler)

… and 5 minutes - game, set, match.

Note: You can subscribe to 100 different channels per client. Shrimpy allows each IP to manage up to 10 clients for a total of 1,000 channels per IP.

Just like that, you are now live streaming the latest trade data from Binance. In the handler we defined, that data is parsed to only extract the price at which each trade was executed. That allows us to print the tick-by-tick price of the cryptocurrency at this exact moment.

Disconnect Websocket

Once you’ve finished collecting data, disconnect the client.

client.disconnect()

This is image title

After connecting to the websocket, you will begin to see price data stream in real time.

Putting it all Together

That was quick, so let’s take a moment to regroup and get a full picture of what we just accomplished.

In the last 5 minutes, we leveraged the Shrimpy APIs and connected to the trade websocket for a crypto exchange. This allowed us to get the real-time ticker price for an asset.

# import the Shrimpy library for crypto exchange websockets
import shrimpy

# a sample error handler, it simply prints the incoming error
def error_handler(err):
    print(err)

# define the handler to manage the output stream
def handler(msg):
    # multiple trades can be returned in each message, so take the last one
    ticker = msg['content'][len(msg['content']) - 1]['price']
    print(ticker)

# input your Shrimpy public and private key
public_key = '6d73c2464a71b94a81aa7b13d...'
private_key = 'e6238b0de3cdf19c7861f8e8f5d137ce7113ac1e884b191a14bbb2...'

# create the Shrimpy websocket client
api_client = shrimpy.ShrimpyApiClient(public_key, private_key)
raw_token = api_client.get_token()
client = shrimpy.ShrimpyWsClient(error_handler, raw_token['token'])

# construct the subscription object
subscribe_data = {
    "type": "subscribe",
    "exchange": "binance",
    "pair": "btc-usdt",
    "channel": "trade"
}

# connect to the Shrimpy websocket and subscribe
client.connect()
client.subscribe(subscribe_data, handler)

# disconnect from the websocket once data collection is complete
client.disconnect()

Now, Binance isn’t the only exchange supported by Shrimpy and the btc-usdt pair isn’t the only trading pair.

The Shrimpy APIs support 17 different exchanges and over 1,300 markets. Each of the most prominent exchanges can be accessed through a simple consolidated websocket API.

Not only that, websockets are just part of the equation. Executing real-time trades, collecting historical order book snapshots, and managing exchange accounts is all part of the API. You can find the full documentation here.

End

Users are able to configure a custom cryptocurrency portfolio and implement a passive rebalancing strategy, removing the hassle of having to actively trade crypto. Shrimpy’s Developer Trading API is a unified way to integrating trading functionality across every major exchange. Collect historical market data, access real-time websockets, execute advanced trading strategies, and manage an unlimited number of users.

Thank for reading !