ddsaif / Roshan_tasks

0 stars 0 forks source link

Yesterday's Code review #1

Open ddsaif opened 2 weeks ago

ddsaif commented 2 weeks ago
const Ladder = require('../model/addSubModel');

const withdrawOrAddFundsToLadder = async (req, res) => {
    try {
        const { lad_id, user_id, new_stocks_to_buy, new_cash_needed, new_order_size, new_step_size } = req.body;

        if (!lad_id || !user_id) {
            return res.status(400).json({ message: "lad_id and user_id are required." });
        }

        const ladder = await Ladder.findOne({ where: { lad_id, user_id } });

        if (!ladder) {
            return res.status(404).json({ message: "Ladder not found for the specified user." });
        }

        ladder.stocks_to_buy += new_stocks_to_buy;
        ladder.cash_allocated += new_cash_needed; 
        ladder.order_size = new_order_size;
        ladder.step_size = new_step_size;

        await ladder.save();

        res.status(200).json({ message: "Ladder updated successfully.", ladder });
    } catch (error) {
        console.error("Error updating ladder:", error);
        res.status(500).json({ message: "Error updating ladder", error });
    }
};

module.exports = {
    withdrawOrAddFundsToLadder,
};

The above Code, function withdrawOrAddFundsToLadder here in ladder there is no field naming stocks_to_buy and the stocks_to_buy should not be adding in the ladder table as well as ladder.cash_allocated += new_cash_needed; cash_allocated is not cash_needed, cash Needed is a different field in the table change it. And also take new_cash_allocated from the request body as well and add it to the ladder.cash_allocated. By adding I mean replacing and you needed not to use incrementing i.e +=. All these values should be replaced with that lad_id in the ladder table. The stocks_to_buy has a different use I will explain after these issue is solved successfully

ddsaif commented 2 weeks ago

we will use new_stocks_to_buy later on. Do these task first then we will use the new_stocks_to_buy in the function

roshanK1998 commented 2 weeks ago

`const Ladder = require('../model/addSubModel');

const withdrawOrAddFundsToLadder = async (req, res) => { try { const { lad_id, new_cash_allocated, new_cash_needed, new_order_size, new_step_size } = req.body; const lad_user_id = req.params.id;

    if (!lad_id || !lad_user_id) {
        return res.status(400).json({ message: "lad_id and lad_user_id are required." });
    }

    const ladder = await Ladder.findOne({ where: { lad_id, lad_user_id } });

    if (!ladder) {
        return res.status(404).json({ message: "Ladder not found for the specified user." });
    }

    ladder.lad_cash_allocated = new_cash_allocated;   
    ladder.lad_cash_needed = new_cash_needed;         
    ladder.lad_order_size = new_order_size;           
    ladder.lad_step_size = new_step_size;             

    await ladder.save();

    res.status(200).json({ message: "Ladder updated successfully.", ladder });
} catch (error) {
    console.error("Error updating ladder:", error);
    res.status(500).json({ message: "Error updating ladder", error });
}

};

module.exports = { withdrawOrAddFundsToLadder, }; `

ddsaif commented 2 weeks ago

Run these code on your machine with the ladder table that i have send you in csv check weather it runs or not

roshanK1998 commented 2 weeks ago

okay

roshanK1998 commented 2 weeks ago

Check the code. I have made some changes in it.

ddsaif commented 2 weeks ago

The code looks good, but have you checked and tested on your machine. If not test it then we will move further.

roshanK1998 commented 2 weeks ago

Actually, I tried to run this code but, I am getting this in response { "message": "lad_id and lad_user_id are required." }

roshanK1998 commented 2 weeks ago

So, if you can check it once in your machine. You might not get this error

roshanK1998 commented 2 weeks ago

I am using the same response body as you have shared. But why it is asking of the lad_id { "lad_id": 1203, "new_stocks_to_buy": 14, "new_cash_needed": 123.23, "new_order_size": 12, "new_step_size":213 }

ddsaif commented 2 weeks ago

check the table and use any lad_id and lad_user_id Note: both of the fields should correspond to each other

Actually, I tried to run this code but, I am getting this in response { "message": "lad_id and lad_user_id are required." }

roshanK1998 commented 2 weeks ago

check the table and use any lad_id and lad_user_id Note: both of the fields should correspond to each other

Actually, I tried to run this code but, I am getting this in response { "message": "lad_id and lad_user_id are required." }

okay, I will check it once. If you do have some time you also try to check my code once

