Java · TestNG
Stock trading with Selenium
A watchlist with prices that tick every second, market and limit orders with buying-power, holdings and price-band checks, a confirm step, and a portfolio with live P&L. Simulated — no real money.
App under test
📊 TradeX
- URL
- /apps/trading
- Login
- TX1001 / Trade@123
- Trading PIN
- 2468
- Starting cash
- ₹5,00,000
- Brokerage
- ₹20 / order
- Limit band
- ±10% of LTP
Scenarios to automate
Work top to bottom — each one adds a new technique.
- 1
Login + trading PIN
BeginnerClient ID + password (tx-login-id, tx-password, tx-login), then a 4-digit PIN (tx-code, tx-verify). Wrong details show attempts left in tx-login-error; 3 failures lock the form (tx-unlock).
- 2
Asserting live data
Intermediateprice-* changes every second — assert format (₹ + 2 decimals) or that it changed, never an exact value.
- 3
Search & watchlist
Beginnersymbol-search → add-<SYM> adds a watch-row; remove-<SYM> deletes it.
- 4
Quantity validation
Beginner0, decimals or text in order-qty show error-order-qty.
- 5
Buying power
IntermediateOrder more than cash allows; the error tells you the affordable quantity.
- 6
Limit band
IntermediateA limit price more than 10% away from LTP is rejected in error-limit-price.
- 7
Buy then sell
AdvancedBuy at market, then sell part of the holding; holding-qty-<SYM> and cash reconcile (with ₹20 brokerage).
- 8
Open limit orders
AdvancedPlace a limit order near LTP; it may fill on its own — poll order-status or cancel-<id> it.
- 9
Sell more than held
Beginnerside-sell with a quantity above your holding shows “You only hold N share(s)”.
Sample Selenium suite
A working starting point that finds elements every way Selenium can — by role, label, text, id, name, CSS, XPath and data-testid — so you practice them all. Pick your language, switch to data-testid only to compare, or try your own in the Locator Playground.
import org.testng.annotations.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.Map;
import org.openqa.selenium.support.ui.*;
import java.time.Duration;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;
// Locators in this suite: By.id ×3 · By.name ×1 · By.linkText ×3 · By.xpath ×6 · By.cssSelector ×1 · data-testid ×12
public class TradeXOrderTest {
static final String BASE = "https://www.practiceqaautomation.com";
WebDriver driver;
WebDriverWait wait;
// Small helpers: every action takes a By and waits for its element first (no Thread.sleep).
By tid(String id) { return By.cssSelector("[data-testid='" + id + "']"); }
WebElement ready(By by) { return centre(wait.until(elementToBeClickable(by))); }
void click(By by) { ready(by).click(); }
WebElement nth(String id, int n) { return centre(wait.until(numberOfElementsToBeMoreThan(tid(id), n)).get(n)); }
void clickNth(String id, int n) { nth(id, n).click(); }
// Scroll to the middle of the screen first: Selenium only scrolls an element to the edge,
// where a sticky header or a fixed bottom bar can cover it (ElementClickInterceptedException).
WebElement centre(WebElement e) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView({block: 'center', inline: 'nearest'})", e);
return e;
}
void type(By by, String text) { ready(by).sendKeys(text); }
void select(By by, String value) { new Select(ready(by)).selectByValue(value); }
void check(By by) { WebElement e = ready(by); if (!e.isSelected()) e.click(); }
void expectText(By by, String text) { wait.until(textToBePresentInElementLocated(by, text)); }
void expectVisible(By by) { wait.until(visibilityOfElementLocated(by)); }
void expectNthText(String id, int n, String text) {
wait.until(d -> d.findElements(tid(id)).size() > n && d.findElements(tid(id)).get(n).getText().contains(text));
}
@BeforeMethod
public void setUp() {
ChromeOptions options = new ChromeOptions();
// Turn off Chrome's "Save password?" and "password found in a data breach" pop-ups: after a
// login they take the keyboard and mouse away from the page, so later typing and clicks are lost.
options.setExperimentalOption("prefs", Map.of(
"credentials_enable_service", false,
"profile.password_manager_enabled", false,
"profile.password_manager_leak_detection", false));
driver = new ChromeDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@AfterMethod(alwaysRun = true)
public void tearDown() { driver.quit(); }
@Test
public void buysAndPartlySellsAStock() {
driver.get(BASE + "/apps/trading");
// Sign in first
type(By.id("tx-login-id"), "TX1001");
type(By.name("tx-password"), "Trade@123");
click(By.xpath("//button[normalize-space()='Continue']"));
type(tid("tx-code"), "2468");
click(By.xpath("//button[normalize-space()='Verify & continue']"));
expectVisible(tid("price-INFY"));
type(By.cssSelector("[aria-label='Search stocks']"), "tata m");
click(tid("add-TATAMOTORS"));
expectVisible(tid("price-TATAMOTORS"));
click(tid("trade-INFY"));
wait.until(urlContains("/apps/trading/trade/INFY"));
click(By.xpath("//button[normalize-space()='Buy']"));
click(By.xpath("//button[normalize-space()='MarketFill now at LTP']"));
type(By.id("order-qty"), "10");
click(tid("review-order"));
expectText(tid("review-qty"), "10");
click(By.xpath("//button[normalize-space()='Confirm']"));
expectText(tid("order-result"), "Filled");
click(By.linkText("Portfolio"));
expectText(tid("holding-qty-INFY"), "10");
// Sell part of the position
click(By.linkText("Sell"));
type(By.id("order-qty"), "4");
click(tid("review-order"));
click(By.xpath("//button[normalize-space()='Confirm']"));
expectText(tid("order-result"), "Sold 4 INFY");
click(By.linkText("Portfolio"));
expectText(tid("holding-qty-INFY"), "6");
}
}