Last active
January 11, 2024 13:26
-
-
Save lucashmsilva/9f4596f2924ac5c1eb0721c2c41dc257 to your computer and use it in GitHub Desktop.
API para criar a função TESOURODIRETO Google Sheets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* @return Retorna a cotação atual de um título específico do Tesouro Direto Junto com a taxa anual de retorno | |
* @customfunction | |
**/ | |
function TESOURODIRETO(bondName) { | |
let srcURL = "https://www.tesourodireto.com.br/json/br/com/b3/tesourodireto/service/api/treasurybondsinfo.json"; | |
let jsonData = UrlFetchApp.fetch(srcURL); | |
let parsedData = JSON.parse(jsonData.getContentText()).response; | |
for(let bond of parsedData.TrsrBdTradgList) { | |
let currBondName = bond.TrsrBd.nm; | |
if (currBondName === bondName) | |
return [bond.TrsrBd.untrRedVal, bond.TrsrBd.anulInvstmtRate]; // créditos ao @figueiredods por ter encontrado o campo que retorna a taxa correta | |
} | |
throw new Error("Not Found"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* @return Retorna a cotação atual de um título específico do Tesouro Direto | |
* @customfunction | |
**/ | |
function TESOURODIRETO(bondName) { | |
let srcURL = "https://www.tesourodireto.com.br/json/br/com/b3/tesourodireto/service/api/treasurybondsinfo.json"; | |
let jsonData = UrlFetchApp.fetch(srcURL); | |
let parsedData = JSON.parse(jsonData.getContentText()).response; | |
for(let bond of parsedData.TrsrBdTradgList) { | |
let currBondName = bond.TrsrBd.nm; | |
if (currBondName === bondName) | |
return bond.TrsrBd.untrRedVal; | |
} | |
throw new Error("Not Found"); | |
} |
@Tiagoalvesds , cara teria que analisar o retorno desses dados no site no TD para descobrir qual campo é a cotação de compra para só então adaptar o código. Hoje em dia não me lembro muito bem, mas não deve ser difícil descobrir o campo. A fonte de dados é essa: json b3
Fiz uma melhoria pra cachear a response do tesouro pq as vezes dá erro por chamar vezes seguidas :)
var cache = CacheService.getScriptCache();
function TESOURODIRETO(bondName, argumento = "r") {
var tesouro = getCachedTesouro();
if (bondName == "tesouro-selic-2027")
bondName = "Tesouro Selic 2027";
if (bondName == "tesouro-selic-2029")
bondName = "Tesouro Selic 2029";
if (bondName == "tesouro-prefixado-2025")
bondName = "Tesouro Prefixado 2025";
if (!tesouro) {
Logger.log("No cached tesouro info found");
updateTesouroCache();
}
tesouro = getCachedTesouro();
for (let bond of tesouro.TrsrBdTradgList) {
console.log(bond);
let currBondName = bond.TrsrBd.nm;
if (currBondName.toLowerCase() === bondName.toLowerCase())
if (argumento == "r")
return bond.TrsrBd.untrRedVal;
else
return bond.TrsrBd.untrInvstmtVal;
}
return 0;
}
function getCachedTesouro() {
var cached = cache.get("tesouro");
if (cached) {
try {
var tesouro = JSON.parse(cached).response;
return tesouro;
} catch (e) {
Logger.log("Error while parsing tesouro from cache");
}
}
}
function updateTesouroCache() {
Logger.log("Updating tesouro cached information");
var response = UrlFetchApp.fetch("https://www.tesourodireto.com.br/json/br/com/b3/tesourodireto/service/api/treasurybondsinfo.json");
var content = response.getContentText();
try {
var data = JSON.parse(content);
var cachedTesouro = {};
cachedTesouro["tesouro"] = JSON.stringify(data)
cache.putAll(cachedTesouro);
} catch (e) {
Logger.log("Error while parsing response from tesouro: " + content);
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lucashmsilva , deu certo e funciona perfeitamente! Obrigado! Notei que a cotação puxada é a de resgate, teria como adicionar uma linha e/ou função que puxa a cotação de compra?