Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.

Stock tradiing using Arduino : execute trades and display profit loss in 16X2 display

Last updated on 4 days ago
K
KevinMember
Posted 4 days ago
1. Fetches **live LTP** (last traded price) from a REST API.
2. Executes **mock trades** (BUY/SELL) to an arbitrary broker API (you can later replace with real broker’s API like Zerodha, Upstox, or Fyers).
3. Displays **current price, position, and profit/loss** on a **16x2 LCD (I²C)**.
## ⚙️ Hardware Requirements
| Component | Purpose |
| -------------------------------------------------------- | ------------------------------------- |
| **ESP32 Dev Board** | Wi-Fi + logic control |
| **16×2 LCD with I²C adapter** (uses LiquidCrystal_I2C) | Display price, P/L |
| Optional push buttons | Manual trade triggers (BUY/SELL/EXIT) |

---
## 📦 Arduino Libraries Needed
Install these via Arduino IDE → *Tools → Manage Libraries*:
* **WiFi.h** (comes with ESP32 board package)
* **HTTPClient.h**
* **LiquidCrystal_I2C** (by Frank de Brabander or similar)
* **ArduinoJson** (optional for JSON parsing)

---

## 🧠 Logic Overview

1. Connect to Wi-Fi.
2. Periodically fetch LTP (dummy API or any free stock price API).
3. Keep track of:

* Current position (BUY, SELL, or NONE)
* Entry price
* Profit/Loss = (LTP − entry_price) × quantity
4. Execute trade via mock API call.
5. Show all key values on the 16x2 LCD.

---

## 🧩 Full Sample Code

cpp
/*
 ESP32 Algo Trading Demo with LCD (16x2 I2C)
 -------------------------------------------
 Features:
 - Fetches LTP from dummy API
 - Sends mock buy/sell orders
 - Displays current LTP and P/L on LCD

 Replace BROKER_ORDER_URL with your actual broker endpoint
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <LiquidCrystal_I2C.h>
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
// Dummy endpoints (replace with real ones)
const char* PRICE_API_URL = "https://api.example.com/ltp?symbol=RELIANCE";
const char* BROKER_ORDER_URL = "https://api.example.com/order";
const char* BROKER_API_KEY = "DUMMY_API_KEY";
// LCD settings
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Trade parameters
String symbol = "RELIANCE";
float entryPrice = 0;
float ltp = 0;
float profitLoss = 0;
String position = "NONE";
int quantity = 10;
// Helper function to fetch latest price
float fetchLTP() {
 if (WiFi.status() != WL_CONNECTED) return 0.0;
 HTTPClient http;
 http.begin(PRICE_API_URL);
 int code = http.GET();
 if (code != 200) {
 Serial.printf("Price fetch failed: %d\n", code);
 http.end();
 return 0.0;
 }
 String payload = http.getString();
 http.end();
 // If payload = plain number like "2543.65"
 float price = payload.toFloat();
 if (price <= 0) {
 // try extracting from JSON: {"ltp":2543.65}
 int p = payload.indexOf(":");
 int e = payload.indexOf("}");
 price = payload.substring(p + 1, e).toFloat();
 }
 return price;
}
// Mock trade execution
void placeOrder(String side) {
 if (WiFi.status() != WL_CONNECTED) return;
 HTTPClient http;
 http.begin(BROKER_ORDER_URL);
 http.addHeader("Content-Type", "application/json");
 http.addHeader("Authorization", String("Bearer ") + BROKER_API_KEY);

 String body = "{\"symbol\":\"" + symbol + "\",\"side\":\"" + side + "\",\"qty\":" + String(quantity) + "}";
 int code = http.POST(body);
 String resp = http.getString();
 http.end();

 Serial.printf("%s order response %d: %s\n", side.c_str(), code, resp.c_str());

 if (side == "BUY") {
 position = "LONG";
 entryPrice = ltp;
 } else if (side == "SELL") {
 if (position == "LONG") {
 float diff = ltp - entryPrice;
 profitLoss += diff * quantity;
 position = "NONE";
 } else {
 position = "SHORT";
 entryPrice = ltp;
 }
 }
}
// Display data > 0) {
 Serial.printf("LTP: %.2f\n", ltp);
 }
 // Simple strategy: Buy below 2500, Sell above 2600 (demo logic)
 if (position == "NONE" && ltp < 2500) {
 placeOrder("BUY");
 } else if (position == "LONG" && ltp > 2600) {
 placeOrder("SELL");
 }
 updateLCD();
 delay(10000); // fetch every 10 sec
}

---
## 🧾 Example Output (Serial Monitor + LCD)
**LCD line 1:** RELIANCE:2560.7
**LCD line 2:** LONG P/L:60.0
**Serial:**

WiFi Connected!
LTP: 2560.70
BUY order response 200: {"status":"ok"}
SELL order response 200: {"status":"ok"}
K
KevinMember
Posted 4 days ago
## 🔐 Integrating a Real Broker

You can adapt the same structure to **any broker with REST APIs** (Zerodha, Fyers, Alpaca, etc.):

| Broker | Auth Type | Docs |
| ------------------- | -------------- | ------------------------------------------------------------------------------------------ |
| **Zerodha Kite** | Token (Bearer) | [https://kite.trade/docs/connect/v3/](https://kite.trade/docs/connect/v3/) |
| **Fyers** | OAuth + Token | [https://myapi.fyers.in/docs/](https://myapi.fyers.in/docs/) |
| **Upstox** | OAuth 2.0 | [https://upstox.com/developer/api/](https://upstox.com/developer/api/) |
| **Alpaca (Global)** | API Key/Secret | [https://alpaca.markets/docs/api-references/](https://alpaca.markets/docs/api-references/) |

You’ll just replace:

* PRICE_API_URL with the broker’s quote endpoint
* BROKER_ORDER_URL with their order endpoint
* Add their specific headers or HMAC signature scheme
You can view all discussion threads in this forum.
You cannot start a new discussion thread in this forum.
You cannot reply in this discussion thread.
You cannot start on a poll in this forum.
You cannot upload attachments in this forum.
You cannot download attachments in this forum.
Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 3
Members Online 0

Total Members: 19
Newest Member: bokovac