Update app.py
Browse files
app.py
CHANGED
|
@@ -262,6 +262,71 @@ def get_open_positions(ssl_sock, account_id):
|
|
| 262 |
return res.position
|
| 263 |
return []
|
| 264 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
# Helper: Place Market Order or Close Position
|
| 266 |
def place_market_order(ssl_sock, account_id, symbol_id, trade_side, volume, position_id=None):
|
| 267 |
if position_id is not None:
|
|
@@ -838,28 +903,44 @@ async def webhook(request: Request):
|
|
| 838 |
execution_msg = ""
|
| 839 |
|
| 840 |
if action == "BUY":
|
| 841 |
-
#
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
logger.info(f"Closing Short position ID {p.positionId}...")
|
| 845 |
-
place_market_order(ssl_sock, account_id, symbol_id, ProtoOATradeSide.BUY, p.tradeData.volume, position_id=p.positionId)
|
| 846 |
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 851 |
|
| 852 |
elif action == "SELL":
|
| 853 |
-
#
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
logger.info(f"Closing Long position ID {p.positionId}...")
|
| 857 |
-
place_market_order(ssl_sock, account_id, symbol_id, ProtoOATradeSide.SELL, p.tradeData.volume, position_id=p.positionId)
|
| 858 |
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 863 |
|
| 864 |
elif action == "CLOSE":
|
| 865 |
# CLOSE = force-close ALL positions on this symbol (manual override)
|
|
@@ -874,43 +955,7 @@ async def webhook(request: Request):
|
|
| 874 |
elif action == "STOP-TRADE":
|
| 875 |
# STOP-TRADE = only close PROFITABLE positions, leave losing ones open
|
| 876 |
if len(symbol_positions) > 0:
|
| 877 |
-
|
| 878 |
-
current_bid = None
|
| 879 |
-
current_ask = None
|
| 880 |
-
try:
|
| 881 |
-
spot_req = ProtoOASubscribeSpotsReq()
|
| 882 |
-
spot_req.ctidTraderAccountId = int(account_id)
|
| 883 |
-
spot_req.symbolId.append(int(symbol_id))
|
| 884 |
-
send_proto_message(ssl_sock, spot_req, 2127)
|
| 885 |
-
|
| 886 |
-
# Read responses until we get a spot event
|
| 887 |
-
for _ in range(10):
|
| 888 |
-
proto_msg = receive_proto_message(ssl_sock)
|
| 889 |
-
if not proto_msg:
|
| 890 |
-
break
|
| 891 |
-
if proto_msg.payloadType == 2131: # ProtoOASpotEvent
|
| 892 |
-
spot = ProtoOASpotEvent()
|
| 893 |
-
spot.ParseFromString(proto_msg.payload)
|
| 894 |
-
if hasattr(spot, 'bid') and spot.bid:
|
| 895 |
-
current_bid = spot.bid / 100000.0 # Convert from protocol price
|
| 896 |
-
if hasattr(spot, 'ask') and spot.ask:
|
| 897 |
-
current_ask = spot.ask / 100000.0
|
| 898 |
-
if current_bid and current_ask:
|
| 899 |
-
break
|
| 900 |
-
elif proto_msg.payloadType == 2128: # Subscribe confirmation
|
| 901 |
-
continue
|
| 902 |
-
|
| 903 |
-
# Unsubscribe from spots
|
| 904 |
-
try:
|
| 905 |
-
unsub_req = ProtoOAUnsubscribeSpotsReq()
|
| 906 |
-
unsub_req.ctidTraderAccountId = int(account_id)
|
| 907 |
-
unsub_req.symbolId.append(int(symbol_id))
|
| 908 |
-
send_proto_message(ssl_sock, unsub_req, 2129)
|
| 909 |
-
receive_proto_message(ssl_sock) # Consume the response
|
| 910 |
-
except Exception:
|
| 911 |
-
pass
|
| 912 |
-
except Exception as e:
|
| 913 |
-
logger.warning(f"Could not fetch spot price: {e}")
|
| 914 |
|
| 915 |
closed_count = 0
|
| 916 |
skipped_count = 0
|
|
@@ -930,7 +975,6 @@ async def webhook(request: Request):
|
|
| 930 |
in_profit = entry_price > current_ask
|
| 931 |
else:
|
| 932 |
# Fallback: use the swap field as a rough P&L indicator
|
| 933 |
-
# If we couldn't get spot prices, check if swap is positive
|
| 934 |
in_profit = getattr(p, 'swap', 0) > 0
|
| 935 |
logger.warning(f"No spot price available, using swap as fallback for position {p.positionId}")
|
| 936 |
|
|
|
|
| 262 |
return res.position
|
| 263 |
return []
|
| 264 |
|
| 265 |
+
# Config: Max losing positions allowed per direction per symbol
|
| 266 |
+
MAX_LOSING_POSITIONS = 2
|
| 267 |
+
|
| 268 |
+
# Helper: Get current spot price (bid/ask) for a symbol
|
| 269 |
+
def get_spot_price(ssl_sock, account_id, symbol_id):
|
| 270 |
+
current_bid = None
|
| 271 |
+
current_ask = None
|
| 272 |
+
try:
|
| 273 |
+
spot_req = ProtoOASubscribeSpotsReq()
|
| 274 |
+
spot_req.ctidTraderAccountId = int(account_id)
|
| 275 |
+
spot_req.symbolId.append(int(symbol_id))
|
| 276 |
+
send_proto_message(ssl_sock, spot_req, 2127)
|
| 277 |
+
|
| 278 |
+
# Read responses until we get a spot event
|
| 279 |
+
for _ in range(10):
|
| 280 |
+
proto_msg = receive_proto_message(ssl_sock)
|
| 281 |
+
if not proto_msg:
|
| 282 |
+
break
|
| 283 |
+
if proto_msg.payloadType == 2131: # ProtoOASpotEvent
|
| 284 |
+
spot = ProtoOASpotEvent()
|
| 285 |
+
spot.ParseFromString(proto_msg.payload)
|
| 286 |
+
if hasattr(spot, 'bid') and spot.bid:
|
| 287 |
+
current_bid = spot.bid / 100000.0 # Convert from protocol price
|
| 288 |
+
if hasattr(spot, 'ask') and spot.ask:
|
| 289 |
+
current_ask = spot.ask / 100000.0
|
| 290 |
+
if current_bid and current_ask:
|
| 291 |
+
break
|
| 292 |
+
elif proto_msg.payloadType == 2128: # Subscribe confirmation
|
| 293 |
+
continue
|
| 294 |
+
|
| 295 |
+
# Unsubscribe from spots
|
| 296 |
+
try:
|
| 297 |
+
unsub_req = ProtoOAUnsubscribeSpotsReq()
|
| 298 |
+
unsub_req.ctidTraderAccountId = int(account_id)
|
| 299 |
+
unsub_req.symbolId.append(int(symbol_id))
|
| 300 |
+
send_proto_message(ssl_sock, unsub_req, 2129)
|
| 301 |
+
receive_proto_message(ssl_sock) # Consume the response
|
| 302 |
+
except Exception:
|
| 303 |
+
pass
|
| 304 |
+
except Exception as e:
|
| 305 |
+
logger.warning(f"Could not fetch spot price: {e}")
|
| 306 |
+
|
| 307 |
+
return current_bid, current_ask
|
| 308 |
+
|
| 309 |
+
# Helper: Count losing positions in a given direction
|
| 310 |
+
def count_losing_positions(positions, trade_side, current_bid, current_ask):
|
| 311 |
+
"""Count positions that are currently in loss.
|
| 312 |
+
trade_side: 1 = BUY positions, 2 = SELL positions"""
|
| 313 |
+
count = 0
|
| 314 |
+
for p in positions:
|
| 315 |
+
if p.tradeData.tradeSide != trade_side:
|
| 316 |
+
continue
|
| 317 |
+
entry_price = p.price
|
| 318 |
+
if trade_side == 1: # BUY position is losing when bid <= entry
|
| 319 |
+
if current_bid and current_bid <= entry_price:
|
| 320 |
+
count += 1
|
| 321 |
+
elif not current_bid:
|
| 322 |
+
count += 1 # Can't determine, assume losing to be safe
|
| 323 |
+
else: # SELL position is losing when ask >= entry
|
| 324 |
+
if current_ask and current_ask >= entry_price:
|
| 325 |
+
count += 1
|
| 326 |
+
elif not current_ask:
|
| 327 |
+
count += 1
|
| 328 |
+
return count
|
| 329 |
+
|
| 330 |
# Helper: Place Market Order or Close Position
|
| 331 |
def place_market_order(ssl_sock, account_id, symbol_id, trade_side, volume, position_id=None):
|
| 332 |
if position_id is not None:
|
|
|
|
| 903 |
execution_msg = ""
|
| 904 |
|
| 905 |
if action == "BUY":
|
| 906 |
+
# Check if we already have too many losing BUY positions
|
| 907 |
+
current_bid, current_ask = get_spot_price(ssl_sock, account_id, symbol_id)
|
| 908 |
+
losing_count = count_losing_positions(symbol_positions, 1, current_bid, current_ask)
|
|
|
|
|
|
|
| 909 |
|
| 910 |
+
if losing_count >= MAX_LOSING_POSITIONS:
|
| 911 |
+
execution_msg = f"BUY BLOCKED: Already {losing_count} losing BUY position(s) on {ticker}. Max {MAX_LOSING_POSITIONS} allowed."
|
| 912 |
+
logger.info(execution_msg)
|
| 913 |
+
else:
|
| 914 |
+
# 1. Close any open SELL (short) positions first
|
| 915 |
+
for p in symbol_positions:
|
| 916 |
+
if p.tradeData.tradeSide == 2: # 2 = SELL
|
| 917 |
+
logger.info(f"Closing Short position ID {p.positionId}...")
|
| 918 |
+
place_market_order(ssl_sock, account_id, symbol_id, ProtoOATradeSide.BUY, p.tradeData.volume, position_id=p.positionId)
|
| 919 |
+
|
| 920 |
+
# 2. Place new BUY position
|
| 921 |
+
logger.info(f"Opening new Long position... ({losing_count} losing BUY(s) open, limit {MAX_LOSING_POSITIONS})")
|
| 922 |
+
res = place_market_order(ssl_sock, account_id, symbol_id, ProtoOATradeSide.BUY, current_trade_volume)
|
| 923 |
+
execution_msg = f"Opened BUY position for {ticker}. Order Result: {res.get('status')} {res.get('message', '')}"
|
| 924 |
|
| 925 |
elif action == "SELL":
|
| 926 |
+
# Check if we already have too many losing SELL positions
|
| 927 |
+
current_bid, current_ask = get_spot_price(ssl_sock, account_id, symbol_id)
|
| 928 |
+
losing_count = count_losing_positions(symbol_positions, 2, current_bid, current_ask)
|
|
|
|
|
|
|
| 929 |
|
| 930 |
+
if losing_count >= MAX_LOSING_POSITIONS:
|
| 931 |
+
execution_msg = f"SELL BLOCKED: Already {losing_count} losing SELL position(s) on {ticker}. Max {MAX_LOSING_POSITIONS} allowed."
|
| 932 |
+
logger.info(execution_msg)
|
| 933 |
+
else:
|
| 934 |
+
# 1. Close any open BUY (long) positions first
|
| 935 |
+
for p in symbol_positions:
|
| 936 |
+
if p.tradeData.tradeSide == 1: # 1 = BUY
|
| 937 |
+
logger.info(f"Closing Long position ID {p.positionId}...")
|
| 938 |
+
place_market_order(ssl_sock, account_id, symbol_id, ProtoOATradeSide.SELL, p.tradeData.volume, position_id=p.positionId)
|
| 939 |
+
|
| 940 |
+
# 2. Place new SELL position
|
| 941 |
+
logger.info(f"Opening new Short position... ({losing_count} losing SELL(s) open, limit {MAX_LOSING_POSITIONS})")
|
| 942 |
+
res = place_market_order(ssl_sock, account_id, symbol_id, ProtoOATradeSide.SELL, current_trade_volume)
|
| 943 |
+
execution_msg = f"Opened SELL position for {ticker}. Order Result: {res.get('status')} {res.get('message', '')}"
|
| 944 |
|
| 945 |
elif action == "CLOSE":
|
| 946 |
# CLOSE = force-close ALL positions on this symbol (manual override)
|
|
|
|
| 955 |
elif action == "STOP-TRADE":
|
| 956 |
# STOP-TRADE = only close PROFITABLE positions, leave losing ones open
|
| 957 |
if len(symbol_positions) > 0:
|
| 958 |
+
current_bid, current_ask = get_spot_price(ssl_sock, account_id, symbol_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 959 |
|
| 960 |
closed_count = 0
|
| 961 |
skipped_count = 0
|
|
|
|
| 975 |
in_profit = entry_price > current_ask
|
| 976 |
else:
|
| 977 |
# Fallback: use the swap field as a rough P&L indicator
|
|
|
|
| 978 |
in_profit = getattr(p, 'swap', 0) > 0
|
| 979 |
logger.warning(f"No spot price available, using swap as fallback for position {p.positionId}")
|
| 980 |
|