Microgrids have become an alternative to increase the controlability and resilience of the electrical system due to the local and efficient energy management they provide. Additionally, when the microgrid has a main DC bus it does not require synchronization hence the control scheme is simplified allowing to improve the dynamics of currents and voltages. These DC microgrids are usually controlled using a three-level hierarchical scheme associated to different elements in the microgrid in which the third control level optimizes the operation of the whole microgrid in term of costs and efficiency. In this paper a tertiary control level is proposed for a DC microgrid which optimizes its operation in terms of costs but at the same time takes into account restrictions of the grid connection and battery state of charge. Simulation results with realistic operating conditions show a good performance in terms of dynamic response and steady state operation while an optimize economic operation is achieved.