Subscribing to changes to onchain is easy using subscription.subscribeProgramAccounts. In this example we subscribe to any SOL margin account changes, but you can subscribe to any account types you wish to track.
Code
require("dotenv").config();import { Exchange, Network, utils, types, programTypes, subscription, constants,} from"@zetamarkets/sdk";import { PublicKey, Connection } from"@solana/web3.js";constNETWORK_URL=process.env["network_url"]!;let network:Network;switch (process.env["network"]) {case"localnet": network =Network.LOCALNET;break;case"devnet": network =Network.DEVNET;break;case"mainnet": network =Network.MAINNET;break;default:throwError("Unsupported network type!");}asyncfunctionmain() {// Create a solana web3 connection to devnet.constconnection=newConnection(NETWORK_URL,"confirmed");constloadExchangeConfig=types.defaultLoadExchangeConfig( network, connection,utils.defaultCommitment(),0,// ThrottleMs - increase if you are running into rate limit issues on startup.true );awaitExchange.load( loadExchangeConfig,// Exchange wallet can be ignored for normal clients.undefined );subscription.subscribeProgramAccounts<programTypes.CrossMarginAccount>(types.ProgramAccountType.CrossMarginAccount,async ( data: subscription.AccountSubscriptionData<programTypes.CrossMarginAccount> ) => {// Here you can filter for only accounts you care about (such as your own)console.log(data); } );awaitutils.sleep(100_000);// Close to end the websockets.// await Exchange.close();}main().catch(console.error.bind(console));