ddsaif commented 2 weeks ago

I can only review and read your code, only you have to test your code itself. Once you have successfully tested. Can I will test on my machine

roshanK1998 commented 2 weeks ago

This is the error, I am receiving now.

"message": "Error updating ladder",
"error": {
    "name": "SequelizeDatabaseError",
    "parent": {
        "code": "ER_BAD_FIELD_ERROR",
        "errno": 1054,
        "sqlState": "42S22",
        "sqlMessage": "Unknown column 'cash_allocated' in 'field list'",
        "sql": "SELECT `lad_id`, `cash_allocated`, `stocks_to_buy`, `order_size`, `step_size` FROM `ladder` AS `Ladder` WHERE `Ladder`.`lad_id` = 1203 AND `Ladder`.`lad_user_id` = '721';"
    },
    "original": {
        "code": "ER_BAD_FIELD_ERROR",
        "errno": 1054,
        "sqlState": "42S22",
        "sqlMessage": "Unknown column 'cash_allocated' in 'field list'",
        "sql": "SELECT `lad_id`, `cash_allocated`, `stocks_to_buy`, `order_size`, `step_size` FROM `ladder` AS `Ladder` WHERE `Ladder`.`lad_id` = 1203 AND `Ladder`.`lad_user_id` = '721';"
    },
    "sql": "SELECT `lad_id`, `cash_allocated`, `stocks_to_buy`, `order_size`, `step_size` FROM `ladder` AS `Ladder` WHERE `Ladder`.`lad_id` = 1203 AND `Ladder`.`lad_user_id` = '721';",
    "parameters": {}
}

}

roshanK1998 commented 2 weeks ago

I made some of the changes again in my code and, I think the issue is resolve. But the response which i am receiving is this { "message": "Ladder not found for the specified user." }

roshanK1998 commented 2 weeks ago

Please check this response and do let me know weather it is correct or not

{ "message": "Ladder updated successfully.", "ladder": { "lad_id": 1283, "lad_cash_allocated": 995000, "lad_step_size": "112.79" } }

ddsaif commented 2 weeks ago

I made some of the changes again in my code and, I think the issue is resolve. But the response which i am receiving is this { "message": "Ladder not found for the specified user." }

use lad_id: 1283 and lad_user_id: 721

roshanK1998 commented 2 weeks ago

I made some of the changes again in my code and, I think the issue is resolve. But the response which i am receiving is this { "message": "Ladder not found for the specified user." }

use lad_id: 1283 and lad_user_id: 721

Please check this response and do let me know weather it is correct or not

{ "message": "Ladder updated successfully.", "ladder": { "lad_id": 1283, "lad_cash_allocated": 995000, "lad_step_size": "112.79" } }

ddsaif commented 2 weeks ago

ok

ddsaif commented 2 weeks ago

Share your table as a csv on whatsapp

roshanK1998 commented 2 weeks ago

Shared

ddsaif commented 2 weeks ago

Now we have the new_stocks_to_buy, so check if it is negative or positive and not 0. if negative create a sell order in the order table or if positive then create a buy order in the order table here is example how to create a sell or buy order.

 let orderData = {
      order_type: "SELL",
      order_status: "OPEN",
      order_user_id: user_id,
      order_position_id: merge_ladder_data.lad_position_id, // position_id of that ladder
      order_automated: true,
      order_open_price: currentPrice + merge_ladder_data.lad_step_size, // here steps size is new_step_size and currentPrice is fetched as below.
      order_trading_mode: merge_ladder_data.lad_trading_mode, // ladder trading mode
      order_units: -merge_ladder_data.lad_default_buy_sell_quantity, // new_order_size
      order_closed_units: 0,
      order_cash_gain: 0,
      order_realized_profit: 0,
      order_exchange: merge_ladder_data.lad_exchange, // ladder exchange
      order_ticker_id: merge_ladder_data.lad_ticker_id, // ladder ticker id
      order_stock_name: merge_ladder_data.lad_ticker, // ladder ticker 
      order_follow_up: "'Buy&Sell'",
    };
    await dd_orders.create(orderData);

    orderData = {
      order_type: "BUY",
      order_status: "OPEN",
      order_user_id: user_id,
      order_position_id: merge_ladder_data.lad_position_id,
      order_automated: true,
      order_open_price: currentPrice - merge_ladder_data.lad_step_size,
      order_trading_mode: merge_ladder_data.lad_trading_mode,
      order_units: merge_ladder_data.lad_default_buy_sell_quantity,
      order_closed_units: 0,
      order_cash_gain: 0,
      order_realized_profit: 0,
      order_exchange: merge_ladder_data.lad_exchange,
      order_ticker_id: merge_ladder_data.lad_ticker_id,
      order_stock_name: merge_ladder_data.lad_ticker,
      order_follow_up: "'Buy&Sell'",
    };
    await dd_orders.create(orderData);
