Fluctuation relation for quantum heat engines and refrigerators