Binary.com Developers

Code samples

Here is a code snippet that opens a websocket, and requests a stream of updates for the symbol R_100.
On receipt of each message, it outputs a message:

var ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089');

ws.onopen = function(evt) {
    ws.send(JSON.stringify({ticks:'R_100'}));
};

ws.onmessage = function(msg) {
   var data = JSON.parse(msg.data);
   console.log('ticks update: %o', data);
};
(ns binaryws.core
   (:require [gniazdo.core :as ws]) ;; [stylefruits/gniazdo "0.4.0"]
   (:require [cheshire.core :refer :all]) ;; [cheshire "5.5.0"]
  (:gen-class))
(defn -main
  [& args]
  (def socket
   (ws/connect
    "wss://ws.binaryws.com/websockets/v3?app_id=1089"
    :on-receive #(prn (parse-string %))))
  (ws/send-msg socket (generate-string {:ticks "R_100"}))
  (Thread/sleep 5000)
  (ws/close socket)
)
ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089')

ws.onopen = (evt) ->
    ws.send JSON.stringify(ticks: 'R_100')

ws.onmessage = (msg) ->
    data = JSON.parse(msg.data)
    console.log 'ticks update: %o', data
using System;
using System.Text;
using System.Threading.Tasks;
using System.Net.WebSockets;
using System.Threading;
using System.Net;

namespace BinaryWSDemo
{
    class BinaryWS
    {
    	private ClientWebSocket ws = new ClientWebSocket();
        private Uri uri = new Uri("wss://ws.binaryws.com/websockets/v3?app_id=1089");
            
        public async Task SendRequest(string data)
        {
        	
        	while(this.ws.State == WebSocketState.Connecting){};
            if (this.ws.State != WebSocketState.Open)
            {
                throw new Exception("Connection is not open.");
            }
            
            var reqAsBytes = Encoding.UTF8.GetBytes(data);
            var ticksRequest = new ArraySegment<byte>(reqAsBytes);

            await this.ws.SendAsync(ticksRequest,
                WebSocketMessageType.Text,
                true,
                CancellationToken.None);
            
            Console.WriteLine("The request has been sent: ");
            Console.WriteLine(data);
            Console.WriteLine("\r\n \r\n");

            
        }
        
        public async Task StartListen(){
        	WebSocketReceiveResult result;
        	while (this.ws.State == WebSocketState.Open){
        	var buffer = new ArraySegment<byte>(new byte[1024]);
                    do
                    {
                        result = await this.ws.ReceiveAsync(new ArraySegment<byte>(buffer.Array), CancellationToken.None);

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                        	Console.WriteLine("Connection Closed!");
                        	break;
                        }
                        else
                        {
                            var str = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                            Console.WriteLine("Received Data at: " + DateTime.Now);
                            Console.WriteLine(str);
                            Console.WriteLine("\r\n");
                        }

                    } while (!result.EndOfMessage);
        	}
        }
        
        public async Task Connect(){
        	Console.WriteLine("Prepare to connect to: " + this.uri.ToString());
        	Console.WriteLine("\r\n");
        	
        	ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
        	await ws.ConnectAsync(uri, CancellationToken.None);
        	
        	Console.WriteLine("The connection is established!");
        	Console.WriteLine("\r\n");
        }

        static void Main(string[] args)
        {
            
			string data = "{\"ticks\":\"R_100\"}";
            
			var bws = new BinaryWS();
			bws.Connect().Wait();
			
			bws.SendRequest(data).Wait();
			bws.StartListen();
            
            Console.ReadLine();
        }
    }
}
# {:socket, "~> 0.3.0"}
# {:poison, "~> 1.5"}
{:ok, omsg}  = Poison.encode(%{:ticks => "R_100"})
socket = Socket.Web.connect! "ws.binaryws.com", 443, [{:secure, true}, {:path, "/websockets/v3?app_id=1089"}]
socket |> Socket.Web.send! {:text, omsg}
{:text, imsg} = socket |> Socket.Web.recv!
IO.puts "ticks update: " <> imsg
package main

import "golang.org/x/net/websocket"

func main() {
	ws, _ := websocket.Dial("wss://ws.binaryws.com/websockets/v3?app_id=1089", "", "http://localhost/")

	ws.Write([]byte(`{"ticks": "R_100"}`))

	var msg = make([]byte, 512000)
	for {
		ws.Read(msg)
		println("Received: ", string(msg))
	}
}
import java.net.URI;
import java.io.IOException;
import java.lang.InterruptedException;
import javax.websocket.*;

@ClientEndpoint
public class WSClient  {

    @OnOpen
    public void onOpen(Session session) throws java.io.IOException
    {
        session.getBasicRemote().sendText("{\"ticks\": \"R_100\"}");
    }

    @OnMessage
    public void onMessage(String message)
    {
        System.out.println("ticks update: " + message);
    }

    public static void main(String[] args)
        throws IOException, DeploymentException, InterruptedException
    {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        URI apiUri = URI.create("wss://ws.binaryws.com/websockets/v3?app_id=1089");
        Session session = container.connectToServer(WSClient.class, apiUri);
        Thread.sleep(10000);
    }
}
use strict;
use warnings;
use v5.10;
use Mojo::UserAgent;
use Data::Dumper;

my $ua = Mojo::UserAgent->new;
$ua->websocket('wss://ws.binaryws.com/websockets/v3?app_id=1089' => sub {
    my ($ua, $tx) = @_;
    say 'WebSocket handshake failed!' and return unless $tx->is_websocket;

    $tx->on(json => sub {
        my ($tx, $data) = @_;
        say "ticks update: " . Dumper(\$data);
    });

    $tx->send({json => {
        ticks => 'R_100'
    }});
});
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
require_once("vendor/autoload.php");

$loop = \React\EventLoop\Factory::create();

$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);