ddsaif commented 2 weeks ago

These is how we find the current Price of a stock

const selectedTickerDetails = await dd_selected_stocks.findOne({
      where: {
        ss_ticker_id: merge_ladder_data.lad_ticker_id, //ladder ticker id
        ss_reg_id: user_id,
      },
      raw: true,
    });

    const currentPrice = convertToCurrency(
      selectedTickerDetails.ss_simulated_price
    );
roshanK1998 commented 2 weeks ago

In the same function, I need to do this changes or I have to create another function for this

ddsaif commented 2 weeks ago

no in the same function itself

roshanK1998 commented 2 weeks ago

okay

roshanK1998 commented 2 weeks ago

The response body, table every thing will be same ?

ddsaif commented 2 weeks ago

don't care about response body and use the order table for creating order.

roshanK1998 commented 2 weeks ago

I have shared the cv with you can you please check is that correct orders table

roshanK1998 commented 2 weeks ago

Now we have the new_stocks_to_buy, so check if it is negative or positive and not 0. if negative create a sell order in the order table or if positive then create a buy order in the order table here is example how to create a sell or buy order.

 let orderData = {
      order_type: "SELL",
      order_status: "OPEN",
      order_user_id: user_id,
      order_position_id: merge_ladder_data.lad_position_id, // position_id of that ladder
      order_automated: true,
      order_open_price: currentPrice + merge_ladder_data.lad_step_size, // here steps size is new_step_size and currentPrice is fetched as below.
      order_trading_mode: merge_ladder_data.lad_trading_mode, // ladder trading mode
      order_units: -merge_ladder_data.lad_default_buy_sell_quantity, // new_order_size
      order_closed_units: 0,
      order_cash_gain: 0,
      order_realized_profit: 0,
      order_exchange: merge_ladder_data.lad_exchange, // ladder exchange
      order_ticker_id: merge_ladder_data.lad_ticker_id, // ladder ticker id
      order_stock_name: merge_ladder_data.lad_ticker, // ladder ticker 
      order_follow_up: "'Buy&Sell'",
    };
    await dd_orders.create(orderData);

    orderData = {
      order_type: "BUY",
      order_status: "OPEN",
      order_user_id: user_id,
      order_position_id: merge_ladder_data.lad_position_id,
      order_automated: true,
      order_open_price: currentPrice - merge_ladder_data.lad_step_size,
      order_trading_mode: merge_ladder_data.lad_trading_mode,
      order_units: merge_ladder_data.lad_default_buy_sell_quantity,
      order_closed_units: 0,
      order_cash_gain: 0,
      order_realized_profit: 0,
      order_exchange: merge_ladder_data.lad_exchange,
      order_ticker_id: merge_ladder_data.lad_ticker_id,
      order_stock_name: merge_ladder_data.lad_ticker,
      order_follow_up: "'Buy&Sell'",
    };
    await dd_orders.create(orderData);

Can you please guide I am getting notNull Violation the response is like this

