API

Crypto Tax Calculator in Google Sheets (Free Template)

Calculating crypto taxes manually is error-prone, especially when you’re transacting between centralized exchanges, DeFi pools, and multiple wallets. A crypto tax calculator helps to calculate capital gains and losses accurately, saving you…

Crypto Tax Calculator in Google Sheets (Free Template) Hero Image

Calculating crypto taxes manually is error-prone, especially when you’re transacting between centralized exchanges, DeFi pools, and multiple wallets. A crypto tax calculator helps to calculate capital gains and losses accurately, saving you time while lowering the risk of penalties. This free Crypto Tax Calculator Google Sheets template automatically fetches historical crypto prices using the CoinGecko API, calculates your capital gains and losses with the FIFO method, and separates them into Short-Term and Long-Term categories. The template provides a structured way to determine your tax liability from selling, swapping, or spending crypto, all based on accurate, verifiable historical data from the industry’s most trusted source.

To get started and follow along with the setup steps, you can make a copy of the free Google Sheets template using the download link at the end of this article.

What is Crypto Tax?

Cryptocurrency is generally treated as property by tax authorities like the IRS, not as currency, which determines how various transactions are taxed.

Tax liability for crypto falls into two main categories:

  1. Ordinary Income: If you are paid in cryptocurrency (e.g., salary, staking, mining rewards, or airdrops), the Fair Market Value (FMV) in USD at the time of receipt is taxed as ordinary income. These profits are taxed at your regular income tax rate, which can range from 10% to 37% in the United States of America.
  2. Capital Gains/Losses: This tax applies when you dispose of crypto holdings, which includes selling for fiat, swapping crypto-to-crypto, or using it to buy goods or services. The taxable event is calculated by subtracting your Adjusted Cost Basis from the sale proceeds. For example, if you bought 1 ETH for $1,500 and later used that 1 ETH to buy a laptop when its value was $2,000, you’ve made a $500 capital gain that you need to report for tax purposes.

How Capital Gains and Losses Are Calculated

To calculate your Capital Gain/Loss, you must first determine the Cost Basis of the specific coins disposed of. Your cost basis is simply the original price you paid for an asset, and it is crucial for calculating the profit from any taxable transaction, such as selling or swapping crypto. Your final cost basis includes the original price plus any related transaction fees.

For example:

  • If you bought ETH for $2,000 and paid a $5 gas fee, your cost basis is $2,005.
  • If you later sell this ETH for $3,000, paying a $15 fee, your capital gain is calculated as:
    $3,000 – $2,020 = $980 (where $2,020 is the total adjusted cost basis).

There are a number of different cost basis methods used in accounting. Depending on your tax jurisdiction and country, you may be entitled to select your preferred method. In the United States, for instance, the IRS allows taxpayers to choose methods like HIFO, FIFO, or LIFO, provided they can specifically identify the assets being sold. Whatever method you choose, you must use it consistently when calculating your gains or losses. If you are uncertain as to which cost basis method you can use, contact the IRS to confirm.

Note: This template is structured to comply with US tax laws and uses the FIFO (First-In, First-Out) method, the most common accounting approach, which assumes the first assets you acquired are the first ones you sell. This can be advantageous, as selling your longest-held assets may qualify them for lower long-term capital gains tax rates.

What Is the Difference Between Short-Term and Long-Term Crypto Taxes?

The primary difference is the tax rate you’ll pay. The rate applied to your capital gain depends on how long you held the asset:

  • Short-Term Gains:
    For crypto held for one year or less (Less than 365 days), the profit is taxed at the higher ordinary income tax rate (10% to 37% in the US).
  • Long-Term Gains:
    For crypto held for more than one year (More than 365 days), the profit is subject to preferential, lower tax rates (0% to 20% in the US).

Prerequisites

Before you start, ensure the following requirements are met to use the template effectively:

  • A Google Account:
    You’ll need a Google account to open, copy, and use the template in Google Sheets. This allows you to save your own version and enable Apps Script for live data connections.
  • CoinGecko Google Sheets Add-on:
    This template uses the official CoinGecko Google Sheets add-on to fetch live and historical crypto prices directly into your spreadsheets using the =COINGECKO() function.
  • A CoinGecko API Key:
    Required to fetch live crypto prices. The free Demo API key is sufficient to get started, while a paid plan offers higher rate limits for more frequent data refreshes. You can follow our guide to get your free Demo API key.

