-
Notifications
You must be signed in to change notification settings - Fork 2
/
Store.js
207 lines (172 loc) · 6.9 KB
/
Store.js
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
import React, { createContext, useReducer, useEffect } from "react";
import Reducer from './Reducer'
import { useTheme } from '@material-ui/core/styles';
export const initialState = {
openClose: false,
openOpen: false,
ticker: "BTCUSDT",
tickerRows: [],
positionRows: [],
prices: {},
walletRows: [],
tradeRows: [],
pnLRows: [],
openAmounts: {
leverage: 5,
price: 0,
capital: { amount: 0, usdt: 0 },
notional: { amount: 0, usdt: 0 },
margin: { amount: 0, usdt: 0 }
},
candleInterval: "1m",
timeRange: {}
};
export const ACTIONS = {
SET_CLOSE_OPEN: 'SET_CLOSE_OPEN',
SET_OPEN_OPEN: 'SET_OPEN_OPEN',
SET_TICKER: 'SET_TICKER',
SET_TICKER_ROWS: 'SET_TICKER_ROWS',
SET_POSITION_ROWS: 'SET_POSITION_ROWS',
SET_TRADE_ROWS: 'SET_TRADE_ROWS',
SET_PRICES: 'SET_PRICES',
SET_WALLET_ROWS: 'SET_WALLET_ROWS',
SET_CAPITAL: 'SET_CAPITAL',
SET_OPEN_AMOUNTS: 'SET_OPEN_AMOUNTS',
SET_PNL_ROWS: 'SET_PNL_ROWS',
SET_CANDLE_INTERVAL: 'SET_CANDLE_INTERVAL',
SET_TIME_RANGE: 'SET_TIME_RANGE',
}
const Store = ({ children }) => {
const [state, dispatch] = useReducer(Reducer, initialState);
const theme = useTheme()
const add_tick = (current, prior) => {
let tick
if (current > prior) {
tick = theme.palette.success.main;
}
if (current < prior) {
tick = theme.palette.error.main;
}
return tick;
};
// Initial data for position table
async function getPositionRows() {
const response = await fetch("http://localhost:8000/account");
const data = await response.json();
const responseDos = await fetch("http://localhost:8000/trades?form=last");
const dataDos = await responseDos.json();
const entryPrices = {}
dataDos.forEach(openPos => entryPrices[openPos.symbol] = openPos.priceMargin)
data.forEach(row => {
if (row.positionAmt !== 0) {
row.marginEntryPrice = entryPrices[row.symbol]
}
})
dispatch({ type: ACTIONS.SET_POSITION_ROWS, payload: data })
}
// Initial data for wallet table
async function getWalletRows() {
const response = await fetch("http://localhost:8000/wallet");
const data = await response.json();
dispatch({ type: ACTIONS.SET_WALLET_ROWS, payload: data });
}
// Initial data for PnL table
async function getPnLRows() {
const response = await fetch("http://localhost:8000/trades?form=summary");
const data = await response.json();
dispatch({ type: ACTIONS.SET_PNL_ROWS, payload: data });
}
// Initial data for trades table
async function getTradeRows() {
const response = await fetch("http://localhost:8000/trades");
const data = await response.json();
dispatch({ type: ACTIONS.SET_TRADE_ROWS, payload: data });
}
useEffect(() => {
getWalletRows();
getPnLRows();
getPositionRows();
getTradeRows();
}, []);
// Price stream for position table
async function streamPrices() {
let ws = new WebSocket("ws://localhost:8000/market-stream");
let oldPrices = {}
ws.onmessage = (event) => {
let filteredTickers = JSON.parse(event.data);
const newPrices = {};
filteredTickers.forEach((element) => {
newPrices[element.s] = {
markPrice: element.p,
spotPrice: element.spotPrice,
fundingRate: element.r,
fundingTime: element.T,
};
if (Object.keys(oldPrices).length > 0) {
newPrices[element.s].markTick = add_tick(element.p, oldPrices[element.s].markPrice);
newPrices[element.s].spotTick = add_tick(element.spotPrice, oldPrices[element.s].spotPrice);
}
});
dispatch({ type: ACTIONS.SET_PRICES, payload: newPrices })
oldPrices = newPrices
}
return () => ws.close()
}
async function streamAccountUpdates() {
let ws = new WebSocket("ws://localhost:8000/user-stream");
ws.onmessage = (event) => {
const update = JSON.parse(event.data)
if (["ACCOUNT_UPDATE", "outboundAccountPosition"].indexOf(update.e) !== -1) {
getWalletRows();
getPnLRows();
getPositionRows();
getTradeRows();
console.log("Positions, wallet and trades updated.")
}
}
return () => ws.close()
};
useEffect(() => {
streamPrices();
streamAccountUpdates()
}, []);
// Update position rows with price changes
useEffect(() => {
const updatePrice = (row) => {
const notional = (price, positionAmt) => {
return parseFloat(price) * parseFloat(positionAmt);
};
const unRealizedProfit = (price, entryPrice, positionAmt) => {
return notional(price, positionAmt) - notional(entryPrice, positionAmt);
};
const margin = (price, entryPrice, positionAmt, leverage) => {
return -notional(entryPrice, positionAmt) / leverage + unRealizedProfit(price, entryPrice, positionAmt);
};
row.markPrice = state.prices[row.symbol].markPrice;
row.markTick = state.prices[row.symbol].markTick;
row.spotPrice = state.prices[row.symbol].spotPrice;
row.spotTick = state.prices[row.symbol].spotTick;
row.fundingRate = state.prices[row.symbol].fundingRate;
row.fundingTime = state.prices[row.symbol].fundingTime;
row.notional = notional(row.markPrice, row.positionAmt)
row.marginNotional = notional(row.spotPrice, row.marginPositionAmt)
row.margin = margin(row.markPrice, row.entryPrice, row.positionAmt, row.leverage)
row.unRealizedProfit = unRealizedProfit(row.markPrice, row.entryPrice, row.positionAmt)
row.unRealizedProfitTick = add_tick(row.unRealizedProfit, 0)
row.marginUnRealizedProfit = unRealizedProfit(row.spotPrice, row.marginEntryPrice, row.marginPositionAmt)
row.marginUnRealizedProfitTick = add_tick(row.marginUnRealizedProfit, 0)
row.totalUnRealizedProfit = parseFloat(row.unRealizedProfit) + parseFloat(row.marginUnRealizedProfit)
row.totalUnRealizedProfitTick = add_tick(row.totalUnRealizedProfit, 0)
return row;
};
const data = state.positionRows.map((row) => updatePrice(row))
dispatch({ type: ACTIONS.SET_POSITION_ROWS, payload: data });
}, [state.prices]);
return (
<Context.Provider value={[state, dispatch]}>
{children}
</Context.Provider>
)
};
export const Context = createContext(initialState);
export default Store;