This code is a class I use in my financial market trading bot (note: I'm a daytrader-come-beginner programmer, not the other way around).
Although I have the application running successfully, it has major design flaws which I intend to now address ASAP.
An API requires that a unique transaction ref is submitted with each new order, otherwise, that order will be rejected. I have very little idea if this is a competent or robust design, I could not find any guidance on the issue elsewhere.
I'm very much open to refactoring or a completely new design.
class UniqueTransactionRef:
"""Transaction reference number iterator
Loads, generates and saves unique transaction ref data for ``Bot`` orders
:ivar file: absolute path the the .json transaction ref data file
:ivar num: an integer representing the last generated transaction ref number
"""
default_file = r"C:\Bot\Bot\trans_ref.json"
def __init__(self, file=None):
"""Initialize the UniqueTransactionRef object
:param file: an absolute path to a .json file containing the transaction
reference number, as an integer
"""
self.file = file if file else self.default_file
self.num = 0
self.load()
def __iter__(self):
return self
def __next__(self):
"""Increment the self.num attribute. Save the value to the local file.
:returns: a string formatted version of the self.num class attribute
"""
self.num += 1
self.save()
return str(self.num)
def get(self):
"""Call the ``next`` function on self """
return next(self)
def load(self):
"""Load the transaction ref data from the local file
:raises errors.UniqueTransactionRefError: Cannot find file
"""
try:
with open(self.file) as f:
self.num = json.load(f)
except FileNotFoundError:
raise errors.UniqueTransactionRefError(
self.file,
num=self.num,
message="Cannot find file",
)
def save(self):
"""Save self.num to the designated local file
:raises UniqueTransactionRefError:
"""
try:
with open(self.file, "w") as f:
json.dump(self.num, f)
except Exception as e:
raise errors.UniqueTransactionRefError(self.file,
num=self.num,
message=e)
unique_trans_ref = UniqueTransactionRef() # module level variable
Simplified example usage:
class Bot:
def __init__(self, unique_trans_ref):
self.unique_trans_ref = unique_trans_ref
def construct_order():
trans_ref = next(self.unique_trans_ref)