Django application to serve separate feeds to each user over Django Channel Package

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












This question is based on my previous question asked here for my code performance and how correct my code. In this section, I have provided my live code which is currently in development:



Django application to serve feeds to each user over websockets



Problem:



I am implementing a WebSocket application for live data feed updates to each client according to their watchlist. Here are the requirements:



  1. Once user register with my application, he can view the list of currency pairs e.g (ETH, BTC etc)


  2. From that list, the user can add one or more pairs to his watchlist.


  3. And based on user's watchlist, the user should get only that data through "Channel 2.1.1" on every data updates on the server end


Here is my Implementation using Django Channel Consumer in which on every request a new channel will create and from that channel user will get his/her feeds.



Web page where I am getting continuous feeds:



 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Feeds</title>
</head>
<body>
<div id="feeds">

</div>
</body>
<script>

function getRandomInt(min, max)
return Math.floor(Math.random() * (max - min + 1)) + min;


var feedUserRoom = user_feed_json ;

console.log(feedUserRoom)

// User watchlist pairs

$pairs =
"1":["NEVABTC", "MZCBTC", "QUNETH", "LINKETH"],
"2":["INSNBTC","LSKBTC", "BCDETH", "VUCBTC"],
"3":["DRPBTC","LBCBTC", "LINDABTC", "PXIBTC"],
"4":["CAPPBTC","SPACEBTC", "BUCKSBTC", "IOPBTC"],
"5":["KRONEBTC","ARGBTC", "BEANBTC", "MTHETH"]


var feedSocket = new WebSocket(
'ws://'+window.location.host+
'/ws/feed/'+feedUserRoom+'/'
);

feedSocket.onmessage = function(e)
var data = JSON.parse(e.data);

// When message comes from a server

if(data['connected'])
console.log(data)
else
console.log("Recieved: ",data)

;

feedSocket.onclose = function(e)
console.error('Chat socket closed unexpectedly: ', e.code);
;

setTimeout(function()
console.log("Message send")
var pairNumber = getRandomInt(1,5);

console.log("Generated Number: ", pairNumber)
feedSocket.send(JSON.stringify(
'uniqueid': feedUserRoom,
'pairs': $pairs[pairNumber]
));
, 2000)


</script>
</html>


My Socket (Consumer) logic where output will push on socket server on every 5 seconds:



from channels.generic.webSocket import WebsocketConsumer
import json
import threading
import random

# importing aribration method here
from .arbitration_calculate import calculateBid


t=0
class FeedsConsumers(WebsocketConsumer):

def periodic(self):
global t
# n = random.randint(10,200)
pairs = self.watchlistpair
self.sendmsg("Watchlist": str(calculateBid(pairs)))
# print(calculateBid(['LTCBTC', 'GASBTC']))
t = threading.Timer(5, self.periodic)
t.start()

def connect(self):
self.accept()
self.sendmsg("connected": "Success!")

def disconnect(self, close_code):
self.sendmsg("disconnected": close_code)

def receive(self, text_data):
# print(text_data)
text_data_json = json.loads(text_data)
message = text_data_json['uniqueid']
self.watchlistpair = text_data_json['pairs']
# Reply message
self.sendmsg(
'uniqueid': message,
'pairs': text_data_json['pairs']
)

# Periodic message
self.periodic()

def sendmsg(self, msg):
print(msg)
self.send(json.dumps(msg))

# def send(self):
# pass


Logic where i am comparing my crypto pairs:



tr_bid = [max_bid_key, exch_list[max_bid_key] + " Bid", bid_list[max_bid_key], bid_vol_list[max_bid_key]]
tr_ask = [min_ask_key, exch_list[min_ask_key] + " Ask", ask_list[min_ask_key], ask_vol_list[min_ask_key]]

gap = tr_bid[2] - tr_ask[2]
gap_pct = (tr_bid[2] / tr_ask[2] - 1)*100
mid_mkt_px = (tr_bid[2] + tr_ask[2])/2

