Skip to content

Commit 4d51522

Browse files
committed
Version 1.0.0 - Core functionality changed
1 parent f34f58e commit 4d51522

File tree

11 files changed

+843
-20
lines changed

11 files changed

+843
-20
lines changed

README.md

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@
44
<a href ="https://www.alpacafinance.org//"><img src="https://pbs.twimg.com/profile_images/1481749291379081217/KGzK2UQS_400x400.png" alt="Alpaca Finance Logo" height="200"></a>
55
<br></br>
66
<h2 align="center"><strong>Alpaca-Finance-Python</strong></h2>
7-
<img src="https://img.shields.io/badge/Python-3.9%2B-yellow"/>&nbsp&nbsp<img src="https://img.shields.io/badge/Chain-BSC-yellow"></img>
7+
<img src="https://img.shields.io/badge/Python-3.9%2B-yellow"/>&nbsp&nbsp<img src="https://img.shields.io/badge/Supported Network-BSC-yellow"></img>
88
<p align="center">
9-
An unofficial Python3.9+ package that models positions on the Alpaca Finance platform to simplify interaction with their smart contracts in your Python projects.
9+
An unofficial Python3.9+ package that models Binance Smart Chain positions on the Alpaca Finance platform to simplify interaction with their smart contracts in your Python projects.
1010
</p>
1111
<h3><strong>Supported Position Types</strong></h3>
1212
<i>Automated Vaults</i><br>
1313
</div>
1414
<br>
1515

