Files
zszq-trs/YLErpWeb/wwwroot/Scripts/app/trade/forwardTradeEditV2.js
T

1040 lines
43 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//otcformat禁止千分位分组
window.otcformat.options.disableGrouping = true;
const consVarieties = ylotc.varieties.filter(x => x.Name != "组合标的");
const consClients = ylotc.clients;
const consTraders = page.traderList;
const consAssetUnits = pageVue.CanSelectTrader ? ylotc.assetunits : ylotc.assetunits.filter(x => x.TraderIds.includes(pageVue.Trade.TraderId));
const consUnderlyingFlag = (function () {
let unSelFlag = tradeHelper.UnderlyingSelectFlag;
return unSelFlag.UseForTrading | unSelFlag.IncludeMatured |
unSelFlag.CommodityFutures | unSelFlag.StockIF | unSelFlag.CommoditySpot | unSelFlag.CheckLaunch | unSelFlag.IncludeBasket | unSelFlag.IncludeSynthetic;
}());
const consUnderlyingFlag2 = (function () {
let unSelFlag = tradeHelper.UnderlyingSelectFlag;
return unSelFlag.UseForTrading | unSelFlag.IncludeMatured |
unSelFlag.CommodityFutures | unSelFlag.StockIF | unSelFlag.CommoditySpot | unSelFlag.CheckLaunch | unSelFlag.IncludeBasket;
}());
//定价格式化(来自配置)
const consFormat = otcformat.trading;
const InputFormatPercent = Object.freeze({ precision: 2, append: '%' });
const InputFormatLots = Object.freeze({ precision: 2, append: '手' });
const InputFormatUmPrice = Object.freeze({ precision: consFormat.umprice.precision, append: '', negative: true });
const InputFormatOpenCommission = Object.freeze({ precision: consFormat.tradeSinglePrice.precision, append: '元/手', negative: true });
const InputFormatSinglePrice = Object.freeze({ precision: consFormat.tradeSinglePrice.precision, append: '' });
//预付金率输入格式
const inputFormatMarginRate = Object.freeze({ precision: consFormat.marginRateP.precision, append: '%' });
//表单提交处理
const submitHandler = (new function () {
function checkDate(value) {
let date = new Date(value);
return date.valueOf();
}
function checkSubmitData(trade) {
if (!trade.UnderlyingId) {
return "请设置标的信息";
}
if (!trade.ClientId) {
return "请设置客户名称";
}
if (!trade.AssetId) {
return "请设置簿记账户";
}
if (!trade.TradeDate) {
return '交易日期 必须填写';
}
if (!checkDate(trade.TradeDate)) {
return '交易日期 填写错误';
}
//if (trade.TradeDate > pageVue.SysDate) {
// return "交易日期不能是未来日期";
//}
if (!trade.ExerciseDate) {
return '到期日期 必须填写';
}
if (!checkDate(trade.ExerciseDate)) {
return '到期日期 填写错误';
}
if (trade.TradeDate > trade.ExerciseDate) {
return "交易日应该在到期日之前";
}
if (trade.ExerciseDate > trade.MaturityDate) {
return "到期日必需在标的到期日之前";
}
if (checkDate(trade.SettlementDate) && trade.SettlementDate < trade.ExerciseDate) {
return "结算日应该在到期日之前";
}
if (vue.isShowActualExerciseDate && page.showZeQi) {
if (!trade.MetaDic['ActualExerciseDate']) {
return '实际到期日期 必须填写';
}
if (!checkDate(trade.MetaDic['ActualExerciseDate'])) {
return '实际到期日期 填写错误';
}
if (trade.MetaDic['ActualExerciseDate'] > trade.MaturityDate) {
return "实际到期日期到期日必需在标的到期日之前";
}
if (trade.TradeDate > trade.MetaDic['ActualExerciseDate']) {
return "交易日应该在实际到期日期之前";
}
}
if (!trade.BuySell) {
return '交易方向 必须填写';
}
let lots = parseFloat(trade.Lots) || 0;
if (lots < 1e-5) {
return '交易手数 必须大于0';
}
let amount = parseFloat(trade.TradeAmount) || 0;
if (amount < 1e-5) {
return '交易数量 必须大于0';
}
if (!trade.Strike) {
return '交割价格 必须填写';
}
if (!trade.SpotPrice) {
return '期初标的价格 必须填写';
}
}
function setRemark(callback, trade, flag) {
if (page.needRemark) {
$("#extendInfo #editRemarks").val("");
layer.open({
type: 1,
title: "请填写修改说明",
shadeClose: false,
shade: 0.4,
area: ['600px', '280px'],
content: $("#extendInfo"),
btn: ['保存', '取消'],
yes: function (index, layero) {
var remark = $("#extendInfo #editRemarks").val();
if (!remark) {
main.alert("交易编辑时,说明为必填字段");
return;
}
trade.MetaDic["remark"] = remark;
callback(trade, flag);
layer.close(index);
},
cancel: function (index, layero) {
layer.close(index);
}
});
} else {
callback(trade, flag);
}
}
this.checkData = function (trade) {
let error = checkSubmitData(trade);
if (error) {
return main.alert(error);
}
return true;
}
this.saveTrade = function (trade, flag) {
if (!flag) {
setRemark(this.saveTrade, trade, 1);
return;
}
let error = checkSubmitData(trade);
if (error) {
return main.alert(error);
}
trade.ObservationDates = $("#setObservationDatesBtn").data().observationdates;
trade.ObservationStart = $("#setObservationDatesBtn").data().observationstart;
trade.MetaDic["主协议编号"] = $("#MainProtocolCode").val();
trade.MetaDic["补充协议编号"] = $("#SupProtocolCode").val();
trade.MetaDic["中央对手方清算"] = $("#IsCentralClearing").val();
trade.MetaDic["中央清算平台"] = $("#CentralClearingPaltform").val();
trade.MetaDic["交易平台"] = $("#TradingPaltform").val();
trade.MetaDic["ExchangeRate"] = $("#ExchangeRate").val();
if (page.showCCR) {
//if (trade.MarginTemplateName === "系统默认") {
trade.MetaDic["ccr_k"] = trade.ccr_k;
//}
trade.MetaDic["ignoreRiskExposure"] = trade.ignoreRiskExposure;
}
var tags = new Array();
$(".tag-context .tag-item").each(function (i, v) {
tags.push({ Id: $(v).data("id"), Name: $(v).data("name") });
});
trade.Tags = tags;
$("#btn_save").prop('disabled', true);
main.post("/forwardtrade/TradeEditJson", trade).done(function (resp) {
window.location.href = "/trade/tradeview?abstract=1&enid=" + resp.obj.EncryptId;
}).always(function () {
$("#btn_save").prop('disabled', false);
});
};
}());
var autoVariety, autoUnderlying, autoBasisUnderlying, salesCommissionCtrl;
let autoMarginTemplateName;
function __init(vue) {
salesCommissionCtrl = new SalesCommissionCtrl(document.getElementById('salesCommissionCtrl'), pageVue.Trade.SalesCommission);
//标的品种
autoVariety = FastVue.autocomplete(document.getElementById('VarietyId'), {
lookup: consVarieties, nameField: 'Name', valueField: 'id', searchField: ['Name', 'Code', 'PinYin'],
onSelect: function (data) { vue.changeVariety(data, 'select'); }
});
//标的资产
autoUnderlying = tradeHelper.UnderlyingAutoComplete('UnderlyingCode', { BlackLimit: 1 }).setFlag(consUnderlyingFlag);
autoUnderlying.onSelect(vue.changeUnderlying);
autoBasisUnderlying = tradeHelper.UnderlyingAutoComplete('BasisUnderlyingCode', { BlackLimit: 1 }).setFlag(consUnderlyingFlag2);
autoBasisUnderlying.onSelect(vue.changeBasisUnderlying);
//组合标的控件
synthenticPriceCtrl.init({
getSynthetic(input) {
return vue.viewState.synthetic;
},
setSynthetic(input, synthetic) {
vue.viewState.synthetic = synthetic;
vue.trade.SpotPrice = synthetic.Price;
vue.changeSpotPrice();
}
});
//标的控件初始化
if (vue.trade.UnderlyingCode) {
autoUnderlying.selectByCode(vue.trade.UnderlyingCode);
}
else {
autoUnderlying.selectFirst();
}
//挂钩标的初始化
if (vue.trade.BasisUnderlyingCode) {
autoBasisUnderlying.selectByCode(vue.trade.BasisUnderlyingCode);
} else {
vue.updateKey.basisUnderlying = 1;
}
//交易员
if (pageVue.CanSelectTrader) {
autoTrader = FastVue.autocomplete(document.getElementById('TraderId'), {
nameField: 'Name', valueField: 'id', searchField: ['Name', 'PinYin'], lookup: consTraders,
onSelect(data) {
vue.trade.TraderId = data.id;
vue.trade.TraderName = data.Name;
}
});
let traderId = pageVue.Trade.TraderId;
let trader = traderId ? consTraders.find(x => x.id === traderId) : null;
//if (!trader && pageVue.IsNew) {
// trader = consTraders[0];
// trader && (vue.trade.TraderId = trader.id);
//}
autoTrader.setData(trader);
}
//簿记账户
let autoAssetUnit = FastVue.autocomplete(document.getElementById('AssetId'), {
nameField: 'Name', valueField: 'id', searchField: ['Name', 'PinYin'], lookup: consAssetUnits,
onSelect(data) {
vue.trade.AssetId = data.id;
}
});
let assetId = pageVue.Trade.AssetId;
let asset = assetId ? consAssetUnits.find(x => x.id === assetId) : null;
if (!asset && pageVue.IsNew) {
asset = consAssetUnits[0];
asset && (vue.trade.AssetId = asset.id);
}
autoAssetUnit.setData(asset);
autoMarginTemplateName = FastVue.autocomplete(document.getElementById('MarginTemplateName'), {
nameField: 'Text', valueField: 'Value', searchField: ['Text'], lookup: page.tradeMarginTemplateItems,
onSelect(data) {
vue.trade.MarginTemplateName = data.Value;
vue.changeMarginTemplate();
}
});
let marginTemplateName = pageVue.Trade.MarginTemplateName;
let marginTemplate = marginTemplateName ? page.tradeMarginTemplateItems.find(x => x.Value === marginTemplateName) : null;
if (!marginTemplate && pageVue.IsNew) {
marginTemplate = page.tradeMarginTemplateItems[0];
marginTemplate && (vue.trade.MarginTemplateName = marginTemplate.Value);
}
autoMarginTemplateName.setData(marginTemplate);
//客户名称
if (pageVue.CanSelectClient) {
var width = 152;
for (var i = 0; i < consClients.length; i++) {
let ele = document.createElement('span')
ele.innerText = consClients[i].Name;
ele.style.fontSize = '14px';
document.documentElement.append(ele);
var charLength = ele.offsetWidth + 28;//滚动条
document.documentElement.removeChild(ele);
if (charLength > width) {
width = charLength
}
}
let autoClient = FastVue.autocomplete(document.getElementById('ClientId'), {
nameField: 'Name', valueField: 'id', searchField: ['Name', 'PinYin'], width: width,
lookup: consClients, onSelect: vue.changeClient
});
let clientId = pageVue.Trade.ClientId;
let client = clientId ? consClients.find(x => x.id === clientId) : null;
!client && pageVue.IsNew && (client = consClients[0]);
autoClient.setData(client);
vue.changeClient(client);
}
if (!vue.trade.StructureType) {
vue.trade.StructureType = "远期";
}
$("#IsCentralClearing").val(vue.trade.MetaDic["中央对手方清算"]);
$("#CentralClearingPaltform").val(vue.trade.MetaDic["中央清算平台"]);
$("#TradingPaltform").val(vue.trade.MetaDic["交易平台"]);
//远期组合标的时,需处理标的2的价格
if (vue.viewState.synthetic != null) {
$("#SpotPrice2").val("").attr('disabled', 'disabled');
vue.trade.SpotPrice1 = vue.trade.SpotPrice;
}
}
var vue = new Vue({
el: '#form1',
data: {
trade: pageVue.Trade,
viewState: {
variety: tradeHelper.getEmptyVariety(),
underlying: tradeHelper.getEmptyUnderlying(),
synthetic: null,
Extend: { TradingPlace: "柜台市场", ClearingAgency: "交易员方" },
priceModel: page.ForwardTradePriceModel,//0=标准模式;1=挂钩标的模式
},
tradeMarginTemplates: page.tradeMarginTemplates,
updateKey: { variety: 0, underlying: pageVue.IsNew ? 1 : 0, instrumentType: 0, basisUnderlying: pageVue.IsNew ? 1 : 0, client: 0 },
countRatio: 1,
isShowActualExerciseDate: false,
codes: []
},
created() {
for ([k, v] of Object.entries(this.trade)) {
v && k.endsWith('Date') && (this.trade[k] = v.substring(0, 10));
}
if (this.trade.MetaDic['组合标的']) {
this.viewState.synthetic = JSON.parse(this.trade.MetaDic['组合标的']);
}
this.viewState.Extend.TradingPlace = this.trade.MetaDic["交易场所"] || "";
this.viewState.Extend.ClearingAgency = this.trade.MetaDic["清算机构"] || "";
this.trade.ccr_k = this.trade.MetaDic["ccr_k"] || "1";
this.trade.ignoreRiskExposure = this.trade.MetaDic["ignoreRiskExposure"] || "0";
if (page.ForwardTradePriceModel === 0 && this.trade.MetaDic["期初信息"]) {
var spotInfo = JSON.parse(this.trade.MetaDic["期初信息"]);
this.trade.SpotPrice1 = spotInfo[0];
if (spotInfo.length > 1) {
this.trade.SpotPrice2 = spotInfo[1];
}
}
if (page.ForwardValueIsSupplyOrPay === 2) {
this.trade.MetaDic["IsSupplyForwardValue"] = this.trade.MetaDic["IsSupplyForwardValue"] == null ? "-1" : this.trade.MetaDic["IsSupplyForwardValue"];
} else {
this.trade.MetaDic["IsSupplyForwardValue"] = this.trade.MetaDic["IsSupplyForwardValue"] == null ? "0" : this.trade.MetaDic["IsSupplyForwardValue"];
}
this.calcForwardValue();
},
mounted() {
__init(this);
$("#MainProtocolCode").val(this.trade.MetaDic["主协议编号"]);
$("#SupProtocolCode").val(this.trade.MetaDic["补充协议编号"]);
let observationUnit = this.trade.MetaDic["敲入观察周期"];
if (observationUnit != null && observationUnit != undefined && observationUnit != "") {
num = observationUnit.substring(0, observationUnit.length - 1);
unit = observationUnit.substring(observationUnit.length - 1, observationUnit.length);
unitStr = "天";
switch (unit) {
case "W": unitStr = "周"; break;
case "M": unitStr = "月"; break;
case "Y": unitStr = "年"; break;
}
$("#ObservationRate").val("每" + num + unitStr).attr('lang', num + unit);
}
if (this.trade.UnderlyingCode != null) this.codes.push(this.trade.UnderlyingCode);
if (this.trade.BasisUnderlyingCode != null) this.codes.push(this.trade.BasisUnderlyingCode);
if (this.codes.length > 0) this.IsCodesExistsCommoditySpot(this.codes);
},
methods: {
//变更客户
changeClient(yldata) {
let client = yldata || { id: 0 };
$("#IsCentralClearing").val(client.IsCentralClearing);
$("#CentralClearingPaltform").val(client.CentralClearingPaltform);
$("#TradingPaltform").val(client.TradingPaltform);
this.clientCanSell = !!client.CanSell;
this.trade.ClientId = client.id;
!client.CanSell && (this.trade.BuySell = '卖出');
this.getMainProtocolCode();
if (pageVue.IsNew || this.updateKey.client !== 0) {
salesCommissionCtrl.changeSalesmen(client.id);
let data = page.tradeMarginTemplateItems[client.MarginOptionType == 3 ? 1 : 0];
this.trade.MarginTemplateName = data.Value;
autoMarginTemplateName.setData(data);
this.changeMarginTemplate();
}
this.updateKey.client++;
this.resetTradePrice(true);
},
//变更标的类型
changeInstrumentType() {
let nowTime = new Date().getTime();
if (nowTime < this.updateKey.variety + 300 || nowTime < this.updateKey.underlying + 300) return;
this.updateKey.instrumentType = nowTime;
autoUnderlying.selectFirst({ InstrumentTypes: [this.trade.UnderlyingInstrumentType] });
},
//设置标的品种
changeVariety(variety, flag) {
if (flag === 'select') {
if (this.viewState.variety.id === variety.id) return;
this.updateKey.variety = new Date().getTime();
this.trade.UnderlyingInstrumentType = variety.InstrumentType;
this.trade.QuoteCurrency = this.viewState.variety.QuoteCurrency;
autoUnderlying.setVarietyId(variety.id);
Object.assign(this.viewState.underlying, tradeHelper.getEmptyUnderlying(variety.id));
autoUnderlying.selectFirst(variety.id);
} else {
this.trade.QuoteCurrency = variety?.QuoteCurrency;
autoVariety.setData(variety);
}
Object.assign(this.viewState.variety, variety || tradeHelper.getEmptyVariety());
this.countRatio = variety.CountRatio;
this.calcForwardValue();
},
//变更标的
changeUnderlying(data) {
if (data.id == 0) {
return;
}
let trade = this.trade;
let editFirst = this.updateKey.underlying === 0;
this.updateKey.underlying = new Date().getTime();
Object.assign(this.viewState.underlying, data);
trade.UnderlyingId = data.id;
trade.UnderlyingCode = data.Code;
this.trade.UnderlyingCode = trade.UnderlyingCode;
trade.UnderlyingInstrumentType = data.InstrumentType;
$('#UnderlyingCode').attr('title', data.Code);
autoUnderlying.setVarietyId(data.VarietyId);
this.changeVariety(data.VarietyId ? ylotc.varieties.find(x => x.id === data.VarietyId) : null);
if (editFirst) {
return;
}
if (data.IsSynthetic) {
this.$nextTick(() => {
});
this.clearBasisUnderlyingCode();
this.getSyntheticPrices(data.Code, trade.TradeDate);
$("#SpotPrice2").attr('disabled', 'disabled');
} else {
this.getSpotPrice();
$("#SpotPrice2").removeAttr('disabled');
this.viewState.synthetic = null;
}
this.changeLots();
},
changeTradeDate() {
this.getNoRiskRate();
this.getSpotPrice();
},
changeExerciseDate() {
if (this.trade.SettlementDate !== this.trade.ExerciseDate) {
this.trade.SettlementDate = this.trade.ExerciseDate;
}
this.getNoRiskRate();
},
changeActualExerciseDate() {
},
//获取无风险利率
getNoRiskRate() {
var self = this;
main.post("/pricing/AjaxGetNoRiskRate", { startDate: this.trade.TradeDate, endDate: this.trade.ExerciseDate }).done(function (resp) {
self.trade.NoRiskRate = resp.obj.toFixed(4);
});
},
//变更挂钩标的
changeBasisUnderlying(data) {
let trade = this.trade;
let editFirst = this.updateKey.basisUnderlying === 0;
this.updateKey.basisUnderlying = 1;
autoBasisUnderlying.setFlag(consUnderlyingFlag);
trade.BasisUnderlyingId = data.id;
trade.BasisUnderlyingCode = data.Code;
$('#BasisUnderlyingCode').attr('title', data.Code);
if (editFirst) {
return;
}
//todo 计算期初价格 期初价格 = 挂钩标的价格 + 基差
this.getSpotPrice();
},
//清空挂钩标的
clearBasisUnderlyingCode() {
autoBasisUnderlying.setValue('');
this.trade.BasisUnderlyingId = '';
this.trade.BasisUnderlyingCode = '';
this.getSpotPrice();
this.trade.BasisGap = 0;
this.trade.SpotPrice2 = "";
},
//变更基差
changeBasisGap() {
this.getSpotPrice();
},
changeCustomPrice() {
var price = this.trade.SpotPrice1;
if (this.trade.BasisUnderlyingCode) {
price = price - this.trade.SpotPrice2;
}
this.trade.SpotPrice = consFormat.umprice(price);
this.changeSpotPrice();
},
//变更预付金模板
changeMarginTemplate() {
if (this.trade.MarginTemplateName === "系统默认") {
this.trade.MarginType = 0;
this.trade.MarginRate = 0;
this.trade.PositionMarginRate = 0;
}
else if (this.trade.MarginTemplateName === "无预付金") {
this.trade.MarginType = 1;
this.trade.MarginRate = 0;
this.trade.PositionMarginRate = 0;
}
else {
this.tradeMarginTemplates.forEach(x => {
if (this.trade.MarginTemplateName === x.Name) {
this.trade.MarginType = x.MarginType;
this.trade.MarginRate = x.InitialMarginRatio;
if (this.trade.MarginType == 3) {
this.trade.PositionMarginRate = 0;
}
else {
this.trade.PositionMarginRate = x.PositionMarginRatio;
}
}
});
}
},
//获取组合标的价格
getSyntheticPrices(underlyingCode, tradedate) {
let self = this;
main.post('/pricing/AjaxGetSyntheticPriceModel', { underlyingCode: underlyingCode, tradedate: tradedate }, false).done(function (resp) {
self.viewState.synthetic = resp.obj;
});
},
syntheticUnderlyingSetting() {
if (!this.viewState.synthetic || !this.trade.UnderlyingCode) {
return;
}
var url = "/SyntheticUnderlying/SyntheticUnderlyingView?syntheticUnderlyingName=" + encodeURIComponent(this.trade.UnderlyingCode);
main.open("合成价差期权标的设置", url, {});
},
//变更多头空头
changeOptionType() {
this.resetTradePrice(true);
},
//计算远期价值
//(交割价格- 期初价格) * 成交数量 * CountRatio *(多-1,空1]*(买入1,卖出 - 1)
calcForwardValue() {
let forwardValue = ((parseFloat(this.trade.Strike || 0)) - parseFloat((this.trade.SpotPrice || 0)))
* this.trade.TradeAmount * this.countRatio * (this.trade.OptionType == "看涨" ? -1 : 1) * (this.trade.BuySell == "买入" ? 1 : -1);
this.trade.ForwardValue = consFormat.umprice(forwardValue);
return forwardValue;
},
//重置开仓总费用
//补偿远期价值+开仓费用
resetTradePrice(blCalcForwardValue) {
let forwardValue = blCalcForwardValue ? this.calcForwardValue() : parseFloat(this.trade.ForwardValue);
let supplyPrice = this.trade.MetaDic["IsSupplyForwardValue"] == "1" ? forwardValue : this.trade.MetaDic["IsSupplyForwardValue"] == "-1" ? -forwardValue : 0;
let tradePrice = supplyPrice + this.trade.OpenCommission * this.trade.Lots;
this.trade.TradePrice = consFormat.TradePrice(tradePrice);
},
//变更交易手数
changeLots() {
this.trade.Notional = consFormat.notional(this.trade.Lots * this.viewState.underlying.ContractSize);
this.trade.OriginalNotional = this.trade.Notional;
this.trade.TradeAmount = consFormat.notional(this.trade.Lots * this.viewState.underlying.ContractSize / this.viewState.underlying.CountRatio);
this.resetTradePrice(true);
},
//变更交易数量
changeTradeAmount() {
this.trade.Lots = _.round(this.trade.TradeAmount * this.viewState.underlying.CountRatio / this.viewState.underlying.ContractSize, InputFormatLots.precision);
this.trade.Notional = consFormat.notional(this.trade.TradeAmount * this.viewState.underlying.CountRatio);
this.trade.OriginalNotional = this.trade.Notional;
this.resetTradePrice(true);
},
//获取期初价格
getSpotPrice() {
if (this.viewState.priceModel === 0) {
this.getSpotPriceStandardMode();
} else {
this.getSpotPriceHookPriceMode();
}
},
getSpotPriceStandardMode() {
var self = this;
this.getPrice(this.trade.UnderlyingCode, (obj) => {
self.trade.SpotPrice1 = consFormat.umprice(Number(obj.price));
self.trade.SpotPrice = consFormat.umprice(Number(self.trade.SpotPrice1 || 0) - Number(self.trade.SpotPrice2 || 0));
self.viewState.synthetic = obj.synthetic;
self.changeSpotPrice(false);
});
if (this.trade.BasisUnderlyingCode) {
this.getPrice(this.trade.BasisUnderlyingCode, (obj) => {
self.trade.SpotPrice2 = consFormat.umprice(Number(obj.price));
self.trade.SpotPrice = consFormat.umprice(Number(self.trade.SpotPrice1 || 0) - Number(self.trade.SpotPrice2 || 0));
self.changeSpotPrice(false);
});
}
},
getSpotPriceHookPriceMode() {
var self = this;
if (this.trade.BasisUnderlyingCode) {
this.getPrice(this.trade.BasisUnderlyingCode, (obj) => {
self.trade.SpotPrice = consFormat.umprice(Number(obj.price) + Number(self.trade.BasisGap || 0));
self.changeSpotPrice(false);
});
}
else {
this.getPrice(this.trade.UnderlyingCode, (obj) => {
self.trade.SpotPrice = consFormat.umprice(obj.price);
self.changeSpotPrice(false);
});
}
},
//获取标的价格
getPrice(underlyingCode, doneCallback) {
main.post("/pricing/AjaxGetUnderlyingPrice", { underlyingCode: underlyingCode, tradeDate: this.trade.TradeDate })
.done(function (resp) {
if (typeof (doneCallback) === 'function') {
doneCallback(resp.obj);
}
});
},
//变更期初价格
changeSpotPrice() {
let SpotPrice = this.trade.SpotPrice || 0;
if (!SpotPrice || SpotPrice === '-') {
SpotPrice = 0;
} else {
let precision = consFormat.umprice.precision || 0;
if (precision < 2) precision = 2;
let regex = new RegExp('^-?\\d*(\\.\\d{0,' + precision + '})?');
let match = regex.exec(SpotPrice);
if (match) {
if (match[0] !== SpotPrice) {
this.trade.SpotPrice = match[0];
SpotPrice = parseFloat(match[0]);
}
} else {
this.trade.SpotPrice = SpotPrice = 0;
}
}
if (this.viewState.underlying.IsSynthetic) {
this.trade.SpotPrice1 = this.trade.SpotPrice;
}
this.resetTradePrice(true);
},
changeSupplyForwardValue() {
this.resetTradePrice(true);
},
blurSpotPrice() {
!this.trade.SpotPrice && (this.trade.SpotPrice !== 0) && (this.trade.SpotPrice = 0);
},
getPriceTick() {
return this.viewState.variety ? parseFloat(this.viewState.variety.PriceTick) || 0.1 : 0.1;
},
//变更交割价格
changeStrike() {
this.resetTradePrice(true);
},
//名义本金 保存交易的时候会重新计算 --- 这个是为了计算浙期的初始预付金
//priceModel 基差价差 名义本金 取 最大
changeStockEqvNotional() {
if (this.viewState.priceModel === 0 && this.trade.SpotPrice1 != null && this.trade.SpotPrice2 != null) {
let SpotPrice1 = parseFloat(this.trade.SpotPrice1 || 0);
let SpotPrice2 = parseFloat(this.trade.SpotPrice2 || 0);
if (SpotPrice1 > SpotPrice2) {
this.trade.StockEqvNotional = consFormat.StockEqvNotional(this.trade.SpotPrice1 * this.trade.Notional);
} else {
this.trade.StockEqvNotional = consFormat.StockEqvNotional(this.trade.SpotPrice2 * this.trade.Notional);
}
}
},
saveTrade() {
this.trade.SalesCommission = salesCommissionCtrl.getValue();
if (this.viewState.synthetic) {
this.trade.MetaDic["组合标的"] = JSON.stringify(this.viewState.synthetic);
} else {
delete this.trade.MetaDic["组合标的"];
}
if (this.viewState.priceModel === 0) {
var spotInfo = [consFormat.umprice(this.trade.SpotPrice1)];
if (this.trade.BasisUnderlyingCode) {
spotInfo.push(consFormat.umprice(this.trade.SpotPrice2));
}
this.trade.MetaDic["期初信息"] = JSON.stringify(spotInfo);
} else {
delete this.trade.MetaDic["期初信息"];
}
this.trade.MetaDic["敲入观察周期"] = $("#ObservationRate").attr('lang');
submitHandler.saveTrade(this.trade);
},
//获取系统计算的初始预付金
getInitialMargin() {
var self = this;
this.changeStockEqvNotional();
//检查数据
if (!submitHandler.checkData(this.trade)) {
return false;
}
main.post("/forwardtrade/AjaxGetInitialMargin_Forward", { trade: this.trade })
.done(function (resp) {
if (pageVue.ClientUsedForCalc && pageVue.TwoSideMargin &&
!self.viewState.TwoSideMargin && resp.obj < 0) {
self.trade.InitialMargin = 0;
}
else {
self.trade.InitialMargin = consFormat.TradePrice(resp.obj);
}
});
},
//变更开仓费用
changeOpenCommission() {
this.resetTradePrice();
},
//变更开仓总费用
//开仓费用 = (开仓总费用 -(补充远期价值))/ 手数
changeTradePrice() {
let supplyPrice = this.trade.MetaDic["IsSupplyForwardValue"] == "1" ? this.trade.ForwardValue : this.trade.MetaDic["IsSupplyForwardValue"] == "-1" ? -this.trade.ForwardValue : 0;
this.trade.OpenCommission = consFormat.TradePrice((parseFloat(this.trade.TradePrice) - parseFloat(supplyPrice)) / this.trade.Lots);
},
//变更交易场所
changeTradingPlace() {
this.trade.MetaDic["交易场所"] = this.viewState.Extend.TradingPlace;
},
//变更清算机构
changeClearingAgency() {
this.trade.MetaDic["清算机构"] = this.viewState.Extend.ClearingAgency;
},
changeObservationRemark1(Comments) {
if (Comments != "" || this.trade.MetaDic["ObservationRemark1"] != undefined) this.trade.MetaDic["ObservationRemark1"] = Comments;
},
getObservationRemark1() {
return this.trade.MetaDic["ObservationRemark1"];
},
changeMainProtocolCode() {
this.getSupProtocolCode();
},
getMainProtocolCode() {
$("#MainProtocolCode option").remove();
main.post("/Client/getMainProtocolCodes", { clientId: $("#ClientId").val() }, { async: false }).done(function (resp) {
var obj = $("#MainProtocolCode");
_.forEach(resp, (v) => {
obj.append("<option >" + v.Text + "</option>");
})
});
this.getSupProtocolCode()
},
getSupProtocolCode() {
$("#SupProtocolCode option").remove();
if ($("#MainProtocolCode").val()) {
main.post("/Client/getSideProtocols", { mainProtocol: $("#MainProtocolCode").val() }, { async: false }).done(function (resp) {
var obj = $("#SupProtocolCode");
_.forEach(resp, (v) => {
obj.append("<option >" + v + "</option>");
})
});
}
},
//交易审批
submit(status) {
var pop = '';
if (status === 'pass') {
pop = "确认通过审批?";
}
if (status === 'reject') {
pop = "确认拒绝?";
}
var confirmFunc = function (additionalProcessing) {
var pData = { tradeId: pageVue.Trade.id, status: status, text: "" };
if (!main.isEmpty(additionalProcessing)) {
pData.additionalProcessing = additionalProcessing;
}
main.post("/processtradelog/UpdateTradeProcessLog", pData).done(
function (data) {
if (data.obj && data.obj.proccessType == "AdditionalProcessing") {
if (data.obj.type == "LackOfMoney") {
var htmlContent = `<div style="padding:10px">${data.obj.message}</div>`;
var lackMoneyConfirmLayer = main.open2("提示",
htmlContent,
{
area: ["430px", "175px"],
btn: ['交易特批', '取消'],
yes: function (index, layero) {
var layerIndex = lackMoneyConfirmLayer;
main.confirm("客户资金或授信不足,强制成交会导致本机构产生风险!要继续审批通过?", function () {
layer.close(layerIndex);
confirmFunc("LackOfMoney");
});
},
cancel: function (index, layero) {
if (window.parent && window.parent.reloadtrade) {
window.parent.reloadtrade();
}
(parent || window).layer.closeAll();
}
});
console.log("lackMoneyConfirmLayer:" + lackMoneyConfirmLayer);
}
return;
}
(parent || window).main.message(data.msg);
if (page.generateAmendDoc) {
if (data.obj && data.obj.generateChangeSuccess) {
main.downloadFiles(data.obj.url);
try { window.parent.reloadtrade(); } catch (e) { }
}
}
if (page.needSendChangeEmail) {
if (data.obj && data.obj.generateChangeSuccess) {
main.confirm("确认发送变更确认书?",
function () {
main.post("/trade/SendChangeConfirmEmails", { tradeids: tradeId }).done(
function (data) {
if (data.success) {
main.message("发送成功");
} else {
main.message(data.msg);
}
try {
window.parent.reloadtrade();
} catch (e) {
}
});
});
} else {
try {
window.parent.reloadtrade();
} catch (e) {
}
}
}
else {
try { window.parent.reloadtrade(); } catch (e) { }
}
if (parent) {
parent.layer.closeAll();
}
});
}
main.confirm(pop, confirmFunc);
},
IsCodesExistsCommoditySpot(codes) {
//判断标的是否为现货
var flag = tradeHelper.IsCodesExistsCommoditySpot(codes);
if (flag) {
this.isShowActualExerciseDate = true;
} else {
this.isShowActualExerciseDate = false;
}
}
},
computed: {
showMaturityDate() {
return this.viewState.underlying.InstrumentType === 'CommodityFutures';
},
showRunHe() {
return page.showRunHe;
},
isShowActualExerciseDate() {
return this.isShowActualExerciseDate && pageData.showZheQi;
},
maxTradeDate() {
let exerciseDate = this.trade.ExerciseDate;
return exerciseDate;// && exerciseDate <= pageVue.SysDate ? exerciseDate : pageVue.SysDate;
},
inputFormatTradeAmount() {
let fmt = { precision: consFormat.notional.precision, append: '' };
let variety = this.viewState.variety;
if (variety) {
var QuoteUnit = variety.QuoteUnit;
var unit = QuoteUnit.substring(QuoteUnit.lastIndexOf('/') + 1).trim();
fmt.append = unit === "500千克" ? "吨" : unit || '';
}
return fmt;
},
Compositespread() {
return this.trade.TradeType === "合成价差期权";
}
},
watch: {
'trade.UnderlyingCode': {
handler(newVal, oldVal) {
//if (this.codes.length > 0) {
// this.codes.splice(this.codes.length - 1, 1);
//}
if (newVal !== null && newVal !== "") {
this.codes[0] = newVal;
}
this.IsCodesExistsCommoditySpot(this.codes);
},
immediate: false
},
'trade.BasisUnderlyingCode': {
handler(newVal, oldVal) {
//if (this.codes.length == 2) {
// this.codes.splice(1, 1);
//}
if (newVal !== null && newVal !== "") {
this.codes[1] = newVal;
}
else {
delete this.codes[1];
this.codes.length = 1;
}
this.IsCodesExistsCommoditySpot(this.codes);
},
immediate: false
}
},
components: {
'vue-datepicker': FastVue.vueDatePicker(),
'vue-number-input': FastVue.vueNumberInput()
}
});
//ESC
$(document).keyup(function (event) {
if (event.keyCode === 27) {
window.parent.layer.closeAll();
}
});
function setObservationDates(thisobj) {
var endTime = $("[name = 'TradeEndDate']").val();
var meg = "到期日期";
if ($("#UnderlyingInstrumentType").val() == "CommoditySpot" && page.showZeQi) {
endTime = $("[name = 'ActualExerciseDate']").val();
meg = "实际到期日期";
}
if (main.isEmpty(endTime)) {
main.message(`请输入${meg}`);
return false;
}
var tradeDate = $("[name = 'TradeDate']").val();
var startTime = $(thisobj).data("observationstart");
if (main.isEmpty(startTime)) {
startTime = endTime;
}
var observationDates = $(thisobj).data("observationdates");
var observationNum = $(thisobj).data("observationnum");
var observationUnit = $(thisobj).data("observationunit");
var observationHolidayType = $(thisobj).data("observationholidaytype");
var btnId = $(thisobj).attr('id');
sessionStorage.setItem(btnId + "_observationdates", observationDates);
var Comments = vue.getObservationRemark1();
Comments = Comments == undefined ? "" : Comments;
let ObservationRate = $("#ObservationRate").attr('lang');
if (ObservationRate != null && ObservationRate != undefined && ObservationRate != "") {
num = ObservationRate.substring(0, ObservationRate.length - 1);
unit = ObservationRate.substring(ObservationRate.length - 1, ObservationRate.length);
observationNum = num;
observationUnit = unit;
}
layer.open({
type: 2,
title: "均价结算设置",
shadeClose: false,
shade: 0.4,
area: ['500px', '560px'],
content: "/trade/tradeAveragePriceDates?observationNum=" + observationNum + "&observationUnit=" + observationUnit + "&observationHolidayType=" + observationHolidayType + "&startTime=" + startTime + "&endTime=" + endTime + "&tradeDate=" + tradeDate + "&btnId=" + btnId + "&Comments=" + Comments
});
}
// 设置观察日窗口返回的函数
function getObservationDatesSetting(startTime, observationNum, observationUnit, observationHolidayType, observationDates, alignEnd, btnId, Comments) {
$("#" + btnId).data("observationdates", observationDates);
$("#" + btnId).data("observationnum", observationNum);
$("#" + btnId).data("observationunit", observationUnit);
$("#" + btnId).data("observationholidaytype", observationHolidayType);
$("#" + btnId).data("alignend", alignEnd);
$("#" + btnId).data("observationstart", startTime);
var observationUnitStr = "天";
switch (observationUnit) {
case "W": observationUnitStr = "周"; break;
case "M": observationUnitStr = "月"; break;
case "Y": observationUnitStr = "年"; break;
}
$("#ObservationRate").val("每" + observationNum + observationUnitStr).attr('lang', observationNum + observationUnit);
vue.changeObservationRemark1(Comments);
}