Thanks for your reply. Using the GUI parameters as a template gives the same result.
Now I realize that if I export the file with Mosaic in BEAM-DIMAP format it handles missing values fine (NaN stays NaN), but if I save it to netCDF4-CF it doesn't (NaN becomes 0). This is why the GUI was working, because it outputs by default to BEAM-DIMAP.
Unfortunately I cannot work with BEAM-DIMAP in my application (IDL). I tried converting the BEAM-DIMAP files to netCDF4-CF with gpt.sh Write, but it reports all NaNs as 0. again