0% found this document useful (0 votes)
3 views

Project

The document outlines a Real-Time Trading Management System developed using React, which allows traders to monitor and execute trading strategies with real-time stock data and an interactive user interface. Key features include dynamic strategy management, trade execution, and error handling, alongside a dashboard for managing live trading positions. The system utilizes REST APIs for backend communication and incorporates various functionalities such as fetching current positions, squaring off trades, and visualizing data through charts.

Uploaded by

Zaid Iqbal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Project

The document outlines a Real-Time Trading Management System developed using React, which allows traders to monitor and execute trading strategies with real-time stock data and an interactive user interface. Key features include dynamic strategy management, trade execution, and error handling, alongside a dashboard for managing live trading positions. The system utilizes REST APIs for backend communication and incorporates various functionalities such as fetching current positions, squaring off trades, and visualizing data through charts.

Uploaded by

Zaid Iqbal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Qn:Project Summary

Ans: Project Summary: Real-Time Trading Management System

This project is a comprehensive Real-Time Trading Management System built using React and supporting
APIs. The system provides traders with the tools to monitor, manage, and execute trading strategies
dynamically. Its core functionalities revolve around fetching real-time stock market data, managing
strategies, executing trades, and providing an intuitive interface for decision-making. Here's an overview
of the key features and components:

Key Features:

Real-Time Stock Data Fetching:

Integrated APIs to fetch and display the latest stock market data for indices like BankNifty and Nifty.

Data updates every 3 seconds to ensure the most accurate and up-to-date information for trading
decisions.

Trading Strategy Management:

Users can create and manage trading strategies, which include details such as stop-loss, re-entry
conditions, quantity, and more.

Strategies are fetched dynamically based on user IDs to ensure personalized strategy handling.

Dynamic Straddle Pricing:

The application calculates and displays ATM Strike Prices and associated Straddle Prices.

Provides calculated values for optimal trade execution, such as OTM gaps and current percentages.

Trade Execution:

A highly interactive trade execution feature allows users to execute trades directly from the platform.

Includes validation mechanisms for confirming or modifying trade actions based on calculated values.

User Inputs and Adjustments:

Supports customizable inputs like quantity, stop loss, and re-entry percentages for both Call Options
(CE) and Put Options (PE).

Real-time calculations assist in aligning user inputs with market trends.

Execution Logs and Feedback:


Tracks and logs all executed trades for future reference and analytics.

Provides immediate feedback on trade execution status.

Interactive UI/UX:

A clean and intuitive interface with data tables, input fields, dropdowns, and buttons for seamless
navigation and user experience.

Includes a loading indicator to signal when background processes, such as data fetching or trade
execution, are ongoing.

Technical Stack:

Frontend: React.js (functional components, hooks like useState and useEffect)

Backend Communication: REST APIs for data fetching and trade execution.

Libraries & Tools:

Chart.js for visual representation of straddle prices and trends.

CSS for responsive styling and better user experience.

1. Error Handling :
o very API call is wrapped in a try-catch block to catch potential errors during the
fetch operations.
o Example:

javascript
Copy code
try {
const response = await axios.get(GETCREATEDSTATEGY);
setStrategylist(response.data);
} catch (error) {
console.error(error);
}

 If an error occurs, it will be logged to the console using console.error.


2. Graceful Failure:
o If an API call fails, the component does not crash; instead, it logs the error.
o Users are not explicitly notified of the failure, which could be improved for better
UX.
3. Loading Indicator:
o A loading state is used to inform users that the data is being fetched or
processed. If an error occurs, the loading state still prevents unwanted actions
during the process.

Qn:Dashboard ,trade execution


This code implements a React Dashboard component to manage, display, and perform actions
on live trading positions. Here's how the code works, broken into functional segments:

Key Functionalities

1. Fetching Current Positions (Trades):


o The mergedStategyData function fetches live trading data from the API
(GETRUNNINGTRADES) every 2 seconds using setInterval and updates the
component state (data).
o It processes the fetched data to group trades by their unique identifiers and
calculates derived values, such as the total last trade price and price at the order
time.

