CreateOpenPosition creates an open position
(pos *TraderPosition)
| 500 | |
| 501 | // CreateOpenPosition creates an open position |
| 502 | func (s *PositionStore) CreateOpenPosition(pos *TraderPosition) error { |
| 503 | if pos.ExchangePositionID != "" && pos.ExchangeID != "" { |
| 504 | existingPos, err := s.GetOpenPositionByExchangePositionID(pos.ExchangeID, pos.ExchangePositionID) |
| 505 | if err != nil { |
| 506 | return err |
| 507 | } |
| 508 | if existingPos != nil { |
| 509 | return s.UpdatePositionQuantityAndPrice(existingPos.ID, pos.Quantity, pos.EntryPrice, pos.Fee) |
| 510 | } |
| 511 | exists, err := s.ExistsWithExchangePositionID(pos.ExchangeID, pos.ExchangePositionID) |
| 512 | if err != nil { |
| 513 | return err |
| 514 | } |
| 515 | if exists { |
| 516 | return nil |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | if pos.Status == "" { |
| 521 | pos.Status = "OPEN" |
| 522 | } |
| 523 | if pos.Source == "" { |
| 524 | pos.Source = "system" |
| 525 | } |
| 526 | if pos.EntryQuantity == 0 { |
| 527 | pos.EntryQuantity = pos.Quantity |
| 528 | } |
| 529 | |
| 530 | err := s.db.Create(pos).Error |
| 531 | if err != nil { |
| 532 | if strings.Contains(err.Error(), "UNIQUE constraint failed") { |
| 533 | existingPos, findErr := s.GetOpenPositionByExchangePositionID(pos.ExchangeID, pos.ExchangePositionID) |
| 534 | if findErr != nil { |
| 535 | return findErr |
| 536 | } |
| 537 | if existingPos != nil { |
| 538 | return s.UpdatePositionQuantityAndPrice(existingPos.ID, pos.Quantity, pos.EntryPrice, pos.Fee) |
| 539 | } |
| 540 | return nil |
| 541 | } |
| 542 | return fmt.Errorf("failed to create open position: %w", err) |
| 543 | } |
| 544 | |
| 545 | return nil |
| 546 | } |
| 547 | |
| 548 | // ClosePositionWithAccurateData closes a position with accurate data from exchange |
| 549 | // exitTimeMs is Unix milliseconds UTC |
no test coverage detected