← Back to Docs

Trading Operations Strategy (v4.1)

The definitive guide to how the PSX Bot manages capital, handles overlapping intraday signals from TradingView, and protects your account against catastrophic volatility.

Division of Responsibility

Golden Rule: Never hardcode your capital or share quantities into Pine Script. The bot mathematically sizes the trade based on exactly how much cash is sitting in your account the millisecond the signal arrives.

ConcernTradingView (Pine Script)Bot (Backend Engine)
When to Buy/Sell✅ Decides & triggers webhook✅ Receives & processes
How Many Shares❌ Never decides this✅ Calculates exactly from Live Buying Power
Order Placement❌ Cannot talk to broker✅ Executes via StockIntel API
Risk & Kill Switches❌ No safety nets✅ Enforces hard limits & EOD cutoffs

Intraday Capital Allocation

Your bot uses Snapshot Equity to calculate fixed slot sizes, guaranteeing equal allocations regardless of the order in which signals arrive. This guarantees you utilize your deposited capital efficiently while leaving room for overlapping trades.

1

Total Equity

100,000 PKR

Bot takes snapshot of actual account value

2

Slot Target (19%)

19,000 PKR

Allocation cap is calculated per trade

3

Affordability Check

Target: 19,000
Available Cash: 50,000

Market Timing Windows

The bot anchors itself to the StockIntel TradingSessionStatus and safely manages intraday dynamics. It natively supports the PSX Friday Jumma split schedule.

Observation
Open + 35m

Rejects all BUY signals to avoid erratic pre-open auction chop.

Trading Window
Standard

Normal operations. Bot evaluates size and executes.

Sell-Only
Close - 20m

Rejects BUY signals. SELL signals and Stop-Loss remain fully active.

Force Square-off
Close - 10m

Cancels unfilled entries. Market sells open positions.

Double-Protection Exit Model

The most dangerous part of automated trading is when your internet goes down or TradingView crashes while you are in a live trade. Your bot uses a bulletproof double-protection model:

1. The Primary Exit

When the trend reverses naturally, TradingView sends a SELL webhook to close the trade for a profit or small loss.

2. The Failsafe Exit

The exact second your bot buys shares, it immediately sends a hard Stop-Loss to the PSX Exchange servers. It survives everything.

Resolution: Whichever exit triggers first wins. If the Stop-Loss hits, the subsequent TradingView SELL signal is safely ignored (logged as NO_POSITION).

Hybrid Risk Model: Gap-Down Isolation

What happens if the market opens with a severe gap-down and your entry order fills at a price that is already below your planned Stop-Loss? The bot's Hybrid Risk Model handles this extreme edge case flawlessly.

SCENARIO

The Gap-Down Trap

Your order fills at 94 PKR, but your hard Stop-Loss was planned at 95 PKR.

Price: 94 PKR
Stop-Loss: 95 PKR
(94 <= 95) = TRUE
BOT RESPONSE

Automation Halted

The bot intercepts the fill event. It strictly avoids placing a Stop-Loss and avoids market selling.

MANUAL_INTERVENTION_REQUIRED

Why this matters:

  • Prevents the bot from instantly selling into a crashing, illiquid market.
  • Prevents invalid limit orders (Stop-Loss price > Current Price is usually rejected).
  • Ignores all future incoming webhooks (Take Profit / EOD Sells) until you manually resolve the position.

3-Signal Webhook Order Lifecycle

How the bot handles the complete trade lifecycle from entry to exit via TradingView Webhooks.

Visual Workflow Architecture

1. BUY SIGNALEntry

TradingView fires BUY webhook

"action": "BUY"
"price": 100.00,
"stop_loss": 95.00,
"take_profit": 110.00

👉 Sizes trade dynamically based on available PKR balance & risk.

Trade State:OPEN
2. TAKE PROFIT (SELL)Exit High

Price reaches Target High (110 PKR)

"action": "SELL"
"price": 110.00,
"reason": "TAKE_PROFIT"

👉 Matches open position, submits SELL order to PSX, logs profit.

Trade State:CLOSED (+10%)
3. STOP LOSSExit Risk

Price drops to Stop Loss (95 PKR)

"action": "SELL"
"price": 95.00,
"reason": "STOP_LOSS"

👉 Triggers emergency market SELL order to cut losses immediately.

Trade State:CLOSED (-5%)
1. Buy Entry Signal

Sent by TradingView when your strategy indicators identify a buy setup.

  • Validates session timing (avoids opening auction chop)
  • Calculates quantity based on cash & risk cap
  • Stores target take_profit & stop_loss
2. Sale on High Price

Triggered when price reaches your designated profit target.

  • TradingView sends a SELL webhook signal
  • Bot verifies active position for that ticker
  • Executes sell order to capture profit & updates analytics
3. Stop Loss Hit

Triggered when the price drops to or below your stop loss price.

  • TradingView alert or bot price monitor fires stop loss
  • Submits immediate sell order to exit position
  • Frees reserved capital & protects portfolio balance

TradingView Alert Message Template

JSON Format

Paste this exact JSON into your TradingView Alert message box. TradingView dynamically replaces variables like {{ticker}} and {{close}} when sending signals:

{
  "secret": "YOUR_WEBHOOK_SECRET",
  "ticker": "{{ticker}}",
  "action": "{{strategy.order.action}}",
  "price": {{close}},
  "stop_loss": 95.00,
  "take_profit": 110.00
}

PSX Market Mechanics & Safety Fallbacks

Engineered for Pakistan Stock Exchange (PSX) liquidity constraints, circuit breakers, and partial order execution.

PSX CIRCUIT BREAKERSUpper / Lower Lock

Lower Circuit Lock Fallback

When a PSX stock hits the Lower Circuit Lock (-7.5%), market buyers disappear. Standard market orders get rejected by exchange servers.

1. Market Order AttemptREJECTED (Lock Hit)
2. Bot Automatic FallbackLIMIT @ Lower Lock Floor
  • Calculates PSX floor price: Entry Price × 0.925
  • Re-submits as a LIMIT SELL Order queued on exchange book
  • Prevents loop-spamming rejected market orders
STATE MANAGEMENTExecution Events

Partial Fill & Order Cancellation

If an order for 1,000 shares only fills 400 shares before market price shifts, the bot tracks confirmed executed shares via live StockIntel execution streams.

Requested Shares: 1,000
Filled Shares: 400 (PARTIAL)
Sell Order Quantity: EXACTLY 400
  • Auto-cancels remaining 600 unfilled BUY shares when exit signal arrives
  • Protects against broker rejection for attempting to sell un-owned shares
  • Verifies live broker position balance before issuing sell requests