در کد زیر وقتی روی دکمه close و یا stop up کلیک میکنم چرا به ازای هر رکورد در پایگاه…
- User
در کد زیر وقتی روی دکمه close و یا stop up کلیک میکنم چرا به ازای هر رکورد در پایگاه داده فقط position id آخرین رکورد را به سمت تمپلیت ارسال میکنه؟
from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.db import database_sync_to_async import asyncio from .models import open_positions from decimal import Decimal from account.models import Account
class SocketConsumer(AsyncWebsocketConsumer): async def connect(self): if self.scope["user"].is_authenticated: user_id = self.scope["user"].id perm = await self.get_access_user(user_id) if perm == "admin": await self.accept() self.send_time_task = asyncio.create_task(self.send_time_updates())
async def send_time_updates(self): while True: try: all_items = await self.get_open_positions() send_list_ = [] profit_percent_list = [] profit_usdt_list = [] long_position = 0 short_position = 0 number_positive_position = 0 number_negative_position = 0 all_position_closed = 0 for item in all_items: def check_float_num(x): num = Decimal(str(x)) num_decimal_places = num.as_tuple().exponent return abs(num_decimal_places) if item['status']: position_id = item['id'] pair = item['pair'].upper() position_side = item['position_side'].upper() entry_price = item['entry_price'] num_float = check_float_num(entry_price) tp_price = round(item['tp_price'],num_float) sl_price = round(item['sl_price'],num_float) profit_percent = round(item['profit_percent'],2) profit_usdt = round(item['profit_usdt'],2) risk_reward = round(item['risk_reward'],2) send_list_.append({ "position_id": position_id, "pair": pair, "position_side":position_side, "entry_price": entry_price, "tp_price": tp_price, "sl_price": sl_price, "profit_percent": profit_percent, "profit_usdt": profit_usdt, "risk_reward": risk_reward, }) elif not item['status']: profit_percent = item["profit_percent"] profit_percent_list.append(profit_percent) profit_usdt_list.append(item["profit_usdt"]) position_side = item["position_side"].lower() if position_side == "long": long_position += 1 elif position_side == "short": short_position += 1 if profit_percent >= 0: number_positive_position += 1 elif profit_percent < 0: number_negative_position += 1 all_position_closed += 1 if all_position_closed > 0: average_profit_percent = round(sum(profit_percent_list)/all_position_closed,2) average_profit_usdt = round(sum(profit_usdt_list)/all_position_closed,2) send_list_.append({ "average_profit_percent" : average_profit_percent, "average_profit_usdt" : average_profit_usdt, "long_position" : long_position, "short_position" : short_position, "number_positive_position" : number_positive_position, "number_negative_position" : number_negative_position, }) await self.send(json.dumps(send_list_)) await asyncio.sleep(1) except: pass @database_sync_to_async def get_open_positions(self): open_positions_ = list(open_positions.objects.all().values()) return open_positions_ @database_sync_to_async def get_access_user(self,user_id): acc_perm = Account.objects.get(id=user_id).access return acc_perm async def disconnect(self, close_code): try: self.send_time_task.cancel() except: return await super().disconnect(close_code) - Assistant
این موضوع که فقط شناسه (ID) آخرین رکورد در دکمهها ارسال میشود به دلیل نحوه برخورد JavaScript با محدوده (scope) متغیرها در تابعها است. در کد شما،
position_idداخل حلقه for برای هر رکورد تعریف میشود ولی زمانی که دکمههایonclickتعریف میشوند، ارجاع به آخرین مقدارposition_idرا میگیرند که در آخرین تکرار حلقه set شده است.این رفتار به دلیل Closure در JavaScript است. تابع
onclickبه یک Closure برای متغیرposition_idتبدیل میشود که فقط آخرین مقدار را از حلقه نگه میدارد. برای حل این مشکل، شما میتوانید از ایجاد یک تابع کمکی استفاده کنید که یک محدوده (scope) جدید برای هر تکرار ایجاد میکند.یک راه حل این است که تعریف تابع
onclickرا به یک تابع دیگر منتقل کنید:function createClickHandler(position_id) { return function() { submit_exit_position(position_id); }; } btn_exit.onclick = createClickHandler(position_id); - User
اتفاقا من این دوتا کد رو هم داشتم که فراموش کردم بفرستم
- Assistant
توابع
submit_exit_positionوsubmit_update_stopکه به عنوان کدهای اضافهای فرستاده شدند، مقادیرposition_idمورد نیاز را به درستی دریافت و به سرور ارسال میکنند. مشکل اصلی که شما با آن روبرو هستید مربوط به این است که چگونگی تعریف event handlerها (onclick) در حلقهforمیباشد.با استفاده از رویکرد
createClickHandlerوcreateStopHandlerکه پیشنهاد شد، میتوانید اطمینان حاصل کنید که هر دکمه به درستی بهposition_idمناسب مرتبط شده و هنگام کلیک کردن بر روی آن،position_idصحیح را به توابعsubmit_exit_positionوsubmit_update_stopارسال خواهد کرد. این به شما کمک میکند تا جریان دادهها را به درستی در تمامی دکمهها مدیریت کنید و جلوگیری از به اشتراک گذاشتن مقدارposition_idدر میان همه event handlers را فراهم میآورد.این راه حل مشکل JavaScript closure در حلقهها را برطرف میکند، جایی که تعریف یک متغیر در داخل حلقه باعث میشود که تمام توابع فراخوانی شده (مثلاً event handlers) به آخرین مقدار اختصاص داده شده به آن متغیر دسترسی داشته باشند. با استفاده از تابع سازنده مانند ، شما یک scope جدید برای هر تکرار حلقه ایجاد میکنید و میتوانید مطمئن شوید که هر دکمه به شناسه موقعیت صحیح متصل شده است.
- User
الان میتونی شکل صحیح اسکریپت ها رو بهم بصورت کامل بدی؟
- Assistant
- User
بخش زیر رو توی سورس جا انداختی؟ else if ("average_profit_percent" in items[i]) { document.getElementById("average-percent").value = items[i].average_profit_percent; document.getElementById("average-percent").dir = "ltr"; document.getElementById("average-percent").style = "text-align: center;"; document.getElementById("average-usdt").value = items[i].average_profit_usdt; document.getElementById("average-usdt").dir = "ltr"; document.getElementById("average-usdt").style = "text-align: center;"; document.getElementById("position-long-number").value = items[i].long_position; document.getElementById("position-long-number").dir = "ltr"; document.getElementById("position-long-number").style = "text-align: center;"; document.getElementById("position-short-number").value = items[i].short_position; document.getElementById("position-short-number").dir = "ltr"; document.getElementById("position-short-number").style = "text-align: center;"; document.getElementById("position-positive-number").value = items[i].number_positive_position; document.getElementById("position-positive-number").dir = "ltr"; document.getElementById("position-positive-number").style = "text-align: center;"; document.getElementById("position-negative-number").value = items[i].number_negative_position; document.getElementById("position-negative-number").dir = "ltr"; document.getElementById("position-negative-number").style = "text-align: center;"; }
- Assistant