The story
Exocentric compound of hat (“head covering”, noun) + trick (“element of a magician’s or variety entertainer’s act; entertaining and difficult physical action”, noun). Sense 2 (“achievement of a bowler taking three wickets in three consecutive balls”)—the original sporting sense—refers to the commemorative hat formerly given as a prize to the bowler by his club.
Etymology from Wiktionary, CC BY-SA 4.0.