*****************UPDATING THE NEW ORDER ROUTE**************

 WHENEVER A NEW ORDER IS REQUESTED ( BUY OR SELL)

- NEW ORDER IS ADDED TO ORDERS (DB)

- WE CALCULATE AVG, NET AND DAY 

THE SCHEMAS ARE UPDATED FOR NET AND DAY AS NUMBERS

  net: Number,
  day: Number,

- WE UPDATE THE HOLDINGS

- UPDATE THE POSITONS

THE ROUTE:

app.post("/newOrder", userVerification, async (req, res) => {
  const userId = req.user._id;
  console.log(userId);
  const { name, qty, price, mode } = req.body;

  try {
    let newOrder = new OrderModel({
      userId,
      name,
      qty,
      price,
      mode,
    });
    await newOrder.save(); NEW ORDER IS SAVED

    //TO CALCULATE AVG,NET AND DAY

    const { data } = await axios.get("https://finnhub.io/api/v1/quote", {
      params: {
        symbol: name,
        token: key,
      },
    });
    const currPrice = data.c;
    const prevClose = data.pc;
    const net = ((currPrice - price) * qty).toFixed(2);
    const day = ((currPrice - prevClose) * qty).toFixed(2);

    const existingHolding = await HoldingModel.findOne({
      userId,
      name,
    });
    const existingPosition = await PositionModel.findOne({ userId, name });
    console.log(existingHolding);
    console.log(existingPosition);

    //CALCULATING AVG
    if (mode === "BUY") {
      //UPDATNG HOLDINGS
      if (existingHolding) {
        const totalQty = existingHolding.qty + qty;
        const totalCost =
          existingHolding.qty * existingHolding.avg + qty * price;
        const newAvg = totalCost / totalQty;
        existingHolding.qty = totalQty; FORMULAE
        existingHolding.price = currPrice;
        existingHolding.avg = newAvg;
        existingHolding.net = ((currPrice - newAvg) * totalQty).toFixed(2);
        existingHolding.day = ((currPrice - prevClose) * totalQty).toFixed(2);

        await existingHolding.save();

        //UPDATING POSITIONS
        if (existingPosition) {
          existingPosition.qty += qty;
          const totalPositionCost =
            existingPosition.avg * existingPosition.qty + qty * price;
          const newPositionAvg =
            totalPositionCost / (existingPosition.qty + qty);
          existingPosition.avg = newPositionAvg;
          existingPosition.price = currPrice;
          existingPosition.net = (
            (currPrice - newPositionAvg) * FORMULAE
            existingPosition.qty
          ).toFixed(2);
          existingPosition.day = (
            (currPrice - prevClose) *
            existingPosition.qty
          ).toFixed(2);
          existingPosition.isLoss = existingPosition.net < 0;
          await existingPosition.save();
        }
      }
WHEN NO HOLDING AND POSITION EXISTS NEW ONE'S ARE DIRECTLY CREATED
else {
        const newHolding = new HoldingModel({
          userId,
          name,
          qty,
          avg: price,
          price: currPrice,
          net,
          day,
        });
        await newHolding.save();
      }
      const newPosition = new PositionModel({
        userId,
        product: "MIs",
        name,
        qty,
        avg: price,
        price: currPrice,
        net,
        day,
        isLoss: net < 0,
      });
      await newPosition.save();
    }
else if (mode === "SELL") {

      //UPDATING HOLDINGS

WHEN NO HOLDING OR THE QUANTITY DEMANDED FOR SELLING IS MORE THAN THE HOLDINGS WE HAVE
      if (!existingHolding || qty > existingHolding.qty) {
        return res
          .status(400)
          .json({ message: "Not enough holdings to sell." });
      }
WHEN DEMANDED QUANTITY AND THE HOLDINGS QUANTITY ARE EQUAL WE JUST DELETE
THE HOLDING
      if (qty === existingHolding.qty) {
        await HoldingModel.deleteOne({ userId, name });
      }

WHEN THE DEMANDED QUANTITY IS LESS THAN THE HOLDING QUANTITY WE HAVE WE
SUBTRACT THE DEMANDED QTY FROM EXISTING QUANTITIES.

else {
        existingHolding.qty -= qty;
if (existingHolding.qty == 0) { WHEN THE QUANTITY OF A STOCK BECOMES '0' AFTER
SELLING THAT STOCK IS DELETED.
          await existingHolding.deleteOne({ userId, name });
        }
        await existingHolding.save();
      }

      //UPDATING POSITIONS
      if (!existingPosition) {
        return res
          .status(400)
          .json({ message: "No position found to update." });
      }

      if (existingPosition) {
        if (existingPosition.qty < qty) {
          return res
            .status(400)
            .json({ message: "Not enough position quantity to sell." });
        }

        if (qty === existingPosition.qty) {
          await PositionModel.deleteOne({ userId, name });
          console.log("Position deleted");
        } else {
          existingPosition.qty -= qty;
          existingPosition.net = (
            (currPrice - existingPosition.avg) *
            existingPosition.qty
          ).toFixed(2);
          existingPosition.day = (
            (currPrice - prevClose) *
            existingPosition.qty
          ).toFixed(2);
          existingPosition.isLoss = existingPosition.net < 0;
          await existingPosition.save();
        }
      } else {
        return res
          .status(400)
          .json({ message: "No existing position to update." });
      }
      console.log("position updated");
    }
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Server error" });
  }
});













Comments

Popular posts from this blog

*********UPDATING THE FRONTEND*********

**************** EXTRACTING DATA FROM API **************