EMA Crossover Strategy with Stoploss and Target

Strategy Type

Test Strategy – Purpose-built for functional validation of data flow, signal generation, order placement, and WebSocket-based exits. Tight SL/Target are kept intentional for testing.

Instrument Configuration

  • Exchange: NSE

  • Symbol: NHPC

  • Quantity: 1

  • Product: MIS

  • Timeframe (bars): 5m

  • Historical Lookback: 5 days

  • Trade Direction Mode: BOTH (supports LONG / SHORT / BOTH)

Note: Behavior is logic-driven; MIS is used only for convenience during tests.

Indicators Used

  • EMA 2: Exponential Moving Average over the last 2 closing prices (very short-term).

  • EMA 4: Exponential Moving Average over the last 4 closing prices (short-term).

Entry Conditions

  • Fetch 5-minute historical candle data approximately every 5 seconds.

  • Calculate EMA-2 and EMA-4.

  • Confirm crossover using the last two closed candles (not the current forming candle).

  • Buy Signal: Previous candle EMA-2 ≤ EMA-4 and last closed candle EMA-2 > EMA-4.

  • Sell Signal: Previous candle EMA-2 ≥ EMA-4 and last closed candle EMA-2 < EMA-4.

  • On confirmed signal:

    • Place a MARKET order (BUY or SELL).

    • Capture entry price and compute risk levels:

      • For BUY: Stoploss = Entry − ₹0.10, Target = Entry + ₹0.20

      • For SELL: Stoploss = Entry + ₹0.10, Target = Entry − ₹0.20

Exit Conditions

  • Use WebSocket streaming to receive live LTP updates.

  • Continuously check if LTP hits the defined stoploss or target.

  • When triggered, exit via a MARKET order in the opposite direction.

Strategy Architecture

  • Two threads:

    • WebSocket Thread: Listens to real-time LTP and checks SL/Target.

    • Strategy Thread: Periodically fetches historical data, evaluates EMA signals, and initiates trades.

  • Uses threading.Event() for graceful shutdown via CTRL+C.

Shutdown Behavior

  • On keyboard interrupt, both threads are stopped safely.

  • WebSocket subscription is removed and the connection is closed.

  • If a position is open, the strategy attempts to close it with a MARKET order before exit.

  • The strategy exits cleanly and logs the shutdown.


Complete Code


Last updated

Was this helpful?