<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anshu Roy on Medium]]></title>
        <description><![CDATA[Stories by Anshu Roy on Medium]]></description>
        <link>https://medium.com/@royanshu.main?source=rss-f35320fb6397------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rU_f2MLheFrxikmi</url>
            <title>Stories by Anshu Roy on Medium</title>
            <link>https://medium.com/@royanshu.main?source=rss-f35320fb6397------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:33:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@royanshu.main/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How we plugged five Google ADK agents into Switch to turn SEBI circulars into verified engineering…]]></title>
            <link>https://medium.com/@royanshu.main/how-we-plugged-five-google-adk-agents-into-switch-to-turn-sebi-circulars-into-verified-engineering-9e57c369fd9d?source=rss-f35320fb6397------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e57c369fd9d</guid>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Anshu Roy]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 12:37:23 GMT</pubDate>
            <atom:updated>2026-11-07T12:37:23.995Z</atom:updated>
            <content:encoded><![CDATA[<h3>How we plugged five Google ADK agents into Switch to turn SEBI circulars into verified engineering work</h3><p>We built RegMind.ai for the Flip the Switch hackathon: five Google ADK agents that live in a Mattermost channel through Switch and turn SEBI circulars into engineering tasks that are checked against real pull requests.</p><p>This post walks through what we made, how we connected custom agents (not Claude Code or Codex) to Switch, and the problems we hit on the way. If you are setting up Switch for the first time, the setup and “what broke” sections are the useful parts.</p><h3>The problem</h3><p>Every time SEBI (India’s securities regulator) issues a circular, a stock broker has to work out what changed and build it into their systems. The rules are written in legal language, but the work is done by engineers.</p><p>Today that handoff runs on calls, emails and spreadsheets. A compliance officer reads a long PDF, explains it to engineers, the engineers build what they understood, and weeks later someone checks by hand whether it actually meets the rule. Things get lost at every step, and small brokers feel it most because they don’t have big compliance teams.</p><p>We wanted the whole loop in one place: the circular comes in, a human approves what matters, engineers get clear tasks, and the code is checked against the rule before anything is marked done.</p><h3>Why Switch</h3><p><a href="https://github.com/sandbox-quantum/switch">Switch</a> is open-source infrastructure from SandboxAQ that puts AI agents into the team chat you already use. A channel becomes a <strong>room</strong>: a shared history that every person and agent in it can read. Agents join under their own names and avatars, like teammates.</p><p>That was exactly what we needed. Compliance is a team process with approvals, handoffs and arguments about wording, so a separate dashboard felt wrong. With Switch:</p><ul><li>The compliance officer, engineers and all five agents share one channel.</li><li>Every handoff between agents is a visible message, so nothing happens behind anyone’s back.</li><li>A person approves before anything reaches engineering, in the same chat.</li><li>The agents talk to Switch, not to Mattermost directly, so the same room could move to Slack, Teams or Discord later without changing the agents.</li></ul><p>We used the Mattermost that comes bundled with Switch, so we didn’t need a company workspace to build.</p><h3>How it fits together</h3><p>One FastAPI backend holds a single live connection to Switch and runs all five agents behind it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*DBd7sGgxfbNLIgWa.png" /><figcaption>People talk in Mattermost; Switch carries every message to one backend, which runs the right agent and posts the reply back as that agent.</figcaption></figure><ul><li><strong>regmind-intake</strong> reads a new circular (PDF, DOCX, image or text), decides if it applies to the firm and registers it.</li><li><strong>regmind-parser</strong> splits it into clauses, classifies each one and asks the compliance officer to approve.</li><li><strong>regmind-spec</strong> turns approved technical obligations into tasks with a spec and an evidence checklist.</li><li><strong>regmind-router</strong> handles amendments: it pauses, rewrites or splits affected tasks based on their status.</li><li><strong>regmind-auditor</strong> reads the engineer’s pull request from GitHub and checks it against the checklist.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*2TQcLLiMzfl7yw3Q.png" /><figcaption>The five agents, their tools, and how they hand work to each other.</figcaption></figure><p>The pieces that connect them to Switch:</p><ol><li><strong>Provisioner.</strong> Registers the five agents on Switch through its Agent Protocol and creates a Compliance Office room with all of them in it.</li><li><strong>Supervisor.</strong> Holds a WebSocket to Switch as regmind-intake, receives every message in the room and downloads any attached files through Switch’s media API.</li><li><strong>Orchestrator.</strong> Reads the @mentions in each message, runs that agent with Google ADK and Gemini, posts the reply back as that agent over HTTP, and follows handoffs (intake to parser to spec) with a hop limit so agents can’t loop.</li><li><strong>Tools.</strong> Plain Python functions the agents call: read the circular, save obligations, create tasks, fetch a PR diff. Anything that must behave the same every time, like splitting clauses or deciding task status after an amendment, is code, not the model.</li></ol><p>All of it is stored in Postgres: circulars, obligations, tasks and an audit trail.</p><h3>Setting it up, step by step</h3><p>This is the path that worked for us with custom agents. If you use Claude Code or Codex, Switch Console’s “Add agent” button is simpler; for anything else, you register agents through the API like we did.</p><ol><li><strong>Run a Switch server.</strong> We used the “Agent Switch” template on Railway. It deploys the Switch server, its Postgres and a bundled Mattermost. Set the admin email and password during deploy; your backend logs in with them.</li><li><strong>Register your agents.</strong> Call the Agent Protocol’s register endpoint once per agent with a registration key. Each call returns an agent id and an API key. Store the keys encrypted; we used the backend’s SECRET_KEY, so never change it after this step.</li><li><strong>Open up addressing.</strong> By default only an agent’s owner can talk to it. We set each agent’s addressing policy to open so anyone in the room can mention it.</li><li><strong>Create a room and add the agents.</strong> One call to the gateway creates the room; Switch links it to a Mattermost channel, and the agents appear and greet everyone.</li><li><strong>Listen and reply.</strong> Open a WebSocket to /agents/&lt;id&gt;/connection/ws with the agent’s key, answer the server’s pings, and handle message events. Post replies with an HTTP call to /agents/&lt;id&gt;/message.</li><li><strong>Download attachments.</strong> A message’s attachments list carries an mxc reference. Fetch the bytes from /agents/&lt;id&gt;/rooms/&lt;room&gt;/media?mxc=... and hand the saved path to your agent.</li><li><strong>Talk to it.</strong> Log into Mattermost as a regular user (not the admin), open the channel and mention an agent.</li></ol><p>We wrapped steps 2 to 4 in one endpoint, POST /api/v1/switch/provision, so the whole setup is a single call. The full code and run instructions are in our <a href="https://github.com/AnshuRoy25/RegMind">repo</a>.</p><h3>What it looks like in the chat</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*aSDsXLwaJB36lWul.png" /><figcaption>From a circular to a verified task, all in one channel.From a circular to a verified task, all in one channel.</figcaption></figure><p>These are real replies from our test run, trimmed a little.</p><p><strong>1. A circular arrives.</strong> The compliance officer attaches the file and mentions intake.</p><blockquote><strong><em>owner:</em></strong><em> @regmind-intake new SEBI circular, please review (master_circular.txt)<br></em><strong><em>RegMind Intake:</em></strong><em> Read Master Circular on Log Retention and Access Control for Stock Brokers. It applies to us. Type: master circular. @regmind-parser please extract obligations from circular_id=1</em></blockquote><p><strong>2. The parser classifies every clause and waits for a human.</strong></p><blockquote><strong><em>RegMind Parser:</em></strong><em> Extracted 15 clauses. OBL-004 · 3.1 · technical · urgent · Retain order management system logs for a minimum of 2 years … 4 technical items will become engineering tasks. Compliance officer, please review and reply “approved”.</em></blockquote><p><strong>3. The officer approves, and work is split.</strong> Technical items go to engineering; reports, board reviews and “no shared passwords” go to the compliance team.</p><blockquote><strong><em>owner:</em></strong><em> @regmind-parser approved<br></em><strong><em>RegMind Spec:</em></strong><em> Created 4 engineering tasks. TSK-001 · urgent · Retain OMS logs for 730 days. Evidence: retention_days set to 730 in the logging config · automated test showing logs can’t be deleted early</em></blockquote><p><strong>4. An engineer picks up a task and opens a PR.</strong></p><blockquote><strong><em>engineer:</em></strong><em> @regmind-spec starting TSK-001</em></blockquote><p><strong>5. The auditor reads the real code.</strong> It fetches the PR diff from GitHub, masks any secrets before the model sees it, and checks each item on the evidence checklist.</p><blockquote><strong><em>RegMind Auditor:</em></strong><em> ❌ TSK-001 not complete yet. retention_days is 365 in config/logging.yaml, needs to be 730. No test verifying logs can’t be deleted early.<br>(the engineer fixes the PR)<br></em><strong><em>RegMind Auditor:</em></strong><em> ✅ TSK-001 verified and marked complete. retention_days set to 730 ✓ · test in tests/test_log_retention.py ✓</em></blockquote><p>The auditor never merges anything. It verifies evidence and closes the task; a person still merges the PR, which is what a regulated firm would want.</p><h3>What broke, and how we fixed it</h3><p>These cost us the most time. If you hit one, the fix is probably here.</p><p><strong>“Invalid credentials” (4401) on an agent that worked an hour ago.</strong> Switch allows one live connection per agent. A teammate was running the same backend on his laptop, and a leftover process from an auto-reload was still connected too, so every new connection got kicked out. Check the Switch server logs: if you see a long-lived connection for your agent that isn’t yours, that’s it. Run exactly one backend, kill stray Python processes, and start uvicorn without --reload while testing.</p><p><strong>Agents replied twice to every message.</strong> Same cause: two processes were connected and both answered.</p><p><strong>“I’m currently offline, my connector isn’t reporting in.”</strong> Only our intake agent holds a live connection; the other four post over HTTP. When a message mentions an agent with no live stream, Switch answers on its behalf. Our real reply still arrived a few seconds later. The clean fix is to hold a lightweight connection for every agent that only answers pings.</p><p><strong>“Cannot post as unknown agent.”</strong> We loaded our list of agents at startup, then registered new ones while the server was running. The backend didn’t know them yet. We now reload the list once when asked to post as an unknown agent.</p><p><strong>Messages arrived with an empty body.</strong> We first tried Discord through Switch’s Discord bridge. Slash commands worked, but every normal message reached our agent with body: &#39;&#39; and no attachments, so the agent kept asking for a file. A quick test that settles it: ask the agent to “reply with only the word BANANA”. The <a href="https://docs.switchagents.ai/switch-rooms/deploy/messaging-apps/discord.md">Switch Discord docs</a> say the bot needs the Message Content intent, saved, and the bot invited with the right permissions. We moved to the bundled Mattermost, where the same test worked first time.</p><p><strong>Mentions from the chat app don’t always look like </strong><strong>@agent-name.</strong> When you pick a name from the autocomplete popup, some platforms send a different format. Our orchestrator matches @regmind-x in the text, so we also route any message addressed to intake to intake by default.</p><p><strong>Log the raw payload.</strong> One log.info(&quot;Switch payload: %s&quot;, payload) line answered most of our questions faster than reading code.</p><h3>What we liked, and what we’d improve</h3><p><strong>Liked:</strong></p><ul><li>Any framework works. Our agents are Google ADK, not a supported coding agent, and the Agent Protocol was enough to make them full room members.</li><li>Rooms as shared context. Agents, people and handoffs in one visible history made the workflow easy to follow and easy to demo.</li><li>The bundled Mattermost. We had a working team chat without setting up a company workspace.</li><li>Commands like !list-agents and !agents-status made debugging much faster.</li></ul><p><strong>Would improve:</strong></p><ul><li>A clearer error than “Invalid credentials” when a second connection kicks out the first. A message like “another connection is active for this agent” would have saved us an hour.</li><li>A message history view in the dashboard, so you can check what Switch actually received from a platform.</li><li>A documented way to keep several agents live from one process, so the “offline” auto-reply doesn’t fire for agents your backend runs internally.</li></ul><h3>Try it</h3><ul><li>Code and setup: <a href="https://github.com/AnshuRoy25/RegMind">github.com/AnshuRoy25/RegMind</a></li><li>Switch: <a href="https://github.com/sandbox-quantum/switch">github.com/sandbox-quantum/switch</a> · <a href="https://docs.switchagents.ai/">docs</a></li><li>Hackathon: <a href="https://www.wemakedevs.org/hackathons/switch">Flip the Switch</a></li></ul><p>Built by Team ASQUARE (Anshu Roy and Aayush Dubey). The circulars in the demo are mock documents written for the hackathon, not real SEBI circulars.</p><p>#HowISwitch</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e57c369fd9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Peer To Peer Architecture (Web Conferencing App)]]></title>
            <link>https://medium.com/@royanshu.main/peer-to-peer-architecture-web-conferencing-app-25d7d0b6d4c5?source=rss-f35320fb6397------2</link>
            <guid isPermaLink="false">https://medium.com/p/25d7d0b6d4c5</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[peer-to-peer]]></category>
            <category><![CDATA[video-conferencing]]></category>
            <dc:creator><![CDATA[Anshu Roy]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 17:45:18 GMT</pubDate>
            <atom:updated>2026-10-11T17:45:18.529Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we are going to understand the in-depth technical and theoretical sequence of events behind web conferencing applications.</p><p>There are different architectures used to build real-time communication applications. In this blog, we will focus on the <strong>Peer-to-Peer (P2P) architecture</strong>. Although P2P is relatively simple to understand and implement, it becomes less scalable as the number of participants increases. Modern applications such as Google Meet and Zoom commonly use server-based media architectures, such as SFUs, for group conferencing. We will not discuss the SFU architecture in this blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EPGpiNID2GH4MbiR.png" /><figcaption>types of architecture</figcaption></figure><p>P2P is a useful starting point for understanding WebRTC. For simplicity, we will limit our implementation to just <strong>two peers</strong>, allowing us to understand the complete sequence of events in detail before moving on to more complex architectures.</p><h3>Before Diving into the Code: How Does P2P Communication Work?</h3><p>Suppose you are building a web application similar to Zoom, with features such as creating rooms, joining rooms, sharing video and audio streams, and screen sharing.</p><p>The most fundamental feature is the ability for two users to exchange audio and video in real time.</p><p>But how does this media actually travel from one user to another? Does it go directly from one browser to the other, or does it pass through a server?</p><p>In a P2P architecture, the media is sent directly between the two browsers whenever a direct network path can be established. However, this raises an important question:</p><p><strong>How do two browsers discover each other and establish a connection when they are running on different devices and networks across the internet?</strong></p><p>Before exchanging media, the browsers must exchange the information needed to negotiate a connection and discover a usable network path. This initial coordination is performed through a common server known as the <strong>signaling server</strong>.</p><p>The signaling server helps the browsers exchange two important types of information:</p><ol><li><strong>SDP (Session Description Protocol):</strong> SDP carries information about the proposed media session, including supported audio and video codecs, media types, and other negotiation parameters. Through the offer-and-answer process, the browsers negotiate how the media session will work.</li><li><strong>ICE candidates (Interactive Connectivity Establishment):</strong> These describe possible network addresses and transport paths through which the browsers may be able to communicate. The browsers exchange candidates and perform connectivity checks to determine which candidate pair can establish a working connection.</li></ol><p><em>The signaling server coordinates the initial exchange of connection information, while WebRTC handles the peer-to-peer media connection.</em></p><p>Once the necessary signaling information has been exchanged, the browsers use WebRTC’s ICE process to check possible network paths and establish a usable connection. If a direct path is possible, the audio and video can flow directly between the browsers. If network restrictions prevent direct connectivity, a TURN server may be required to relay the media.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CFeIVoKXAzgDwfWp.png" /><figcaption>(here webrtc is the network route through which media stream is transferred)</figcaption></figure><p>At this point, the signaling server does not need to carry the ongoing media stream. Its primary role is to facilitate signaling, although it may continue to handle other application events, such as users joining or leaving a room.</p><p>Now that we understand the basic idea behind P2P communication, let’s examine the code step by step and understand exactly what happens on both the client side and the server side.</p><h3>Step 1 : User A Establishes a Socket Connection with the Signaling Server</h3><p>When User A opens the website, the client-side JavaScript code runs in the browser. As soon as the following code executes, Socket.IO attempts to establish a connection between User A’s browser and the signaling server.</p><p>//client</p><pre>const socket = io();</pre><p>The io() function initializes a Socket.IO client. It initiates a connection request to the signaling server, using the current page&#39;s origin by default when no URL is specified.</p><p>//server</p><pre>io.on(&quot;connection&quot;, (socket) =&gt; {<br><br>}</pre><p>On the server, the &quot;connection&quot; event listener runs when a new client&#39;s Socket.IO connection has been established. The socket parameter represents that particular client&#39;s connection and allows the server to communicate with it.</p><p>//client</p><pre>socket.on(&quot;connect&quot;, () =&gt; {<br>  console.log(&quot;Connected to the signaling server!&quot;);<br>  setStatus(&quot;Connected to signaling server&quot;);<br>});</pre><p>On the client side, the &quot;connect&quot; event listener runs when the Socket.IO client successfully connects to the server. The status message is then updated to indicate that the signaling connection is ready.</p><p>At this point, <strong>User A has established a connection with the signaling server, but has not yet joined any room or established a WebRTC peer connection with another user.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W40UMKsKwLwv0OASOKRAyA.png" /><figcaption>step 1: socket connection is build up</figcaption></figure><h3>Step 2 : User A Creates a Room and Joins It</h3><p>Now that User A has established a Socket.IO connection with the signaling server, the next step is to join a room.</p><blockquote><strong>2.1 Accessing the camera and microphone</strong></blockquote><p>User A enters a room ID and clicks the <strong>Join Room</strong> button. This triggers the following client-side function.</p><p>//client</p><pre>async function join() {<br>  const room = roomInput.value.trim();<br><br>  if (!room) {<br>    alert(&quot;Enter a room name first&quot;);<br>    return;<br>  }<br><br>  try {<br>    const stream = await navigator.mediaDevices.getUserMedia({<br>      video: true,<br>      audio: true,<br>    });<br><br>    localStream = stream;<br>    localVideo.srcObject = stream;<br><br>    createPeerConnection();<br><br>    socket.emit(&quot;join&quot;, {<br>      room: room,<br>      name: &quot;user&quot;,<br>    });<br><br>    joinBtn.disabled = true;<br>    roomInput.disabled = true;<br>    micBtn.disabled = false;<br>    camBtn.disabled = false;<br>    leaveBtn.disabled = false;<br><br>    setStatus(&quot;Joined room, waiting for peer...&quot;);<br>  } catch (error) {<br>    console.log(&quot;getUserMedia error:&quot;, error);<br>    alert(&quot;Could not access camera/mic: &quot; + error.message);<br>  }<br>}</pre><p>First, the function reads the room ID entered by the user.</p><p>Next, getUserMedia() requests permission to access the camera and microphone. If permission is granted, it returns a MediaStream containing the available audio and video tracks. This stream is stored in the localStream variable.</p><p>The following line displays User A’s own camera feed in the browser:</p><pre>localVideo.srcObject = stream;</pre><p>This is only User A’s own video; it does not mean that a connection with User B has been established.</p><blockquote><strong>2.2 Creating a WebRTC peer connection</strong></blockquote><p>After obtaining the local media stream, the code calls:</p><pre>createPeerConnection();</pre><pre>function createPeerConnection() {<br><br>  if (peerConnection) {<br>    peerConnection.close();<br>  }<br><br>  const pc = new RTCPeerConnection(pc_config);<br><br>  pc.onicecandidate = (e) =&gt; {<br>    if (e.candidate) socket.emit(&quot;candidate&quot;, e.candidate);<br>  };<br><br>  pc.ontrack = (ev) =&gt; {<br>    console.log(&quot;add remote track success&quot;);<br>    remoteVideo.srcObject = ev.streams[0];<br>  };<br><br>  if (localStream) {<br>    const tracks = localStream.getTracks();<br>    for (let i = 0; i &lt; tracks.length; i++) {<br>      pc.addTrack(tracks[i], localStream);<br>    }<br>  }<br><br>  peerConnection = pc;<br>}</pre><p>This is an important step in the WebRTC process.</p><p>A <strong>peer connection (pc)</strong>, represented by the RTCPeerConnection object, is the browser&#39;s WebRTC object responsible for negotiating and managing a real-time connection with another peer. It handles the connection&#39;s media configuration, ICE candidate gathering, connectivity checks, and the sending and receiving of audio and video.</p><p>we create a new peer connection:</p><pre>const pc = new RTCPeerConnection(pc_config);</pre><p>This object provides the APIs and event handlers needed to establish and manage the future connection with User B.</p><blockquote><strong>2.3 Handling ICE candidates</strong></blockquote><p>consider following code.</p><pre>pc.onicecandidate = (e) =&gt; {<br>  if (e.candidate) {<br>    socket.emit(&quot;candidate&quot;, e.candidate);<br>  }<br>};</pre><p>Once the peer connection is configured, the browser’s WebRTC implementation can begin gathering ICE candidates. These candidates describe possible network addresses and paths through which the browser may be reachable.</p><p>Whenever a new candidate is discovered, the icecandidate event fires. The handler checks whether e.candidate contains a candidate. If it does, the client sends that candidate to the signaling server through Socket.IO:</p><pre>socket.emit(&quot;candidate&quot;, e.candidate);</pre><p>The signaling server can then relay it to the intended remote peer, allowing the two browsers to exchange their candidates.</p><blockquote><strong>2.4 Handling incoming remote media</strong></blockquote><p>Next, we register the ontrack event handler:</p><pre>pc.ontrack = (ev) =&gt; {<br>  console.log(&quot;add remote track success&quot;);<br>  remoteVideo.srcObject = ev.streams[0];<br>};</pre><p>This event is triggered when a remote media track is added to the peer connection. The handler assigns the associated remote stream to the remoteVideo element.</p><p>For example, once User B joins, completes the necessary negotiation, and sends media to User A, the incoming audio and video can be delivered through this peer connection. The ontrack handler allows User A&#39;s browser to display the remote stream and play its audio.</p><p><strong>Important:</strong> Registering this handler does not immediately display User B’s video. It prepares the browser to handle incoming remote media when it becomes available.</p><blockquote><strong>2.5 Adding User A’s local media tracks</strong></blockquote><pre>if (localStream) {<br>    const tracks = localStream.getTracks();<br>    for (let i = 0; i &lt; tracks.length; i++) {<br>      pc.addTrack(tracks[i], localStream);<br>    }<br>  }</pre><p>Here, getTracks() retrieves the audio and video tracks contained in User A&#39;s local stream. The for()loop iterates through them and adds each track to the peer connection using addTrack().</p><p>This tells WebRTC which local media tracks are available to be sent to the remote peer during negotiation.</p><p>For example, User A’s camera track and microphone track are added so they can be negotiated and sent to User B.</p><blockquote><strong>2.6 Sending the room join request to the signaling server</strong></blockquote><p>After obtaining the local media and creating the peer connection, the code executes:</p><pre>socket.emit(&quot;jo<br>in&quot;, {<br>  room: room,<br>  name: &quot;user&quot;,<br>});</pre><p>This is where User A explicitly requests to join the room.</p><p>The socket.emit() method sends a Socket.IO event named &quot;join&quot; to the signaling server. The accompanying object contains the room ID entered by the user and the user&#39;s name.</p><p>//server</p><pre>socket.on(&quot;join&quot;, (data) =&gt; {<br><br>  const roomId =<br>    typeof data?.room === &quot;string&quot; ? data.room.trim() : &quot;&quot;;<br><br>  const name =<br>    typeof data?.name === &quot;string&quot; ? data.name.trim() : &quot;&quot;;<br><br><br>  // Create the room if it doesn&#39;t exist.<br>  if (!rooms.has(roomId)) {<br>    rooms.set(roomId, new Map());<br>  }<br><br>  const roomUsers = rooms.get(roomId);<br><br>  // This example supports one-to-one calls only.<br>  if (roomUsers.size &gt;= 2) {<br>    socket.emit(&quot;join_error&quot;, &quot;This room is full.&quot;);<br>    if (roomUsers.size === 0) rooms.delete(roomId);<br>    return;<br>  }<br><br>  const existingUsers = [];<br>  for (const user of roomUsers.values()) {<br>    existingUsers.push(user);<br>  }<br><br>  roomUsers.set(socket.id, {<br>    id: socket.id,<br>    name: name || &quot;user&quot;,<br>  });<br><br>  socketToRoom.set(socket.id, roomId);<br><br>  socket.join(roomId);<br><br>  socket.emit(&quot;room_users&quot;, existingUsers);<br><br>});</pre><p>Let’s understand the server’s work step by step.</p><p>First, the server validates the request.</p><pre>if (!rooms.has(roomId)) {<br>  rooms.set(roomId, new Map());<br>}</pre><p>Here, rooms is a server-side Map that stores room IDs and their members. If the requested room doesn&#39;t exist, the server creates a new entry whose value is another Map for storing the room&#39;s users.</p><pre>const roomUsers = rooms.get(roomId);<br><br>  // This example supports one-to-one calls only.<br>  if (roomUsers.size &gt;= 2) {<br>    socket.emit(&quot;join_error&quot;, &quot;This room is full.&quot;);<br>    return;<br>  }</pre><p><strong>it checks whether the room is full.</strong> This example supports only two participants per room. If two users are already present, the server rejects the new request.</p><pre>const existingUsers = [];<br>  for (const user of roomUsers.values()) {<br>    existingUsers.push(user);<br>  }</pre><p><strong>it gets the list of existing users before adding the new user.</strong></p><p>This line is important because it records who was already in the room before the current user joined.</p><pre>roomUsers.set(socket.id, {<br>  id: socket.id,<br>  name: name || &quot;user&quot;,<br>});<br><br>socketToRoom.set(socket.id, roomId);<br>socket.join(roomId);</pre><p>The first line stores User A’s information in the room’s user map. The second records which room the socket belongs to. The third joins the socket to the corresponding Socket.IO room, allowing the server to send events to room members.</p><pre>socket.emit(&quot;room_users&quot;, existingUsers);</pre><p>The &quot;room_users&quot; event is sent to the user who just joined (user A). It contains the list of users who were already in the room (Empty here).</p><p>The client listens for the &quot;room_users&quot; event:</p><p>//client</p><pre>socket.on(&quot;room_users&quot;, (users) =&gt; {<br>  console.log(&quot;Existing users:&quot;, users);<br><br>  if (users.length &gt; 0) {<br>    setStatus(&quot;Peer found. Connecting...&quot;);<br>    createOffer();<br>  } else {<br>    setStatus(&quot;Waiting for another person to join...&quot;);<br>  }<br>});</pre><p>When <strong>User A is the first person to join</strong>, the server creates the room and adds A to it. Because existingUsers was collected before A was added, the server sends an empty array: [].</p><p>Therefore, users.length is 0, and the else block runs:</p><pre>setStatus(&quot;Waiting for another person to join...&quot;);</pre><p>The client does <strong>not</strong> call createOffer() because there is no existing peer to send an offer to. An SDP offer is intended to begin negotiation with a remote peer, so creating one before another participant is available would be premature in this application&#39;s flow.</p><p>When <strong>User B joins later</strong>, the server sends B a &quot;room_users&quot; event containing User A&#39;s information. Since B receives a non-empty list, B&#39;s client calls createOffer() to begin the WebRTC negotiation with A.</p><blockquote><strong>At the end of Step 2, the following has happened:</strong></blockquote><ol><li>User A has accessed their local camera and microphone.</li><li>User A can see their own video preview.</li><li>A WebRTC peer connection object has been created and configured with event handlers.</li><li>User A’s local media tracks have been added to that peer connection.</li><li>The client has sent a &quot;join&quot; request to the signaling server.</li><li>The server has created or located the room, recorded User A as a member, and returned the list of existing users.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRqWSvMnyxKKePLaN0hRkQ.png" /></figure><h3><strong>Step 3. </strong>User B Joins the Existing Room</h3><p>User B follows the same client-side sequence as User A. The browser accesses the camera and microphone, stores the media stream, creates a WebRTC peer connection, adds the local media tracks, and sends a &quot;join&quot; event to the signaling server.</p><p>However, <strong>this time, the room already exists</strong>, because User A created it earlier.</p><blockquote><strong>3.1 The server finds the existing room</strong></blockquote><p>When the server receives User B’s &quot;join&quot; event, it executes the following code:</p><pre>if (!rooms.has(roomId)) {<br>  rooms.set(roomId, new Map());<br>}<br><br>const roomUsers = rooms.get(roomId);</pre><p>Since the room already exists in the rooms map, the condition !rooms.has(roomId) evaluates to false. Therefore, the server does not create another room.</p><p>Instead, it retrieves the existing room’s user map, which already contains User A.</p><blockquote><strong>3.2 The server retrieves the existing users</strong></blockquote><p>Next, the server executes:</p><pre>const existingUsers = [];<br>  for (const user of roomUsers.values()) {<br>    existingUsers.push(user);<br>  }</pre><p>this creates an array containing the users who were already in the room before User B joined.</p><p>Since User A is already there, the array contains User A’s information:</p><pre>existingUsers = [<br>  { id: &quot;userA_socket_id&quot;, name: &quot;user&quot; }<br>];</pre><p>The server then adds User B to the room:</p><pre>roomUsers.set(socket.id, {<br>  id: socket.id,<br>  name: name || &quot;user&quot;,<br>});</pre><pre>socketToRoom.set(socket.id, roomId);<br>socket.join(roomId);</pre><p>At this point, both User A and User B are members of the same signaling room.</p><blockquote><strong>3.3 The server sends the existing-user list to User B</strong></blockquote><p>After adding User B, the server executes:</p><pre>socket.emit(&quot;room_users&quot;, existingUsers);</pre><p>This sends the &quot;room_users&quot; event to User B, containing the list of users who were already present in the room.</p><p>On User B’s browser, the following client-side event handler receives that list:</p><p>//client</p><pre>socket.on(&quot;room_users&quot;, (users) =&gt; {<br>  console.log(&quot;Existing users:&quot;, users);<br><br>  if (users.length &gt; 0) {<br>    setStatus(&quot;Peer found. Connecting...&quot;);<br>    createOffer();<br>  } else {<br>    setStatus(&quot;Waiting for another person to join...&quot;);<br>  }<br>});</pre><p>This time, users.length &gt; 0 evaluates to true because the list contains User A.</p><p>Therefore, User B’s browser executes:</p><pre>setStatus(&quot;Peer found. Connecting...&quot;);<br>createOffer();</pre><p>The status message changes, and createOffer() is called to begin the WebRTC negotiation with User A.</p><p>At the end of this step, both users have joined the same signaling room, and User B is ready to initiate the WebRTC offer/answer exchange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdYRrt-pyiD9TbKxUv71UA.png" /></figure><h3>Step 4: Offer/Answer Exchange</h3><p>Now that User A and User B have joined the same signaling room, User B’s client calls createOffer() because the &quot;room_users&quot; event returned a non-empty list.</p><p>The purpose of this step is to let both browsers negotiate the parameters required for their WebRTC connection. User B creates an SDP offer and sends it to the signaling server, which relays it to User A. User A processes that offer and responds with an SDP answer, which the server relays back to User B.</p><blockquote><strong>4.1 User B Creates an SDP Offer</strong></blockquote><pre>async function createOffer() {<br>  if (!peerConnection) return;<br><br>  try {<br>    const offer = await peerConnection.createOffer();<br><br>    await peerConnection.setLocalDescription(offer);<br><br>    socket.emit(&quot;offer&quot;, peerConnection.localDescription);<br>  } catch (err) {<br>    console.log(err);<br>  }<br>}</pre><p>User B’s browser executes:</p><pre>const offer = await peerConnection.createOffer();</pre><p>The createOffer() method generates an SDP offer describing User B&#39;s proposed WebRTC session parameters. This includes information such as the media sections, supported codecs, and other negotiation details.</p><p>The offer does not contain User B’s actual video or audio. Instead, it describes how the browsers can negotiate the exchange of media.</p><p>Next, the following line executes:</p><pre>await peerConnection.setLocalDescription(offer);</pre><p>This sets the generated offer as User B’s local session description. The browser uses it as part of the negotiation process.</p><p>Finally, User B sends the local description to the signaling server:</p><pre>socket.emit(&quot;offer&quot;, peerConnection.localDescription);</pre><p>This emits an event named &quot;offer&quot;, carrying the SDP offer as its payload.</p><p>At this point, User B has created and sent the offer to the signaling server. However, User A has not received it yet.</p><blockquote><strong>4.2 The Signaling Server Relays the Offer to User A</strong></blockquote><p>On the server side, the following function is used to relay signaling messages:</p><pre>function relayToPeer(eventName, outgoingEventName) {<br>  socket.on(eventName, (payload) =&gt; {<br>    const roomId = socketToRoom.get(socket.id);<br><br>    if (!roomId || !rooms.has(roomId)) return;<br><br>    const roomUsers = rooms.get(roomId);<br><br>    // Only relay if the sender is a member of this room.<br>    if (!roomUsers.has(socket.id)) return;<br><br>    // Forward only to the other socket in this room.<br>    socket.to(roomId).emit(outgoingEventName, payload);<br>  });<br>}</pre><p>The server registers this function for offers using:</p><pre>relayToPeer(&quot;offer&quot;, &quot;getOffer&quot;);</pre><p>Here, &quot;offer&quot; is the incoming event name, while &quot;getOffer&quot; is the outgoing event name.</p><pre>socket.to(roomId).emit(&quot;getOffer&quot;, payload);</pre><p>Because User A is the other participant in this one-to-one room, User A receives the &quot;getOffer&quot; event.</p><blockquote><strong>4.3 User A Receives the Offer and Creates an Answer</strong></blockquote><p>On User A’s client, the following listener handles the incoming offer:</p><pre>socket.on(&quot;getOffer&quot;, (sdp) =&gt; {<br>  createAnswer(sdp);<br>});</pre><p>When User A receives the &quot;getOffer&quot; event, the SDP offer is passed to createAnswer(sdp).</p><p>Here is the function:</p><pre>async function createAnswer(sdp) {<br>  if (!peerConnection) return;<br><br>  try {<br>    await peerConnection.setRemoteDescription(sdp);<br>    console.log(&quot;answer: set remote description success&quot;);<br><br>    const answer = await peerConnection.createAnswer();<br><br>    await peerConnection.setLocalDescription(answer);<br><br>    socket.emit(&quot;answer&quot;, peerConnection.localDescription);<br><br>    console.log(&quot;create answer&quot;);<br>  } catch (err) {<br>    console.log(err);<br>  }<br>}</pre><p>Let’s break it down.</p><p><strong>First, User A sets User B’s offer as the remote description:</strong></p><pre>await peerConnection.setRemoteDescription(sdp);</pre><p>Remember, this SDP was created by User B. Therefore, from User A’s perspective, it is the <em>remote description</em>.</p><p>This tells User A’s WebRTC peer connection about User B’s proposed session parameters so that User A can respond appropriately.</p><p><strong>Second, User A creates an answer:</strong></p><pre>const answer = await peerConnection.createAnswer();</pre><p>Based on the received offer and User A’s own media configuration, the browser generates an SDP answer describing the parameters User A is willing and able to use for the session.</p><p><strong>Third, User A sets the answer as its local description:</strong></p><pre>await peerConnection.setLocalDescription(answer);</pre><p>Now the answer becomes User A’s local session description.</p><p><strong>Finally, User A sends the answer to the signaling server:</strong></p><pre>socket.emit(&quot;answer&quot;, peerConnection.localDescription);</pre><p>This emits an &quot;answer&quot; event carrying User A&#39;s SDP answer.</p><p>At this point, User A has received User B’s offer, set it as the remote description, created an answer, and sent that answer to the signaling server.</p><blockquote><strong>4.4 The Signaling Server Relays the Answer to User B</strong></blockquote><p>Just as it relayed the offer, the server also relays the answer:</p><pre>relayToPeer(&quot;answer&quot;, &quot;getAnswer&quot;);</pre><p>This tells the server to listen for incoming &quot;answer&quot; events and forward their payloads to the other participant under the event name &quot;getAnswer&quot;.</p><p>When User A emits &quot;answer&quot;, the server verifies the room membership and forwards the answer to User B:</p><pre>socket.to(roomId).emit(&quot;getAnswer&quot;, payload);</pre><p>User B’s browser receives this event through the following listener:</p><pre>socket.on(&quot;getAnswer&quot;, async (sdp) =&gt; {<br>  if (!peerConnection) return;</pre><pre>  try {<br>    await peerConnection.setRemoteDescription(sdp);<br>  } catch (err) {<br>    console.log(err);<br>  }<br>});</pre><p>The received SDP answer is passed to:</p><pre>await peerConnection.setRemoteDescription(sdp);</pre><p>From User B’s perspective, this is the <em>remote description</em> because the answer was generated by User A.</p><p>Setting it tells User B’s peer connection that the remote side’s response to the original offer has been received and applied.</p><p>At this point, the offer/answer exchange has completed: User B has applied User A’s answer, and both peer connections have the other’s session description.</p><p>The signaling flow so far is:</p><ol><li><strong>User B creates an offer</strong> and sets it as the local description.</li><li><strong>User B sends the offer</strong> to the signaling server.</li><li><strong>The server relays the offer</strong> to User A as &quot;getOffer&quot;.</li><li><strong>User A sets the offer as its remote description</strong>, creates an answer, and sets the answer as its local description.</li><li><strong>User A sends the answer</strong> to the signaling server.</li><li><strong>The server relays the answer</strong> to User B as &quot;getAnswer&quot;.</li><li><strong>User B sets the answer as its remote description.</strong></li></ol><p>The offer/answer exchange establishes the agreed session parameters, but it does not by itself guarantee that the browsers can communicate over the network.</p><p>The next step is to exchange ICE candidates so that the browsers can discover and test possible network paths for the actual media connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mAoqzFdvsgA0XobuFl4ww.png" /></figure><h3>Step 5: ICE Candidate Exchange</h3><p>After the offer/answer exchange, User B and User A have exchanged their SDP descriptions. However, this does not guarantee that they can communicate directly over the network yet.</p><p>The browsers must discover and test possible network paths through which they can exchange audio and video. This is where <strong>ICE (Interactive Connectivity Establishment)</strong> comes into play.</p><p>ICE candidates describe possible network addresses and connection paths that a browser can use to reach the other peer. Both users gather their own candidates and exchange them through the signaling server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRny-yKesoQweSV7_dbb9g.png" /></figure><blockquote><strong>5.1 User B gathers and sends ICE candidates</strong></blockquote><p>Inside the createPeerConnection() function, we have the following event handler:</p><pre>pc.onicecandidate = (e) =&gt; {<br>  if (e.candidate) {<br>    socket.emit(&quot;candidate&quot;, e.candidate);<br>  }<br>};</pre><p>When the browser discovers a new ICE candidate for the peer connection, the icecandidate event fires.</p><p>The condition:</p><pre>if (e.candidate)</pre><p>checks whether the event contains a candidate. If it does, the browser sends that candidate to the signaling server using:</p><pre>socket.emit(&quot;candidate&quot;, e.candidate);</pre><p>Here, &quot;candidate&quot; is the Socket.IO event name, and e.candidate contains the ICE candidate information.</p><p>The browser may discover multiple candidates, so this event handler can run multiple times as candidate gathering progresses.</p><blockquote><strong>5.2 The signaling server relays the candidates to User A</strong></blockquote><p>On the server side, we register the following relay:</p><pre>relayToPeer(&quot;candidate&quot;, &quot;getCandidate&quot;);</pre><p>This uses the same relayToPeer() function that we used for the offer and answer exchange.</p><p>When the server receives a &quot;candidate&quot; event, it checks the sender&#39;s room membership and forwards the candidate to the other participant:</p><pre>socket.to(roomId).emit(&quot;getCandidate&quot;, payload);</pre><p>Since User A is the other participant in this one-to-one room, User A receives the candidate through the &quot;getCandidate&quot; event.</p><blockquote><strong>5.3 User A receives and adds the ICE candidate</strong></blockquote><p>On User A’s client, the following event handler receives the candidate:</p><pre>socket.on(&quot;getCandidate&quot;, async (candidate) =&gt; {<br>  if (!peerConnection) return;<br><br>  // If the remote description isn&#39;t set yet, hold the candidate for later.<br>  if (!peerConnection.remoteDescription) {<br>    pendingCandidates.push(new RTCIceCandidate(candidate));<br>    return;<br>  }<br><br>  try {<br>    await peerConnection.addIceCandidate(<br>      new RTCIceCandidate(candidate)<br>    );<br><br>    console.log(&quot;candidate add success&quot;);<br>  } catch (err) {<br>    console.log(err);<br>  }<br>});</pre><p>Next, it passes the received candidate to the WebRTC peer connection, allowing it to consider that candidate during ICE connectivity checks.</p><pre>await peerConnection.addIceCandidate(<br>  new RTCIceCandidate(candidate)<br>);</pre><blockquote><strong>5.4 User A and User B exchange candidates in both directions</strong></blockquote><p>The same process also happens in the opposite direction.</p><p>User A gathers ICE candidates and sends them to the signaling server. The server relays them to User B, and User B adds them to its own peer connection.</p><p>The complete exchange looks like this:</p><ol><li>User B discovers an ICE candidate and sends it to the server using &quot;candidate&quot;.</li><li>The server forwards it to User A using &quot;getCandidate&quot;.</li><li>User A adds the candidate to its peer connection, or queues it if the remote description is not yet set.</li><li>User A discovers its own ICE candidates and sends them to the server.</li><li>The server forwards those candidates to User B.</li><li>User B adds the received candidates or queues them until its remote description is ready.</li></ol><p><strong>The next step:</strong> The browsers perform ICE connectivity checks and attempt to establish a usable media path. Depending on the network conditions, this may use a direct connection or a TURN relay.</p><h3>Step 6: Establishing the WebRTC Connection and Receiving Media</h3><p>After the offer/answer exchange and ICE candidate exchange, both browsers have the information needed to attempt to establish a working network path.</p><p>However, exchanging ICE candidates does not automatically mean that a connection has been established. The browsers must perform ICE connectivity checks to determine which candidate pair can successfully communicate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*D1NUlXyXR_TxPizwDKucGA.png" /></figure><blockquote><strong>User A receives User B’s audio and video</strong></blockquote><p>Once negotiation and connectivity progress sufficiently, User B can send media through the peer connection.</p><p>Earlier, inside createPeerConnection(), we registered the following handler:</p><pre>pc.ontrack = (ev) =&gt; {<br>  console.log(&quot;add remote track success&quot;);<br>  remoteVideo.srcObject = ev.streams[0];<br>};</pre><p>This handler is responsible for processing incoming remote media tracks.</p><p>When User A’s browser receives a remote track, the ontrack event fires. The code then assigns the remote stream to the HTML video element:</p><pre>remoteVideo.srcObject = ev.streams[0];</pre><p>This allows User A to see User B’s video and hear their audio, assuming the stream contains those tracks and playback is permitted.</p><p>The same process occurs on User B’s side. When User A’s media tracks arrive, User B’s ontrack handler assigns the incoming stream to User B&#39;s remote video element.</p><p>Ok so finally its done.</p><p>This completes our walkthrough of a <strong>one-to-one WebRTC peer-to-peer (P2P) connection</strong> using Socket.IO for signaling. We started with User A connecting to the signaling server and creating a room, followed by User B joining the same room. User B then initiated the SDP offer/answer exchange, both browsers exchanged ICE candidates through the signaling server, and WebRTC attempted to establish a working network path for real-time audio and video communication. Once the connection was established, both users could receive each other’s media streams. This is the basic flow of a two-person P2P call. However, when more participants join a call, the architecture becomes more complex because each participant in a mesh P2P setup needs a separate peer connection with every other participant, which increases the network and processing load. This is one of the reasons larger group calls often use a <strong>Selective Forwarding Unit (SFU)</strong> architecture instead.</p><p>(if you need the full code, dm)</p><p>thanks for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25d7d0b6d4c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Greeks: Gods of the Options Market]]></title>
            <link>https://medium.com/@royanshu.main/the-greeks-gods-of-the-options-market-d70487b0b436?source=rss-f35320fb6397------2</link>
            <guid isPermaLink="false">https://medium.com/p/d70487b0b436</guid>
            <category><![CDATA[quant]]></category>
            <category><![CDATA[derivatives]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[options-greeks]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Anshu Roy]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 16:53:46 GMT</pubDate>
            <atom:updated>2026-04-18T17:02:11.486Z</atom:updated>
            <content:encoded><![CDATA[<p>Option trading is kind of a bet where people buy the right but not the obligation. But have you ever thought, is it really so simple to make profits in option trading? You have heard many places that option trading is way too dangerous than what it actually seems. Here profits and losses both can be massive. One loss can clear almost all of your profits made here, it is that risky. So you might think, is there a hack or a trick to know the market better so that the risk becomes minimum?</p><p>You have already read about the Black Scholes formula, how the 5 important factors determine the option pricing. But did you think about how sensitive each factor was to the option pricing? This measurable sensitivity of those 5 factors can actually be very helpful in determining the risk based on how the market behaves.</p><p>Those are called the Greeks, and they emerged along with the Black Scholes Model in 1973.</p><h4>History of the Greeks</h4><p>Greeks are numbers linked to each of the input factors that we feed into the Black Scholes formula and tell us how sensitive each one is to the option pricing.</p><p>Initially when the Black Scholes model came up in 1973, it was only in papers, meaning these terms were only known to the quants and PhDs of that time. They were the only ones having an understanding of these terms.</p><p>As time passed by, the big investment banks of Wall Street started hiring quants and PhDs to apply those academic financial models into their trading desks and bring those models into the real trading world. They started using those Greeks to understand the risks in depth. Till then, regular people had no access to these. It was just for elite institutions and big banks.</p><p>Slowly, professional computer systems started coming onto the desks of these elite organisations and there was no more need for PhDs. Machines were now doing all the automated calculation of the Greeks for their trading desks.</p><p>By 2010, options could be traded by sitting at home by anyone. Greeks started being displayed to every person out there through trading websites and apps.</p><p>Greeks went from being inside academic papers to something self taught traders were learning on YouTube and forums.</p><h4>The 5 Greeks in Option Trading</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9g0HVnV1vx-U15LGo9VsbQ.png" /></figure><h4>Delta</h4><p>Delta is a number which ranges between -1 and 1. This number tells us about the change in the option price due to a $1 change in the price of the stock.</p><p>So it is like saying: “If the stock moves $1, how much does my option move?”</p><p>Now let us understand how it helps in knowing the market.</p><p>Assuming you have a call option. For a call option, delta is between 0 and 1.</p><p>Let us say the stock is at $100 and the strike is $100 as well, which is ATM. Let us say the amount you paid as a premium to purchase that contract is $2. Now the stock price rises up to $101. The question is how will that option price change. I am talking about the price of that contract that you paid $2 for earlier. Will it remain the same? No it will not. Because we know that changing any of the 5 input parameters results in the change of option pricing, but the question is how much. That how much is answered by delta simply. Let us say delta is 0.5 here. So you can get the change in option price just by multiplying this delta with the change in the stock price, which is 1 here. So 0.5 is the change in the option price and the option price would now increase to $2.5. If the stock has become $150 then the increase would simply be 0.5 x 50 which is 25, so the final option price would be $27.</p><p>Now one might think how can this be helpful to know.</p><p>See, option trading is not just about making profits by exercising the contracts. Rather 95 percent of the traders make their profits by trading those contracts. By knowing delta, one can know how much that contract’s option price may rise in the upcoming future and can then simply trade that contract by selling it to someone else at a higher price.</p><p>The second thing delta tells us is the probability of that stock rising significantly above the strike price. Yes, it is the N(d1) term appearing in the main Black Scholes formula.</p><p>And one more reason I assumed delta as 0.5 here is because that is what the value of delta will be in our assumed example. The stock was at $100 and the strike was $100 as well. So if we think in terms of N(d1), the chances of it rising is 50/50, thus 0.5. If the stock was at $100 and the strike was $130 then the delta would not be 0.5, rather it would be less than that, around 0.3. Why? Because it is unlikely for that stock to cross $130 as compared to the previous case where the stock was already at the strike price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gGnOb6dUtN2uGPNp1scsw.png" /></figure><p>Look at this graph. It is for a call option. Look carefully, here the stock and the strike price are the same, thus delta here is 0.5 and you can see how it grows or falls as we change the stock price.</p><p>If the stock price falls, delta would fall as well. Why? Because then the stock would be at a lower value than the strike and it would be much more unlikely for that stock to cross that strike.</p><p>Similarly if the stock rises, delta will increase and move towards 1. Why? Because the stock has now already surpassed the strike and the chances of the stock making a significant rise from the strike has increased much more from when the stock was at the ATM level. Thus the option has gained value here.</p><p>This is how delta works in depth. You can use it to know how much the value of that option might increase in the future, or in other words how likely that stock is to return profits.</p><h4>Gamma</h4><p>Gamma is simply how delta is changing with respect to a $1 change in the stock price. It is not how the option price is changing, it is delta itself that is changing.</p><p>Delta is not a constant. It keeps on changing as the stock price changes. The rate of change of this delta with respect to the stock price is Gamma.</p><p>Assume the same example. Stock is at $100 and strike is $100. You pay $2 for buying that contract. Delta here is 0.5.</p><p>Now stock rises to $101. Option price becomes $2.5. Now stock price rises again by $1 and becomes $102. Will delta in this case be 0.5 as well? No it will change. Look at the graph we discussed in the delta part. Delta is 0.5 only in the ATM case. If the stock is above the strike then delta is above 0.5. So here let us say delta would have become 0.6. So this time the option price will not increase by 0.5, rather it will increase by 0.6. So option price becomes $2.5 + $0.6 which is $3.1.</p><p>So here delta actually rose from 0.5 to 0.6, meaning the change in delta is 0.1. So gamma here is 0.1.</p><p>But to be more precise, even gamma is not constant.</p><p>Let us say the stock now becomes $103. You cannot say that delta will increase by 0.1 this time as well, making delta 0.7 and option price $3.8. That would be wrong.</p><p>Look at the graph below. This is how gamma changes with the stock moves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxzvcZTEP6gSl9wbJZRtpA.png" /></figure><p>The rate of change of gamma with respect to the stock price is maximum when the stock value is at the strike. As we move away in both directions, the rate of how delta changes decreases. Delta will change significantly in the middle and slowly as we move away.</p><p>Why? To understand this we have to go back to the delta vs stock move graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvOjPBdrHvb1gBoedkukcw.png" /></figure><p>Gamma is not constant because the change in delta is not linear. The slope of this line keeps on changing, it first increases then decreases, which is the gamma itself. So the core question is not why gamma is constant, it is why delta is not changing linearly.</p><p>The reason is simple. In the stock market, we assume stocks follow a log normal distribution. We will not be going into much depth here.</p><p>When you buy an option, gamma gives you a very unfair advantage in the best possible way. If the stock moves in your favour, your profits keep accelerating with every dollar and you make more than you would expect. If the stock moves against you, your losses slow down with every dollar and you lose less than you would expect.</p><h4>Theta</h4><p>Theta is a number by which the option price falls as the time to expiry approaches, given that all other factors are constant.</p><p>It tells us how much the option price will be falling each day as expiry comes near. The change in theta over days is not constant. Theta increases as we keep approaching the time to expiry, and that too not linearly. Theta is also a negative number since it represents a decrease in the option price.</p><p>We know that the reason for the decreasing option value is simply because time is everything here. More the time, more the chances of that stock crossing that strike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*886BdwgGEuffkf3GVKpU4g.png" /></figure><p>But why does it accelerate more towards expiry? The reason is simple. When there is enough time there is high uncertainty. Anything can happen till expiry, so there are more chances of winning and theta decreases slowly. But as we come close to expiry, we are sure nothing much can happen now, thus theta decreases significantly day by day till expiry.</p><h4>VEGA</h4><p>Vega is a number that tells us the change in the option price due to a 1% change in the implied volatility of the stock.</p><p>You might think what is implied volatility. So there are generally two types of volatility we talk about.</p><ul><li>Historical Volatility tells us about how wild the stock has behaved on a daily basis in the past. By past it can mean last 30 days, 60 days or even 90 days. So this kind of volatility is linked with the overall past behaviour in that duration.</li><li>Implied Volatility is about how the stock is going to behave in the future. To be precise, it is the expected behaviour of that stock. This volatility is decided by the market and we get it by reverse engineering the Black Scholes model using the option price governed by the market.</li></ul><p>So vega is about the implied volatility one.</p><p>Let us say a stock is at $100 and the implied volatility is 15%. You paid $2 as the premium. Now a big event is announced, let us say the budget is announced next week. Because of this event announcement, the volatility rises to 30%. Now let us say vega is 1. So what does this 1 actually mean here? It is saying the increase in the option price due to a 1% increase in the implied volatility. So here in our example it got increased by 15, so 1 x 15 becomes 15. A rise of $15 is observed in the option price so it becomes $17.</p><p>You can see here that the stock did not move in this example. Just a small event announcement caused the price of the option to rise. That event did not even happen, it just brought uncertainty and panic among the market players.</p><h4>Rho</h4><p>Rho measures how much your option price changes when interest rates change by 1%. It is the least talked about Greek among traders and for good reason. For short term options like weekly or monthly expiries, rho is almost negligible. The effect of a 1% interest rate change on a short dated option premium is so small that delta, theta and vega completely overshadow it on any given trading day.</p><p>Call options have a positive rho, meaning they gain slightly when interest rates rise. Put options have a negative rho, meaning they lose slightly when interest rates rise. The logic is that higher interest rates make it cheaper to control a stock through an option rather than buying it outright, which adds a small amount of value to calls.</p><p>Rho only starts to matter meaningfully when you are dealing with long dated options, sometimes called LEAPS, that expire a year or more into the future. Over such a long horizon, even a small shift in interest rates can compound into a noticeable change in the option price. But for most retail traders doing short term trades, rho is simply background noise and can safely be kept at the back of your mind.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d70487b0b436" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 5 input parameters that drives the Pricing of Options in Black Scholes Model.]]></title>
            <link>https://medium.com/@royanshu.main/the-5-input-parameters-that-drives-the-pricing-of-options-in-black-scholes-model-60dcfaf0e497?source=rss-f35320fb6397------2</link>
            <guid isPermaLink="false">https://medium.com/p/60dcfaf0e497</guid>
            <category><![CDATA[black-scholes-model]]></category>
            <category><![CDATA[volatility]]></category>
            <category><![CDATA[quant]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[options-trading]]></category>
            <dc:creator><![CDATA[Anshu Roy]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 17:07:02 GMT</pubDate>
            <atom:updated>2026-04-17T17:07:02.301Z</atom:updated>
            <content:encoded><![CDATA[<p>As we have already discussed what the Black Scholes Model actually is and how it is formulated, there is still remaining on my side to explain how those 5 factors actually influence the changes in option pricing and how they are fed into the Black Scholes Model to return option pricing.</p><p>The 5 input factors were:</p><ol><li>Stock Price (Spot Price)</li><li>Strike Price</li><li>Interest Rate</li><li>Time to Expiry</li><li>Volatility</li></ol><p><strong>1. Stock Price (S)</strong></p><p>The stock price alone is not a deciding factor in the Black Scholes formula, rather it is the ratio of S and K (S/K) which determines the change in the price of the options, so it is a relative ratio between the stock price and the strike price.</p><p>Let’s say we increase the stock price, how does the call option pricing change? Firstly, as we increase S, the ratio S/K will increase, and thus ln(S/K) will increase which will result in the overall increase of both d1 and d2, and thus N(d1) and N(d2) will also increase, meaning that both of these will approach more towards 1. Looking at the formula of Call option pricing, increasing S will increase both on the left side, S and N(d1). Thus the left side will increase. Now talking about the right side, no doubt N(d2) will increase here but K is a constant in the right term, so overall the left side will increase more than the right side and thus overall the option pricing will increase.</p><p><strong>2. Strike Price (K)</strong></p><p>Similar logic applies with K, just with the opposite behaviour. Increasing the strike price will lower the call option pricing. This makes perfect sense because if the stock price today is $80 and you keep a large strike price of $150 (almost double the spot price) and only 2 days are remaining for the contract to expire, then there is hardly any chance for you to win that bet and make a profit. Thus this algorithm will lower that option price a lot and you will hardly pay any amount for it, for example the option price here will be around $0.02. To explain this I have assumed that other factors except K are constant and not changing, because obviously option pricing is governed by all 5.</p><p><strong>3. Risk Free Interest Rate (r)</strong></p><p>So what is this now. To conclude fast, as this increases, the option price increases as well. Why and how? We know that in option trading, if you are buying a contract betting that a stock might rise a lot in the future, you pay a small premium for that today. Unlike stock trading, you do not need to buy those shares today with the money that you have. That is what option trading is, you bet that if this comes true, you will be buying that stock later at the strike price, with no need to pay now for those stocks today. So here you are just using your premium money today. If you think intelligently, you can actually invest that money somewhere else and earn profits as well, here to be more precise in a risk free environment where investments are safe, for example in government bonds. So from the seller’s point of view, they are seeing that you are having an advantage here. The more the expiry date is away from you, the more time you have to grow that idle money. Thus they tend to increase the call option price. To understand this from the formula, if you carefully look at it, the increase in r increases d1 and d2 and thus the probabilities. Both increase in the main Black Scholes call option formula, but you can notice there is one more place where r appears, which is in the main formula e^(-rT). As we have previously discussed, this accounts for the time value of money, converting the future price that we will be paying as the strike price to today’s value. So increasing r will overall decrease this term, thus decreasing the right hand term of the main formula, and thus the overall call option price will increase.</p><p><strong>4. Time to Expiry (T)</strong></p><p>Time to expiry means the time till the contract is valid and you have the right to buy that stock at that strike price (assuming you have made a long call here). So how can time influence option pricing? Obviously these factors are considered because we want options to be of a fair price so that both sides of the game have chances to win. Think of it this way, more time means more chances of possible scenarios that can happen with the stock. The stock you have bet on has more time and chances to cross that strike. Thus if we think casually, more time will result in a higher price of the option, which actually makes sense.</p><p>If we look into the formula, increasing T will result in the overall increase of d1 and d2 and thus the probabilities. Also T appears in the main formula on the right term e^(-rT). The same logic applies as with r. More T will result in the term e^(-rT) decreasing, so no doubt N(d1) and N(d2) will increase, but the left term will increase more, so overall the call option price will increase. If we decrease time, there is less time for the stock to cross that strike, given that other factors are constant.</p><p><strong>5. Volatility (Sigma)</strong></p><p>Volatility means how erratically the stock behaves over time. To be more precise, how abruptly the stock price moves on a timely basis. The more volatile the stock is, the more chances of it crossing the strike price. A normal smooth behaviour of the stock price may not change much in the future, but a volatile stock can mean anything. Thus more volatile stocks have higher option pricing.</p><p>From the formula, if you look closely, increasing sigma will increase d1 or cause no change in d1, but will decrease d2. So increasing sigma creates a gap between these two. Thus N(d1) will increase or will not change much, but N(d2) will decrease, and thus the call option price will increase. Also if we look at it from the seller’s point of view, obviously they are seeing that the player on the opposite side has more chances of winning the bet due to high volatility, so obviously they will be charging higher premiums. That is how these 5 factors govern option pricing using the Black Scholes formula.</p><p><strong>The assumptions of Black Scholes are as follows:</strong></p><ol><li>Volatility is constant and fixed over time.</li><li>Interest rates are assumed to be constant and known over the option’s life.</li><li>Stock prices follow a Log-Normal Distribution.</li><li>No Dividends.</li><li>European Options Only.</li></ol><p><strong>In our later upcoming blogs, we will be seeing what the limitations of Black Scholes are and whether these assumptions really account for everything happening in the real market.</strong></p><p><strong>Does Black Scholes still being used today?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60dcfaf0e497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the Black Scholes Model?]]></title>
            <link>https://medium.com/@royanshu.main/what-is-the-black-scholes-model-f38b8ac7156f?source=rss-f35320fb6397------2</link>
            <guid isPermaLink="false">https://medium.com/p/f38b8ac7156f</guid>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[black-scholes-model]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Anshu Roy]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 14:23:46 GMT</pubDate>
            <atom:updated>2026-04-17T14:23:46.352Z</atom:updated>
            <content:encoded><![CDATA[<p>In options trading, we know that we have to pay or receive an amount known as the premium when we buy or sell a contract. Who decides that price? Because you can’t just bet on a random amount. Many factors need to be considered. Who does that, and how?</p><p>First of all, what is the option price actually? Let’s say a stock of a company is running at $80 and you think that the stock price might rise a lot in a few weeks, so you buy a long call option contract with a strike price of $90. Now, the stock price might either rise or fall below $80 in the upcoming future. So what actually decides how much you have to pay now to buy that contract, which gives you the right to buy those virtual shares at a price of $90 if the stock price rises above $90? There are many factors that actually influence this price.</p><p>Before 1973, it was all guesswork. There was no proper formula or way to calculate that price, because of which people used to overpay or underpay that premium. In 1973, three scientists worked on this problem and found a way to price these options. They named their formula the Black Scholes Model. Here, “Model” does not mean a mathematical Machine Learning algorithm; rather, it is just a simple formula which takes inputs and gives the option price as the output. According to this model, option pricing depends on 5 major things:</p><ul><li>Stock Price (Spot Price)</li><li>Strike Price</li><li>Interest Rate</li><li>Time to Expiry</li><li>Volatility</li></ul><p>Lets have a look at what the Black Scholes Model actually is and what is means.</p><h4>The Main Black Scholes Formula</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*FTITfHD8EARPcHpw2rX7cQ.png" /><figcaption>The Main Black Scholes Formula</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*Dvtn99yqzhjn9dsVm5uBoA.png" /><figcaption>Value of d1 and d2</figcaption></figure><p>Lets understand this firstly for a call option, then we will look at how things changes when we deal with a put option.</p><p>Ok, before going deep into this formula, what do you think how an option should actually be priced? Let’s say the stock is at $80 today, the strike you kept is $90 and the expiry is in 1 week. What do you think, how much option price should you pay today and how should that amount change as the expiry of that contract comes near, or if any other factor changes that influences this price? Actually the formula is divided into 2 parts. The left one tells what you will receive (the stock) and the right side tells what you will pay (the strike). Now, we aren’t sure whether the stock will actually cross the strike, so you might think how can we actually determine the option price today. If the left and right side actually mean that, then if we look at it in terms of present value, the stock today is $80 and the strike we kept is $90, so if we simply subtract those 2, don’t you think the option price will simply be a negative number? The formula is designed in such a way that it can never be zero or negative. So that is the reason Black Scholes says that we need to multiply these stock and strike prices with some weight, which is the cumulative probability density itself.</p><h4>The left side — S₀N(d₁)</h4><p>This part represents what you stand to receive if the option pays off, which is the stock. But since the stock does not always cross the strike price, we cannot just use the full stock price. So we multiply it by N(d₁), which accounts for two things together: the probability that the stock will cross the strike, and given that it does, how significantly it is expected to rise above it. Think of it as asking: “If we win, how much do we win?” This is why N(d₁) is always a number greater than N(d₂).</p><h4>The right side — Ke^(-rT)N(d₂)</h4><p>This part represents what you will pay, which is the strike price K. But again, you only pay the strike if the stock has actually crossed it and the trade is in your favour. So we multiply K by N(d₂), which is simply the probability that the stock price will be above the strike on the expiry date. The extra term e^(−rT) is there because you are not paying the strike price today. You would be paying it sometime in the future, so we discount it back to today’s value to account for the time value of money.</p><h4>Difference between N(d₁) and N(d₂)</h4><p>You might think what’s the actual difference between these 2. They almost seemed to be the same right, how are they different then?</p><p>So N(d₂) was simple, it was saying the chances of the stock being at a higher value than strike at the expiry date.</p><p>But N(d₁) accounts for much more than that, here we assume that the condition of the stock crossing the strike is already true. Kind of Conditional Probability and given that we account for the chances of how significantly that stock rises above that strike. So its like saying giving that we will be winning, how much will we win? So this number is actually always greater than N(d₂).</p><p>To understand it better lets take an example.</p><p>Let’s say:</p><ul><li>Stock price S₀ = $100</li><li>Strike price K = $105</li><li>N(d₁) comes out to 0.6</li><li>N(d₂) comes out to 0.45</li><li>Ke^(-rT) after discounting = $103 (just an example)</li></ul><p>Then:</p><p>Benefit side = 100 × 0.6 = <strong>$60</strong> Cost side = 103 × 0.45 = <strong>$46.35</strong></p><p>Call option price C = 60–46.35 = <strong>$13.65 per share</strong></p><p><strong>The Whole Formula In One Sentence:</strong></p><p>The fair price of a call option is the expected value of the stock you will receive if things go well, minus the expected present value of the strike price you will have to pay, both weighted by their respective probabilities of actually happening.</p><p>This was all for the call option side. Now let’s see what changes when we look at a put option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*JY09Te548BS58lFvfLWpwA.png" /><figcaption>Option Price for Call and Put Option</figcaption></figure><p>For a put option, the whole formula gets reversed. Why? Because in a put option we are betting that the stock will fall below the strike price. We buy a contract that gives us the right to sell that stock at a strike price which is above the current stock price. The stock needs to fall below the strike for the trade to be in our favour. So in this case, the left side represents what we receive (the strike price) and the right side represents what we pay (the stock price).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*Dvtn99yqzhjn9dsVm5uBoA.png" /><figcaption>Value of d1 and d2</figcaption></figure><p>This is it for this part. In the next blog, we will continue in detail with how those 5 previously discussed factors influence option pricing, and we will also be going deep into the formulas for d₁ and d₂.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f38b8ac7156f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Call and Put Option in Options Trading (For Beginners)]]></title>
            <link>https://medium.com/@royanshu.main/call-and-put-option-in-options-trading-for-beginners-050945b4ce67?source=rss-f35320fb6397------2</link>
            <guid isPermaLink="false">https://medium.com/p/050945b4ce67</guid>
            <category><![CDATA[options]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[call-and-put-options]]></category>
            <category><![CDATA[stock-trading]]></category>
            <dc:creator><![CDATA[Anshu Roy]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 16:40:01 GMT</pubDate>
            <atom:updated>2026-04-16T16:40:01.640Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will be understanding a few financial trading terms in simple language that cover the backbone of option trading. In order to excel in option trading, a good grasp of these fundamental terms is a must and will help in understanding the whole thing about option trading.</p><p>We have discussed in our last blog about what option trading actually is and had an idea about it in terms of real estate. But now we’ll be advancing towards the actual option trading world, trading itself.</p><p>Let’s say there’s a stock at a current spot price of $80 of Wells Fargo Company (WFC). Now let’s say we don’t have the money right now to buy the shares, or let’s say we have it but are thinking about making extra profits somehow by betting on the market. We can bet the system here in 2 ways.</p><p>Either we can bet that the stock will rise a lot, or we can bet that the stock will fall a lot. By betting both ways, we can earn profits in option trading. In option trading, we don’t actually pay the whole amount like in stock trading. For example, in stock trading, we would simply buy the shares by paying the full $80. But in option trading, we have to pay just a small portion known as the option price, which depends on several important market factors and is governed by market sentiment.</p><p>So let’s finally start as if we are doing it right now. The stock is at $80, and let’s say we want to bet that it will rise a lot. What we will do is first pay a small portion while buying the option, and we will set a Strike Price. So what is a strike price? It’s actually the target value which we think the stock will surely be crossing in the upcoming future before the expiry date of our contract. So let’s say the strike price we keep is $90. We are kind of sure today that in the future the stock will surely rise above $90. We have successfully bought a contract here which states that we have the right to buy this stock at $90 in the upcoming future, even if the stock price rises above $90.</p><p>So how do we actually make a profit here? Let’s say the market was very volatile and in just 2 days the stock’s price rose to $100. Now, let’s say during buying this contract we had paid a premium of $2. The stock price is now $100, and if we assume we had a bet to purchase a single quantity of stock at $90, meaning a single stock of WFC, and today it’s $100, then our profit would be ($100 — $90) minus $2, giving us a profit of $8, but only if we exercise the contract, meaning close the contract.</p><p>But obviously, it’s not compulsory that the market will always be on our side. What if the stock price had remained constant till the expiry date, or had fallen by then? Let’s discuss that.</p><p><strong>Remained Constant:</strong> If the stock price had not moved, we had 2 options till the expiry date. Either trade that contract with someone else, essentially selling that risk to someone else, or just wait till the expiry date and lose the premium of $2 that we had paid for this contract. As we have already discussed in our previous blogs, in options trading it’s not compulsory to close the deal. You can just wait till expiry and lose your premium with no return.</p><p><strong>Fallen below $100:</strong> If the stock price had fallen, we would again have the 2 options discussed above, because obviously no one wants to close a contract deal at a loss. Here, the maximum loss one can have is just the premium paid at the start.</p><p>Now, the example discussed above was a Call option, specifically a Long Call option.</p><p>In option trading, we have a total of 4 types of choices:</p><ol><li>Long Call</li><li>Short Call</li><li>Long Put</li><li>Short Put</li></ol><p>CALL means having the right to buy an underlying asset. PUT means having the right to sell an underlying asset. Long and Short are the actions. Long means buying a contract and Short means writing/selling a contract.</p><p><strong>LONG CALL</strong></p><p>Here, we were buying a long call option, meaning we were buying a bet where we assumed that the stock price would rise, so profit was governed by the assumed rise in stock price. That’s why we called it a Call option. In the case of a put option, we bet that the stock price would fall and make profits governed by the fall of the stock price. It’s called Long because here we aren’t writing a new contract ourselves. Rather, we are the ones who are willing to buy contracts, and we are the ones who pay the premium while buying.</p><p><strong>SHORT CALL</strong></p><p>Here, we are not the buyers. We act as the people on the other side of the trade, the ones who write or sell a contract to buyers. Obviously, profits can be made on both sides; it depends on who predicts the market well. Here you sell a contract to the buyers, and you are the ones who collect the premium. Let’s discuss it in depth.</p><p>Let’s say the stock price of WFC is again $80 and a buyer wants to buy a call option contract with a strike price of $90. If you want to make a profit, you would not want the price of the stock to rise above $90, because if that happens you will be the one who has to pay out their earned profits. Let’s say the stock price rises to $100 and the premium they had paid you was $2. Now they want to close the contract. They are at a net profit of $8 ($100 — $90 minus $2 from their point of view). From your point of view, they have paid you $2 already, but now you have to pay them the $8 they are making while closing the contract.</p><p>So when you actually do a short call, the broker locks this estimated margin money. In short calls, the seller’s loss can be unlimited because these contracts work at lot sizes, not single shares. People buy contracts in lots, for example 1 lot can have 1,000 shares of WFC, so losses for the seller here can be huge, and obviously the profit on the buyer’s side can be huge as well. That’s why option trading is considered dangerous. For the seller, the maximum profit they can make is just the premium that people pay them.</p><p>You might wonder then why people go for a short call. Because most of the time it’s hardly possible for a stock to be so volatile and cross strike prices, so sellers make huge profits from the premium itself. But the thing is, one loss can wipe out all the earned profits at once.</p><p><strong>LONG PUT</strong></p><p>Now let’s say you want to bet on the market, but this time you want to bet that the price of the stock will fall a lot. What you actually do here is buy a contract which states that you have the right to sell a share at the strike price if the stock falls below it. For example, let’s say the same WFC stock falls to $60 from $80, and the strike price you kept while buying the contract was $70. You are saying that you have the right to sell at $70, even if the price falls any amount below it, whether it be $40, $30, or any price below. You do this by first paying a premium.</p><p>Let’s say you pay a premium of $20 this time with a strike of $70, and the stock falls to $40. If you sell that stock at $70, you will have a net profit of $10 ($70 — $40 minus the $20 premium). By the way, these numbers are just being used to help you understand. In real markets, these happen in large amounts.</p><p>And yes, in scenarios where the stock won’t fall, you can either trade that contract or just wait and lose the premium you paid earlier. So yes, the maximum loss one can have in a long put is the premium itself, unless you agree to sell at a net loss, which obviously no one would.</p><p><strong>SHORT PUT</strong></p><p>Here, you are the one selling/writing the contract. You aren’t the one with the right to sell at the strike price. Instead, you are the one selling the contract and agreeing to pay the profit to the person on the other side if they win the bet. Simply put, you are on the other side of the game from the people who want to bet that the stock will fall. As a seller of the contract (not the stock), you want the stock price to rise so that you win this game against the put buyers.</p><p>Taking the same scenario as above, where the net profit of the put buyer was $10, this amount would be paid by you as the contract seller. This margin amount will be locked when you create the contract. And here as well, as a contract seller, the maximum profit you can make is just the premium that the put buyer pays you, while the loss can be unlimited.</p><p>That’s all for this blog. I tried my best to keep things as simple as possible for someone who is new to these terms and can’t differentiate between them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=050945b4ce67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Option Trading (For Beginners)]]></title>
            <link>https://medium.com/@royanshu.main/option-trading-for-beginners-e692eca475fe?source=rss-f35320fb6397------2</link>
            <guid isPermaLink="false">https://medium.com/p/e692eca475fe</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[options-trading]]></category>
            <dc:creator><![CDATA[Anshu Roy]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 12:31:47 GMT</pubDate>
            <atom:updated>2026-04-16T12:31:47.507Z</atom:updated>
            <content:encoded><![CDATA[<p>Almost everyone has heard about stock trading, where you can buy or sell shares of a company or an index in real time, meaning the transaction happens instantaneously at that very moment.</p><p>But I think you’ve rarely heard about futures and options. It’s not normal trading. Here, you actually have something like an insurance policy on a bet you think might play out. For example, what is insurance in the first place? Having insurance means paying a frequent monthly amount to cover some risk you think might happen in your future. And if something bad does happen, the insurance company pays out that whole amount on your behalf, covering hospital bills, flight tickets, hotel bills, etc. Options trading works in a very similar way. Let’s understand how it works overall.</p><p>Let’s take an example. An option is essentially a kind of bet. You place a bet with the system and pay some amount for them to consider it valid. If you win that bet, you make profits. But if you lose, you only lose the money you paid as a premium, nothing more.</p><p>Assume you want to buy a home in Mumbai but don’t have the money right now. You plan to buy it sometime in the future once you have the funds. As someone who understands the market, you know that the price of that house will rise over time. Let’s say the house owner is an old person who doesn’t have much knowledge of how the market works and isn’t thinking too hard about it. He just wants instant money and his only goal is to sell the house.</p><p>Knowing how the market works, you go to that person and tell him you plan to buy the house after 5 years. The current price is ₹2 crore. Based on your research, you believe the price will rise to around ₹2.5 crore in 5 years, but the seller doesn’t know that. So you propose to him that you’ll buy the house later at ₹2.3 crore, and you pay him ₹5 lakhs right now as a commitment. From the seller’s perspective, he sees two big wins: instant money without actually handing over the house yet, and a buyer willing to pay ₹30 lakhs more than the current market price. He sees instant money and profit, so he agrees immediately and hands you the contract.</p><p>You, on the other hand, have intelligently set yourself up for a profit of around ₹15 lakhs. The expected market price will be ₹2.5 crore and your contracted price is ₹2.3 crore, so the gain is ₹20 lakhs. Subtract the ₹5 lakh premium you paid upfront and your net profit is ₹15 lakhs. On top of that, you can invest whatever remaining money you have elsewhere in the meantime, so either way you’re in a good position.</p><p>Now, you might wonder what if the house price doesn’t rise? What if it stays the same or even falls due to a market crash or some other reason?</p><ol><li><strong>Price stays the same at ₹2 crore.</strong> In that case, you’d be buying the same house 5 years later at ₹2.3 crore, which means you’re paying ₹30 lakhs more than its actual value. Add the ₹5 lakh premium you paid upfront and the total net loss comes to ₹35 lakhs. That’s massive. But in options trading, you’re not obligated to go through with the purchase. You can simply cancel the contract, and your net loss becomes only the ₹5 lakh premium you paid upfront.</li><li><strong>Price falls below ₹2 crore, say to ₹1.8 crore.</strong> Completing the deal now would mean paying ₹2.3 crore for a house worth ₹1.8 crore, which is a ₹50 lakh loss, plus the ₹5 lakh premium, making it a total net loss of ₹55 lakhs. In such a case, it’s always better to walk away from the deal and accept the ₹5 lakh loss instead.</li></ol><p>Options in the stock market work exactly the same way, just with stocks and indexes instead of real estate. There are two types of options one can trade: the <strong>Call Option</strong> and the <strong>Put Option</strong>. We’ll be covering those in the next blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e692eca475fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>