Skip to content

Commit 5700bf8

Browse files
authored
Merge pull request #54 from zahidhussaina2l/patch-1
Create binance_spot.py
2 parents fbaeaf6 + c07b703 commit 5700bf8

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from components.actions.base.action import Action
2+
import ccxt as ccxt
3+
4+
class BinanceSpot(Action):
5+
#Add your API_KEY from Binance Testnet or Mainnet
6+
API_KEY = ''
7+
#Add your API_SECRET from Binance Testnet or Mainnet
8+
API_SECRET = ''
9+
10+
exchange = ccxt.binance({
11+
'rateLimit': 2000,
12+
'enableRateLimit': True,
13+
'apiKey': API_KEY,
14+
'secret': API_SECRET,
15+
'id': 'binance',
16+
})
17+
18+
def __init__(self):
19+
super().__init__()
20+
#uncomment the below line to use sandbox/testnet api
21+
# exchange = self.exchange.set_sandbox_mode(True)
22+
23+
def place_order(self, symbol, side, price=None):
24+
try:
25+
26+
# Get the balance of the base currency
27+
balance = self.exchange.fetch_balance()
28+
if side == 'buy':
29+
base_balance = balance['free'][symbol[-4:]]
30+
elif side == 'sell':
31+
base_balance = balance['free'][symbol[:-4]]
32+
33+
# Calculate the amount of asset to buy or sell
34+
if side == 'buy':
35+
amount = base_balance / price
36+
elif side == 'sell':
37+
amount = base_balance
38+
39+
markets = self.exchange.load_markets()
40+
formatted_amount = self.exchange.amount_to_precision(symbol, amount)
41+
order = self.exchange.create_market_order(symbol, side, quoteOrderQty=formatted_amount)
42+
print(order)
43+
# Print the order details
44+
except ccxt.BaseError as e:
45+
# Handle the exception
46+
print("An error occurred while placing the order:", e)
47+
except ValueError as e:
48+
# Handle the exception
49+
print("An error occurred while checking the filters or calculating the amount:", e)
50+
51+
def run(self, *args, **kwargs):
52+
super().run(*args, **kwargs) # this is required
53+
data = self.validate_data()
54+
self.place_order(symbol=data['symbol'], side=data['side'])

0 commit comments

Comments
 (0)