Skip to content

Commit

Permalink
Merge pull request #17 from Ctri-The-Third/nodeV
Browse files Browse the repository at this point in the history
Add SDK changes and simple "trade best in system" behaviour for commanders
  • Loading branch information
Ctri-The-Third authored Jan 13, 2024
2 parents a04f690 + 71a6799 commit d6fadc5
Show file tree
Hide file tree
Showing 8 changed files with 191 additions and 8 deletions.
6 changes: 6 additions & 0 deletions behaviour_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@
BEHAVIOUR_NAME as BHVR_WARP_TO_SYSTEM,
)

from behaviours.trade_best_intrasolar import (
TradeBestInSystem,
BEHAVIOUR_NAME as BHVR_TRADE_BEST_INTRASOLAR,
)

behaviours_and_classes = {
BHVR_EXTRACT_AND_GO_SELL: ExtractAndGoSell,
BHVR_RECEIVE_AND_FULFILL: ReceiveAndFulfillOrSell_3,
Expand Down Expand Up @@ -142,4 +147,5 @@
BHVR_CHAIN_TRADE_EST: ChainTradeEST,
BHVR_GO_AND_BUY_A_SHIP: GoAndBuyShip,
BHVR_WARP_TO_SYSTEM: WarpToSystem,
BHVR_TRADE_BEST_INTRASOLAR: TradeBestInSystem,
}
8 changes: 4 additions & 4 deletions behaviours/monitor_specific_location.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,14 @@ def monitor_market(self, waypoint_symbol):
if __name__ == "__main__":
from dispatcherWK16 import lock_ship

agent = sys.argv[1] if len(sys.argv) > 2 else "CTRI-W-"
agent = sys.argv[1] if len(sys.argv) > 2 else "CTRI-U-"
# 3, 4,5,6,7,8,9
# A is the surveyor
ship_suffix = sys.argv[2] if len(sys.argv) > 2 else "2"
ship = f"{agent}-{ship_suffix}"
params = {"waypoint": "X1-JR22-A2"}
params = {"waypoint": "X1-TN14-A2"}
bhvr = MonitorPrices(agent, f"{ship}", params)
lock_ship(ship, "MANUAL", bhvr.connection, duration=120)
lock_ship(ship, "MANUAL", duration=120)
set_logging(logging.DEBUG)
bhvr.run()
lock_ship(ship, "", bhvr.connection, duration=0)
lock_ship(ship, "", duration=0)
2 changes: 1 addition & 1 deletion behaviours/sell_or_jettison_all_cargo.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def _run(self):