{ "message": "Error updating ladder", "error": { "name": "SequelizeValidationError", "errors": [ { "message": "Order.order_position_id cannot be null", "type": "notNull Violation", "path": "order_position_id", "value": null, "origin": "CORE", "instance": { "id": null, "order_type": "BUY", "order_status": "OPEN", "order_user_id": "721", "order_automated": true, "order_open_price": null, "order_units": 12, "order_closed_units": 0, "order_cash_gain": 0, "order_realized_profit": 0, "order_follow_up": "'Buy&Sell'", "updatedAt": "2024-11-05T10:25:06.172Z", "createdAt": "2024-11-05T10:25:06.172Z" }, "validatorKey": "is_null", "validatorName": null, "validatorArgs": [] }, { "message": "Order.order_trading_mode cannot be null", "type": "notNull Violation", "path": "order_trading_mode", "value": null, "origin": "CORE", "instance": { "id": null, "order_type": "BUY", "order_status": "OPEN", "order_user_id": "721", "order_automated": true, "order_open_price": null, "order_units": 12, "order_closed_units": 0, "order_cash_gain": 0, "order_realized_profit": 0, "order_follow_up": "'Buy&Sell'", "updatedAt": "2024-11-05T10:25:06.172Z", "createdAt": "2024-11-05T10:25:06.172Z" }, "validatorKey": "is_null", "validatorName": null, "validatorArgs": [] }, { "message": "Order.order_exchange cannot be null", "type": "notNull Violation", "path": "order_exchange", "value": null, "origin": "CORE", "instance": { "id": null, "order_type": "BUY", "order_status": "OPEN", "order_user_id": "721", "order_automated": true, "order_open_price": null, "order_units": 12, "order_closed_units": 0, "order_cash_gain": 0, "order_realized_profit": 0, "order_follow_up": "'Buy&Sell'", "updatedAt": "2024-11-05T10:25:06.172Z", "createdAt": "2024-11-05T10:25:06.172Z" }, "validatorKey": "is_null", "validatorName": null, "validatorArgs": [] }, { "message": "Order.order_ticker_id cannot be null", "type": "notNull Violation", "path": "order_ticker_id", "value": null, "origin": "CORE", "instance": { "id": null, "order_type": "BUY", "order_status": "OPEN", "order_user_id": "721", "order_automated": true, "order_open_price": null, "order_units": 12, "order_closed_units": 0, "order_cash_gain": 0, "order_realized_profit": 0, "order_follow_up": "'Buy&Sell'", "updatedAt": "2024-11-05T10:25:06.172Z", "createdAt": "2024-11-05T10:25:06.172Z" }, "validatorKey": "is_null", "validatorName": null, "validatorArgs": [] }, { "message": "Order.order_stock_name cannot be null", "type": "notNull Violation", "path": "order_stock_name", "value": null, "origin": "CORE", "instance": { "id": null, "order_type": "BUY", "order_status": "OPEN", "order_user_id": "721", "order_automated": true, "order_open_price": null, "order_units": 12, "order_closed_units": 0, "order_cash_gain": 0, "order_realized_profit": 0, "order_follow_up": "'Buy&Sell'", "updatedAt": "2024-11-05T10:25:06.172Z", "createdAt": "2024-11-05T10:25:06.172Z" }, "validatorKey": "is_null", "validatorName": null, "validatorArgs": [] } ] } }

ddsaif commented 2 weeks ago

order_position_id should not be null please check and enter ladder position id at the order_position_id

roshanK1998 commented 2 weeks ago

"Ladder position ID cannot be null." this is i am getting now

ddsaif commented 2 weeks ago

you are giving it null, get the position id of the ladder from the ladder itself

ddsaif commented 2 weeks ago

let me review your code. Push your code in the file

roshanK1998 commented 2 weeks ago

Okay

roshanK1998 commented 2 weeks ago

Please check the code

ddsaif commented 2 weeks ago

I have updated code and added a console.log statement run it and send the what prints on the terminal

roshanK1998 commented 2 weeks ago

okay..I will do it

roshanK1998 commented 2 weeks ago

This is what I am getting in the terminal

ladder details here ---- Ladder { dataValues: { lad_id: 1283, lad_cash_allocated: 995000, lad_step_size: '112.79' }, _previousDataValues: { lad_id: 1283, lad_cash_allocated: 995000, lad_step_size: '112.79' }, uniqno: 1, _changed: Set(0) {}, _options: { isNewRecord: false, _schema: null, _schemaDelimiter: '', raw: true, attributes: [ 'lad_id', 'lad_cash_allocated', 'lad_step_size' ] }, isNewRecord: false }

ddsaif commented 2 weeks ago

show these file addSubModel

roshanK1998 commented 2 weeks ago

I have created another model for this changes, I do have 2 models

This is orderModel const { Model, DataTypes } = require('sequelize'); const sequelize = require('../config/database');

class Order extends Model {}

