Create a CryptoCurrency Price Update website using Wix Code

In this tutorial, we are going to create a CryptoCurrency Price Update website using Wix Code.&nbsp;<a href="https://www.wix.com/mystunningwebsites/wixcode4?utm_campaign=ma_dunebook_wixcode&amp;experiment_id=dunebook" target="_blank">Wix Code</a>&nbsp;is a new advanced feature added to the Wix platform that makes it easier to create custom functionalities for your Wix website. As you may already know Wix is a website builder that lets you create a website from scratch without writing any code.

In this tutorial, we are going to create a CryptoCurrency Price Update website using Wix Code. Wix Code is a new advanced feature added to the Wix platform that makes it easier to create custom functionalities for your Wix website. As you may already know Wix is a website builder that lets you create a website from scratch without writing any code.

Quoting the Wix Code website:

“Wix Code makes it easy to build web applications and robust websites. It’s serverless, hassle-free coding. Set up database collections, create content-rich websites, add custom forms and change site behavior with our APIs.”

Wix code, however, was created to target developers who are willing to customize their website beyond the simple drag and drop and ready-made widgets already created by Wix. With Wix code you have full control of your website, you can create custom widgets and add custom behaviors as you desire. Read more about Wix Code here

We are going to take advantage of the Wix Code API in this tutorial to query a third party API and display data dynamically. We will build a Cryptocurrency app that will enable a user to keep track of their favorite Coins by search and also display the top 10 performing cryptocurrencies.

So to get started, you need to create an account on Wix, visit the Signup page to create an account. After that create a new site by hitting the plus icon on the top right corner of the page.

Creating a new Wix site

Which will take you to a new page asking, what kind of website do you want to create? You can choose any option you want there. I chose business.

Creating a Wix site, what kind of website do you want to create?

And then it takes you to the next page where you will be asked to choose how you want to create your website. To be able to use Wix code you have to choose to create your website with Wix editor.

Choose how you want to create your Wix site

And then on the next page, you will be asked to choose a template for your website. You can choose to either create with one of the existing templates or choose to start yours from scratch by choosing the blank template.

On any template you decide to choose, just click on edit so we can start developing our app. You can find edit when you hover over any of the templates. Upon clicking it will take you to the Wix website editor.

Choosing and Editing a Template in Wix

We can now start customizing our chosen template. We will add some important HTML elements.

We also need to enable Wix Code on this template. To do so, we click on Tools and then enable the Developer Tools, which is disabled by default.

Enabling the Wix Code Developer Tools

So the first element we need to add to the page is an input control, this is where the user will type in the name of the cryptocurrency they want to keep track of, and then search for its information using the CoinMarketCap API. To add that navigate and click on plus, which will open a panel with lots of HTML elements that you can use on your page. To add an element to your page, you can either drag and drop it anywhere on your page or double-click on it.

Adding an HTML element to your page in Wix

As you can see the input element gets assigned an ID which must always be unique. We will use the ID to interact with this Input element, later on, to get the value of the user input and then pass it on to the CoinMarketCap API. Let’s change the name of the Input element to something more friendly. Follow the instruction as in the image below.

Changing the ID of an HTML element in Wix Code

Next, let us place a Button beside the input box which will initiate the search when the user clicks on it. We can place a button on the page by repeating the same steps we used to add the input box into the page. We can change the text of the button to Search and also give it an ID of search. After making the changes, my page now looks like this:

Adding a Button to a page in Wix

Later on, we will register an onClick event handler on this button, such that when a user clicks on it, it will initiate a Wix Code function that we will write. This function will search the CoinMarketCap API for any valid currency value you type into the Input element and then retrieve its information and then display it to the user.

But before doing that we need to add another HTML element to the page, a Text element where the result of the search will be displayed. So go ahead and click on the Plus icon again, navigate to Text. I have inserted a paragraph on the page, changed the ID to searchResult and also edited the text content and gave it a simple title of Search Result.

Insert a Text to display search result in Wix Code

This concludes the design and layout of our page and now we can start coding the main logic of the site which is to interact directly with the CoinMarketCap API. You can get an overview and explore the CoinMarketCap API more here. To preview your design you should click Save on the navigation bar before clicking Preview.

Next, We will create a method called getCoinInfo()

With Wix Code it is easy to add a Backend code, you can write functions that you would rather have to write in Backend programming languages like PHP, Python or Ruby.

