The increasing penetration of renewable energy resources and volatility of energy prices cause huge challenges in planning and regulating energy generation, transport, and distribution. A possible solution can be a paradigm change of employing control actions from the demand side in addition to the conventional generation control. To realize such shifts, the primary stage should be a proper and robust analysis of the energy flexibility on the demand side. Recently, demand side control in buildings has become a major research issue because buildings share a substantial portion of the total electricity consumption. The increasing use of controllable devices in buildings combined with the advent of smart metering system has paved the way to exploit the potential flexibility of managing the energy generation and demand of buildings for optimal energy trading. In this paper, we investigate the benefits of demand resources in buildings for optimal energy trading in day-ahead and real-time energy markets. The building flexible demand resources considered are electric vehicles and batteries. The paper examines the combined optimization of EVs and batteries in the day-ahead and regulation electricity markets with the objective of maximizing the total profit of the building microgrid. It takes EVs driving pattern into consideration. The major contribution of the paper is the exploitation of the energy flexibility of buildings using EVs as dynamic energy storage device and batteries as manageable demand facility. The devised optimization problem is formulated as a double-stage mixed-integer linear programming (MILP) problem, and solved using the CPLEX solver. Several numerical results are presented to validate the effectiveness of the devised optimization framework using actual data of building electricity demand and local renewable generation in the Otaniemi area of Espoo, Finland. We demonstrate that the proposed optimization solution can achieve considerable increase in profit, reduce renewable energy curtailment and decrease power demand in peak hours, compared to uncontrolled or non-optimized operation.