Giter Site home page Giter Site logo

dydx-v3-python's Introduction


Python client for dYdX (v3 API).

The library is currently tested against Python versions 2.7, 3.4, 3.5, 3.6, 3.9, and 3.11.

Installation

The dydx-v3-python package is available on PyPI. Install with pip:

pip install dydx-v3-python

Getting Started

The Client object can be created with different levels of authentication depending on which features are needed. For more complete examples, see the examples directory, as well as the integration tests.

Public endpoints

No authentication information is required to access public endpoints.

from dydx3 import Client
from web3 import Web3

#
# Access public API endpoints.
#
public_client = Client(
    host='http://localhost:8080',
)
public_client.public.get_markets()

Private endpoints

One of the following is required:

  • api_key_credentials
  • eth_private_key
  • web3
  • web3_account
  • web3_provider
#
# Access private API endpoints, without providing a STARK private key.
#
private_client = Client(
    host='http://localhost:8080',
    api_key_credentials={ 'key': '...', ... },
)
private_client.private.get_orders()
private_client.private.create_order(
    # No STARK key, so signatures are required for orders and withdrawals.
    signature='...',
    # ...
)

#
# Access private API endpoints, with a STARK private key.
#
private_client_with_key = Client(
    host='http://localhost:8080',
    api_key_credentials={ 'key': '...', ... },
    stark_private_key='...',
)
private_client.private.create_order(
    # Order will be signed using the provided STARK private key.
    # ...
)

Onboarding and API key management endpoints

One of the following is required:

  • eth_private_key
  • web3
  • web3_account
  • web3_provider
#
# Onboard a new user or manage API keys, without providing private keys.
#
web3_client = Client(
    host='http://localhost:8080',
    web3_provider=Web3.HTTPProvider('http://localhost:8545'),
)
web3_client.onboarding.create_user(
    stark_public_key='...',
    ethereum_address='...',
)
web3_client.eth_private.create_api_key(
    ethereum_address='...',
)

#
# Onboard a new user or manage API keys, with private keys.
#
web3_client_with_keys = Client(
    host='http://localhost:8080',
    stark_private_key='...',
    eth_private_key='...',
)
web3_client_with_keys.onboarding.create_user()
web3_client_with_keys.eth_private.create_api_key()

Using the C++ Library for STARK Signing

By default, STARK curve operations such as signing and verification will use the Python native implementation. These operations occur whenever placing an order or requesting a withdrawal. To use the C++ implementation, initialize the client object with crypto_c_exports_path:

client = Client(
    crypto_c_exports_path='./libcrypto_c_exports.so',
    ...
)

The path should point to a C++ shared library file, built from Starkware's crypto-cpp library (CMake target) for the particular platform (e.g. Linux, etc.) that you are running your trading program on.

Running tests

If you want to run tests when developing the library locally, clone the repo and run:

pip install -r requirements.txt
docker-compose up # In a separate terminal
V3_API_HOST=<api-host> tox

NOTE: api-host should be https://api.stage.dydx.exchange to test in staging.

dydx-v3-python's People

Contributors

0xmichalis avatar brendanchou avatar christopher-li avatar esemeniuc avatar eyqs avatar jiajames avatar kenadia avatar kurdziel-k avatar liakakos avatar samweinberg23 avatar teddyding avatar vincentwschau avatar

Stargazers

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

Watchers

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

dydx-v3-python's Issues

Allow multiple providers to use signTypedData with geth

Annoyingly I get a not implemented error when using dydx's client saying that eth_signTypedData is not implemented. After some searching I found that geth doesn't support that method, but it's sibling project Clef support it (called account_signTypedData) https://geth.ethereum.org/docs/clef/apis#account_signtypeddata, but not other APIs. Web3.py only supports one provider per instance, so it would be helpful to be able to create web3 clients as appropriate for the different services.

receiving incorrect information for orderbook from the websocket api

Hello,
i am using a websockets library to stream orderbook data from dydx. I'm receiving incorrect information on each offset. example:
offset 1: bids: [22, 0.5], Asks: []
offset 2: asks: [23, 0.6], bids: []

i have no idea what this even means. Any help here? I would assume each offset, there are multiple levels. Not just a single level correct?
Also, the parameter 'includeOffsets' setting it to 'true', 'false', 'False', 'True', etc none of the options worked as it all gives me the same data.

