In the frame of a research project conducted at the Smart Living Lab (SLL), a research center dedicated to the building of the future, this paper presents an algorithm that optimizes the coupling of local renewable energy production systems with energy storage devices and the different consumers both at the level of the building and of its peripherals. The main goal is to improve the energy self-sufficiency of a building by combining three aspects in the same time. The optimization criteria are the renewable energy based independence and the ecological (greenhouses gases emissions) and economical (costs) aspects. The underlying approach to perform the global optimization is first presented, explaining how the algorithm combines and optimizes these three criteria. For this purpose, it takes into account the current value of the state variables (temperature, etc.) and the forecasts future values. These data represent the input of a genetic optimization algorithm that computes the best use of each element of the production and storage systems to ensure the electrical and thermal energy demand. The choice of genetic algorithm is motivated by the large amount of optimization variables and the non-linearity of the score function. The typical computation time for this kind of optimization is short enough to allow a real time regulation. The composition of the energy production and storage is flexible allowing to integrate many technologies types, thus increasing its portability.