This paper presents an optimization model for Home Energy Management Systems from an aggregator's standpoint. The aggregator manages a set of resources such as PV, elec-trochemical batteries and Thermal Energy Storage by means of Electric Water Heaters. The resources are managed in order to participate in the day-ahead energy market, considering also local flexibility needs. The resulting model is a mixed-integer linear programming problem in which the aim is to minimize day-ahead operation costs for the aggregator while complying with DSO flexibility constraints in the form of maximum allowed net power exchange and ramping limits. Three sources of uncertainty are considered: day-ahead energy prices, PV production and load. Kernel Density Estimator and a backward reduction algorithm are used to create price scenarios and Robust Optimization is used to model PV and load uncertainties. The obtained results show the changes in the operation of the aggregator when grid flexibilities are considered and the impacts on the operation costs. In addition, a proposal for bidding in local flexibility markets is shown.