How to receive real time data through Bitmex Websocket Api on python? - python

I understand that I can use "while true" and call the 'get_ticker' method to get the last price of the product, but this drives from python instead of the market itself. I was wondering if there is a way to get the last price as BitMEX's website changes. Thanks

Check my bitmex project, there is solution of your problem: bitmex-supervisor
Essential code fragments:
In __init__():
self.last_price = 0
self._min_price = float('inf')
self._max_price = -1
self.initial_price = float('nan')
self.tracking = False
Methods:
#property
def min_price(self):
return self._min_price
#min_price.setter
def min_price(self, value):
if value < self.initial_price:
self.callback_price_decreased() # here you can do some stuff
self._min_price = value
#property
def max_price(self):
return self._max_price
#max_price.setter
def max_price(self, value):
if value > self.initial_price:
self.callback_price_increased() # here you can do some stuff
self._max_price = value
def stop_trailing(self):
self.tracking = False
def start_trailing(self, initial_price: float):
"""
:param initial_price: the price after reaching which order will be moving
"""
self._max_price = -1
self._min_price = float('inf')
self.initial_price = initial_price
self.tracking = True
In __on_message():
instrument = self.get_instrument(symbol=self.order.symbol)
if instrument is not None:
self.last_price = instrument['lastPrice']
if self.tracking:
if self.last_price > self.max_price and self.order.side == 'Sell':
self.max_price = self.last_price
elif self.last_price < self.min_price and self.order.side == 'Buy':
self.min_price = self.last_price

Related

Proxy Class in Python 3

I wrote a simple Proxy class in python3, but I have a problem with "was_called" function
class Proxy:
last_invoked = ""
calls = {}
def __init__(self, obj):
self._obj = obj
def __getattr__(self, item):
attrs = dir(self._obj)
if item in attrs:
Proxy.last_invoked = item
if item in Proxy.calls.keys():
Proxy.calls[item] += 1
else:
Proxy.calls[item] = 1
if item in Proxy.calls.keys():
Proxy.calls[item] += 1
else:
Proxy.calls[item] = 1
return getattr(self._obj, item)
else:
raise Exception('No Such Method')
def last_invoked_method(self):
if Proxy.last_invoked == "":
raise Exception('No Method Is Invoked')
else:
return Proxy.last_invoked
def count_of_calls(self, method_name):
if method_name in Proxy.calls.keys():
return Proxy.calls[method_name]
return 0
def was_called(self, method_name):
if method_name in Proxy.calls.keys():
if Proxy.calls[method_name] > 0: return True
return False
class Radio():
def __init__(self):
self._channel = None
self.is_on = False
self.volume = 0
def get_channel(self):
return self._channel
def set_channel(self, value):
self._channel = value
def power(self):
self.is_on = not self.is_on
radio = Radio()
radio_proxy = Proxy(radio)
radio.number = 3
radio_proxy.number = 3
radio_proxy.power()
print(radio_proxy.was_called("number"))
print(radio_proxy.was_called("power"))
"was_called" function is work for functions and attributes that is in radio at first such as "power", but it's not work for new attributes that we add such as "number".
I expect for both print "True", because both of "power" and "number" is called. but first print return False!
What do you suggest?
def Proxy(class_type):
class ProxyClass(class_type):
def __init__(self, *args, **kwargs):
# Set your _calls and _last_invoked here, so that they are not class attributes (and are instead instance attributes).
self._calls = {}
self._last_invoked = ""
# Pass the arguments back to the class_type (in our case Radio) to initialize the class.
super().__init__(*args, **kwargs)
def __getattribute__(self, item):
# We must do this prelimary check before continuing on to the elif statement.
# This is since _calls and _last_invoked is grabbed when self._last_invoked/self._calls is called below.
if item in ("_calls", "_last_invoked"):
return super(ProxyClass, self).__getattribute__(item)
elif not item.startswith("_"):
self._last_invoked = item
self._calls[item] = 1 if item not in self._calls.keys() else self._calls[item] + 1
return super(ProxyClass, self).__getattribute__(item)
def __setattr__(self, item, val):
# Wait until _calls is initialized before trying to set anything.
# Only set items that do not start with _
if not item == "_calls" and not item.startswith("_"):
self._calls[item] = 0
super(ProxyClass, self).__setattr__(item, val)
def last_invoked_method(self):
if self._last_invoked == "":
raise Exception('No Method Is Invoked')
else:
return self._last_invoked
def count_of_calls(self, method_name):
return self._calls[method_name] if method_name in self._calls.keys() else 0
def was_called(self, method_name):
return True if method_name in self._calls.keys() and self._calls[method_name] > 0 else False
return ProxyClass
#Proxy
class Radio():
def __init__(self):
self._channel = None
self.is_on = False
self.volume = 0
def get_channel(self):
return self._channel
def set_channel(self, value):
self._channel = value
def power(self):
self.is_on = not self.is_on
radio = Proxy(Radio)()
radio.number = 3 # Notice that we are only setting the digit here.
radio.power()
print(radio._calls)
print(radio.number) # Notice that this when we are actually calling it.
print(radio._calls)
outputs:
{'is_on': 0, 'volume': 0, 'number': 0, 'power': 1}
3
{'is_on': 0, 'volume': 0, 'number': 1, 'power': 1}
A few modifications here and there, but you should be able to see the bigger idea by reading through the code. From here you should be able to modify the code to your liking. Also note that any variable that starts with _ is automatically removed from the _calls dictionary.
If you rather not use the decorator #Proxy, you may initialize your Radio class (as a proxy) like so:
# Second parentheses is where your Radio args go in.
# Since Radio does not take any args, we leave it empty.
radio_proxy = Proxy(Radio)()
Also, make sure to understand the difference between class attributes, and instance attributes.
Edit:
class Test:
def __init__(self, var):
self.var = var
self.dictionary = {}
def __getattribute__(self, item):
print("we are GETTING the following item:", item)
# If we don't do this, you end up in an infinite loop in which Python is
# trying to get the `dictionary` class to do `self.dictionary['dictionary'] = ...`
if item == "dictionary":
super(Test, self).__getattribute__(item)
else:
self.dictionary[item] = "Now we can use this!"
return super(Test, self).__getattribute__(item)
def __setattr__(self, item, key):
print("we are SETTING the following item:", item)
super(Test, self).__setattr__(item, key)
Notice:
test = Test(4)
outputs:
we are SETTING the following item: var
we are SETTING the following item: dictionary
then following it:
test.var
outputs:
we are GETTING the following item: var
we are GETTING the following item: dictionary

