【发布时间】:2021-08-27 14:04:01
【问题描述】:
我有一个用 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
【问题讨论】:
-
PyCharm 使用的内存与运行脚本无关。这是一个非常复杂的程序,具有许多功能,并且为此使用了大量内存。
标签: python python-3.x memory-management