Search code examples
pythonpython-3.xwhile-loopalgorithmic-trading

Summing Results from a function running every 30 seconds


I've made a simple trading strategy, which executes every 30 seconds. I've defined the strategy in a function:

def strategy():
    # strategy
    time.sleep(30)
    print(f'The Result from the Trade is: {result}')

Then I run it through a while loop:

while True:
    strategy()

It's definitely not the best implementation, but it works for only testing a strategy. It shows me the result from each trade. However, I want to let it run through the whole day and accumulate and store the result from each trade in a variable, so I have the final result from all the trades from the whole day.

I've been looking at how to make this happen, but I can't find anything for the structure I have. Can someone help, please?


Solution

  • If you want to sum up the value returned you can do the following

    strategy_output = 0
    while True:
         strategy_output =+ strategy()
    

    If you want to save all the values till the last loop you can mantain the value in a dictionary corresponding to execution time

    from datetime import datetime
    
    strategy_output_dict = {}
    while True:
         now = datetime.now()
         current_time = now.strftime("%H:%M:%S")
         strategy_output = strategy()
         strategy_output_dict[current_time] = strategy_output