Skip to content
This repository has been archived by the owner on Aug 15, 2023. It is now read-only.

Commit

Permalink
Fix: zero usd liability hedging (#98)
Browse files Browse the repository at this point in the history
* fix: implement and use close position
* fix: display correct balance type
Co-authored-by: Sebastien Verreault <[email protected]>
  • Loading branch information
sebastienverreault authored May 19, 2022
1 parent 654df89 commit 6f28888
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 15 deletions.
4 changes: 3 additions & 1 deletion dealer/src/Dealer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,13 +204,15 @@ export class Dealer {
if (usdLiability < hedgingBounds.MINIMUM_POSITIVE_LIABILITY_USD) {
logger.debug(
{ usdLiability },
"No liabilities to hedge, skipping the order loop",
"No liabilities to hedge, skipping the order loop and closing position if any",
)

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.results.orderLoopSkipped`]: true,
})

await this.strategy.closePosition()

result.updatePositionSkipped = true
} else {
logger.debug("starting with order loop")
Expand Down
8 changes: 4 additions & 4 deletions dealer/src/DealerRemoteWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,21 +108,21 @@ export class DealerRemoteWallet implements GaloyWallet {
(wallet) => wallet?.id === "BTCWallet",
)
const btcWalletId = btcWallet?.id
const btcWalletBalance = btcWallet?.balance ?? NaN
const btcWalletBalance: number = btcWallet?.balance ?? NaN

const usdWallet = result.data.wallets?.find(
(wallet) => wallet?.id === "USDWallet",
)
const usdWalletId = usdWallet?.id
const usdWalletBalance = usdWallet?.balance ?? NaN
const usdWalletBalance: number = usdWallet?.balance ?? NaN

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.results.btcWalletId`]: btcWalletId,
[`${SemanticAttributes.CODE_FUNCTION}.results.btcWalletBalance`]:
btcWalletBalance,
String(btcWalletBalance),
[`${SemanticAttributes.CODE_FUNCTION}.results.usdWalletId`]: usdWalletId,
[`${SemanticAttributes.CODE_FUNCTION}.results.usdWalletBalance`]:
usdWalletBalance,
String(usdWalletBalance),
})

return {
Expand Down
12 changes: 6 additions & 6 deletions dealer/src/DealerRemoteWalletV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,25 +109,25 @@ export class DealerRemoteWalletV2 implements GaloyWallet {
(wallet) => wallet?.__typename === "BTCWallet",
)
const btcWalletId = btcWallet?.id
const btcWalletBalance = (btcWallet?.balance ?? NaN) - btcBalanceOffset
const btcWalletBalance: number = (btcWallet?.balance ?? NaN) - btcBalanceOffset

const usdWallet = me?.defaultAccount?.wallets?.find(
(wallet) => wallet?.__typename === "UsdWallet",
)
const usdWalletId = usdWallet?.id
const usdWalletBalance = (usdWallet?.balance ?? NaN) - usdBalanceOffset
const usdWalletBalance: number = (usdWallet?.balance ?? NaN) - usdBalanceOffset

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.results.btcWalletId`]: btcWalletId,
[`${SemanticAttributes.CODE_FUNCTION}.results.btcWalletBalance`]:
btcWalletBalance,
String(btcWalletBalance),
[`${SemanticAttributes.CODE_FUNCTION}.results.btcBalanceOffset`]:
btcBalanceOffset,
String(btcBalanceOffset),
[`${SemanticAttributes.CODE_FUNCTION}.results.usdWalletId`]: usdWalletId,
[`${SemanticAttributes.CODE_FUNCTION}.results.usdWalletBalance`]:
usdWalletBalance,
String(usdWalletBalance),
[`${SemanticAttributes.CODE_FUNCTION}.results.usdBalanceOffset`]:
usdBalanceOffset,
String(usdBalanceOffset),
})

return {
Expand Down
8 changes: 4 additions & 4 deletions dealer/src/DealerSimulatedWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,21 +108,21 @@ export class DealerSimulatedWallet implements GaloyWallet {
(wallet) => wallet?.id === "BTCWallet",
)
const btcWalletId = btcWallet?.id
const btcWalletBalance = btcWallet?.balance ?? NaN
const btcWalletBalance: number = btcWallet?.balance ?? NaN

const usdWallet = result.data.wallets?.find(
(wallet) => wallet?.id === "USDWallet",
)
const usdWalletId = usdWallet?.id
const usdWalletBalance = usdWallet?.balance ?? NaN
const usdWalletBalance: number = usdWallet?.balance ?? NaN

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.results.btcWalletId`]: btcWalletId,
[`${SemanticAttributes.CODE_FUNCTION}.results.btcWalletBalance`]:
btcWalletBalance,
String(btcWalletBalance),
[`${SemanticAttributes.CODE_FUNCTION}.results.usdWalletId`]: usdWalletId,
[`${SemanticAttributes.CODE_FUNCTION}.results.usdWalletBalance`]:
usdWalletBalance,
String(usdWalletBalance),
})