Component States

 data: Stores the processed list of trades.


 isLoading: Indicates if a process like fetching or squaring off is in progress.
 loading: Tracks whether data is being fetched.
 popup: Manages notification or confirmation messages.
 tradesArray: Stores details for individual trades fetched by fetchData.
 hideFooter: Toggles the visibility of the footer.

Lifecycle Management

1. Initialization (useEffect):
o Starts a data-fetching interval that repeatedly calls mergedStategyData.
o Cleans up the interval on component unmount.
2. Fetching Data (mergedStategyData):
o Sends a POST request to fetch data for the logged-in user (userID from
localStorage).
o Maps the data to include last trade prices from a separate stock data array and
groups trades by orderUniqueIdentifier for display.

Core Functions

Process Trades (processData)


 Groups trades by orderUniqueIdentifier.
 Calculates aggregated values (totalLastTradePrice and totalPriceAtOrderTime) for
each unique trade group.

View Trades (viewTrades)

 Fetches trade details for a specific orderUniqueIdentifier from the API


(GETTRADEWITHUNIQUEIDENTIFIER) and updates the tradesArray.
 Calculates values such as difference between lastTradePrice and aggregated
priceAtOrderTime.

Square Off Trades

 Single Trade (handleSquareOff):


o Sends a request to the CALLTRADESQUAREOFF endpoint to square off a specific
trade.
 All Trades (handleSquareOffAll):
o Prompts a confirmation popup.
o On confirmation, squares off all trades one by one by invoking handleSquareOff
for each trade.

Square Off All Trades Simultaneously

 Sends POST requests for all trades in parallel using Promise.all to optimize
performance.

User Interface

1. Header:
o Displays the title "CURRENT POSITIONS."
o Provides a button to "Square Off All" trades, disabled while processing.
2. Table:
o Lists all trades with columns for:
 Instrument (Trade Identifier or Re-entry details).
 Order Side.
 Mark-to-Market (MTM) profit/loss (totalLastTradePrice -
totalPriceAtOrderTime).
 Buttons for:
 Square Off (single trade).
 View Trades (fetch trade details).
3. Popup:
o Displays confirmation dialogs or notifications.
o For confirmations (e.g., square off all trades), includes "Confirm" and "Cancel"
buttons.
4. Footer:
o Conditionally renders a footer using the Footer component.

Key Workflow

1. Data Fetching:
o Trades are fetched every 2 seconds.
o Each trade is grouped and processed for display.
2. Viewing a Trade:
o The user clicks "View Trades" for a specific trade.
o Trade details are fetched, and calculations like difference are displayed.
3. Squaring Off:
o Single trade: User clicks "Square Off" for a trade, triggering an API call.
o All trades: User clicks "Square Off All," confirms the action, and API calls are
made for all trades.
4. Notifications:
o Success or error messages are displayed in a popup.

Error Handling

 Logs errors in fetching or processing data.


 Displays fallback UI or warnings (e.g., "No data found").

Code Reusability and Design

 API Abstraction: Constants (GETRUNNINGTRADES, CALLTRADESQUAREOFF,


GETTRADEWITHUNIQUEIDENTIFIER) centralize API endpoints.
 State Updates: Avoids direct mutation of states, ensuring reactivity.
 Popup Mechanism: Modular notification and confirmation dialogs improve UX.

Real-World Usage

This code is ideal for a trading platform, where users monitor live positions, view individual
trade details, and close positions interactively. The frequent updates ensure real-time accuracy,
while the interactive UI supports user actions effectively.

import React, { useState, useEffect } from "react";


import "./form.css";
import { POSTORDER, GETEXPIRYDATE } from '../constant';

const Form = ({ onLoadingChange }) => {


const [formData, setForm] = useState({
orderQuantity: "",
orderSide: "SELL",
orderType: "MARKET",
stopPrice: "50",
otm: "",
index: "BANKNIFTY",
ceEntry: "1",
peEntry: "1",
disclosedQuantity: "",
date: "" // Initially empty
});
const [isLoading, setIsLoading] = useState(false);
const [expiryDate, setExpiryDate] = useState(null);
const [availableExpiryDates, setAvailableExpiryDates] = useState([]); //
State for expiry dates

useEffect(() => {
onLoadingChange(isLoading);
}, [isLoading, onLoadingChange]);

const fetchExpiryDates = async () => {


console.log("Fetching expiry dates for:", formData.date); // Log the
date being used
try {
const response = await fetch(GETEXPIRYDATE, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ date: formData.date }) // Adjust if
needed
});

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const data = await response.json();


console.log("Full API Response:", data); // Log full API response

if (data && data.data && data.data.length > 0) {


const dates = data.data.map(item => item.ExpiryDate); //
Extract ExpiryDate values
setAvailableExpiryDates(dates);
console.log("Available Expiry Dates:", dates); // Log
available expiry dates
if (dates.length > 0 && !formData.date) {
// Set the default expiry date if not already selected
setForm(prevFormData => ({
...prevFormData,
date: dates[0] // Set the first available date as the
default
}));
setExpiryDate(dates[0]); // Set the expiryDate state
}
} else {
setAvailableExpiryDates([]);
alert("No expiry dates found.");
}
} catch (error) {
console.error("Error fetching expiry dates:", error);
alert("Failed to fetch expiry dates: " + error.message);
setAvailableExpiryDates([]);
}
};

useEffect(() => {
fetchExpiryDates(); // Fetch expiry dates on component mount
}, [formData.index]); // Fetch expiry dates when the index changes

const handleChange = async (event) => {


const { name, value } = event.target;

if ((name === "ceEntry" || name === "peEntry") && (value > 5 || value
< 0)) {
alert(`${name.toUpperCase()} should be between 0 and 5`);
return;
}

setForm(prevFormData => ({
...prevFormData,
[name]: value
}));

// Fetch expiry dates when the index or date changes


if (name === "index" || name === "date") {
await fetchExpiryDates(); // Fetch expiry dates for the selected
index if needed
}
};

const handleSubmit = async (event) => {


event.preventDefault();
setIsLoading(true);

const stopPrice = formData.stopPrice.trim() === "" ? 50 :


parseFloat(formData.stopPrice);

const jsonData = {
orderQuantity: parseInt(formData.orderQuantity, 10),
orderSide: formData.orderSide,
orderType: formData.orderType,
index: formData.index,
stopPrice: stopPrice,
otm: parseInt(formData.otm, 10),
ceEntry: formData.ceEntry,
peEntry: formData.peEntry,
disclosedQuantity: 0,
userId: localStorage.getItem("objectId"),
date: formData.date,
expiryDate: expiryDate, // Ensure expiryDate is being sent
indexExpiry: formData.index // Pass index as indexExpiry
};

// Log all the form data before sending it


console.log("Form Data before submission:", {
orderQuantity: jsonData.orderQuantity,
orderSide: jsonData.orderSide,
orderType: jsonData.orderType,
index: jsonData.index,
stopPrice: jsonData.stopPrice,
otm: jsonData.otm,
ceEntry: jsonData.ceEntry,
peEntry: jsonData.peEntry,
disclosedQuantity: jsonData.disclosedQuantity,
userId: jsonData.userId,
date: jsonData.date,
expiryDate: jsonData.expiryDate,
indexExpiry: jsonData.indexExpiry // Log the indexExpiry as well
});
try {
const response = await fetch(POSTORDER, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(jsonData)
});

console.log("Response Status:", response.status);


const contentType = response.headers.get("content-type");

if (contentType && contentType.includes("application/json")) {


const data = await response.json();
console.log("Response Data:", data);
} else {
const text = await response.text();
console.log("Non-JSON Response:", text);
alert("Received non-JSON response from server");
}
} catch (error) {
alert("Error: " + error.message);
console.error("Error in handleSubmit:", error);
} finally {
setIsLoading(false);
}
};

return (
<div className="container">
<label>
QUANTITY
<input
type="number"
onChange={handleChange}
value={formData.orderQuantity}
name="orderQuantity"
/>
</label><br />
<label>
STOP LOSS
<input
type="number"
onChange={handleChange}
value={formData.stopPrice}
name="stopPrice"
/>
</label><br />
<label>
INDEX
<select
onChange={handleChange}
value={formData.index}
name="index"
>
<option value="BANKNIFTY">BANKNIFTY</option>
<option value="NIFTY">NIFTY</option>
</select>
</label><br />
<label>
ORDER SIDE
<select
onChange={handleChange}
value={formData.orderSide}
name="orderSide"
>
<option value="BUY">BUY</option>
<option value="SELL">SELL</option>
</select>
</label><br />
<label>
CE RE-ENTRY
<input
type="number"
onChange={handleChange}
value={formData.ceEntry}
name="ceEntry"
/>
</label><br />
<label>
PE RE-ENTRY
<input
type="number"
onChange={handleChange}
value={formData.peEntry}
name="peEntry"
/>
</label><br />
<label>
OTM
<input
type="number"
onChange={handleChange}
value={formData.otm}
name="otm"
/>
</label><br />
<label>
EXPIRY DATE
<select
onChange={(e) => {
const selectedDate = e.target.value;
setForm(prevFormData => ({ ...prevFormData, date:
selectedDate })); // Update form data with selected date
setExpiryDate(selectedDate); // Update expiry date
state
console.log("Selected Expiry Date:", selectedDate);
// Log the selected expiry date
}}
value={formData.date}
name="expirydate"
>
<option value="" disabled></option> {/* Placeholder
option */}
{availableExpiryDates.map((date, index) => (
<option key={index} value={date}>{date}</option>
))}
</select>
</label>
<br />
<button onClick={handleSubmit} disabled={isLoading}>
{isLoading ? 'LOADING...' : 'EXECUTE'}
</button>
</div>
);
};

export default Form;

Qn:Chart PLotting
This React component (NiftyLineChartComponent) is a comprehensive solution for rendering
two interactive line charts using the Chart.js library. The charts visualize Nifty Straddle Price
data, incorporating Bollinger Bands and SMA (Simple Moving Average), with a time period
filtering mechanism. Let’s break it down step by step:

Code Explanation

1. Dependencies

 React: For component creation, state management, and lifecycle handling.


 Chart.js & Chart.js Plugins: For chart rendering and advanced features like zoom and
pan.
 Line Component: Used to render line charts.

2. State Variables

 chartData & chartData2: Store data for the two charts.


 decayPercentage: Tracks the last straddle price.
 lastDateIndexPrice: Tracks the most recent Nifty index price.
 loading: Toggles between loading and data display states.
 selectedTab: Tracks the currently selected time period.
 timePeriodData: Stores preprocessed data for different time periods.

3. Core Functions

1. calculateBollingerBands:
o Computes SMA, Upper Band, and Lower Band for a given set of prices.
o Purpose: To enhance the chart by visualizing volatility using Bollinger Bands.
2. fetchNiftyData:
o Fetches the Nifty Straddle Price data from the backend.
o Processes the data into:
 Labels: Strike prices.
 Values: Corresponding straddle prices.
o Stores full and time-filtered datasets in timePeriodData.
o Calculates Bollinger Bands and updates chartData.
3. fetchLastDateIndexPrice:
o Fetches the latest Nifty index price and updates lastDateIndexPrice.
4. Lifecycle Management

 useEffect:
o Initial Data Fetch: On component mount, it triggers fetchNiftyData and
fetchLastDateIndexPrice.
o Auto-Refresh: Re-fetches data every 30 seconds using setInterval.
 useEffect for selectedTab:
o Updates chartData based on the selected time period (e.g., '1 day', '30 min').

5. Chart Plotting

 Data Structure:
o Chart.js expects datasets, each having:
 label: Describes the dataset (e.g., "Straddle Price").
 data: Y-axis values.
 Styling: Colors, line tension, etc.
 Options:
o Configures axes and plugins like zoom/pan.
 Rendering:
o Two charts are rendered side-by-side, each with its own chartData and options.

