Bitcoin Exchange Solution Kit

Developers can quickly and easily deliver real-time trade, pricing and collaborative features
to Bitcoin exchanges using the PubNub Real-Time Network.

Solution Kit Walk-Thru

Real-Time Public Pricing Data Stream

All trading platforms require up to the millisecond pricing information in order to execute trades effectively. Building the infrastructure to stream this data to thousands of devices simultaneously can be costly and difficult to manage. PubNub provides a core messaging platform allowing developers to publish data streams to millions of devices in less than ¼ of a second without the need for any costly servers or configuration.

Full Transaction and Pricing History API

Accurate tracking of transaction data and history is critical to providing a high-trust trading experience. PubNub can automatically record all data that has been published over the network for quick retrieval and playback. In the event a transaction is interrupted for some reason (network connection issues, for example) you could quickly recall historical transaction data and complete the transaction.

Secure Streaming Channels to Users

Security is paramount in a trading platform. Transaction and account information must be kept private from end to end. PubNub offers various encryption and access control options to manage all stream data. Access can be controlled for all operations within the PubNub Real-Time Network.

User Detection & Collaboration Drive a Strong Community

PubNub provides powerful community collaboration features like real-time user presence detection, enabling real-time customer collaboration. With PubNub, it’s easy to build real-time chat, forums, and other collaboration features that allow customers to share information and receive assistance throughout the trading process.

Persistent Socket Connections
The Core of Real-Time Data

The foundation for all these features is the ability to maintain a persistent network connection to all devices, all the time. PubNub ensures that network sockets remain open to any device and that data can be delivered in under ¼ of second anywhere in the world.

User Analytics
Track Visitors and Volumes

Understanding user behaviour is critical to any emerging platform. PubNub provides key analytic data to track unique visitor, traffic volume by data type and geographical information over time. All of this data is presented in a dashboard in our customer portal.

Step-by-Step Solution Kit Guide.

These simple docs will walk you through how to use all the components of Bitcoin Exchange Solution Kit.

The Solution Kit contains client-side (JavaScript) and server-side components (example PHP code, but PubNub supports all popular server-side languages). This Solution Kit will demonstrate how to use the PubNub Real-Time Network to stream trades, price, social, and other data to end-users, as well as other related uses.

While the examples below are in JavaScript and PHP, PubNub supports iOS, Android, Python, .NET, Java, and over 50 other programming environments. Head over to the PubNub Developer Page to download the SDKs needed for your environment.

1. Get Free PubNub API Keys to Power the Solution Kit

You'll need some API Keys to get started. Follow these easy steps:

Step Action to Take
1 Signup For PubNub - Signup/Login to PubNub Admin Portal

Optionally Watch PubNub Basic Video 1 - Registering for PubNub API Keys
The video also describes what each key purpose.

2 Download the SDKs you will need for your programming environment. (The examples below use PHP and JavaScript).

2. Publishing Stream in PHP

<?php
// Require PubNub Library
require_once('Pubnub.php');

// Init PubNub Instance Class
$pubnub = new Pubnub(
    $publish_key,
    $subscribe_key
);

// Publish Ticker Feed Data
$pubnub->publish(array(
    'channel' => 'ticker',
    'message' => array(
        'date'           => 1386661231,
        'amount'         => 0.1,
        'price'          => 940.00001,
        'price_currency' => 'USD'
    )
));
?>

Providing Data for your Subscribers

Real-Time Feeds are easy! Simply take the latest pricing or trade data as it occurs and publish it into a PubNub "channel" from your server. In the example to the left, the channel "ticker" is used; however, you can use countless PubNub channels that each end-user can subscribe to. The example here uses PHP, however this model works equally well with Java, Python, .NET, Perl, or any other server environment.

3. Add PubNub to JavaScript

var pubnub = PUBNUB.init({
    subscribe_key : 'YOUR_SUBSCRIBE_KEY_HERE'
});

Initalize PubNub on your Page

The first step in receiving real-time data thru PubNub is to initialize PubNub on your webpage. PubNub works on any web and mobile browser, from IE6 thru the latest Chrome, Firefox, and Opera browsers.

