Any code to move up Z axis after finishing the printing?
You can use:

G91
G1 Z10


G91 make the printer use ralative positioning, while G1 Z10 would move the gantry up of 10mm, reagrdless of its actual position.

In order to understand what's going on, you could experiment with the position of those lines in the script.

The safest bet it to insert them at the very top, but you could insert them straight after the homing of the X axis to understand if the drop you are seeing is caused by the homing command itself or by the ´M84´ one.

My guess is that the drop is actually caused by the latter.  M84 doesn't really "disable motors", rather it stops using energy to keep them still (i.e.: it stops the idle hold).  What I believe is happening in your case is that when you stop the idle hold, the weight and mechanical play of the X gantry causes it to move slightly (a bit like when you relax your body on the sofa and you "sink" in it a bit more).