Skip to content

Commit

Permalink
v1.0.8
Browse files Browse the repository at this point in the history
v1.0.8
  • Loading branch information
platschi authored Jul 24, 2023
2 parents 9303084 + f22fa55 commit 28c1841
Show file tree
Hide file tree
Showing 8 changed files with 542 additions and 55 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,7 @@ Queries will default to Kwenta's public Hosted Service endpoints for The Graph.
| `price_service_endpoint` | `string` | **Optional.** Endpoint for the price service, defaults to None. |
| `telegram_token` | `string` | **Optional.** Token for the Telegram bot, defaults to None. |
| `telegram_channel_name` | `string` | **Optional.** Name of the Telegram channel for notifications, defaults to None. |

## Workflow

![KWENTA SDK WORKFLOW](/kwenta_python_sdk_workflow_SM.png?raw=true "KWENTA SDK WORKFLOW")
407 changes: 407 additions & 0 deletions examples/ATS/Kwenta_supertrend_bot.py

Large diffs are not rendered by default.

55 changes: 55 additions & 0 deletions examples/ATS/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Kwenta SDK ATS Example

_Disclaimer_

Use this ATS your own risk. We do not guarantee profits or accuracy of the bot's decisions. Trading in financial markets carries inherent risks, and you are solely responsible for your trading decisions. We are not liable for any losses or damages resulting from the use of our trading bot. Please consult with a qualified financial advisor before making any investment decisions.

#

This is an example of how you can use the Kwenta Python SDK to build automated trading systems based on strategy. This example shows how you can can apply a triple supertrend strat to any market supported by Kwenta.

## Run ATS