How to Use the Crypto Tax Calculator Google Sheet Template

This section provides a clear, step-by-step guide on how to integrate and use the Crypto Tax Calculator template effectively. Follow these instructions to set up the CoinGecko add-on, input your transaction history, and view your automatically calculated tax summary.

Setting up the CoinGecko Add-on

First, connect the template to the CoinGecko Google Sheets add-on to enable live and historical price data within the spreadsheet. To get started, install the add-on and configure your API credentials (Subscription Level and API Key) by following the setup guide.

Once configured, all =COINGECKO() formulas across the template will automatically fetch the required data. You don’t need to modify any formulas or configure scripts manually.

Refreshing Crypto Price Data

Now that the CoinGecko add-on is configured, your data will be fetched automatically through the =COINGECKO() formulas across the template.

However, Google Sheets may cache results for a short period of time. If you need the most up-to-date prices, you can manually refresh all data in your sheet. Keep in mind that more frequent refreshes will consume your API call credits faster. If you run into rate limits, consider upgrading to a paid API plan for higher call credits and rate limits.

Note: For tax calculation purposes, most values are based on historical price data retrieved using formulas such as =COINGECKO("id:bitcoin", "2025-12-31"). Once the daily closing price is determined, these values remain fixed, so frequent data refreshes are generally not required.

Once the add-on status is Live, you can start customising the template by adding the tokens you want to track in the following section.

How to Add Specific Coins

To calculate historical values, the template needs the unique API ID for each asset, which you can find on any individual coin page on the CoinGecko website.

Once you have the API ID, simply paste it into cell B4 on the Tax Calculator Sheet. The template will then automatically fetch the correct historical data for your calculations.

Logging your Cryptocurrency’s Transactions in the Tax Calculator Sheet

Once the API key and coin ID are set up, you can begin logging your buy and sell transactions in the “Tax Transaction Log” table. This log is the foundation for calculating your cost basis and capital gains or losses using the FIFO method.
To log your transactions efficiently, you should import the data from your exchange history:

  1. Export History from Your Source: Most crypto exchanges and centralized wallets allow you to download your complete transaction history as a CSV file. For on-chain data (e.g., from a MetaMask wallet), you can use a block explorer like Etherscan to view your address and download its transaction history.

  2. Filter and Prepare Data: Open your exported CSV file and prepare the essential details required by the template’s columns:

    • The Transaction Date and Time.
    • The Asset Name (e.g., "Bitcoin") to help you look up the correct CoinGecko API ID.
    • The Quantity purchased or sold.
    • The Transaction Fee, if applicable.
    • Whether the transaction was a Buy or a Sell.

Analyzing Your Crypto Tax Summary

Upon logging your transaction history appropriately, the in-built functions will start running immediately. The CoinGecko API will fetch the precise historical price for each transaction date, and the template will begin calculating your Capital Gains/Losses, separating them into Short-Term and Long-Term categories based on the FIFO method.

This system automatically transforms complex transaction data into auditable, tax-ready figures. You can use the Net FIFO Short-Term Gain and Net FIFO Long-Term Gain figures directly to complete your final tax forms, such as IRS Form 8949 and Schedule D.

To calculate your final tax liability, you must apply the appropriate tax rates to your Net FIFO Short-Term Gain and Net FIFO Long-Term Gain figures. Tax systems, like the one in the US, are often progressive, meaning different portions of your income are taxed at different rates (or ‘brackets’). Your final tax payable is the sum of the taxes calculated for each bracket your gains fall into.

While the tax table in this template reflects US rates, the calculator’s gain/loss figures can be used in any jurisdiction. Since FIFO is a widely accepted method, you can apply your country’s specific tax rates to the net gains calculated by the sheet to determine your liability. To see an estimate of your U.S. federal income tax bracket, navigate to the Read me Sheet. Simply input your annual taxable income into Cell C20 and select your filing status from the dropdown menu in Cell D20.

The tax rate that automatically appears in Cell E20 is the Progressive Tax Rate Ceiling. This represents the highest marginal tax bracket your income falls into. Please note that this is not your effective tax rate and should not be used to calculate your final tax bill. It is an indicator of the highest tax rate applied to only the top portion of your income.

How to Create a Crypto Tax Calculator in Google Sheets

Creating a crypto tax calculator in Google Sheets involves three main components: a reliable source of historical price data, a structured transaction log, and formulas to execute tax calculations.

