package models

import "github.com/shopspring/decimal"

//Liquidation 强平计算公式字段
type Liquidation struct {
	WalletBalance  decimal.Decimal //账户余额,钱包余额= 1,535,443.01
	TMM1           decimal.Decimal //（TMM1）其它合约下的全部保证金（除合约1外）= 71200.81144,维持保证金=名义价值*维持保证金率-维持保证金速算額,名义价值=价格*数量,拿标记价格计算
	UPNL1          decimal.Decimal //全部其它合约的未实现盈亏（除合约1外）= -56,249.35
	CumB           decimal.Decimal //单向模式下合约1的维持保证金速算額= 135,365.00
	CumL           decimal.Decimal //开多合约1下的维持保证金速算額（双向持仓模式）= 0
	CumS           decimal.Decimal //开空合约1下的维持保证金速算額（双向持仓模式）= 0
	Side1BOTH      int             //合约1的方向（单向持仓模式）；“1”代表开多持仓；“-1”代表开空持仓= 1
	Position1BOTH  decimal.Decimal //合约1的持仓大小（单向持仓模式）；无论开多或开空，取绝对值= 3,683.979
	EP1BOTH        decimal.Decimal //合约1的头寸价格（单向持仓模式）=1,456.84
	Position1LONG  decimal.Decimal //开多仓位大小（双向持仓模式）；无论开多或开空，取绝对值= 0
	EP1LONG        decimal.Decimal //开多持仓的头寸（双向持仓模式）；无论开多或开空，取绝对值= 0
	Position1SHORT decimal.Decimal //开空仓位大小（双向持仓模式）；无论开多或开空，取绝对值= 0
	EP1SHORT       decimal.Decimal //开空持仓的头寸（双向持仓模式）；无论开多或开空，取绝对值= 0
	MMRB           decimal.Decimal //单向持仓模式合约的维持保证金费率= 10%
	MMRL           decimal.Decimal //开多合约的维持保证金费率（双向持仓模式）= 0
	MMRS           decimal.Decimal //开空合约的维持保证金费率（双向持仓模式）= 0
}

//CalculateLiquidationPrice 计算强平公式
func (lq Liquidation) CalculateLiquidationPrice() decimal.Decimal {
	//d1=WB-TMM1+UPNL1+CumB+CumL+CumS-Side1BOTH*Position1BOTH*EP1BOTH-Position1LONG*EP1LONG+Position1SHORT*EP1SHORT
	t1 := lq.WalletBalance
	if lq.TMM1.Cmp(decimal.Zero) != 0 {
		t1 = t1.Sub(lq.TMM1)
	}
	if lq.UPNL1.Cmp(decimal.Zero) != 0 {
		t1 = t1.Add(lq.UPNL1)
	}
	if lq.CumB.Cmp(decimal.Zero) != 0 {
		t1 = t1.Add(lq.CumB)
	}
	if lq.CumL.Cmp(decimal.Zero) != 0 {
		t1 = t1.Add(lq.CumL)
	}
	if lq.CumS.Cmp(decimal.Zero) != 0 {
		t1 = t1.Add(lq.CumS)
	}

	position1BOTH := lq.Position1BOTH
	side1BOTH := decimal.NewFromInt32(int32(lq.Side1BOTH))
	position1LONG := lq.Position1LONG
	position1SHORT := lq.Position1SHORT

	d1 := t1.Sub(side1BOTH.Mul(position1BOTH).Mul(lq.EP1BOTH)).
		Sub(position1LONG.Mul(lq.EP1LONG)).Add(position1SHORT.Mul(lq.EP1SHORT))

	//d2=Position1BOTH*MMRB+Position1LONG*MMRL+Position1SHORT*MMRS-Side1BOTH*Position1BOTH-Position1LONG+Position1SHORT
	t2 := position1BOTH.Mul(lq.MMRB).Add(position1LONG.Mul(lq.MMRL)).Add(position1SHORT.Mul(lq.MMRS))
	t2 = t2.Sub(side1BOTH.Mul(position1BOTH))
	d2 := t2.Sub(position1LONG).Add(position1SHORT)
	//LP1= d1/d2

	return d1.Div(d2)
}