1. Install the Kwenta SDK + Example Requirements (_pandas_ta_ is optional, you can remove it from the script if you don't need it.)

```bash
pip install kwenta pandas schedule pandas_ta
```

Upgrade Kwenta to 1.0.8 if you have not already.

```bash
pip install kwenta --upgrade
```

2. Configure the _Kwenta_supertrend_bot.py_ script with your params

3. Run ATS

```bash
python Kwenta_supertrend_bot.py
```

## FAQ

#### I'm Stuck and I want to withdrawal everything from a Market.

Run the following: (This will withdrawal everything from the market and send it back to your EOA Wallet)

```
provider_rpc = "Provider_rpc"
wallet_address = "EOA_WALLET_ADDRESS"
private_key = "PRIVATE_KEY"
account = Kwenta(provider_rpc=provider_rpc, wallet_address=wallet_address, private_key=private_key)
account.withdrawal_margin(market, token_amount=-1, withdrawal_all=True, execute_now=True)
account.transfer_margin(market, -1, withdrawal_all=True, execute_now=True)
```

## Optimizations

There's already more alpha in this example script than I would like to leak, but here are some suggestions to make this stronger.

1. Add Shorts -- Currently script only longs
2. Add more indicators. The Example Strategy is very basic, I included some extras for those who are savvy.
3. Use Pyth for higher resolution pricing. Currently using Chainlink Oracle.
4. Utilize Multiple SM Accounts for double sided trades.
Binary file added kwenta_python_sdk_workflow_SM.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
114 changes: 61 additions & 53 deletions module/kwenta/kwenta.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ def transfer_margin(
)
if token_amount == 0:
raise Exception("token_amount Cannot be 0.")

#Check for withdrawal
is_withdrawal = -1 if token_amount < 0 else 1
token_amount = self.web3.to_wei(abs(token_amount), "ether") * is_withdrawal
print(token_amount)
Expand All @@ -767,68 +767,76 @@ def transfer_margin(
else:
susd_balance = self.get_susd_balance(self.sm_account)
print(f"sUSD Balance: {susd_balance['balance_usd']}")
if token_amount < susd_balance["balance"]:
if execute_now:
if (token_amount > 0) and (skip_approval is False):
self.approve_susd(token_amount)
print("Waiting for Approval...")
time.sleep(4.5)
if token_amount > 0:
print(f"Adding sUSD to {token_symbol} Market.")
time.sleep(4.5)
print(
f"Market_address: {(self.markets[token_symbol.upper()]['market_address'])}"
)
commandBytes1 = encode(["int256"], [token_amount])
commandBytes2 = encode(
["address", "int256"],
[
str(self.markets[token_symbol.upper()]["market_address"]),
token_amount,
],
)
data_tx = sm_account_contract.encodeABI(
fn_name="execute", args=[[0, 2], [commandBytes1, commandBytes2]]
)
tx_params = self._get_tx_params(to=self.sm_account, value=0)
tx_params["data"] = data_tx
tx_params["nonce"] = self.web3.eth.get_transaction_count(
self.wallet_address
)
tx_token = self.execute_transaction(tx_params)
return tx_token
else:
# Execute Commands: https://github.com/Kwenta/smart-margin/wiki/Commands
# args[0] == Command ID, args[1] == command inputs, in bytes
if withdrawal_all:
token_amount = (
int(
self.get_accessible_margin(self.sm_account)[
"margin_remaining_usd"
]
)
* -1
)
commandBytes = encode(["int256"], [token_amount])
data_tx = sm_account_contract.encodeABI(
fn_name="execute", args=[[0], [commandBytes]]
)
tx_params = self._get_tx_params(to=self.sm_account, value=0)
tx_params["data"] = data_tx
tx_params["nonce"] = self.web3.eth.get_transaction_count(
self.wallet_address
)
#check that withdrawal is less than account balance
if (token_amount > susd_balance["balance"]):
raise Exception(f"Token amount: {token_amount} is greater than Account Balance: {{susd_balance['balance_usd']}}! Verify your balance.")
#Move amount from EOA Wallet to SM Account
if (is_withdrawal > 0):
if (token_amount > 0) and (skip_approval is False):
self.approve_susd(token_amount)
print("Waiting for Approval...")
time.sleep(4.5)
#adding to sm account
if token_amount > 0:
print(f"Adding sUSD to {token_symbol} Market.")
time.sleep(4.5)
print(
f"Market_address: {(self.markets[token_symbol.upper()]['market_address'])}"
)
commandBytes1 = encode(["int256"], [token_amount])
commandBytes2 = encode(
["address", "int256"],
[
str(self.markets[token_symbol.upper()]["market_address"]),
token_amount,
],
)
data_tx = sm_account_contract.encodeABI(
fn_name="execute", args=[[0, 2], [commandBytes1, commandBytes2]]
)
tx_params = self._get_tx_params(to=self.sm_account, value=0)
tx_params["data"] = data_tx
tx_params["nonce"] = self.web3.eth.get_transaction_count(
self.wallet_address
)
if execute_now:
tx_token = self.execute_transaction(tx_params)
print(f"Adding {token_amount} sUSD to Account.")
print(f"TX: {tx_token}")
return tx_token
else:
return {
"token_amount": token_amount / (10**18),
"susd_balance": susd_balance,
"tx_data": tx_params,
}
#token Amount Negative == Withdrawal to EOA Wallet
else:
# Execute Commands: https://github.com/Kwenta/smart-margin/wiki/Commands
# args[0] == Command ID, args[1] == command inputs, in bytes
if withdrawal_all:
token_amount = (int(self.get_accessible_margin(self.sm_account)["margin_remaining"])* -1)
commandBytes = encode(["int256"], [token_amount])
data_tx = sm_account_contract.encodeABI(
fn_name="execute", args=[[0], [commandBytes]]
)
tx_params = self._get_tx_params(to=self.sm_account, value=0)
tx_params["data"] = data_tx
tx_params["nonce"] = self.web3.eth.get_transaction_count(
self.wallet_address
)
if execute_now:
tx_token = self.execute_transaction(tx_params)
print(f"Adding {token_amount} sUSD Moved to EOA Account.")
print(f"TX: {tx_token}")
return tx_token
else:
return {
"token_amount": token_amount / (10**18),
"susd_balance": susd_balance,
"tx_data": tx_params,
}

def modify_position(
self,
token_symbol: str,
Expand Down
13 changes: 13 additions & 0 deletions module/kwenta/pyth/pyth.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,16 @@ def price_update_data(self, token_symbol):
except Exception as e:
print(e)
return None

def get_pyth_price(self, asset_id:str):
url = "https://xc-mainnet.pyth.network/api/latest_price_feeds"
params = {
'ids[]': asset_id
}
try:
response = requests.get(url, params)
price_data = response.json()[0]['price']
return price_data
except Exception as e:
print(e)
return None
2 changes: 1 addition & 1 deletion module/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name="kwenta",
version="1.0.7",
version="1.0.8",
description="Python SDK for Kwenta",
long_description="Python SDK for Kwenta",
author="Kwenta DAO",
Expand Down
2 changes: 1 addition & 1 deletion tests/workflow_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
)
print("transfer_margin from SM_account...")
# account.transfer_margin("SOL",(margin_in_account*-1),execute_now=True)
account.transfer_margin("SOL", token_amount=1, withdrawal_all=True, execute_now=True)
account.transfer_margin("SOL", token_amount=-1, withdrawal_all=True, execute_now=True)
time.sleep(4)
account.get_susd_balance(smaccount)
account.get_susd_balance(wallet_address)

0 comments on commit 28c1841

Please sign in to comment.