This template integrates all three into a single system powered by the CoinGecko Google Sheets add-on, allowing you to fetch accurate crypto price data directly using simple =COINGECKO() formulas without any custom scripts.

  • Historical Crypto Price Data
    Accurate price data is fetched directly using the CoinGecko Google Sheets add-on through the =COINGECKO() function. This allows the template to retrieve the Fair Market Value (FMV) of assets on specific transaction dates, which is essential for calculating cost basis and capital gains.
  • Structured Transaction Logging
    A detailed log sheet to record transaction input, such as quantities bought or sold, dates, and fees.
  • Google Sheets Formulas and Tables
    Advanced Sheets formulas are used to calculate and classify every taxable event instantly. These nested calculations determine the specific cost basis consumed by a sale, calculate the resulting Capital gain or loss, and classify it as Short-Term or Long-Term.

This connected system ensures that every metric, from your original cost basis to your final net gain, is calculated dynamically and accurately.

How to Get Historical Crypto Data in Google Sheets

You can fetch historical crypto data in Google Sheets using two different approaches, depending on your preferred level of control and customization:

Option 1 (Recommended): Using the CoinGecko Add-on

The simplest way is to use the CoinGecko Google Sheets add-on with the =COINGECKO() function. This method is fully integrated into the template and does not require any scripting, allowing you to fetch live or historical crypto data directly, for example, retrieving the price of Bitcoin on a specific date with (=COINGECKO("id: bitcoin", "price", DATE(2024,12,31)).

Option 2 (Advanced): Using Apps Script

For users who require more flexibility, you can fetch data directly from the CoinGecko API using Google Apps Script. This approach gives you fine-grained control over the request parameters, such as specifying dates, currencies, and endpoints, as well as how the returned data is structured and used within your sheet.
You can get historical crypto data in Google Sheets by creating custom functions that call the CoinGecko API’s /coins/{id}/history endpoint.

Step 1: Create an ImportJSON Script

First, create the main function that will fetch and parse data from CoinGecko API.

Open your Google Sheet and navigate to ‘Extensions’ and select ‘Apps Script’ – a new tab will appear.

On the left panel, select ‘< > Editor’ and add a new script using the ‘+’ button. Copy and paste the following importJSON script, and save the script as ‘ImportJSON’. This importJSON script is a versatile one that will allow you to import data in many different ways.

/*====================================================================================================================================*
ImportJSON by Brad Jasper and Trevor Lohrbeer

Version: 1.5.0
Project Page: https://github.com/bradjasper/ImportJSON
Copyright: (c) 2017-2019 by Brad Jasper
(c) 2012-2017 by Trevor Lohrbeer
License: GNU General Public License, version 3 (GPL-3.0)
http://www.opensource.org/licenses/gpl-3.0.html

A library for importing JSON feeds into Google spreadsheets. Functions include:
ImportJSON For use by end users to import a JSON feed from a URL
ImportJSONFromSheet For use by end users to import JSON from one of the Sheets
ImportJSONViaPost For use by end users to import a JSON feed from a URL using POST parameters
ImportJSONAdvanced For use by script developers to easily extend the functionality of this library
ImportJSONBasicAuth For use by end users to import a JSON feed from a URL with HTTP Basic Auth (added by Karsten Lettow)
For future enhancements see https://github.com/bradjasper/ImportJSON/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement

For bug reports see https://github.com/bradjasper/ImportJSON/issues

Changelog:

1.6.0 (June 2, 2019) Fixed null values (thanks @gdesmedt1)
1.5.0 (January 11, 2019) Adds ability to include all headers in a fixed order even when no data is present for a given header in some or all rows.
1.4.0 (July 23, 2017) Transfer project to Brad Jasper. Fixed off-by-one array bug. Fixed previous value bug. Added custom annotations. Added ImportJSONFromSheet and ImportJSONBasicAuth.
1.3.0 Adds ability to import the text from a set of rows containing the text to parse. All cells are concatenated
1.2.1 Fixed a bug with how nested arrays are handled. The rowIndex counter wasn’t incrementing properly when parsing.
1.2.0 Added ImportJSONViaPost and support for fetchOptions to ImportJSONAdvanced
1.1.1 Added a version number using Google Scripts Versioning so other developers can use the library
1.1.0 Added support for the noHeaders option
1.0.0 Initial release
*====================================================================================================================================*/
/**
* Imports a JSON feed and returns the results to be inserted into a Google Spreadsheet. The JSON feed is flattened to create
* a two-dimensional array. The first row contains the headers, with each column header indicating the path to that data in
* the JSON feed. The remaining rows contain the data.
* * By default, data gets transformed so it looks more like a normal data import. Specifically:
*
* – Data from parent JSON elements gets inherited to their child elements, so rows representing child elements contain the values
* of the rows representing their parent elements.
* – Values longer than 256 characters get truncated.
* – Headers have slashes converted to spaces, common prefixes removed and the resulting text converted to title case.
*
* To change this behavior, pass in one of these values in the options parameter:
*
* noInherit: Don’t inherit values from parent elements
* noTruncate: Don’t truncate values
* rawHeaders: Don’t prettify headers
* noHeaders: Don’t include headers, only the data
* allHeaders: Include all headers from the query parameter in the order they are listed
* debugLocation: Prepend each value with the row & column it belongs in
*
* For example:
*
* =ImportJSON("http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=json", "/feed/entry/title,/feed/entry/content",
* "noInherit,noTruncate,rawHeaders")
* * @param {url} the URL to a public JSON feed
* @param {query} a comma-separated list of paths to import. Any path starting with one of these paths gets imported.
* @param {parseOptions} a comma-separated list of options that alter processing of the data
* @customfunction
*
* @return a two-dimensional array containing the data, with the first row containing headers
**/
function ImportJSON(url, query, parseOptions) {
return ImportJSONAdvanced(url, null, query, parseOptions, includeXPath_, defaultTransform_);
}
/**
* Imports a JSON feed via a POST request and returns the results to be inserted into a Google Spreadsheet. The JSON feed is
* flattened to create a two-dimensional array. The first row contains the headers, with each column header indicating the path to
* that data in the JSON feed. The remaining rows contain the data.
*
* To retrieve the JSON, a POST request is sent to the URL and the payload is passed as the content of the request using the content
* type "application/x-www-form-urlencoded". If the fetchOptions define a value for "method", "payload" or "contentType", these
* values will take precedent. For example, advanced users can use this to make this function pass XML as the payload using a GET
* request and a content type of "application/xml; charset=utf-8". For more information on the available fetch options, see
* https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app . At this time the "headers" option is not supported.
* * By default, the returned data gets transformed so it looks more like a normal data import. Specifically:
*
* – Data from parent JSON elements gets inherited to their child elements, so rows representing child elements contain the values
* of the rows representing their parent elements.
* – Values longer than 256 characters get truncated.
* – Headers have slashes converted to spaces, common prefixes removed and the resulting text converted to title case.
*
* To change this behavior, pass in one of these values in the options parameter:
*
* noInherit: Don’t inherit values from parent elements
* noTruncate: Don’t truncate values
* rawHeaders: Don’t prettify headers
* noHeaders: Don’t include headers, only the data
* allHeaders: Include all headers from the query parameter in the order they are listed
* debugLocation: Prepend each value with the row & column it belongs in
*
* For example:
*
* =ImportJSON("http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=json", "user=bob&apikey=xxxx",
* "validateHttpsCertificates=false", "/feed/entry/title,/feed/entry/content", "noInherit,noTruncate,rawHeaders")
* @param {url} the URL to a public JSON feed
* @param {payload} the content to pass with the POST request; usually a URL encoded list of parameters separated by ampersands
* @param {fetchOptions} a comma-separated list of options used to retrieve the JSON feed from the URL
* @param {query} a comma-separated list of paths to import. Any path starting with one of these paths gets imported.
* @param {parseOptions} a comma-separated list of options that alter processing of the data
* @customfunction
*
* @return a two-dimensional array containing the data, with the first row containing headers
**/
function ImportJSONViaPost(url, payload, fetchOptions, query, parseOptions) {
var postOptions = parseToObject_(fetchOptions);

if (postOptions["method"] == null) {
postOptions["method"] = "POST";
}
if (postOptions["payload"] == null) {
postOptions["payload"] = payload;
}
if (postOptions["contentType"] == null) {
postOptions["contentType"] = "application/x-www-form-urlencoded";
}
convertToBool_(postOptions, "validateHttpsCertificates");
convertToBool_(postOptions, "useIntranet");
convertToBool_(postOptions, "followRedirects");
convertToBool_(postOptions, "muteHttpExceptions");

return ImportJSONAdvanced(url, postOptions, query, parseOptions, includeXPath_, defaultTransform_);
}
/**
* Imports a JSON text from a named Sheet and returns the results to be inserted into a Google Spreadsheet. The JSON feed is flattened to create
* a two-dimensional array. The first row contains the headers, with each column header indicating the path to that data in
* the JSON feed. The remaining rows contain the data.
* * By default, data gets transformed so it looks more like a normal data import. Specifically:
*
* – Data from parent JSON elements gets inherited to their child elements, so rows representing child elements contain the values
* of the rows representing their parent elements.
* – Values longer than 256 characters get truncated.
* – Headers have slashes converted to spaces, common prefixes removed and the resulting text converted to title case.
*
* To change this behavior, pass in one of these values in the options parameter:
*
* noInherit: Don’t inherit values from parent elements
* noTruncate: Don’t truncate values
* rawHeaders: Don’t prettify headers
* noHeaders: Don’t include headers, only the data
* allHeaders: Include all headers from the query parameter in the order they are listed
* debugLocation: Prepend each value with the row & column it belongs in
*
* For example:
*
* =ImportJSONFromSheet("Source", "/feed/entry/title,/feed/entry/content",
* "noInherit,noTruncate,rawHeaders")
* @param {sheetName} the name of the sheet containg the text for the JSON
* @param {query} a comma-separated lists of paths to import. Any path starting with one of these paths gets imported.
* @param {options} a comma-separated list of options that alter processing of the data
*
* @return a two-dimensional array containing the data, with the first row containing headers
* @customfunction
**/
function ImportJSONFromSheet(sheetName, query, options) {
var object = getDataFromNamedSheet_(sheetName);

return parseJSONObject_(object, query, options, includeXPath_, defaultTransform_);
}
/**
* An advanced version of ImportJSON designed to be easily extended by a script. This version cannot be called from within a
* spreadsheet.
* * Imports a JSON feed and returns the results to be inserted into a Google Spreadsheet. The JSON feed is flattened to create
* a two-dimensional array. The first row contains the headers, with each column header indicating the path to that data in
* the JSON feed. The remaining rows contain the data.
*
* The fetchOptions can be used to change how the JSON feed is retrieved. For instance, the "method" and "payload" options can be
* set to pass a POST request with post parameters. For more information on the available parameters, see
* https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app .
*
* Use the include and transformation functions to determine what to include in the import and how to transform the data after it is
* imported.
*
* For example:
*
* ImportJSON("http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=json",
* new Object() { "method" : "post", "payload" : "user=bob&apikey=xxxx" },
* "/feed/entry",
* "",
* function (query, path) { return path.indexOf(query) == 0; },
* function (data, row, column) { data[row][column] = data[row][column].toString().substr(0, 100); } )
*
* In this example, the import function checks to see if the path to the data being imported starts with the query. The transform
* function takes the data and truncates it. For more robust versions of these functions, see the internal code of this library.
*
* @param {url} the URL to a public JSON feed
* @param {fetchOptions} an object whose properties are options used to retrieve the JSON feed from the URL
* @param {query} the query passed to the include function
* @param {parseOptions} a comma-separated list of options that may alter processing of the data
* @param {includeFunc} a function with the signature func(query, path, options) that returns true if the data element at the given path
* should be included or false otherwise.
* @param {transformFunc} a function with the signature func(data, row, column, options) where data is a 2-dimensional array of the data
* and row & column are the current row and column being processed. Any return value is ignored. Note that row 0
* contains the headers for the data, so test for row==0 to process headers only.
*
* @return a two-dimensional array containing the data, with the first row containing headers
* @customfunction
**/
function ImportJSONAdvanced(url, fetchOptions, query, parseOptions, includeFunc, transformFunc) {
var jsondata = UrlFetchApp.fetch(url, fetchOptions);
var object = JSON.parse(jsondata.getContentText());

return parseJSONObject_(object, query, parseOptions, includeFunc, transformFunc);
}
/**
* Helper function to authenticate with basic auth informations using ImportJSONAdvanced
*
* Imports a JSON feed and returns the results to be inserted into a Google Spreadsheet. The JSON feed is flattened to create
* a two-dimensional array. The first row contains the headers, with each column header indicating the path to that data in
* the JSON feed. The remaining rows contain the data.
*
* The fetchOptions can be used to change how the JSON feed is retrieved. For instance, the "method" and "payload" options can be
* set to pass a POST request with post parameters. For more information on the available parameters, see
* https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app .
*
* Use the include and transformation functions to determine what to include in the import and how to transform the data after it is
* imported.
*
* @param {url} the URL to a http basic auth protected JSON feed
* @param {username} the Username for authentication
* @param {password} the Password for authentication
* @param {query} the query passed to the include function (optional)
* @param {parseOptions} a comma-separated list of options that may alter processing of the data (optional)
*
* @return a two-dimensional array containing the data, with the first row containing headers
* @customfunction
**/
function ImportJSONBasicAuth(url, username, password, query, parseOptions) {
var encodedAuthInformation = Utilities.base64Encode(username + ":" + password);
var header = {headers: {Authorization: "Basic " + encodedAuthInformation}};
return ImportJSONAdvanced(url, header, query, parseOptions, includeXPath_, defaultTransform_);
}
/** * Encodes the given value to use within a URL.
*
* @param {value} the value to be encoded
* * @return the value encoded using URL percent-encoding
*/
function URLEncode(value) {
return encodeURIComponent(value.toString());
}
/**
* Adds an oAuth service using the given name and the list of properties.
*
* @note This method is an experiment in trying to figure out how to add an oAuth service without having to specify it on each
* ImportJSON call. The idea was to call this method in the first cell of a spreadsheet, and then use ImportJSON in other
* cells. This didn’t work, but leaving this in here for further experimentation later.
*
* The test I did was to add the following into the A1:
* * =AddOAuthService("twitter", "https://api.twitter.com/oauth/access_token",
* "https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/authorize",
* "", "", "", "")
*
* Information on obtaining a consumer key & secret for Twitter can be found at https://dev.twitter.com/docs/auth/using-oauth
*
* Then I added the following into A2:
*
* =ImportJSONViaPost("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=fastfedora&count=2", "",
* "oAuthServiceName=twitter,oAuthUseToken=always", "/", "")
*
* I received an error that the "oAuthServiceName" was not a valid value. [twl 18.Apr.13]
*/
function AddOAuthService__(name, accessTokenUrl, requestTokenUrl, authorizationUrl, consumerKey, consumerSecret, method, paramLocation) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
if (accessTokenUrl != null && accessTokenUrl.length > 0) {
oAuthConfig.setAccessTokenUrl(accessTokenUrl);
}

if (requestTokenUrl != null && requestTokenUrl.length > 0) {
oAuthConfig.setRequestTokenUrl(requestTokenUrl);
}

if (authorizationUrl != null && authorizationUrl.length > 0) {
oAuthConfig.setAuthorizationUrl(authorizationUrl);
}

if (consumerKey != null && consumerKey.length > 0) {
oAuthConfig.setConsumerKey(consumerKey);
}

if (consumerSecret != null && consumerSecret.length > 0) {
oAuthConfig.setConsumerSecret(consumerSecret);
}

if (method != null && method.length > 0) {
oAuthConfig.setMethod(method);
}

if (paramLocation != null && paramLocation.length > 0) {
oAuthConfig.setParamLocation(paramLocation);
}
}
/** * Parses a JSON object and returns a two-dimensional array containing the data of that object.
*/
function parseJSONObject_(object, query, options, includeFunc, transformFunc) {
var headers = new Array();
var data = new Array();

if (query && !Array.isArray(query) && query.toString().indexOf(",") != -1) {
query = query.toString().split(",");
}
// Prepopulate the headers to lock in their order
if (hasOption_(options, "allHeaders") && Array.isArray(query))
{
for (var i = 0; i 1 ? data.slice(1) : new Array()) : data;
}
/** * Parses the data contained within the given value and inserts it into the data two-dimensional array starting at the rowIndex.
* If the data is to be inserted into a new column, a new header is added to the headers array. The value can be an object,
* array or scalar value.
*
* If the value is an object, it’s properties are iterated through and passed back into this function with the name of each
* property extending the path. For instance, if the object contains the property "entry" and the path passed in was "/feed",
* this function is called with the value of the entry property and the path "/feed/entry".
*
* If the value is an array containing other arrays or objects, each element in the array is passed into this function with
* the rowIndex incremeneted for each element.
*
* If the value is an array containing only scalar values, those values are joined together and inserted into the data array as
* a single value.
*
* If the value is a scalar, the value is inserted directly into the data array.
*/
function parseData_(headers, data, path, state, value, query, options, includeFunc) {
var dataInserted = false;
if (Array.isArray(value) && isObjectArray_(value)) {
for (var i = 0; i 1) {
removeCommonPrefixes_(data, row);
}

data[row][column] = toTitleCase_(data[row][column].toString().replace(/[/_]/g, " "));

}

if (!hasOption_(options, "noTruncate") && data[row][column]) {
data[row][column] = data[row][column].toString().substr(0, 256);
}
if (hasOption_(options, "debugLocation")) {
data[row][column] = "[" + row + "," + column + "]" + data[row][column];
}
}
/** * If all the values in the given row share the same prefix, remove that prefix.
*/
function removeCommonPrefixes_(data, row) {
var matchIndex = data[row][0].length;
for (var i = 1; i = 0;
}
/** * Parses the given string into an object, trimming any leading or trailing spaces from the keys.
*/
function parseToObject_(text) {
var map = new Object();
var entries = (text != null && text.trim().length > 0) ? text.toString().split(",") : new Array();

for (var i = 0; i ‘CoinGecko’ > ‘View Error Logs’ to access the debug logs and view the returned error code and message.

Once you’ve identified the issue, here are a few common problems along with quick ways to fix them.

  1. API Rate Limit (Error 429)
    This happens when the free CoinGecko Demo API hits its request limit. Wait a few minutes before refreshing again, or switch to a Pro API key for uninterrupted updates.
    If you receive other error codes, refer to the full list of CoinGecko API status codes to troubleshoot them.

  2. API Key or Connection Issues
    If your data isn’t loading or you’re seeing errors such as 401 or 403, try reconnecting your CoinGecko API key within the add-on settings and ensure your subscription level is correctly configured.

  3. Data Not Updating or Showing Older Prices
    Google Sheets may cache formula results temporarily. To refresh your data, open the CoinGecko sidebar and click “Refresh All Data” to force-update all =COINGECKO() formulas.

  4. Inaccurate Gain/Loss Calculations
    This happens when the transactions were not entered in chronological order, which breaks the sequential logic of the FIFO formulas. Sort your entire transaction log by date to ensure the FIFO engine works correctly:

    • Click on the Downward arrow on the “Transactions Date & Time” Cell.
    • Navigate to “Sort Column” > “Sort A to Z”.

For more detailed troubleshooting steps and a list of common errors, refer to the Error Debugging Guide.

Further Enhancements

You can further enhance this Crypto Tax Calculator spreadsheet to better suit your needs. Here are a few ideas that leverage other CoinGecko API endpoints:

  • Fetch Historical Price Data
    Pull Historical Prices for specific coins for more in-depth performance analysis. You can follow our guide on how to pull crypto historical data in Google Sheets and visualize long-term trends.
  • Add OHLC (Open, High, Low, Close) Data
    If you want more granular price insights, consider fetching OHLC data for each coin. Check out our step-by-step guide on how to pull crypto OHLC data into Google Sheets.
  • Add a Crypto Portfolio Tracker
    Extend the spreadsheet into a complete Crypto Portfolio Tracker to monitor unrealized P&L (the current profit/loss of assets you still hold) alongside your realized tax gains. For a full guide, see our article on how to create a crypto portfolio tracker in Google Sheets.
  • Create a Crypto Exit Strategy Planner
    To complement your tax planning, you can build a Crypto Exit Strategy Planner. Planning your exits strategically may help optimize your returns, which in turn impacts your final tax calculations. Check out our step-by-step guide on how to build a crypto exit strategy planner in Google Sheets.

Conclusion

A clear and auditable tax report is crucial for any crypto investor. This free Crypto Tax Calculator Google Sheets template, powered by the CoinGecko API offers a streamlined solution to determine your capital gains.

Reporting taxes with data from a reputable, industry-trusted source is essential to avoid potential discrepancies that invite scrutiny by tax authorities. Our template helps simplify the complex process of tracing asset cost basis across trades using reliable, aggregated historical data.

If you need more historical data beyond the Demo API’s limits, higher rate limits and call credits, or access to exclusive endpoints, consider subscribing to a paid API plan.

Reminder: Consult a Tax Professional

Cryptocurrency tax regulations, particularly those involving DeFi and cross-border activity, are complex and constantly evolving. Users must be aware that crypto tax jurisdictions and methodologies vary by country or region. Confirm and apply the correct rules for your locale, and always consult a qualified tax professional to ensure accurate filing and to identify strategic tax optimization opportunities.

Download Your Free Template ⬇️