Order.init({ order_type: { type: DataTypes.STRING, allowNull: false, }, order_status: { type: DataTypes.STRING, allowNull: false, }, order_user_id: { type: DataTypes.INTEGER, allowNull: false, }, order_position_id: { type: DataTypes.INTEGER, allowNull: true, }, order_automated: { type: DataTypes.BOOLEAN, defaultValue: false, }, order_open_price: { type: DataTypes.FLOAT, allowNull: false, }, order_trading_mode: { type: DataTypes.STRING, allowNull: false, }, order_units: { type: DataTypes.FLOAT, allowNull: false, }, order_closed_units: { type: DataTypes.FLOAT, defaultValue: 0, }, order_cash_gain: { type: DataTypes.FLOAT, defaultValue: 0, }, order_realized_profit: { type: DataTypes.FLOAT, defaultValue: 0, }, order_exchange: { type: DataTypes.STRING, allowNull: false, }, order_ticker_id: { type: DataTypes.INTEGER, allowNull: false, }, order_stock_name: { type: DataTypes.STRING, allowNull: false, }, order_follow_up: { type: DataTypes.STRING, allowNull: true, }, }, { sequelize, modelName: 'Order', tableName: 'ordersnewtable_1', timestamps: true, } );

module.exports = Order;

This is addSubModel

const { DataTypes } = require('sequelize'); const sequelize = require('../config/database');

const Ladder = sequelize.define('Ladder', { lad_id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, lad_cash_allocated: { type: DataTypes.DECIMAL, allowNull: false }, // lad_stocks_to_buy: { // type: DataTypes.INTEGER, // allowNull: false // },

// lad_order_size: {
//     type: DataTypes.INTEGER,
//     allowNull: false
// },
lad_step_size: {
    type: DataTypes.INTEGER,
    allowNull: false
},

}, { tableName: 'ladder', timestamps: false });

module.exports = Ladder;

ddsaif commented 2 weeks ago

These model is wrong. I have added ladderModels in the repository check.

I have created another model for this changes, I do have 2 models

This is orderModel const { Model, DataTypes } = require('sequelize'); const sequelize = require('../config/database');

class Order extends Model {}

Order.init({ order_type: { type: DataTypes.STRING, allowNull: false, }, order_status: { type: DataTypes.STRING, allowNull: false, }, order_user_id: { type: DataTypes.INTEGER, allowNull: false, }, order_position_id: { type: DataTypes.INTEGER, allowNull: true, }, order_automated: { type: DataTypes.BOOLEAN, defaultValue: false, }, order_open_price: { type: DataTypes.FLOAT, allowNull: false, }, order_trading_mode: { type: DataTypes.STRING, allowNull: false, }, order_units: { type: DataTypes.FLOAT, allowNull: false, }, order_closed_units: { type: DataTypes.FLOAT, defaultValue: 0, }, order_cash_gain: { type: DataTypes.FLOAT, defaultValue: 0, }, order_realized_profit: { type: DataTypes.FLOAT, defaultValue: 0, }, order_exchange: { type: DataTypes.STRING, allowNull: false, }, order_ticker_id: { type: DataTypes.INTEGER, allowNull: false, }, order_stock_name: { type: DataTypes.STRING, allowNull: false, }, order_follow_up: { type: DataTypes.STRING, allowNull: true, }, }, { sequelize, modelName: 'Order', tableName: 'ordersnewtable_1', timestamps: true, } );

module.exports = Order;

This is addSubModel

const { DataTypes } = require('sequelize'); const sequelize = require('../config/database');

const Ladder = sequelize.define('Ladder', { lad_id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, lad_cash_allocated: { type: DataTypes.DECIMAL, allowNull: false }, // lad_stocks_to_buy: { // type: DataTypes.INTEGER, // allowNull: false // },

// lad_order_size: {
//     type: DataTypes.INTEGER,
//     allowNull: false
// },
lad_step_size: {
    type: DataTypes.INTEGER,
    allowNull: false
},

}, { tableName: 'ladder', timestamps: false });

module.exports = Ladder;

roshanK1998 commented 2 weeks ago

Okay

ddsaif commented 2 weeks ago

you have to update in ladder table the following values new_cash_needed, new_order_size, new_step_size await ladder.save(); line 77. Hence these line is wrong use update

roshanK1998 commented 2 weeks ago

Okay..I will try to do it. Its getting little difficult for me. Can you please fix it

ddsaif commented 2 weeks ago

Okay..I will try to do it. Its getting little difficult for me. Can you please fix it

try to do it. If you have doubt ask me. Ask me specifically where you are having difficulty

roshanK1998 commented 2 weeks ago

Okay..

roshanK1998 commented 2 weeks ago

you have to update in ladder table the following values new_cash_needed, new_order_size, new_step_size await ladder.save(); line 77. Hence these line is wrong use update

Do, I need to add this fields in the ladder table

ddsaif commented 2 weeks ago

in ladder table there are already these fields, all you need to replace the values from these fields.

roshanK1998 commented 2 weeks ago

okay