Chart Workflow

1. Data Fetching:
o The component fetches Nifty Straddle Price data and computes necessary
transformations (e.g., Bollinger Bands).
o Time-filtered datasets ('30 min', '10 min', etc.) are created using slice.
2. Chart Data Preparation:
o A common structure is used for chartData:
 Labels: X-axis (Strike prices).
 Datasets: Y-axis data for Straddle Price, SMA, Upper Band, and Lower
Band.
3. Chart Rendering:
o The Line component from react-chartjs-2 is used to render the chart.
o Plugins (e.g., chartjs-plugin-zoom) enable interactivity like zooming and
panning.
4. Dynamic Updates:
o On time period selection, useEffect recalculates and updates chartData.
o Every 30 seconds, the data refreshes automatically.
Key Features

 Interactive Chart: Supports zoom and pan using chartjs-plugin-zoom.


 Dynamic Time Filters: Allows switching between different time views (e.g., '1 day', '30
min').
 Bollinger Bands: Visualize market volatility.
 Auto-Refresh: Keeps the chart data up-to-date with real-time updates.

Chart Customization

 Chart Appearance:
o Line colors and tensions define how the chart looks.
o Bollinger Bands are highlighted with distinct colors.
 Interactivity:
o Zoom and pan provide a better exploration experience for users.
 Decay Calculation:
o The component displays the percentage change in straddle price
(decayPercentage) relative to the last index price.

How the Chart is Plotted

1. X-Axis (Labels):
o Strike prices (chartLabels) are set as the X-axis labels.
2. Y-Axis (Values):
o Four datasets:
 Straddle Price
 SMA
 Upper Band
 Lower Band
o Y-axis values are derived from fetched data or calculated metrics.
3. Time Period Selection:
o Dynamically filters data for specific intervals, updating both labels and values.

If you'd like further clarification on any specific part, feel free to ask!

4o
O
Chat
Code: import React, { useState, useEffect, useRef } from 'react';

import { Line } from 'react-chartjs-2';


import { Chart as ChartJS } from 'chart.js/auto';
import zoomPlugin from 'chartjs-plugin-zoom';
import './chart.css'; // Ensure this path is correct
import { GETNIFTYSTRADDLECHART, GETLASTINDEXRATE } from '../constant';

// Register Chart.js components and plugins


ChartJS.register(zoomPlugin);

const NiftyLineChartComponent = () => {


const [chartData, setChartData] = useState(null);
const [chartData2, setChartData2] = useState(null); // Second chart data
const [decayPercentage, setDecayPercentage] = useState(null);
const [lastDateIndexPrice, setLastDateIndexPrice] = useState(null);
const [loading, setLoading] = useState(true);
const [selectedTab, setSelectedTab] = useState('1 day'); // Default tab
const [timePeriodData, setTimePeriodData] = useState(null);

const chartRef1 = useRef(null);


const chartRef2 = useRef(null);

const timePeriods = {
'1 day': 1, // Full data
'30 min': 30, // Last 30 minutes
'20 min': 20, // Last 20 minutes
'10 min': 10, // Last 10 minutes
'5 min': 5, // Last 5 minutes
};

const calculateBollingerBands = (prices, period = 20, deviations = 2) => {


const sma = [];
const upperBand = [];
const lowerBand = [];
for (let i = 0; i < prices.length; i++) {
if (i >= period - 1) {
const slice = prices.slice(Math.max(0, i - period + 1), i + 1);
const mean = slice.reduce((acc, price) => acc + price, 0) /
slice.length;
const stdDeviation = Math.sqrt(
slice.reduce((acc, price) => acc + Math.pow(price - mean, 2),
0) / slice.length
);

sma.push(mean);
upperBand.push(mean + deviations * stdDeviation);
lowerBand.push(mean - deviations * stdDeviation);
} else {
sma.push(null);
upperBand.push(null);
lowerBand.push(null);
}
}

return { sma, upperBand, lowerBand };


};

const fetchNiftyData = async () => {


try {
const response = await fetch(GETNIFTYSTRADDLECHART, { method: 'POST'
});
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
if (!data.result) throw new Error('Data result is missing');

const chartLabels = data.result.map(item => item.strike);


const chartValues = data.result.map(item => item.straddle_price);
const newDecayPercentage = data.result.slice(-1)[0].straddle_price;
setDecayPercentage(newDecayPercentage);

const { sma, upperBand, lowerBand } =


calculateBollingerBands(chartValues, 20, 2);

setTimePeriodData({
'1 day': { labels: chartLabels, values: chartValues },
'30 min': { labels: chartLabels.slice(-30), values:
chartValues.slice(-30) },
'20 min': { labels: chartLabels.slice(-20), values:
chartValues.slice(-20) },
'10 min': { labels: chartLabels.slice(-10), values:
chartValues.slice(-10) },
'5 min': { labels: chartLabels.slice(-5), values:
chartValues.slice(-5) },
});

const commonChartData = {
labels: chartLabels,
datasets: [
{
label: 'Straddle Price',
data: chartValues,
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1,
},
{
label: 'Upper Bollinger Band',
data: upperBand,
fill: false,
borderColor: 'rgb(255, 99, 132)',
tension: 0.1,
},
{
label: 'Lower Bollinger Band',
data: lowerBand,
fill: false,
borderColor: 'rgb(54, 162, 235)',
tension: 0.1,
},
{
label: 'SMA (20)',
data: sma,
fill: false,
borderColor: 'rgb(153, 102, 255)',
tension: 0.1,
},
],
};

setChartData(commonChartData);
setChartData2({ ...commonChartData, datasets: [{
...commonChartData.datasets[0], label: 'Different Straddle Price' }] });
} catch (error) {
console.error('Error fetching Nifty data:', error);
}
};

const fetchLastDateIndexPrice = async () => {


const myHeaders = new Headers({ "Content-Type": "application/json" });
const params = JSON.stringify({ "indexName": "NIFTY" });

try {
const response = await fetch(GETLASTINDEXRATE, {
method: 'POST',
headers: myHeaders,
body: params,
});
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
if (!data.data || !data.data[0]) throw new Error('Data is missing');

const newLastIndexPrice = data.data[0].lastRecordedRate;


setLastDateIndexPrice(newLastIndexPrice);
} catch (error) {
console.error('Error fetching last day index price:', error);
}
};

useEffect(() => {
const fetchData = async () => {
setLoading(true);
await fetchNiftyData();
await fetchLastDateIndexPrice();
setLoading(false);
};

fetchData();
const interval = setInterval(fetchData, 30000);

return () => clearInterval(interval);


}, []);

useEffect(() => {
if (chartData && timePeriodData) {
const { labels, values } = timePeriodData[selectedTab] || {};
const { sma, upperBand, lowerBand } = calculateBollingerBands(values,
20, 2);

const updatedChartData = {
labels,
datasets: [
{
label: 'Straddle Price',
data: values,
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1,
},
{
label: 'Upper Bollinger Band',
data: upperBand,
fill: false,
borderColor: 'rgb(255, 99, 132)',
tension: 0.1,
},
{
label: 'Lower Bollinger Band',
data: lowerBand,
fill: false,
borderColor: 'rgb(54, 162, 235)',
tension: 0.1,
},
{
label: 'SMA (20)',
data: sma,
fill: false,
borderColor: 'rgb(153, 102, 255)',
tension: 0.1,
},
],
};

setChartData(updatedChartData);
setChartData2({ ...updatedChartData, datasets: [{
...updatedChartData.datasets[0], label: 'Different Straddle Price' }] });
}
}, [selectedTab, timePeriodData]);

const zoomIn = () => {


try {
if (chartRef1.current && chartRef2.current) {
chartRef1.current.chartInstance.zoom(1.1);
chartRef2.current.chartInstance.zoom(1.1);
}
} catch (error) {
console.error("Error zooming in:", error);
}
};

const zoomOut = () => {


try {
if (chartRef1.current && chartRef2.current) {
chartRef1.current.chartInstance.zoom(0.9);
chartRef2.current.chartInstance.zoom(0.9);
}
} catch (error) {
console.error("Error zooming out:", error);
}
};

const options = {
scales: {
x: {
type: 'category',
labels: chartData ? chartData.labels : [],
},
y: {
ticks: {
beginAtZero: true,
},
},
},
plugins: {
zoom: {
pan: {
enabled: true,
mode: 'x',
},
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true,
},
mode: 'x',
},
},
},
};

