You don't have to write a script - it's already been written. Go to Omni's "Extras" page ...
http://www.omnigroup.com/products/omnioutliner/extras/
... and download the "Useful Scripts". Among them you'll find "Collapse to Level X". It will collapse or expand to whatever level you set.