To begin to write a backend code, navigate to the Arrow function in the footer of the page as shown in the image below.

Adding Backend Code to a Wix Code Website

Once you click on Add a new Web Module you will be given a name suggestion of aModule.jsw I renamed mine to apiModule.jsw, rename the module and hit enter. Once you hit enter you should be shown a code editor page that looks like this:

Creating a Backend Module in Wix Code
import {fetch} from 'wix-fetch';

export function getCoinInfo(currencyName) {
const url = 'https://api.coinmarketcap.com/v1/ticker/' + currencyName + '/';

return fetch(url, {method: 'get'})
.then(response => response.json())
}

With the first import statement, we’re making sure that fetch is imported from the wix-fetch package. With fetch, we are able to initiate an HTTP call needed to retrieve information from the external API. The fetch function is then used within the function getCoinInfo to initiate an HTTP GET request to the API endpoint. The fetch function accepts/expects two parameters:

  • The first parameter is a string containing the URL of the API endpoint.
  • The second parameter is a configuration object in JSON format. In our specific case, this object is containing the property method which is set to string ‘get’ which simply means, we’re initiating an HTTP GET request.
  • Fetch is returning a promise so we can use method chaining and add a .then() to retrieve the value being returned by fetch.

We created a URL string, the base URL, which is passed into the fetch function call, the function getCoinInfo is expecting to get the name of the cryptocurrency as an input parameter. The complete URL is built by concatenating the base URL endpoint https://api.coinmarketcap.com/v1/ticker/ with the currency name. Read more about wix-fetch here. It’s just an extension of the JavaScript fetch API.

Writing a custom function in Wix code editor and navigating back to the Website

Next, we will use the backend code we have just created and then connect it with Search button we created earlier. We want the backend code to run when a user types in the name of a currency in the input element and clicks on the search button. To make this work, we will register an onClick event on the search button. Select the button and then in the properties panel click on the plus icon opposite the onClick event listed there as shown in the image below:

Creating an onClick event in Wix Code

We will make use of the function getCoinInfo in the code editor that opened after clicking on the plus icon of the onClick event. Insert the following import statement first at the top of the editor.

import {getCoinInfo} from 'backend/apiModule';

Now, we can use the getCoinInfo() function on the frontend side by simply calling it inside the search_click() function created for the onClick event of the search button.

import {getCoinInfo} from 'backend/apiModule';

export function search_click(event, $w) {
getCoinInfo($w('#currencyName').value)
.then(response => {
$w('#searchResult').text = "Name: " + response[0].name + "n"

  • "Symbol: " + response[0].symbol + "n"
  • "Price (USD): " + response[0].price_usd;
    });
    }

First we get the value of the text input from user, which is the name of the currency that the getCoinInfo() function expects, the javascript’s fetch api responds with a promise so we use method chaining to apply the then() which is where we retrieve the currency info.

After writing this code, you can hit save and then preview to see your site up and running.

Here’s the result after testing it:

Query an API with Wix Code

You can display more results from the API by simply adding from the list on CoinMarketCap API .

We can further improve the app by adding another function to get the first 10 currencies from the Coin Market Cap API. This will be displayed directly under the search result. Before proceeding to write the function, let’s add another Text element and then give it an ID of coinList. After that, navigate to the Backend/apiModule.jsw file and then add the function there.

export function getTopCoins() {
const url = 'https://api.coinmarketcap.com/v1/ticker/?limit=10';

return fetch(url, {method: 'get'})
.then(response => response.json());
}


And then navigate back to Home. On the home do the following, Choose the Coin List which should have coinList Id and then navigate to the onViewportEnter event, click on the plus icon, which will create a new function in the frontend editor. And then import the getTopCoins()  from the backend.

Adding a function that executes on page load in Wix Code

After adding the content of the function for the onViewportEnter event, my code looks like this:

