// getContract returns the Contract object, creating a database record if needed. func (a *AccountFeed) getContract(criteria core.Contract) (core.Contract, error) { existing := new(core.Contract) err := meddler.QueryRow(a.tx, existing, "SELECT * FROM contract WHERE ib_contract_id = $1 AND "+ "iso_4217_code = $2 AND symbol_id = $3 AND local_symbol_id = $4 AND "+ "security_type_id = $5 AND primary_exchange_id = $6", criteria.IbContractId, criteria.Iso4217Code, criteria.SymbolId, criteria.LocalSymbolId, criteria.SecurityTypeId, criteria.PrimaryExchangeId) if err != nil && err != sql.ErrNoRows { return *existing, err } if existing.Id != 0 { return *existing, nil } criteria.Created = a.created err = meddler.Insert(a.tx, "contract", &criteria) return criteria, err }
func (a *AccountFeed) position() error { for key, value := range a.pam.Portfolio() { snapshot, err := a.getSnapshot(key.AccountCode) if err != nil { return err } newPosition := new(core.AccountPosition) newPosition.AccountSnapshotId = snapshot.Id c := new(core.Contract) c.IbContractId = value.Contract.ContractId iso := new(core.Iso4217) err = meddler.QueryRow(a.tx, iso, "SELECT * FROM iso_4217 WHERE alphabetic_code = $1", value.Contract.Currency) if err != nil { return err } c.Iso4217Code = iso.Iso4217Code symbol, err := a.getSymbol(value.Contract.Symbol) if err != nil { return err } c.SymbolId = symbol.Id localSymbol, err := a.getSymbol(value.Contract.LocalSymbol) if err != nil { return err } c.LocalSymbolId = localSymbol.Id secType, err := a.getSecurityType(value.Contract.SecurityType) if err != nil { return err } c.SecurityTypeId = secType.Id exg, err := a.getExchange(value.Contract.PrimaryExchange) if err != nil { return err } c.PrimaryExchangeId = exg.Id con, err := a.getContract(*c) if err != nil { return err } newPosition.ContractId = con.Id newPosition.Position = value.Position newPosition.MarketPrice = value.MarketPrice newPosition.MarketValue = value.MarketValue newPosition.AverageCost = value.AverageCost newPosition.UnrealizedPNL = value.UnrealizedPNL newPosition.RealizedPNL = value.RealizedPNL knownPositions := a.positions[snapshot] knownPositions = append(knownPositions, *newPosition) a.positions[snapshot] = knownPositions } return nil }