JavaScript code that retrieves the current exchange rate of Bitcoin (BTC)

Seeking to create a JavaScript function that returns the current exchange rate for BTC/USD. Keeping it simple without using server-side calculations, just a user-friendly feature. I have 2 text fields and want one value to update automatically when the other is changed.

This is what I have so far:

var getBTCRate = function(){ /* code here */ };

var btcprice = getBTCRate();

// Update BTC value as USD value changes
$("#usdvalue").keyup(function(ev){
    var usdvalue = $("#usdvalue").val();
    $("#btcvalue").val(usdvalue / btcprice);
});

// Update USD value as BTC value changes
$("#btcvalue").keyup(function(ev){
    var btcvalue = $("#btcvalue").val();
    $("#usdvalue").val(btcvalue * btcprice);
});

Straightforward approach. Couldn't find a solution in my research, only confusing APIs. Any assistance is greatly appreciated.

EDITED to correct a mistake in the code.

EDITED AGAIN to adjust the position of the function declaration. Thanks to @RobG for pointing this out.

Answer №1

Originally, I attempted to utilize JQuery load in the following manner

$.get('https://www.google.com/search?q=btc+value', function(p) {
  console.log(p);
}); 

Unfortunately, my progress was hindered by cross-origin rules. While there are paid services available with APIs for this purpose, my intention was to achieve it without any financial cost. Consequently, I opted for a server-based approach using PowerBasic for the backend, coupled with the SocketTools Library.

#COMPILE EXE
#DIM ALL
#Include "pbcgi.inc"
#Include "C:\bas_src\socketTools\v9.5\inc\cstools9.inc"

Function PBMain () As Long         
    Local btc As String         
    Local html As String   

    html = httpGet("https://www.google.com/search?q=btc+value")      

    ' Filtering out just the current BTC value
    ' By isolating the content between "Bitcoin =" and "United States Dollar"
    btc = Remain$(html,"Bitcoin =")     
    btc = Extract$(btc,"United States Dollar")
    btc = Trim$(btc)

    writeCGI "{" + jsonPad("btc") + ":" + jsonPad(btc) + "," + jsonPad("error") + ":" + jsonPad("0") + "}"

END FUNCTION

'================================================================
' Retrieve the page and return it as a string
Function httpGet(ByVal URL As String) As String

    If IsFalse( HttpInitialize($CSTOOLS9_LICENSE_KEY) ) Then
        Function = "Unable to initialize socket library"
        Exit Function
    End If         

    Local hClient      As Dword
    Local lpszURL      As STRINGZ * 4096
    Local lpszBuffer   As STRINGZ * 100000
    Local httpContents As String
    Local httpPort     As Long
    Local httpOptions  As Dword
    Local nResult      As Long

    If LCase$(Trim$(Left$(URL, 8))) = "https://" Then
        httpPort    = 443
        httpOptions = %HTTP_OPTION_SECURE Or %HTTP_OPTION_REDIRECT
    Else
        httpPort    = 80
        httpOptions = %HTTP_OPTION_REDIRECT
    End If

    lpszURL = URL & Chr$(0)

    hClient = HttpConnect(lpszURL, _
                          httpPort, _
                          %HTTP_TIMEOUT, _
                          httpOptions, _
                          %HTTP_VERSION_10)

    If hClient = %INVALID_CLIENT Then
        Function = "Could not connect to: " & URL
        Exit Function
    End If

    HttpSetEncodingType(hClient, %HTTP_ENCODING_NONE)
    nResult = HttpGetText(hClient, lpszURL, lpszBuffer, 100000)

    If nResult = %HTTP_ERROR Then
        Function = "Error retrieving file." + Str$(nResult)
    Else    
        ' Success
        httpContents = lpszBuffer     
        Function = httpContents    
    End If

    Call HttpDisconnect(hClient)        
    HttpUninitialize()

End Function
'================================================================

' Pad string for JSON return
Function jsonPad(jstr As String) As String       
    Local i As Long

    Replace Chr$(10) With " " In jstr    
    Replace Chr$(13) With " " In jstr    
    Replace "\" With "\\" In jstr  
    Replace $Dq With "\" + $Dq In jstr   

    For i = 0 To 9
        Replace Chr$(i) With " " In jstr
    Next       

    Function = $Dq + Trim$(jstr) + $Dq               

End Function

On my website, I invoke it via AJAX

function showBTC(){

  $.ajax({
    type: "POST",
    url: "../cgi/btcGet.exe",
    dataType: "json",
    success: function(json){       

            if(json.error !== "0" ){
                console.log(json.error);
                return;
            }

            $("#btcValue").html("Current BTC value $" + json.btc + "<br><br>");
    }
  });   
}

I understand that this may seem like a very specific solution, but this is how I have chosen to address it.

UPDATED ON 5/11/2020: An easier method has been discovered through a Bitcoin API accessible at coindesk.com, simplifying the process significantly.

Answer №2

const api = 'https://apiv2.bitcoinaverage.com/indices/local/ticker/short?crypto=BTC&fiat=USD'
$.get(api, data => {
  document.querySelector('pre').textContent = JSON.stringify(data, null, 2)
}); 

