Skip to main content
This example demonstrates how to connect to the WebSocket API directly from a browser using the native WebSocket object.
Security Note: Exposing your API key in client-side code (like this example) is risky because anyone can view the source code and steal your key.For production applications, we recommend using a backend proxy.

Full Example

index.html
<!DOCTYPE html>
<html>
<body>
  <script src="websocket.js"></script>
  <pre id="output">Example API output:
-------------------
</pre>
  <script>

      var protocb = new Object(),
          wscb = new Object(),
          ws,
          pre = document.getElementById('output');

      protocb.__default = null;

      protocb.on0 = function() {
        print('Connected.');
      };

      protocb.on1 = function(data) {
        print('Data received: ' + JSON.stringify(data));
      };

      protocb.on2 = function() {
        print('Ping received.');
      };

      protocb.on7 = function(error) {
        print('Error:' + error);
      };

      protocb.on8 = function(error) {
        print('Error:' + error);
      };

      protocb.on9 = function(error) {
        print('Error:' + error);
      };

      protocb.fatal = function(error) {
        print('Error:' + error);
      };

      wscb.onopen = function() {
        print('Connection opened.');
      };

      wscb.onclose = function() {
        print('Connection closed.');
      };

      wscb.onerror = function() {
        print('Fatal error.');
      };

      var p = new Proto('wss://api.xchangeapi.com/websocket/live?api-key=<YOUR_API_KEY>', wscb, protocb);

      p.start(['EURUSD', 'GBPCHF']);

      function print(message) {
        console.log(message);
        pre.innerHTML += message + "\n"
      }

  </script>
</body>
</html>

Running Locally

To run this example on your machine:
  1. Create a new folder for the project:
    mkdir websocket-example
    cd websocket-example
    
  2. Download the example files:
    curl -O https://xchangeapi.com/docs/websocket/example-implementation/js/index.html
    curl -O https://xchangeapi.com/docs/websocket/example-implementation/js/websocket.js
    
  3. Open index.html in your text editor and replace <YOUR_API_KEY> with your actual API key. For more details on API keys, see the Authentication page.
  4. Open index.html in your web browser. You can do this by double-clicking the file or using the command line:
open index.html