-
Notifications
You must be signed in to change notification settings - Fork 79
/
phoenixSubscriber.ts
218 lines (198 loc) · 5.23 KB
/
phoenixSubscriber.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import { Connection, PublicKey, SYSVAR_CLOCK_PUBKEY } from '@solana/web3.js';
import { BulkAccountLoader } from '../accounts/bulkAccountLoader';
import {
Client,
deserializeClockData,
toNum,
getMarketUiLadder,
Market,
} from '@ellipsis-labs/phoenix-sdk';
import { PRICE_PRECISION } from '../constants/numericConstants';
import { BN } from '@coral-xyz/anchor';
import { L2Level, L2OrderBookGenerator } from '../dlob/orderBookLevels';
export type PhoenixMarketSubscriberConfig = {
connection: Connection;
programId: PublicKey;
marketAddress: PublicKey;
accountSubscription:
| {
// enables use to add web sockets in the future
type: 'polling';
accountLoader: BulkAccountLoader;
}
| {
type: 'websocket';
};
};
export class PhoenixSubscriber implements L2OrderBookGenerator {
connection: Connection;
client: Client;
programId: PublicKey;
marketAddress: PublicKey;
subscriptionType: 'polling' | 'websocket';
accountLoader: BulkAccountLoader | undefined;
market: Market;
marketCallbackId: string | number;
clockCallbackId: string | number;
subscribed: boolean;
lastSlot: number;
lastUnixTimestamp: number;
public constructor(config: PhoenixMarketSubscriberConfig) {
this.connection = config.connection;
this.programId = config.programId;
this.marketAddress = config.marketAddress;
if (config.accountSubscription.type === 'polling') {
this.subscriptionType = 'polling';
this.accountLoader = config.accountSubscription.accountLoader;
} else {
this.subscriptionType = 'websocket';
}
this.lastSlot = 0;
this.lastUnixTimestamp = 0;
}
public async subscribe(): Promise<void> {
if (this.subscribed) {
return;
}
this.market = await Market.loadFromAddress({
connection: this.connection,
address: this.marketAddress,
});
const clock = deserializeClockData(
(await this.connection.getAccountInfo(SYSVAR_CLOCK_PUBKEY, 'confirmed'))
.data
);
this.lastUnixTimestamp = toNum(clock.unixTimestamp);
if (this.subscriptionType === 'websocket') {
this.marketCallbackId = this.connection.onAccountChange(
this.marketAddress,
(accountInfo, _ctx) => {
try {
this.market = this.market.reload(accountInfo.data);
} catch {
console.error('Failed to reload Phoenix market data');
}
}
);
this.clockCallbackId = this.connection.onAccountChange(
SYSVAR_CLOCK_PUBKEY,
(accountInfo, ctx) => {
try {
this.lastSlot = ctx.slot;
const clock = deserializeClockData(accountInfo.data);
this.lastUnixTimestamp = toNum(clock.unixTimestamp);
} catch {
console.error('Failed to reload clock data');
}
}
);
} else {
this.marketCallbackId = await this.accountLoader.addAccount(
this.marketAddress,
(buffer, slot) => {
try {
this.lastSlot = slot;
if (buffer) {
this.market = this.market.reload(buffer);
}
} catch {
console.error('Failed to reload Phoenix market data');
}
}
);
this.clockCallbackId = await this.accountLoader.addAccount(
SYSVAR_CLOCK_PUBKEY,
(buffer, slot) => {
try {
this.lastSlot = slot;
const clock = deserializeClockData(buffer);
this.lastUnixTimestamp = toNum(clock.unixTimestamp);
} catch {
console.error('Failed to reload clock data');
}
}
);
}
this.subscribed = true;
}
public getBestBid(): BN | undefined {
const ladder = getMarketUiLadder(
this.market,
this.lastSlot,
this.lastUnixTimestamp,
1
);
const bestBid = ladder.bids[0];
if (!bestBid) {
return undefined;
}
return new BN(Math.floor(bestBid.price * PRICE_PRECISION.toNumber()));
}
public getBestAsk(): BN | undefined {
const ladder = getMarketUiLadder(
this.market,
this.lastSlot,
this.lastUnixTimestamp,
1
);
const bestAsk = ladder.asks[0];
if (!bestAsk) {
return undefined;
}
return new BN(Math.floor(bestAsk.price * PRICE_PRECISION.toNumber()));
}
public getL2Bids(): Generator<L2Level> {
return this.getL2Levels('bids');
}
public getL2Asks(): Generator<L2Level> {
return this.getL2Levels('asks');
}
*getL2Levels(side: 'bids' | 'asks'): Generator<L2Level> {
const basePrecision = Math.pow(
10,
this.market.data.header.baseParams.decimals
);
const pricePrecision = PRICE_PRECISION.toNumber();
const ladder = getMarketUiLadder(
this.market,
this.lastSlot,
this.lastUnixTimestamp,
20
);
for (let i = 0; i < ladder[side].length; i++) {
const { price, quantity } = ladder[side][i];
const size = new BN(Math.floor(quantity * basePrecision));
yield {
price: new BN(Math.floor(price * pricePrecision)),
size,
sources: {
phoenix: size,
},
};
}
}
public async unsubscribe(): Promise<void> {
if (!this.subscribed) {
return;
}
// remove listeners
if (this.subscriptionType === 'websocket') {
await this.connection.removeAccountChangeListener(
this.marketCallbackId as number
);
await this.connection.removeAccountChangeListener(
this.clockCallbackId as number
);
} else {
this.accountLoader.removeAccount(
this.marketAddress,
this.marketCallbackId as string
);
this.accountLoader.removeAccount(
SYSVAR_CLOCK_PUBKEY,
this.clockCallbackId as string
);
}
this.subscribed = false;
}
}