set_logging(level=logging.DEBUG)
agent = sys.argv[1] if len(sys.argv) > 2 else "CTRI-U-"
ship_number = sys.argv[2] if len(sys.argv) > 2 else "25"
ship_number = sys.argv[2] if len(sys.argv) > 2 else "1"
ship = f"{agent}-{ship_number}"
behaviour_params = {
"priority": 3,
Expand Down
132 changes: 132 additions & 0 deletions behaviours/trade_best_intrasolar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# takes a tradegood. Then trades that to ensure that the market is LIMITED
# if the export activity hits RESTRICTED, it switches to finding profitable import goods until that clears.

# script is happy to work to 0 profit, but will not work at a loss.


import time
import sys


sys.path.append(".")
from behaviours.generic_behaviour import Behaviour
import logging
from straders_sdk.ship import Ship
from straders_sdk.models import Market, Waypoint
from straders_sdk.utils import waypoint_slicer, set_logging, try_execute_select
from straders_sdk.constants import SUPPLY_LEVELS
from behaviours.generic_behaviour import Behaviour
import random

BEHAVIOUR_NAME = "TRADE_BEST_INTRASOLAR"
SAFETY_PADDING = 180


class TradeBestInSystem(Behaviour):
def __init__(
self,
agent_name,
ship_name,
behaviour_params: dict = ...,
config_file_name="user.json",
session=None,
) -> None:
super().__init__(
agent_name,
ship_name,
behaviour_params,
config_file_name,
session,
)
self.agent = self.st.view_my_self()
self.logger = logging.getLogger(BEHAVIOUR_NAME)

def run(self):
self.ship = self.st.ships_view_one(self.ship_name)
self.sleep_until_ready()
self.st.logging_client.log_beginning(
BEHAVIOUR_NAME,
self.ship.name,
self.agent.credits,
behaviour_params=self.behaviour_params,
)
self._run()
self.end()

def _run(self):
st = self.st
ship = self.ship # = st.ships_view_one(self.ship_name, True)
ship: Ship
agent = self.agent
self.sleep_until_arrived()
best_trade = self.get_best_trade()
if not best_trade:
self.logger.info("No trade found")
self.st.sleep(SAFETY_PADDING)
return

(
trade_symbol,
system_symbol,
export_market,
market_depth,
sell_price,
import_market,
) = best_trade

export_market = st.waypoints_view_one(export_market)
import_market = st.waypoints_view_one(import_market)
if trade_symbol not in [c.symbol for c in ship.cargo_inventory]:
have_cargo = self.go_and_buy(
trade_symbol, export_market, burn_allowed=True, max_to_buy=market_depth
)
else:
have_cargo = True

if have_cargo:
self.go_and_sell_or_fulfill(trade_symbol, import_market, burn_allowed=True)
else:
self.logger.info("No cargo to sell")
self.st.sleep(SAFETY_PADDING)
# your code goes here

def get_best_trade(self):
sql = """SELECT trade_symbol, system_symbol, export_market, market_depth, sell_price, import_market
FROM public.trade_routes_intrasystem
where system_symbol = %s;"""
results = try_execute_select(
sql, (self.ship.nav.system_symbol,), self.st.connection
)
if not results:
return None
best_trade = results[0]
return (
best_trade[0],
best_trade[1],
best_trade[2],
best_trade[3],
best_trade[4],
best_trade[5],
)


#
# to execute from commandline, run the script with the agent and ship_symbol as arguments, or edit the values below
#
if __name__ == "__main__":
from dispatcherWK16 import lock_ship

set_logging(level=logging.DEBUG)
agent = sys.argv[1] if len(sys.argv) > 2 else "CTRI-U-"
ship_number = sys.argv[2] if len(sys.argv) > 2 else "1"
ship = f"{agent}-{ship_number}"
behaviour_params = {
"priority": 3,
}

bhvr = TradeBestInSystem(agent, ship, behaviour_params or {})

lock_ship(ship, "MANUAL", 60 * 24)

bhvr.run()
lock_ship(ship, "MANUAL", 0)
25 changes: 25 additions & 0 deletions blog/version 2.1.4 (week 27&28).md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# week 28

Database instability continues to be our woe - and we're now back to "idle in transaction" issues causing the database to be locked.

The first transaction to lock itself was one on node U - ship CTRI--4
`select total_seconds, expiration from ship_cooldown where ship_symbol = 'CTRI-U--4'`

Intestingly, the thread appears to have moved beyond the database (perhaps because it got a bad response from a timeout) and is now stuck waiting for the request consumer, which has jammed. Attempts to pause it and inspect are failing, which is fascinating.

## ramp up improvements - "Trade best"

Chain trading is pretty good for efficiency, but during the ramp up we really want one ship trading the best possible trade - the commander.

I've created a simple "trade best" behaviour that will look at the best trade available and execute it. It can be optimised by factoring in the distance to the starting location. The commander is set to use this behaviour when it's trading.

:

## Command and control

We're at the point where we want to be able to make instructions via the UI.

* Must haves
* Log task for ship
* Set behaviour for ship
* direct move, buy, sell instructions.
13 changes: 11 additions & 2 deletions conductorWK25.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
log_task,
wait_until_reset,
missing_market_prices,
get_ship_price_in_system,
)


Expand Down Expand Up @@ -281,7 +282,15 @@ def system_quarterly_update(self, system: "ConductorSystem"):
# if the system's "buy_next_ship" attribute is set, log a task to buy it.

if system._next_ship_to_buy:
price = get_ship_price_in_system(
system._next_ship_to_buy, system.system_symbol, self.st.connection
)
if price and price > self.st.view_my_self().credits:
# we can't afford it, so we'll need to wait until we can.
return
best_ship = None
# check we can afford it

if len(system.explorers) > 0:
best_ship = system.explorers[0]
elif len(system.commanders) > 0:
Expand Down Expand Up @@ -560,8 +569,8 @@ def set_commander_tasks(self, system: "ConductorSystem") -> int:
commander = self.st.ships_view_one(f"{self.current_agent_symbol}-1")
set_behaviour(
commander.name,
BHVR_CHAIN_TRADE,
{"priority": 3, "target_sys": system.system_symbol},
bhvr.BHVR_TRADE_BEST_INTRASOLAR,
{"priority": 2, "target_sys": system.system_symbol},
)

def populate_ships(self, ships: list[Ship], system: "ConductorSystem"):
Expand Down
11 changes: 11 additions & 0 deletions conductor_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,17 @@ def log_task(
return hash_str if resp else resp


def get_ship_price_in_system(ship_type: str, system_symbol: str, connection):
sql = """select avg(ship_cost) from shipyard_Types
where ship_Type = %s
and shipyard_symbol ilike %s"""
results = try_execute_select(sql, (ship_type, f"{system_symbol}%"), connection)
if not results:
return None

return results[0][0]


def maybe_buy_ship_sys2(
client: SpaceTraders,
system: "ConductorSystem",
Expand Down
2 changes: 1 addition & 1 deletion spacetraders_sdk

0 comments on commit d6fadc5

Please sign in to comment.