wAgEr: A stablecoin, and a DeFi portfolio manager

Wager is a formal term for betting i.e. to place a sum of money at risk or odds defined by a bookmaker with the goal of making a profit at risk.

Horse racing: Odds or appetite for risk?


The inspiration for wager came at the ETHLondon hackathon from DeFi projects that redefine investment as a “loan”. Investors face opaqueness of risk in investment platforms. There is friction for non-crypto users from lending, investment and participation in smart contract ecosystem. Most of the blockchain projects are not mobile first, and do not harness the power of statistical ML models. My vision is to disrupt this conventional approach with wAgEr which will flip investment into a loan with ML models, smart contracts. An app which has the potential to be a truly decentralised yet personalised trading/investing/lending platform. A wager for its participants.

Basket of tokens


The first step in this journey is in identifying a basket of tokens with low risk, high performance. The challenge is to match the risk appetite of the user quantified by a simple horse racing odds style approach provided by a bookie but complex enough to capture its diverse underlying performance.

Architecting open-source finance

Before I get into the detail of the parameters or levers which control this basket, it’s worth getting a bigger picture of the current state of DeFi. DeFi or Decentralized finance is considered as the most amazing use case to emerge from blockchain. As Bank of England cuts interest rates in the midst of CoVid19 crisis, currently close to 633 Million dollars is locked up in DeFi assets such as tokens, loans, contracts earning interest.

DeFi is parallel to traditional finance, and at the same time an excellent hedge to traditional finance due to many of the assets being uncorrelated with market performance. A more detailed intro to DeFi can be found here. Basically DeFi aims to tokenise assets such as tokens, loans, assets, and derivatives which provide a plethora of benefits for prospective investors over the paper-based incumbents. This includes increased accessibility, accelerated liquidity on the underlying asset, automated compliance and payment distributions and transparent ownership.

An example of this hedge is USDT which provides the stability of dollar currently trading at 1$ but having the speed of crypto in its ability to be integrated in ecosystem. A detailed stable-coin intro can be found here.

Having understood the basics of DeFi we can proceed to the next aspect of addressing the challenge at hand which is to understand the relative performance of tokens. As explained at the outset a simple risk profile interface combined with the duration should estimate and generate a range of personalised tokens. But how do we estimate whether a stable coin with 3% interest rate over 6 months is a risk of 20% or whether a high risk high volatility asset is preferred by the user at 80%? This is traditionally answered by investment funds based upon a wealth of data indicating market movement, transaction volume, money supply etc. An analog of this model can be constructed and used to predict our portfolio. There is one major difference with the traditional companies such as Goldman Sachs, the barrier of entry as an investor is really low, a higher level of transparency can be achieved, and with smart contracts the middle man can be “automated” away. Access to reliable data is the one major stumbling block, and there are promising decentralized oracles. In the next section I will explore one such oracle Amberdata, and how it can be harnessed to evaluate the parameters or levers which can control the basket of tokens.

Token performance: Risk vs Reward

Token performance can be estimated with several parameters its utility, volatility, stability and performance. Most of the users of our platform will expect to wager but some of them will prefer to gain a better interest than a savings account at minimal risk. Thus a combination of token velocity, market cap and stability needs to be considered.

In this excellent paper in 2017 Vitalik Buterin defined the relationship between Market Capitalization, and token velocity with the formula below:


Where: M= total money supply (or total number of coins), C= price of the currency (or 1/P, with P being price level), T= transaction volume (the economic value of transactions per time), H= 1/V (the time that a user holds a coin before using it to make a transaction)

Essentially this implies that Token Velocity or HODL time indicated by H is an important factor. In our case we can adapt this formula by considering the circulating supply of coins, liquid market cap, and given a constant token velocity(relatively constant over a period of 1 week) a snapshot of the currency value can be estimated.

At the other end of the spectrum stablecoins such as Gold backed tokens will provide the necessary stability and satisfy customers who are risk averse. This could also be achieved by combining the HODL factor(inverse of token velocity). The stability of xAUT is better than fiat currencies.

Unique addresses or holders of tokens provide an insight on how many people are actually using the token. Too high a number indicates utility for example US dollar is one of the world’s most used Fiat token, but it has no intrinsic value. By combining the above factors we find that it has a value close to 1 which is quite low.

The opposite of utility tokens are tokens with very high volatility which promise 100x returns but have very high risk. These have short HODL times but differ from utility tokens in their lack of utility. However these speculative tokens are an important factor in increasing the estimated interest rate for short term loans.