if tr_bid[0] != tr_ask[0] and tr_bid[2] > tr_ask[2] and tr_bid[2] != 0 and tr_ask[2] != 0: #and gap_pct > 0.09:
ts = int(time.time())
res2 =
'SYMBOL': i.upper(),
'QUOTE' : i[-3:].upper(),
'BID_EXCH': exch_list[tr_bid[0]], 'BID_PX': tr_bid[2],
'ASK_EXCH': exch_list[tr_ask[0]], 'ASK_PX': tr_ask[2],
'GAP': round(gap,8),
'GAP%': round(gap_pct,8),
'TS_UNIX': ts,
'TS': datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'),
'YYYY': datetime.datetime.fromtimestamp(ts).strftime('%Y'),
'MM' : datetime.datetime.fromtimestamp(ts).strftime('%m'),
'DD' : datetime.datetime.fromtimestamp(ts).strftime('%d'),
'HR' : datetime.datetime.fromtimestamp(ts).strftime('%H'),
'MIN' : datetime.datetime.fromtimestamp(ts).strftime('%M'),


calculated_crypto_pairs[i.upper()] = res2
else:
calculated_crypto_pairs[i.upper()] =

return calculated_crypto_pairs


Output:





'Watchlist': "'VUCBTC': , 'LSKBTC': , 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': , 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': 'GAP%': 0.04828002, 'QUOTE': 'BTC', 'TS_UNIX': 1526899276, 'DD': '21', 'BID_PX': 0.00132624, 'ASK_EXCH': 'Binance', 'MIN': '41', 'BID_EXCH': 'Bittrex', 'YYYY': '2018', 'MM': '05', 'ASK_PX': 0.0013256, 'HR': '10', 'TS': '2018-05-21 10:41:16', 'GAP': 6.4e-07, 'SYMBOL': 'LSKBTC', 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': 'GAP%': 0.04828002, 'QUOTE': 'BTC', 'TS_UNIX': 1526899304, 'DD': '21', 'BID_PX': 0.00132624, 'ASK_EXCH': 'Binance', 'MIN': '41', 'BID_EXCH': 'Bittrex', 'YYYY': '2018', 'MM': '05', 'ASK_PX': 0.0013256, 'HR': '10', 'TS': '2018-05-21 10:41:44', 'GAP': 6.4e-07, 'SYMBOL': 'LSKBTC', 'INSNBTC': , 'BCDETH': "


Is this correct the implementation for periodic output to each user with separate output, or is there any other method to implement this?







share|improve this question





















  • Does your code currently achieve what you want it to? If the five second period isn't a hard requirement I think you could use a AsyncWebsocketConsumer and make FeedsConsumers.periodic asynchronously send an event every so often?
    – James Hiew
    May 24 at 8:56
















up vote
0
down vote

favorite












This question is based on my previous question asked here for my code performance and how correct my code. In this section, I have provided my live code which is currently in development:



Django application to serve feeds to each user over websockets



Problem:



I am implementing a WebSocket application for live data feed updates to each client according to their watchlist. Here are the requirements:



  1. Once user register with my application, he can view the list of currency pairs e.g (ETH, BTC etc)


  2. From that list, the user can add one or more pairs to his watchlist.


  3. And based on user's watchlist, the user should get only that data through "Channel 2.1.1" on every data updates on the server end


Here is my Implementation using Django Channel Consumer in which on every request a new channel will create and from that channel user will get his/her feeds.



Web page where I am getting continuous feeds:



 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Feeds</title>
</head>
<body>
<div id="feeds">

</div>
</body>
<script>

function getRandomInt(min, max)
return Math.floor(Math.random() * (max - min + 1)) + min;


var feedUserRoom = user_feed_json ;

console.log(feedUserRoom)

// User watchlist pairs

$pairs =
"1":["NEVABTC", "MZCBTC", "QUNETH", "LINKETH"],
"2":["INSNBTC","LSKBTC", "BCDETH", "VUCBTC"],
"3":["DRPBTC","LBCBTC", "LINDABTC", "PXIBTC"],
"4":["CAPPBTC","SPACEBTC", "BUCKSBTC", "IOPBTC"],
"5":["KRONEBTC","ARGBTC", "BEANBTC", "MTHETH"]


