Exemplo n.º 1
0
    def AddOrder(self,  wallet,  stock,  amount,  unitary_price,  type,  fees):
        log.debug('AddOrder(' + wallet + ',' + stock + ')...')
        
        order = Order(wallet = wallet, 
            stock = stock, 
            amount = amount, 
            unitary_price = unitary_price, 
            type = type, 
            fees = fees
        )
        
        # Check order feasability
        balance_change = order.GetBalanceChange()
        log.debug('balance_change=' + str(balance_change))
        

        
        try:
            wallet = Wallet.objects.get(name=wallet)
            
            new_balance = wallet.balance + balance_change           
            
            if new_balance < 0:
                return tools.HttpHelper.BuildBadRequest('Wallet balance is too low ' + str(wallet.balance))
        except DoesNotExist:
            return tools.HttpHelper.BuildBadRequest('Wallet doesn t exist')
        except Exception as e:
            log.error('Exception: ' + str(e))
            return tools.HttpHelper.BuildBadRequest('Exception: ' + str(e))

        wallet.balance = new_balance

        result = wallet.UpdateWalletItem(stock,  amount,  unitary_price,  type)

        if isinstance(result, WalletItem):
            wallet_item = result
            
            # save all at once
            log.debug('save all at once')
            wallet_item.save();
            order.save()
            wallet.save()
            
            wallet_item.average_cost = wallet.GetAverageCost(stock)
            wallet_item.save()
        else:
            return result            

        log.debug('order applied')
        
        return  tools.HttpHelper.BuildGoodRequest('Order applied')