/ LiveMode / src / positions / active.jl
active.jl
 1  @doc """ Sets the active position for an asset based on cash and timestamp conditions
 2  
 3  $(TYPEDSIGNATURES)
 4  
 5  Determines the active position (long or short) for an asset based on the cash amounts and timestamps of the long and short positions.
 6  If there is no decisive active side, the last active position remains.
 7  
 8  """
 9  function set_active_position!(
10      ai;
11      cash_long=cash(ai, Long()),
12      cash_short=cash(ai, Short()),
13      ts_long=position(ai, Long()).timestamp[],
14      ts_short=position(ai, Short()).timestamp[],
15      default_date=now(),
16  )::Option{Position}
17      active_side = if iszero(cash_long)
18          if !iszero(cash_short)
19              Short()
20          end
21      elseif iszero(cash_short)
22          Long()
23      elseif something(ts_long, default_date) > something(ts_short, default_date)
24          Long()
25      else
26          Short()
27      end
28      ai.lastpos[] = if !isnothing(active_side)
29          position(ai, active_side)
30      end
31  end