position.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { reactive, computed, toRefs } from 'vue'
  2. import { BuyOrSell } from '@/constants/order'
  3. import { queryTradePosition } from '@/services/api/order'
  4. import { useFuturesStore } from './futures'
  5. import { defineStore } from '../store'
  6. import eventBus from '@/services/bus'
  7. /**
  8. * 持仓存储对象
  9. */
  10. const useStore = defineStore(() => {
  11. const futuresStore = useFuturesStore()
  12. const state = reactive({
  13. loading: false,
  14. tradeMode: 0,
  15. orderPositionList: <Model.TradePositionRsp[]>[], // 持仓汇总列表
  16. })
  17. // 获取持仓汇总列表
  18. const getTradePosition = async () => {
  19. try {
  20. state.loading = true
  21. const res = await queryTradePosition()
  22. state.orderPositionList = res.data
  23. } finally {
  24. state.loading = false
  25. }
  26. }
  27. // 持仓汇总计算列表
  28. const orderPositionComputedList = computed(() => {
  29. const result: (Model.TradePositionRsp & {
  30. closepl: number; // 参考损益
  31. })[] = []
  32. state.orderPositionList.forEach((item) => {
  33. const lastPrice = futuresStore.getQuotePrice(item.goodscode)
  34. // 计算参考损益
  35. const closepl = (lastPrice.value * item.curpositionqty * item.agreeunit - item.curholderamount) * (item.buyorsell === BuyOrSell.Buy ? 1 : -1)
  36. result.push({
  37. ...item,
  38. closepl,
  39. })
  40. })
  41. return result
  42. })
  43. const orderPositionList = computed(() => {
  44. if (state.tradeMode) {
  45. return orderPositionComputedList.value.filter((e) => e.trademode === state.tradeMode)
  46. }
  47. return orderPositionComputedList.value
  48. })
  49. // 获取持仓数量
  50. const getOrderQty = (buyOrSell: BuyOrSell, goodsCode: string) => {
  51. return computed(() => {
  52. const item = state.orderPositionList.find((e) => e.goodscode === goodsCode && e.buyorsell === buyOrSell)
  53. return item?.enableqty ?? 0
  54. })
  55. }
  56. // 接收持仓变化通知
  57. const posChangedNtf = eventBus.$on('PosChangedNtf', () => getTradePosition())
  58. return {
  59. ...toRefs(state),
  60. getTradePosition,
  61. getOrderQty,
  62. orderPositionList,
  63. posChangedNtf,
  64. }
  65. })
  66. export const usePositionStore = (tradeMode = 0) => {
  67. const store = useStore()
  68. store.tradeMode = tradeMode
  69. return store
  70. }