Adding a function that executes on page load in Wix Code
export function page1_viewportEnter(event, $w) {
getTopCoins().then(response => {
$w('#coinList').text = "Name: " + response[0].name + "t t"

  • "Symbol: " + response[0].symbol + "t t"
  • "Price (USD): " + response[0].price_usd + "n n"
  • "Name: " + response[1].name + "t t"
  • "Symbol: " + response[1].symbol + "t t"
  • "Price (USD): " + response[1].price_usd + "n n"
  • "Name: " + response[2].name + "t t"
  • "Symbol: " + response[2].symbol + "t t"
  • "Price (USD): " + response[2].price_usd + "n n"
  • "Name: " + response[3].name + "t t"
  • "Symbol: " + response[3].symbol + "t t"
  • "Price (USD): " + response[3].price_usd + "n n"
  • "Name: " + response[4].name + "t t"
  • "Symbol: " + response[4].symbol + "t t"
  • "Price (USD): " + response[4].price_usd + "n n"
  • "Name: " + response[5].name + "t t"
  • "Symbol: " + response[5].symbol + "t t"
  • "Price (USD): " + response[5].price_usd + "n n"
  • "Name: " + response[6].name + "t t"
  • "Symbol: " + response[6].symbol + "t t"
  • "Price (USD): " + response[6].price_usd + "n n"
  • "Name: " + response[7].name + "t t"
  • "Symbol: " + response[7].symbol + "t t"
  • "Price (USD): " + response[7].price_usd + "n n"
  • "Name: " + response[8].name + "t t"
  • "Symbol: " + response[8].symbol + "t t"
  • "Price (USD): " + response[8].price_usd + "n n"
  • "Name: " + response[9].name + "t t"
  • "Symbol: " + response[9].symbol + "t t"
  • "Price (USD): " + response[9].price_usd + "n n"
    });
    }


This function is displaying all the 10 currencies that was requested from the CoinMarketCap API in the backend code and function getTopCoin() through this url https://api.coinmarketcap.com/v1/ticker/?limit=10.

The final output looks like this:

Query a third party API with Wix Code (Result)
Update

Due to high demand from our readers, we’ve extended the app further and made the UI even better, but to do that. We wanted to add images of the currencies, but Coin Market Cap API does not provide images for these currencies so we had to query another API to get the images of the currencies. Here’s how we did that:

Navigate back to the Backend/apiModule.jsw file and add this code to query the CryptoCompare API. The API has an endpoint for ImageUrl for the images/logo of each of the currencies. You can navigate here to see the Logo of Bitcoin for example.

export function getImageFromCryptoCompare() {
const url = 'https://min-api.cryptocompare.com/data/all/coinlist';

return fetch(url, {method: 'get'})
.then(response => response.json());
}

Import the backend function into the frontend code editor. And then Add the functions to display the data.

import {getImageFromCryptoCompare} from 'backend/apiModule';

Navigate to the Home and then Add a Repeater from the Lists & Grids.

Adding and displaying data with Repeaters in Wix Code

You have to add a single repeater for each of the ten coins. And then give each of the HTML text elements a unique Id. The code to interact with the repeaters should be placed in $w.onReady() function since we want the function to execute immediately the page loads. Each section of this code represents data being displayed on each of the repeaters.

