dydxprotocol / dydx-v3-python Goto Github PK
View Code? Open in Web Editor NEWPython client for dYdX (API v3)
License: Apache License 2.0
Python client for dYdX (API v3)
License: Apache License 2.0
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
the last version of dateparser that support py27 is 0.7.6, could dateparser 0.7.6 be working with your current version package?
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
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?
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 ?
Hi, I have done the orderbook subscription following the docs:
https://docs.dydx.exchange/#orderbook
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
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.
dydx3.errors.DydxApiError: DydxApiError(status_code=400, response={'errors': [{'msg': 'No order found with id: 164fdc2720cb6fb42a76a73b225ba8d3d90fe4ccfe982d71468a90d6471dc24'}]})
I submit an order to get the ID of the order, but when I try to query the order by id, I got this error. WHY???
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?
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?
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
I am currently using the api on Ropsten, and I am coming across some issues
registration_tx_hash = self._client.eth.register_user(self._signature)
deposit_tx_hash = self._client.eth.deposit_to_exchange(self.get_position_id(), 3, human_amount,)
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!
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 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.
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'
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)),
)
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:
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?
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.
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?
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.
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'.
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.
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()
`
I am having trouble closing an existing position in the dydx-v3-python package, whereas this can be easily accomplished using the UI.
Otherwise one has to manually calculate prices for closing the position, which can be tedious.
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
Please use api_timeout when initiating Client class or set a default timeout for requests session.
The current code does not set a timeout value for requests session, so client might hang there if server is not responding.
https://docs.python-requests.org/en/master/user/advanced/#timeouts
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'}]})
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.
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.
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}
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
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?
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.
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
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
how can i get a stark private key or public key ?
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(
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))
It's on line 899 of this file,The key is error , The correct key should be "accountId"
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
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'}]})
求助啊 查询订单 撤销订单 都没问题
"lp_position_id" and "lp_stark_public_key" are not clearly specified in the documentation when I call dydx's "create_fast_withdrawal" API in Python.What exactly are "lp_position_id" and "lp_stark_public_key"? Where do I get them?
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.
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!
When I call Create A New Order with the API_KEY, return {"errors":[{'msg': 'Invalid signature for order'}]}
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>
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)?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.