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 Long/MAX_VALUE)
  (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();
        }
    }
}
# Build as an escript, cf https://elixirschool.com/en/lessons/advanced/escripts/
# Depends on: [{:socket, "~> 0.3"}, {:poison, "~> 4.0"}]
defmodule BinaryWS do
  def main(_args) do
    {: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})
    spawn_link(fn -> loop(socket) end)
    :timer.sleep(:infinity)
    socket |> Socket.Web.close
  end

  # Start receiving updates in another process until main process wakes up.
  defp loop(socket) do
    case socket |> Socket.Web.recv! do
      {:text, imsg} ->
        IO.puts "ticks update: " <> imsg
        loop(socket)
      _ -> exit(:normal)
    end
  end
end
package main

import (
	"fmt"
	"log"

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

func receive(ticks chan string, ws *websocket.Conn) {
	defer close(ticks)
	var msg string
	for {
		if err := websocket.Message.Receive(ws, &msg); err != nil {
			log.Fatalln("recv:", err)
		}
		ticks <- msg
	}
}

func main() {
	origin := "http://localhost"
	url := "wss://ws.binaryws.com/websockets/v3?app_id=1089"

	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		log.Fatalln("dial:", err)
	}
	defer ws.Close()

	var ticks = make(chan string)
	go receive(ticks, ws)

	if err = websocket.Message.Send(ws, `{"ticks": "R_100"}`); err != nil {
		log.Fatalln("send:", err)
	}

	for {
		select {
		case tick := <-ticks:
			fmt.Println("ticks update:", tick)
		}
	}
}
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);
        while (session.isOpen()) {
            // receive ticks
        }
    }
}

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) = @_;
    unless($tx->is_websocket) {
        say 'WebSocket handshake failed!';
        return;
    }

    $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 __DIR__ . '/vendor/autoload.php';

$loop = \React\EventLoop\Factory::create();
$connector = new \Ratchet\Client\Connector($loop);

$connector('wss://ws.binaryws.com/websockets/v3?app_id=1089')->then(function ($conn) {
    $conn->on('message', function ($msg) {
        echo "ticks update: {$msg}\n";
    });

    $conn->send("{\"ticks\": \"R_100\"}");
});

$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 env_logger;
extern crate ws;

use ws::{connect, CloseCode};

fn main() { 
    env_logger::init();
    println!("Starting connection");
    connect(
        "wss://frontend.binaryws.com/websockets/v3?app_id=1089",
        |out| { 
            println!("Connection established");
            out.send("{\"ticks\": \"R_100\"}").unwrap();
                        
            move |msg| {
                println!("Got message: {}", msg);
                out.close(CloseCode::Normal)
            }
        },
    )
    .unwrap();
    println!("Event loop ended");
}
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()
package com.binary.ws

import com.github.andyglow.websocket._

object BinaryWS extends App {
  val uri = "wss://ws.binaryws.com/websockets/v3?app_id=1089"
  val cli = WebsocketClient[String](uri) {
    case str =>
      println("ticks update: " + str)
  }
  val ws = cli.open()

  ws ! "{\"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)
}