Skip to content

Commit

Permalink
fix: position-limit error (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
zccz14 authored Oct 30, 2023
1 parent d7f9129 commit 7917b7e
Showing 1 changed file with 24 additions and 42 deletions.
66 changes: 24 additions & 42 deletions @libs/utils/usePositionLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { mergePositions } from "./mergePositions";
*/
export function usePositionLimit(
source_account_id: string,
product_id: string,
positionLimit: number
) {
const src = useAccountInfo({ account_id: source_account_id });
Expand All @@ -16,50 +17,31 @@ export function usePositionLimit(
currency: src.money.currency,
leverage: src.money.leverage,
});
const ex = useExchange();
const pL = useSinglePosition(
product_id,
PositionVariant.LONG,
tar.account_id
);
const pS = useSinglePosition(
product_id,
PositionVariant.SHORT,
tar.account_id
);
useEffect(() => {
const orders: IOrder[] = [];
const mapProductToPosition = Object.fromEntries(
mergePositions(tar.positions).map((position) => [
`${position.product_id}-${position.variant}`,
position,
])
const srcNetPosition = src.positions.reduce(
(acc, cur) =>
acc +
(cur.product_id !== product_id
? 0
: cur.volume * (cur.variant === PositionVariant.LONG ? 1 : -1)),
0
);
pL.setTargetVolume(
srcNetPosition > 0 ? Math.min(positionLimit, Math.abs(srcNetPosition)) : 0
);
pS.setTargetVolume(
srcNetPosition < 0 ? Math.min(positionLimit, Math.abs(srcNetPosition)) : 0
);
for (const order of ex.listOrders()) {
if (order.account_id === src.account_id) {
const positionVolume =
mapProductToPosition[
`${order.product_id}-${
[OrderDirection.CLOSE_LONG, OrderDirection.OPEN_LONG].includes(
order.direction
)
? PositionVariant.LONG
: PositionVariant.SHORT
}`
]?.volume ?? 0;
const volume = [
OrderDirection.CLOSE_LONG,
OrderDirection.CLOSE_SHORT,
].includes(order.direction)
? Math.min(order.volume, positionVolume)
: Math.min(order.volume, positionLimit - positionVolume);
if (volume > 0) {
const theOrder = {
...order,
account_id: tar.account_id,
client_order_id: UUID(),
volume,
};
ex.submitOrder(theOrder);
orders.push(theOrder);
}
}
}
return () => {
for (const order of orders) {
ex.cancelOrder(order.client_order_id);
}
};
});
return tar;
}

0 comments on commit 7917b7e

Please sign in to comment.