var feedSocket = new WebSocket(
'ws://'+window.location.host+
'/ws/feed/'+feedUserRoom+'/'
);

feedSocket.onmessage = function(e)
var data = JSON.parse(e.data);

// When message comes from a server

if(data['connected'])
console.log(data)
else
console.log("Recieved: ",data)

;

feedSocket.onclose = function(e)
console.error('Chat socket closed unexpectedly: ', e.code);
;

setTimeout(function()
console.log("Message send")
var pairNumber = getRandomInt(1,5);

console.log("Generated Number: ", pairNumber)
feedSocket.send(JSON.stringify(
'uniqueid': feedUserRoom,
'pairs': $pairs[pairNumber]
));
, 2000)


</script>
</html>


My Socket (Consumer) logic where output will push on socket server on every 5 seconds:



from channels.generic.webSocket import WebsocketConsumer
import json
import threading
import random

# importing aribration method here
from .arbitration_calculate import calculateBid


t=0
class FeedsConsumers(WebsocketConsumer):

def periodic(self):
global t
# n = random.randint(10,200)
pairs = self.watchlistpair
self.sendmsg("Watchlist": str(calculateBid(pairs)))
# print(calculateBid(['LTCBTC', 'GASBTC']))
t = threading.Timer(5, self.periodic)
t.start()

def connect(self):
self.accept()
self.sendmsg("connected": "Success!")

def disconnect(self, close_code):
self.sendmsg("disconnected": close_code)

def receive(self, text_data):
# print(text_data)
text_data_json = json.loads(text_data)
message = text_data_json['uniqueid']
self.watchlistpair = text_data_json['pairs']
# Reply message
self.sendmsg(
'uniqueid': message,
'pairs': text_data_json['pairs']
)

# Periodic message
self.periodic()

def sendmsg(self, msg):
print(msg)
self.send(json.dumps(msg))

# def send(self):
# pass


Logic where i am comparing my crypto pairs:



tr_bid = [max_bid_key, exch_list[max_bid_key] + " Bid", bid_list[max_bid_key], bid_vol_list[max_bid_key]]
tr_ask = [min_ask_key, exch_list[min_ask_key] + " Ask", ask_list[min_ask_key], ask_vol_list[min_ask_key]]

gap = tr_bid[2] - tr_ask[2]
gap_pct = (tr_bid[2] / tr_ask[2] - 1)*100
mid_mkt_px = (tr_bid[2] + tr_ask[2])/2

if tr_bid[0] != tr_ask[0] and tr_bid[2] > tr_ask[2] and tr_bid[2] != 0 and tr_ask[2] != 0: #and gap_pct > 0.09:
ts = int(time.time())
res2 =
'SYMBOL': i.upper(),
'QUOTE' : i[-3:].upper(),
'BID_EXCH': exch_list[tr_bid[0]], 'BID_PX': tr_bid[2],
'ASK_EXCH': exch_list[tr_ask[0]], 'ASK_PX': tr_ask[2],
'GAP': round(gap,8),
'GAP%': round(gap_pct,8),
'TS_UNIX': ts,
'TS': datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'),
'YYYY': datetime.datetime.fromtimestamp(ts).strftime('%Y'),
'MM' : datetime.datetime.fromtimestamp(ts).strftime('%m'),
'DD' : datetime.datetime.fromtimestamp(ts).strftime('%d'),
'HR' : datetime.datetime.fromtimestamp(ts).strftime('%H'),
'MIN' : datetime.datetime.fromtimestamp(ts).strftime('%M'),


calculated_crypto_pairs[i.upper()] = res2
else:
calculated_crypto_pairs[i.upper()] =

return calculated_crypto_pairs


Output:





'Watchlist': "'VUCBTC': , 'LSKBTC': , 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': , 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': 'GAP%': 0.04828002, 'QUOTE': 'BTC', 'TS_UNIX': 1526899276, 'DD': '21', 'BID_PX': 0.00132624, 'ASK_EXCH': 'Binance', 'MIN': '41', 'BID_EXCH': 'Bittrex', 'YYYY': '2018', 'MM': '05', 'ASK_PX': 0.0013256, 'HR': '10', 'TS': '2018-05-21 10:41:16', 'GAP': 6.4e-07, 'SYMBOL': 'LSKBTC', 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': 'GAP%': 0.04828002, 'QUOTE': 'BTC', 'TS_UNIX': 1526899304, 'DD': '21', 'BID_PX': 0.00132624, 'ASK_EXCH': 'Binance', 'MIN': '41', 'BID_EXCH': 'Bittrex', 'YYYY': '2018', 'MM': '05', 'ASK_PX': 0.0013256, 'HR': '10', 'TS': '2018-05-21 10:41:44', 'GAP': 6.4e-07, 'SYMBOL': 'LSKBTC', 'INSNBTC': , 'BCDETH': "


Is this correct the implementation for periodic output to each user with separate output, or is there any other method to implement this?







share|improve this question





















  • Does your code currently achieve what you want it to? If the five second period isn't a hard requirement I think you could use a AsyncWebsocketConsumer and make FeedsConsumers.periodic asynchronously send an event every so often?
    – James Hiew
    May 24 at 8:56












up vote
0
down vote

favorite









up vote
0
down vote

favorite











This question is based on my previous question asked here for my code performance and how correct my code. In this section, I have provided my live code which is currently in development:



Django application to serve feeds to each user over websockets



Problem:



I am implementing a WebSocket application for live data feed updates to each client according to their watchlist. Here are the requirements:



  1. Once user register with my application, he can view the list of currency pairs e.g (ETH, BTC etc)


  2. From that list, the user can add one or more pairs to his watchlist.


  3. And based on user's watchlist, the user should get only that data through "Channel 2.1.1" on every data updates on the server end


Here is my Implementation using Django Channel Consumer in which on every request a new channel will create and from that channel user will get his/her feeds.



Web page where I am getting continuous feeds:



 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Feeds</title>
</head>
<body>
<div id="feeds">

</div>
</body>
<script>

function getRandomInt(min, max)
return Math.floor(Math.random() * (max - min + 1)) + min;


var feedUserRoom = user_feed_json ;

console.log(feedUserRoom)

// User watchlist pairs

$pairs =
"1":["NEVABTC", "MZCBTC", "QUNETH", "LINKETH"],
"2":["INSNBTC","LSKBTC", "BCDETH", "VUCBTC"],
"3":["DRPBTC","LBCBTC", "LINDABTC", "PXIBTC"],
"4":["CAPPBTC","SPACEBTC", "BUCKSBTC", "IOPBTC"],
"5":["KRONEBTC","ARGBTC", "BEANBTC", "MTHETH"]


var feedSocket = new WebSocket(
'ws://'+window.location.host+
'/ws/feed/'+feedUserRoom+'/'
);

feedSocket.onmessage = function(e)
var data = JSON.parse(e.data);

// When message comes from a server

if(data['connected'])
console.log(data)
else
console.log("Recieved: ",data)

;

feedSocket.onclose = function(e)
console.error('Chat socket closed unexpectedly: ', e.code);
;

setTimeout(function()
console.log("Message send")
var pairNumber = getRandomInt(1,5);

console.log("Generated Number: ", pairNumber)
feedSocket.send(JSON.stringify(
'uniqueid': feedUserRoom,
'pairs': $pairs[pairNumber]
));
, 2000)


</script>
</html>


My Socket (Consumer) logic where output will push on socket server on every 5 seconds:



from channels.generic.webSocket import WebsocketConsumer
import json
import threading
import random

# importing aribration method here
from .arbitration_calculate import calculateBid


t=0
class FeedsConsumers(WebsocketConsumer):

def periodic(self):
global t
# n = random.randint(10,200)
pairs = self.watchlistpair
self.sendmsg("Watchlist": str(calculateBid(pairs)))
# print(calculateBid(['LTCBTC', 'GASBTC']))
t = threading.Timer(5, self.periodic)
t.start()