Outcome

{
  "BTCUSD": {
    "ask": 3594.5649555077953,
    "timestamp": 1550284932,
    "bid": 3591.715961836563,
    "last": 3592.745617344171,
    "averages": {
      "day": 3583.13243402
    }
  }
}

So you can select p.BTCUSD.ask // or bid or last

demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to smoothly scroll to a specific Label using GSAP's scrollTrigger and scrubbing within a Timeline

Currently facing an issue with a scrollTrigger Timeline where I need a button to scroll to a specific position. I attempted using seek but it did not work, and even the ScrollTo plugin lacks support for this functionality. The Timeline created using gsap ...

Load image asynchronously using a mirror server in React/Next.js with a set timeout time

For my website, I have decided to store all of my images on IPFS, which are pinned successfully. This has helped reduce traffic and keep costs within the free tier offered by my hosting provider. However, at times the IPFS url may not load fast enough dep ...

Waiting for the `page.evaluate()` method in Node.js Puppeteer---Is there a way

I am facing an issue where I need to wait for the scrolling action to finish before resolving. When I placed resolve() inside the page.evaluate() block, I encountered an error stating: (node:22646) UnhandledPromiseRejectionWarning: Error: Evaluation failed ...

Tips for resolving an issue with an array and the find method?

Seeking guidance on using the find method. Specifically, I am tasked with searching an array to find a specific string match. The catch is that this string may be nested within one of the objects in its child array. I attempted to create an if statement in ...

The basic evaluation of jQuery elements does not result in a comparison

Wondering what's going wrong in this code: employee_ids = $('[data-employee_id="'+employee+'"]'); timestamp_ids = $('[data-scheduled_on="'+timestamp+'"]'); var common = $.grep(timestamp_ids, function(element) ...

What is the mechanism behind the functioning of Long Polling or Comet with PHP?

I am in the process of developing a notification system for my website, with the goal of ensuring that logged-in users are promptly made aware of any new notifications. There are various methods available for achieving this, as many individuals have pointe ...

Ways to send distinct values to updateMany $set in mongodb

I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user. Below is the code snippet that I am working with: func ...

Trouble with feedback form not showing up

I've been working on creating an ajax feedback form, but I'm facing difficulties in getting it to show up properly. The feedback image appears, but clicking on it doesn't trigger any action. Here's my Form: <div id="feedback"> ...

Tips on changing an image with a button click

I am currently working on a project where I have a div tag containing an image that is selected randomly from different arrays based on topics. However, I am facing some challenges in making the image change when the "go" button is clicked. I want the if ...

CSS Class Returns to Inactive State

One of my tasks involves adding a new class to an image. .bbbLink img { outline: 1px solid #ddd; border-top: 1px solid #fff; padding: 10px; background: #f0f0f0; } When hovering over the image, I apply the following styles, .bbbLink img ...

Sending an Ajax request using a dropdown menu

I'm having trouble retrieving a value from my database when a select option is chosen. The select options are generated dynamically from the same database. As a beginner in AJAX requests, I am struggling to figure out why I am only getting a blank re ...

Unable to successfully submit an HTML form following the utilization of a JavaScript script

I am currently working on an HTML site with some complex functionality. Here is a snippet of my code: <html> <head> <link rel="stylesheet" href="~/Content/index.css" /> <link rel="stylesheet" href="~/Scripts/fancyBox/source/jq ...

Grab the inner html content of a specific element and release it into a different element by holding down the mouse button

I am working with a grid that has a start node. My goal is to make this node a draggable object without moving the HTML element itself, as it contains important information about that particular node (such as position and state). Instead, I only want to mo ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

Developing custom events in an NPM package

Developing a basic npm package with signalr integration has been my recent project. Here's how it works: First, the user installs the package Then, the package establishes a connection using signalr At a certain point, the server triggers a function ...

When the jQuery keyup event is triggered, the "function" will be incremented to 0

There are three input fields to search a JSON tree. When all three fields are filled correctly, the data from the next level of the JSON tree is retrieved. A number is incremented through the keyup event to access the next data of the JSON tree. However, ...

What can I do to comprehend and diagnose the error that is appearing in my reactjs code?

Working on a React project, I came across an error in the Google Chrome console. Uncaught true https://i.stack.imgur.com/dL8jW.png https://i.stack.imgur.com/kXn9m.png https://i.stack.imgur.com/UMQbh.png The throw true appears to be causing this uncau ...

Keep running AJAX operations using setTimeout even when the browser window has been closed

I have set up a PHP page that sends an AJAX request to another PHP page containing a casperJS script, which is triggered by a button click and runs every 60 seconds. My goal is to be able to close the browser window while still allowing the AJAX requests ...

How can I toggle the radio button based on the dropdown selection?

I'm attempting to enable or disable a radio button based on the selection from a dropdown menu. View my jsfiddle example here For example, if the user selects "persons" from the dropdown, only the options for Anthony and Paul should be available to ...

Create a library with CSS files added, excluding any test files

As I develop a React library, I've encountered an issue where the CSS files are being ignored during the build process. In an attempt to resolve this, I included the --copy-files flag in the build script, which successful copied the CSS files but also ...