Moving towards clean and sustainable transportation system, electrification of railway systems along with the use of electric vehicles (EVs) are of great interest. For economic operation of such systems, the peer-to-peer (P2P) energy trading policy became more applicable. Therefore, this paper proposes a double-layer individual-based optimization algorithm for P2P based optimal energy management (EM) of a smart distribution network incorporating flexible smart railway substation taking into consideration multiple energy sources of the traction system and the wayside distribution network with the integration of both EVs and energy hubs (EHs). For efficient operation of the railway substation, captured regenerative braking energy (RBE) are considered. In addition, photovoltaic (PV) units are used on station’s and platforms’ roof-tops for clean energy generation along with a multistory parking garage of electric vehicles (EVs). The wayside distribution network of district distribution area with flexible loads also contains several energy sources including distributed generation and multiple EHs. Optimal energy management is carried out including optimal demand side management of flexible loads and EHs. The optimization study takes into consideration several operational uncertainties arising from several components of the system. The simulation results show the feasibility of applying the proposed EM algorithm with an improvement of the energy economics of the system. The results show a reduction of 6.5 % in energy cost of the distribution network loads, 48 % in net energy cost of EHs, 70.8 % in net energy cost of EVs, and 59.1 % in the cost of energy bought by the traction substation.