Django application to serve separate feeds to each user over Django Channel Package
Clash 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:
Once user register with my application, he can view the list of currency pairs e.g (ETH, BTC etc)
From that list, the user can add one or more pairs to his watchlist.
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?
python python-3.x django
add a comment |Â
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:
Once user register with my application, he can view the list of currency pairs e.g (ETH, BTC etc)
From that list, the user can add one or more pairs to his watchlist.
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?
python python-3.x django
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 aAsyncWebsocketConsumer
and makeFeedsConsumers.periodic
asynchronously send an event every so often?
â James Hiew
May 24 at 8:56
add a comment |Â
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:
Once user register with my application, he can view the list of currency pairs e.g (ETH, BTC etc)
From that list, the user can add one or more pairs to his watchlist.
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?
python python-3.x django
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:
Once user register with my application, he can view the list of currency pairs e.g (ETH, BTC etc)
From that list, the user can add one or more pairs to his watchlist.
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?
python python-3.x django
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 aAsyncWebsocketConsumer
and makeFeedsConsumers.periodic
asynchronously send an event every so often?
â James Hiew
May 24 at 8:56
add a comment |Â
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 aAsyncWebsocketConsumer
and makeFeedsConsumers.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
add a comment |Â
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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 makeFeedsConsumers.periodic
asynchronously send an event every so often?â James Hiew
May 24 at 8:56