import { reactive, computed, toRefs } from 'vue' import { BuyOrSell } from '@/constants/order' import { queryTradePosition } from '@/services/api/order' import { useFuturesStore } from './futures' import { defineStore } from '../store' import eventBus from '@/services/bus' /** * 持仓存储对象 */ const useStore = defineStore(() => { const futuresStore = useFuturesStore() const state = reactive({ loading: false, tradeMode: 0, orderPositionList: [], // 持仓汇总列表 }) // 获取持仓汇总列表 const getTradePosition = async () => { try { state.loading = true const res = await queryTradePosition() state.orderPositionList = res.data } finally { state.loading = false } } // 持仓汇总计算列表 const orderPositionComputedList = computed(() => { const result: (Model.TradePositionRsp & { closepl: number; // 参考损益 })[] = [] state.orderPositionList.forEach((item) => { const lastPrice = futuresStore.getQuotePrice(item.goodscode) // 计算参考损益 const closepl = (lastPrice.value * item.curpositionqty * item.agreeunit - item.curholderamount) * (item.buyorsell === BuyOrSell.Buy ? 1 : -1) result.push({ ...item, closepl, }) }) return result }) const orderPositionList = computed(() => { if (state.tradeMode) { return orderPositionComputedList.value.filter((e) => e.trademode === state.tradeMode) } return orderPositionComputedList.value }) // 获取持仓数量 const getOrderQty = (buyOrSell: BuyOrSell, goodsCode: string) => { return computed(() => { const item = state.orderPositionList.find((e) => e.goodscode === goodsCode && e.buyorsell === buyOrSell) return item?.enableqty ?? 0 }) } // 接收持仓变化通知 const posChangedNtf = eventBus.$on('PosChangedNtf', () => getTradePosition()) return { ...toRefs(state), getTradePosition, getOrderQty, orderPositionList, posChangedNtf, } }) export const usePositionStore = (tradeMode = 0) => { const store = useStore() store.tradeMode = tradeMode return store }