Working example needed for mainnet with Infura web3 provider

Can anybody provide a working example for placing orders using the ETH mainnet and Infura web3 provider?
I followed the workarounds in the issue lists but still getting this error:

python main.py
2021-12-01T17:10:00.000Z
Traceback (most recent call last):
  File "/app/main.py", line 12, in <module>
    job()
  File "/app/sniper/sniper.py", line 108, in job
    place_order(order_params)
  File "/app/sniper/sniper.py", line 69, in place_order
    order_creation_response = client.private.create_order(**order_params)
  File "/usr/local/lib/python3.10/site-packages/dydx3/modules/private.py", line 538, in create_order
    return self._post(
  File "/usr/local/lib/python3.10/site-packages/dydx3/modules/private.py", line 78, in _post
    return self._private_request(
  File "/usr/local/lib/python3.10/site-packages/dydx3/modules/private.py", line 64, in _private_request
    return request(
  File "/usr/local/lib/python3.10/site-packages/dydx3/helpers/requests.py", line 33, in request
    raise DydxApiError(response)
dydx3.errors.DydxApiError: DydxApiError(status_code=400, response={'errors': [{'msg': 'Invalid signature for order'}]})
make: *** [Makefile:4: run] Error 1

FYI, I configured my browser to keep my credentials in the local storage("Remember me"), and grabbed STARK_KEY_PAIRS, API_KEY_PAIRS from there. But it still doesn't work giving me the above error.

Any help would be appreciated!

Websocket subscription of Orderbook

Hi, I have done the orderbook subscription following the docs:
https://docs.dydx.exchange/#orderbook

  1. subscribe the orderbook with the includeOffsets.
  2. channel data and full data is pushed.
  3. if the offset if bigger than the price level, use the latest price and quantity.

however, the ask and bids data is wrong sometimes.

And it happens frequently.

Can you give any websocket examples to handle the orderbook data?

Thanks

Close an open position programmatically when a condition is met

I've been trying to build a programmatic trading bot, and I'm stuck at this noob question.
I can create all kinds of orders using this python client. But, is there any way to make my open positions automatically closed when the index price crosses a certain value?
Here it says it's possible but I can't figure it out in practice: https://help.dydx.exchange/en/articles/4797992-perpetual-order-types

Stop limit orders can be used to limit losses on your positions by automatically closing them when the price falls below (for longs) or rises above (for shorts) the stop price.

Any help would be very appreciated!

dydx3.errors.DydxApiError: DydxApiError(status_code=400, response={'errors': [{'msg': 'Invalid signature for order'}]})

I have checked #75 and #96 .
I think I have covered all the suggestions there. Still I get the error.

Could you help? Million thanks.

(Edited) My command to run geth might be wrong=> /path/to/geth --http --syncmode light --ws.origins="*"

import time

from dydx3 import Client
from dydx3.constants import API_HOST_MAINNET
from dydx3.constants import MARKET_ETH_USD
from dydx3.constants import API_HOST_MAINNET
from dydx3.constants import NETWORK_ID_MAINNET
from dydx3.constants import ORDER_SIDE_BUY
from dydx3.constants import ORDER_STATUS_OPEN
from dydx3.constants import ORDER_TYPE_LIMIT
from web3 import Web3

ETHEREUM_ADDRESS = '0xxxxxxx'

WEB3_PROVIDER_URL = 'http://localhost:xxxx' # I am running geth (/path/to/geth --http --syncmode light --ws.origins="*")
client = Client(
    network_id=NETWORK_ID_MAINNET,
    host=API_HOST_MAINNET,
    default_ethereum_address=ETHEREUM_ADDRESS,
    
    web3=Web3(Web3.HTTPProvider(WEB3_PROVIDER_URL)),
    eth_private_key='xxxxx',
    stark_private_key="0x0xxxxxx",
    api_key_credentials={"walletAddress": "0xxxxxxx", "secret": "xxxxx",
                         "key": "xxxxx", "passphrase": "xxxx", "legacySigning": False, "walletType": "METAMASK"}, # I got it from chrome developer mode. I have signed the transaction to approve dydx but have no funds in mainnet yet.
)

client.stark_private_key = "0xxxxxx"
client.stark_public_key = "0xxxxxx"

account_response = client.private.get_account(
    ethereum_address=ETHEREUM_ADDRESS,
)
position_id = account_response.data['account']['positionId']
order_params = {
    'position_id': position_id,
    'market': MARKET_ETH_USD,
    'side': ORDER_SIDE_BUY,
    'order_type': ORDER_TYPE_LIMIT,
    'post_only': True,
    'size': '0.01',
    'price': '20',
    'limit_fee': '0.0015',
    'expiration_epoch_seconds': time.time() + 65,
}
order_response = client.private.create_order(**order_params)


order_id = order_response['order']['id']

Why does this lib need pytest 4.6 in published package?

We're installing this lib using pip as it doesn't exist on conda-forge. Pip uninstalls our pytest package v7.3 and then installs pytest 4.6 which is quite old and doesn't work in our environment. I'm wondering why it's necessary to have pytest in requirements.txt and not requirements.develop.txt or something along those lines?

Installing collected packages: pytest
  Attempting uninstall: pytest
    Found existing installation: pytest 7.1.0
    Uninstalling pytest-7.1.0:
      Successfully uninstalled pytest-7.1.0
Successfully installed pytest-4.6.11

Creating dydx order from smart contract

Hello, I've been trying to implement a smart contract in Solidity that is able to exchange tokens that are stored in its reserve.

For example, smart contract A received 10 ETH via transfer from Alice, and now the contract wants to exchange the 10 ETH for its value in WBTC. What's the easiest way to achieve that?

Would dydx-v3-python be a viable option?

Thank you

Testing the first example generates this error

Hello,

I'm BM. A very nice and polite guy.

Testing the first example in this repo generates this error message on every device:

aceback (most recent call last): File "/usr/local/lib/python3.9/dist-packages/urllib3/connection.py", line 174, in _new_conn conn = connection.create_connection( File "/usr/local/lib/python3.9/dist-packages/urllib3/util/connection.py", line 95, in create_connection raise err
File "/usr/local/lib/python3.9/dist-packages/urllib3/util/connection.py", line 85, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/urllib3/connectionpool.py", line 703, in urlopen
httplib_response = self._make_request(

the method eth_signTypedData does not exist/is not available

Running the python client gives the following error:

ValueError: {'code': -32601, 'message': 'the method eth_signTypedData does not exist/is not available'}

This is the code that was executed:

# Ganache test address.
ETHEREUM_ADDRESS = '0xa6DAD6c64F8795CDe5AfB2A031B880a6849edE73'

# Ganache node.
WEB_PROVIDER_URL = 'http://localhost:8545'

API_HOST_ROPSTEN = 'https://api.stage.dydx.exchange'

NETWORK_ID_ROPSTEN = 3

client = Client(
    network_id=NETWORK_ID_ROPSTEN,
    host=API_HOST_ROPSTEN,
    default_ethereum_address=ETHEREUM_ADDRESS,
    web3=Web3(Web3.HTTPProvider(WEB_PROVIDER_URL)),
)

Invalid signature for order

I am getting the following error while placing an order

placed_order = client.private.create_order(
  position_id=1, # required for creating the order signature
  market=MARKET_BTC_USD,
  side=ORDER_SIDE_BUY,
  order_type=ORDER_TYPE_LIMIT,
  post_only=False,
  size='0.01',
  price='35000',
  limit_fee='0.1',
  expiration_epoch_seconds=int(time.time() + 60 * 60),
  time_in_force=TIME_IN_FORCE_GTT,
)

DydxApiError: DydxApiError(status_code=400, response={'errors': [{'msg': 'Invalid signature for order'}]})

ValueError: Amount 0.65 is not a multiple of the quantum size 1e-09

I'm trying to place an order for ETH-USD pair with amount of 0.65 ETH, but it shows this error message:
ValueError: Amount 0.65 is not a multiple of the quantum size 1e-09
I can't understand what this means? would you please clarify & show me a solution?
FYI, I get this amount based on some calculations of my open position & market data. So I need a way to open or close a position with exactly the amount returned by the calculations, not even 0.1% more or less.

deposit issue

Hello,
I have been trying to deposit usdc to eth smart contract, there are a few fields in this method:

0 | depositAmount | uint256 |
1 | starkKey | uint256 |
2 | positionId | uint256 |
3 | signature | bytes

First 3 fields are self explanatory, but the last one is some signature of some unknown message with private stark key, my guess. I cannot find that message in any api or protocol description. Could you help me out here, please?

Problem with the Ropsten contract?

I am currently using the api on Ropsten, and I am coming across some issues

  1. it's unclear how to get the test collateral token (there is a another issue that appears unresolved... I reached out to dydx and got no response)
  2. all interactions with the L1 contracts (Ropsten) yield transaction reverts. At first I assumed the problem was on my end - and I still acknowledge I am making a mistake - but after double-checking with the logic within the integration tests, I believe there is a chance the problem lies in the Ropsten L1 contract
    specifically registration_tx_hash = self._client.eth.register_user(self._signature)
    and deposit_tx_hash = self._client.eth.deposit_to_exchange(self.get_position_id(), 3, human_amount,)
    yield issues.
    I haven't found if anyone has been successfully using the test contracts in recent history. Any help is appreciated :)

Issue creating orders

def open_short(size, price, variance):
order_params = {
'position_id': position_id,
'market' : MARKET_BTC_USD,
'side': ORDER_SIDE_SELL,
'order_type' : ORDER_TYPE_MARKET,
'post_only' : True,
'size' : str(size),
'price' : str(round(price + variance, 1)),
'limitFee' : str(0.015),
'expiration_epoch_seconds': time.time() + 50,
}
order_response = client.private.create_order(**order_params)
order_id = order_response['order']['id']
return order_id

other functions like cancel order, get balance etc all work but when calling this function to open a position of any type -short long stop i time out

Connection Error

Hello,

I am new to the dydx API. I am having trouble connecting. As a test, I am just pulling public market data but I get this error:

"ConnectionError: HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /v3/markets (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000020763C0BD90>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))"

The code is below

`
import dydx3 as dydx

public_client = dydx.Client(
host='http://localhost:8080',
)
public_client.public.get_markets()
`

Relax dependencies requirements to be compatible with other libraries, like Solana

I'm working on a project which is using dydx-python and dydx-v3-python libraries.

Unfortunately, for both of them, they require the exact version of 2.22.0 of the requests library.
Because of that, I'm having a dependency conflict with the Solana library which from the very beginning requires requests>=2.24.

So, how about we update the requirements.txt of these libraries (dydx-v3-python and dydx-python) to work with other versions of the requests as well? And maybe relax the other dependencies a little bit too?

Invalid order book data from the websocket. Python

I am new to WebSockets and I can't get what am I doing wrong:
Here is my request to websocket:

req_orderbook = {
    'type': 'subscribe',
    'channel': 'v3_orderbook',
    'id': 'XMR-USD',
    'includeOffsets': True
}
async def main():
    async with websockets.connect(uri) as websocket:
        await websocket.send(json.dumps(req_orderbook))
        while True:
	        res = await websocket.recv()
	        try:
	        	print(json.loads(res)['contents'])
	        except:
	        	print(json.loads(res))
asyncio.get_event_loop().run_until_complete(main())

And I get first response with full list of orders, but all next responses looks like:

{'offset': '4946284407', 'bids': [['196.1', '1148.37']], 'asks': []}
{'offset': '4946284409', 'bids': [['196.1', '1240.37']], 'asks': []}

There is always only one bid or one ask in the list and I don't know what I need to do for fetch full order book.

Field with relationship to another table must match other table'}

when i create api key got a error:

api_key_response = client.eth_private.create_api_key(ethereum_address='0x2f5204b96c9E34630...')

dydx3\helpers\requests.py", line 33, in request
raise DydxApiError(response)
dydx3.errors.DydxApiError: DydxApiError(status_code=400, response={'errors': [{'msg': 'Field with relationship to another table must match other table'}]})

is it right?
what i can do next ? thanks

Order after 30 min is still pending

Some orders have pending status even after 30 minutes interval, Is it expected behaviour? If so, when time do you usually have to wait until order is accepted, so you could cancel permanent pending?

4

'The method eth_signTypedData does not exist/is not available'

Warning: Failed to derive default API key credentials: {'code': -32601, 'message': 'The method eth_signTypedData does not exist/is not available'}
Traceback (most recent call last):
File "/dydxDataWss.py", line 20, in
stark_private_key = client.onboarding.derive_stark_key()
File "/usr/local/lib/python3.9/site-packages/dydx3/modules/onboarding.py", line 124, in derive_stark_key
signature = self.signer.sign(
File "/usr/local/lib/python3.9/site-packages/dydx3/eth_signing/sign_off_chain_action.py", line 38, in sign
typed_signature = self.signer.sign(
File "/usr/local/lib/python3.9/site-packages/dydx3/eth_signing/signers.py", line 51, in sign
raw_signature = self.web3.eth.signTypedData(
File "/usr/local/lib/python3.9/site-packages/web3/module.py", line 57, in caller
result = w3.manager.request_blocking(method_str,
File "/usr/local/lib/python3.9/site-packages/web3/manager.py", line 187, in request_blocking
return self.formatted_response(response,
File "/usr/local/lib/python3.9/site-packages/web3/manager.py", line 168, in formatted_response
raise ValueError(response["error"])
ValueError: {'code': -32601, 'message': 'The method eth_signTypedData does not exist/is not available'}

When I try to create the stack key, I find this error. Does someone know how to solve it ?

"Internal error, could not fetch data for subscription: v3_accountsAPI key not found"

I encountered an error when I tried to subscribe account update using websocket. The returned error says: "Internal error, could not fetch data for subscription: v3_accountsAPI key not found". But I used the same API key to create new orders and succeeded in that task. Specifically, I was trying to run the websocket example from the official Github repo:
https://github.com/dydxprotocol/dydx-v3-python/blob/master/examples/websockets.py
, with my own API credentials of course. Any insight into this matter is welcome.

Websocket response:
< {"type":"connected","connection_id":"7fd7b9e9-882b-4d39-bb20-29084701a7b9","message_id":0}
< {"type":"error","message":"Internal error, could not fetch data for subscription: v3_accountsAPI key not found","connection_id":"7fd7b9e9-882b-4d39-bb20-29084701a7b9","message_id":1}

Tox dependency is too old.

It's causing dependency issues when using poetry as dep/venv manager. This is due to having an ancient importlib_metadata dependency in the currently used version of tox.

Ecdsa order faster signature

Is there a reason why ecdsa signing takes 100ms? Included starkex cpp lib is even slower at around 250ms per signature. Are there faster implementations?

private.py exist bug

It's on line 899 of this file,The key is error , The correct key should be "accountId"

create_user ValueError: STARK private key or public key is required

when i create user get error:

o_info=client.onboarding.create_user(country='SG')

lib\site-packages\dydx3\modules\onboarding.py", line 96, in create_user
'STARK private key or public key is required'
ValueError: STARK private key or public key is required

image

how can i get a stark private key or public key ?

Web socket sends wrong order book data

Why doesn't your socket send a full orderbook? There are always wrong asks and bids, WebSocket prices often doesn't match web interface prices and amounts never match. Please make it work like in other exchanges, for example as in FTX.

Orderbook not coherent

I am having problems maintaining a coherent orderbook on the V3 socket API.

I have tried filtering updates using the "offsets" field and disregarding the "offsets" field. I can maintain a good book for about 3-10 seconds then either a bid or ask price will get "stuck" - I have traced through the Websocket updates and confirmed that the message stream does NOT contain any updates (or removals) for the prices[s] that get stuck

This happens on EVERY attempt i have made, not just occasionally. There looks to be relevant activity at where the top of book seems to be moving but unless i implement a "cancel on overlap" mechanism the book will always end up overlapping

Is there an implied "cancel on overlap" assumption ? (e.g. where all asks are removed when a bid is higher .. and vice versa) - if so then the official GUI shows "backwardation" of proces (overlap) by 1 or 2 spread sometimes so i require guidance . If that is not the problem then why am i losing updates

I can provide examples easily if you require tham

Deleted default api key

I accidentally deleted the default API key and now getting API key not found error trying to connect via websocket. I'm also getting an error connecting wallet on https://trade.dydx.exchange/ both with new and old authentications.

So the issue is that the key returned by client.onboarding.recover_default_api_key_credentials is not in the list of keys returned by client.private.get_api_keys.

I have eth public/private key and Stark public/private key. I also have id/secret/passphrase for the default API key. But I can't find any way to change the default API key neither a way to add a given particular key (id/secret/passphrase).

Can you please clarify if there is any way to fix this or I have to do withdrawal and create a new account (using new eth address)?

Onboarding is not supported since no Ethereum signing method (web3, web3_account, web3_provider) was provided

Onboarding is not supported since no Ethereum signing method (web3, web3_account, web3_provider) was provided

from dydx3 import Client
from web3 import Web3

client = Client(host='https://api.stage.dydx.exchange')
key_pair_with_y_coordinate = client.onboarding.derive_stark_key(
ethereum_address='https://etherscan.io',
)

Exception: Onboarding is not supported since no Ethereum signing method (web3, web3_account, web3_provider) was provided

how can i fix this?

public.py get_fast_withdrawal() does not support any parameters

According to https://docs.dydx.exchange/#get-fast-withdrawal-liquidity

The python public endpoint get_fast_withdrawal() is supposed to accept three optional parameters:

creditAsset | (Optional): The asset that would be sent to the user. Required if creditAmount or debitAmount are set.
creditAmount | (Optional): Set this value if the user wants a quote based on the creditAmount.
debitAmount | (Optional): Set this value if the user wants a quote based on the debitAmount.

But it actually doesn't accept any parameter at all /END

dydx

get position_id error

Traceback (most recent call last):
  File "/Users/a/Downloads/dydx-robot/orders.py", line 37, in <module>
    position_id = account_response['account']['positionId']
TypeError: 'Response' object is not subscriptable

Onboarding from a smart contract

Hi, I want a contract in solidity to be able to register itself on dydx. Is it possible to do?

I was reading the authentication here https://github.com/dydxprotocol/dydx-v3-python/blob/master/dydx3/modules/onboarding.py and it generates a signature, so I guess a private key is needed, however we cannot sign with the private key in the contract.

Ideally, we would like the contract to register itself on dydx and provide the credentials for using the dydx API to the owner of the contract. Do you think that's realistic or even possible?

How to get a hold of the Testnet collateral token?

I'm trying to run the test_integration.py file, and I want to make some orders with fake money on ropsten. I've made a lot of progress up until the deposit_to_exchange line. It looks like I need to have some USDC to deposit into my account, and I have tried that on the mainnet and it works!

However this doesn't seem to be working on the ropsten testnet! I used uniswap to get some usdc, but looks like dydx is using this token instead. Is there a faucet for this token? How can I get a hold of this token? I can see the token on ropsten, and that a whole bunch of people own it, but I don't know how to get some for my own testing purposes.

accounts_response <dydx3.helpers.requests.Response object at 0x00000207DA569250>

Hi, I manually linked DyDx to my metamask wallet and funded it, am I right that I do not have to have a script to onboard and derive the stark keys etc? I just need to extract my stark keys and api credentials and put it into the Client initialization? Somehow when I do that even basic requests like get accounts are not working, I get the error below, can someone help with an end to end example on how to set this up? Thanks!

accounts_response <dydx3.helpers.requests.Response object at 0x00000207DA569250>

Problem with starkex when creating order

I tried to create an order using the dydx3 python package, but I receive an error with my signature.
Using the UI the order creation process works fine.

~\code\deepb-ai\trading_engine\trading_coordinator.py in execute_order(self, order_container)
    169     def execute_order(self, order_container: OrderContainer):
    170 
--> 171         create_order_result = self.client.private.create_order(**dataclasses.asdict(order_container))
    172 
    173         order_id = create_order_result.data['order']['id']

~\miniconda3\envs\alpaca-env\lib\site-packages\dydx3\modules\private.py in create_order(self, position_id, market, side, order_type, post_only, size, price, limit_fee, time_in_force, cancel_id, trigger_price, trailing_percent, client_id, expiration, expiration_epoch_seconds, signature)
    556                 expiration_epoch_seconds=expiration_epoch_seconds,
    557             )
--> 558             order_signature = order_to_sign.sign(self.stark_private_key)
    559 
    560         order = {

~\miniconda3\envs\alpaca-env\lib\site-packages\dydx3\starkex\signable.py in sign(self, private_key_hex)
     30     def sign(self, private_key_hex):
     31         """Sign the hash of the object using the given private key."""
---> 32         r, s = sign(self.hash, int(private_key_hex, 16))
     33         return serialize_signature(r, s)
     34 

~\miniconda3\envs\alpaca-env\lib\site-packages\dydx3\starkex\signable.py in hash(self)
     25         """Get the hash of the object."""
     26         if self._hash is None:
---> 27             self._hash = self._calculate_hash()
     28         return self._hash
     29 

~\miniconda3\envs\alpaca-env\lib\site-packages\dydx3\starkex\order.py in _calculate_hash(self)
    166         )
    167         return get_hash(
--> 168             get_hash(
    169                 assets_hash,
    170                 part_1,

~\miniconda3\envs\alpaca-env\lib\site-packages\dydx3\starkex\starkex_resources\proxy.py in get_hash(*elements)
     37         return cpp_hash(*elements)
     38 
---> 39     return py_pedersen_hash(*elements)

~\miniconda3\envs\alpaca-env\lib\site-packages\dydx3\starkex\starkex_resources\python_signature.py in py_pedersen_hash(*elements)
    249 
    250 def py_pedersen_hash(*elements: int) -> int:
--> 251     return pedersen_hash_as_point(*elements)[0]
    252 
    253 

~\miniconda3\envs\alpaca-env\lib\site-packages\dydx3\starkex\starkex_resources\python_signature.py in pedersen_hash_as_point(*elements)
    259     point = SHIFT_POINT
    260     for i, x in enumerate(elements):
--> 261         assert 0 <= x < FIELD_PRIME
    262         point_list = CONSTANT_POINTS[2 + i * N_ELEMENT_BITS_HASH:2 + (i + 1) * N_ELEMENT_BITS_HASH]
    263         assert len(point_list) == N_ELEMENT_BITS_HASH

AssertionError: 

Clean install on python 3.6, example fails immediately

A fresh 3.6 environment, dydx-v3-python installed OK (actual is dydx-v3-python-1.2.0) , trying to run an example, immediately import error:
(what did I miss, guys?)

dydx_examples$ python -m onboard
Traceback (most recent call last):
  File "/home/elk/miniconda3/envs/peri/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/elk/miniconda3/envs/peri/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/elk/0x/periscope/dydx_examples/onboard.py", line 6, in <module>
    from dydx3 import Client
  File "/home/elk/miniconda3/envs/peri/lib/python3.6/site-packages/dydx3/__init__.py", line 1, in <module>
    from dydx3.dydx_client import Client
  File "/home/elk/miniconda3/envs/peri/lib/python3.6/site-packages/dydx3/dydx_client.py", line 1, in <module>
    from web3 import Web3
  File "/home/elk/miniconda3/envs/peri/lib/python3.6/site-packages/web3/__init__.py", line 9, in <module>
    from web3.main import (
  File "/home/elk/miniconda3/envs/peri/lib/python3.6/site-packages/web3/main.py", line 86, in <module>
    from web3.manager import (
  File "/home/elk/miniconda3/envs/peri/lib/python3.6/site-packages/web3/manager.py", line 44, in <module>
    from web3.providers import (
  File "/home/elk/miniconda3/envs/peri/lib/python3.6/site-packages/web3/providers/__init__.py", line 11, in <module>
    from .websocket import (  # noqa: F401,
  File "/home/elk/miniconda3/envs/peri/lib/python3.6/site-packages/web3/providers/websocket.py", line 21, in <module>
    from websockets.client import (
  File "/home/elk/0x/periscope/dydx_examples/websockets.py", line 10, in <module>
    from dydx3 import Client
ImportError: cannot import name 'Client'

Need a way to do private end points without sharing my private key

For example, by generating a unique 'secret phrase' on the DYDX front end and putting that into the python script. Requiring pasting my private key into code is bad practice because the private key can compromise the entire wallet. Would be nice if there can be multiple 'secret phrases' with escalating privileges such as 'view only', or 'trading but not withdraw', or 'full access to everything'.

Dependencies versions mismatch: eth-typing

There are incompatible versions in the resolved dependencies:
  eth-typing<3.0.0,>=2.0.0 (from web3==5.29.0->dydx-v3-python==1.5.1->-r /var/folders/c6/2md_1txd6l38vv3ly2_kz4t80000gn/T/pipenv5lnq22earequirements/pipenv-fobg0z3s-constraints.txt (line 2))
  eth-typing<4,>=3.0.0 (from eth-keys==0.4.0->dydx-v3-python==1.5.1->-r /var/folders/c6/2md_1txd6l38vv3ly2_kz4t80000gn/T/pipenv5lnq22earequirements/pipenv-fobg0z3s-constraints.txt (line 2))

求助 下单签名错误问题

client = Client(
network_id=NETWORK_ID_MAINNET,
host=API_HOST_MAINNET,
default_ethereum_address=ETH_ADDRESS,
web3=Web3(Web3.HTTPProvider(WEB_PROVIDER_URL)),
api_key_credentials=api_key,
stark_private_key=STARK_KEY,
)

发送订单

account_response = client.private.get_account()
position_id = account_response['account']['positionId']
print(position_id)

order_params = {
'position_id': position_id,
'market': MARKET_ETH_USD,
'side': ORDER_SIDE_BUY,
'order_type': ORDER_TYPE_LIMIT,
'post_only': False,
'size': '0.01',
'price': '2400',
'limit_fee': '0.0018',
"expiration_epoch_seconds": int(time.time()) + 4 * 7 * 1440 * 60,
}
order_response = client.private.create_order(**order_params)
order_id = order_response['order']['id']

返回

Traceback (most recent call last):
File "api.py", line 54, in
order_response = client.private.create_order(**order_params)
File "/Users/Desktop/dydx/dydx3/modules/private.py", line 463, in create_order
order,
File "/Users/Desktop/dydx/dydx3/modules/private.py", line 82, in _post
data
File "/Users/Desktop/dydx/dydx3/modules/private.py", line 69, in _private_request
data,
File "/Users/Desktop/dydx/dydx3/helpers/requests.py", line 27, in request
raise DydxApiError(response)
dydx3.errors.DydxApiError: DydxApiError(status_code=400, response={'errors': [{'msg': 'Invalid signature for order'}]})

求助啊 查询订单 撤销订单 都没问题

Layer2 API question on retrieving my balance and positions

Can someone give me a python3 script to retrieve my balance and positions on the new Layer2 DYDX exchange for perps? On the old Layer1 DYDX exchange, I can get my balance/positions very easily like this. Note this script works for both SPOT and PERPS.

import requests
import sys
from decimal import *
if len(sys.argv) < 2:
        print("ERROR: Must specify Ethereum address.")
        print("Optional arguments: 'futures'")
        exit()
if len(sys.argv) > 2 and sys.argv[2] == 'futures':
        request = requests.get("https://api.dydx.exchange/v1/perpetual-accounts/" + sys.argv[1]).json()
        request2 = requests.get("https://api.dydx.exchange/v1/index-price").json()
        for key, value in request['confirmedBalances'].items():
                value = (float(value['position']) / float(request2[key]['price']) + float(value['cachedMargin'])) / float(Decimal(10 ** 18))
                if value != 0:
                        print(key, value)
else:
        request = requests.get("https://api.dydx.exchange/v1/accounts/" + sys.argv[1]).json()
        for key, value in request['accounts'][0]['confirmedBalances'].items():
                if key == '0':
                        symbol = 'WETH'
                elif key == '1':
                        symbol = 'SAI'
                elif key == '2':
                        symbol = 'USDC'
                elif key == '3':
                        symbol = 'DAI'
                if float(value['wei']) != 0:
                        print(symbol.ljust(4), '{0:.18f}'.format(float(value['wei']) / float(Decimal(10 ** 18))).rjust(21))

The script runs like this, when you pass an ETH address to it. When you add 'futures' to the end, it gets the PERP balance.

$ python3 dydxbalances.py 0x<ADDRESS>
WETH  0.000071392628207050
DAI  -0.003082044339038793
$ python3 dydxbalances.py 0x<ADDRESS> futures
WETH-PUSD 39.739323027634406

This script doesn't work on the new Layer2 exchange and I could use some help here on what I have to change.

derive_stark_key issue

I've been trying to port this api to C#
In derive_stark_key method there is a line:

hashed_signature = Web3.solidityKeccak(['uint256'], [signature_int])

where signature_int is not a uint256 (exceeds max uint256 value). While it is working without any errors on python, it generates unpredictable result, and so cannot be ported to C# or anywhere else.

Any ideas how to fix this?

Historical data about Markets volume

Hi! I have a question: How can I get the historical USD for each market?
There is only volume24H parameter at get_markets().
For example: I wanna see the volume on April 5.

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.