Python: List index out of range for hash table program

Not sure if this code works and it shows index out of range which I don't know how to solve
class Hash():
def __init__(self, user):
self.max = user
self.table = []
def isFull(self):
if len(self.table) == self.max:
return True
else:
return False
def insert(self,item):
if self.isFull():
print('Hash table is full')
else:
hashing = self.index(item)
if self.table[hashing] == None:
self.table[hashing] = item
else:
for a in range(len(self.table)):
if self.table[a] == None:
self.table[a] = item
return self.table
def index(self,item):
hashval = int(item) % self.max
return hashval
def searching(self,item):
pass
user = int(input('Enter a number for the maximum number of items that can be stored in the hash table: '))
It says index is out of range due to -> if self.table[hashing] == None:
You are using list instead of dict. You should replace self.table = [] with self.table = {}
if self.table[hashing] == None: will raise an error if hashing not in self.table. You should replace it with: if hashing not in self.table:
for a in range(len(self.table)): will not iterate through self.table because it is not a list. for a in self.table: will work.
Here is the correct code:
class Hash():
def __init__(self, user):
self.max = user
self.table = {}
def isFull(self):
if len(self.table) == self.max:
return True
else:
return False
def insert(self,item):
if self.isFull():
print('Hash table is full')
else:
hashing = self.index(item)
if hashing not in self.table:
self.table[hashing] = item
else:
for a in self.table:
if self.table[a] == None:
self.table[a] = item
return self.table
def index(self,item):
hashval = int(item) % self.max
return hashval
def searching(self,item):
pass
user = int(input('Enter a number for the maximum number of items that can be stored in the hash table: '))
h = Hash(user)
h.insert(5)
h.insert(6)

Instance Method returning the wrong value

