Help needed fixing error in code

I have attached the console stack trace and getting an error, as I'm still playing around with limit orders. Will happy to attach the code as well if needed. Not sure, what is going wrong here.

``
Traceback (most recent call last):
File "run_simulation.py", line 558, in
main(sys.argv[1:])
File "run_simulation.py", line 442, in main
cls = extract_strategy_class(src_file)
File "run_simulation.py", line 66, in extract_strategy_class
execfile(filename, global_dict)
File "job/CQ8c5e9d1d357e48b189e295d50682df56.py", line 94
else: # position isn't on, therefore check to see if we should buy.
^
SyntaxError: invalid syntax

Exception during results loading:

account read
log read.
log loaded.
trades read.
trades loaded.
``

Comments

  • ptunneyptunney Posts: 246

    A
    That is not enough information to be able to help. The problem is higher up in your code.
    I have sent you an email.

    Paul

  • `from cloudquant.interfaces import Strategy

    class CQ8c5e9d1d357e48b189e295d50682df56(Strategy):

    #
    # high level strategy - start/finish
    #
    #######################################################################################
    
    # called when the strategy starts (aka before anything else)
    @classmethod
    def on_strategy_start(cls, md, service, account):
        pass
    
    
    # called when the strategy finish (aka after everything else has stopped)
    @classmethod
    def on_strategy_finish(cls, md, service, account):
        pass
    
    ########################################################################################
    #
    # symbol universe
    #
    ########################################################################################
    
    # note that this doesn't start with "self" because it's a @classmethod
    @classmethod
    def is_symbol_qualified(cls, symbol, md, service, account):
        # Return only the symbols that I am interested in trading or researching.
        return symbol in ['GOOG', 'MSFT']
    
    # used to load other symbols data not in is_symbol_qualified(). Only used in backtesting
    @classmethod
    def backtesting_extra_symbols(cls, symbol, md, service, account):
        return False
    
    ########################################################################################
    #
    # start/finish instance related methods
    #
    ########################################################################################
    
    # used to pass external parameters for each instance (same for values for every instance)
    def __init__(self):  # , **params - if passing in parameters is desired
    
        self.IsPositionOn = False  # do we have a position on?
        self.status = 0
        # How Many Bars the position has been held.
        self.filename = "output.csv"
        self.sOutString = ""
    
    # called at the beginning of each instance
    def on_start(self, md, order, service, account):
        # print "OnStart {0}\t{1}\n".format(service.time_to_string(service.system_time), self.symbol)
    
        # The model requires that we have at least X minutes of bar data prior
        # to checking to see if a bear price flip has occurred. Therefore we
        # need a variable to track this start time.
        self.model_start = md.market_open_time + service.time_interval(minutes=5)
    
    # if running with an instance per symbol, call when an instance is terminated
    def on_finish(self, md, order, service, account):
        pass
    
    ########################################################################################
    #
    # timer method
    #
    ########################################################################################
    
    # called in timer event is received
    def on_timer(self, event, md, order, service, account):
        pass
    
    ########################################################################################
    #
    # market data related methods
    #
    ########################################################################################
    
    # called every minute before the first on_trade of every new minute, or 5 seconds after a new minute starts
    def on_minute_bar(self, event, md, order, service, account, bar):
        #
        # don't want to initiate any long positions in the last 5 minutes of the trading day
        # as we won't likely have time to trade out of the position for a profit using 1 minute
        # bar data.
        #
        if service.system_time < md.market_close_time - service.time_interval(minutes=5, seconds=1):
            #
            # If a position is on we want to check to see if we should take a profit or trade out
            # of a losing position.
    
            else:  # position isn't on, therefore check to see if we should buy.
                if (service.system_time > (md.market_open_time + service.time_interval(minutes=30, seconds=1))
                & (self.status = 0)):
                    bar_1 = bar.minute(start=-30, include_empty=True)
                    bv = bar_1.close
                    # Check to see if we have a TD bear flip
                    if len(bv) == 30:
                        mean_initial_price = np.mean(bv)
                        lower_barrier = mean_initial_price-np.std(bv)
                        upper_barrier = mean_initial_price+np.std(bv)
    
                        self.order_handle_b = order.algo_buy(self.symbol, "limit", "init", price=lower_barrier,order_quantity=100)
                        self.order_handle_s = order.algo_sell(self.symbol, "limit", "init", price=higher_barrier,order_quantity=100)
                        self.status = 1
                        print ("Bingo")
    
    
        elif account[self.symbol].position.shares>0:
            ####################################################################
            # close out of our position at the end of the day because we don't
            # want to carry overnight risk.
    
            order_id = order.algo_sell(self.symbol, "market", intent="exit")   
            print('sold ' + self.symbol + ' at end of day.')    
            if len(bar_close)>0:    
                print('Approximate price: ' + str(bar_close[0]))     
    
        elif account[self.symbol].position.shares<0:
    
            order_id = order.algo_buy(self.symbol, "market", intent="exit")
            print('bought ' + self.symbol + ' at end of day.')
            if len(bar_close)>0:
                print('Approximate price: ' + str(bar_close[0]))  
    
    def on_fill(self, event, md, order, service, account): 
        if self.status ==1 or self.status ==2:
            print "{} -  Filled,  price{:8.2f}".format(service.time_to_string(event.timestamp, format='%H:%M:%S'), event.price)
            self.status += 1 # increment status for each fill
        if self.status == 3 :
            print "Both Filled"
            service.terminate()`
    
  • ptunneyptunney Posts: 246

    So it looks like from line 85 to line 104 you are wanting to say, and I will put this in psuedo code with the correct tabulation...

        if time<15:55: 
            If position true : 
                code to get out if I am making money or losing money
            else:
                code to decide if I want to get in.
        elif position positive: #so the line 106 elif is saying, it is after 15:55 so if my position is positive > exit with the appropriate order
            code to exit long position
        elif position negative: # line 116 the elif is saying, it is after 15:55 so if my position negative > exit with the appropriate order 
            code to exit short position        
    

    Tabulation is important in python, as is taking an action after an if, you cannot have an if and not do anything and then have an else which is what you have (and your else is tabbed in too far).

    Your issue is you appear to have copied code, remove the code to get out if I am making money or losing money, then your else is tabbed in too far...

    I will put a print statement in there and tab in your else correctly..

        if service.system_time < md.market_close_time - service.time_interval(minutes=5, seconds=1):
            #
            # If a position is on we want to check to see if we should take a profit or trade out
            # of a losing position.
            else:  # position isn't on, therefore check to see if we should buy.
                if (service.system_time > (md.market_open_time + service.time_interval(minutes=30, seconds=1))
                & (self.status = 0)):
                    bar_1 = bar.minute(start=-30, include_empty=True)
                    bv = bar_1.close
                    # Check to see if we have a TD bear flip
                    if len(bv) == 30:
                        mean_initial_price = np.mean(bv)
                        lower_barrier = mean_initial_price-np.std(bv)
                        upper_barrier = mean_initial_price+np.std(bv)
                        self.order_handle_b = order.algo_buy(self.symbol, "limit", "init", price=lower_barrier,order_quantity=100)
                        self.order_handle_s = order.algo_sell(self.symbol, "limit", "init", price=higher_barrier,order_quantity=100)
                        self.status = 1
                        print ("Bingo")
    

    You also were not importing numpy so I added that, and you called a variable upper_barrier then referenced it alter as higher_barrier.. fixed those for you.

    from cloudquant.interfaces import Strategy
    import numpy as np
    class CQ8c5e9d1d357e48b189e295d50682df56(Strategy):
        @classmethod
        def is_symbol_qualified(cls, symbol, md, service, account):
            # Return only the symbols that I am interested in trading or researching.
            return symbol in ['GOOG', 'MSFT']
        def __init__(self):  # , **params - if passing in parameters is desired
            self.IsPositionOn = False  # do we have a position on?
            self.status = 0
            # How Many Bars the position has been held.
            self.filename = "output.csv"
            self.sOutString = ""
        def on_start(self, md, order, service, account):
            # print "OnStart {0}\t{1}\n".format(service.time_to_string(service.system_time), self.symbol)
            # The model requires that we have at least X minutes of bar data prior
            # to checking to see if a bear price flip has occurred. Therefore we
            # need a variable to track this start time.
            self.model_start = md.market_open_time + service.time_interval(minutes=5)
        def on_minute_bar(self, event, md, order, service, account, bar):
            if service.system_time < md.market_close_time - service.time_interval(minutes=5, seconds=1):
                if account[self.symbol].position.shares!=0:
                    print "I should be checking here to see if I have made enough or lost too much money on this trade"
                    print account.mtm_pl,account.unrealized_entry_pl,account.realized_entry_pl
                else:  # position isn't on, therefore check to see if we should buy.
                    if (service.system_time > (md.market_open_time + service.time_interval(minutes=30, seconds=1)) & (self.status == 0)):
                        bar_1 = bar.minute(start=-30, include_empty=True)
                        bv = bar_1.close
                        # Check to see if we have a TD bear flip
                        if len(bv) == 30:
                            mean_initial_price = np.mean(bv)
                            lower_barrier = mean_initial_price-np.std(bv)
                            upper_barrier = mean_initial_price+np.std(bv)
                            self.order_handle_b = order.algo_buy(self.symbol, "limit", "init", price=lower_barrier,order_quantity=100)
                            self.order_handle_s = order.algo_sell(self.symbol, "limit", "init", price=upper_barrier,order_quantity=100)
                            self.status = 1
                            print ("Bingo")
            elif account[self.symbol].position.shares>0:
                order_id = order.algo_sell(self.symbol, "market", intent="exit")   
                print('sold ' + self.symbol + ' at end of day.')    
                if len(bar_close)>0:    
                    print('Approximate price: ' + str(bar_close[0]))     
            elif account[self.symbol].position.shares<0:
                order_id = order.algo_buy(self.symbol, "market", intent="exit")
                print('bought ' + self.symbol + ' at end of day.')
                if len(bar_close)>0:
                    print('Approximate price: ' + str(bar_close[0]))  
        def on_fill(self, event, md, order, service, account): 
            if self.status ==1 or self.status ==2:
                print "{} -  Filled,  price{:8.2f}".format(service.time_to_string(event.timestamp, format='%H:%M:%S'), event.price)
                self.status += 1 # increment status for each fill
            if self.status == 3 :
                print "Both Filled"
                service.terminate()
    
  • Hi Paul,

    Thanks a ton !! This was really useful. I seem to have made some very silly errors such the naming mismatches, will be careful from now, getting used to the whole IDE and APIs is confusing a bit.

Sign In or Register to comment.