How to test if a trade object is null in CBT?

My goal: I have a symbol on which I need to enter position, but I need to check if there is an open position . I tried this:

for( openpos = bo.GetFirstOpenPos(); openpos; openpos = bo.GetNextOpenPos() )
{
    if (NOT openpos)
// and this
    if (IsNull(openpos))

neither worked

I had to do this:

if (openpos)
{}
else
{
    ... // my code here
}

Is there a better solution?

Something is wrong with your code elsewhere because openpos inside loop would ALWAYS be set and outside loop will NEVER be set because the continuation condition inside for( ; openpos /* HERE */; ) causes that openpos is ALWAYS valid inside loop.

for( openpos = bo.GetFirstOpenPos(); openpos; openpos = bo.GetNextOpenPos() )
{
 // openpos inside this loop is ALWAYS valid !
}
//outside loop openpos is NOT set always because that's loop termination condition!

BTW: openpos it an OBJECT, not boolean or number.

Sorry, I posted the wrong code. Here is the correct one:

trade = bo.FindOpenPos(symbol);

Then the question of how to test if the trade object is null.
The code in the OP was actually my workaround when I could not find a way to test it.

As I wrote, this is an OBJECT, not a number or boolean, it does not have a numerical or boolean "value". Therefore you can only use it to test it if is VALID this way:

if( object )
{
  // object valid you can use object
}
else
{
  // object is NOT valid you can NOT use it
}

This is possible because if() understands if object is valid or not, but "validity" has no numerical value that you could compare to.

Thanks, Tomasz. Now it is clear to me that a trade object cannot be compared to a numerical value.

The question becomes, how do we find out if we have an open position with a given symbol? Since we have the bo.FindOpenPos() function, logically we should be able to do that easily, or am I missing something? Thanks.

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.