Skip to content

Instantly share code, notes, and snippets.

@ss-sonic
Last active July 10, 2020 09:47
Show Gist options
  • Select an option

  • Save ss-sonic/e9b73b9af748f5059c7f6c4d0f2dd2f5 to your computer and use it in GitHub Desktop.

Select an option

Save ss-sonic/e9b73b9af748f5059c7f6c4d0f2dd2f5 to your computer and use it in GitHub Desktop.
exitTrade = async ({ sourceExitLimitPrice, circuitBreaker }) => {
this.log.debug(`Placing Exit order on Source at ${sourceExitLimitPrice} ${sourceExitLimitPrice}`)
let options = { timeInForce: "FOK" }
if (!circuitBreaker) {
options["price"] = sourceExitLimitPrice
options["premimumMargin"] = this.premimumMargin
options["quantityFraction"] = this.currentStackCount
}
if (this.executionType === "MARKET") {
delete options.price
delete options.premimumMargin
}
let sourceOrder = await this.sourceClient.futuresClosePositionAsync({
symbol: this.sourceClient.symbol,
options
})
this.log.debug(`Placed Exit Order on ${this.sourceClient.name}`, sourceOrder)
if (sourceOrder.status != "FILLED")
return { sourceOrder }
delete options.price
delete options.premimumMargin
delete options.timeInForce
let targetOrder = await this.targetSafeExit(sourceOrder, options)
this.log.debug(`Placed Exit Order on ${this.targetClient.name}`, targetOrder)
return { sourceOrder, targetOrder, circuitBreaker }
}
targetSafeExit = async (sourceOrder, options) => {
try {
let targetOrder = await this.executeWithRetry({
executionMethod: this.targetClient.futuresClosePositionAsync,
executionInstruction: {
symbol: this.targetClient.symbol,
options
},
retryCount: this.retryCount
})
return targetOrder
} catch (error) {
if (error.message == errors.NO_POSITION) {
throw error
}
this.log.debug(`Failed Exit on Target Exchange, Hedging on Source`, error.toJSON())
let counterSourceOrder
let executionMethod = sourceOrder.side == "SELL" ?
this.sourceClient.futuresMarketBuyAsync :
this.sourceClient.futuresMarketSellAsync
try {
counterSourceOrder = await this.executeWithRetry({
executionMethod,
executionInstruction: {
symbol: this.sourceClient.symbol,
quantity: sourceOrder.quantity
},
retryCount: this.retryCount
})
await this.adjustSpreadAfterEntry({ ordersPlaced: true })
this.blockExitQueue(15)
} catch (error) {
throw new APIError({
message: errors.HEDGE_FAILED,
name: error.name,
meta: {
message: error.message,
name: error.name,
...error.meta
}
})
}
throw new APIError({
message: "Failed Exit on Target Exchange, Hedged on Source",
name: error.name,
stack: error.stack,
meta: {
sourceOrder,
counterSourceOrder,
message: error.message
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment