It's difficult to help you out without knowing where the problem is occuring, since you pasted the whole code.
But if I had to guess, I would say it's because one of your variables (possibly buy or sell) is failing for some reason and not returning anything. Did you by any chance forget to set your APIKEY and SECRET?