This study introduces a significant advancement in peer-to-peer (P2P) energy trading systems within smart grids, addressing a crucial gap in existing research by incorporating optimal energy storage capacities to accommodate varying energy demands resulting from lifestyle changes. Through a two-level optimization approach, aimed at maximizing self consumption and optimizing energy flow within the grid, we propose a novel energy management strategy. Our contribution lies in the introduction of a new layer of deep learning and rules control, forming a self-energy sharing system for each prosumer. This architecture, termed the smart node, integrates deep learning techniques, to predict and customize energy services through dynamic adjustment of lower and upper bounds of battery capacities. Additionally, we leverage cellular automaton (CA) approaches to establish sustainable consensus among P2P network users, enhancing the adaptability and efficiency of the energy management system. The results show that the proposed algorithm could reduce the energy consumed by the P2P community from the utility by around 20% and maximize the collective self-consumption by around 8% compared to conventional energy trading in microgrids.