Thus a data source which provides an estimate of token velocity, circulating supply, liquid market cap and unique addresses will allow us to make an estimate of the value of the token corresponding to the risk profile.


Basket selection view in app

With the theoretical background for the concept out of the way, let us look at how these are incorporated in wAgEr. I had a weekend of no plans due to Coronavirus, and decided to use it to build a web server running in the background serving data to an Android app.

Feel free to download the APK file Have a look at it and let me know below in comments!

For webserver I used Digital ocean and created a droplet or cloud instance to serve via Flask. The server will be running for another 2 weeks. I will leave it running longer if there is user interest. The next section of the article will explain it in a bit more detail.


Let us break down the components of building this app.

Stream of Data(JSON), Web Server running on Digital Ocean (Python/Flask), App(Java/Android), Smart contract execution.


As mentioned earlier I used Amber Data to get access to the parameters mentioned in the previous sections. Let us examine in detail how to access the JSON strings or nested JSON strings accompanying these data streams. The first step was to capture it directly in the front end, and visualise token performance in the form of a graph.

Peeling the layers of onion in a nested JSON string to reveal the top 5 tokens

The best analogy for working with nested JSON strings is peeling onions… Sometimes the analogy is too perfect with the programmer driven to tears with malformed strings… The first step involves selecting the right onion or URL. In this case let us examine the liquid market cap URL. As shown below I built the URL for a get request with the API key in Java.

Request request = new Request.Builder()
.header("x-api-key", apikey)

Peeling it reveals the payload of the JSON string. This done by calling a map with Map response = gson.fromJson(response.get(“payload”).toString(),Map.class);

Next step involves looking at the object values, and using a Key to get the JSON object.
JsonArray objectValues = gson.fromJson(response.get(currencykey).toString(),JsonArray.class);

Keep peeling away, and get a snapshot of historical price data.

Web Server:

Although technically the complete app can be done by making calls to the backend, considering scalability and bringing elements of machine learning into the fold its necessary to run a cloud instance. In this case I chose Digital Ocean with its fixed cloud rate droplets an ideal option for an MVP. I am running this droplet for about 2 weeks, so it will be open till April 15th.

There are several recipes on how to run a good flask application on Apache instances. Have a look at some of the links to get an idea. In this case we again need to go back to peeling onions, this time on Python:

Let us examine how we can GET token velocity for example over a few weeks:

url = “https://web3api.io/api/v2/tokens/rankings"

querystring ={“direction”:”descending”,”sortType”:”tokenVelocity”,”timeInterval”:”weeks”}

response = requests.request(“GET”, url, headers=headers, params=querystring)

response_native = json.loads(response.text)


I always recommend converting the standard get response to a native response which will enable easy manipulation with the list. Going back to the onion analogy it’s simply cutting the onion before peeling it, always a reasonable idea.

Having got this data, a series of calculations are performed to estimate the overall performance of the tokens.

As discussed above Token Velocity, circulating supply, change in Price will yield the correct mix of tokens.

The next step is to construct the JSON strings which will convey the information to the App. This can listen in on the port and reconstruct the risk profiles and token indices.


The elements of the app we need to construct include a pie chart which will visualise the spread in the basket of tokens. A sliding bar to allow the user to select the risk level, and since we assume that most users will need an onboarding process to top up their crypto balance a web3 wallet is automatically generated. Since the address will be different, in this test case a wallet address is shown, please top up by requesting ETH from Kovan faucet.

The slider on the top represents the risk level or appetite. Higher risk say 80% or above indicates investors who want more action.

To make it interactive as shown in the GIF above as the user slides different percentage estimates are made in the pie chart.

A slider to represent the amount from the wallet which is used to place the wager is shown. To increase participation a percentage amount from wallet is preferred.

Finally Loan duration the most interesting aspect, when a duration of 48 days is chosen by the user based on the formulas we find that Gold backed tokens with a very small percentage of MKR is necessary. This is based on the current market conditions due to CoVid 19.

The Pie chart shows an almost equal split across these currencies. When the user presses the wager button a smart contract is executed. At this point in time the trades are not placed.


It was an interesting full stack journey to write more than a thousand lines of code to use token velocity, unique addresses and circulating supply to gain insights via Amberdata over the last weekend. The surprising findings of gold backed tokens combined with utility tokens provides new approaches for wager to pursue.

Next instalment will focus on the smart contract execution, and how short positions can be made with the token basket.

Founder | V-Cred Full stack Developer: DeFi, ML