How to Use CoinGecko’s Free API to Calculate the ROI of a Short Position

Grant Ferowich
Coinmonks
4 min readAug 29, 2023

--

Curious Weekly — writing inspired by curiosity.

Are you looking to buy the CoinGecko Annual API subscription here? Use referral code CGGRANT to get $500 off the Annual API subscription purchase.

Suppose you shorted 1 Bitcoin on January 1, 2023 and you want to find the return on investment programmatically. This post is for you.

In my last post, I covered how to programmatically determine the return on investment of a long position with CoinGecko’s free application programming interface (API). In this post, I will show you how to calculate the ROI of a short position.

CoinGecko’s API has been useful for making financial calculations

A short position is a position in which the position value increases when the price of the underlying asset falls. Suppose you shorted 1 Bitcoin on January 1, 2023 and you want to find the return on investment programmatically. This post is for you.

In the previous exercise, you may have observed you can calculate the ROI of a position with just a few pieces of information:

  • The quantity of the asset.
  • The initial date on which the short position was opened.
  • The API symbol associated with the asset you care about

You will also need the API key associated with the asset you want information about. You can go to the /coins/list endpoint of the CoinGecko API to find the symbol associated with the asset you care about. For Bitcoin, the symbol is “bitcoin.”

Just as with the calculation of the long position ROI, we start out by calculating the initial position value. On January 1, 2023, the price of Bitcoin was $16,540.69. Let’s suppose that the short position consists of selling short 1 Bitcoin. The initial position value is $16,540.69.

const calculateInitialPositionInt = async (APISymbolStr, quantityInt ,indexDateStr) => {     
let historicalPriceAPIStr = "https://api.coingecko.com/api/v3/coins/"+APISymbolStr+"/history?date="+indexDateStr+"&localization=false";
let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) => response.data.market_data.current_price.usd);
let initialPositionValueInt = historicalPriceInt * quantityInt;
return initialPositionValueInt.toFixed(2);
}

Next, we will calculate how much the position changed in value. Again, we need the API symbol, the quantity of the asset shorted (1), and the date on which the position was initiated (“01–01–2023”). To find the difference, we take the present price less the historical price on January 1, 2023, multiply by the quantity (1), and multiply by -1 since we are interested in the short position.

const calculateDifferenceInt = async (APISymbolStr, quantityInt, indexDateStr) => {
let historicalPriceAPIStr = "https://api.coingecko.com/api/v3/coins/"+APISymbolStr+"/history?date="+indexDateStr+"&localization=false";
let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) => response.data.market_data.current_price.usd);
let presentPriceAPIStr = "https://api.coingecko.com/api/v3/simple/price?ids="+APISymbolStr+"&vs_currencies=usd";
let presentPriceInt = await axios.get(presentPriceAPIStr).then((response) => response.data[APISymbolStr].usd);
let differenceInt = -1 * (presentPriceInt - historicalPriceInt) * quantityInt;
return differenceInt.toFixed(2)
}

To make the percentage calculation, we need to determine the present position value. We will do that next. We simply combine the current position value with the difference value. If the difference value is positive, the position has increased in value. If the difference value is negative, the position has decreased in value.

const calculatePresentPositionInt = (initialPositionValueInt, differenceInt) => {
let currentPositionInt = parseFloat(initialPositionValueInt) + parseFloat(differenceInt)
return currentPositionInt.toFixed(2)
}

Next, we will calculate the ROI in percentage point terms.

const calculatePercentageROIInt = (initialInt, presentInt) => {
let percentageInt = ((presentInt - initialInt) / initialInt) * 100;
return percentageInt.toFixed(2)
}

Finally, let’s tie everything together. Notice that by writing with JavaScript here we make use of the async/await syntax. The async/await syntax basically just means the function will wait until an API call is completed before the next line of code is executed. Also note that whenever you want to use async/await inside of a function, the entire function must be an async function.

// Developed August 28, 2023 
// file is called roiShort.js
const axios = require('axios');
// inputs: api key string, asset quantity, and index date
// output: $ value of the position
const calculateInitialPositionInt = async (APISymbolStr, quantityInt ,indexDateStr) => {
let historicalPriceAPIStr = "https://api.coingecko.com/api/v3/coins/"+APISymbolStr+"/history?date="+indexDateStr+"&localization=false";
let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) => response.data.market_data.current_price.usd);
let initialPositionValueInt = historicalPriceInt * quantityInt;
return initialPositionValueInt.toFixed(2);
}

const calculateDifferenceInt = async (APISymbolStr, quantityInt, indexDateStr) => {
let historicalPriceAPIStr = "https://api.coingecko.com/api/v3/coins/"+APISymbolStr+"/history?date="+indexDateStr+"&localization=false";
let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) => response.data.market_data.current_price.usd);
let presentPriceAPIStr = "https://api.coingecko.com/api/v3/simple/price?ids="+APISymbolStr+"&vs_currencies=usd";
let presentPriceInt = await axios.get(presentPriceAPIStr).then((response) => response.data[APISymbolStr].usd);
let differenceInt = -1 * (presentPriceInt - historicalPriceInt) * quantityInt;
return differenceInt.toFixed(2)
}

const calculatePresentPositionInt = (initialPositionValueInt, differenceInt) => {
let currentPositionInt = parseFloat(initialPositionValueInt) + parseFloat(differenceInt)
return currentPositionInt.toFixed(2)
}

const calculatePercentageROIInt = (initialInt, presentInt) => {
let percentageInt = ((presentInt - initialInt) / initialInt) * 100;
return percentageInt.toFixed(2)
}

const callFunctions = async () => {
const initialBitcoinPositionValueInt = await calculateInitialPositionInt("bitcoin", 1, "01-01-2023");
console.log("Intial Bitcoin position value: $", initialBitcoinPositionValueInt);
const differenceBetweenInitialAndCurrentInt = await calculateDifferenceInt("bitcoin", 1, "01-01-2023")
console.log("Difference between initial position and current position in $:", differenceBetweenInitialAndCurrentInt);
const presentPositionInt = calculatePresentPositionInt(initialBitcoinPositionValueInt, differenceBetweenInitialAndCurrentInt);
console.log("Present Bitcoin position value: $", presentPositionInt)
const percentageROIInt = calculatePercentageROIInt(initialBitcoinPositionValueInt, presentPositionInt);
console.log("ROI in % terms:", percentageROIInt)
}

callFunctions();

The resulting output from this script is the following:

Intial Bitcoin position value: $ 16540.69
Difference between initial position and current position in $: -9453.31
Present Bitcoin position value: $ 7087.38
ROI in % terms: -57.15

Boom! There you have it. The ROI of a short position on Bitcoin in 2023 is -57.15%. The ROI is negative because the price of Bitcoin has increased. If the price of Bitcoin had decreased, the ROI on the short position would be position.

Also, read:

--

--

Grant Ferowich
Coinmonks

Writing code. "Everyone you meet is fighting a battle you know nothing about. Be kind." Curious Weekly - https://curiousweekly.com/.