Skip to content

Instantly share code, notes, and snippets.

@RookieOne
Last active December 30, 2015 23:49
Show Gist options
  • Save RookieOne/7903276 to your computer and use it in GitHub Desktop.
Save RookieOne/7903276 to your computer and use it in GitHub Desktop.
Blurst #1 2013 Calculate Position
class Trading::CalculatePosition
def self.execute(user, contender, options={})
position = user.positions.where(contender_id: contender.id).first
contracts = user.contracts
.select{|c| c.contender_id == contender.id}
.sort{|x,y| x.created_at <=> y.created_at }
if contracts.empty?
position.destroy if position
return
end
position = user.positions.build(contender: contender) if position.nil?
calculate(user, position, contracts)
position.save
end
def self.calculate(user, position, contracts)
net_shares = 0
net_value = 0
position.shares = 0
contracts.each do |contract|
if contract.seller == user
if position.short?
position.shares -= contract.shares
net_shares -= contract.shares
net_value -= contract.value
else
position.shares -= contract.shares
if position.short? # so went from long to short
net_shares = position.shares
net_value = contract.price * position.shares
end
end
else
if position.long?
position.shares += contract.shares
net_shares += contract.shares
net_value += contract.value
else
position.shares += contract.shares
if position.long? # so went from short to long
net_shares = position.shares
net_value = contract.price * position.shares
end
end
end
end
position.average_price = (net_shares == 0) ? 0 : (net_value / net_shares).round(2)
position.save
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment