-1

What is wrong with my code? I want to retrieve my current open positions from my Phemex contract account, but it doesn't output anything, not even indicating that I don't have any open positions. Here is my code:

import ccxt
import api
import time



exchange = ccxt.phemex({
    'apiKey': api.contract_apiKey,
    'secret': api.contract_secret,
    'enableRateLimit': True,
})


def get_balance():
    params = {"type": "swap", "code": "USDT"}
    response = exchange.fetch_balance(params=params)
    return response


def get_positions():
    params = {"type": "swap", "code": "BTCUSDT"}
    positions = exchange.fetch_positions(params=params)
    return positions


def print_balance():
    balance = get_balance()
    print("Egyenleg:")
    for currency, amount in balance['total'].items():
        print(f"{currency}: {amount}")


def print_positions():
    positions = get_positions()
    if len(positions) > 0:
        print("Aktuális pozíciók:")
        for position in positions:
            if position['symbol'] != 'ETH/USD:USD':
                print(f"Pozíció: {position['symbol']}")
                print(f"  Méret: {position['info']['size']}")
                print(f"  Átlagos nyitási ár: {position['info']['avgEntryPrice']}")
                print(f"  Nyitott oldal: {'Long' if position['info']['side'] == 'buy' else 'Short'}")
                print("---------------")
    else:
        print("Nincsenek aktuális pozíciók.")


while True:
    print_balance()
    print_positions()
    print("------------------------------")
    time.sleep(10)`

Thank you

Skrihy
  • 1
  • 1
  • Does the response in get_balance() contain anything? Try printing it. – Captain Caveman May 22 '23 at 20:13
  • The get_balance function is working; it displays my current balance. – Skrihy May 22 '23 at 20:19
  • does ```positions = exchange.fetch_positions(params=params)``` contain data? – Captain Caveman May 22 '23 at 20:51
  • Yes, but I receive information about ETH, which in fact doesn't exist. ************Position************ [{'collateral': 0.0, 'contractSize': 0.005, 'contracts': 0.0, 'datetime': None, 'entryPrice': 0.0, 'hedged': False, 'id': None, ... ... ... 'size': '0', 'symbol': 'ETHUSD', 'takerFeeRateEr': '-100000000', 'term': '1', 'transactTimeNs': '1684828800001568784', 'usedBalance': '0E-8', 'usedBalanceEv': '0', ... ... – Skrihy May 23 '23 at 11:30
  • 1
    So, "it doesn't output anything" isn't true. It appears that the issue isn't with your code, but either your API call or the response. – Captain Caveman May 23 '23 at 12:58
  • I don't know what the problem could be – Skrihy May 23 '23 at 17:06

1 Answers1

1

The current solution of the fetch_positions() method for the Phemex exchange in the CCXT library is not quite the best programmed.

You must first define the symbols for which you want to download open positions and then filter the result where the size of the position is greater than zero.

Attention, if you call the fetch_positions() method without the symbols parameter, the method does not return relevant data.

Tested on CCXT version 3.1.17.

I created a bug directly in CCXT library git, before they can fix it you can use the solution mentioned above.

Code example

class CcxtTests(unittest.TestCase):

    def setUp(self) -> None:
        self.exchange = ccxt.phemex({
            'apiKey': "",
            'secret': "",
            'enableRateLimit': True,
        })
        
        # only for testing purpose
        #self.exchange.set_sandbox_mode(enabled=True)

    def test_fetch_positions(self):
        # Actually open position 0.01 EHT and 10 DOGE
        symbols = ["BTCUSDT", "ETHUSDT", "DOGEUSDT"]
        positions_raw = self.exchange.fetch_positions(symbols=symbols)

        print("Position raw: {}".format(positions_raw))

        positions = [x for x in positions_raw if float(x["info"]["size"]) > 0]

        print("Positions: {}".format(positions))

        self.assertEqual(positions[0]["info"]["symbol"], "DOGEUSDT")
        self.assertEqual(positions[0]["info"]["size"], "10")

        self.assertEqual(positions[1]["info"]["symbol"], "ETHUSDT")
        self.assertEqual(positions[1]["info"]["size"], "0.01")

Positions raw response

[
    {
        "info": {
            "userID": "1006534",
            "accountID": "10065340003",
            "symbol": "DOGEUSDT",
            "currency": "USDT",
            "side": "Buy",
            "positionStatus": "Normal",
            "crossMargin": false,
            "leverageRr": "-10",
            "initMarginReqRr": "0.1",
            "maintMarginReqRr": "0.01",
            "riskLimitRv": "200000",
            "size": "10",
            "valueRv": "0.7315",
            "avgEntryPriceRp": "0.07315",
            "avgEntryPrice": "0.07315",
            "posCostRv": "0.07354501",
            "assignedPosBalanceRv": "0.07435818",
            "bankruptCommRv": "0.00000006",
            "bankruptPriceRp": "0.00001",
            "positionMarginRv": "75.640717136268",
            "liquidationPriceRp": "0.00001",
            "deleveragePercentileRr": "0",
            "buyValueToCostRr": "0.10114",
            "sellValueToCostRr": "0.10126",
            "markPriceRp": "0.073068683",
            "estimatedOrdLossRv": "0",
            "usedBalanceRv": "0.07435818",
            "cumClosedPnlRv": "0",
            "cumFundingFeeRv": "0",
            "cumTransactFeeRv": "0.0004389",
            "transactTimeNs": "1685639599370317039",
            "takerFeeRateRr": "-1",
            "makerFeeRateRr": "-1",
            "term": "1",
            "lastTermEndTimeNs": "0",
            "lastFundingTimeNs": "0",
            "curTermRealisedPnlRv": "-0.0004389",
            "execSeq": "1750338145",
            "posSide": "Merged",
            "posMode": "OneWay",
            "buyLeavesValueRv": "0",
            "sellLeavesValueRv": "0"
        },
        "id": null,
        "symbol": "DOGE/USDT:USDT",
        "contracts": 10.0,
        "contractSize": null,
        "unrealizedPnl": null,
        "leverage": -10.0,
        "liquidationPrice": 1e-05,
        "collateral": 75.640717136268,
        "notional": 0.7315,
        "markPrice": 0.073068683,
        "lastPrice": null,
        "entryPrice": 0.07315,
        "timestamp": null,
        "lastUpdateTimestamp": null,
        "initialMargin": 0.07435818,
        "initialMarginPercentage": 0.10165164730006836,
        "maintenanceMargin": 0.007315,
        "maintenanceMarginPercentage": 0.01,
        "marginRatio": 9.670717408485e-05,
        "datetime": null,
        "marginMode": null,
        "side": "long",
        "hedged": false,
        "percentage": null
    },
    {
        "info": {
            "userID": "1006534",
            "accountID": "10065340003",
            "symbol": "BTCUSDT",
            "currency": "USDT",
            "side": "None",
            "positionStatus": "Normal",
            "crossMargin": false,
            "leverageRr": "20",
            "initMarginReqRr": "0.05",
            "maintMarginReqRr": "0.005",
            "riskLimitRv": "2000000",
            "size": "0",
            "valueRv": "0",
            "avgEntryPriceRp": "0",
            "avgEntryPrice": "0",
            "posCostRv": "0",
            "assignedPosBalanceRv": "0",
            "bankruptCommRv": "0",
            "bankruptPriceRp": "0",
            "positionMarginRv": "0",
            "liquidationPriceRp": "0",
            "deleveragePercentileRr": "0",
            "buyValueToCostRr": "0.05117",
            "sellValueToCostRr": "0.05123",
            "markPriceRp": "26963.7",
            "estimatedOrdLossRv": "0",
            "usedBalanceRv": "0",
            "cumClosedPnlRv": "-19.6916",
            "cumFundingFeeRv": "0.856435628732",
            "cumTransactFeeRv": "2.65365589",
            "transactTimeNs": "1685639599370317039",
            "takerFeeRateRr": "-1",
            "makerFeeRateRr": "-1",
            "term": "62",
            "lastTermEndTimeNs": "1682344601428187148",
            "lastFundingTimeNs": "1685635200000000000",
            "curTermRealisedPnlRv": "-0.05177328",
            "execSeq": "1750169286",
            "posSide": "Merged",
            "posMode": "OneWay",
            "buyLeavesValueRv": "0",
            "sellLeavesValueRv": "0"
        },
        "id": null,
        "symbol": "BTC/USDT:USDT",
        "contracts": 0.0,
        "contractSize": null,
        "unrealizedPnl": null,
        "leverage": 20.0,
        "liquidationPrice": 0.0,
        "collateral": 0.0,
        "notional": 0.0,
        "markPrice": 26963.7,
        "lastPrice": null,
        "entryPrice": 0.0,
        "timestamp": null,
        "lastUpdateTimestamp": null,
        "initialMargin": 0.0,
        "initialMarginPercentage": null,
        "maintenanceMargin": 0.0,
        "maintenanceMarginPercentage": 0.005,
        "marginRatio": null,
        "datetime": null,
        "marginMode": null,
        "side": "short",
        "hedged": false,
        "percentage": null
    },
    {
        "info": {
            "userID": "1006534",
            "accountID": "10065340003",
            "symbol": "ETHUSDT",
            "currency": "USDT",
            "side": "Buy",
            "positionStatus": "Normal",
            "crossMargin": false,
            "leverageRr": "20",
            "initMarginReqRr": "0.05",
            "maintMarginReqRr": "0.005",
            "riskLimitRv": "1000000",
            "size": "0.01",
            "valueRv": "18.7125",
            "avgEntryPriceRp": "1871.25",
            "avgEntryPrice": "1871.25",
            "posCostRv": "0.946291125",
            "assignedPosBalanceRv": "0.946291125",
            "bankruptCommRv": "0.010666125",
            "bankruptPriceRp": "1777.69",
            "positionMarginRv": "0.935625",
            "liquidationPriceRp": "1787.05",
            "deleveragePercentileRr": "0",
            "buyValueToCostRr": "0.05117",
            "sellValueToCostRr": "0.05123",
            "markPriceRp": "1871.479970115",
            "estimatedOrdLossRv": "0",
            "usedBalanceRv": "0.946291125",
            "cumClosedPnlRv": "-0.065",
            "cumFundingFeeRv": "0",
            "cumTransactFeeRv": "0.14586126",
            "transactTimeNs": "1685639599375750090",
            "takerFeeRateRr": "-1",
            "makerFeeRateRr": "-1",
            "term": "7",
            "lastTermEndTimeNs": "1681289047875676677",
            "lastFundingTimeNs": "1685635200000000000",
            "curTermRealisedPnlRv": "-0.0112275",
            "execSeq": "1750354137",
            "posSide": "Merged",
            "posMode": "OneWay",
            "buyLeavesValueRv": "0",
            "sellLeavesValueRv": "0"
        },
        "id": null,
        "symbol": "ETH/USDT:USDT",
        "contracts": 0.01,
        "contractSize": null,
        "unrealizedPnl": null,
        "leverage": 20.0,
        "liquidationPrice": 1787.05,
        "collateral": 0.935625,
        "notional": 18.7125,
        "markPrice": 1871.479970115,
        "lastPrice": null,
        "entryPrice": 1871.25,
        "timestamp": null,
        "lastUpdateTimestamp": null,
        "initialMargin": 0.946291125,
        "initialMarginPercentage": 0.05057,
        "maintenanceMargin": 0.0935625,
        "maintenanceMarginPercentage": 0.005,
        "marginRatio": 0.1,
        "datetime": null,
        "marginMode": null,
        "side": "long",
        "hedged": false,
        "percentage": null
    }
]

Positions

[
    {
        "info": {
            "userID": "1006534",
            "accountID": "10065340003",
            "symbol": "DOGEUSDT",
            "currency": "USDT",
            "side": "Buy",
            "positionStatus": "Normal",
            "crossMargin": false,
            "leverageRr": "-10",
            "initMarginReqRr": "0.1",
            "maintMarginReqRr": "0.01",
            "riskLimitRv": "200000",
            "size": "10",
            "valueRv": "0.7315",
            "avgEntryPriceRp": "0.07315",
            "avgEntryPrice": "0.07315",
            "posCostRv": "0.07354501",
            "assignedPosBalanceRv": "0.07435818",
            "bankruptCommRv": "0.00000006",
            "bankruptPriceRp": "0.00001",
            "positionMarginRv": "75.640717136268",
            "liquidationPriceRp": "0.00001",
            "deleveragePercentileRr": "0",
            "buyValueToCostRr": "0.10114",
            "sellValueToCostRr": "0.10126",
            "markPriceRp": "0.073068683",
            "estimatedOrdLossRv": "0",
            "usedBalanceRv": "0.07435818",
            "cumClosedPnlRv": "0",
            "cumFundingFeeRv": "0",
            "cumTransactFeeRv": "0.0004389",
            "transactTimeNs": "1685639599370317039",
            "takerFeeRateRr": "-1",
            "makerFeeRateRr": "-1",
            "term": "1",
            "lastTermEndTimeNs": "0",
            "lastFundingTimeNs": "0",
            "curTermRealisedPnlRv": "-0.0004389",
            "execSeq": "1750338145",
            "posSide": "Merged",
            "posMode": "OneWay",
            "buyLeavesValueRv": "0",
            "sellLeavesValueRv": "0"
        },
        "id": null,
        "symbol": "DOGE/USDT:USDT",
        "contracts": 10.0,
        "contractSize": null,
        "unrealizedPnl": null,
        "leverage": -10.0,
        "liquidationPrice": 1e-05,
        "collateral": 75.640717136268,
        "notional": 0.7315,
        "markPrice": 0.073068683,
        "lastPrice": null,
        "entryPrice": 0.07315,
        "timestamp": null,
        "lastUpdateTimestamp": null,
        "initialMargin": 0.07435818,
        "initialMarginPercentage": 0.10165164730006836,
        "maintenanceMargin": 0.007315,
        "maintenanceMarginPercentage": 0.01,
        "marginRatio": 9.670717408485e-05,
        "datetime": null,
        "marginMode": null,
        "side": "long",
        "hedged": false,
        "percentage": null
    },
    {
        "info": {
            "userID": "1006534",
            "accountID": "10065340003",
            "symbol": "ETHUSDT",
            "currency": "USDT",
            "side": "Buy",
            "positionStatus": "Normal",
            "crossMargin": false,
            "leverageRr": "20",
            "initMarginReqRr": "0.05",
            "maintMarginReqRr": "0.005",
            "riskLimitRv": "1000000",
            "size": "0.01",
            "valueRv": "18.7125",
            "avgEntryPriceRp": "1871.25",
            "avgEntryPrice": "1871.25",
            "posCostRv": "0.946291125",
            "assignedPosBalanceRv": "0.946291125",
            "bankruptCommRv": "0.010666125",
            "bankruptPriceRp": "1777.69",
            "positionMarginRv": "0.935625",
            "liquidationPriceRp": "1787.05",
            "deleveragePercentileRr": "0",
            "buyValueToCostRr": "0.05117",
            "sellValueToCostRr": "0.05123",
            "markPriceRp": "1871.479970115",
            "estimatedOrdLossRv": "0",
            "usedBalanceRv": "0.946291125",
            "cumClosedPnlRv": "-0.065",
            "cumFundingFeeRv": "0",
            "cumTransactFeeRv": "0.14586126",
            "transactTimeNs": "1685639599375750090",
            "takerFeeRateRr": "-1",
            "makerFeeRateRr": "-1",
            "term": "7",
            "lastTermEndTimeNs": "1681289047875676677",
            "lastFundingTimeNs": "1685635200000000000",
            "curTermRealisedPnlRv": "-0.0112275",
            "execSeq": "1750354137",
            "posSide": "Merged",
            "posMode": "OneWay",
            "buyLeavesValueRv": "0",
            "sellLeavesValueRv": "0"
        },
        "id": null,
        "symbol": "ETH/USDT:USDT",
        "contracts": 0.01,
        "contractSize": null,
        "unrealizedPnl": null,
        "leverage": 20.0,
        "liquidationPrice": 1787.05,
        "collateral": 0.935625,
        "notional": 18.7125,
        "markPrice": 1871.479970115,
        "lastPrice": null,
        "entryPrice": 1871.25,
        "timestamp": null,
        "lastUpdateTimestamp": null,
        "initialMargin": 0.946291125,
        "initialMarginPercentage": 0.05057,
        "maintenanceMargin": 0.0935625,
        "maintenanceMarginPercentage": 0.005,
        "marginRatio": 0.1,
        "datetime": null,
        "marginMode": null,
        "side": "long",
        "hedged": false,
        "percentage": null
    }
]