return {
Expand Down
2 changes: 2 additions & 0 deletions dealer/src/ExchangeBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,8 @@ export abstract class ExchangeBase {
btcPriceInUsd: number,
): Promise<Result<GetAccountAndPositionRiskResult>>

abstract closePosition(instrumentId: string): Promise<Result<boolean>>

abstract getInstrumentDetails(): Promise<Result<GetInstrumentDetailsResult>>

abstract getPublicFundingRate(): Promise<Result<GetPublicFundingRateResult>>
Expand Down
1 change: 1 addition & 0 deletions dealer/src/HedgingStrategyTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export interface HedgingStrategy {

isDepositCompleted(address: string, amountInSats: number): Promise<Result<boolean>>
isWithdrawalCompleted(address: string, amountInSats: number): Promise<Result<boolean>>
closePosition(): Promise<Result<boolean>>
updatePosition(
liabilityInUsd: number,
btcPriceInUsd: number,
Expand Down
110 changes: 110 additions & 0 deletions dealer/src/OkexExchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,63 @@ export class OkexExchange extends ExchangeBase {
return ret as Result<GetAccountAndPositionRiskResult>
}

public async closePosition(instrumentId: string): Promise<Result<boolean>> {
const ret = await asyncRunInSpan(
"app.okexExchange.closePosition",
{
[SemanticAttributes.CODE_FUNCTION]: "closePosition",
[SemanticAttributes.CODE_NAMESPACE]: "app.okexExchange",
[`${SemanticAttributes.CODE_FUNCTION}.params.instrumentId`]: instrumentId,
[`${SemanticAttributes.CODE_FUNCTION}.sub.method`]:
"privatePostTradeClosePosition",
},
async () => {
try {
const config = this.exchangeConfig as OkexExchangeConfiguration
const params = {
instId: instrumentId,
mgnMode: config.marginMode,
autoCxl: true,
}

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.sub.params`]: JSON.stringify(params),
})

const response = await this.exchange.privatePostTradeClosePosition(params)
this.logger.debug(
{ config, params, response },
"exchange.privatePostTradeClosePosition({params}) returned: {response}",
)

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.results.result`]:
JSON.stringify(response),
})

return {
ok: true,
value: true,
}
} catch (error) {
recordExceptionInCurrentSpan({ error, level: ErrorLevel.Warn })
return { ok: true, value: true }
}
},
)
return ret as Result<boolean>
}

