Class: SchwabMCP::Tools::PlaceOrderTool

Inherits:
MCP::Tool
  • Object
show all
Extended by:
Loggable
Defined in:
lib/schwab_mcp/tools/place_order_tool.rb

Class Method Summary collapse

Methods included from Loggable

log_debug, log_error, log_fatal, log_info, log_warn, logger

Class Method Details

.call(server_context:, **params) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/schwab_mcp/tools/place_order_tool.rb', line 85

def self.call(server_context:, **params)
  log_info("Placing #{params[:strategy_type]} order for account name: #{params[:account_name]}")

  unless params[:account_name].end_with?("_ACCOUNT")
    log_error("Invalid account name format: #{params[:account_name]}")
    return MCP::Tool::Response.new([{
                                     type: "text",
                                     text: "**Error**: Account name must end with '_ACCOUNT'. Example: 'TRADING_BROKERAGE_ACCOUNT'"
                                   }])
  end

  begin
    validate_strategy_params(params)
    client = SchwabClientFactory.create_client
    return SchwabClientFactory.client_error_response unless client

     = (client, params[:account_name])
    return  if .is_a?(MCP::Tool::Response)

    order_builder = SchwabRb::Orders::OrderFactory.build(
      strategy_type: params[:strategy_type],
      price: params[:price],
      quantity: params[:quantity] || 1,
      order_instruction: (params[:order_instruction] || "open").to_sym,
      credit_debit: (params[:credit_debit] || "credit").to_sym,
      # Iron Condor params
      put_short_symbol: params[:put_short_symbol],
      put_long_symbol: params[:put_long_symbol],
      call_short_symbol: params[:call_short_symbol],
      call_long_symbol: params[:call_long_symbol],
      # Vertical spread params
      short_leg_symbol: params[:short_leg_symbol],
      long_leg_symbol: params[:long_leg_symbol],
      # Single
      symbol: params[:symbol]
    )

    log_debug("Making place order API request")
    response = client.place_order(account_name: params[:account_name], order: order_builder)

    if response && (200..299).include?(response.status)
      log_info("Successfully placed #{params[:strategy_type]} order (HTTP #{response.status})")
      formatted_response = format_place_order_response(response, params)
      MCP::Tool::Response.new([{
                                type: "text",
                                text: formatted_response
                              }])
    elsif response
      log_error("Order placement failed with HTTP status #{response.status}")
      error_details = extract_error_details(response)
      MCP::Tool::Response.new([{
                                type: "text",
                                text: "**Error**: Order placement failed (HTTP #{response.status})\n\n#{error_details}"
                              }])
    else
      log_warn("Empty response from Schwab API for order placement")
      MCP::Tool::Response.new([{
                                type: "text",
                                text: "**No Data**: Empty response from Schwab API for order placement"
                              }])
    end
  rescue StandardError => e
    log_error("Error placing #{params[:strategy_type]} order: #{e.message}")
    log_debug("Backtrace: #{e.backtrace.first(5).join('\n')}")
    MCP::Tool::Response.new([{
                              type: "text",
                              text: "**Error** placing #{params[:strategy_type]} order: #{e.message}\n\n#{e.backtrace.first(3).join('\n')}"
                            }])
  end
end

.extract_error_details(response) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/schwab_mcp/tools/place_order_tool.rb', line 257

def self.extract_error_details(response)
  if response.body && !response.body.empty?
    begin
      parsed = JSON.parse(response.body)
      redacted_data = Redactor.redact(parsed)
      "**Error Details:**\n\n```json\n#{JSON.pretty_generate(redacted_data)}\n```"
    rescue JSON::ParserError
      "**Error Details:**\n\n```\n#{response.body}\n```"
    end
  else
    "No additional error details provided."
  end
rescue StandardError => e
  log_debug("Error extracting error details: #{e.message}")
  "Could not extract error details."
end

.extract_order_id_from_response(response) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/schwab_mcp/tools/place_order_tool.rb', line 244

def self.extract_order_id_from_response(response)
  # Schwab API typically returns the order ID in the Location header
  # Format: https://api.schwabapi.com/trader/v1/accounts/{accountHash}/orders/{orderId}
  location = response.headers["Location"] || response.headers["location"]
  return nil unless location

  match = location.match(%r{/orders/(\d+)$})
  match ? match[1] : nil
