Listen to Trades

In this guide, we will write a simple script using the Lyra.js package to listen to incoming trades and report on the position's profit and loss.

1. Setup Lyra.js

Lyra.js is a JavaScript SDK for Optimistic Ethereum and the Lyra Protocol. It wraps around ethers and works in the web browser and Node.js.
To get started, clone the Lyra.js starter project:
git clone
cd lyra-js-starter
Next, run yarn install to install node modules, including lyrafinance/lyra-js:
yarn install

2. Listen to trades

To listen to trades across all markets, simply initialize an onTrade listener which passes TradeEvent entities to a handler function. To get the position from a trade event, simply fetch its position edge. From a position,y ou can calculate its realized and unrealized profit and loss.
import Lyra from '@lyrafinance/lyra-js'
const lyra = new Lyra()
lyra.onTrade(async tradeEvent => {
// Fetch position for trade
const position = await tradeEvent.position()
// Calculate realized and unrealized P&L
const realizedPnl = position.realizedPnl()
const unrealizedPnl = position.unrealizedPnl()
With this template, you can implement a variety of functionality:
  • Social trade feeds, such as a Discord or Twitter bot
  • Arbitrage bots which execute trades based on price updates.
  • Liquidation alerts for partially collateralized positions (combined with chainlink oracle price updates)