Action Cable (Rails 5) Pulling data from Stock Exchange

151 Views Asked by At

I am hoping to stream data that I receive from a stock exchange (via a websocket) and broadcast that data to the client. I believe action cable is the best approach, but have been unsuccessful thus far.

The "DataProvider" built an SDK on Ruby to create the connection between my server and the stock-exchange server. I have been able to successfully connect, but have not seen data stream in.

Any suggestions?

Channel:

class StockPriceChannel < ApplicationCable::Channel
  def subscribed
    stream_from "portfolio_#{params[:portfolio_id]}"

  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
    EventMachine.stop()
  end

  def receive(data)
    tickers = data["message"]

    tickers = tickers.split(",")

    puts tickers


    options = {
       username: ENV["DataProvider_USERNAME"],
       password: ENV["DataProvider_PASSWORD"],
      channels: tickers
     }

    EventMachine.run do

     client = DataProvider::Realtime::Client.new(options)
      client.on_quote do |quote|
        StockPriceChannel.server.broadcast_to("portfolio_#
 {params[:portfolio_id]}",quote)
      end
      client.connect()

      EventMachine.add_timer(1) do
        puts "joining tickers"
        client.join(tickers)
      end

  #     EventMachine.add_timer(10) do
  #       client.disconnect()
  #       EventMachine.stop()
  #     end

    end
  end
end

ReactJS (in componentDidMount() )

App.portfolioChannel = App.cable.subscriptions.create(
  {
    channel:"StockPriceChannel",
    portfolio_id:this.props.match.params.port_id
  },
  {
    connected: () => console.log("StockPriceChannel connected"),
    disconnected: () => console.log("StockPriceChannel disconnected"),
    received: data => {
      debugger;
      console.log(data)
    }
  }
)
App.portfolioChannel.send({
  message:"AAPL,MSFT"
})
1

There are 1 best solutions below

0
On

Well... I hope this (at the very least) helps some one else.

I realized my issue was

StockPriceChannel.server.broadcast_to("portfolio_#
    {params[:portfolio_id]}",quote)

should be

ActionCable.server.broadcast_to("portfolio_#
    {params[:portfolio_id]}",quote)