16-
> NOTE: Codebase is currently in development and incomplete
16+
> NOTE: Existing users please update to the latest version of the package before using, core functionality has changed in version 1+.
1717
1818
<!-- TABLE OF CONTENTS -->
1919
### Table of Contents
@@ -36,8 +36,7 @@ This package is set up to be installed using the `pip` package manager.
3636
```bash
3737
pip install --upgrade git+https://github.com/PathX-Projects/Alpaca-Finance-Python.git
3838
```
39-
40-
***Note:*** You may need to provide your git credentials depending on the repository privacy settings. In the event, if you need help generating a personal access token see [here](https://catalyst.zoho.com/help/tutorials/githubbot/generate-access-token.html)
39+
<!-- ***Note:*** You may need to provide your git credentials depending on the repository privacy settings. In the event, if you need help generating a personal access token see [here](https://catalyst.zoho.com/help/tutorials/githubbot/generate-access-token.html) -->
4140

4241
2. After install, the package will be available to you in your local Python environment as ***alpaca_finance***
4342

@@ -47,7 +46,9 @@ ___
4746

4847
## Usage
4948

50-
How to use the package:
49+
How to use the package
50+
51+
### Automated Vaults:
5152

5253
1. Import the package into your Python script:
5354
```python
@@ -61,8 +62,6 @@ How to use the package:
6162
provider = get_web3_provider("your_rpc_url")
6263
```
6364

64-
### Automated Vaults:
65-
6665
3. Creating an [AutomatedVaultPosition](alpaca_finance/automated_vault/positions.py) instance requires the following:
6766
- Your position key (string)
6867
- This key should match your position key on Alpaca Finance's webapp
@@ -78,32 +77,73 @@ How to use the package:
7877
position = AutomatedVaultPosition(position_key="n3x-BNBBUSD-PCS1", owner_wallet_address="0x...", owner_private_key="123abc456efg789hij...")
7978
```
8079
4. Use your position instance to interact with Alpaca Finance:
81-
```python
80+
- For reference, see the BEP20Token class [documentation](https://github.com/hschickdevs/Python-BEP20-Token/blob/main/bep20/token.py)
81+
- Please view the **usage examples** under [examples/automated_vault](examples/automated_vault)
82+
```python
8283
""" Informational Methods (Private Key not Required) """
8384
85+
# Get the asset token or stable token for the vault (BEP20Token object)
86+
position.asset_token, position.stable_token
87+
88+
8489
# Get the current yields for the vault:
8590
position.yields()
8691
92+
8793
# Get the current vault TVL:
8894
position.tvl()
8995
96+
9097
# Get the current vault capacity:
9198
position.capacity()
9299
100+
93101
# Get the position's cost basis (entry price in USD):
94102
position.cost_basis()
95103
104+
96105
# Get the current position value (in USD):
97106
position.current_value()
98107
108+
99109
# Get the position profit/loss (PnL in USD):
100110
position.pnl()
101111
112+
102113
# Get the amount of shares held and the USD value of all shares held:
103114
position.shares()
104115
116+
105117
# get the full vault summary (See the documentation alpaca_fiance/position.py for more details):
106118
position.get_vault_summary()
119+
120+
121+
""" Transactional Methods (Private Key Required) """
122+
123+
124+
# Approve a token for deposit to the vault (only required once if never approved):
125+
position.approve_token(<token_address> or <BEP20Token object>)
126+
127+
128+
# Invest the given amount of stable and asset token into the vault:
129+
position.do_invest(<stable_token_amt>, <asset_token_amt>)
130+
131+
132+
# Withdraw the given amount of shares from the vault:
133+
# Available strategies: "Minimize Trading" and "Convert All" (as shown on the webapp)
134+
135+
# Using the "Minimize Trading" strategy (default, so not necessary to specify strategy):
136+
position.do_withdraw(<shares_amt>)
137+
# Using the "Convert All" strategy (must specify, and provide the percentage of stable token to receive):
138+
position.do_withdraw(<shares_amt>, <pct_stable_token>, strategy="Convert All")
139+
140+
141+
# Close a position (remove all shares):
142+
143+
# (default) Using the "Minimize Trading" strategy:
144+
position.do_close()
145+
# Optionally specify the "Convert All" strategy:
146+
position.do_close(<pct_stable_token>, strategy="Convert All")
107147
```
108148

109149
___

alpaca_finance/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__version__ = "1.0.0"

alpaca_finance/automated_vault/contracts.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,18 @@ def __init__(self, vault_address: str, w3_provider: Web3 = None, protocol: str =
7676
self.partialCloseMinimizeStrat = {"pancakeswap": r['SharedStrategies']["Pancakeswap"]["StrategyPartialCloseMinimizeTrading"],
7777
"biswap": r['SharedStrategies']["Biswap"]["StrategyPartialCloseMinimizeTrading"]}
7878

79-
def invest(self) -> web3.contract.ContractFunction:
80-
pass
79+
def invest(self, stableTokenAmount: int, assetTokenAmount: int, shareReceiver: str) -> web3.contract.ContractFunction:
80+
"""Invest the specified token into the vault"""
81+
82+
minShareReceive = 0 # Slippage
83+
84+
_calldata = encode_abi(
85+
["uint256"],
86+
[25]
87+
)
88+
89+
return self.contract.functions.deposit(stableTokenAmount, assetTokenAmount, checksum(shareReceiver),
90+
minShareReceive, _calldata)
8191

8292
def withdraw(self, shares: int) -> web3.contract.ContractFunction:
8393
"""

alpaca_finance/automated_vault/position.py

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Optional, Union
1+
from typing import Union, Optional
22
from math import floor
33

44
from ..util import get_entry_prices, get_web3_provider, get_vault_addresses
@@ -20,6 +20,8 @@ def __init__(self, position_key: str, owner_wallet_address: str, owner_wallet_ke
2020
self.w3_provider = get_web3_provider(DEFAULT_BSC_RPC_URL)
2121
else:
2222
self.w3_provider = w3_provider
23+
if self.w3_provider.eth.chainId != 56:
24+
raise ValueError("This package currently supports positions on the Binance Smart Chain (BSC - 56) network only")
2325

2426
summary = self.get_vault_summary(position_key.lower())
2527

@@ -45,8 +47,19 @@ def __init__(self, position_key: str, owner_wallet_address: str, owner_wallet_ke
4547

4648
""" ------------------ Transactional Methods (Requires private wallet key) ------------------ """
4749

48-
def do_invest(self) -> TransactionReceipt:
49-
raise NotImplementedError
50+
def do_invest(self, stable_token_amt: int = 0, asset_token_amt: int = 0) -> TransactionReceipt:
51+
"""
52+
Invest the specified amount of each token into the Automated Vault.
53+
Use self.asset_token and self.stable_token to identify the underlying assets.
54+
55+
:param stable_token_amt: The amount of stable token to deposit
56+
:param asset_token_amt: The amount of asset token to deposit
57+
:return:
58+
"""
59+
assert stable_token_amt > 0 or asset_token_amt > 0, \
60+
"Please provide an investment value for either the stable or asset tokens"
61+
62+
return self._execute(self.vault.invest(stable_token_amt, asset_token_amt, shareReceiver=self.owner_address))
5063

5164
def do_withdraw(self, shares: int, pct_stable: float = None, strategy: str = "Minimize Trading") -> TransactionReceipt:
5265
"""
@@ -80,6 +93,20 @@ def do_close(self, pct_stable: float = None, strategy: str = "Minimize Trading")
8093
"""
8194
return self.do_withdraw(shares=self.shares()[0], pct_stable=pct_stable, strategy=strategy)
8295

96+
def do_approve_deposit_token(self, token: Union[BEP20Token, str], amount: int = None) -> TransactionReceipt:
97+
"""
98+
Approves the given token for deposit into an Automated Vault.
99+
100+
:param token: Optional - either the BEP20Token object, or the token address (str)
101+
:param amount: The amount of token to approve, default = maximum
102+
"""
103+
if type(token) != BEP20Token:
104+
token = BEP20Token(token)
105+
106+
func_call = token.prepare_approve(self.address, amount)
107+
return self._execute(func_call)
108+
109+
83110
""" ---------------- Informational Methods (Private wallet key not required) ---------------- """
84111

85112
def get_vault_summary(self, position_key: str = None) -> AttrDict:
@@ -214,7 +241,7 @@ def _execute(self, function_call: web3.contract.ContractFunction) -> Transaction
214241
'gasPrice': 5000000000,
215242
'nonce': self.w3_provider.eth.get_transaction_count(self.owner_address),
216243
})
217-
print(txn)
244+
# print(txn)
218245

219246
signed_txn = self.w3_provider.eth.account.sign_transaction(
220247
txn, private_key=self.owner_key
@@ -278,7 +305,7 @@ def _decode_deposit_transaction(self, transaction_address: Optional):
278305
)
279306
"""
280307
transaction = self.w3_provider.eth.get_transaction(transaction_address)
281-
print(transaction)
308+
# print(transaction)
282309

283310
try:
284311
decoded_bank_transaction = self.vault.contract.decode_function_input(transaction.input)

0 commit comments

Comments
 (0)