I'm not really sure what you're trying to do, but can't you run a check for stuff in your stash first?
I have a free fights script that pulls up to 3 items from the stash, and puts them back when it's done. It wouldn't be that hard to do.
Instead of using retrieve_item you could do this:
PHP:
if ($item[yellow pixel potion].available_amount() < 1) // I have 0 left. Lets do something about it.
{
int ineed = 10; // need 10 pixels to make the potion
int ihave = $item[yellow pixel].available_amount(); //this is how many I have on hand
refresh_stash();
int stashhas = stash_amount($item[yellow pixel]); // this is how many the clan stash has
ineed = ihave - stashhas; // this will figure out how many I can grab from the stash up to what I need.
take_stash(ineed, $item[yellow pixel]); // take what the stash has
ineed = 10 - $item[yellow pixel].available_amount(); // I needed 10
if ($item[yellow pixel].available_amount() < 10) // if I still don't have the 10 I need, I will buy just what I need to get me there.
{
buy(ineed, $item[yellow pixel]);
}
}
create (1, $item[yellow pixel potion]);
There's probably multiple ways of doing this. This is just the first one I came up with in a pinch. I tested this exact code, and it worked as expected.