return (
<div className='chart-container'>
<h2>
Nifty Straddle Price Line Charts
{decayPercentage && lastDateIndexPrice && (
<> Decay: {((lastDateIndexPrice - decayPercentage) /
lastDateIndexPrice * 100).toFixed(1)} %</>
)}
</h2>
<div className='time-periods'>
{Object.keys(timePeriods).map(period => (
<button
key={period}
className={`tab ${selectedTab === period ? 'active' :
''}`}
onClick={() => setSelectedTab(period)}
>
{period}
</button>
))}
</div>
{loading ? (
<p>Loading...</p>
) : (
<div className='chart-content'>
{chartData && (
<>
<div className='chart'>
<Line ref={chartRef1} data={chartData}
options={options} />
</div>
<div className='chart'>
<Line ref={chartRef2} data={chartData2}
options={options} />
</div>
</>
)}
</div>
)}
</div>
);
};
export default NiftyLineChartComponent;

Qn:Challenges faced

In response to the interviewer's question about challenges faced while working on this project,
you could provide an answer like this:

Challenges Faced:

1. Real-Time Data Fetching and Performance:


One of the key challenges was ensuring that real-time stock market data was fetched at
regular intervals without compromising performance. To handle this, I implemented
periodic API calls (every 2 seconds) to fetch data and update the UI. Ensuring that the
application remained responsive and did not get overwhelmed by constant data updates
was crucial. I had to carefully optimize the fetching and processing logic to maintain a
smooth user experience, especially in a high-frequency trading environment.
2. Handling Large Volumes of Data:
The application deals with a significant amount of trade and stock data. A challenge was
efficiently processing and displaying this data, particularly when performing complex
calculations like aggregating prices, handling different order sides, and ensuring the
correctness of the MTM (Mark-to-Market) calculations. I tackled this by using
JavaScript's reduce() function to aggregate data and efficiently process large arrays
without affecting performance.
3. API Integration and Error Handling:
Integrating multiple APIs (such as for running trades, square-offs, and fetching trade
details) posed challenges around handling potential errors like failed API requests or
timeouts. I had to ensure the app was resilient, providing meaningful error messages and
fallback options, especially when dealing with financial data that is critical to the user.
4. State Management and UI Responsiveness:
Managing the state of various components—like loading indicators, trade data, and the
popup notifications—was complex, especially with multiple asynchronous operations
running simultaneously. I used React’s useState and useEffect hooks to manage state
and ensure the UI updated correctly when trade data was fetched or when trade actions
(like square-offs) were processed.
5. User Interface and UX:
Designing the interface to present large sets of data clearly while making it interactive
was another challenge. I worked on ensuring that the table of trades was easy to navigate
and displayed relevant information in a concise way. Additionally, I had to handle edge
cases, such as when no data was returned from the API or when a trade could not be
squared off.
6. Error and Popup Handling:
Providing the user with feedback, especially in case of errors or success, required careful
planning. I implemented a popup system to notify users about the status of their actions
(like "Trade squared off successfully"), but I had to ensure it did not interfere with the
overall flow of the application. Ensuring the right timing for showing notifications was
also a critical challenge.
7. Ensuring Data Integrity:
Ensuring that the data from the APIs was processed correctly and that stock prices
matched with their respective trade data was essential for accuracy. I had to ensure that
even when the data was aggregated or updated in real time, it remained consistent across
all trades and calculations.

This answer highlights some of the technical challenges and how you addressed them while
working on the project. It also demonstrates problem-solving skills and an understanding of the
complexities involved in real-time data applications.

2/2
4o mini

You might also like