Git Product home page Git Product logo

vertex-python-sdk's Introduction

Vertex Protocol Python SDK

This is the Python SDK for the Vertex Protocol API.

See SDK docs to get started.

Requirements

  • Python 3.9 or above

Installation

You can install the SDK via pip:

pip install vertex-protocol

Basic usage

Import the necessary utilities:

from vertex_protocol.client import create_vertex_client, VertexClientMode
from vertex_protocol.contracts.types import DepositCollateralParams
from vertex_protocol.engine_client.types.execute import (
    OrderParams,
    PlaceOrderParams,
    SubaccountParams
)
from vertex_protocol.utils.expiration import OrderType, get_expiration_timestamp
from vertex_protocol.utils.math import to_pow_10, to_x18
from vertex_protocol.utils.nonce import gen_order_nonce

Create the VertexClient providing your private key:

print("setting up vertex client...")
private_key = "xxx"
client = create_vertex_client(VertexClientMode.MAINNET, private_key)

Perform basic operations:

# Depositing collaterals
print("approving allowance...")
approve_allowance_tx_hash = client.spot.approve_allowance(0, to_pow_10(100000, 6))
print("approve allowance tx hash:", approve_allowance_tx_hash)

print("querying my allowance...")
token_allowance = client.spot.get_token_allowance(0, client.context.signer.address)
print("token allowance:", token_allowance)

print("depositing collateral...")
deposit_tx_hash = client.spot.deposit(
   DepositCollateralParams(
      subaccount_name="default", product_id=0, amount=to_pow_10(100000, 6)
   )
)
print("deposit collateral tx hash:", deposit_tx_hash)

# Placing orders
print("placing order...")
owner = client.context.engine_client.signer.address
product_id = 1
order = OrderParams(
   sender=SubaccountParams(
      subaccount_owner=owner,
      subaccount_name="default",
   ),
   priceX18=to_x18(20000),
   amount=to_pow_10(1, 17),
   expiration=get_expiration_timestamp(OrderType.POST_ONLY, int(time.time()) + 40),
   nonce=gen_order_nonce(),
)
res = client.market.place_order({"product_id": product_id, "order": order})
print("order result:", res.json(indent=2))

See Getting Started for more.

Running locally

  1. Clone github repo

  2. Install poetry


$ curl -sSL https://install.python-poetry.org | python3 -

  1. Setup a virtual environment and activate it

$ python3 -m venv venv
$ source ./venv/bin/activate

  1. Install dependencies via poetry install
  2. Setup an .env file and set the following envvars
CLIENT_MODE='mainnet|sepolia-testnet|devnet'
SIGNER_PRIVATE_KEY="0x..."
LINKED_SIGNER_PRIVATE_KEY="0x..." # not required

Run tests

$ poetry run test

Run sanity checks

  • poetry run client-sanity: runs sanity checks for the top-level client.
  • poetry run engine-sanity: runs sanity checks for the engine-client.
  • poetry run indexer-sanity: runs sanity checks for the indexer-client.
  • poetry run contracts-sanity: runs sanity checks for the contracts module.

Build Docs

To build the docs locally run:

$ poetry run sphinx-build docs/source docs/build

vertex-python-sdk's People

Contributors

0xyuan90 avatar clarkohw avatar threeandtwo avatar wphan avatar yruej301 avatar yukigaru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

vertex-python-sdk's Issues

Add clarity to opening a short perp position

It's not entirely clear how to open a short position

 order = OrderParams(
        sender=subaccount,
        priceX18=round_x18(
            eth_perp.oracle_price_x18, eth_perp.book_info.price_increment_x18
        )
        + to_x18(100),
        amount=to_pow_10(1, 17),
        expiration=get_expiration_timestamp(OrderType.IOC, int(time.time()) + 1000),
        nonce=gen_order_nonce(),
    )
    res = client.market.place_order({"product_id": 4, "order": order})

could use an opening short perp position in the sanity checks

Cancel order fails.

Hi forks,
I meet an error when using client.market.cancel_orders() function. I just followed the guideline here: https://vertex-protocol.github.io/vertex-python-sdk/getting-started.html#cancelling-an-order, and the error is looks like this:

vertex_protocol.utils.exceptions.ExecuteFailedException: {"status":"failure","signature":"","error_code":2011,"error":"Request received after ‘recv_time’. Ensure that your ‘recv_time’ allows adequate time for requests to be received","request_type":"execute_cancel_orders"}

Can you guys double-check the cancel_orders function? would like to know the reasons why this couldn't work,

spot_leverage in QueryMaxOrderSizeParams cannot be explicitly assign a bool value

I tried to use the QueryMaxOrderSizeParams to call get_max_order_size(), I found that in any way, if I set a value on spot_leverage, the API always raises error; if I remove the spot_leverage, it will works.

params = QueryMaxOrderSizeParams(
            sender=sender,
            product_id=product_id,
            price_x18=to_x18(price),
            direction=direction,
            # only if I remove this line, the API call can succeed, otherwise it fails with below error, regardless of True or False
            spot_leverage=False 
    )
    result = client.context.engine_client.get_max_order_size(params)

Traceback (most recent call last):
File "order_vertex.py", line 303, in
get_max_order_size(65000, "long", spot_leverage=True)
File "order_vertex.py", line 113, in get_max_order_size
result = client.context.engine_client.get_max_order_size(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "...\Lib\site-packages\vertex_protocol\engine_client\query.py", line 291, in get_max_order_size
self.query(QueryMaxOrderSizeParams.parse_obj(params)).data, MaxOrderSizeData
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "...\Lib\site-packages\vertex_protocol\engine_client\query.py", line 92, in query
raise QueryFailedException(res.text)
vertex_protocol.utils.exceptions.QueryFailedException: {"status":"failure","error_code":2040,"error":"The value you entered is not a valid boolean. Please try again with a value of true or false.","request_type":"query_max_order_size"}

WS support

The TS SDK provides WS support but I couldn't find the same for the python SDK.

Closing position wrapper function, more intuitive

Nowhere in the docs does it discuss closing out a perps positions.

I've searched through everything, and I recommend either doing a perps-specific sanity workflow example or including it here:

https://github.com/vertex-protocol/vertex-python-sdk/blob/main/sanity/vertex_client.py

for reference, this is how you would do it in kwenta

def closeKwentaPosition(client: Kwenta, symbol):
    smaccount = client.get_sm_accounts()[0]
    txId = client.close_position(symbol, smaccount, execute_now=True)
    print("Closing kwenta position:", txId)

Programatic way of getting subaccount address from address

There is currently no way to retrieve the full subaccount address associated with one wallet

"0x1232....123" maps to "0x1232....123" + some other stuff, i've just been inspecting element on the vertex site to retrieve it, but that's not great.

For reference this is how you would do it in Kwenta:

smaccounts = Kwenta.get_sm_accounts()

I recommend creating a similar function

client = create_vertex_client("mainnet")
subaccounts = client.get_subaccounts()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.