$client = new \Devristo\Phpws\Client\WebSocket("wss://ws.binaryws.com/websockets/v3?app_id=1089", $loop, $logger);

$client->on("connect", function($headers) use ($client, $logger){
    $logger->notice("connected!");
    $client->send("{\"ticks\":\"R_100\"}");
});

$client->on("message", function($message) use ($client, $logger){
    $logger->notice("ticks update: ".$message->getData());
});

$client->open();
$loop->run();
gem install faye-websocket

require 'faye/websocket'
require 'eventmachine'
require 'json'

EM.run {
    ws = Faye::WebSocket::Client.new('wss://ws.binaryws.com/websockets/v3?app_id=1089')

    ws.on :open do |event|
        p [:open]
        ws.send(JSON.generate({ticks:'R_100'}))
    end

    ws.on :message do |event|
        p [:message, event.data]
    end
}
extern crate websocket;    // websocket = "~0.12.2"

use std::string::String;
use websocket::client::request::Url;
use websocket::{Client, Message, Sender, Receiver};

fn main() {
    let url = Url::parse("wss://ws.binaryws.com/websockets/v3?app_id=1089").unwrap();
    let request = Client::connect(url).unwrap();
    let response = request.send().unwrap();
    let (mut sender, mut receiver) = response.begin().split();
    let req = Message::Text(String::from("{\"ticks\": \"R_100\"}"));
    sender.send_message(req).unwrap();
    for message in receiver.incoming_messages::<Message>() {
        match message {
            Ok(Message::Text(m))    => { println!("tick update: {:?}", m) },
            _                       => { break },
        };
    }
}
import websocket
import json

def on_open(ws):
    json_data = json.dumps({'ticks':'R_100'})
    ws.send(json_data)

def on_message(ws, message):
    print('ticks update: %s' % message)

if __name__ == "__main__":
    apiUrl = "wss://ws.binaryws.com/websockets/v3?app_id=1089"
    ws = websocket.WebSocketApp(apiUrl, on_message = on_message, on_open = on_open)
    ws.run_forever()
import org.jfarcand.wcs._   // "org.jfarcand" % "wcs" % "1.4"

object BinaryWS extends App {
  WebSocket().open("wss://ws.binaryws.com/websockets/v3?app_id=1089")
      .listener(new TextListener() {
          override def onMessage(message: String) {
              println("ticks update: "+message)
          }
      })
      .send("{\"ticks\":\"R_100\"}")
}
let ws = WebSocket("wss://ws.binaryws.com/websockets/v3?app_id=1089")

ws.event.open = {
    ws.send("{\"ticks\":\"R_100\"}")
}

ws.event.message = {
    var obj: AnyObject? = NSJSONSerialization.JSONObjectWithData(
        source.dataUsingEncoding(NSUTF8StringEncoding)!,
        options: nil,
        error: &err
    )
    print(obj)
}