rescue StandardError => e
  log_debug("Could not extract order ID from response: #{e.message}")
  nil
end

.format_place_order_response(response, params) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/schwab_mcp/tools/place_order_tool.rb', line 196

def self.format_place_order_response(response, params)
  strategy = params[:strategy_type].to_s.upcase
  strategy_summary = case strategy
  when 'IRON_CONDOR'
    "**Iron Condor Order Placed**\n" \
    "- Put Short: #{params[:put_short_symbol]}\n" \
    "- Put Long: #{params[:put_long_symbol]}\n" \
    "- Call Short: #{params[:call_short_symbol]}\n" \
    "- Call Long: #{params[:call_long_symbol]}\n"
  when 'VERTICAL'
    "**Vertical Spread Order Placed**\n" \
    "- Short Leg: #{params[:short_leg_symbol]}\n" \
    "- Long Leg: #{params[:long_leg_symbol]}\n"
  when 'SINGLE'
    "**Single Option Order Placed**\n" \
    "- Symbol: #{params[:symbol]}\n"
  end

  friendly_name = params[:account_name].gsub("_ACCOUNT", "").split("_").map(&:capitalize).join(" ")

  order_details = "**Order Details:**\n" \
                 "- Strategy: #{params[:strategy_type]}\n" \
                 "- Action: #{params[:order_instruction] || "open"}\n" \
                 "- Quantity: #{params[:quantity] || 1}\n" \
                 "- Price: $#{params[:price]}\n" \
                 "- Account: #{friendly_name} (#{params[:account_name]})\n\n"

  order_id = extract_order_id_from_response(response)
  order_id_info = order_id ? "**Order ID**: #{order_id}\n\n" : ""

  response_info = if response.body && !response.body.empty?
                    begin
                      parsed = JSON.parse(response.body)
                      redacted_data = Redactor.redact(parsed)
                      "**Schwab API Response:**\n\n```json\n#{JSON.pretty_generate(redacted_data)}\n```"
                    rescue JSON::ParserError
                      "**Schwab API Response:**\n\n```\n#{response.body}\n```"
                    end
                  else
                    "**Status**: Order submitted successfully (HTTP #{response.status})"
                  end

  "#{strategy_summary}\n#{order_details}#{order_id_info}#{response_info}"
rescue StandardError => e
  log_error("Error formatting response: #{e.message}")
  "**Order Status**: #{response.status}\n\n**Raw Response**: #{response.body}"
end

.resolve_account_details(client, account_name) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/schwab_mcp/tools/place_order_tool.rb', line 156

def self.(client, )
  available_accounts = client.
  unless available_accounts.include?()
    log_error("Account name '#{}' not found in configured accounts")
    return MCP::Tool::Response.new([{
                                     type: "text",
                                     text: "**Error**: Account name '#{}' not found in configured accounts.\n\nAvailable accounts: #{available_accounts.join(", ")}\n\nTo configure: Add the account to your schwab_rb configuration file."
                                   }])
  end

  log_debug("Using account name: #{}")
  
end

.validate_strategy_params(params) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/schwab_mcp/tools/place_order_tool.rb', line 170

def self.validate_strategy_params(params)
  strategy = params[:strategy_type].to_s.upcase
  case strategy
  when 'IRON_CONDOR'
    required_fields = %i[put_short_symbol put_long_symbol call_short_symbol call_long_symbol]
    missing_fields = required_fields.select { |field| params[field].nil? || params[field].empty? }
    unless missing_fields.empty?
      raise ArgumentError, "Iron condor strategy requires: #{missing_fields.join(", ")}"
    end
  when 'VERTICAL'
    required_fields = %i[short_leg_symbol long_leg_symbol]
    missing_fields = required_fields.select { |field| params[field].nil? || params[field].empty? }
    unless missing_fields.empty?
      raise ArgumentError, "#{params[:strategy_type]} strategy requires: #{missing_fields.join(", ")}"
    end
  when 'SINGLE'
    required_fields = %i[symbol]
    missing_fields = required_fields.select { |field| params[field].nil? || params[field].empty? }
    unless missing_fields.empty?
      raise ArgumentError, "#{params[:strategy_type]} strategy requires: #{missing_fields.join(", ")}"
    end
  else
    raise ArgumentError, "Unsupported strategy type: #{params[:strategy_type]}"
  end
end