hootnot / oanda-api-v20

OANDA REST-V20 API wrapper. Easy access to OANDA's REST v20 API with oandapyV20 package. Checkout the Jupyter notebooks!
MIT License
398 stars 107 forks source link

question for hootnot 2 #199

Closed traveller1011 closed 1 year ago

traveller1011 commented 1 year ago

CONTEXT

  1. imagine a situation where multiple trades are open in the same subaccount, same instrument, and unit quantity... Like this:

image

  1. attempting to close all but one of these open trades will result in order being cancelled for FIFO reasons.

QUESTION

Do you know any tricks to test which trade is "allowed" to be closed per US FIFO law? Or stated differently, given a list of trades, can we determine which ones are NOT eligible to be closed?

I understand I could query for the lowest trade_id among such a group, and that should, by definition, work. But I thought maybe you might know a better way.

This is all the info I see when I query for a trade... nothing lends itself to "can be closed", or im just blind

{
    "trade": {
        "id": "148",
        "instrument": "EUR_USD",
        "price": "1.09190",
        "openTime": "2023-01-26T01:48:04.744487039Z",
        "initialUnits": "-1",
        "initialMarginRequired": "0.0218",
        "state": "OPEN",
        "currentUnits": "-1",
        "realizedPL": "0.0000",
        "financing": "0.0001",
        "dividendAdjustment": "0.0000",
        "unrealizedPL": "0.0057",
        "marginUsed": "0.0217"
    },
    "lastTransactionID": "266"
}
hootnot commented 1 year ago

personally I use PositionClose and close a pos. completely regardless how many trades it took to build the pos.

regarding your JSON response above: if a trade has the state OPEN that also says that it can be closed.

Using TradeClose() with the trade id, you should be able to close a specific trade.

There is also: positions.PositionDetails(accountID=accountID, instrument) https://oanda-api-v20.readthedocs.io/en/latest/endpoints/positions/positiondetails.html

it gives the tradeids involved regarding a position. In this example 1. But in your case you should see 144, 146, 148

{
  "position": {
    "short": {
      "unrealizedPL": "-0.0738",
      "tradeIDs": [
        "2323"                                   <---------------------------
      ],
      "resettablePL": "0.0000",
      "units": "-100",
      "averagePrice": "1.09843",
      "pl": "0.0000"
    },
    "unrealizedPL": "-0.0738",
    "long": {
      "units": "0",
      "resettablePL": "-44.6272",
      "unrealizedPL": "0.0000",
      "pl": "-44.6272"
    },
    "instrument": "EUR_USD",
    "resettablePL": "-44.6272",
    "pl": "-44.6272"
  },
  "lastTransactionID": "2327"
}