def connect(self):
self.accept()
self.sendmsg("connected": "Success!")

def disconnect(self, close_code):
self.sendmsg("disconnected": close_code)

def receive(self, text_data):
# print(text_data)
text_data_json = json.loads(text_data)
message = text_data_json['uniqueid']
self.watchlistpair = text_data_json['pairs']
# Reply message
self.sendmsg(
'uniqueid': message,
'pairs': text_data_json['pairs']
)

# Periodic message
self.periodic()

def sendmsg(self, msg):
print(msg)
self.send(json.dumps(msg))

# def send(self):
# pass


Logic where i am comparing my crypto pairs:



tr_bid = [max_bid_key, exch_list[max_bid_key] + " Bid", bid_list[max_bid_key], bid_vol_list[max_bid_key]]
tr_ask = [min_ask_key, exch_list[min_ask_key] + " Ask", ask_list[min_ask_key], ask_vol_list[min_ask_key]]

gap = tr_bid[2] - tr_ask[2]
gap_pct = (tr_bid[2] / tr_ask[2] - 1)*100
mid_mkt_px = (tr_bid[2] + tr_ask[2])/2

if tr_bid[0] != tr_ask[0] and tr_bid[2] > tr_ask[2] and tr_bid[2] != 0 and tr_ask[2] != 0: #and gap_pct > 0.09:
ts = int(time.time())
res2 =
'SYMBOL': i.upper(),
'QUOTE' : i[-3:].upper(),
'BID_EXCH': exch_list[tr_bid[0]], 'BID_PX': tr_bid[2],
'ASK_EXCH': exch_list[tr_ask[0]], 'ASK_PX': tr_ask[2],
'GAP': round(gap,8),
'GAP%': round(gap_pct,8),
'TS_UNIX': ts,
'TS': datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'),
'YYYY': datetime.datetime.fromtimestamp(ts).strftime('%Y'),
'MM' : datetime.datetime.fromtimestamp(ts).strftime('%m'),
'DD' : datetime.datetime.fromtimestamp(ts).strftime('%d'),
'HR' : datetime.datetime.fromtimestamp(ts).strftime('%H'),
'MIN' : datetime.datetime.fromtimestamp(ts).strftime('%M'),


calculated_crypto_pairs[i.upper()] = res2
else:
calculated_crypto_pairs[i.upper()] =

return calculated_crypto_pairs


Output:





'Watchlist': "'VUCBTC': , 'LSKBTC': , 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': , 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': 'GAP%': 0.04828002, 'QUOTE': 'BTC', 'TS_UNIX': 1526899276, 'DD': '21', 'BID_PX': 0.00132624, 'ASK_EXCH': 'Binance', 'MIN': '41', 'BID_EXCH': 'Bittrex', 'YYYY': '2018', 'MM': '05', 'ASK_PX': 0.0013256, 'HR': '10', 'TS': '2018-05-21 10:41:16', 'GAP': 6.4e-07, 'SYMBOL': 'LSKBTC', 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': 'GAP%': 0.04828002, 'QUOTE': 'BTC', 'TS_UNIX': 1526899304, 'DD': '21', 'BID_PX': 0.00132624, 'ASK_EXCH': 'Binance', 'MIN': '41', 'BID_EXCH': 'Bittrex', 'YYYY': '2018', 'MM': '05', 'ASK_PX': 0.0013256, 'HR': '10', 'TS': '2018-05-21 10:41:44', 'GAP': 6.4e-07, 'SYMBOL': 'LSKBTC', 'INSNBTC': , 'BCDETH': "


Is this correct the implementation for periodic output to each user with separate output, or is there any other method to implement this?







share|improve this question













This question is based on my previous question asked here for my code performance and how correct my code. In this section, I have provided my live code which is currently in development:



Django application to serve feeds to each user over websockets



Problem:



I am implementing a WebSocket application for live data feed updates to each client according to their watchlist. Here are the requirements:



  1. Once user register with my application, he can view the list of currency pairs e.g (ETH, BTC etc)


  2. From that list, the user can add one or more pairs to his watchlist.


  3. And based on user's watchlist, the user should get only that data through "Channel 2.1.1" on every data updates on the server end


Here is my Implementation using Django Channel Consumer in which on every request a new channel will create and from that channel user will get his/her feeds.



Web page where I am getting continuous feeds:



 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Feeds</title>
</head>
<body>
<div id="feeds">

</div>
</body>
<script>

function getRandomInt(min, max)
return Math.floor(Math.random() * (max - min + 1)) + min;


var feedUserRoom = user_feed_json ;

console.log(feedUserRoom)

// User watchlist pairs

$pairs =
"1":["NEVABTC", "MZCBTC", "QUNETH", "LINKETH"],
"2":["INSNBTC","LSKBTC", "BCDETH", "VUCBTC"],
"3":["DRPBTC","LBCBTC", "LINDABTC", "PXIBTC"],
"4":["CAPPBTC","SPACEBTC", "BUCKSBTC", "IOPBTC"],
"5":["KRONEBTC","ARGBTC", "BEANBTC", "MTHETH"]


var feedSocket = new WebSocket(
'ws://'+window.location.host+
'/ws/feed/'+feedUserRoom+'/'
);

feedSocket.onmessage = function(e)
var data = JSON.parse(e.data);

// When message comes from a server

if(data['connected'])
console.log(data)
else
console.log("Recieved: ",data)

;

feedSocket.onclose = function(e)
console.error('Chat socket closed unexpectedly: ', e.code);
;

setTimeout(function()
console.log("Message send")
var pairNumber = getRandomInt(1,5);

console.log("Generated Number: ", pairNumber)
feedSocket.send(JSON.stringify(
'uniqueid': feedUserRoom,
'pairs': $pairs[pairNumber]
));
, 2000)


</script>
</html>


My Socket (Consumer) logic where output will push on socket server on every 5 seconds:



from channels.generic.webSocket import WebsocketConsumer
import json
import threading
import random

# importing aribration method here
from .arbitration_calculate import calculateBid


t=0
class FeedsConsumers(WebsocketConsumer):

def periodic(self):
global t
# n = random.randint(10,200)
pairs = self.watchlistpair
self.sendmsg("Watchlist": str(calculateBid(pairs)))
# print(calculateBid(['LTCBTC', 'GASBTC']))
t = threading.Timer(5, self.periodic)
t.start()

def connect(self):
self.accept()
self.sendmsg("connected": "Success!")

def disconnect(self, close_code):
self.sendmsg("disconnected": close_code)

def receive(self, text_data):
# print(text_data)
text_data_json = json.loads(text_data)
message = text_data_json['uniqueid']
self.watchlistpair = text_data_json['pairs']
# Reply message
self.sendmsg(
'uniqueid': message,
'pairs': text_data_json['pairs']
)

# Periodic message
self.periodic()

def sendmsg(self, msg):
print(msg)
self.send(json.dumps(msg))

# def send(self):
# pass


Logic where i am comparing my crypto pairs:



tr_bid = [max_bid_key, exch_list[max_bid_key] + " Bid", bid_list[max_bid_key], bid_vol_list[max_bid_key]]
tr_ask = [min_ask_key, exch_list[min_ask_key] + " Ask", ask_list[min_ask_key], ask_vol_list[min_ask_key]]

gap = tr_bid[2] - tr_ask[2]
gap_pct = (tr_bid[2] / tr_ask[2] - 1)*100
mid_mkt_px = (tr_bid[2] + tr_ask[2])/2

if tr_bid[0] != tr_ask[0] and tr_bid[2] > tr_ask[2] and tr_bid[2] != 0 and tr_ask[2] != 0: #and gap_pct > 0.09:
ts = int(time.time())
res2 =
'SYMBOL': i.upper(),
'QUOTE' : i[-3:].upper(),
'BID_EXCH': exch_list[tr_bid[0]], 'BID_PX': tr_bid[2],
'ASK_EXCH': exch_list[tr_ask[0]], 'ASK_PX': tr_ask[2],
'GAP': round(gap,8),
'GAP%': round(gap_pct,8),
'TS_UNIX': ts,
'TS': datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'),
'YYYY': datetime.datetime.fromtimestamp(ts).strftime('%Y'),
'MM' : datetime.datetime.fromtimestamp(ts).strftime('%m'),
'DD' : datetime.datetime.fromtimestamp(ts).strftime('%d'),
'HR' : datetime.datetime.fromtimestamp(ts).strftime('%H'),
'MIN' : datetime.datetime.fromtimestamp(ts).strftime('%M'),


