To set your troops to defend. click on your Castle, directly above resource production and below happiness it says Hide troops in sanctuary, Order troops to defend city click on the bubble between the two to set to defend. to set back to hide, click on the bubble to the left of Hide troops in sanctuary.
HOWEVER _ Do not do this unless you are sure you will win the battle ( you should get a report that depending on what level watch tower you have, will tell you of any impending attack and information about those troops ) as you may end up losing not only any resources not protected by your stores and all your gold, but all your troops as well. If your troops are not set to defend all you will lose is any unspent gold and if you are unlucky the resourses you have over the protection of your stores. Again a good defence would be to have as large a stores as you can and research shrinking powder in the alchemy lab as this adds 10% to your storage for every upgrade. If attacked by a superior force, you can protect your gold and surplus resources by hiding it in the wilds with troops, or make a trade at the market that you know will not be accepted and then cancel later. The best way to actually defend a wall is with a combination of wall defences, 10000 wall mounted cross bows would deter all but the most determined attack if you can build them. Caltrops and Spikes will also help. trebuchets do a lot of damage but have to be rebuilt after every attack. Traps can help but there are ways around traps. ie sending in one militia and one supply troop is meant to take out much more than 2 traps.