Credit: Nero 3D (

Handy G-Code to retract filament at end of the print enable you change nozzle after print end.  G Code Basically retract filament after print is finished.

[gcode_macro PRINT_END]
#   Use PRINT_END for the slicer ending script - please customise for your slicer of choice

    M400                           ; wait for buffer to clear
    G92 E0                         ; zero the extruder
    G1 E-5 F3600                ; retract filament
    G91                            ; relative positioning
    G0 Z1.00 X20.0 Y20.0 F20000    ; move nozzle to remove stringing
    M107                           ; turn off fan
    G1 Z2 F3000                    ; move nozzle up 2mm
    G90                            ; absolute positioning
    G0  X125 Y250 F3600            ; park nozzle at rear

Another Option (E3D)

Full Guide:

Add (G Code to retract Filament) 

G1 E-18 F800 ;retract filament from meltzone