The following examples below will show a few more options that will allow you to open TCP sockets and stream only the data that you are interested in. This is called Stream Multiplexing which streams multiple feeds over a single TCP Socket.

4. Subscribe to the Stream

pubnub.subscribe({
    backfill : true,
    channel  : [
        'ticker'
    ],
    message  : function( message, env, channel ) {
        // FIRE EVENT WHEN DATA ARRIVES
        PUBNUB.events.fire( channel, message );
    }
});

// Multiplexing channels is performed by simply creating
// a comma-separated list of channels:
...
channel  : [
        'ticker',
        'trade'
    ],
...

Receiving Real-Time Data

The JavaScript to the left will get triggered each time a new message is sent by your server on the 'ticker" channel. Using the PubNub event model, we will fire events based on the channel name. Then we can bind on these events in our view model to update the User Interface.

This is a simple example; but it's also easy to subscribe to multiple channels simultaneously. See the second example to the left.

5. Binding to Data with Callback

//  -- TICKER DISPLAY -- 
PUBNUB.events.bind( 'TRADE', function(data) {
    console.log(data); // Update User Interface Here
} );

// -- TRADES (BUY/SELL) -- 
PUBNUB.events.bind( 'TICKER', function(data) {
    console.log(data); // Update User Interface Here
} );

Hooking up to User Interfaces

Bind to the events which are fired from our data model layer in order to update the user interface. By receiving this data we can issue UI updates which change the display of the ticker numbers and also showing a log of all trades that occur. You may also want to animate the UI to better demonstrate the changes occurring.

6. Live Graph Data with D3.js

var svg  = d3.select("#chart-graph");
var x    = d3.time.scale().range([0, 1140]);
var y    = d3.scale.linear().range([280, 0]);
var area = d3.svg.area()
    .x(function(d)  { return x(d.date); })
    .y0(100)
    .y1(function(d) { return y(d.close); });

(function add_data(data) {
    data.forEach(function(d) {
        d.date  = d3.time.format("%d-%b-%y").parse(d[0]);
        d.close = +d[1];
    });

    x.domain(d3.extent(  data, function(d) { return d.date  }));
    y.domain([0, d3.max( data, function(d) { return d.close })]);

    svg.append("path")
        .datum(data)
        .attr("class", "area")
        .attr("d", area);
})(
    /* [ initial [x,y],.. array of arrays here ] */
);

add_data(data); // append more data;
add_data(data); // append more data;

Graphing Ticker Price Changes

With data streaming in real-time it is easy to capture and display visual reference data in graph form using d3.js rendering the dual axis changes in the ticker price over time. X-axis is price and Y-axis is time. This code gets you started with the graphing points. Note that you need a HTML div element named <div id="chart-graph"></div> as the place holder for the graph.

You can find the D3.js graphing library for data driven documents here.

7. Multi-user Group Chat

// INIT PUB/SUB KEY
var pubnub_chat = PUBNUB.init({
    publish_key   : 'YOUR_SUBSCRIBE_KEY_HERE',
    subscribe_key : 'YOUR_SUBSCRIBE_KEY_HERE'
});

// OPEN DATA STREAM FOR RECEIVING CHAT MESSAGES
pubnub_chat.subscribe({
    backfill : true,
    channel  : chat_channel,
    message  : process_inbound_chat
});

// SEND A CHAT MESSAGE
function send_chat_message( user, message ) {
    var msg = safe(message);
    if (!msg) return;

    pubnub_chat.publish({
        channel : chat_channel,
        message : {
            color   : chat_color,
            date    : +new Date,
            user    : safe(user),
            message : msg
        }
    });
}

Anonymous Group Communication

Create a new instance of PubNub with a second set of API Keys for anonymous group chat. This keeps the namespace separate from your secure streams allowing your users to chat in real-time over anonymous wire.

8. Load Historical Events

pubnub.history({
    limit    : 10,
    channel  : 'TICKER',
    callback : history_receiver
})

function history_receiver(messages) {
    console.log(messages);
}

Pre-populate UI at First Load

Load data from storage back-end in order to update your user interface with latest changes. This is a good idea to do before you open the TCP Socket Stream so you may pre-populate the user interface with most recent events and get the newly launched app in-sync with everyone else.