public async getInstrumentDetails(): Promise<Result<GetInstrumentDetailsResult>> {
const ret = await asyncRunInSpan(
"app.okexExchange.getInstrumentDetails",
{
[SemanticAttributes.CODE_FUNCTION]: "getInstrumentDetails",
[SemanticAttributes.CODE_NAMESPACE]: "app.okexExchange",
[`${SemanticAttributes.CODE_FUNCTION}.sub.method`]: "publicGetPublicInstruments",
[`${SemanticAttributes.CODE_FUNCTION}.sub.params.instType`]:
SupportedInstrumentType.Swap,
[`${SemanticAttributes.CODE_FUNCTION}.sub.params.instId`]: this.instrumentId,
},
async () => {
try {
Expand All @@ -157,6 +208,12 @@ export class OkexExchange extends ExchangeBase {
{ instrumentId: this.instrumentId, response },
"publicGetPublicInstruments({instrumentId}) returned: {response}",
)

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.sub.results.result`]:
JSON.stringify(response),
})

assert(response, ApiError.UNSUPPORTED_API_RESPONSE)
assert(
response.data[0].ctValCcy === TradeCurrency.USD,
Expand Down Expand Up @@ -193,6 +250,8 @@ export class OkexExchange extends ExchangeBase {
{
[SemanticAttributes.CODE_FUNCTION]: "getPublicFundingRate",
[SemanticAttributes.CODE_NAMESPACE]: "app.okexExchange",
[`${SemanticAttributes.CODE_FUNCTION}.sub.method`]: "publicGetPublicFundingRate",
[`${SemanticAttributes.CODE_FUNCTION}.sub.params.instId`]: this.instrumentId,
},
async () => {
try {
Expand All @@ -203,6 +262,12 @@ export class OkexExchange extends ExchangeBase {
{ instrumentId: this.instrumentId, response },
"exchange.publicGetPublicFundingRate({instrumentId}) returned: {response}",
)

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.sub.results.result`]:
JSON.stringify(response),
})

assert(response, ApiError.UNSUPPORTED_API_RESPONSE)
assert(
response.data[0].instId === this.instrumentId,
Expand Down Expand Up @@ -241,6 +306,10 @@ export class OkexExchange extends ExchangeBase {
{
[SemanticAttributes.CODE_FUNCTION]: "getPublicMarkPrice",
[SemanticAttributes.CODE_NAMESPACE]: "app.okexExchange",
[`${SemanticAttributes.CODE_FUNCTION}.sub.method`]: "publicGetPublicMarkPrice",
[`${SemanticAttributes.CODE_FUNCTION}.sub.params.instType`]:
SupportedInstrumentType.Swap,
[`${SemanticAttributes.CODE_FUNCTION}.sub.params.instId`]: this.instrumentId,
},
async () => {
try {
Expand All @@ -252,6 +321,12 @@ export class OkexExchange extends ExchangeBase {
{ instrumentId: this.instrumentId, response },
"exchange.publicGetPublicMarkPrice({instrumentId}) returned: {response}",
)

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.sub.results.result`]:
JSON.stringify(response),
})

assert(response, ApiError.UNSUPPORTED_API_RESPONSE)
assert(
response?.data[0]?.instType === SupportedInstrumentType.Swap,
Expand Down Expand Up @@ -290,6 +365,9 @@ export class OkexExchange extends ExchangeBase {
{
[SemanticAttributes.CODE_FUNCTION]: "getMarketIndexTickers",
[SemanticAttributes.CODE_NAMESPACE]: "app.okexExchange",
[`${SemanticAttributes.CODE_FUNCTION}.sub.method`]: "publicGetMarketIndexTickers",
[`${SemanticAttributes.CODE_FUNCTION}.sub.params.instId`]:
SupportedInstrument.OKEX_BTC_USD_SPOT,
},
async () => {
try {
Expand All @@ -300,6 +378,12 @@ export class OkexExchange extends ExchangeBase {
{ instrumentId: this.instrumentId, response },
"exchange.publicGetMarketIndexTickers({instrumentId}) returned: {response}",
)

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.sub.results.result`]:
JSON.stringify(response),
})

assert(response, ApiError.UNSUPPORTED_API_RESPONSE)
assert(
response?.data[0]?.instId === SupportedInstrument.OKEX_BTC_USD_SPOT,
Expand Down Expand Up @@ -436,6 +520,8 @@ export class OkexExchange extends ExchangeBase {
[SemanticAttributes.CODE_FUNCTION]: "withdrawOnLightning",
[SemanticAttributes.CODE_NAMESPACE]: "app.okexExchange",
[`${SemanticAttributes.CODE_FUNCTION}.params.args`]: JSON.stringify(args),
[`${SemanticAttributes.CODE_FUNCTION}.sub.method`]:
"privatePostAssetWithdrawalLightning",
},
async () => {
try {
Expand All @@ -444,11 +530,22 @@ export class OkexExchange extends ExchangeBase {
invoice: args.invoice,
pwd: this.fundingPassword,
}

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.sub.params`]: JSON.stringify(params),
})

const response = await this.exchange.privatePostAssetWithdrawalLightning(params)
this.logger.debug(
{ params, response },
"privatePostAssetWithdrawalLightning({params}) returned: {response}",
)

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.sub.results.result`]:
JSON.stringify(response),
})

assert(response, ApiError.UNSUPPORTED_API_RESPONSE)
assert(response.code === "0", ApiError.UNSUPPORTED_API_RESPONSE)
assert(response.data[0].wdId, ApiError.UNSUPPORTED_API_RESPONSE)
Expand Down Expand Up @@ -483,6 +580,8 @@ export class OkexExchange extends ExchangeBase {
[SemanticAttributes.CODE_FUNCTION]: "depositOnLightning",
[SemanticAttributes.CODE_NAMESPACE]: "app.okexExchange",
[`${SemanticAttributes.CODE_FUNCTION}.params.args`]: JSON.stringify(args),
[`${SemanticAttributes.CODE_FUNCTION}.sub.method`]:
"privateGetAssetDepositLightning",
},
async () => {
try {
Expand All @@ -491,11 +590,22 @@ export class OkexExchange extends ExchangeBase {
amt: args.amountInSats,
to: AccountTypeToId.Trading,
}

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.sub.params`]: JSON.stringify(params),
})

const response = await this.exchange.privateGetAssetDepositLightning(params)
this.logger.debug(
{ params, response },
"privateGetAssetDepositLightning({params}) returned: {response}",
)

addAttributesToCurrentSpan({
[`${SemanticAttributes.CODE_FUNCTION}.sub.results.result`]:
JSON.stringify(response),
})

assert(response, ApiError.UNSUPPORTED_API_RESPONSE)
assert(response.data[0].invoice, ApiError.UNSUPPORTED_API_RESPONSE)

Expand Down
10 changes: 10 additions & 0 deletions dealer/src/OkexPerpetualSwapStrategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,16 @@ export class OkexPerpetualSwapStrategy implements HedgingStrategy {
return { ok: true, value: false }
}

public async closePosition(): Promise<Result<boolean>> {
const instrumentId = this.instrumentId
const result = await this.exchange.closePosition(instrumentId)
this.logger.debug(
{ instrumentId, result },
"exchange.closePosition({instrumentId}) returned: {result}",
)
return result
}

public async updatePosition(
liabilityInUsd: number,
btcPriceInUsd: number,
Expand Down

0 comments on commit 6f28888

Please sign in to comment.