如何在 Python 中管理内存
How to manage memory in Python
我有一个用 python 开发的简单软件。我的电脑不是很强大,但我需要同时在我的电脑上运行 20到40个这样的程序。
进入任务管理器后,我发现程序虽然很简单,但是占用内存很大。您可以在下图中看到它;
我在内存管理方面做错了什么吗?我如何配置该程序才能使我的计算机不那么累人?感谢您的帮助:)
我的代码如下;
import ops
import talib
import numpy
import math
import time
import urllib.request
from datetime import datetime
import csv
import smtplib
import config
from binance.client import Client
while True:
time.sleep(1)
now = datetime.now()
if (now.minute % 5) == 0 and now.second == 3:
ops.check_internet_conn(urllib, time)
now = ops.check_time(datetime, time, now, 5)
client = Client(config.api_key, config.api_secret)
balance = 15.0
is_active = ops.check_active_positions(client, time, "ETHUSDT")
candles = ops.get_candlesticks(client, time)
close_prices = ops.get_close_prices(candles)
numpy_prices = numpy.array(close_prices)
ema_200 = talib.EMA(numpy_prices, 200)
selected_cs = 498
ts = int(candles[selected_cs][0])
dt_obj = datetime.fromtimestamp(ts / 1000)
high = float("{:.2f}".format(float(candles[(selected_cs - 1)][2])))
low = float("{:.2f}".format(float(candles[(selected_cs - 1)][3])))
close = float("{:.2f}".format(float(candles[selected_cs][4])))
ema = float("{:.2f}".format(float(ema_200[selected_cs])))
bb_upper = float("{:.2f}".format(float(upper[selected_cs])))
bb_middle = float("{:.2f}".format(float(middle[selected_cs])))
bb_lower = float("{:.2f}".format(float(lower[selected_cs])))
if close > ema:
direction = "BUY"
else:
direction = "SELL"
stop_loss = ops.calc_stop_loss(direction, close, high, low)
take_profit = ops.calc_take_profit(direction, close, high, low)
leverage = 3
quantity = ops.calc_quantity(time, balance, leverage, close)
print("----------------------------------------")
print("Run Time: {0}:{1}:{2}".format(now.hour, now.minute, now.second))
print("CS Datetime: ", dt_obj)
print("USDT Balance: ", balance, "USDT")
print("----------------------------------------")
print("High: ", high)
print("Low: ", low)
print("Close: ", close)
print("----------------------------------------")
print("Ema ", ema)
print("----------------------------------------")
print("Entry Price: ", close)
print("Take Profit: ", take_profit)
print("Stop Loss: ", stop_loss)
print("Leverage: ", leverage)
print("Direction: ", direction)
print("Quantity: ", quantity)
print("----------------------------------------")
print("Is Active: ", is_active)
print("----------------------------------------")
b_cons = close > ema and is_active == False and 0 < leverage < 101
s_cons = close < ema and is_active == False and 0 < leverage < 101
if b_cons or s_cons:
ops.close_open_orders(client, time, "ETHUSDT")
ops.set_leverage(client, time, leverage)
ops.place_order(client, time, direction, quantity, close)
ops.set_stop_loss(client, time, direction, stop_loss)
ops.set_take_profit(client, time, direction, take_profit)
ops.py
def check_internet_conn(urllib, time):
print("\n----------------------------------------")
while True:
try:
urllib.request.urlopen('http://google.com')
print("İnternet bağlantısı mevcut.")
break
except Exception:
print("İnternet bağlantısı yok. Tekrar bağlantı deneniyor..")
time.sleep(5)
def check_time(datetime, time, old_now, mn):
now = datetime.now()
if old_now.minute != now.minute:
while True:
time.sleep(1)
now = datetime.now()
if (now.minute % mn) == 0 and now.second == 0:
break
return now
def get_candlesticks(client, time):
while True:
try:
candles = client.futures_klines(symbol='ETHUSDT', interval=client.KLINE_INTERVAL_5MINUTE)
if len(candles) > 0:
return candles
except Exception as e:
print("Candles Error:", e)
time.sleep(1)
pass
def get_close_prices(cs_list):
close_prices = []
for candle in cs_list:
close_prices.append(float(candle[4]))
return close_prices
def calc_stop_loss(side, close_price, last_high, last_low):
if side == "BUY":
difference = close_price - last_low
stop_loss = float("{:.2f}".format(close_price - (difference * 1.1)))
else:
difference = last_high - close_price
stop_loss = float("{:.2f}".format(close_price + (difference * 1.1)))
return stop_loss
def calc_take_profit(side, close_price, last_high, last_low):
if side == "BUY":
difference = close_price - last_low
take_profit = float("{:.2f}".format(close_price + (difference * 1.1 * 1.5)))
else:
difference = last_high - close_price
take_profit = float("{:.2f}".format(close_price - (difference * 1.1 * 1.5)))
return take_profit
def calc_quantity(time, balance, leverage, close):
while True:
try:
quantity = float("{:.3f}".format(((balance * 0.9) / close) * leverage))
if type(quantity) == float:
return quantity
except Exception as e:
print("Quantity Error:", e)
time.sleep(1)
pass
def check_active_positions(client, time, coin):
while True:
try:
positions = client.futures_position_information()
amount = None
for pos in positions:
if pos["symbol"] == coin:
amount = float(pos["positionAmt"])
if len(positions) > 0 and amount == 0:
return False
elif len(positions) > 0 and amount != 0:
return True
except Exception as e:
print("Check Active Position Error:", e)
time.sleep(1)
pass
def close_open_orders(client, time, symbol):
while True:
try:
client.futures_cancel_all_open_orders(symbol=symbol)
break
except Exception as e:
print("Close Open Orders Error:", e)
time.sleep(1)
pass
def set_leverage(client, time, leverage):
while True:
try:
client.futures_change_leverage(symbol="ETHUSDT", leverage=leverage)
break
except Exception as e:
print("Set Leverage Error:", e)
time.sleep(1)
pass
def place_order(client, time, direction, quantity, close):
if direction == "BUY":
while True:
try:
buy_sell_order = client.futures_create_order(symbol="ETHUSDT", side=direction, type="LIMIT",
timeinforce="GTC", quantity=quantity, price=close)
print("Buy Order :", buy_sell_order)
print("----------------------------------------")
break
except Exception as e:
print("Buy Order Error:", e)
time.sleep(1)
pass
else:
while True:
try:
buy_sell_order = client.futures_create_order(symbol="ETHUSDT", side=direction, type="LIMIT",
timeinforce="GTC", quantity=quantity, price=close)
print("Buy Order :", buy_sell_order)
print("----------------------------------------")
break
except Exception as e:
print("Sell Order Error:", e)
time.sleep(1)
pass
def set_stop_loss(client, time, direction, stop_loss):
if direction == "BUY":
while True:
try:
stop_loss_order = client.futures_create_order(symbol="ETHUSDT", side="SELL", type="STOP_MARKET",
stopPrice=stop_loss, closePosition="true")
print("Stop Loss Order :", stop_loss_order)
print("----------------------------------------")
break
except Exception as e:
print("Set Stop Loss Error:", e)
time.sleep(1)
pass
else:
while True:
try:
stop_loss_order = client.futures_create_order(symbol="ETHUSDT", side="BUY", type="STOP_MARKET",
stopPrice=stop_loss, closePosition="true")
print("Stop Loss Order :", stop_loss_order)
print("----------------------------------------")
break
except Exception as e:
print("Set Stop Loss Error:", e)
time.sleep(1)
pass
def set_take_profit(client, time, direction, take_profit):
if direction == "BUY":
while True:
try:
take_profit_order = client.futures_create_order(symbol="ETHUSDT", side="SELL",
type="TAKE_PROFIT_MARKET", stopPrice=take_profit,
closePosition="true")
print("Take Profit Order:", take_profit_order)
print("----------------------------------------")
break
except Exception as e:
print("Set Take Profit Error:", e)
time.sleep(1)
pass
else:
while True:
try:
take_profit_order = client.futures_create_order(symbol="ETHUSDT", side="BUY",
type="TAKE_PROFIT_MARKET", stopPrice=take_profit,
closePosition="true")
print("Take Profit Order:", take_profit_order)
print("----------------------------------------")
break
except Exception as e:
print("Set Take Profit Error:", e)
time.sleep(1)
pass
在发布的打印屏幕上,您显示了 IDE. To be clear, PyCharm is not your python programme. You should run you python code in console. In this case 20 consoles (cmd)。此外,PyCharm有时需要大量内存,这完全正常。
如果你有 Windows OS 你可以尝试 运行 python cmd 中的代码。只需在 cmd 中输入 window:
python [my_code].py
它应该可以工作。
如果您担心内存使用量,如果 PyCharm 占用大量内存,请在 cmd 上尝试 运行 它们。因为它是一个 IDE,所以除了 运行 您的代码之外,它可能还在后台做几件事。
除此之外,可能值得分析您的 python 代码的内存使用情况,看看您是否可以进行某种代码优化。您可以使用 memory_profiler .
之类的东西
我有一个用 python 开发的简单软件。我的电脑不是很强大,但我需要同时在我的电脑上运行 20到40个这样的程序。
进入任务管理器后,我发现程序虽然很简单,但是占用内存很大。您可以在下图中看到它;
我在内存管理方面做错了什么吗?我如何配置该程序才能使我的计算机不那么累人?感谢您的帮助:)
我的代码如下;
import ops
import talib
import numpy
import math
import time
import urllib.request
from datetime import datetime
import csv
import smtplib
import config
from binance.client import Client
while True:
time.sleep(1)
now = datetime.now()
if (now.minute % 5) == 0 and now.second == 3:
ops.check_internet_conn(urllib, time)
now = ops.check_time(datetime, time, now, 5)
client = Client(config.api_key, config.api_secret)
balance = 15.0
is_active = ops.check_active_positions(client, time, "ETHUSDT")
candles = ops.get_candlesticks(client, time)
close_prices = ops.get_close_prices(candles)
numpy_prices = numpy.array(close_prices)
ema_200 = talib.EMA(numpy_prices, 200)
selected_cs = 498
ts = int(candles[selected_cs][0])
dt_obj = datetime.fromtimestamp(ts / 1000)
high = float("{:.2f}".format(float(candles[(selected_cs - 1)][2])))
low = float("{:.2f}".format(float(candles[(selected_cs - 1)][3])))
close = float("{:.2f}".format(float(candles[selected_cs][4])))
ema = float("{:.2f}".format(float(ema_200[selected_cs])))
bb_upper = float("{:.2f}".format(float(upper[selected_cs])))
bb_middle = float("{:.2f}".format(float(middle[selected_cs])))
bb_lower = float("{:.2f}".format(float(lower[selected_cs])))
if close > ema:
direction = "BUY"
else:
direction = "SELL"
stop_loss = ops.calc_stop_loss(direction, close, high, low)
take_profit = ops.calc_take_profit(direction, close, high, low)
leverage = 3
quantity = ops.calc_quantity(time, balance, leverage, close)
print("----------------------------------------")
print("Run Time: {0}:{1}:{2}".format(now.hour, now.minute, now.second))
print("CS Datetime: ", dt_obj)
print("USDT Balance: ", balance, "USDT")
print("----------------------------------------")
print("High: ", high)
print("Low: ", low)
print("Close: ", close)
print("----------------------------------------")
print("Ema ", ema)
print("----------------------------------------")
print("Entry Price: ", close)
print("Take Profit: ", take_profit)
print("Stop Loss: ", stop_loss)
print("Leverage: ", leverage)
print("Direction: ", direction)
print("Quantity: ", quantity)
print("----------------------------------------")
print("Is Active: ", is_active)
print("----------------------------------------")
b_cons = close > ema and is_active == False and 0 < leverage < 101
s_cons = close < ema and is_active == False and 0 < leverage < 101
if b_cons or s_cons:
ops.close_open_orders(client, time, "ETHUSDT")
ops.set_leverage(client, time, leverage)
ops.place_order(client, time, direction, quantity, close)
ops.set_stop_loss(client, time, direction, stop_loss)
ops.set_take_profit(client, time, direction, take_profit)
ops.py
def check_internet_conn(urllib, time):
print("\n----------------------------------------")
while True:
try:
urllib.request.urlopen('http://google.com')
print("İnternet bağlantısı mevcut.")
break
except Exception:
print("İnternet bağlantısı yok. Tekrar bağlantı deneniyor..")
time.sleep(5)
def check_time(datetime, time, old_now, mn):
now = datetime.now()
if old_now.minute != now.minute:
while True:
time.sleep(1)
now = datetime.now()
if (now.minute % mn) == 0 and now.second == 0:
break
return now
def get_candlesticks(client, time):
while True:
try:
candles = client.futures_klines(symbol='ETHUSDT', interval=client.KLINE_INTERVAL_5MINUTE)
if len(candles) > 0:
return candles
except Exception as e:
print("Candles Error:", e)
time.sleep(1)
pass
def get_close_prices(cs_list):
close_prices = []
for candle in cs_list:
close_prices.append(float(candle[4]))
return close_prices
def calc_stop_loss(side, close_price, last_high, last_low):
if side == "BUY":
difference = close_price - last_low
stop_loss = float("{:.2f}".format(close_price - (difference * 1.1)))
else:
difference = last_high - close_price
stop_loss = float("{:.2f}".format(close_price + (difference * 1.1)))
return stop_loss
def calc_take_profit(side, close_price, last_high, last_low):
if side == "BUY":
difference = close_price - last_low
take_profit = float("{:.2f}".format(close_price + (difference * 1.1 * 1.5)))
else:
difference = last_high - close_price
take_profit = float("{:.2f}".format(close_price - (difference * 1.1 * 1.5)))
return take_profit
def calc_quantity(time, balance, leverage, close):
while True:
try:
quantity = float("{:.3f}".format(((balance * 0.9) / close) * leverage))
if type(quantity) == float:
return quantity
except Exception as e:
print("Quantity Error:", e)
time.sleep(1)
pass
def check_active_positions(client, time, coin):
while True:
try:
positions = client.futures_position_information()
amount = None
for pos in positions:
if pos["symbol"] == coin:
amount = float(pos["positionAmt"])
if len(positions) > 0 and amount == 0:
return False
elif len(positions) > 0 and amount != 0:
return True
except Exception as e:
print("Check Active Position Error:", e)
time.sleep(1)
pass
def close_open_orders(client, time, symbol):
while True:
try:
client.futures_cancel_all_open_orders(symbol=symbol)
break
except Exception as e:
print("Close Open Orders Error:", e)
time.sleep(1)
pass
def set_leverage(client, time, leverage):
while True:
try:
client.futures_change_leverage(symbol="ETHUSDT", leverage=leverage)
break
except Exception as e:
print("Set Leverage Error:", e)
time.sleep(1)
pass
def place_order(client, time, direction, quantity, close):
if direction == "BUY":
while True:
try:
buy_sell_order = client.futures_create_order(symbol="ETHUSDT", side=direction, type="LIMIT",
timeinforce="GTC", quantity=quantity, price=close)
print("Buy Order :", buy_sell_order)
print("----------------------------------------")
break
except Exception as e:
print("Buy Order Error:", e)
time.sleep(1)
pass
else:
while True:
try:
buy_sell_order = client.futures_create_order(symbol="ETHUSDT", side=direction, type="LIMIT",
timeinforce="GTC", quantity=quantity, price=close)
print("Buy Order :", buy_sell_order)
print("----------------------------------------")
break
except Exception as e:
print("Sell Order Error:", e)
time.sleep(1)
pass
def set_stop_loss(client, time, direction, stop_loss):
if direction == "BUY":
while True:
try:
stop_loss_order = client.futures_create_order(symbol="ETHUSDT", side="SELL", type="STOP_MARKET",
stopPrice=stop_loss, closePosition="true")
print("Stop Loss Order :", stop_loss_order)
print("----------------------------------------")
break
except Exception as e:
print("Set Stop Loss Error:", e)
time.sleep(1)
pass
else:
while True:
try:
stop_loss_order = client.futures_create_order(symbol="ETHUSDT", side="BUY", type="STOP_MARKET",
stopPrice=stop_loss, closePosition="true")
print("Stop Loss Order :", stop_loss_order)
print("----------------------------------------")
break
except Exception as e:
print("Set Stop Loss Error:", e)
time.sleep(1)
pass
def set_take_profit(client, time, direction, take_profit):
if direction == "BUY":
while True:
try:
take_profit_order = client.futures_create_order(symbol="ETHUSDT", side="SELL",
type="TAKE_PROFIT_MARKET", stopPrice=take_profit,
closePosition="true")
print("Take Profit Order:", take_profit_order)
print("----------------------------------------")
break
except Exception as e:
print("Set Take Profit Error:", e)
time.sleep(1)
pass
else:
while True:
try:
take_profit_order = client.futures_create_order(symbol="ETHUSDT", side="BUY",
type="TAKE_PROFIT_MARKET", stopPrice=take_profit,
closePosition="true")
print("Take Profit Order:", take_profit_order)
print("----------------------------------------")
break
except Exception as e:
print("Set Take Profit Error:", e)
time.sleep(1)
pass
在发布的打印屏幕上,您显示了 IDE. To be clear, PyCharm is not your python programme. You should run you python code in console. In this case 20 consoles (cmd)。此外,PyCharm有时需要大量内存,这完全正常。
如果你有 Windows OS 你可以尝试 运行 python cmd 中的代码。只需在 cmd 中输入 window:
python [my_code].py
它应该可以工作。
如果您担心内存使用量,如果 PyCharm 占用大量内存,请在 cmd 上尝试 运行 它们。因为它是一个 IDE,所以除了 运行 您的代码之外,它可能还在后台做几件事。
除此之外,可能值得分析您的 python 代码的内存使用情况,看看您是否可以进行某种代码优化。您可以使用 memory_profiler .
之类的东西