0

I'm creating a database to store all trades made in a portfolio, which are segregated by individual "strategies".

As shown in the code below, what are the drawbacks of appending new contracts/trades to the ListFields as a way of adding EmbeddedDocuments to the database?

from mongoengine import *
import datetime

class Trade(EmbeddedDocument):
    tradeDate = DateTimeField(default=datetime.datetime.now(), required=True)
    position = IntField(required=True)

class Contract(EmbeddedDocument):
    contractID = IntField(required=True, unique=True)
    trades = ListField(EmbeddedDocumentField(Trade))

    def addTrade(self, trade: Trade):
        self.trades.append(trade)

class Strategy(Document):
    strategyType = StringField()
    contracts = ListField(EmbeddedDocumentField(Contract))

    def addContract(self, contract: Contract):
        self.contracts.append(contract)

Strategy creation example:

contract = Contract(contractID=1234)
contract.addTrade(Trade(position=1))
strat = Strategy(strategyType="Strategy One")
strat.addContract(contract)
strat.save()

Each strategy will have under 10 contracts 99% of the time, but many times there will be additional contracts added after the strategy's creation to the "contracts" ListField.

Each time a trade is made on each specific contract the position and date will be recorded in a new trade document added to the "trades" ListField.

Duff
  • 410
  • 2
  • 13

1 Answers1

1

There would be one huge drawback: insert time. It seems to be natural that insert element do list is O(1) time, but it is not in MongoDB. Appending element to list is treated as inserting element to any place at list, so it takes O(n) time (n is 'Contracts' list length). When you will have bigger database this would be painful.

What to do? Try to keep each contract-trade as plain mongo document with index on contractID. Insert time would be O(1), as well as read time would be similar to List approach.

scezar
  • 46
  • 1