diff --git a/@libs/utils/usePositionLimit.ts b/@libs/utils/usePositionLimit.ts index 4a15ae0..d492220 100644 --- a/@libs/utils/usePositionLimit.ts +++ b/@libs/utils/usePositionLimit.ts @@ -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 }); @@ -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; }