This article explores integrating digital twin technology and blockchain within smart grids to optimize energy trading among prosumers and consumers in smart nanogrids. Our platform employs a multi-objective optimization strategy, including Particle Swarm Optimization (PSO), to delineate energy trading routes between nanogrids, optimizing parameters such as route distance, surplus renewable energy, and energy power loss. Our platform ensures efficient and effective energy trading services by meticulously considering factors such as surplus energy amount, energy price, route distance, and time. The proposed digital twin-based architecture comprises seven layers, each tailored to address specific functionalities and services for energy management within smart nanogrids. At the apex lies the application layer (digital twin services), leveraging the digital twin's capabilities to optimize energy trading, manage surplus energy, and efficiently meet energy demand. This layer facilitates informed decision-making and resource optimization. Integrating a digital twin-driven architecture with a blockchain-based platform tackles challenges inherent in decentralized energy trading. The digital twin offers real-time energy resource monitoring and optimisation, ensuring efficient utilisation and autonomous decision-making. Concurrently, leveraging blockchain technology ensures secure and transparent transactions, fostering trust among participants and facilitating peer-to-peer energy exchange. Task generation, device virtualization, task mapping, scheduling on edge devices, and task assignment layers further streamline task execution and resource utilization, enhancing the efficiency of energy management processes. The predictive optimal energy control layer also orchestrates the entire architecture, enabling predictive and optimized energy control within smart nanogrids. Furthermore, the Security as a Service (SECaaS) layer enhances security and trustworthiness using blockchain technology, incorporating components such as consensus management, real-time distributed ledgers, and identity management. This layer enhances the security and transparency of energy-related transactions and data within the digital twin framework. The results showcase a remarkable 53% reduction in peak load, emphasizing the optimized energy consumption and demand achieved. Furthermore, our platform has significantly increased the utilization of renewable energy resources by 24%, highlighting its contribution to sustainable energy resource management. Rigorous assessment of the prediction and optimization modules reveals their high accuracy and precision, with mean absolute percentage error (MAPE) values of 15.125 and 14.369, respectively. These findings underscore the efficacy and reliability of our digital twin-based approach, surpassing existing solutions and benchmarks.