calculated_crypto_pairs[i.upper()] = res2
else:
calculated_crypto_pairs[i.upper()] =

return calculated_crypto_pairs


Output:





'Watchlist': "'VUCBTC': , 'LSKBTC': , 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': , 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': 'GAP%': 0.04828002, 'QUOTE': 'BTC', 'TS_UNIX': 1526899276, 'DD': '21', 'BID_PX': 0.00132624, 'ASK_EXCH': 'Binance', 'MIN': '41', 'BID_EXCH': 'Bittrex', 'YYYY': '2018', 'MM': '05', 'ASK_PX': 0.0013256, 'HR': '10', 'TS': '2018-05-21 10:41:16', 'GAP': 6.4e-07, 'SYMBOL': 'LSKBTC', 'INSNBTC': , 'BCDETH': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'MTHETH': , 'KRONEBTC': , 'BEANBTC': , 'ARGBTC': "
'Watchlist': "'LBCBTC': , 'DRPBTC': , 'LINDABTC': , 'PXIBTC': "
'Watchlist': "'VUCBTC': , 'LSKBTC': 'GAP%': 0.04828002, 'QUOTE': 'BTC', 'TS_UNIX': 1526899304, 'DD': '21', 'BID_PX': 0.00132624, 'ASK_EXCH': 'Binance', 'MIN': '41', 'BID_EXCH': 'Bittrex', 'YYYY': '2018', 'MM': '05', 'ASK_PX': 0.0013256, 'HR': '10', 'TS': '2018-05-21 10:41:44', 'GAP': 6.4e-07, 'SYMBOL': 'LSKBTC', 'INSNBTC': , 'BCDETH': "


Is this correct the implementation for periodic output to each user with separate output, or is there any other method to implement this?









share|improve this question












share|improve this question




share|improve this question








edited May 28 at 1:29









Jamal♦

30.1k11114225




30.1k11114225









asked May 21 at 11:02









Sahadev

1011




1011











  • Does your code currently achieve what you want it to? If the five second period isn't a hard requirement I think you could use a AsyncWebsocketConsumer and make FeedsConsumers.periodic asynchronously send an event every so often?
    – James Hiew
    May 24 at 8:56
















  • Does your code currently achieve what you want it to? If the five second period isn't a hard requirement I think you could use a AsyncWebsocketConsumer and make FeedsConsumers.periodic asynchronously send an event every so often?
    – James Hiew
    May 24 at 8:56















Does your code currently achieve what you want it to? If the five second period isn't a hard requirement I think you could use a AsyncWebsocketConsumer and make FeedsConsumers.periodic asynchronously send an event every so often?
– James Hiew
May 24 at 8:56




Does your code currently achieve what you want it to? If the five second period isn't a hard requirement I think you could use a AsyncWebsocketConsumer and make FeedsConsumers.periodic asynchronously send an event every so often?
– James Hiew
May 24 at 8:56















active

oldest

votes











Your Answer




StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");

StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: false,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);








 

draft saved


draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194863%2fdjango-application-to-serve-separate-feeds-to-each-user-over-django-channel-pack%23new-answer', 'question_page');

);

Post as a guest



































active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes










 

draft saved


draft discarded


























 


draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194863%2fdjango-application-to-serve-separate-feeds-to-each-user-over-django-channel-pack%23new-answer', 'question_page');

);

Post as a guest













































































Popular posts from this blog

Greedy Best First Search implementation in Rust

Function to Return a JSON Like Objects Using VBA Collections and Arrays

C++11 CLH Lock Implementation