DEV Community

Emil Nielsen
Emil Nielsen

Posted on

Building a Reliable Stop-Loss System for an Automated Trading Bot

One of the most important parts of any automated trading bot isn't entering trades—it's managing risk after a position has been opened. A stop-loss system is only effective if it continuously monitors orders and reacts correctly to every stage of the order lifecycle.

In this article, I'll walk through the stop-loss architecture I've been implementing in Raven, my no-code framework for building automated prediction market strategies. If you prefer a video walkthrough, you can watch the full implementation here:

📺 Video: https://www.youtube.com/watch?v=wc9XaGDV-J4


Why Monitoring Orders Matters

Placing an order does not mean you have an active position.

When an order is submitted, it simply enters the order book where it waits to be matched. Until that happens, there is no live position to manage.

This distinction is essential when building reliable trading systems.

Instead of assuming an order will immediately execute, Raven tracks every state transition and only activates position management once the exchange confirms the order has been matched.


The Order Lifecycle

The architecture separates order management into several stages.

1. Order Placement

The bot submits an order to the exchange.

At this point, the order is simply waiting on the order book.

When a placement event arrives through the exchange's user event stream, the order is added to the Pending Order Tracker.

Its only responsibility is to monitor orders waiting to be matched.

2. Order Match

Once the exchange reports that the order has been matched, it is removed from the Pending Order Tracker and transferred into the Position Tracker.

This is the point where the bot considers the position to be live.

Only now do we begin tracking profit and loss, confirmations, updates, and stop-loss conditions.

3. Position Tracking

The Position Tracker monitors:

  • Position updates
  • Order confirmations
  • Position lifecycle events
  • Profit & Loss (P&L)
  • Stop-loss conditions

When the position becomes fully confirmed, the stop-loss logic is activated.


The Position Monitor

The Position Monitor continuously watches every live position.

Its responsibilities include:

Start Monitoring

Registers a newly opened position and begins listening for updates.

Handle Price Changes

The monitor subscribes to events published through the event bus.

Whenever market prices or user events arrive, the position state is updated.

Calculate Position P&L

Every update recalculates the current profit or loss.

This value drives both:

  • Take-profit logic
  • Stop-loss logic

Generate Exit Actions

If the unrealized loss exceeds the configured stop-loss threshold, the Position Monitor generates an exit action.

Rather than placing the order directly, it publishes the action to the execution layer, keeping the architecture modular and easy to extend.


Current Stop-Loss Implementation

The current implementation exits positions using Fill-or-Kill (FOK) orders.

A Fill-or-Kill order must execute immediately in full. If sufficient liquidity isn't available, the order is automatically cancelled.

While this works well for testing, Raven will eventually allow users to choose between multiple execution strategies depending on their own trading preferences.

The goal is to make every aspect of execution configurable rather than hardcoded.


A Real Trading Example

To validate the stop-loss system, I tested it using real trades.

The objective wasn't to make money—it was to verify that the system behaves correctly under live market conditions.

In one example, I bought five shares at 0.55.

The Position Monitor immediately began tracking the position and calculating its P&L.

The stop-loss threshold for this test was approximately 10%.

When the position crossed that threshold, the bot generated an exit signal and submitted a Fill-or-Kill sell order.

Unfortunately, the market moved almost instantly.

Although the order was submitted at the best bid, liquidity disappeared before the exchange could fill it.

The order was therefore cancelled.

This perfectly demonstrates why monitoring execution is so important.

Submitting an order doesn't guarantee that it will execute.


Automatic Recovery

Instead of assuming the stop-loss had worked, the system continued monitoring the order status.

When it detected that the Fill-or-Kill order had been cancelled, it immediately submitted another exit order using the updated market price.

The second order executed successfully.

By the time the position closed, however, the loss had grown to around 20%, even though the stop-loss threshold had originally been 10%.

While that wasn't the desired trading outcome, it validated the architecture.

The system correctly detected the failed execution, kept monitoring the position, and successfully exited on the next opportunity.


Building for Real Markets

One lesson becomes obvious when building trading infrastructure:

Markets don't always behave the way we'd like.

Liquidity disappears.

Orders fail.

Prices move between the moment you decide to exit and the moment your order reaches the exchange.

A robust trading system must continuously monitor these events and respond intelligently when execution doesn't go as planned.

Simply submitting a stop-loss order isn't enough.


Building Raven

Everything described here is being built into Raven, a no-code strategy builder for prediction markets.

Instead of writing hundreds or even thousands of lines of Python, users will be able to visually construct automated trading strategies using connected nodes.

The goal is to make sophisticated prediction market automation accessible while still giving advanced users full control over execution, risk management, and strategy design.

I'm documenting the entire development process publicly on my YouTube channel, where I share architecture decisions, implementation details, and live coding sessions.

📺 Follow the development here: https://www.youtube.com/channel/UCY8IodKR5XCx3yJNGRZi0Sg


Open Source Resources

If you're interested in learning more about automated prediction market trading, I've also open-sourced a trading bot that demonstrates many of the concepts discussed throughout these articles.

💻 GitHub Repository: https://github.com/nahuelvivas/Polymarket-Arbitrage-Trading-Bot

Feel free to explore the codebase, experiment with it, or use it as inspiration for your own trading systems.


Final Thoughts

Building a reliable stop-loss system involves far more than triggering a sell order once losses reach a predefined percentage.

It requires continuously tracking the order lifecycle, monitoring position state, responding to exchange events, and handling failed executions gracefully.

By separating responsibilities between a Pending Order Tracker, Position Tracker, Position Monitor, and a dedicated execution layer, Raven provides a resilient architecture designed for the realities of live prediction markets.

As development continues, the framework will become increasingly flexible, allowing traders to configure execution behaviour, risk management, and strategy logic without writing code.

Top comments (0)