1

I have a function that prints OHLCV data for stock prices from a websocket. It works but I have to copy it for each variable (Var1 to Var14) to get each individual stock data. How would I automate this process given that I have list:

varlist = [var1, var2, var3...var14]

and my code is:

def process_messages_for_var1(msg):
    if msg['e'] == 'error':
        print(msg['m'])
   # If message is a trade, print the OHLC data
    else:
    # Convert time into understandable structure
    transactiontime = msg['k']['T'] / 1000
    transactiontime = datetime.fromtimestamp(transactiontime).strftime('%d %b %Y %H:%M:%S')
    # Process this message once websocket starts
    print("{} - {} - Interval {} - Open: {} - Close: {} - High: {} - Low: {} - Volume: {}".
          format(transactiontime,msg['s'],msg['k']['i'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v']))
    # Also, put information into an array
    kline_array_msg = "{},{},{},{},{},{}".format(
        msg['k']['T'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v'])         
# Insert at first position
    kline_array_dct[var1].insert(0, kline_array_msg)
    if (len(kline_array_dct[var1]) > window): 
        # Remove last message when res_array size is > of FIXED_SIZE
        del kline_array_dct[var1][-1]

I'm hoping to get the following result (notice how function name also changes):

def process_messages_for_var2(msg):
   if msg['e'] == 'error':
       print(msg['m'])
   # If message is a trade, print the OHLC data
   else:
   # Convert time into understandable structure
   transactiontime = msg['k']['T'] / 1000
   transactiontime = datetime.fromtimestamp(transactiontime).strftime('%d %b %Y %H:%M:%S')
   # Process this message once websocket starts
   print("{} - {} - Interval {} - Open: {} - Close: {} - High: {} - Low: {} - Volume: {}".
          format(transactiontime,msg['s'],msg['k']['i'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v']))
    # Also, put information into an array
    kline_array_msg = "{},{},{},{},{},{}".format(
        msg['k']['T'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v'])         
# Insert at first position
    kline_array_dct[var2].insert(0, kline_array_msg)
    if (len(kline_array_dct[var2]) > window): 
        # Remove last message when res_array size is > of FIXED_SIZE
        del kline_array_dct[var2][-1]
5
  • Hello and welcome to StackOverflow! Would you mind fixing your indentation (for example, for if/else)? That'll make your code easier to read. Commented May 21, 2020 at 3:46
  • It seems that the only difference between the two functions is one references var1 and the other references var2. If I'm reading that correctly, couldn't you simply pass the variable in as a function argument? Commented May 21, 2020 at 3:47
  • Hi, thanks the reply. How do you indent? I wasn't able to tab. Commented May 21, 2020 at 3:47
  • That's correct, the only differences are var1 and var2. I'm still new to coding so not sure how to do so. Commented May 21, 2020 at 3:48
  • To indent, just use four spaces. Commented May 21, 2020 at 3:49

2 Answers 2

1

You can adjust the function so that it takes one of the vars as an argument. I.e.,

def process_messages(msg, var):
    ...

    kline_array_dct[var].insert(0, kline_array_msg)
    if (len(kline_array_dct[var]) > window): 
        # Remove last message when res_array size is > of FIXED_SIZE
        del kline_array_dct[var][-1]
Sign up to request clarification or add additional context in comments.

8 Comments

I would also include a for loop to call the process for every var in the list instead of calling it 14 separate times
Hmm the problem is later on I need to start the websocket this way: (1) varlist = [var1, var2, var3...var14] and (2) messages = [process_messages_for_var1, process_messages_for_var2...process_messages_for_var14] and pass it through (3) run_klines = list(map(lambda args: bm_kline.start_kline_socket(*args), zip(varlist, messages))). How would I go about to replace function (2)?
Is messages supposed to be a list of functions?
Yes. Its a list of functions that stores process_messages
Since I don't know how bm_kline.start_kline_socket uses its arguments, it's hard for me to know how things should be arranged. Perhaps you could look at the partial function from the functools module.
|
1

If the processes are generally the same, just define one of them, and give it more arguments:

def process_messages(msg, var)

Then, you can adjust your process code to run through each var when you call it. You can do this by removing the numbered vars in the process code:

if msg['e'] == 'error':
   print(msg['m'])
   # If message is a trade, print the OHLC data
   else:
   # Convert time into understandable structure
   transactiontime = msg['k']['T'] / 1000
   transactiontime = datetime.fromtimestamp(transactiontime).strftime('%d %b %Y %H:%M:%S')
   # Process this message once websocket starts
   print("{} - {} - Interval {} - Open: {} - Close: {} - High: {} - Low: {} - Volume: {}".
          format(transactiontime,msg['s'],msg['k']['i'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v']))
    # Also, put information into an array
    kline_array_msg = "{},{},{},{},{},{}".format(
        msg['k']['T'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v'])         
# Insert at first position
    kline_array_dct[var].insert(0, kline_array_msg)
    if (len(kline_array_dct[var]) > window): 
        # Remove last message when res_array size is > of FIXED_SIZE
        del kline_array_dct[var][-1]

Then, create a simple for loop to call the process for each var in the list:

for var in varList:
    process_messages("msg", var)

The for loop will call the process for each var in the list.

2 Comments

The problem is later on I need to start the websocket this way: (1) varlist = [var1, var2, var3...var14] and (2) messages = [process_messages_for_var1, process_messages_for_var2...process_messages_for_var14] and pass and start the websocket via (3) run_klines = list(map(lambda args: bm_kline.start_kline_socket(*args), zip(varlist, messages))). How would I go about to replace function (2)?
also I get TypeError: string indices must be integers. "msg" is not a string but its to refer to the dictionary of OHLCV data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.