$w.onReady(function () {
getTopCoins().then(response => {
getImageFromCryptoCompare().then(resp => {
$w('#image1').src = 'https://www.cryptocompare.com' + resp.Data[response[0].symbol].ImageUrl;
$w('#coin1').text = response[0].name;
$w('#text23').text = response[0].price_usd;
$w('#text13').text = "Rank: " + response[0].rank;
$w('#text21').text = response[0].total_supply;
$w('#text22').text = response[0].available_supply;
$w('#text20').text = response[0].max_supply;
$w('#text19').text = response[0].symbol;

$w('#image2').src = 'https://www.cryptocompare.com' + resp.Data[response[1].symbol].ImageUrl;
$w('#coin2').text = response[1].name;
$w('#text35').text = response[1].price_usd;
$w('#text25').text = "Rank: " + response[1].rank;
$w('#text33').text = response[1].total_supply;
$w('#text34').text = response[1].available_supply;
$w('#text32').text = response[1].max_supply;
$w('#text31').text = response[1].symbol;

$w('#image3').src = 'https://www.cryptocompare.com' + resp.Data[response[2].symbol].ImageUrl;
$w('#coin3').text = response[2].name;
$w('#text47').text = response[2].price_usd;
$w('#text37').text = "Rank: " + response[2].rank;
$w('#text45').text = response[2].total_supply;
$w('#text46').text = response[2].available_supply;
$w('#text44').text = response[2].max_supply;
$w('#text43').text = response[2].symbol;

$w('#image4').src = 'https://www.cryptocompare.com' + resp.Data[response[3].symbol].ImageUrl;
$w('#coin4').text = response[3].name;
$w('#text59').text = response[3].price_usd;
$w('#text49').text = "Rank: " + response[3].rank;
$w('#text57').text = response[3].total_supply;
$w('#text58').text = response[3].available_supply;
$w('#text56').text = response[3].max_supply;
$w('#text55').text = response[3].symbol;

$w('#image5').src = 'https://www.cryptocompare.com' + resp.Data[response[4].symbol].ImageUrl;
$w('#coin5').text = response[4].name;
$w('#text71').text = response[4].price_usd;
$w('#text61').text = "Rank: " + response[4].rank;
$w('#text69').text = response[4].total_supply;
$w('#text70').text = response[4].available_supply;
$w('#text68').text = response[4].max_supply;
$w('#text67').text = response[4].symbol;

$w('#image6').src = 'https://www.cryptocompare.com' + resp.Data[response[5].symbol].ImageUrl;
$w('#coin6').text = response[5].name;
$w('#text83').text = response[5].price_usd;
$w('#text73').text = "Rank: " + response[5].rank;
$w('#text81').text = response[5].total_supply;
$w('#text82').text = response[5].available_supply;
$w('#text80').text = response[5].max_supply;
$w('#text79').text = response[5].symbol;

$w('#image6').src = 'https://www.cryptocompare.com' + resp.Data[response[5].symbol].ImageUrl;
$w('#coin6').text = response[5].name;
$w('#text83').text = response[5].price_usd;
$w('#text73').text = "Rank: " + response[5].rank;
$w('#text81').text = response[5].total_supply;
$w('#text82').text = response[5].available_supply;
$w('#text80').text = response[5].max_supply;
$w('#text79').text = response[5].symbol;

$w('#image7').src = 'https://www.cryptocompare.com' + resp.Data[response[6].symbol].ImageUrl;
$w('#coin7').text = response[6].name;
$w('#text95').text = response[6].price_usd;
$w('#text85').text = "Rank: " + response[6].rank;
$w('#text93').text = response[6].total_supply;
$w('#text94').text = response[6].available_supply;
$w('#text92').text = response[6].max_supply;
$w('#text91').text = response[6].symbol;

$w('#image8').src = 'https://www.cryptocompare.com' + resp.Data[response[7].symbol].ImageUrl;
$w('#coin8').text = response[7].name;
$w('#text107').text = response[7].price_usd;
$w('#text97').text = "Rank: " + response[7].rank;
$w('#text105').text = response[7].total_supply;
$w('#text106').text = response[7].available_supply;
$w('#text104').text = response[7].max_supply;
$w('#text103').text = response[7].symbol;

$w('#image9').src = 'https://www.cryptocompare.com' + resp.Data[response[8].symbol].ImageUrl;
$w('#coin9').text = response[8].name;
$w('#text119').text = response[8].price_usd;
$w('#text109').text = "Rank: " + response[8].rank;
$w('#text117').text = response[8].total_supply;
$w('#text118').text = response[8].available_supply;
$w('#text116').text = response[8].max_supply;
$w('#text115').text = response[8].symbol;

$w('#image10').src = 'https://www.cryptocompare.com' + resp.Data[response[9].symbol].ImageUrl;
$w('#coin10').text = response[9].name;
$w('#text131').text = response[9].price_usd;
$w('#text121').text = "Rank: " + response[9].rank;
$w('#text129').text = response[9].total_supply;
$w('#text130').text = response[9].available_supply;
$w('#text128').text = response[9].max_supply;
$w('#text127').text = response[9].symbol;
});
});
});

For clarity, here’s how the code looks in the Home Page Editor.

Query CryptoCompare and Coin Market Cap API with Wix Code

As you can see on line 9, for example, we get the symbol of the coin from CoinMarketCap API first, which is the response object returned by the getTopCoins() function. And then we pass this symbol to the resp object returned by CryptoCompare API, which is in the getImageFromCyptoCompare() function. And everything else remains the same as we’ve received the info and displayed in the text element earlier.

And the final output after updated design now looks like this:

Display data from Coin Market Cap and Crypto Compare API with Wix Code
Conclusion

Wix Code has great potential that I believe could help the platform continue to grow. The addition of Wix Code to the Wix suite will eventually make it possible to develop a fully functioning app with custom components that will not need a special backend. One of the most significant features of Wix is that it is serverless and Wix code will only continue to expose these benefits. A combination of all the ready-made features and component of Wix plus Wix Code opens up new ways to think about your application, giving you a powerful toolset for creating awesome websites quickly.

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 !