I have a class for a Dialogue system as follows
class DIALOGUE(object):
def __init__(self, place, who, sTime, eTime, isActive, mood, menuText, func, repeatable, num):
self.place = place
self.who = who
self.sTime = sTime
self.eTime = eTime
self.isActive = isActive
self.mood = mood
self.menuText = menuText
self.func = func
self.repeatable = repeatable
self.num = num
#property
def ACheck(self):
global Date
if self.sTime == "none":
return True
else:
tHour,tMin = self.sTime.split(":")
if tHour >= Date.Hour and tMin <= Date.Minute:
tHour,tMin = self.eTime.split(":")
if tHour < Date.Hour and tMin < Date.Minute:
return True
return False
#property
def BCheck(self):
global Act
if self.who == Act:
return True
else:
return False
#property
def CCheck(self):
global Location
if self.place == Location:
return True
if self.place == "none":
return True
return False
#property
def DCheck(self):
if self.repeatable:
return True
else:
if self.num > 0:
return False
else:
return True
#property
def CanChat(self):
if self.isActive and self.ACheck and self.BCheck and self.CCheck and self.DCheck:
return True
else:
return False
def SetActive(self):
self.isActive = True
def Do(self):
self.num += 1
renpy.call(self.func)
Most of this should be self explanatory but I parse an XML file into a list of Instances of this class.
The user is presented with a list of available dialogues based on what Location they are in, what time of day it is and what NPC they have selected. If the dialogue is not repeatable The DCheck method looks at whether or not the dialogue has been completed before i.e if the dialogue is not repeatable and self.num > 0 the method will return False
Essentially it loops through all the dialogues and carries out i.CanChat and if this value returns True, the Dialogue is added to the menu
The issue I'm having is that the Check methods aren't returning the correct value. Specifically DCheck is returning True all the time, regardless of whether the Dialogue is repeatable or not, and ignoring the value of self.num
The class is created in an init python: block and then the xml file is parsed in a separate python block which is called from inside the start label
It's probably something really simple but I can't figure it out.
The list of instances is parsed as follows
Dialogues = []
for j in Dialo:
JPlace = j.find('Place').text
JWho = j.find('Who').text
JsTime = j.find('Start').text
JeTime = j.find('End').text
JMood = int(j.find('Mood').text)
JText = j.find('Text').text
JFunc = j.find('Func').text
JRep = j.find('Rep').text
if JRep == "True":
Jrep = True
else:
Jrep = False
Dialogues.append(DIALOGUE(JPlace, JWho, JsTime, JeTime, False, JMood, JText, JFunc, JRep, 0))
The method for creating the menu is as follows
def TalkCheck():
talks = []
talks.append(("Nevermind.", "none"))
for i, q in enumerate(Dialogues):
if q.CanChat:
talks.append((q.menuText,i))
renpy.say(None, "", interact=False)
talkchoice = renpy.display_menu(talks)
if talkchoice <> "none":
talkchoice = int(talkchoice)
Dialogues[talkchoice].Do()
Your question is incomplete - you didn't post a MCVE, we don't know the effective values for "repeatble" and "num" that leads to this behaviour, and we don't even know if it's using Python 2.x or Python 3.x - so we can just try and guess. Now since you mention that you "parse an XML file into a list of instances", I stronly suspect you are running Python 2.x and passing those values as strings instead of (resp.) boolean and int. In Python 2, "-1" (string) compares greater than 0 (int) - it raises a TypeError in Python 3.x -, and in both cases a non-empty string evals to True in a boolean context (bool('False') == True). Since there's no obvious logical error in your method implementation, that's the only explanation I can think of.
BTW, expressions have a boolean values and return exits the function, so you can simplify your code:
#property
def DCheck(self):
if self.repeatable:
return True
return self.num > 0

closest point is equal to whole different places in the tree why?

after returning the closest point of a particular point , the next time when i return the closest point to another point the same closest point as before returns. why is that?
class kdnode:
def __init__(self,point,left,right):
self.point = point
self.left = left
self.right = right
class kdTree:
def __init__(self,points,threshold):
self.threshold = threshold
self.root = self.make_kdtree(points)
self.froot = None
self.isFirst = True
def make_kdtree(self,points,depth = 0):
if(len(points) <= self.threshold):
return kdnode(points,None,None)
dimension = 2
axis = depth % dimension
sp = sorted(points,key = lambda point:point[axis])
mid = len(points)//2
return kdnode(sp[mid],self.make_kdtree(sp[:mid],depth+1),self.make_kdtree(sp[mid+1:],depth+1))
def find_closest(self,point,depth=0):
if self.isFirst:
self.froot = self.root.point
self.isFirst = False
if(self.root.left) is None and self.root.right is None:
return self.root.point
axis = depth%2
if point[axis] > self.root.point[axis]:
self.root = self.root.right
else:
self.root = self.root.left
return self.find_closest(point,depth+1)
This is why:
def find_closest(self,point,depth=0):
if self.isFirst:
self.froot = self.root.point
self.isFirst = False
When find_closest() is called, it changes itself. This is definitely not what you want. find_closest() should be a read-only operation that doesn't destruct the data structure.

How can I take an implementation of a HashTable in python and make it use chaining instead of open addressing?

This is the code I've got that uses open addressing:
import math
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self,key,data):
hashvalue = self.hashfunction(key,len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] = data #replace
else:
nextslot = self.rehash(hashvalue,len(self.slots))
while self.slots[nextslot] != None and \
self.slots[nextslot] != key:
nextslot = self.rehash(nextslot,len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot]=key
self.data[nextslot]=data
else:
self.data[nextslot] = data #replace
def hashfunction(self,key,size):
return key%size
def rehash(self,oldhash,size):
return (oldhash+1)%size
def get(self,key):
startslot = self.hashfunction(key,len(self.slots))
data = None
stop = False
found = False
position = startslot
while self.slots[position] != None and \
not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position=self.rehash(position,len(self.slots))
if position == startslot:
stop = True
return data
def __getitem__(self,key):
return self.get(key)
def __setitem__(self,key,data):
self.put(key,data)
def hash(astring, tablesize):
sum = 0
for pos in range(len(astring)):
sum = sum + ord(astring[pos])
return sum%tablesize
I'm open to using either dictionaries or linked lists for the chaining because it's simple basic.
I'm not sure if I need to make everything in the list a linkedlist or just the ones that need to be chained, also I'm not sure how to get the data from a chained location. Can anyone help me get some ideas?

Categories

Resources